-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathMetadataVisualizer.tsx
More file actions
397 lines (350 loc) · 12.5 KB
/
MetadataVisualizer.tsx
File metadata and controls
397 lines (350 loc) · 12.5 KB
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
import React, { useRef, useEffect, useState, useMemo } from 'react';
import * as THREE from 'three'; // Use namespace import
import { useThree, useFrame } from '@react-three/fiber';
// import { Text, Billboard, useTexture } from '@react-three/drei'; // Commented out due to import errors
import { usePlatform } from '@/services/platformManager';
import { useSettingsStore } from '@/store/settingsStore';
import { createLogger } from '@/utils/logger';
const logger = createLogger('MetadataVisualizer');
// Type guard to check for Vector3 instance using instanceof
// Reverting to instanceof check as property check didn't resolve TS errors
function isVector3Instance(obj: any): obj is THREE.Vector3 {
// Check if Vector3 constructor exists on THREE before using instanceof
return typeof THREE.Vector3 === 'function' && obj instanceof THREE.Vector3;
}
// Types for metadata and labels
export interface NodeMetadata {
id: string;
position: [number, number, number] | { x: number; y: number; z: number } | THREE.Vector3;
label?: string;
description?: string;
fileSize?: number;
type?: string;
color?: string | number;
icon?: string;
priority?: number;
[key: string]: any; // Allow additional properties
}
interface MetadataVisualizerProps {
children?: React.ReactNode;
renderLabels?: boolean;
renderIcons?: boolean;
renderMetrics?: boolean;
}
/**
* MetadataVisualizer component using React Three Fiber
* This is a modernized version of the original MetadataVisualizer class
*/
export const MetadataVisualizer: React.FC<MetadataVisualizerProps> = ({
children,
renderLabels = true,
renderIcons = true,
renderMetrics = false
}) => {
const { scene, camera } = useThree();
// Use THREE.Object3D as Group might not be resolving correctly
const groupRef = useRef<THREE.Group>(null);
const { isXRMode } = usePlatform();
const labelSettings = useSettingsStore(state => state.settings?.visualisation?.labels);
// Layer management for XR mode
useEffect(() => {
if (!groupRef.current) return;
// Set layers based on XR mode
const group = groupRef.current;
if (isXRMode) {
// In XR mode, use layer 1 to ensure labels are visible in XR
group.traverse(obj => {
obj.layers.set(1);
});
} else {
// In desktop mode, use default layer
group.traverse(obj => {
obj.layers.set(0);
});
}
}, [isXRMode]);
// Render optimization - only update label positions at 30fps
useFrame((state, delta) => {
// Potential optimization logic here
}, 2); // Lower priority than regular rendering
return (
// Use THREE.Group directly in JSX if needed, or keep as <group>
<group ref={groupRef} name="metadata-container">
{children}
{/* {renderLabels && <LabelSystem />} */} {/* Commented out LabelSystem usage */}
{renderIcons && <IconSystem />}
{renderMetrics && <MetricsDisplay />}
</group>
);
};
// Component to display node labels with proper positioning and formatting
const LabelSystem: React.FC = () => {
const labelManagerRef = useTextLabelManager();
const { labels } = labelManagerRef.current;
const labelSettings = useSettingsStore(state => state.settings?.visualisation?.labels);
// Don't render if labels are disabled
// if (!labelSettings?.enabled) return null; // Commented out due to type error
return (
<group name="label-system">
{labels.map(label => (
<NodeLabel
key={label.id}
id={label.id}
position={label.position}
text={label.text}
// color={labelSettings.color || '#ffffff'} // Commented out
// size={labelSettings.size || 1} // Commented out
// backgroundColor={labelSettings.backgroundColor} // Commented out
// showDistance={labelSettings.showDistance} // Commented out
// fadeDistance={labelSettings.fadeDistance} // Commented out
/>
))}
</group>
);
};
// Advanced label component with distance-based fading and billboarding
interface NodeLabelProps {
id: string;
position: [number, number, number] | { x: number; y: number; z: number } | THREE.Vector3;
text: string;
color?: string;
size?: number;
backgroundColor?: string;
showDistance?: number;
fadeDistance?: number;
}
const NodeLabel: React.FC<NodeLabelProps> = ({
id,
position,
text,
color = '#ffffff',
size = 1,
backgroundColor,
showDistance = 0,
fadeDistance = 0
}) => {
// Skip rendering empty labels
if (!text?.trim()) return null;
const { camera } = useThree();
const [opacity, setOpacity] = useState(1);
// Convert position to tuple format with type guards
const labelPos: [number, number, number] = useMemo(() => {
if (isVector3Instance(position)) { // Use instanceof type guard
// Explicit cast to help TS understand the type is narrowed
const vec = position as THREE.Vector3;
return [vec.x, vec.y, vec.z];
} else if (Array.isArray(position)) {
return position as [number, number, number]; // Assume it's a tuple if array
} else if (typeof position === 'object' && position !== null && 'x' in position && 'y' in position && 'z' in position) {
const posObj = position as { x: number; y: number; z: number };
return [posObj.x, posObj.y, posObj.z];
}
logger.warn(`Invalid position format for label ${id}:`, position);
return [0, 0, 0]; // Default position if format is unknown
}, [position]);
// Handle distance-based opacity
useFrame(() => {
if (!fadeDistance) return;
// Calculate distance using tuple positions
const dx = camera.position.x - labelPos[0];
const dy = camera.position.y - labelPos[1];
const dz = camera.position.z - labelPos[2];
const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (distance > fadeDistance) {
setOpacity(0);
} else if (distance > showDistance) {
// Linear fade from showDistance to fadeDistance
const fadeRatio = 1 - ((distance - showDistance) / (fadeDistance - showDistance));
setOpacity(Math.max(0, Math.min(1, fadeRatio)));
} else {
setOpacity(1);
}
});
// Don't render if fully transparent
if (opacity <= 0) return null;
// Commenting out Billboard and Text usage due to import errors
return null;
/*
return (
<Billboard
position={labelPos}
follow={true}
lockX={false}
lockY={false}
lockZ={false}
>
<Text
fontSize={size}
color={color}
anchorX="center"
anchorY="middle"
outlineWidth={0.02}
outlineColor="#000000"
outlineOpacity={0.8}
overflowWrap="normal"
maxWidth={10}
textAlign="center"
renderOrder={10} // Ensure text renders on top of other objects
material-depthTest={false} // Make sure text is always visible
material-transparent={true}
material-opacity={opacity}
>
{text}
{backgroundColor && (
<meshBasicMaterial
// color={backgroundColor} // Commented out due to type error
opacity={opacity * 0.7}
transparent={true}
side={THREE.DoubleSide} // Use THREE namespace
/>
)}
</Text>
</Billboard>
);
*/
};
// System to display icons next to nodes
const IconSystem: React.FC = () => {
// Implement if needed
return null;
};
// System to display performance metrics
const MetricsDisplay: React.FC = () => {
// Implement if needed
return null;
};
// Hook to manage text labels
export function useTextLabelManager() {
const labelManagerRef = useRef<{
labels: Array<{
id: string;
text: string;
position: [number, number, number];
}>;
updateLabel: (id: string, text: string, position: [number, number, number] | { x: number; y: number; z: number } | THREE.Vector3) => void;
removeLabel: (id: string) => void;
clearLabels: () => void;
}>({
labels: [],
updateLabel: (id, text, position) => {
const labels = labelManagerRef.current.labels;
// Convert position to tuple format with type guards
let pos: [number, number, number];
if (isVector3Instance(position)) { // Use instanceof type guard
// Explicit cast to help TS understand the type is narrowed
const vec = position as THREE.Vector3;
pos = [vec.x, vec.y, vec.z];
} else if (Array.isArray(position)) {
pos = position as [number, number, number];
} else if (typeof position === 'object' && position !== null && 'x' in position && 'y' in position && 'z' in position) {
const posObj = position as { x: number; y: number; z: number };
pos = [posObj.x, posObj.y, posObj.z];
} else {
logger.warn(`Invalid position format for updateLabel ${id}:`, position);
pos = [0, 0, 0]; // Default or handle error
}
const existingLabelIndex = labels.findIndex(label => label.id === id);
if (existingLabelIndex >= 0) {
// Update existing label
labels[existingLabelIndex] = {
...labels[existingLabelIndex],
text: text || labels[existingLabelIndex].text,
position: pos
};
} else {
// Add new label
labels.push({ id, text, position: pos });
}
// Force update by creating a new array
labelManagerRef.current.labels = [...labels];
},
removeLabel: (id) => {
labelManagerRef.current.labels = labelManagerRef.current.labels.filter(
label => label.id !== id
);
},
clearLabels: () => {
labelManagerRef.current.labels = [];
}
});
return labelManagerRef;
}
// Factory function to create SDF font texture for high-quality text rendering
export const createSDFFont = async (fontUrl: string, fontSize: number = 64) => {
// This would be an implementation of SDF font generation
// For now, we use drei's Text component which provides high-quality text
return null;
};
// Class-based API for backwards compatibility
export class MetadataVisualizerManager {
private static instance: MetadataVisualizerManager;
private labels: Map<string, { text: string; position: [number, number, number] }> = new Map();
private updateCallback: (() => void) | null = null;
private constructor() {}
public static getInstance(): MetadataVisualizerManager {
if (!MetadataVisualizerManager.instance) {
MetadataVisualizerManager.instance = new MetadataVisualizerManager();
}
return MetadataVisualizerManager.instance;
}
public setUpdateCallback(callback: () => void): void {
this.updateCallback = callback;
}
public updateNodeLabel(
nodeId: string,
text: string,
position: [number, number, number] | { x: number; y: number; z: number } | THREE.Vector3
): void {
try {
// Convert position to tuple format with type guards
let pos: [number, number, number];
if (isVector3Instance(position)) { // Use instanceof type guard
// Explicit cast to help TS understand the type is narrowed
const vec = position as THREE.Vector3;
pos = [vec.x, vec.y, vec.z];
} else if (Array.isArray(position)) {
pos = position as [number, number, number];
} else if (typeof position === 'object' && position !== null && 'x' in position && 'y' in position && 'z' in position) {
const posObj = position as { x: number; y: number; z: number };
pos = [posObj.x, posObj.y, posObj.z];
} else {
logger.warn(`Invalid position format for updateNodeLabel ${nodeId}:`, position);
pos = [0,0,0]; // Default or handle error
}
this.labels.set(nodeId, { text, position: pos });
if (this.updateCallback) {
this.updateCallback();
}
} catch (error) {
logger.error('Error updating node label:', error);
}
}
public clearLabel(nodeId: string): void {
this.labels.delete(nodeId);
if (this.updateCallback) {
this.updateCallback();
}
}
public clearAllLabels(): void {
this.labels.clear();
if (this.updateCallback) {
this.updateCallback();
}
}
public getAllLabels(): Array<{ id: string; text: string; position: [number, number, number] }> {
return Array.from(this.labels.entries()).map(([id, label]) => ({
id,
text: label.text,
position: label.position
}));
}
public dispose(): void {
this.labels.clear();
this.updateCallback = null;
// Reset singleton instance
MetadataVisualizerManager.instance = null as any;
}
}
// Export singleton instance for backwards compatibility
export const metadataVisualizer = MetadataVisualizerManager.getInstance();
export default MetadataVisualizer;