File size: 19,034 Bytes
23c6996
85f79d1
 
23c6996
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695a588
 
 
 
 
 
 
 
85f79d1
 
 
23c6996
 
 
 
 
 
 
85f79d1
23c6996
85f79d1
 
 
 
 
 
 
 
 
 
 
 
 
23c6996
 
 
 
 
 
85f79d1
 
 
 
23c6996
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695a588
23c6996
 
 
009cc67
 
 
 
dd01638
 
 
 
23c6996
 
 
 
 
 
7f3416a
23c6996
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f79d1
 
 
23c6996
 
bae1b70
7f3416a
23c6996
 
 
 
85f79d1
7f3416a
85f79d1
7f3416a
23c6996
 
 
 
 
7f3416a
23c6996
 
85f79d1
23c6996
 
 
 
7f3416a
 
aed8983
23c6996
 
 
 
 
 
 
 
 
aed8983
85f79d1
 
aed8983
85f79d1
23c6996
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd01638
23c6996
 
 
dd01638
 
23c6996
 
dd01638
 
23c6996
 
 
 
 
 
 
 
f8672d0
85f79d1
 
 
 
23c6996
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f79d1
 
 
 
 
bae1b70
 
aed8983
bae1b70
23c6996
7f3416a
695a588
23c6996
85f79d1
 
 
 
bae1b70
85f79d1
 
 
 
 
 
 
 
 
 
 
f8672d0
85f79d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8672d0
85f79d1
 
 
 
 
f8672d0
85f79d1
 
 
 
59f3654
85f79d1
59f3654
85f79d1
 
 
 
 
 
 
 
 
 
 
 
 
59f3654
85f79d1
 
 
 
 
59f3654
85f79d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8672d0
85f79d1
 
 
 
 
 
f8672d0
85f79d1
aed8983
85f79d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8672d0
23c6996
85f79d1
 
 
 
 
 
 
 
 
 
 
23c6996
85f79d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23c6996
f8672d0
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
(async function() {
  // Retrieve the current script tag and load the JSON configuration file from the data-config attribute.
  const scriptTag = document.currentScript;
  const configUrl = scriptTag.getAttribute("data-config");
  let config = {};
  if (configUrl) {
    try {
      const response = await fetch(configUrl);
      config = await response.json();
    } catch (error) {
      console.error("Error loading config file:", error);
      return;
    }
  } else {
    console.error("No config file provided. Please set a data-config attribute on the script tag.");
    return;
  }

  // Load the external CSS file if provided in the config.
  if (config.css_url) {
    const linkEl = document.createElement("link");
    linkEl.rel = "stylesheet";
    linkEl.href = config.css_url;
    document.head.appendChild(linkEl);
  }

  // --- Outer scope variables for viewer state ---
  let SPLAT = null;
  let viewerActive = false;
  
  // Generate a unique identifier for this widget instance.
  const instanceId = Math.random().toString(36).substr(2, 8);
  
  // Read configuration values from the JSON file.
  const gifUrl = config.gif_url;
  const plyUrl = config.ply_url;
  const minZoom = parseFloat(config.minZoom || "0");
  const maxZoom = parseFloat(config.maxZoom || "20");
  const minAngle = parseFloat(config.minAngle || "0");
  const maxAngle = parseFloat(config.maxAngle || "360");
  const minAzimuth = config.minAzimuth !== undefined ? parseFloat(config.minAzimuth) : -Infinity;
  const maxAzimuth = config.maxAzimuth !== undefined ? parseFloat(config.maxAzimuth) : Infinity;
  
  // Read initial orbit parameters for desktop.
  const initAlphaDesktop = config.initAlpha !== undefined ? parseFloat(config.initAlpha) : 0.5;
  const initBetaDesktop  = config.initBeta  !== undefined ? parseFloat(config.initBeta)  : 0.5;
  const initRadiusDesktop = config.initRadius !== undefined ? parseFloat(config.initRadius) : 5;
  // Read initial orbit parameters for phone.
  const initAlphaPhone = config.initAlphaPhone !== undefined ? parseFloat(config.initAlphaPhone) : initAlphaDesktop;
  const initBetaPhone  = config.initBetaPhone  !== undefined ? parseFloat(config.initBetaPhone)  : initBetaDesktop;
  const initRadiusPhone = config.initRadiusPhone !== undefined ? parseFloat(config.initRadiusPhone) : initRadiusDesktop;

  // Detect if the device is iOS.
  const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  // Also detect Android devices.
  const isMobile = isIOS || /Android/i.test(navigator.userAgent);
  
  // Choose the appropriate initial orbit values based on device type.
  const chosenInitAlpha = isMobile ? initAlphaPhone : initAlphaDesktop;
  const chosenInitBeta  = isMobile ? initBetaPhone  : initBetaDesktop;
  const chosenInitRadius = isMobile ? initRadiusPhone : initRadiusDesktop;
  
  // Determine the aspect ratio.
  let aspectPercent = "100%";
  if (config.aspect) {
    if (config.aspect.indexOf(":") !== -1) {
      const parts = config.aspect.split(":");
      const w = parseFloat(parts[0]);
      const h = parseFloat(parts[1]);
      if (!isNaN(w) && !isNaN(h) && w > 0) {
        aspectPercent = (h / w * 100) + "%";
      }
    } else {
      const aspectValue = parseFloat(config.aspect);
      if (!isNaN(aspectValue) && aspectValue > 0) {
        aspectPercent = (100 / aspectValue) + "%";
      }
    }
  } else {
    const parentContainer = scriptTag.parentNode;
    const containerWidth = parentContainer.offsetWidth;
    const containerHeight = parentContainer.offsetHeight;
    if (containerWidth > 0 && containerHeight > 0) {
      aspectPercent = (containerHeight / containerWidth * 100) + "%";
    }
  }
  
  // Create the widget container.
  const widgetContainer = document.createElement('div');
  widgetContainer.id = 'ply-widget-container-' + instanceId;
  widgetContainer.classList.add('ply-widget-container');
  // Add a mobile class if on a phone.
  if (isMobile) {
    widgetContainer.classList.add('mobile');
  }
  // Set inline style for aspect ratio.
  widgetContainer.style.height = "0";
  widgetContainer.style.paddingBottom = aspectPercent;

  widgetContainer.innerHTML = `
    <!-- GIF Preview Container -->
    <div id="gif-preview-container-${instanceId}" class="gif-preview-container">
      <img id="preview-image-${instanceId}" alt="Preview" crossorigin="anonymous">
    </div>
    <!-- Viewer Container -->
    <div id="viewer-container-${instanceId}" class="viewer-container" style="display: none;">
      <canvas id="canvas-${instanceId}" class="ply-canvas"></canvas>
      <div id="progress-dialog-${instanceId}" class="progress-dialog">
        <progress id="progress-indicator-${instanceId}" max="100" value="0"></progress>
      </div>
      <button id="close-btn-${instanceId}" class="widget-button close-btn">X</button>
      <button id="fullscreen-toggle-${instanceId}" class="widget-button fullscreen-toggle">⇱</button>
      <button id="help-toggle-${instanceId}" class="widget-button help-toggle">?</button>
      <button id="reset-camera-btn-${instanceId}" class="widget-button reset-camera-btn">
        <span class="reset-icon">⟲</span>
      </button>
      <div id="menu-content-${instanceId}" class="menu-content"></div>
    </div>
  `;
  scriptTag.parentNode.appendChild(widgetContainer);
  
  // Grab element references.
  const gifPreview = document.getElementById('gif-preview-container-' + instanceId);
  const viewerContainer = document.getElementById('viewer-container-' + instanceId);
  const previewImage = document.getElementById('preview-image-' + instanceId);
  const closeBtn = document.getElementById('close-btn-' + instanceId);
  const fullscreenToggle = document.getElementById('fullscreen-toggle-' + instanceId);
  const helpToggle = document.getElementById('help-toggle-' + instanceId);
  const resetCameraBtn = document.getElementById('reset-camera-btn-' + instanceId);
  const menuContent = document.getElementById('menu-content-' + instanceId);
  const canvas = document.getElementById('canvas-' + instanceId);
  const progressDialog = document.getElementById('progress-dialog-' + instanceId);
  const progressIndicator = document.getElementById('progress-indicator-' + instanceId);
  
  // Set help instructions based on device type.
  if (isMobile) {
    menuContent.innerHTML = `
      - Pour vous déplacer, glissez deux doigts sur l'écran.<br>
      - Pour orbiter, utilisez un doigt.<br>
      - Pour zoomer, pincez avec deux doigts.
    `;
  } else {
    menuContent.innerHTML = `
      - orbitez avec le clic droit<br>
      - zoomez avec la molette<br>
      - déplacez vous avec le clic gauche
    `;
  }
  
  // If a gif_url is provided, set the preview image.
  // Otherwise, hide the preview container, show the viewer immediately,
  // and hide the "close" button since there's no preview to return to.
  if (gifUrl) {
    previewImage.src = gifUrl;
    gifPreview.style.display = 'block';
    viewerContainer.style.display = 'none';
  } else {
    gifPreview.style.display = 'none';
    viewerContainer.style.display = 'block';
    closeBtn.style.display = 'none';
    // Need to load the PLY without a GIF preview
    setTimeout(() => {
      loadAndStartViewer();
    }, 100);
  }
  
  // --- Button Event Handlers ---
  if (gifUrl) {
    gifPreview.addEventListener('click', function() {
      console.log("GIF preview clicked, showing 3D viewer");
      gifPreview.style.display = 'none';
      viewerContainer.style.display = 'block';
      loadAndStartViewer();
    });
  }
  
  closeBtn.addEventListener('click', function() {
    console.log("Close button clicked");
    
    // Handle fullscreen exit
    if (document.fullscreenElement === widgetContainer) {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
    if (widgetContainer.classList.contains('fake-fullscreen')) {
      widgetContainer.classList.remove('fake-fullscreen');
      fullscreenToggle.textContent = '⇱';
    }
    
    // Stop the viewer
    stopViewer();
    
    // Show GIF and hide viewer
    viewerContainer.style.display = 'none';
    gifPreview.style.display = 'block';
  });
  
  fullscreenToggle.addEventListener('click', function() {
    if (isIOS) {
      if (!widgetContainer.classList.contains('fake-fullscreen')) {
        widgetContainer.classList.add('fake-fullscreen');
      } else {
        widgetContainer.classList.remove('fake-fullscreen');
      }
      fullscreenToggle.textContent = widgetContainer.classList.contains('fake-fullscreen') ? '⇲' : '⇱';
    } else {
      if (!document.fullscreenElement) {
        if (widgetContainer.requestFullscreen) {
          widgetContainer.requestFullscreen();
        } else if (widgetContainer.webkitRequestFullscreen) {
          widgetContainer.webkitRequestFullscreen();
        } else if (widgetContainer.mozRequestFullScreen) {
          widgetContainer.mozRequestFullScreen();
        } else if (widgetContainer.msRequestFullscreen) {
          widgetContainer.msRequestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        }
      }
    }
  });
  
  // Listen for native fullscreen changes.
  document.addEventListener('fullscreenchange', function() {
    if (document.fullscreenElement === widgetContainer) {
      fullscreenToggle.textContent = '⇲';
      widgetContainer.style.height = '100%';
      widgetContainer.style.paddingBottom = '0';
    } else {
      fullscreenToggle.textContent = '⇱';
      widgetContainer.style.height = '0';
      widgetContainer.style.paddingBottom = aspectPercent;
    }
  });
  
  helpToggle.addEventListener('click', function(e) {
    e.stopPropagation();
    menuContent.style.display = (menuContent.style.display === 'block') ? 'none' : 'block';
  });
  
  resetCameraBtn.addEventListener('click', function() {
    console.log("Reset camera button clicked.");
    if (window.viewer && typeof window.viewer.resetCamera === 'function') {
      window.viewer.resetCamera();
    }
  });
  
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' || e.key === 'Esc') {
      let wasFullscreen = false;
      if (document.fullscreenElement === widgetContainer) {
        wasFullscreen = true;
        if (document.exitFullscreen) {
          document.exitFullscreen();
        }
      }
      if (widgetContainer.classList.contains('fake-fullscreen')) {
        wasFullscreen = true;
        widgetContainer.classList.remove('fake-fullscreen');
        fullscreenToggle.textContent = '⇱';
      }
    }
  });
  
  // --- Load SPLAT Library and Initialize the 3D PLY Viewer ---
  async function loadAndStartViewer() {
    // Don't reinitialize if already active
    if (viewerActive) {
      console.log("Viewer already active, skipping initialization");
      return;
    }
    
    console.log("Initializing PLY viewer...");
    progressDialog.style.display = 'block';
    progressIndicator.value = 0;
    
    try {
      // Only load the SPLAT library once
      if (!SPLAT) {
        SPLAT = await import("https://bilca-gsplat-library.static.hf.space/dist/index.js");
      }
      
      // Create a fresh viewer instance
      window.viewer = {
        // Properties
        renderer: null,
        scene: null,
        camera: null,
        controls: null,
        animFrameId: null,
        resizeObserver: null,
        initialCameraPosition: null,
        initialCameraRotation: null,
        
        // Initialize the viewer
        async init() {
          // Create renderer and scene
          this.renderer = new SPLAT.WebGLRenderer(canvas);
          this.scene = new SPLAT.Scene();
          
          // Create camera
          this.camera = new SPLAT.Camera();
          
          // Store initial camera state
          this.initialCameraPosition = this.camera.position.clone();
          this.initialCameraRotation = this.camera.rotation.clone();
          
          // Create controls
          this.controls = new SPLAT.OrbitControls(
            this.camera,
            canvas,
            0.5,
            0.5,
            5,
            true,
            new SPLAT.Vector3(),
            chosenInitAlpha,
            chosenInitBeta,
            chosenInitRadius
          );
          
          // Set control constraints
          this.controls.maxZoom = maxZoom;
          this.controls.minZoom = minZoom;
          this.controls.minAngle = minAngle;
          this.controls.maxAngle = maxAngle;
          this.controls.minAzimuth = minAzimuth;
          this.controls.maxAzimuth = maxAzimuth;
          this.controls.panSpeed = isMobile ? 0.5 : 1.2;
          
          // Set canvas background
          canvas.style.background = config.canvas_background || "#FEFEFD";
          
          // Handle resize
          this.handleResize();
          
          // Set up resize observer
          this.resizeObserver = new ResizeObserver(() => {
            this.handleResize();
          });
          this.resizeObserver.observe(canvas);
          
          // Update controls
          this.controls.update();
          
          // Load the PLY file
          try {
            await SPLAT.PLYLoader.LoadAsync(
              plyUrl,
              this.scene,
              (progress) => {
                progressIndicator.value = progress * 100;
              }
            );
            progressDialog.style.display = 'none';
          } catch (error) {
            console.error("Error loading PLY file:", error);
            progressDialog.innerHTML = `<p style="color: red">Error loading model: ${error.message}</p>`;
            return false;
          }
          
          // Start rendering
          this.startRenderLoop();
          return true;
        },
        
        // Handle resize
        handleResize() {
          if (this.renderer) {
            this.renderer.setSize(canvas.clientWidth, canvas.clientHeight);
          }
        },
        
        // Start the render loop
        startRenderLoop() {
          // Animation frame loop
          const renderFrame = () => {
            if (this.controls && this.scene && this.camera && this.renderer) {
              this.controls.update();
              this.renderer.render(this.scene, this.camera);
              this.animFrameId = requestAnimationFrame(renderFrame);
            }
          };
          
          this.animFrameId = requestAnimationFrame(renderFrame);
        },
        
        // Reset camera to initial position
        resetCamera() {
          if (!this.camera || !this.initialCameraPosition || !this.initialCameraRotation) {
            console.log("Cannot reset camera - missing camera instance or initial positions");
            return;
          }
          
          try {
            // Dispose previous controls if they exist
            if (this.controls && typeof this.controls.dispose === 'function') {
              this.controls.dispose();
            }
            
            // Set camera back to initial position
            this.camera.position = this.initialCameraPosition.clone();
            this.camera.rotation = this.initialCameraRotation.clone();
            
            // Create new controls
            this.controls = new SPLAT.OrbitControls(
              this.camera,
              canvas,
              0.5,
              0.5,
              5,
              true,
              new SPLAT.Vector3(),
              chosenInitAlpha,
              chosenInitBeta,
              chosenInitRadius
            );
            
            // Set control constraints
            this.controls.maxZoom = maxZoom;
            this.controls.minZoom = minZoom;
            this.controls.minAngle = minAngle;
            this.controls.maxAngle = maxAngle;
            this.controls.minAzimuth = minAzimuth;
            this.controls.maxAzimuth = maxAzimuth;
            this.controls.panSpeed = isMobile ? 0.5 : 1.2;
            
            // Update controls
            this.controls.update();
            
            console.log("Camera reset successful");
          } catch (error) {
            console.error("Error resetting camera:", error);
          }
        },
        
        // Clean up resources
        dispose() {
          // Cancel animation frame
          if (this.animFrameId) {
            cancelAnimationFrame(this.animFrameId);
            this.animFrameId = null;
          }
          
          // Remove resize observer
          if (this.resizeObserver) {
            this.resizeObserver.disconnect();
            this.resizeObserver = null;
          }
          
          // Dispose controls
          if (this.controls && typeof this.controls.dispose === 'function') {
            try {
              this.controls.dispose();
            } catch (e) {
              console.warn("Error disposing controls:", e);
            }
            this.controls = null;
          }
          
          // Dispose renderer
          if (this.renderer && typeof this.renderer.dispose === 'function') {
            try {
              this.renderer.dispose();
            } catch (e) {
              console.warn("Error disposing renderer:", e);
            }
            this.renderer = null;
          }
          
          // Clear scene
          if (this.scene) {
            this.scene = null;
          }
          
          // Clear camera
          this.camera = null;
          this.initialCameraPosition = null;
          this.initialCameraRotation = null;
          
          console.log("Viewer resources disposed");
        }
      };
      
      // Initialize the viewer
      const success = await window.viewer.init();
      if (success) {
        viewerActive = true;
        console.log("PLY viewer started successfully");
      } else {
        viewerActive = false;
        console.error("Failed to initialize PLY viewer");
      }
      
    } catch (error) {
      console.error("Error in loadAndStartViewer:", error);
      progressDialog.innerHTML = `<p style="color: red">Error initializing viewer: ${error.message}</p>`;
      viewerActive = false;
    }
  }
  
  // Stop the viewer and clean up resources
  function stopViewer() {
    if (!viewerActive) {
      console.log("Viewer not active, nothing to stop");
      return;
    }
    
    console.log("Stopping viewer...");
    
    // Dispose viewer resources
    if (window.viewer && typeof window.viewer.dispose === 'function') {
      window.viewer.dispose();
    }
    
    // Reset WebGL context if possible
    if (canvas) {
      const ctx = canvas.getContext('webgl') || canvas.getContext('webgl2');
      if (ctx && ctx.getExtension('WEBGL_lose_context')) {
        try {
          ctx.getExtension('WEBGL_lose_context').loseContext();
        } catch (e) {
          console.warn("Error releasing WebGL context:", e);
        }
      }
    }
    
    // Mark viewer as not active
    viewerActive = false;
    
    console.log("Viewer stopped");
  }
})();