File size: 17,251 Bytes
c5b97be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fd1402
33895bb
 
 
 
1423a30
 
a46b6d6
 
 
c5b97be
 
1423a30
 
 
 
 
 
 
 
557a969
1423a30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba66e71
1423a30
c5b97be
 
1423a30
 
 
119d33f
 
 
 
1423a30
119d33f
 
 
 
ba66e71
1423a30
 
 
ba66e71
 
 
119d33f
c5b97be
a46b6d6
1423a30
a961fe1
505e63f
a46b6d6
242cb42
 
 
119d33f
242cb42
e7d95af
a46b6d6
e7d95af
 
 
 
 
 
 
 
9b05583
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505e63f
a46b6d6
9b05583
242cb42
 
 
 
 
505e63f
242cb42
 
1423a30
 
242cb42
505e63f
a46b6d6
242cb42
 
505e63f
 
2d5adad
a46b6d6
505e63f
 
 
 
242cb42
505e63f
 
 
2d5adad
 
505e63f
dc7a9f3
a46b6d6
505e63f
 
c3a9a2d
 
505e63f
 
 
de91bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5b97be
9b05583
 
 
1423a30
9b05583
a46b6d6
de91bf7
 
 
a46b6d6
c3a9a2d
 
c5b97be
de91bf7
a46b6d6
c3a9a2d
 
 
2f7a63f
c3a9a2d
7fa0d2c
b8ed62c
c6beb8a
 
b8ed62c
c6beb8a
a961fe1
de91bf7
c5b97be
de91bf7
1423a30
a46b6d6
a961fe1
9b05583
 
 
 
 
a46b6d6
 
 
 
550e9af
9b05583
a46b6d6
 
c6beb8a
605bd0e
c6beb8a
1423a30
550e9af
a961fe1
c5b97be
 
 
1423a30
 
 
 
 
 
 
 
 
 
 
c5b97be
1423a30
 
 
 
 
 
 
 
 
 
 
 
 
9b05583
c5b97be
1423a30
 
 
 
 
 
9b05583
 
1423a30
 
9b05583
1423a30
 
 
 
 
 
 
 
 
 
c5b97be
9b05583
 
 
 
 
 
1423a30
 
 
 
 
 
9b05583
 
 
c5b97be
550e9af
 
 
 
 
 
1423a30
 
550e9af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5b97be
1423a30
 
 
 
550e9af
 
 
1423a30
 
 
550e9af
 
1423a30
 
 
 
550e9af
 
c5b97be
550e9af
 
 
 
c5b97be
1423a30
 
 
550e9af
1423a30
550e9af
 
 
 
 
1423a30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550e9af
 
 
c5b97be
550e9af
 
1423a30
 
550e9af
 
 
1423a30
 
550e9af
1423a30
 
 
 
 
 
 
 
 
 
 
 
 
 
c5b97be
2c24aec
1423a30
3c7f3fe
 
c5b97be
7097572
1423a30
 
 
 
 
 
 
c5b97be
1423a30
c5b97be
550e9af
 
 
 
 
 
 
 
 
 
 
a961fe1
550e9af
c5b97be
550e9af
1423a30
550e9af
 
 
c5b97be
5fd1402
 
 
c5b97be
550e9af
 
 
 
c5b97be
1423a30
 
a961fe1
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
(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;
  }

  // --- Outer scope variables for camera state ---
  let cameraInstance = null;
  let controlsInstance = null;
  let initialCameraPosition = null;
  let initialCameraRotation = null;
  // We'll save the imported SPLAT module here so we can reuse it later.
  let SPLAT = null;
  
  // 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) + "%";
    }
  }
  
  // Inject CSS styles into the document head, scoped with the unique id.
  const styleEl = document.createElement('style');
  styleEl.textContent = `
    /* Widget container styling */
    #ply-widget-container-${instanceId} {
      position: relative;
      width: 100%;
      height: 0;
      padding-bottom: ${aspectPercent};
    }
    /* When in fake fullscreen mode (iOS fallback) */
    #ply-widget-container-${instanceId}.fake-fullscreen {
      position: fixed !important;
      top: 0 !important;
      left: 0 !important;
      width: 100vw !important;
      height: 100vh !important;
      padding-bottom: 0 !important;
      z-index: 9999 !important;
    }
    /* GIF Preview styling */
    #gif-preview-container-${instanceId} {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      border: 1px solid #474558;
      border-radius: 10px;
      overflow: hidden;
      cursor: pointer;
    }
    #gif-preview-container-${instanceId} img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    /* Viewer Container styling */
    #viewer-container-${instanceId} {
      display: none;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: #FEFEFD;
      border: 1px solid #474558;
      border-radius: 10px;
      overflow: hidden;
      box-sizing: border-box;
    }
    /* Canvas fills the viewer container */
    #canvas-${instanceId} {
      width: 100%;
      height: 100%;
      display: block;
    }
    /* Progress dialog styling (as a centered div) */
    #progress-dialog-${instanceId} {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border: none;
      background: rgba(255,255,255,0.9);
      padding: 20px;
      border-radius: 5px;
      z-index: 1000;
      display: none;
    }
    /* Menu (instructions) content styling */
    #menu-content-${instanceId} {
      display: none;
      position: absolute;
      top: 70px;
      right: 15px;
      background: #FFFEF4;
      border: 1px solid #474558;
      border-radius: 5px;
      padding: 10px;
      font-size: 15px;
      line-height: 1.4;
      color: #474558;
    }
    /* Button styling */
    .widget-button {
      position: absolute;
      width: 45px;
      height: 45px;
      background-color: #FFFEF4;
      border: 1px solid #474558;
      border-radius: 50%;
      cursor: pointer;
      font-size: 14px;
      color: #474558;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    /* Positions: Close at top-left, fullscreen at top-right, help and reset buttons */
    #close-btn-${instanceId} {
      top: 17px;
      left: 15px;
      font-family: sans-serif;
    }
    #fullscreen-toggle-${instanceId} {
      top: 17px;
      right: 15px;
    }
    #help-toggle-${instanceId} {
      top: 17px;
      right: 70px;
      font-size: 22px;
    }
    #reset-camera-btn-${instanceId} {
      top: 17px;
      right: 123px;
      font-size: 22px;
      line-height: normal;
      padding: 0;
    }
    /* Adjust the reset icon position: move it slightly upward */
    .reset-icon {
      display: inline-block;
      transform: translateY(-3px);
    }
  `;
  document.head.appendChild(styleEl);
  
  // Create the widget container and set its inner HTML.
  const widgetContainer = document.createElement('div');
  widgetContainer.id = 'ply-widget-container-' + instanceId;
  widgetContainer.innerHTML = `
    <!-- GIF Preview Container -->
    <div id="gif-preview-container-${instanceId}">
      <img id="preview-image-${instanceId}" alt="Preview" crossorigin="anonymous">
    </div>
    <!-- Viewer Container -->
    <div id="viewer-container-${instanceId}">
      <canvas id="canvas-${instanceId}"></canvas>
      <div id="progress-dialog-${instanceId}">
        <progress id="progress-indicator-${instanceId}" max="100" value="0"></progress>
      </div>
      <button id="close-btn-${instanceId}" class="widget-button">X</button>
      <button id="fullscreen-toggle-${instanceId}" class="widget-button">⇱</button>
      <button id="help-toggle-${instanceId}" class="widget-button">?</button>
      <button id="reset-camera-btn-${instanceId}" class="widget-button">
        <span class="reset-icon">⟲</span>
      </button>
      <div id="menu-content-${instanceId}"></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;
  } else {
    gifPreview.style.display = 'none';
    viewerContainer.style.display = 'block';
    closeBtn.style.display = 'none';
    // Start the viewer immediately.
    initializeViewer();
  }
  
  // --- Button Event Handlers ---
  if (gifUrl) {
    gifPreview.addEventListener('click', function() {
      gifPreview.style.display = 'none';
      viewerContainer.style.display = 'block';
      initializeViewer();
    });
  }
  
  closeBtn.addEventListener('click', function() {
    if (document.fullscreenElement === widgetContainer) {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
    if (widgetContainer.classList.contains('fake-fullscreen')) {
      widgetContainer.classList.remove('fake-fullscreen');
      fullscreenToggle.textContent = '⇱';
      // For fake-fullscreen, reset camera immediately.
      resetCamera();
    }
    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');
        // Reset camera when exiting fake-fullscreen.
        resetCamera();
      }
      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.
  // Modified here: update the widget container styles so that in fullscreen
  // the aspect ratio style is removed (height = 100% and padding-bottom = 0) and
  // then reset the camera.
  document.addEventListener('fullscreenchange', function() {
    if (document.fullscreenElement === widgetContainer) {
      fullscreenToggle.textContent = '⇲';
      widgetContainer.style.height = '100%';
      widgetContainer.style.paddingBottom = '0';
      resetCamera();
    } else {
      fullscreenToggle.textContent = '⇱';
      // Restore the original aspect ratio style when not fullscreen.
      widgetContainer.style.height = '0';
      widgetContainer.style.paddingBottom = aspectPercent;
      resetCamera();
    }
  });
  
  helpToggle.addEventListener('click', function(e) {
    e.stopPropagation();
    menuContent.style.display = (menuContent.style.display === 'block') ? 'none' : 'block';
  });
  
  // --- Camera Reset Function ---
  function resetCamera() {
    console.log("Resetting camera to initial position.");
    if (cameraInstance && initialCameraPosition && initialCameraRotation) {
      // Reset camera position and rotation.
      cameraInstance.position = initialCameraPosition.clone();
      cameraInstance.rotation = initialCameraRotation.clone();
      if (typeof cameraInstance.update === 'function') {
        cameraInstance.update();
      }
      // Dispose of the current controls.
      if (controlsInstance && typeof controlsInstance.dispose === 'function') {
        controlsInstance.dispose();
      }
      // Re-create OrbitControls with the original chosen parameters.
      controlsInstance = new SPLAT.OrbitControls(
        cameraInstance,
        canvas,
        0.5,  // default alpha fallback
        0.5,  // default beta fallback
        5,    // default radius fallback
        true,
        new SPLAT.Vector3(),
        chosenInitAlpha,
        chosenInitBeta,
        chosenInitRadius
      );
      controlsInstance.maxZoom = maxZoom;
      controlsInstance.minZoom = minZoom;
      controlsInstance.minAngle = minAngle;
      controlsInstance.maxAngle = maxAngle;
      controlsInstance.minAzimuth = minAzimuth;
      controlsInstance.maxAzimuth = maxAzimuth;
      controlsInstance.panSpeed = isMobile ? 0.5 : 1.2;
      controlsInstance.update();
    }
  }
  
  // Modified reset button now calls the resetCamera function.
  resetCameraBtn.addEventListener('click', async function() {
    console.log("Reset camera button clicked.");
    resetCamera();
  });
  
  // --- Add keydown listener to exit fullscreen with Esc (or Echap) ---
  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 = '⇱';
      }
      if (wasFullscreen) {
        resetCamera();
      }
    }
  });
  
  // --- Initialize the 3D PLY Viewer ---
  async function initializeViewer() {
    // Import SPLAT and store it globally.
    SPLAT = await import("https://bilca-gsplat-library.static.hf.space/dist/index.js");
    progressDialog.style.display = 'block';
    const renderer = new SPLAT.WebGLRenderer(canvas);
    const scene = new SPLAT.Scene();

    // Construct the camera.
    const camera = new SPLAT.Camera();
    
    // Construct OrbitControls with the chosen initial orbit parameters.
    controlsInstance = new SPLAT.OrbitControls(
      camera,
      canvas,
      0.5, // default alpha fallback
      0.5, // default beta fallback
      5,   // default radius fallback
      true,
      new SPLAT.Vector3(),
      chosenInitAlpha,
      chosenInitBeta,
      chosenInitRadius
    );
  
    cameraInstance = camera;
    // Save the initial camera state (after controls are created)
    initialCameraPosition = camera.position.clone();
    initialCameraRotation = camera.rotation.clone();
  
    canvas.style.background = "#FEFEFE";
    controlsInstance.maxZoom = maxZoom;
    controlsInstance.minZoom = minZoom;
    controlsInstance.minAngle = minAngle;
    controlsInstance.maxAngle = maxAngle;
    controlsInstance.minAzimuth = minAzimuth;
    controlsInstance.maxAzimuth = maxAzimuth;
    controlsInstance.panSpeed = isMobile ? 0.5 : 1.2;
  
    controlsInstance.update();
  
    try {
      await SPLAT.PLYLoader.LoadAsync(
        plyUrl,
        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>`;
    }
  
    const frame = () => {
      controlsInstance.update();
      renderer.render(scene, camera);
      requestAnimationFrame(frame);
    };
  
    const handleResize = () => {
      renderer.setSize(canvas.clientWidth, canvas.clientHeight);
    };
  
    handleResize();
    window.addEventListener("resize", handleResize);
    requestAnimationFrame(frame);
  }
  
  // If a gif_url exists, the viewer is started on preview click;
  // otherwise, it was already started above.
})();