File size: 19,872 Bytes
365ca90
 
 
004a743
 
 
 
1488910
61ccdd8
902940d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2af0591
61ccdd8
1488910
902940d
ebc809d
902940d
ebc809d
 
 
 
 
 
dea4690
 
004a743
dea4690
 
 
 
902940d
 
 
 
dea4690
 
004a743
dea4690
 
 
 
004a743
6063278
902940d
 
 
 
6063278
 
004a743
 
 
 
 
 
 
 
 
 
 
 
 
a2e7f03
004a743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9c169f
c7c8c1d
e8b4797
 
c7c8c1d
8c64c02
1488910
c7c8c1d
004a743
caacb2c
004a743
caacb2c
670d350
e7ca7b5
3c3ddba
dea4690
1488910
 
 
 
 
 
004a743
 
 
902940d
004a743
 
902940d
004a743
 
902940d
004a743
1488910
e7ca7b5
902940d
004a743
 
 
 
902940d
004a743
 
 
 
902940d
004a743
 
8feb783
 
004a743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1488910
 
 
 
 
 
 
 
 
 
 
004a743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
902940d
 
004a743
902940d
004a743
902940d
004a743
 
 
 
 
902940d
004a743
 
 
 
 
 
 
1488910
 
 
004a743
 
 
 
 
1488910
004a743
 
 
 
 
 
 
 
 
1488910
004a743
 
 
 
 
 
1488910
004a743
1488910
 
 
 
 
004a743
 
 
1488910
 
 
 
 
 
004a743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
902940d
1488910
 
 
 
004a743
1488910
 
 
 
 
004a743
1488910
004a743
 
1488910
 
 
 
 
 
9279634
1488910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
902940d
1488910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
902940d
1488910
 
 
 
459cefb
1488910
 
 
 
 
 
32fe69b
004a743
1488910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
004a743
1488910
 
 
 
 
004a743
1488910
 
 
 
902940d
1488910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
004a743
1488910
902940d
1488910
902940d
1488910
b6a8b79
902940d
004a743
 
 
902940d
004a743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// viewer.js
// ==============================

/* -------------------------------------------
   Utils
-------------------------------------------- */

// (Conservé pour compat, même si .sog n'en a pas besoin)
async function loadImageAsTexture(url, app) {
  return new Promise((resolve, reject) => {
    const img = new window.Image();
    img.crossOrigin = "anonymous";
    img.onload = function () {
      const tex = new pc.Texture(app.graphicsDevice, {
        width: img.width,
        height: img.height,
        format: pc.PIXELFORMAT_R8_G8_B8_A8
      });
      tex.setSource(img);
      resolve(tex);
    };
    img.onerror = reject;
    img.src = url;
  });
}

// Patch global Image -> force CORS
(function () {
  const OriginalImage = window.Image;
  window.Image = function (...args) {
    const img = new OriginalImage(...args);
    img.crossOrigin = "anonymous";
    return img;
  };
})();

function hexToRgbaArray(hex) {
  try {
    hex = String(hex || "").replace("#", "");
    if (hex.length === 6) hex += "FF";
    if (hex.length !== 8) return [1, 1, 1, 1];
    const num = parseInt(hex, 16);
    return [
      ((num >> 24) & 0xff) / 255,
      ((num >> 16) & 0xff) / 255,
      ((num >> 8) & 0xff) / 255,
      (num & 0xff) / 255
    ];
  } catch (e) {
    console.warn("hexToRgbaArray error:", e);
    return [1, 1, 1, 1];
  }
}

// Parcours récursif d'une hiérarchie d'entités
function traverse(entity, callback) {
  callback(entity);
  if (entity.children) {
    entity.children.forEach((child) => traverse(child, callback));
  }
}

/* -------------------------------------------
   Chargement unique de orbit-camera.js
-------------------------------------------- */

async function ensureOrbitScriptsLoaded() {
  if (window.__PLY_ORBIT_LOADED__) return;
  if (window.__PLY_ORBIT_LOADING__) {
    await window.__PLY_ORBIT_LOADING__;
    return;
  }

  window.__PLY_ORBIT_LOADING__ = new Promise((resolve, reject) => {
    const s = document.createElement("script");
    s.src = "https://mikafil-viewer-sgos.static.hf.space/orbit-camera.js";
    s.async = true;
    s.onload = () => {
      window.__PLY_ORBIT_LOADED__ = true;
      resolve();
    };
    s.onerror = (e) => {
      console.error("[viewer.js] Failed to load orbit-camera.js", e);
      reject(e);
    };
    document.head.appendChild(s);
  });

  await window.__PLY_ORBIT_LOADING__;
}

/* -------------------------------------------
   State (par module = par instance importée)
-------------------------------------------- */

let pc;
export let app = null;
let cameraEntity = null;
let modelEntity = null;
let viewerInitialized = false;
let resizeObserver = null;
let resizeTimeout = null;

// paramètres courants de l'instance
let chosenCameraX, chosenCameraY, chosenCameraZ;
let minZoom, maxZoom, minAngle, maxAngle, minAzimuth, maxAzimuth, minY;
let modelX, modelY, modelZ, modelScale, modelRotationX, modelRotationY, modelRotationZ;
let presentoirScaleX, presentoirScaleY, presentoirScaleZ;
let sogUrl, glbUrl, presentoirUrl;
let color_bg_hex, color_bg, espace_expo_bool;

// perf dynamique
let maxDevicePixelRatio = 1.75;   // plafond par défaut (configurable)
let interactDpr = 1.0;            // DPR pendant interaction
let idleRestoreDelay = 350;       // ms avant de restaurer le DPR
let idleTimer = null;

/* -------------------------------------------
   Initialisation
-------------------------------------------- */

export async function initializeViewer(config, instanceId) {
  if (viewerInitialized) return;

  const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
  const isMobile = isIOS || /Android/i.test(navigator.userAgent);

  // --- Configuration ---
  // Nouveau format .sog (et compat si seul sogs_json_url est présent)
  sogUrl = config.sog_url || config.sogs_json_url;

  glbUrl =
    config.glb_url !== undefined
      ? config.glb_url
      : "https://huggingface.co/datasets/MikaFil/viewer_gs/resolve/main/ressources/espace_expo/sol_blanc_2.glb";

  presentoirUrl =
    config.presentoir_url !== undefined
      ? config.presentoir_url
      : "https://huggingface.co/datasets/MikaFil/viewer_gs/resolve/main/ressources/espace_expo/sol_blanc_2.glb";

  minZoom = parseFloat(config.minZoom || "1");
  maxZoom = parseFloat(config.maxZoom || "20");
  minAngle = parseFloat(config.minAngle || "-2000");
  maxAngle = parseFloat(config.maxAngle || "2000");
  minAzimuth = config.minAzimuth !== undefined ? parseFloat(config.minAzimuth) : -360;
  maxAzimuth = config.maxAzimuth !== undefined ? parseFloat(config.maxAzimuth) : 360;
  minY = config.minY !== undefined ? parseFloat(config.minY) : 0;

  modelX = config.modelX !== undefined ? parseFloat(config.modelX) : 0;
  modelY = config.modelY !== undefined ? parseFloat(config.modelY) : 0;
  modelZ = config.modelZ !== undefined ? parseFloat(config.modelZ) : 0;
  modelScale = config.modelScale !== undefined ? parseFloat(config.modelScale) : 1;
  modelRotationX = config.modelRotationX !== undefined ? parseFloat(config.modelRotationX) : 0;
  modelRotationY = config.modelRotationY !== undefined ? parseFloat(config.modelRotationY) : 0;
  modelRotationZ = config.modelRotationZ !== undefined ? parseFloat(config.modelRotationZ) : 0;

  presentoirScaleX = config.presentoirScaleX !== undefined ? parseFloat(config.presentoirScaleX) : 0;
  presentoirScaleY = config.presentoirScaleY !== undefined ? parseFloat(config.presentoirScaleY) : 0;
  presentoirScaleZ = config.presentoirScaleZ !== undefined ? parseFloat(config.presentoirScaleZ) : 0;

  const cameraX = config.cameraX !== undefined ? parseFloat(config.cameraX) : 0;
  const cameraY = config.cameraY !== undefined ? parseFloat(config.cameraY) : 2;
  const cameraZ = config.cameraZ !== undefined ? parseFloat(config.cameraZ) : 5;

  const cameraXPhone = config.cameraXPhone !== undefined ? parseFloat(config.cameraXPhone) : cameraX;
  const cameraYPhone = config.cameraYPhone !== undefined ? parseFloat(config.cameraYPhone) : cameraY;
  const cameraZPhone = config.cameraZPhone !== undefined ? parseFloat(config.cameraZPhone) : cameraZ * 1.5;

  color_bg_hex = config.canvas_background !== undefined ? config.canvas_background : "#FFFFFF";
  espace_expo_bool = config.espace_expo_bool !== undefined ? config.espace_expo_bool : false;
  color_bg = hexToRgbaArray(color_bg_hex);

  chosenCameraX = isMobile ? cameraXPhone : cameraX;
  chosenCameraY = isMobile ? cameraYPhone : cameraY;
  chosenCameraZ = isMobile ? cameraZPhone : cameraZ;

  // Options perf configurables
  if (config.maxDevicePixelRatio !== undefined) {
    maxDevicePixelRatio = Math.max(0.75, parseFloat(config.maxDevicePixelRatio) || maxDevicePixelRatio);
  }
  if (config.interactionPixelRatio !== undefined) {
    interactDpr = Math.max(0.75, parseFloat(config.interactionPixelRatio) || interactDpr);
  }
  if (config.idleRestoreDelayMs !== undefined) {
    idleRestoreDelay = Math.max(120, parseInt(config.idleRestoreDelayMs, 10) || idleRestoreDelay);
  }

  // --- Prépare le canvas unique à cette instance ---
  const canvasId = "canvas-" + instanceId;
  const progressDialog = document.getElementById("progress-dialog-" + instanceId);
  const viewerContainer = document.getElementById("viewer-container-" + instanceId);

  const old = document.getElementById(canvasId);
  if (old) old.remove();

  const canvas = document.createElement("canvas");
  canvas.id = canvasId;
  canvas.className = "ply-canvas";
  canvas.style.width = "100%";
  canvas.style.height = "100%";
  canvas.setAttribute("tabindex", "0");
  viewerContainer.insertBefore(canvas, progressDialog);

  // interactions de base
  canvas.style.touchAction = "none";
  canvas.style.webkitTouchCallout = "none";
  canvas.addEventListener("gesturestart", (e) => e.preventDefault());
  canvas.addEventListener("gesturechange", (e) => e.preventDefault());
  canvas.addEventListener("gestureend", (e) => e.preventDefault());
  canvas.addEventListener("dblclick", (e) => e.preventDefault());
  canvas.addEventListener(
    "touchstart",
    (e) => {
      if (e.touches.length > 1) e.preventDefault();
    },
    { passive: false }
  );
  canvas.addEventListener(
    "wheel",
    (e) => {
      e.preventDefault();
    },
    { passive: false }
  );

  // Bloque le scroll page uniquement quand le pointeur est sur le canvas
  const scrollKeys = new Set([
    "ArrowUp",
    "ArrowDown",
    "ArrowLeft",
    "ArrowRight",
    "PageUp",
    "PageDown",
    "Home",
    "End",
    " ",
    "Space",
    "Spacebar"
  ]);
  let isPointerOverCanvas = false;
  const focusCanvas = () => canvas.focus({ preventScroll: true });

  const onPointerEnter = () => {
    isPointerOverCanvas = true;
    focusCanvas();
  };
  const onPointerLeave = () => {
    isPointerOverCanvas = false;
    if (document.activeElement === canvas) canvas.blur();
  };
  const onCanvasBlur = () => {
    isPointerOverCanvas = false;
  };

  canvas.addEventListener("pointerenter", onPointerEnter);
  canvas.addEventListener("pointerleave", onPointerLeave);
  canvas.addEventListener("mouseenter", onPointerEnter);
  canvas.addEventListener("mouseleave", onPointerLeave);
  canvas.addEventListener("mousedown", focusCanvas);
  canvas.addEventListener(
    "touchstart",
    () => {
      focusCanvas();
    },
    { passive: false }
  );
  canvas.addEventListener("blur", onCanvasBlur);

  const onKeyDownCapture = (e) => {
    if (!isPointerOverCanvas) return;
    if (scrollKeys.has(e.key) || scrollKeys.has(e.code)) {
      e.preventDefault();
    }
  };
  window.addEventListener("keydown", onKeyDownCapture, true);

  progressDialog.style.display = "block";

  // --- Charge PlayCanvas lib ESM (une par module/instance) ---
  if (!pc) {
    pc = await import("https://esm.run/playcanvas");
    window.pc = pc; // utiles pour tooltips.js
  }

  // --- Crée l'Application ---
  const device = await pc.createGraphicsDevice(canvas, {
    deviceTypes: ["webgl2"],
    glslangUrl: "https://playcanvas.vercel.app/static/lib/glslang/glslang.js",
    twgslUrl: "https://playcanvas.vercel.app/static/lib/twgsl/twgsl.js",
    antialias: false
  });

  // Cap DPR pour limiter le coût CPU/GPU
  device.maxPixelRatio = Math.min(window.devicePixelRatio || 1, maxDevicePixelRatio);

  const opts = new pc.AppOptions();
  opts.graphicsDevice = device;
  opts.mouse = new pc.Mouse(canvas);
  opts.touch = new pc.TouchDevice(canvas);
  opts.keyboard = new pc.Keyboard(canvas);
  opts.componentSystems = [
    pc.RenderComponentSystem,
    pc.CameraComponentSystem,
    pc.LightComponentSystem,
    pc.ScriptComponentSystem,
    pc.GSplatComponentSystem,
    pc.CollisionComponentSystem,
    pc.RigidbodyComponentSystem
  ];
  // GSplatHandler gère nativement les .sog
  opts.resourceHandlers = [pc.TextureHandler, pc.ContainerHandler, pc.ScriptHandler, pc.GSplatHandler];

  app = new pc.Application(canvas, opts);
  app.setCanvasFillMode(pc.FILLMODE_NONE);
  app.setCanvasResolution(pc.RESOLUTION_AUTO);

  // --- Debounce resize (moins de rafales) ---
  resizeObserver = new ResizeObserver((entries) => {
    if (!entries || !entries.length) return;
    if (resizeTimeout) clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
      app.resizeCanvas(entries[0].contentRect.width, entries[0].contentRect.height);
    }, 60);
  });
  resizeObserver.observe(viewerContainer);

  window.addEventListener("resize", () => {
    if (resizeTimeout) clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
      app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight);
    }, 60);
  });

  // Nettoyage complet
  app.on("destroy", () => {
    try {
      resizeObserver.disconnect();
    } catch {}
    if (opts.keyboard && opts.keyboard.detach) opts.keyboard.detach();
    window.removeEventListener("keydown", onKeyDownCapture, true);

    canvas.removeEventListener("pointerenter", onPointerEnter);
    canvas.removeEventListener("pointerleave", onPointerLeave);
    canvas.removeEventListener("mouseenter", onPointerEnter);
    canvas.removeEventListener("mouseleave", onPointerLeave);
    canvas.removeEventListener("mousedown", focusCanvas);
    canvas.removeEventListener("touchstart", focusCanvas);
    canvas.removeEventListener("blur", onCanvasBlur);
  });

  // --- Enregistre les assets en 2 phases ---
  // Phase 1 : .sog (priorité) ⇒ time-to-first-pixel
  const sogAsset = new pc.Asset("gsplat", "gsplat", { url: sogUrl });
  app.assets.add(sogAsset);

  // Phase 2 (déférée) : glb + présentoir
  const glbAsset = new pc.Asset("glb", "container", { url: glbUrl });
  const presentoirAsset = new pc.Asset("presentoir", "container", { url: presentoirUrl });
  app.assets.add(glbAsset);
  app.assets.add(presentoirAsset);

  // Assure orbit-camera.js (nécessaire pour les scripts d'input)
  await ensureOrbitScriptsLoaded();

  // ---------- PHASE 1 : charger le .sog, démarrer tout de suite ----------
  await new Promise((resolve, reject) => {
    const loader1 = new pc.AssetListLoader([sogAsset], app.assets);
    loader1.load(() => resolve());
    loader1.on('error', reject);
  });

  app.start(); // démarre l'update loop le plus tôt possible
  progressDialog.style.display = "none";

  // --- Modèle principal (GSplat via .sog) ---
  modelEntity = new pc.Entity("model");
  modelEntity.addComponent("gsplat", { asset: sogAsset });
  modelEntity.setLocalPosition(modelX, modelY, modelZ);
  modelEntity.setLocalEulerAngles(modelRotationX, modelRotationY, modelRotationZ);
  modelEntity.setLocalScale(modelScale, modelScale, modelScale);
  app.root.addChild(modelEntity);

  // --- Caméra + scripts d’input ---
  cameraEntity = new pc.Entity("camera");
  cameraEntity.addComponent("camera", {
    clearColor: new pc.Color(color_bg),
    nearClip: 0.001,
    farClip: 100
  });
  cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
  cameraEntity.lookAt(modelEntity.getPosition());
  cameraEntity.addComponent("script");

  cameraEntity.script.create("orbitCamera", {
    attributes: {
      focusEntity: modelEntity,
      inertiaFactor: 0.2,
      distanceMax: maxZoom,
      distanceMin: minZoom,
      pitchAngleMax: maxAngle,
      pitchAngleMin: minAngle,
      yawAngleMax: maxAzimuth,
      yawAngleMin: minAzimuth,
      minY: minY,
      frameOnStart: false
    }
  });
  cameraEntity.script.create("orbitCameraInputMouse");
  cameraEntity.script.create("orbitCameraInputTouch");
  cameraEntity.script.create("orbitCameraInputKeyboard", {
    attributes: {
      forwardSpeed: 1.2,
      strafeSpeed: 1.2
    }
  });
  app.root.addChild(cameraEntity);

  // Taille initiale
  app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight);
  app.once("update", () => resetViewerCamera());

  // ---------- Perf dynamique : DPR temporairement réduit pendant interaction ----------
  const setDpr = (val) => {
    const clamped = Math.max(0.5, Math.min(val, maxDevicePixelRatio));
    if (app.graphicsDevice.maxPixelRatio !== clamped) {
      app.graphicsDevice.maxPixelRatio = clamped;
      // Force un resize pour appliquer immédiatement
      app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight);
    }
  };

  const bumpInteraction = () => {
    // baisse DPR pendant l'interaction
    setDpr(interactDpr);
    if (idleTimer) clearTimeout(idleTimer);
    idleTimer = setTimeout(() => {
      // restaure DPR max quand l'utilisateur s'arrête
      setDpr(Math.min(window.devicePixelRatio || 1, maxDevicePixelRatio));
    }, idleRestoreDelay);
  };

  // Hooks d'interaction
  const interactionEvents = ["mousedown", "mousemove", "mouseup", "wheel", "touchstart", "touchmove", "keydown"];
  interactionEvents.forEach((ev) => {
    canvas.addEventListener(ev, bumpInteraction, { passive: true });
  });

  // ---------- PHASE 2 (déférée) : charger sol/environnement et tooltips ----------
  // On charge le reste sans bloquer l’affichage initial
  setTimeout(async () => {
    try {
      await new Promise((resolve) => {
        const loader2 = new pc.AssetListLoader([glbAsset, presentoirAsset], app.assets);
        loader2.load(() => resolve());
      });

      // Sol / environnement
      const glbEntity = glbAsset.resource ? glbAsset.resource.instantiateRenderEntity() : null;
      if (glbEntity) {
        app.root.addChild(glbEntity);
      }

      const presentoirEntity =
        presentoirAsset.resource ? presentoirAsset.resource.instantiateRenderEntity() : null;
      if (presentoirEntity) {
        presentoirEntity.setLocalScale(presentoirScaleX, presentoirScaleY, presentoirScaleZ);
        app.root.addChild(presentoirEntity);
      }

      if (!espace_expo_bool) {
        const matSol = new pc.StandardMaterial();
        matSol.blendType = pc.BLEND_NONE;
        matSol.emissive = new pc.Color(color_bg);
        matSol.emissiveIntensity = 1;
        matSol.useLighting = false;
        matSol.update();

        if (presentoirEntity) {
          traverse(presentoirEntity, (node) => {
            if (node.render && node.render.meshInstances) {
              for (const mi of node.render.meshInstances) mi.material = matSol;
            }
          });
        }

        if (glbEntity) {
          traverse(glbEntity, (node) => {
            if (node.render && node.render.meshInstances) {
              for (const mi of node.render.meshInstances) mi.material = matSol;
            }
          });

          // ////// MODIFIE A LA MANO FAIRE GAFFE //////
          glbEntity.setLocalScale(10, 10, 10);
        }
      }

      // Tooltips (optionnels) — chargés après premier rendu
      try {
        if (config.tooltips_url) {
          import("./tooltips.js")
            .then((tooltipsModule) => {
              tooltipsModule.initializeTooltips({
                app,
                cameraEntity,
                modelEntity,
                tooltipsUrl: config.tooltips_url,
                defaultVisible: !!config.showTooltipsDefault,
                moveDuration: config.tooltipMoveDuration || 0.6
              });
            })
            .catch(() => { /* optional */ });
        }
      } catch (e) { /* optional */ }
    } catch (e) {
      console.warn("[viewer.js] Deferred assets load failed:", e);
    }
  }, 0);

  viewerInitialized = true;
}

/* -------------------------------------------
   Reset caméra (API)
-------------------------------------------- */

export function resetViewerCamera() {
  try {
    if (!cameraEntity || !modelEntity || !app) return;
    const orbitCam = cameraEntity.script.orbitCamera;
    if (!orbitCam) return;

    const modelPos = modelEntity.getPosition();
    const tempEnt = new pc.Entity();
    tempEnt.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
    tempEnt.lookAt(modelPos);

    const dist = new pc.Vec3()
      .sub2(new pc.Vec3(chosenCameraX, chosenCameraY, chosenCameraZ), modelPos)
      .length();

    cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
    cameraEntity.lookAt(modelPos);

    orbitCam.pivotPoint = modelPos.clone();
    orbitCam._targetDistance = dist;
    orbitCam._distance = dist;

    const rot = tempEnt.getRotation();
    const fwd = new pc.Vec3();
    rot.transformVector(pc.Vec3.FORWARD, fwd);

    const yaw = Math.atan2(-fwd.x, -fwd.z) * pc.math.RAD_TO_DEG;
    const yawQuat = new pc.Quat().setFromEulerAngles(0, -yaw, 0);
    const rotNoYaw = new pc.Quat().mul2(yawQuat, rot);
    const fNoYaw = new pc.Vec3();
    rotNoYaw.transformVector(pc.Vec3.FORWARD, fNoYaw);
    const pitch = Math.atan2(fNoYaw.y, -fNoYaw.z) * pc.math.RAD_TO_DEG;

    orbitCam._targetYaw = yaw;
    orbitCam._yaw = yaw;
    orbitCam._targetPitch = pitch;
    orbitCam._pitch = pitch;
    if (orbitCam._updatePosition) orbitCam._updatePosition();

    tempEnt.destroy();
  } catch (e) {
    console.error("[viewer.js] resetViewerCamera error:", e);
  }
}