-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3dViewer_01.html
More file actions
753 lines (627 loc) · 25.9 KB
/
Copy path3dViewer_01.html
File metadata and controls
753 lines (627 loc) · 25.9 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
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D Model Viewer with Annotations</title>
<style>
/* ========================================
MINIMAL CSS STYLES
======================================== */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background: #000;
overflow: hidden;
}
/* 3D Canvas Container */
#canvas-container {
width: 100vw;
height: 100vh;
position: relative;
}
/* Loading Screen */
#loading {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 18px;
z-index: 100;
}
/* Controls Panel */
#controls {
position: absolute;
bottom: 20px;
left: 20px;
<!--background: rgba(255, 255, 255, 0.9);-->
padding: 15px;
border-radius: 8px;
z-index: 200;
}
#controls button {
margin: 5px;
padding: 8px 12px;
border: none;
border-radius: 4px;color: white;
background:none;
<!--background: #007bff;-->
cursor: pointer;
}
#controls button:hover {
background: #0056b3;
color: white;
}
/* Annotation Tooltips */
.annotation {
position: absolute;
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 8px 12px;
border-radius: 4px;
font-size: 14px;
pointer-events: none;
z-index: 300;
max-width: 200px;
display: none;
}
.annotation::after {
content: '';
position: absolute;
bottom: -5px;
left: 50%;
transform: translateX(-50%);
border: 5px solid transparent;
border-top-color: rgba(0, 0, 0, 0.8);
}
/* Hotspot Markers */
.hotspot {
position: absolute;
width: 10px;
height: 10px;
background: #ff6b6b;
border: 2px solid white;
border-radius: 50%;
cursor: pointer;
z-index: 250;
animation: pulse 2s infinite;
}
.hotspot:hover {
background: #ff5252;
transform: scale(1.1);
}
@keyframes pulse {
0% { box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.7); }
70% { box-shadow: 0 0 0 10px rgba(255, 107, 107, 0); }
100% { box-shadow: 0 0 0 0 rgba(255, 107, 107, 0); }
}
/* Error Message */
#error {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #ff6b6b;
text-align: center;
display: none;
z-index: 100;
}
</style>
</head>
<body>
<!-- ========================================
HTML STRUCTURE
======================================== -->
<div id="canvas-container">
<!-- Loading indicator -->
<div id="loading">Loading 3D Model...</div>
<!-- Error message -->
<div id="error">
<h3>Error Loading Model</h3>
<p>Please check the file path and try again.</p>
</div>
<!-- Control Panel -->
<div id="controls">
<!--<h4>3D Model Controls</h4>-->
<button onclick="ModelViewer.resetCamera()">Reset View</button>
<button onclick="ModelViewer.toggleWireframe()">Toggle Wireframe</button>
<button onclick="ModelViewer.changeModel()">Change Model</button>
</div>
<!-- Annotation tooltips (hidden by default) -->
<div id="annotation-1" class="annotation">
This is annotation point 1 - describing a specific feature of the model.
</div>
<div id="annotation-2" class="annotation">
Annotation point 2 - highlighting another important detail.
</div>
<div id="annotation-3" class="annotation">
Point 3 annotation - additional information about this area.
</div>
<!-- Hotspot markers (positioned dynamically) -->
<div id="hotspot-1" class="hotspot" data-annotation="annotation-1"></div>
<div id="hotspot-2" class="hotspot" data-annotation="annotation-2"></div>
<div id="hotspot-3" class="hotspot" data-annotation="annotation-3"></div>
<div id="hotspot-4" class="hotspot" data-annotation="annotation-4"></div>
</div>
<!-- Three.js Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/loaders/GLTFLoader.js"></script>
<script>
/* ========================================
GLOBAL VARIABLES AND CONFIGURATION
======================================== */
const ModelViewer = {
// File configuration - CHANGE THIS PATH AS NEEDED
currentModelPath: "https://gefercan2.github.io/were_we_there.glb", // Replace with: "./Objeto1_.glb"
// Alternative models for switching (optional)
modelPaths: [
"here goes the path of the file", // Model 1
"./alternative-model.glb", // Model 2 (example)
"./another-model.glb" // Model 3 (example)
],
currentModelIndex: 0,
// Three.js core objects
scene: null,
camera: null,
renderer: null,
controls: null,
loader: null,
// Model and lighting
currentModel: null,
lights: [],
// Annotation data - CONFIGURE YOUR HOTSPOTS HERE
annotations: [
{
id: 'hotspot-1',
position: { x:-21, y:-5, z: -39 }, // 3D world position
annotationId: 'annotation-1'
},
{
id: 'hotspot-2',
position: { x:-12, y: -8, z: -19 }, // 3D world position
annotationId: 'annotation-2'
},
{
id: 'hotspot-3',
position: { x:-19, y: -10, z: -19}, // 3D world position
annotationId: 'annotation-3'
},
{
id: 'hotspot-4',
position: { x:-19, y: -10, z: -12}, // 3D world position
annotationId: 'annotation-4'
}
],
// State variables
isWireframe: false,
isLoading: false
};
/* ========================================
INITIALIZATION FUNCTIONS
======================================== */
/**
* Initialize the entire 3D viewer
*/
function initializeViewer() {
console.log('Initializing 3D Model Viewer...');
try {
setupScene();
setupCamera();
setupRenderer();
setupControls();
setupLighting();
setupEventListeners();
loadModel(ModelViewer.currentModelPath);
startRenderLoop();
console.log('3D Viewer initialized successfully');
} catch (error) {
console.error('Error initializing viewer:', error);
showError('Failed to initialize 3D viewer');
}
}
/**
* Setup the Three.js scene
*/
function setupScene() {
ModelViewer.scene = new THREE.Scene();
ModelViewer.scene.background = new THREE.Color(0x767676);
console.log('Scene created');
}
/**
* Setup the camera with optimal settings
*/
function setupCamera() {
const container = document.getElementById('canvas-container');
const aspect = container.clientWidth / container.clientHeight;
ModelViewer.camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000);
ModelViewer.camera.position.set(5, 3, 5);
ModelViewer.camera.lookAt(0, 0, 0);
console.log('Camera configured');
}
/**
* Setup the WebGL renderer
*/
function setupRenderer() {
const container = document.getElementById('canvas-container');
ModelViewer.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
ModelViewer.renderer.setSize(container.clientWidth, container.clientHeight);
ModelViewer.renderer.shadowMap.enabled = true;
ModelViewer.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
container.appendChild(ModelViewer.renderer.domElement);
console.log('Renderer initialized');
}
/**
* Setup orbit controls for camera movement
*/
function setupControls() {
ModelViewer.controls = new THREE.OrbitControls(
ModelViewer.camera,
ModelViewer.renderer.domElement
);
ModelViewer.controls.enableDamping = true;
ModelViewer.controls.dampingFactor = 0.05;
ModelViewer.controls.enableZoom = true;
ModelViewer.controls.enablePan = true;
console.log('Camera controls configured');
}
/**
* Setup scene lighting
*/
function setupLighting() {
// Ambient light for overall illumination
const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
ModelViewer.scene.add(ambientLight);
ModelViewer.lights.push(ambientLight);
// Directional light for shadows and definition
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(10, 10, 5);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
ModelViewer.scene.add(directionalLight);
ModelViewer.lights.push(directionalLight);
// Point light for additional illumination
const pointLight = new THREE.PointLight(0xffffff, 0.5);
pointLight.position.set(-10, 10, -10);
ModelViewer.scene.add(pointLight);
ModelViewer.lights.push(pointLight);
console.log('Lighting setup complete');
}
/* ========================================
MODEL LOADING FUNCTIONS
======================================== */
/**
* Load a 3D model from the specified path
* @param {string} modelPath - Path to the GLB/GLTF file
*/
function loadModel(modelPath) {
if (ModelViewer.isLoading) {
console.log('Model already loading, please wait...');
return;
}
console.log(`Loading model: ${modelPath}`);
showLoading(true);
// Remove existing model if any
if (ModelViewer.currentModel) {
removeCurrentModel();
}
// Initialize loader if not exists
if (!ModelViewer.loader) {
ModelViewer.loader = new THREE.GLTFLoader();
}
ModelViewer.isLoading = true;
// Load the model
ModelViewer.loader.load(
modelPath,
onModelLoaded,
onModelProgress,
onModelError
);
}
/**
* Callback when model loads successfully
* @param {Object} gltf - The loaded GLTF object
*/
function onModelLoaded(gltf) {
console.log('Model loaded successfully');
ModelViewer.currentModel = gltf.scene;
// Configure model properties
configureModel(ModelViewer.currentModel);
// Add to scene
ModelViewer.scene.add(ModelViewer.currentModel);
// Center and scale model appropriately
centerAndScaleModel(ModelViewer.currentModel);
// Setup annotations after model is loaded
setupAnnotations();
// Hide loading indicator
showLoading(false);
ModelViewer.isLoading = false;
console.log('Model setup complete');
}
/**
* Callback for model loading progress
* @param {ProgressEvent} progress - Loading progress event
*/
function onModelProgress(progress) {
if (progress.lengthComputable) {
const percentComplete = (progress.loaded / progress.total) * 100;
console.log(`Loading progress: ${Math.round(percentComplete)}%`);
const loadingElement = document.getElementById('loading');
loadingElement.textContent = `Loading: ${Math.round(percentComplete)}%`;
}
}
/**
* Callback when model loading fails
* @param {Error} error - The error that occurred
*/
function onModelError(error) {
console.error('Error loading model:', error);
showError('Failed to load 3D model. Please check the file path.');
showLoading(false);
ModelViewer.isLoading = false;
}
/**
* Configure model properties (materials, shadows, etc.)
* @param {Object} model - The loaded model object
*/
function configureModel(model) {
model.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
// Ensure materials are properly configured
if (child.material) {
child.material.needsUpdate = true;
}
}
});
}
/**
* Center and scale the model to fit nicely in the scene
* @param {Object} model - The model to center and scale
*/
function centerAndScaleModel(model) {
const box = new THREE.Box3().setFromObject(model);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
// Center the model
model.position.set(-32, 136, -39);
// Scale the model to fit in a reasonable size
const maxDimension = Math.max(size.x, size.y, size.z);
if (maxDimension > 0) {
const scale = 4 / maxDimension;
model.scale.setScalar(222);
}
console.log('Model centered and scaled');
}
/**
* Remove the current model from the scene
*/
function removeCurrentModel() {
if (ModelViewer.currentModel) {
ModelViewer.scene.remove(ModelViewer.currentModel);
// Dispose of geometries and materials to free memory
ModelViewer.currentModel.traverse((child) => {
if (child.isMesh) {
if (child.geometry) child.geometry.dispose();
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach(material => material.dispose());
} else {
child.material.dispose();
}
}
}
});
ModelViewer.currentModel = null;
console.log('Previous model removed and disposed');
}
}
/* ========================================
ANNOTATION SYSTEM FUNCTIONS
======================================== */
/**
* Setup annotation hotspots and tooltips
*/
function setupAnnotations() {
console.log('Setting up annotations...');
ModelViewer.annotations.forEach(annotation => {
const hotspot = document.getElementById(annotation.id);
const tooltip = document.getElementById(annotation.annotationId);
if (hotspot && tooltip) {
// Add event listeners for hotspot interactions
setupHotspotEvents(hotspot, tooltip);
}
});
console.log('Annotations configured');
}
/**
* Setup event listeners for a hotspot
* @param {HTMLElement} hotspot - The hotspot element
* @param {HTMLElement} tooltip - The associated tooltip element
*/
function setupHotspotEvents(hotspot, tooltip) {
hotspot.addEventListener('mouseenter', () => {
tooltip.style.display = 'block';
});
hotspot.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
hotspot.addEventListener('click', () => {
console.log(`Hotspot clicked: ${hotspot.id}`);
// You can add custom click behavior here
});
}
/**
* Update annotation positions based on 3D world positions
*/
function updateAnnotationPositions() {
ModelViewer.annotations.forEach(annotation => {
const hotspot = document.getElementById(annotation.id);
const tooltip = document.getElementById(annotation.annotationId);
if (hotspot && ModelViewer.currentModel) {
// Convert 3D world position to screen coordinates
const vector = new THREE.Vector3(
annotation.position.x,
annotation.position.y,
annotation.position.z
);
vector.project(ModelViewer.camera);
// Convert to screen pixels
const canvas = ModelViewer.renderer.domElement;
const x = (vector.x * 0.5 + 0.5) * canvas.clientWidth;
const y = (vector.y * -0.5 + 0.5) * canvas.clientHeight;
// Position the hotspot
hotspot.style.left = `${x - 10}px`;
hotspot.style.top = `${y - 10}px`;
// Position the tooltip near the hotspot
if (tooltip) {
tooltip.style.left = `${x - 100}px`;
tooltip.style.top = `${y - 40}px`;
}
// Hide hotspot if behind camera
hotspot.style.display = vector.z > 1 ? 'none' : 'block';
}
});
}
/* ========================================
USER INTERACTION FUNCTIONS
======================================== */
/**
* Reset camera to default position
*/
ModelViewer.resetCamera = function() {
console.log('Resetting camera position');
ModelViewer.camera.position.set(5, 3, 5);
ModelViewer.camera.lookAt(0, 0, 0);
ModelViewer.controls.reset();
};
/**
* Toggle wireframe mode on/off
*/
ModelViewer.toggleWireframe = function() {
console.log('Toggling wireframe mode');
if (ModelViewer.currentModel) {
ModelViewer.isWireframe = !ModelViewer.isWireframe;
ModelViewer.currentModel.traverse((child) => {
if (child.isMesh && child.material) {
child.material.wireframe = ModelViewer.isWireframe;
}
});
console.log(`Wireframe mode: ${ModelViewer.isWireframe ? 'ON' : 'OFF'}`);
}
};
/**
* Change to the next model in the array
*/
ModelViewer.changeModel = function() {
console.log('Changing model...');
ModelViewer.currentModelIndex = (ModelViewer.currentModelIndex + 1) % ModelViewer.modelPaths.length;
const newModelPath = ModelViewer.modelPaths[ModelViewer.currentModelIndex];
loadModel(newModelPath);
};
/* ========================================
EVENT LISTENERS AND UTILITY FUNCTIONS
======================================== */
/**
* Setup all event listeners
*/
function setupEventListeners() {
// Window resize handler
window.addEventListener('resize', onWindowResize);
// Keyboard shortcuts
window.addEventListener('keydown', onKeyDown);
console.log('Event listeners configured');
}
/**
* Handle window resize events
*/
function onWindowResize() {
const container = document.getElementById('canvas-container');
const width = container.clientWidth;
const height = container.clientHeight;
ModelViewer.camera.aspect = width / height;
ModelViewer.camera.updateProjectionMatrix();
ModelViewer.renderer.setSize(width, height);
console.log('Window resized, viewport updated');
}
/**
* Handle keyboard shortcuts
* @param {KeyboardEvent} event - The keyboard event
*/
function onKeyDown(event) {
switch(event.code) {
case 'KeyR':
ModelViewer.resetCamera();
break;
case 'KeyW':
ModelViewer.toggleWireframe();
break;
case 'KeyM':
ModelViewer.changeModel();
break;
default:
break;
}
}
/**
* Show/hide loading indicator
* @param {boolean} show - Whether to show the loading indicator
*/
function showLoading(show) {
const loading = document.getElementById('loading');
const error = document.getElementById('error');
loading.style.display = show ? 'block' : 'none';
error.style.display = 'none';
}
/**
* Show error message
* @param {string} message - Error message to display
*/
function showError(message) {
const loading = document.getElementById('loading');
const error = document.getElementById('error');
loading.style.display = 'none';
error.style.display = 'block';
error.querySelector('p').textContent = message;
}
/**
* Main render loop
*/
function startRenderLoop() {
function animate() {
requestAnimationFrame(animate);
// Update controls
if (ModelViewer.controls) {
ModelViewer.controls.update();
}
// Update annotation positions
updateAnnotationPositions();
// Render the scene
if (ModelViewer.renderer && ModelViewer.scene && ModelViewer.camera) {
ModelViewer.renderer.render(ModelViewer.scene, ModelViewer.camera);
}
}
animate();
console.log('Render loop started');
}
/* ========================================
INITIALIZATION - START THE APPLICATION
======================================== */
// Initialize when the page loads
window.addEventListener('load', initializeViewer);
// Expose ModelViewer to global scope for debugging
window.ModelViewer = ModelViewer;
console.log('3D Model Viewer script loaded');
</script>
</body>
</html>