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 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
import { Component, Suspense, useRef, useEffect, useState, type ReactNode } from 'react'
import { Tooltip } from '@radix-ui/themes'
import { ArrowsClockwiseIcon, CaretDownIcon, CaretUpIcon } from '@phosphor-icons/react'
import { Canvas, useThree } from '@react-three/fiber'
import * as THREE from 'three'
import { Html } from '@react-three/drei'
import { Physics } from '@react-three/rapier'
import { SplatRenderer } from '../modules/splat/SplatRenderer'
import { EnvironmentMap } from '../modules/environment/EnvironmentMap'
import { WorldCollider } from '../modules/collider/WorldCollider'
import { GroundPlane } from '../modules/collider/GroundPlane'
import { CharacterController, type CharacterControllerHandle } from '../modules/character/CharacterController'
import { FlyController, type FlyControllerHandle } from '../modules/character/FlyController'
import { ButterflyScene } from '../modules/butterfly/ButterflyScene'
import { ObjectGrid } from '../modules/scene/ObjectGrid'
import { OriginHelper } from '../modules/scene/OriginHelper'
import { AudioManager } from '../modules/audio/AudioManager'
import { PostProcessing } from '../modules/postprocessing/PostProcessing'
import { DEFAULT_SHADOW_CATCHER_COLOR, DEFAULT_SHADOW_CATCHER_OPACITY, shadowCatcherColor, shadowCatcherOpacity } from '../modules/scene/shadows'
import { getSplatUrl } from '../utils/worldLoader'
import { useDebugStore } from '../store/debug'
import { WorldRenderMode, ObjectRenderMode, ViewerQuality, type Vec3Tuple, type World, type WorldHoverPreview, type WorldObjectAsset, type WorldSceneProject } from '../types/world'
import { AppButton } from './AppButton'
import { chrome } from './AppChrome'

function ModelLoader() {
  return (
    <Html center>
      <div className="flex flex-col items-center justify-center space-y-4">
        <div className="w-8 h-8 border-4 border-white border-t-transparent rounded-full animate-spin"></div>
        <div className="text-white text-base font-semibold tracking-wide drop-shadow-md">Downloading Model...</div>
        <div className="text-white/70 text-xs mt-2 max-w-xs text-center space-y-1">
          <p>This may take a moment depending on model size and network speed.</p>
        </div>
      </div>
    </Html>
  )
}

type CharHandle = CharacterControllerHandle | FlyControllerHandle
const DEFAULT_ENVIRONMENT_URL = '/hdri.jpg'
const DEFAULT_WORLD_SEMANTICS = {
  metric_scale_factor: 1,
  ground_plane_offset: 0,
  flip_y: true,
}

function sunPositionFromRotation(rotation: Vec3Tuple): Vec3Tuple {
  let x = 0
  let y = 10
  let z = 0
  const [rx, ry, rz] = rotation
  const cx = Math.cos(rx)
  const sx = Math.sin(rx)
  const cy = Math.cos(ry)
  const sy = Math.sin(ry)
  const cz = Math.cos(rz)
  const sz = Math.sin(rz)

  ;[y, z] = [y * cx - z * sx, y * sx + z * cx]
  ;[x, z] = [x * cy + z * sy, -x * sy + z * cy]
  ;[x, y] = [x * cz - y * sz, x * sz + y * cz]

  return [x, y, z]
}

interface OptionalAssetBoundaryProps {
  label: string
  resetKey: string
  fallback?: ReactNode
  children: ReactNode
}

interface OptionalAssetBoundaryState {
  hasError: boolean
}

class OptionalAssetBoundary extends Component<OptionalAssetBoundaryProps, OptionalAssetBoundaryState> {
  state: OptionalAssetBoundaryState = { hasError: false }

  static getDerivedStateFromError(): OptionalAssetBoundaryState {
    return { hasError: true }
  }

  componentDidCatch(error: unknown) {
    console.warn(`Skipping optional world asset "${this.props.label}" because it failed to load.`, error)
  }

  componentDidUpdate(prevProps: OptionalAssetBoundaryProps) {
    if (prevProps.resetKey !== this.props.resetKey && this.state.hasError) {
      this.setState({ hasError: false })
    }
  }

  render() {
    if (this.state.hasError) return this.props.fallback ?? null
    return this.props.children
  }
}

function GrayEnvironmentFallback() {
  return (
    <>
      <color attach="background" args={['#6b7280']} />
      <ambientLight color="#ffffff" intensity={0.9} />
    </>
  )
}

function DefaultEnvironment({ intensity }: { intensity: number }) {
  return (
    <OptionalAssetBoundary label={DEFAULT_ENVIRONMENT_URL} resetKey={DEFAULT_ENVIRONMENT_URL} fallback={<GrayEnvironmentFallback />}>
      <Suspense fallback={null}>
        <EnvironmentMap panoUrl={DEFAULT_ENVIRONMENT_URL} intensity={intensity} />
      </Suspense>
    </OptionalAssetBoundary>
  )
}

interface Props {
  world?: World
  slug: string
  sourceImageUrl?: string
  hoveredWorldPreview?: WorldHoverPreview | null
  objectAssets: WorldObjectAsset[]
  allObjectAssets: WorldObjectAsset[]
  worldSfxUrls: string[]
  sceneProject?: WorldSceneProject
  sceneProjectReady?: boolean
  hoveredObjectAssetId?: string | null
  hoveredObjectInstanceId?: string | null
  editing?: boolean
  setEditing?: (editing: boolean) => void
  uiVisible?: boolean
  onObjectHover?: (asset: WorldObjectAsset, hovering: boolean, instanceId?: string) => void
  onSceneProjectSaved?: (project: WorldSceneProject) => void
  onRefreshWorlds?: () => void
  refreshingWorlds?: boolean
}

export function WorldViewer({
  world: desiredWorld,
  slug: desiredSlug,
  sourceImageUrl,
  hoveredWorldPreview,
  objectAssets: desiredObjectAssets,
  allObjectAssets,
  worldSfxUrls,
  sceneProject,
  sceneProjectReady = true,
  hoveredObjectAssetId,
  hoveredObjectInstanceId,
  editing = false,
  setEditing,
  uiVisible = true,
  onObjectHover,
  onSceneProjectSaved,
  onRefreshWorlds,
  refreshingWorlds = false,
}: Props) {
  const charRef = useRef<CharHandle>(null)
  const worldRenderMode = useDebugStore((s) => s.worldRenderMode)
  const objectRenderMode = useDebugStore((s) => s.objectRenderMode)
  const viewerQuality = useDebugStore((s) => s.viewerQuality)
  const controllerMode = useDebugStore((s) => s.controllerMode)
  const butterfliesEnabled = useDebugStore((s) => s.butterfliesEnabled)
  const controllerResetToken = useDebugStore((s) => s.controllerResetToken)
  const environmentIntensity = useDebugStore((s) => s.environmentIntensity)
  const sunIntensity = useDebugStore((s) => s.sunIntensity)
  const sunColor = useDebugStore((s) => s.sunColor)
  const [sourceThumbnailCollapsed, setSourceThumbnailCollapsed] = useState(false)
  const colliderUrl = desiredWorld?.assets.mesh?.collider_mesh_url?.startsWith('/models/')
    ? desiredWorld.assets.mesh.collider_mesh_url
    : ''
  const panoUrl = desiredWorld?.assets.imagery?.pano_url?.startsWith('/models/')
    ? desiredWorld.assets.imagery.pano_url
    : ''

  useEffect(() => {
    charRef.current?.reset()
  }, [desiredSlug])

  useEffect(() => {
    if (controllerResetToken > 0) charRef.current?.reset()
  }, [controllerResetToken])

  const splatUrl = desiredWorld ? getSplatUrl(desiredWorld) : ''
  const { ground_plane_offset, flip_y, metric_scale_factor } = desiredWorld?.assets.splats.semantics_metadata ?? DEFAULT_WORLD_SEMANTICS
  const flipY = flip_y ?? true
  const baseMetricScaleFactor = metric_scale_factor ?? 1
  const baseGroundPlaneOffset = ground_plane_offset ?? 0
  const isHighQuality = viewerQuality === ViewerQuality.High
  const showScene = worldRenderMode !== WorldRenderMode.ObjectOnly
  const showSplat = showScene && objectRenderMode === ObjectRenderMode.Lit
  const showObjects = worldRenderMode !== WorldRenderMode.SplatOnly
  const activeSceneSun = sceneProject?.sun
  const activeSunIntensity = activeSceneSun?.intensity ?? sunIntensity
  const activeEnvironmentIntensity = activeSceneSun?.environmentIntensity ?? environmentIntensity
  const activeSunPosition = sunPositionFromRotation(activeSceneSun?.rotation ?? [0, 0, 0])
  const activeMetricScaleFactor = sceneProject?.metricScaleFactor ?? baseMetricScaleFactor
  const defaultGroundPlaneOffset = baseGroundPlaneOffset * (activeMetricScaleFactor / baseMetricScaleFactor)
  const activeGroundPlaneOffset = sceneProject?.groundPlaneOffset ?? defaultGroundPlaneOffset
  const sceneGroundPlaneColliderEnabled = sceneProject?.groundPlaneColliderEnabled ?? true
  const activeGroundPlaneColliderEnabled = worldRenderMode === WorldRenderMode.ObjectOnly
    ? true
    : sceneGroundPlaneColliderEnabled
  const sceneShadowCatcherOpacity = sceneProject?.shadowCatcherOpacity
  const activeShadowCatcherOpacity = shadowCatcherOpacity(sceneShadowCatcherOpacity ?? DEFAULT_SHADOW_CATCHER_OPACITY)
  const sceneShadowCatcherColor = sceneProject?.shadowCatcherColor
  const activeShadowCatcherColor = shadowCatcherColor(sceneShadowCatcherColor ?? DEFAULT_SHADOW_CATCHER_COLOR)
  const objectPlacements = sceneProject?.instances ?? []
  const objectPhysicsAssets = sceneProject?.instances.length ? allObjectAssets : desiredObjectAssets
  const activeControllerMode = controllerMode
  const hoveredObjectAsset = hoveredObjectAssetId
    ? allObjectAssets.find((asset) => asset.assetId === hoveredObjectAssetId)
      ?? desiredObjectAssets.find((asset) => asset.assetId === hoveredObjectAssetId)
    : undefined
  const activePreviewImageUrl = hoveredObjectAsset?.referenceImageUrl
    ?? hoveredObjectAsset?.thumbnailUrl
    ?? hoveredWorldPreview?.imageUrl
    ?? sourceImageUrl
  const activePreviewAlt = hoveredObjectAsset
    ? `${hoveredObjectAsset.name} reference image`
    : hoveredWorldPreview?.imageUrl
      ? hoveredWorldPreview.alt
      : 'Original source'
  return (
    <>
      <Canvas
        camera={{ fov: 75, near: 0.1, far: 1000 }}
        className="w-full h-full"
        gl={{ antialias: false }}
        shadows={isHighQuality}
      >
        <CameraLogger />
        <Suspense fallback={<ModelLoader />}>
          <AudioManager urls={worldSfxUrls} />
          <Physics key={`${desiredSlug}:${controllerResetToken}`} gravity={[0, -9.81, 0]}>
            {activeControllerMode === 'fly' ? (
              <FlyController ref={charRef as React.RefObject<FlyControllerHandle>} preserveCameraOnMount={editing} />
            ) : (
              <CharacterController ref={charRef as React.RefObject<CharacterControllerHandle>} />
            )}
            {showScene && colliderUrl && (
              <OptionalAssetBoundary label={colliderUrl} resetKey={colliderUrl}>
                <Suspense fallback={null}>
                  <WorldCollider
                    url={colliderUrl}
                    flipY={flipY}
                    groundPlaneOffset={activeGroundPlaneOffset}
                    metricScaleFactor={activeMetricScaleFactor}
                    shadowOpacity={activeShadowCatcherOpacity}
                    shadowColor={activeShadowCatcherColor}
                  />
                </Suspense>
              </OptionalAssetBoundary>
            )}
            {showObjects && !editing && (
              <Suspense fallback={null}>
                <ObjectGrid
                  objects={objectPhysicsAssets}
                  placements={objectPlacements}
                />
              </Suspense>
            )}
            <GroundPlane
              groundColliderEnabled={activeGroundPlaneColliderEnabled}
            />
          </Physics>
          {splatUrl && (
            <OptionalAssetBoundary label={splatUrl} resetKey={splatUrl}>
              <SplatRenderer
                url={splatUrl}
                visible={showSplat}
                groundPlaneOffset={activeGroundPlaneOffset}
                flipY={flipY}
                metricScaleFactor={activeMetricScaleFactor}
              />
            </OptionalAssetBoundary>
          )}
          <directionalLight
            castShadow={isHighQuality && activeSunIntensity > 0}
            color={sunColor}
            intensity={activeSunIntensity}
            position={activeSunPosition}
            shadow-mapSize={[2048, 2048]}
            shadow-bias={-0.0001}
            shadow-normalBias={0.02}
            shadow-camera-near={0.5}
            shadow-camera-far={30}
            shadow-camera-left={-20}
            shadow-camera-right={20}
            shadow-camera-top={20}
            shadow-camera-bottom={-20}
          />
          {panoUrl && (
            <OptionalAssetBoundary label={panoUrl} resetKey={panoUrl} fallback={<DefaultEnvironment intensity={activeEnvironmentIntensity} />}>
              <Suspense fallback={null}>
                <EnvironmentMap panoUrl={panoUrl} intensity={activeEnvironmentIntensity} />
              </Suspense>
            </OptionalAssetBoundary>
          )}
          {!panoUrl && <DefaultEnvironment intensity={activeEnvironmentIntensity} />}
          {butterfliesEnabled && <ButterflyScene />}
          <OriginHelper />
          {isHighQuality && <PostProcessing />}
        </Suspense>
      </Canvas>
      {uiVisible && (
        <SourceImageControls
          activeSourceImageUrl={activePreviewImageUrl}
          previewAlt={activePreviewAlt}
          thumbnailCollapsed={sourceThumbnailCollapsed}
          refreshingWorlds={refreshingWorlds}
          onRefreshWorlds={onRefreshWorlds}
          onThumbnailCollapseToggle={() => setSourceThumbnailCollapsed((collapsed) => !collapsed)}
        />
      )}
    </>
  )
}

function CameraLogger() {
  const { camera } = useThree()
  
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key.toLowerCase() === 'p') {
        const { x, y, z } = camera.position
        const euler = new THREE.Euler(0, 0, 0, 'YXZ').setFromQuaternion(camera.quaternion, 'YXZ')
        const yaw = euler.y
        const pitch = euler.x
        
        const params = new URLSearchParams(window.location.search)
        params.set('spawn', `${x.toFixed(2)},${y.toFixed(2)},${z.toFixed(2)},${yaw.toFixed(2)},${pitch.toFixed(2)}`)
        const newUrl = `${window.location.origin}${window.location.pathname}?${params.toString()}`
        
        console.log(`\n============== [Camera Spawn Logger] ==============`)
        console.log(`Position: ${x.toFixed(2)}, ${y.toFixed(2)}, ${z.toFixed(2)}`)
        console.log(`Rotation: Yaw ${yaw.toFixed(2)}, Pitch ${pitch.toFixed(2)}`)
        console.log(`Spawn URL: ${newUrl}`)
        console.log(`===================================================\n`)
        
        if (navigator.clipboard) {
          navigator.clipboard.writeText(newUrl).then(() => {
            console.log('✅ Spawn URL copied to clipboard!')
          }).catch(() => {
            console.log('❌ Failed to copy to clipboard')
          })
        }
      }
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [camera])
  return null
}

function SourceImageControls({
  activeSourceImageUrl,
  previewAlt,
  thumbnailCollapsed,
  refreshingWorlds,
  onRefreshWorlds,
  onThumbnailCollapseToggle,
}: {
  activeSourceImageUrl?: string
  previewAlt: string
  thumbnailCollapsed: boolean
  refreshingWorlds: boolean
  onRefreshWorlds?: () => void
  onThumbnailCollapseToggle: () => void
}) {
  if (!activeSourceImageUrl && !import.meta.env.DEV) return null

  return (
    <div className={`pointer-events-none fixed bottom-2 right-2 z-30 hidden md:block ${chrome.enter}`}>
      {activeSourceImageUrl ? (
        thumbnailCollapsed ? (
          <div className="flex items-center gap-1">
            {import.meta.env.DEV && onRefreshWorlds && (
              <RefreshWorldsButton
                refreshing={refreshingWorlds}
                onRefresh={onRefreshWorlds}
                className="pointer-events-auto"
              />
            )}
            <SourceThumbnailCollapseButton
              collapsed={thumbnailCollapsed}
              onToggle={onThumbnailCollapseToggle}
              className="pointer-events-auto"
            />
          </div>
        ) : (
          <div className="relative overflow-hidden rounded-lg border border-white/15 bg-black/70 shadow-lg ring-1 ring-black/30 backdrop-blur-md">
            <img
              src={activeSourceImageUrl}
              alt={previewAlt}
              className="block h-96 aspect-square object-cover"
              draggable={false}
            />
            <div className="absolute bottom-0.5 right-0.5 flex items-center gap-1">
              {import.meta.env.DEV && onRefreshWorlds && (
                <RefreshWorldsButton
                  refreshing={refreshingWorlds}
                  onRefresh={onRefreshWorlds}
                  className="pointer-events-auto"
                />
              )}
              <SourceThumbnailCollapseButton
                collapsed={thumbnailCollapsed}
                onToggle={onThumbnailCollapseToggle}
                className="pointer-events-auto"
              />
            </div>
          </div>
        )
      ) : (
        import.meta.env.DEV && onRefreshWorlds && (
          <RefreshWorldsButton
            refreshing={refreshingWorlds}
            onRefresh={onRefreshWorlds}
            className="pointer-events-auto"
          />
        )
      )}
    </div>
  )
}

function SourceThumbnailCollapseButton({
  collapsed,
  onToggle,
  className = '',
}: {
  collapsed: boolean
  onToggle: () => void
  className?: string
}) {
  const Icon = collapsed ? CaretUpIcon : CaretDownIcon

  return (
    <Tooltip
      content={collapsed ? 'show original source image' : 'collapse original source image'}
      delayDuration={0}
      side="top"
    >
      <AppButton
        onClick={onToggle}
        className={`h-6 w-6 justify-center rounded border border-white/15 bg-black/70 p-0 text-white opacity-70 shadow-lg backdrop-blur-md ${className}`}
        aria-label={collapsed ? 'Show original source image' : 'Collapse original source image'}
        aria-pressed={collapsed}
      >
        <Icon size={15} weight="bold" />
      </AppButton>
    </Tooltip>
  )
}

function RefreshWorldsButton({
  refreshing,
  onRefresh,
  className = '',
}: {
  refreshing: boolean
  onRefresh: () => void
  className?: string
}) {
  return (
    <Tooltip
      content={refreshing ? 'refreshing local assets' : 'refresh local assets'}
      delayDuration={0}
      side="top"
    >
      <AppButton
        onClick={onRefresh}
        active={refreshing}
        className={`h-6 w-6 justify-center rounded border border-white/15 bg-black/70 p-0 text-white shadow-lg backdrop-blur-md ${className}`}
        aria-label="Refresh local assets"
      >
        <ArrowsClockwiseIcon size={12} weight={refreshing ? 'bold' : 'regular'} />
      </AppButton>
    </Tooltip>
  )
}