@umituz/web-virtual 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,6 +19,8 @@ export interface VirtualCommandBarProps {
19
19
  onToggleDemoMode?: () => void
20
20
  isLaunching?: boolean
21
21
  defaultOpen?: boolean
22
+ isOpen?: boolean
23
+ onToggleOpen?: (open: boolean) => void
22
24
  placeholder?: string
23
25
  className?: string
24
26
  }
@@ -34,22 +36,30 @@ export function VirtualCommandBar({
34
36
  isDemoMode = true,
35
37
  onToggleDemoMode,
36
38
  isLaunching = false,
37
- defaultOpen = true,
38
- placeholder = "Genel Müdür'e veya bir uzmana görev verin... (Enter ile gönder)",
39
+ defaultOpen = false,
40
+ isOpen: externalIsOpen,
41
+ onToggleOpen,
42
+ placeholder = "Assign a mission to the general manager or a specialist... (Enter to send)",
39
43
  className = '',
40
44
  }: VirtualCommandBarProps): ReactNode {
41
- const [isOpen, setIsOpen] = useState(defaultOpen)
45
+ const [internalIsOpen, setInternalIsOpen] = useState(defaultOpen)
46
+ const isOpen = externalIsOpen !== undefined ? externalIsOpen : internalIsOpen
47
+
48
+ const handleToggle = (open: boolean) => {
49
+ setInternalIsOpen(open)
50
+ if (onToggleOpen) onToggleOpen(open)
51
+ }
42
52
 
43
53
  if (!isOpen) {
44
54
  return (
45
55
  <button
46
56
  type="button"
47
- onClick={() => setIsOpen(true)}
57
+ onClick={() => handleToggle(true)}
48
58
  className="wv-command-collapsed-btn"
49
- aria-label="Komut Barını Aç"
59
+ aria-label="Open mission panel"
50
60
  >
51
61
  <Send size={14} color="#3b82f6" />
52
- <span>Komut ve Görev Barını Aç ▲</span>
62
+ <span>⚡ Mission Panel ▲</span>
53
63
  </button>
54
64
  )
55
65
  }
@@ -74,11 +84,11 @@ export function VirtualCommandBar({
74
84
 
75
85
  <button
76
86
  type="button"
77
- onClick={() => setIsOpen(false)}
87
+ onClick={() => handleToggle(false)}
78
88
  className="wv-collapse-btn"
79
- title="Komut Barını Küçült"
89
+ title="Collapse mission panel"
80
90
  >
81
- Gizle ▼
91
+ Hide ▼
82
92
  </button>
83
93
  </div>
84
94
  )}
@@ -92,9 +102,9 @@ export function VirtualCommandBar({
92
102
  onChange={(e) => onChangeTarget(e.target.value)}
93
103
  className="wv-target-select"
94
104
  >
95
- <option value="auto">👑 Genel Müdür (Otomatik Delege)</option>
105
+ <option value="auto">👑 General Manager (auto-delegate)</option>
96
106
  {entities.length > 0 && (
97
- <optgroup label="Ofis Masaları / Çalışanlar">
107
+ <optgroup label="Office desks / staff">
98
108
  {entities.map((en) => (
99
109
  <option key={en.id} value={en.id}>
100
110
  {en.pinNumber ? `#${en.pinNumber} ` : ''}
@@ -128,10 +138,10 @@ export function VirtualCommandBar({
128
138
  type="button"
129
139
  onClick={onToggleDemoMode}
130
140
  className={`wv-demo-toggle-btn ${isDemoMode ? 'is-demo' : 'is-ai'}`}
131
- title="Çalışma Modu"
141
+ title="Execution mode"
132
142
  >
133
143
  {isDemoMode ? <Sparkles size={14} /> : <Bot size={14} />}
134
- <span className="wv-demo-label">{isDemoMode ? 'Demo Hızlı' : 'Gerçek AI'}</span>
144
+ <span className="wv-demo-label">{isDemoMode ? 'Fast demo' : 'Real AI'}</span>
135
145
  </button>
136
146
  )}
137
147
 
@@ -147,7 +157,7 @@ export function VirtualCommandBar({
147
157
  ) : (
148
158
  <>
149
159
  <Send size={14} style={{ marginRight: 6 }} />
150
- <span>Ateşle</span>
160
+ <span>Launch</span>
151
161
  </>
152
162
  )}
153
163
  </button>
@@ -64,14 +64,14 @@ export function VirtualEntityDrawer({
64
64
  type="button"
65
65
  onClick={onClose}
66
66
  className="wv-drawer-close-btn"
67
- title="Kapat (Esc)"
67
+ title="Close (Esc)"
68
68
  >
69
69
  <X size={16} />
70
70
  </button>
71
71
 
72
72
  <div className="wv-drawer-meta-tags">
73
73
  {entity.pinNumber && (
74
- <span className="wv-drawer-pin-tag">Masa #{entity.pinNumber}</span>
74
+ <span className="wv-drawer-pin-tag">Desk #{entity.pinNumber}</span>
75
75
  )}
76
76
  {entity.department && (
77
77
  <span className="wv-drawer-dept-tag">{entity.department}</span>
@@ -86,13 +86,13 @@ export function VirtualEntityDrawer({
86
86
  <div className="wv-drawer-body">
87
87
  {/* Status Row */}
88
88
  <div className="wv-drawer-status-card">
89
- <span className="wv-drawer-status-label">Çalışma Durumu</span>
89
+ <span className="wv-drawer-status-label">Work status</span>
90
90
  <span className={`wv-drawer-status-chip ${isRunning ? 'is-running' : isAwaiting ? 'is-awaiting' : 'is-idle'}`}>
91
91
  {isRunning
92
- ? '⚡ Görev Yürütüyor'
92
+ ? '⚡ Working on a mission'
93
93
  : isAwaiting
94
- ? '⏳ Onay Bekliyor'
95
- : '✓ Boşta / Göreve Hazır'}
94
+ ? '⏳ Awaiting approval'
95
+ : '✓ Idle / ready for a mission'}
96
96
  </span>
97
97
  </div>
98
98
 
@@ -101,19 +101,19 @@ export function VirtualEntityDrawer({
101
101
  <div className="wv-drawer-metrics-grid">
102
102
  <div className="wv-drawer-metric-cell">
103
103
  <div className="wv-metric-val">{metrics.totalRuns}</div>
104
- <div className="wv-metric-lbl">Toplam Görev</div>
104
+ <div className="wv-metric-lbl">Total missions</div>
105
105
  </div>
106
106
  <div className="wv-drawer-metric-cell">
107
107
  <div className="wv-metric-val is-success">
108
108
  {metrics.successRate !== undefined ? `${Math.round(metrics.successRate)}%` : '100%'}
109
109
  </div>
110
- <div className="wv-metric-lbl">Başarı Oranı</div>
110
+ <div className="wv-metric-lbl">Success rate</div>
111
111
  </div>
112
112
  <div className="wv-drawer-metric-cell">
113
113
  <div className="wv-metric-val">
114
114
  ${metrics.costUsd !== undefined ? metrics.costUsd.toFixed(3) : '0.000'}
115
115
  </div>
116
- <div className="wv-metric-lbl">Son 24s Maliyet</div>
116
+ <div className="wv-metric-lbl">Cost (last 24h)</div>
117
117
  </div>
118
118
  </div>
119
119
  )}
@@ -122,7 +122,7 @@ export function VirtualEntityDrawer({
122
122
  {latestTask ? (
123
123
  <div className="wv-drawer-task-section">
124
124
  <div className="wv-task-header">
125
- <span className="wv-task-title">Son / Aktif Görev</span>
125
+ <span className="wv-task-title">Latest / active mission</span>
126
126
  {latestTask.createdAt && (
127
127
  <span className="wv-task-time">
128
128
  {new Date(latestTask.createdAt).toLocaleTimeString([], {
@@ -137,7 +137,7 @@ export function VirtualEntityDrawer({
137
137
  <p className="wv-task-prompt">{latestTask.prompt}</p>
138
138
  {latestTask.summary && (
139
139
  <div className="wv-task-summary">
140
- <strong>Özet: </strong>
140
+ <strong>Summary: </strong>
141
141
  {latestTask.summary}
142
142
  </div>
143
143
  )}
@@ -148,7 +148,7 @@ export function VirtualEntityDrawer({
148
148
  className="wv-view-report-btn"
149
149
  >
150
150
  <FileText size={13} style={{ marginRight: 6 }} />
151
- <span>Çıktı Raporunu İncele</span>
151
+ <span>View output report</span>
152
152
  </button>
153
153
  )}
154
154
  </div>
@@ -156,14 +156,14 @@ export function VirtualEntityDrawer({
156
156
  ) : (
157
157
  <div className="wv-drawer-empty-task">
158
158
  <Clock size={20} className="wv-empty-icon" />
159
- <p>Henüz bu masada bir görev yürütülmedi.</p>
159
+ <p>No mission has been run at this desk yet.</p>
160
160
  </div>
161
161
  )}
162
162
 
163
163
  {/* Direct Dispatch to this Entity */}
164
164
  {onDispatch && onChangeDispatchPrompt && (
165
165
  <div className="wv-drawer-dispatch-section">
166
- <span className="wv-dispatch-title">Doğrudan Bu Masaya Görev Ver</span>
166
+ <span className="wv-dispatch-title">Assign a mission to this desk</span>
167
167
  <div className="wv-dispatch-row">
168
168
  <input
169
169
  type="text"
@@ -175,7 +175,7 @@ export function VirtualEntityDrawer({
175
175
  onDispatch()
176
176
  }
177
177
  }}
178
- placeholder="Örn: Yeni kampanya metinlerini hazırla..."
178
+ placeholder="e.g. Draft the new campaign copy..."
179
179
  className="wv-dispatch-input"
180
180
  />
181
181
  <button
@@ -17,7 +17,7 @@ export interface VirtualReportModalProps {
17
17
  export function VirtualReportModal({
18
18
  report,
19
19
  onClose,
20
- title = 'Görev ve Rapor Çıktısı',
20
+ title = 'Mission & output report',
21
21
  }: VirtualReportModalProps): ReactNode {
22
22
  useEffect(() => {
23
23
  const handleKeyDown = (e: KeyboardEvent) => {
@@ -42,7 +42,7 @@ export function VirtualReportModal({
42
42
  type="button"
43
43
  onClick={onClose}
44
44
  className="wv-modal-close-btn"
45
- title="Kapat"
45
+ title="Close"
46
46
  >
47
47
  <X size={16} />
48
48
  </button>
@@ -51,14 +51,15 @@ export function VirtualReportModal({
51
51
  {/* Modal Body */}
52
52
  <div className="wv-modal-body">
53
53
  <div className="wv-modal-prompt-box">
54
- <span className="wv-modal-section-label">İstek / Görev Briefi:</span>
54
+ <span className="wv-modal-section-label">Request / mission brief:</span>
55
55
  <p className="wv-modal-prompt-text">{report.prompt}</p>
56
56
  </div>
57
57
 
58
58
  <div className="wv-modal-output-section">
59
- <span className="wv-modal-section-label">Üretilen Sonuç / Rapor:</span>
59
+ <span className="wv-modal-section-label">Generated output / report:</span>
60
60
  <div className="wv-modal-output-box">
61
- {report.summary || 'Görev başarıyla tamamlandı. Çıktılar operasyon havuzuna aktarıldı.'}
61
+ {report.summary ||
62
+ 'Mission completed successfully. Outputs have been routed to the operations pool.'}
62
63
  </div>
63
64
  </div>
64
65
  </div>
@@ -70,7 +71,7 @@ export function VirtualReportModal({
70
71
  onClick={onClose}
71
72
  className="wv-modal-btn"
72
73
  >
73
- Kapat
74
+ Close
74
75
  </button>
75
76
  </div>
76
77
  </div>
@@ -37,7 +37,7 @@ export function VirtualRoster({
37
37
  onSearchChange,
38
38
  selectedCategory,
39
39
  onSelectCategory,
40
- title = 'Ofis Kadrosu',
40
+ title = 'Office roster',
41
41
  className = '',
42
42
  }: VirtualRosterProps): ReactNode {
43
43
  // Filter entities based on search and category
@@ -85,14 +85,16 @@ export function VirtualRoster({
85
85
  </div>
86
86
  <div>
87
87
  <h3 className="wv-roster-heading">{title}</h3>
88
- <p className="wv-roster-subheading">{entities.length} çalışan ofis masalarında</p>
88
+ <p className="wv-roster-subheading">
89
+ {entities.length} {entities.length === 1 ? 'member' : 'members'} at their desks
90
+ </p>
89
91
  </div>
90
92
  </div>
91
93
  <button
92
94
  type="button"
93
95
  onClick={onClose}
94
96
  className="wv-roster-close-btn"
95
- title="Kadro Panelini Gizle"
97
+ title="Hide roster panel"
96
98
  >
97
99
  <X size={16} />
98
100
  </button>
@@ -105,7 +107,7 @@ export function VirtualRoster({
105
107
  type="text"
106
108
  value={searchQuery}
107
109
  onChange={(e) => onSearchChange(e.target.value)}
108
- placeholder="Çalışan veya rol ara..."
110
+ placeholder="Search by name or role..."
109
111
  className="wv-roster-search-input"
110
112
  />
111
113
  </div>
@@ -118,7 +120,7 @@ export function VirtualRoster({
118
120
  onClick={() => onSelectCategory('all')}
119
121
  className={`wv-roster-pill ${selectedCategory === 'all' ? 'is-active' : ''}`}
120
122
  >
121
- Tümü
123
+ All
122
124
  </button>
123
125
  {departments.map((dept) => (
124
126
  <button
@@ -169,7 +171,7 @@ export function VirtualRoster({
169
171
  {en.pinNumber && <span className="wv-roster-pin">#{en.pinNumber}</span>}
170
172
  <h4 className="wv-roster-name">{en.name}</h4>
171
173
  </div>
172
- <p className="wv-roster-role">{en.role || en.description || 'Çalışan'}</p>
174
+ <p className="wv-roster-role">{en.role || en.description || 'Staff member'}</p>
173
175
  </div>
174
176
  </div>
175
177
 
@@ -7,6 +7,7 @@ import {
7
7
  forwardRef,
8
8
  useImperativeHandle,
9
9
  } from 'react'
10
+ import { MonitorOff, RotateCw } from 'lucide-react'
10
11
  import * as THREE from 'three'
11
12
  import type {
12
13
  WorldDefinition,
@@ -15,7 +16,7 @@ import type {
15
16
  PinDisplayMode,
16
17
  } from '../core/types'
17
18
  import { WorldEngine } from '../engine/renderer'
18
- import { createStylizedAvatar } from '../entities/people/AvatarBuilder'
19
+ import { createStylizedAvatar, type CreatedAvatar } from '../entities/people/AvatarBuilder'
19
20
  import { EntityPins } from './EntityPins'
20
21
  import { WorldControls } from './WorldControls'
21
22
  import { EntityInspector } from './EntityInspector'
@@ -36,6 +37,10 @@ export interface VirtualWorldProps {
36
37
  onSelectEntity?: (entity: WorldEntity | null) => void
37
38
  onHoverEntity?: (entity: WorldEntity | null) => void
38
39
  defaultPinMode?: PinDisplayMode
40
+ pinMode?: PinDisplayMode
41
+ onChangePinMode?: (mode: PinDisplayMode) => void
42
+ nightMode?: boolean
43
+ onToggleNightMode?: () => void
39
44
  showControls?: boolean
40
45
  showInspector?: boolean
41
46
  className?: string
@@ -53,7 +58,11 @@ export const VirtualWorld = forwardRef<VirtualWorldRef, VirtualWorldProps>(
53
58
  selectedEntityId,
54
59
  onSelectEntity,
55
60
  onHoverEntity,
56
- defaultPinMode = 'pins',
61
+ defaultPinMode = 'off',
62
+ pinMode: externalPinMode,
63
+ onChangePinMode,
64
+ nightMode: externalNightMode,
65
+ onToggleNightMode: externalToggleNightMode,
57
66
  showControls = true,
58
67
  showInspector = true,
59
68
  className = '',
@@ -69,11 +78,34 @@ export const VirtualWorld = forwardRef<VirtualWorldRef, VirtualWorldProps>(
69
78
  const engineRef = useRef<WorldEngine | null>(null)
70
79
  const pinElementsRef = useRef<Map<string, HTMLElement>>(new Map())
71
80
 
72
- const [nightMode, setNightMode] = useState(false)
73
- const [pinMode, setPinMode] = useState<PinDisplayMode>(defaultPinMode)
81
+ // Hot-sync registry: avatars are created once per entity and updated in place.
82
+ const avatarRegistryRef = useRef<Map<string, CreatedAvatar>>(new Map())
83
+ const avatarGroupRef = useRef<THREE.Group | null>(null)
84
+ const staticInteractivesRef = useRef<THREE.Object3D[]>([])
85
+
86
+ // Latest props/refs readable by stable engine callbacks (prevents engine re-init churn)
87
+ const worldRef = useRef(world)
88
+ const nightModeRef = useRef(false)
89
+ const callbacksRef = useRef({
90
+ onSelectEntity: (_entity: WorldEntity | null) => {},
91
+ onHoverEntity: (_entity: WorldEntity | null) => {},
92
+ })
93
+
94
+ const [internalNightMode, setInternalNightMode] = useState(false)
95
+ const [internalPinMode, setInternalPinMode] = useState<PinDisplayMode>(defaultPinMode)
74
96
  const [fps, setFps] = useState<number>(60)
75
97
  const [internalSelectedEntity, setInternalSelectedEntity] = useState<WorldEntity | null>(null)
76
98
 
99
+ // WebGL resilience state
100
+ const [webglFailed, setWebglFailed] = useState(false)
101
+ const [contextLost, setContextLost] = useState(false)
102
+ const [engineEpoch, setEngineEpoch] = useState(0)
103
+
104
+ const nightMode = externalNightMode !== undefined ? externalNightMode : internalNightMode
105
+ const pinMode = externalPinMode !== undefined ? externalPinMode : internalPinMode
106
+ nightModeRef.current = nightMode
107
+ worldRef.current = world
108
+
77
109
  // Determine active selected entity (controlled or uncontrolled)
78
110
  const activeEntity =
79
111
  selectedEntityId !== undefined
@@ -90,6 +122,14 @@ export const VirtualWorld = forwardRef<VirtualWorldRef, VirtualWorldProps>(
90
122
  [onSelectEntity],
91
123
  )
92
124
 
125
+ // Keep stable engine callbacks pointing at the latest handler identities
126
+ useEffect(() => {
127
+ callbacksRef.current = {
128
+ onSelectEntity: handleSelectEntity,
129
+ onHoverEntity: onHoverEntity || (() => {}),
130
+ }
131
+ })
132
+
93
133
  const handleRegisterPinElement = useCallback((entityId: string, el: HTMLElement | null) => {
94
134
  if (el) {
95
135
  pinElementsRef.current.set(entityId, el)
@@ -98,59 +138,63 @@ export const VirtualWorld = forwardRef<VirtualWorldRef, VirtualWorldProps>(
98
138
  }
99
139
  }, [])
100
140
 
101
- // Initialize Three.js Engine
141
+ // ============================================================
142
+ // ENGINE LIFECYCLE — created once per preset (NOT per world data
143
+ // change). Scene, lighting, camera and GLB models survive
144
+ // entity/polling updates; only avatars are diffed below.
145
+ // ============================================================
102
146
  useEffect(() => {
103
147
  const canvas = canvasRef.current
104
148
  const container = containerRef.current
105
149
  if (!canvas || !container) return
106
150
 
107
- const engine = new WorldEngine({
108
- canvas,
109
- world,
110
- pinElements: pinElementsRef.current,
111
- onSelectEntity: (evt) => {
112
- handleSelectEntity(evt.entity)
113
- },
114
- onHoverEntity: (entity) => {
115
- if (onHoverEntity) onHoverEntity(entity)
116
- },
117
- onFpsUpdate: (currentFps) => {
118
- setFps(currentFps)
119
- },
120
- })
151
+ let engine: WorldEngine
152
+ try {
153
+ engine = new WorldEngine({
154
+ canvas,
155
+ world: worldRef.current,
156
+ pinElements: pinElementsRef.current,
157
+ onSelectEntity: (evt) => callbacksRef.current.onSelectEntity(evt.entity),
158
+ onHoverEntity: (entity) => callbacksRef.current.onHoverEntity(entity),
159
+ onFpsUpdate: (currentFps) => {
160
+ setFps(currentFps)
161
+ },
162
+ onContextLost: () => setContextLost(true),
163
+ })
164
+ } catch (err) {
165
+ console.error('[web-virtual] WebGL is unavailable, rendering fallback UI:', err)
166
+ setWebglFailed(true)
167
+ return
168
+ }
169
+
121
170
  engineRef.current = engine
171
+ setWebglFailed(false)
172
+ setContextLost(false)
122
173
 
123
174
  // 1. Build environment from preset or custom scene builder
124
175
  const activePreset = preset
125
176
  if (activePreset && activePreset.buildScene) {
126
177
  activePreset.buildScene(engine.scene, {
127
- nightMode,
128
- theme: world.theme,
178
+ nightMode: nightModeRef.current,
179
+ theme: worldRef.current.theme,
129
180
  })
130
181
  }
131
182
 
132
- // 2. Build 3D Avatars for people/actor entities
183
+ // 2. Avatar container — populated by the entity sync effect below
133
184
  const avatarGroup = new THREE.Group()
134
185
  avatarGroup.name = 'world-avatars'
135
-
136
- for (const entity of world.entities) {
137
- if (entity.type === 'person' || entity.type === 'actor') {
138
- const { group, animate } = createStylizedAvatar(entity, engine.materials)
139
- avatarGroup.add(group)
140
- engine.animators.push(animate)
141
- engine.interactiveObjects.push(group)
142
- }
143
- }
144
186
  engine.scene.add(avatarGroup)
187
+ avatarGroupRef.current = avatarGroup
145
188
 
146
- // 3. Register all interactive objects with entityId (workstations, chairs, monitors, avatars)
189
+ // 3. Collect static interactive objects (workstations, chairs, monitors)
190
+ const staticInteractives: THREE.Object3D[] = []
147
191
  engine.scene.traverse((obj) => {
148
192
  if (obj.userData && obj.userData.entityId) {
149
- if (!engine.interactiveObjects.includes(obj)) {
150
- engine.interactiveObjects.push(obj)
151
- }
193
+ staticInteractives.push(obj)
152
194
  }
153
195
  })
196
+ staticInteractivesRef.current = staticInteractives
197
+ engine.interactiveObjects = [...staticInteractives]
154
198
 
155
199
  // Resize Observer
156
200
  const resizeObserver = new ResizeObserver((entries) => {
@@ -165,22 +209,85 @@ export const VirtualWorld = forwardRef<VirtualWorldRef, VirtualWorldProps>(
165
209
 
166
210
  return () => {
167
211
  resizeObserver.disconnect()
212
+ avatarRegistryRef.current.clear()
213
+ avatarGroupRef.current = null
214
+ staticInteractivesRef.current = []
168
215
  engine.dispose()
169
216
  engineRef.current = null
170
- pinElementsRef.current.clear()
171
217
  }
172
- }, [world, preset, handleSelectEntity, onHoverEntity])
218
+ }, [preset, engineEpoch])
219
+
220
+ // ============================================================
221
+ // ENTITY HOT-SYNC — diff world.entities against the avatar
222
+ // registry: add new avatars, update changed ones in place
223
+ // (status halo, animation flags, transform), remove stale ones.
224
+ // No scene rebuild, no GLB reload, no camera reset.
225
+ // ============================================================
226
+ useEffect(() => {
227
+ const engine = engineRef.current
228
+ const avatarGroup = avatarGroupRef.current
229
+ if (!engine || !avatarGroup) return
230
+
231
+ // Always point the engine (raycaster/projector/focus) at the latest data
232
+ engine.updateWorld(world)
233
+
234
+ const registry = avatarRegistryRef.current
235
+ const seen = new Set<string>()
236
+
237
+ for (const entity of world.entities) {
238
+ if (entity.type !== 'person' && entity.type !== 'actor') continue
239
+ seen.add(entity.id)
240
+
241
+ const existing = registry.get(entity.id)
242
+ if (existing) {
243
+ existing.update(entity)
244
+ continue
245
+ }
246
+
247
+ const created = createStylizedAvatar(entity, engine.materials)
248
+ registry.set(entity.id, created)
249
+ avatarGroup.add(created.group)
250
+ }
251
+
252
+ // Remove avatars for entities that no longer exist
253
+ for (const [id, created] of registry) {
254
+ if (!seen.has(id)) {
255
+ created.group.removeFromParent()
256
+ registry.delete(id)
257
+ }
258
+ }
259
+
260
+ // Rebuild animator + interactive lists from the registry
261
+ engine.animators = Array.from(registry.values()).map((a) => a.animate)
262
+ engine.interactiveObjects = [
263
+ ...staticInteractivesRef.current,
264
+ ...Array.from(registry.values()).map((a) => a.group),
265
+ ]
266
+ }, [world, preset, engineEpoch])
267
+
268
+ // Sync Night Mode with engine
269
+ useEffect(() => {
270
+ if (engineRef.current) {
271
+ engineRef.current.setNightMode(nightMode)
272
+ }
273
+ }, [nightMode])
173
274
 
174
275
  // Handle Night Mode Toggle
175
276
  const handleToggleNightMode = useCallback(() => {
176
- setNightMode((prev) => {
177
- const next = !prev
178
- if (engineRef.current) {
179
- engineRef.current.setNightMode(next)
180
- }
181
- return next
182
- })
183
- }, [])
277
+ if (externalToggleNightMode) {
278
+ externalToggleNightMode()
279
+ } else {
280
+ setInternalNightMode((prev) => !prev)
281
+ }
282
+ }, [externalToggleNightMode])
283
+
284
+ const handlePinModeChange = useCallback(
285
+ (newMode: PinDisplayMode) => {
286
+ setInternalPinMode(newMode)
287
+ if (onChangePinMode) onChangePinMode(newMode)
288
+ },
289
+ [onChangePinMode],
290
+ )
184
291
 
185
292
  // Handle Camera Presets
186
293
  const handleCameraPreset = useCallback((presetName: CameraPresetName) => {
@@ -215,7 +322,7 @@ export const VirtualWorld = forwardRef<VirtualWorldRef, VirtualWorldProps>(
215
322
  if (engineRef.current) engineRef.current.resetCamera()
216
323
  },
217
324
  setNightMode: (isNight: boolean) => {
218
- setNightMode(isNight)
325
+ setInternalNightMode(isNight)
219
326
  if (engineRef.current) engineRef.current.setNightMode(isNight)
220
327
  },
221
328
  resize: () => {
@@ -228,16 +335,68 @@ export const VirtualWorld = forwardRef<VirtualWorldRef, VirtualWorldProps>(
228
335
  [],
229
336
  )
230
337
 
338
+ const handleRestoreContext = useCallback(() => {
339
+ // Rebuild the engine from scratch (fresh WebGL context, fresh scene)
340
+ setContextLost(false)
341
+ setEngineEpoch((epoch) => epoch + 1)
342
+ }, [])
343
+
344
+ // Graceful fallback when WebGL is not available at all
345
+ if (webglFailed) {
346
+ return (
347
+ <div
348
+ ref={containerRef}
349
+ className={`wv-container wv-webgl-fallback ${className}`}
350
+ style={style}
351
+ role="region"
352
+ aria-label={`${world.name} 3D environment`}
353
+ >
354
+ <div className="wv-fallback-card">
355
+ <MonitorOff size={28} />
356
+ <h3>3D view unavailable</h3>
357
+ <p>
358
+ Your browser or device does not support WebGL, which is required for the 3D
359
+ environment. Entity data remains available below.
360
+ </p>
361
+ <ul className="wv-fallback-entity-list">
362
+ {world.entities.slice(0, 12).map((entity) => (
363
+ <li key={entity.id}>
364
+ <span className={`wv-status-pip ${entity.status || 'idle'}`} />
365
+ {entity.pinNumber ? `#${entity.pinNumber} ` : ''}
366
+ {entity.name}
367
+ </li>
368
+ ))}
369
+ </ul>
370
+ </div>
371
+ {children}
372
+ </div>
373
+ )
374
+ }
375
+
231
376
  return (
232
377
  <div
233
378
  ref={containerRef}
234
- className={`wv-container ${className}`}
379
+ className={`wv-container ${nightMode ? 'is-night' : ''} ${className}`}
235
380
  style={style}
236
381
  role="region"
237
- aria-label={`${world.name} 3D Sanal Ortamı`}
382
+ aria-label={`${world.name} 3D environment`}
238
383
  >
239
384
  <canvas ref={canvasRef} className="wv-canvas" />
240
385
 
386
+ {/* WebGL context lost overlay (e.g. GPU driver reset) */}
387
+ {contextLost && (
388
+ <div className="wv-context-lost-overlay">
389
+ <div className="wv-fallback-card">
390
+ <RotateCw size={26} />
391
+ <h3>3D view interrupted</h3>
392
+ <p>The graphics context was lost (usually a GPU or tab reset). Restore it below.</p>
393
+ <button type="button" className="wv-fallback-btn" onClick={handleRestoreContext}>
394
+ Restore 3D view
395
+ </button>
396
+ </div>
397
+ </div>
398
+ )}
399
+
241
400
  {/* Floating 60fps GPU Projected Pins */}
242
401
  <EntityPins
243
402
  entities={world.entities}
@@ -253,7 +412,7 @@ export const VirtualWorld = forwardRef<VirtualWorldRef, VirtualWorldProps>(
253
412
  nightMode={nightMode}
254
413
  onToggleNightMode={handleToggleNightMode}
255
414
  pinMode={pinMode}
256
- onChangePinMode={setPinMode}
415
+ onChangePinMode={handlePinModeChange}
257
416
  onSelectCameraPreset={handleCameraPreset}
258
417
  onResetCamera={handleResetCamera}
259
418
  fps={fps}