File size: 8,962 Bytes
9802882
fd2aa6b
f4af987
fd2aa6b
 
 
bf8d4d8
fd2aa6b
 
40fde09
ab75c71
40fde09
 
fd2aa6b
e62f50c
 
fd2aa6b
f4af987
b1ecc22
6311de2
b1ecc22
637dd5c
bf8d4d8
 
ab75c71
9802882
 
b1ecc22
637dd5c
bf8d4d8
 
819e443
9802882
fd2aa6b
e62f50c
9802882
 
 
ab75c71
fd2aa6b
1e2c870
9802882
e62f50c
 
 
 
 
 
 
 
 
 
 
ab75c71
 
 
 
 
 
 
 
 
 
 
 
 
 
9802882
6311de2
 
9802882
6311de2
 
 
 
 
 
 
 
 
 
 
 
9802882
f4af987
9802882
f4af987
 
 
9802882
f4af987
9802882
 
 
 
f4af987
 
9802882
 
 
b1ecc22
9802882
 
 
 
 
 
 
 
 
 
 
 
 
f4af987
9802882
 
6311de2
9802882
 
 
 
 
 
 
 
 
 
 
8fb2ec4
9802882
 
 
 
 
 
1e2c870
ab75c71
b1ecc22
e62f50c
 
 
 
fd2aa6b
e62f50c
 
 
 
 
 
 
fd2aa6b
6896326
e62f50c
 
f0dc1c3
 
 
1e2c870
 
 
 
f4af987
9802882
6896326
1e2c870
6896326
1e2c870
6896326
f0dc1c3
 
ab75c71
f4af987
 
e62f50c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40fde09
e62f50c
6896326
e62f50c
6896326
 
e62f50c
 
 
 
6896326
b1ecc22
e62f50c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0dc1c3
9802882
637dd5c
3f09ee7
fd2aa6b
f4af987
fd2aa6b
40fde09
e62f50c
fd2aa6b
 
 
7a3bdc2
40fde09
 
 
e62f50c
 
 
40fde09
fd2aa6b
6311de2
40fde09
6311de2
40fde09
819e443
40fde09
a60cb50
40fde09
6311de2
40fde09
819e443
40fde09
 
6311de2
40fde09
819e443
40fde09
 
 
fd2aa6b
 
 
 
 
 
 
 
 
 
637dd5c
 
e62f50c
fd2aa6b
 
e62f50c
 
 
 
 
fd2aa6b
e62f50c
 
f4af987
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import { useEffect, useRef, useState } from "react"
import { useDrop } from "react-dnd"

import { DropZoneTarget, ImageSegment, RenderedScene, SceneEvent } from "@/types"
import { useImageDimension } from "@/lib/useImageDimension"
import { formatActionnableName } from "@/lib/formatActionnableName"
import { Game } from "@/app/games/types"
import { Engine } from "@/app/engine/engines"

import { CartesianImage } from "./cartesian-image"
import { MouseEventHandler, MouseEventType } from "./types"
import { CartesianVideo } from "./cartesian-video"
import { SphericalImage } from "./spherical-image"

import { SceneTooltip } from "./scene-tooltip"
import { SceneMenu } from "./scene-menu"
import { cn } from "@/lib/utils"

export const SceneRenderer = ({
  rendered,
  onEvent,
  isLoading,
  game,
  engine,
  debug,
}: {
  rendered: RenderedScene
  onEvent: (event: SceneEvent, actionnable?: string) => void
  isLoading: boolean
  game: Game
  engine: Engine
  debug: boolean
}) => {

  const containerRef = useRef<HTMLDivElement>(null)
  const canvasRef = useRef<HTMLCanvasElement | null>(null)
  const contextRef = useRef<CanvasRenderingContext2D | null>(null)
  const [actionnable, setActionnable] = useState<string>("")
  const actionnableRef = useRef<string>("")

  const maskDimension = useImageDimension(rendered.maskUrl)

  const [isHover, setHover] = useState(false)

  const tooltipTimeoutRef = useRef<ReturnType<typeof setTimeout>>()
  const menuTimeoutRef = useRef<ReturnType<typeof setTimeout>>()
  const [isTooltipVisible, setTooltipVisible] = useState(false)
  const [isMenuVisible, setMenuVisible] = useState(false)
  const [tooltipX, setTooltipX] = useState(0)
  const [tooltipY, setTooltipY] = useState(0)
  const [menuX, setMenuX] = useState(0)
  const [menuY, setMenuY] = useState(0)

  const [{ isOver, canDrop }, drop] = useDrop({
    accept: "item",
    drop: (): DropZoneTarget => ({
      type: "Actionnable",
      name: actionnable,
      title: formatActionnableName(actionnable),
      description: ""
    }),
    collect: (monitor) => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop(),
    }),
  })

  useEffect(() => {
    if (!rendered.maskUrl) {
      return
    }
    const img = new Image()
    img.onload = function () {
      canvasRef.current = document.createElement('canvas')
      canvasRef.current.width = img.width
      canvasRef.current.height = img.height
      contextRef.current = canvasRef.current.getContext('2d', {
        willReadFrequently: true
      })
      contextRef.current!.drawImage(img, 0, 0, img.width, img.height)
    }
    img.src = rendered.maskUrl
  }, [rendered.maskUrl])

  const getPixelColor = (x: number, y: number) => {
    if (!contextRef.current) {
      throw new Error("Unable to get context from canvas")
    }

    const imgData = contextRef.current.getImageData(x, y, 1, 1).data


    const clickedColor = Array.from(imgData.slice(0, 3), value => value / 255);

    return clickedColor
  }


  const getSegmentAt = (x: number, y: number): ImageSegment => {
    if (!contextRef.current) throw new Error("Unable to get context from canvas");
    
    let closestSegment: ImageSegment = {
      id: 0,
      box: [],
      color: [],
      label: "",
      score: 0,
    }

    const clickedColor = getPixelColor(x,y) as any

    if (`${clickedColor}` === "1,1,1") {
      return closestSegment
    }
  
    let minDistance = Infinity;
        
    rendered.segments.forEach(segment => {
      const segmentColor = segment.color.slice(0,3); // get the RGB part only

      const distance = Math.sqrt(
        Math.pow(clickedColor[0] - segmentColor[0], 2) +
        Math.pow(clickedColor[1] - segmentColor[1], 2) +
        Math.pow(clickedColor[2] - segmentColor[2], 2)
      );
      
      if(distance < minDistance) {
        minDistance = distance;
        closestSegment = segment;
        // console.log(`${distance} -> ${segment.label}: score = ${segment.score}`)
      }
    });

    return closestSegment;
  }

  // note: coordinates must be between 0 and 1
  const handleMouseEvent: MouseEventHandler = async (type: MouseEventType, relativeX: number, relativeY: number) => {
    
    const noMenu = !containerRef.current
    const noContext = !contextRef.current
    const noSegmentationMask = !rendered.maskUrl
    const noSegmentsToClickOn = rendered.segments.length == 0
    const outOfBounds = relativeX < 0 || relativeX > 1 || relativeY < 0 || relativeY > 1

    const mustAbort =
     noMenu
     || noContext
     || noSegmentationMask
     || noSegmentsToClickOn
     || isLoading
     || outOfBounds

    if (mustAbort) {
      // if (type === "click") { onEvent("ClickOnNothing") }
      return
    }

    const imageX = relativeX * maskDimension.width
    const imageY = relativeY * maskDimension.height
    
    const newSegment = getSegmentAt(imageX, imageY)

    if (actionnable !== newSegment.label) {
      if (newSegment.label) {
        // console.log(`User is hovering "${newSegment.label}"`)
      } else {
        // console.log(`Nothing in the area`)
      }

      // update the actionnable immediately, so we can show the hand / finger cursor pointer
      setActionnable(actionnableRef.current = newSegment.label)
    }

    const container = containerRef.current
    const containerBox = container.getBoundingClientRect()

    const absoluteMouseX = containerBox.left + relativeX * container.clientWidth
    const absoluteMouseY = containerBox.top + relativeY * container.clientHeight
    
    clearTimeout(tooltipTimeoutRef.current)
    clearTimeout(menuTimeoutRef.current)
    setTooltipVisible(false)
    setMenuVisible(false)
    setTooltipX(absoluteMouseX)
    setTooltipY(absoluteMouseY)
    setMenuX(absoluteMouseX)
    setMenuY(absoluteMouseY)

    
    if (type === "click") {
      setMenuVisible(false)
      if (!newSegment.label) {
        // setMenuVisible(false)
        return
      }

      setTooltipVisible(true)
      setMenuVisible(true)

      console.log("User clicked on " + newSegment.label)
      onEvent("ClickOnActionnable", actionnable)
    } else { // hover
      if (actionnable) {
        setHover(true)

        tooltipTimeoutRef.current = setTimeout(() => {
          if (tooltipTimeoutRef.current) {
            clearTimeout(tooltipTimeoutRef.current)
            tooltipTimeoutRef.current = undefined
            setTooltipVisible(true)
          }
        }, 400)

        menuTimeoutRef.current = setTimeout(() => {
          if (menuTimeoutRef.current) {
            clearTimeout(menuTimeoutRef.current)
            menuTimeoutRef.current = undefined
            setMenuVisible(true)
          }
        }, 500)

        onEvent("HoveringActionnable", actionnable)
      } else {
        setHover(false)
        onEvent("HoveringNothing")

        /*
        tooltipTimeoutRef.current = setTimeout(() => {
          if (tooltipTimeoutRef.current) {
            setTooltipVisible(false)
            clearTimeout(tooltipTimeoutRef.current)
            tooltipTimeoutRef.current = undefined
          }
        }, 500)

        menuTimeoutRef.current = setTimeout(() => {
          if (menuTimeoutRef.current) {
            setMenuVisible(false)
            clearTimeout(menuTimeoutRef.current)
            menuTimeoutRef.current = undefined
          }
        }, 500)
        */

      }
    }
  }

  const isFullScreen = true
  return (
    <div className="" ref={drop}>
      <div
        ref={containerRef}
        className={cn(
          "border-0 overflow-hidden",
          `fixed top-0 left-0 right-0 w-screen`,
            
          isLoading
            ? "cursor-wait"
            : actionnable
            ? isHover
            ? "cursor-crosshair"
            : "cursor-crosshair"
            : ""
          )}>
        {engine.type === "cartesian_video"
          ? <CartesianVideo
              rendered={rendered}
              onEvent={handleMouseEvent}
              debug={debug}
            />
          : (engine.type === "spherical_image" || engine.type === "spherical_video")
          ? <SphericalImage
              rendered={rendered}
              onEvent={handleMouseEvent}
              debug={debug}
            />
          : <CartesianImage
              rendered={rendered}
              onEvent={handleMouseEvent}
              debug={debug}
            />
        }

        {/*
        engine.type === "cartesian_image" || engine.type === "cartesian_video"
        ? <SceneTooltip
          isVisible={isTooltipVisible && !isLoading}
          x={tooltipX}
          y={tooltipY}>
          {actionnable}
        </SceneTooltip> : null
        */
        }
      </div>

      {/*
      engine.type === "cartesian_image" || engine.type === "cartesian_video"
       ? 
      <SceneMenu
        actions={["Go here", "Interact"]}
        isVisible={isMenuVisible && !isLoading}
        x={menuX}
        y={menuY}
      /> : null
      */}

    </div>
  )
}