@needle-tools/engine 4.7.4 → 4.8.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/gltf-progressive-VTcU5sMu.min.js +8 -0
  2. package/dist/gltf-progressive-VXeY4K8o.js +1370 -0
  3. package/dist/gltf-progressive-_-uQwSK8.umd.cjs +8 -0
  4. package/dist/loader.worker-D5fjeWJO.js +27 -0
  5. package/dist/needle-engine.bundle-3y1KBFjI.js +42600 -0
  6. package/dist/needle-engine.bundle-D5cg00Gf.min.js +1607 -0
  7. package/dist/needle-engine.bundle-DQ3d-G3Q.umd.cjs +1607 -0
  8. package/dist/needle-engine.d.ts +15 -15
  9. package/dist/needle-engine.js +591 -592
  10. package/dist/needle-engine.min.js +1 -1
  11. package/dist/needle-engine.umd.cjs +1 -1
  12. package/dist/{postprocessing-BzY0H7ry.min.js → postprocessing-ChsrvDkI.min.js} +54 -54
  13. package/dist/{postprocessing-vKBVFpSz.js → postprocessing-DElbMQgB.js} +479 -483
  14. package/dist/{postprocessing-Dw2OCMp4.umd.cjs → postprocessing-DtxaELce.umd.cjs} +66 -66
  15. package/dist/{three-examples-DUcCNw9s.umd.cjs → three-examples-BhQvv1B9.umd.cjs} +11 -11
  16. package/dist/{three-examples-tvuhV8Ne.js → three-examples-CM6Iip03.js} +23 -27
  17. package/dist/{three-examples-BMOhDaYR.min.js → three-examples-D2zemuAM.min.js} +12 -12
  18. package/dist/{three-mesh-ui-CxuWt7m-.js → three-mesh-ui-D6Mz5Yl7.js} +799 -810
  19. package/dist/three-mesh-ui-DWcMuyQ_.min.js +406 -0
  20. package/dist/three-mesh-ui-tt0buEDC.umd.cjs +406 -0
  21. package/dist/{vendor-BmYIgaS1.js → vendor-ClB-U1Hn.js} +10 -10
  22. package/dist/{vendor-Cavtu3CP.umd.cjs → vendor-bOWOWClg.umd.cjs} +1 -1
  23. package/lib/engine-components/export/usdz/extensions/behavior/Behaviour.d.ts +1 -1
  24. package/lib/engine-components/postprocessing/PostProcessingHandler.d.ts +1 -0
  25. package/lib/engine-components/postprocessing/PostProcessingHandler.js +8 -0
  26. package/lib/engine-components/postprocessing/PostProcessingHandler.js.map +1 -1
  27. package/package.json +4 -4
  28. package/plugins/vite/dependencies.js +28 -19
  29. package/plugins/vite/dependency-watcher.js +6 -1
  30. package/src/engine-components/postprocessing/PostProcessingHandler.ts +14 -0
  31. package/dist/gltf-progressive-Bgh1c4Fd.js +0 -1224
  32. package/dist/gltf-progressive-D6f5talj.min.js +0 -8
  33. package/dist/gltf-progressive-otA_hxSA.umd.cjs +0 -8
  34. package/dist/needle-engine.bundle-Bb6xVcZE.min.js +0 -1607
  35. package/dist/needle-engine.bundle-BldBPoPh.js +0 -43846
  36. package/dist/needle-engine.bundle-ByrSH-zp.umd.cjs +0 -1607
  37. package/dist/three-mesh-ui-B3p3gyUz.min.js +0 -406
  38. package/dist/three-mesh-ui-CQiIQIlA.umd.cjs +0 -406
@@ -1,1224 +0,0 @@
1
- var Qe = Object.defineProperty;
2
- var Ee = (o) => {
3
- throw TypeError(o);
4
- };
5
- var je = (o, t, e) => t in o ? Qe(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e;
6
- var u = (o, t, e) => je(o, typeof t != "symbol" ? t + "" : t, e), $e = (o, t, e) => t.has(o) || Ee("Cannot " + e);
7
- var x = (o, t, e) => ($e(o, t, "read from private field"), e ? e.call(o) : t.get(o)), Y = (o, t, e) => t.has(o) ? Ee("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(o) : t.set(o, e), U = (o, t, e, s) => ($e(o, t, "write to private field"), s ? s.call(o, e) : t.set(o, e), e);
8
- import { BufferGeometry as ye, Mesh as te, Texture as ne, TextureLoader as Je, Matrix4 as Ie, Clock as Ze, MeshStandardMaterial as et, Sphere as tt, Box3 as Ge, Vector3 as V } from "./three-DrqIzZTH.js";
9
- import { DRACOLoader as st, KTX2Loader as rt, MeshoptDecoder as it, GLTFLoader as Ce } from "./three-examples-tvuhV8Ne.js";
10
- const nt = "";
11
- globalThis.GLTF_PROGRESSIVE_VERSION = nt;
12
- console.debug("[gltf-progressive] version -");
13
- let q = "https://www.gstatic.com/draco/versioned/decoders/1.5.7/", se = "https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/";
14
- const ot = q, at = se, Ne = new URL(q + "draco_decoder.js");
15
- Ne.searchParams.append("range", "true");
16
- fetch(Ne, {
17
- method: "GET",
18
- headers: {
19
- Range: "bytes=0-1"
20
- }
21
- }).catch((o) => {
22
- console.debug(`Failed to fetch remote Draco decoder from ${q} (offline: ${typeof navigator < "u" ? navigator.onLine : "unknown"})`), q === ot && lt("./include/draco/"), se === at && ut("./include/ktx2/");
23
- }).finally(() => {
24
- Ue();
25
- });
26
- function lt(o) {
27
- q = o, G && G[Pe] != q ? (console.debug("Updating Draco decoder path to " + o), G[Pe] = q, G.setDecoderPath(q), G.preload()) : console.debug("Setting Draco decoder path to " + o);
28
- }
29
- function ut(o) {
30
- se = o, R && R.transcoderPath != se ? (console.debug("Updating KTX2 transcoder path to " + o), R.setTranscoderPath(se), R.init()) : console.debug("Setting KTX2 transcoder path to " + o);
31
- }
32
- const Pe = Symbol("dracoDecoderPath");
33
- let G, Le, R;
34
- function Ue() {
35
- G || (G = new st(), G[Pe] = q, G.setDecoderPath(q), G.setDecoderConfig({ type: "js" }), G.preload()), R || (R = new rt(), R.setTranscoderPath(se), R.init()), Le || (Le = it);
36
- }
37
- function ze(o) {
38
- return Ue(), o ? R.detectSupport(o) : o !== null && console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"), { dracoLoader: G, ktx2Loader: R, meshoptDecoder: Le };
39
- }
40
- function qe(o) {
41
- o.dracoLoader || o.setDRACOLoader(G), o.ktx2Loader || o.setKTX2Loader(R), o.meshoptDecoder || o.setMeshoptDecoder(Le);
42
- }
43
- const Te = /* @__PURE__ */ new WeakMap();
44
- function Ve(o, t) {
45
- let e = Te.get(o);
46
- e ? e = Object.assign(e, t) : e = t, Te.set(o, e);
47
- }
48
- const ve = Ce.prototype.load;
49
- function dt(...o) {
50
- const t = Te.get(this);
51
- let e = o[0];
52
- const s = new URL(e, window.location.href);
53
- if (s.hostname.endsWith("needle.tools")) {
54
- const r = (t == null ? void 0 : t.progressive) !== void 0 ? t.progressive : !0, i = t != null && t.usecase ? t.usecase : "default";
55
- r ? this.requestHeader.Accept = `*/*;progressive=allowed;usecase=${i}` : this.requestHeader.Accept = `*/*;usecase=${i}`, e = s.toString();
56
- }
57
- return o[0] = e, ve == null ? void 0 : ve.call(this, ...o);
58
- }
59
- Ce.prototype.load = dt;
60
- ue("debugprogressive");
61
- function ue(o) {
62
- if (typeof window > "u") return !1;
63
- const e = new URL(window.location.href).searchParams.get(o);
64
- return e == null || e === "0" || e === "false" ? !1 : e === "" ? !0 : e;
65
- }
66
- function ct(o, t) {
67
- if (t === void 0 || t.startsWith("./") || t.startsWith("http") || o === void 0)
68
- return t;
69
- const e = o.lastIndexOf("/");
70
- if (e >= 0) {
71
- const s = o.substring(0, e + 1);
72
- for (; s.endsWith("/") && t.startsWith("/"); ) t = t.substring(1);
73
- return s + t;
74
- }
75
- return t;
76
- }
77
- let oe;
78
- function ft() {
79
- return oe !== void 0 || (oe = /iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent), ue("debugprogressive") && console.log("[glTF Progressive]: isMobileDevice", oe)), oe;
80
- }
81
- function Be() {
82
- if (typeof window > "u") return !1;
83
- const o = new URL(window.location.href), t = o.hostname === "localhost" || /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(o.hostname);
84
- return o.hostname === "127.0.0.1" || t;
85
- }
86
- class ht {
87
- constructor(t = 100, e = {}) {
88
- u(this, "_running", /* @__PURE__ */ new Map());
89
- u(this, "_queue", []);
90
- u(this, "debug", !1);
91
- u(this, "tick", () => {
92
- this.internalUpdate(), setTimeout(this.tick, 10);
93
- });
94
- this.maxConcurrent = t, this.debug = e.debug ?? !1, window.requestAnimationFrame(this.tick);
95
- }
96
- /**
97
- * Request a slot for a promise with a specific key. This function returns a promise with a `use` method that can be called to add the promise to the queue.
98
- */
99
- slot(t) {
100
- return this.debug && console.debug(`[PromiseQueue]: Requesting slot for key ${t}, running: ${this._running.size}, waiting: ${this._queue.length}`), new Promise((e) => {
101
- this._queue.push({ key: t, resolve: e });
102
- });
103
- }
104
- add(t, e) {
105
- this._running.has(t) || (this._running.set(t, e), e.finally(() => {
106
- this._running.delete(t), this.debug && console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${t})`);
107
- }), this.debug && console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${t})`));
108
- }
109
- internalUpdate() {
110
- const t = this.maxConcurrent - this._running.size;
111
- for (let e = 0; e < t && this._queue.length > 0; e++) {
112
- this.debug && console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);
113
- const { key: s, resolve: n } = this._queue.shift();
114
- n({
115
- use: (r) => this.add(s, r)
116
- });
117
- }
118
- }
119
- }
120
- const gt = typeof window > "u" && typeof document > "u", Ae = Symbol("needle:raycast-mesh");
121
- function de(o) {
122
- return (o == null ? void 0 : o[Ae]) instanceof ye ? o[Ae] : null;
123
- }
124
- function pt(o, t) {
125
- if ((o.type === "Mesh" || o.type === "SkinnedMesh") && !de(o)) {
126
- const s = yt(t);
127
- s.userData = { isRaycastMesh: !0 }, o[Ae] = s;
128
- }
129
- }
130
- function mt(o = !0) {
131
- if (o) {
132
- if (ae) return;
133
- const t = ae = te.prototype.raycast;
134
- te.prototype.raycast = function(e, s) {
135
- const n = this, r = de(n);
136
- let i;
137
- r && n.isMesh && (i = n.geometry, n.geometry = r), t.call(this, e, s), i && (n.geometry = i);
138
- };
139
- } else {
140
- if (!ae) return;
141
- te.prototype.raycast = ae, ae = null;
142
- }
143
- }
144
- let ae = null;
145
- function yt(o) {
146
- const t = new ye();
147
- for (const e in o.attributes)
148
- t.setAttribute(e, o.getAttribute(e));
149
- return t.setIndex(o.getIndex()), t;
150
- }
151
- const Q = new Array(), L = ue("debugprogressive");
152
- let pe, ee = -1;
153
- if (L) {
154
- let o = function() {
155
- ee += 1, ee >= t && (ee = -1), console.log(`Toggle LOD level [${ee}]`);
156
- }, t = 6;
157
- window.addEventListener("keyup", (e) => {
158
- e.key === "p" && o(), e.key === "w" && (pe = !pe, console.log(`Toggle wireframe [${pe}]`));
159
- const s = parseInt(e.key);
160
- !isNaN(s) && s >= 0 && (ee = s, console.log(`Set LOD level to [${ee}]`));
161
- });
162
- }
163
- function We(o) {
164
- if (L)
165
- if (Array.isArray(o))
166
- for (const t of o)
167
- We(t);
168
- else o && "wireframe" in o && (o.wireframe = pe === !0);
169
- }
170
- const W = "NEEDLE_progressive", Oe = Symbol("needle-progressive-texture"), _ = class _ {
171
- constructor(t, e) {
172
- u(this, "parser");
173
- u(this, "url");
174
- u(this, "_isLoadingMesh");
175
- u(this, "loadMesh", (t) => {
176
- var s, n;
177
- if (this._isLoadingMesh) return null;
178
- const e = (n = (s = this.parser.json.meshes[t]) == null ? void 0 : s.extensions) == null ? void 0 : n[W];
179
- return e ? (this._isLoadingMesh = !0, this.parser.getDependency("mesh", t).then((r) => {
180
- var i;
181
- return this._isLoadingMesh = !1, r && _.registerMesh(this.url, e.guid, r, (i = e.lods) == null ? void 0 : i.length, 0, e), r;
182
- })) : null;
183
- });
184
- L && console.log("Progressive extension registered for", e), this.parser = t, this.url = e;
185
- }
186
- /** The name of the extension */
187
- get name() {
188
- return W;
189
- }
190
- static getMeshLODExtension(t) {
191
- const e = this.getAssignedLODInformation(t);
192
- return e != null && e.key ? this.lodInfos.get(e.key) : null;
193
- }
194
- static getPrimitiveIndex(t) {
195
- var s;
196
- const e = (s = this.getAssignedLODInformation(t)) == null ? void 0 : s.index;
197
- return e ?? -1;
198
- }
199
- static getMaterialMinMaxLODsCount(t, e) {
200
- const s = this, n = "LODS:minmax", r = t[n];
201
- if (r != null) return r;
202
- if (e || (e = {
203
- min_count: 1 / 0,
204
- max_count: 0,
205
- lods: []
206
- }), Array.isArray(t)) {
207
- for (const a of t)
208
- this.getMaterialMinMaxLODsCount(a, e);
209
- return t[n] = e, e;
210
- }
211
- if (L === "verbose" && console.log("getMaterialMinMaxLODsCount", t), t.type === "ShaderMaterial" || t.type === "RawShaderMaterial") {
212
- const a = t;
213
- for (const l of Object.keys(a.uniforms)) {
214
- const c = a.uniforms[l].value;
215
- (c == null ? void 0 : c.isTexture) === !0 && i(c, e);
216
- }
217
- } else if (t.isMaterial)
218
- for (const a of Object.keys(t)) {
219
- const l = t[a];
220
- (l == null ? void 0 : l.isTexture) === !0 && i(l, e);
221
- }
222
- return t[n] = e, e;
223
- function i(a, l) {
224
- const c = s.getAssignedLODInformation(a);
225
- if (c) {
226
- const d = s.lodInfos.get(c.key);
227
- if (d && d.lods) {
228
- l.min_count = Math.min(l.min_count, d.lods.length), l.max_count = Math.max(l.max_count, d.lods.length);
229
- for (let h = 0; h < d.lods.length; h++) {
230
- const f = d.lods[h];
231
- f.width && (l.lods[h] = l.lods[h] || { min_height: 1 / 0, max_height: 0 }, l.lods[h].min_height = Math.min(l.lods[h].min_height, f.height), l.lods[h].max_height = Math.max(l.lods[h].max_height, f.height));
232
- }
233
- }
234
- }
235
- }
236
- }
237
- /** Check if a LOD level is available for a mesh or a texture
238
- * @param obj the mesh or texture to check
239
- * @param level the level of detail to check for (0 is the highest resolution). If undefined, the function checks if any LOD level is available
240
- * @returns true if the LOD level is available (or if any LOD level is available if level is undefined)
241
- */
242
- static hasLODLevelAvailable(t, e) {
243
- var r;
244
- if (Array.isArray(t)) {
245
- for (const i of t)
246
- if (this.hasLODLevelAvailable(i, e)) return !0;
247
- return !1;
248
- }
249
- if (t.isMaterial === !0) {
250
- for (const i of Object.keys(t)) {
251
- const a = t[i];
252
- if (a && a.isTexture && this.hasLODLevelAvailable(a, e))
253
- return !0;
254
- }
255
- return !1;
256
- } else if (t.isGroup === !0) {
257
- for (const i of t.children)
258
- if (i.isMesh === !0 && this.hasLODLevelAvailable(i, e))
259
- return !0;
260
- }
261
- let s, n;
262
- if (t.isMesh ? s = t.geometry : (t.isBufferGeometry || t.isTexture) && (s = t), s && (r = s == null ? void 0 : s.userData) != null && r.LODS) {
263
- const i = s.userData.LODS;
264
- if (n = this.lodInfos.get(i.key), e === void 0) return n != null;
265
- if (n)
266
- return Array.isArray(n.lods) ? e < n.lods.length : e === 0;
267
- }
268
- return !1;
269
- }
270
- /** Load a different resolution of a mesh (if available)
271
- * @param context the context
272
- * @param source the sourceid of the file from which the mesh is loaded (this is usually the component's sourceId)
273
- * @param mesh the mesh to load the LOD for
274
- * @param level the level of detail to load (0 is the highest resolution)
275
- * @returns a promise that resolves to the mesh with the requested LOD level
276
- * @example
277
- * ```javascript
278
- * const mesh = this.gameObject as Mesh;
279
- * NEEDLE_progressive.assignMeshLOD(context, sourceId, mesh, 1).then(mesh => {
280
- * console.log("Mesh with LOD level 1 loaded", mesh);
281
- * });
282
- * ```
283
- */
284
- static assignMeshLOD(t, e) {
285
- var s;
286
- if (!t) return Promise.resolve(null);
287
- if (t instanceof te || t.isMesh === !0) {
288
- const n = t.geometry, r = this.getAssignedLODInformation(n);
289
- if (!r)
290
- return Promise.resolve(null);
291
- for (const i of Q)
292
- (s = i.onBeforeGetLODMesh) == null || s.call(i, t, e);
293
- return t["LOD:requested level"] = e, _.getOrLoadLOD(n, e).then((i) => {
294
- if (Array.isArray(i)) {
295
- const a = r.index || 0;
296
- i = i[a];
297
- }
298
- return t["LOD:requested level"] === e && (delete t["LOD:requested level"], i && n != i && ((i == null ? void 0 : i.isBufferGeometry) ? t.geometry = i : L && console.error("Invalid LOD geometry", i))), i;
299
- }).catch((i) => (console.error("Error loading mesh LOD", t, i), null));
300
- } else L && console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh", t);
301
- return Promise.resolve(null);
302
- }
303
- static assignTextureLOD(t, e = 0) {
304
- if (!t) return Promise.resolve(null);
305
- if (t.isMesh === !0) {
306
- const s = t;
307
- if (Array.isArray(s.material)) {
308
- const n = new Array();
309
- for (const r of s.material) {
310
- const i = this.assignTextureLOD(r, e);
311
- n.push(i);
312
- }
313
- return Promise.all(n).then((r) => {
314
- const i = new Array();
315
- for (const a of r)
316
- Array.isArray(a) && i.push(...a);
317
- return i;
318
- });
319
- } else
320
- return this.assignTextureLOD(s.material, e);
321
- }
322
- if (t.isMaterial === !0) {
323
- const s = t, n = [], r = new Array();
324
- if (s.uniforms && (s.isRawShaderMaterial || s.isShaderMaterial === !0)) {
325
- const i = s;
326
- for (const a of Object.keys(i.uniforms)) {
327
- const l = i.uniforms[a].value;
328
- if ((l == null ? void 0 : l.isTexture) === !0) {
329
- const c = this.assignTextureLODForSlot(l, e, s, a).then((d) => (d && i.uniforms[a].value != d && (i.uniforms[a].value = d, i.uniformsNeedUpdate = !0), d));
330
- n.push(c), r.push(a);
331
- }
332
- }
333
- } else
334
- for (const i of Object.keys(s)) {
335
- const a = s[i];
336
- if ((a == null ? void 0 : a.isTexture) === !0) {
337
- const l = this.assignTextureLODForSlot(a, e, s, i);
338
- n.push(l), r.push(i);
339
- }
340
- }
341
- return Promise.all(n).then((i) => {
342
- const a = new Array();
343
- for (let l = 0; l < i.length; l++) {
344
- const c = i[l], d = r[l];
345
- c && c.isTexture === !0 ? a.push({ material: s, slot: d, texture: c, level: e }) : a.push({ material: s, slot: d, texture: null, level: e });
346
- }
347
- return a;
348
- });
349
- }
350
- if (t instanceof ne || t.isTexture === !0) {
351
- const s = t;
352
- return this.assignTextureLODForSlot(s, e, null, null);
353
- }
354
- return Promise.resolve(null);
355
- }
356
- static assignTextureLODForSlot(t, e, s, n) {
357
- return (t == null ? void 0 : t.isTexture) !== !0 ? Promise.resolve(null) : n === "glyphMap" ? Promise.resolve(t) : _.getOrLoadLOD(t, e).then((r) => {
358
- if (Array.isArray(r))
359
- return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen", r), null;
360
- if ((r == null ? void 0 : r.isTexture) === !0) {
361
- if (r != t && s && n) {
362
- const i = s[n];
363
- if (i && !L) {
364
- const a = this.getAssignedLODInformation(i);
365
- if (a && (a == null ? void 0 : a.level) < e)
366
- return L === "verbose" && console.warn("Assigned texture level is already higher: ", a.level, e, s, i, r), null;
367
- }
368
- s[n] = r;
369
- }
370
- return r;
371
- } else L == "verbose" && console.warn("No LOD found for", t, e);
372
- return null;
373
- }).catch((r) => (console.error("Error loading LOD", t, r), null));
374
- }
375
- // private _isLoadingTexture;
376
- // loadTexture = (textureIndex: number) => {
377
- // if (this._isLoadingTexture) return null;
378
- // const ext = this.parser.json.textures[textureIndex]?.extensions?.[EXTENSION_NAME] as NEEDLE_ext_progressive_texture;
379
- // if (!ext) return null;
380
- // this._isLoadingTexture = true;
381
- // return this.parser.getDependency("texture", textureIndex).then(tex => {
382
- // this._isLoadingTexture = false;
383
- // if (tex) {
384
- // NEEDLE_progressive.registerTexture(this.url, tex as Texture, ext.lods?.length, textureIndex, ext);
385
- // }
386
- // return tex;
387
- // });
388
- // }
389
- afterRoot(t) {
390
- var e, s;
391
- return L && console.log("AFTER", this.url, t), (e = this.parser.json.textures) == null || e.forEach((n, r) => {
392
- var i;
393
- if (n != null && n.extensions) {
394
- const a = n == null ? void 0 : n.extensions[W];
395
- if (a) {
396
- if (!a.lods) {
397
- L && console.warn("Texture has no LODs", a);
398
- return;
399
- }
400
- let l = !1;
401
- for (const c of this.parser.associations.keys())
402
- if (c.isTexture === !0) {
403
- const d = this.parser.associations.get(c);
404
- (d == null ? void 0 : d.textures) === r && (l = !0, _.registerTexture(this.url, c, (i = a.lods) == null ? void 0 : i.length, r, a));
405
- }
406
- l || this.parser.getDependency("texture", r).then((c) => {
407
- var d;
408
- c && _.registerTexture(this.url, c, (d = a.lods) == null ? void 0 : d.length, r, a);
409
- });
410
- }
411
- }
412
- }), (s = this.parser.json.meshes) == null || s.forEach((n, r) => {
413
- if (n != null && n.extensions) {
414
- const i = n == null ? void 0 : n.extensions[W];
415
- if (i && i.lods) {
416
- for (const a of this.parser.associations.keys())
417
- if (a.isMesh) {
418
- const l = this.parser.associations.get(a);
419
- (l == null ? void 0 : l.meshes) === r && _.registerMesh(this.url, i.guid, a, i.lods.length, l.primitives, i);
420
- }
421
- }
422
- }
423
- }), null;
424
- }
425
- static async getOrLoadLOD(t, e) {
426
- var a, l, c, d;
427
- const s = L == "verbose", n = this.getAssignedLODInformation(t);
428
- if (!n)
429
- return L && console.warn(`[gltf-progressive] No LOD information found: ${t.name}, uuid: ${t.uuid}, type: ${t.type}`, t), null;
430
- const r = n == null ? void 0 : n.key;
431
- let i;
432
- if (t.isTexture === !0) {
433
- const h = t;
434
- h.source && h.source[Oe] && (i = h.source[Oe]);
435
- }
436
- if (i || (i = _.lodInfos.get(r)), i) {
437
- if (e > 0) {
438
- let D = !1;
439
- const v = Array.isArray(i.lods);
440
- if (v && e >= i.lods.length ? D = !0 : v || (D = !0), D)
441
- return this.lowresCache.get(r);
442
- }
443
- const h = Array.isArray(i.lods) ? (a = i.lods[e]) == null ? void 0 : a.path : i.lods;
444
- if (!h)
445
- return L && !i["missing:uri"] && (i["missing:uri"] = !0, console.warn("Missing uri for progressive asset for LOD " + e, i)), null;
446
- const f = ct(n.url, h);
447
- if (f.endsWith(".glb") || f.endsWith(".gltf")) {
448
- if (!i.guid)
449
- return console.warn("missing pointer for glb/gltf texture", i), null;
450
- const D = f + "_" + i.guid, v = this.previouslyLoaded.get(D);
451
- if (v !== void 0) {
452
- s && console.log(`LOD ${e} was already loading/loaded: ${D}`);
453
- let g = await v.catch((A) => (console.error(`Error loading LOD ${e} from ${f}
454
- `, A), null)), w = !1;
455
- if (g == null || (g instanceof ne && t instanceof ne ? (l = g.image) != null && l.data || (c = g.source) != null && c.data ? g = this.copySettings(t, g) : (w = !0, this.previouslyLoaded.delete(D)) : g instanceof ye && t instanceof ye && ((d = g.attributes.position) != null && d.array || (w = !0, this.previouslyLoaded.delete(D)))), !w)
456
- return g;
457
- }
458
- const P = await this.queue.slot(f);
459
- if (!P.use)
460
- return L && console.log(`LOD ${e} was aborted: ${f}`), null;
461
- const b = i, B = new Promise(async (g, w) => {
462
- const A = new Ce();
463
- qe(A), L && (await new Promise((O) => setTimeout(O, 1e3)), s && console.warn("Start loading (delayed) " + f, b.guid));
464
- let F = f;
465
- if (b && Array.isArray(b.lods)) {
466
- const O = b.lods[e];
467
- O.hash && (F += "?v=" + O.hash);
468
- }
469
- const S = await A.loadAsync(F).catch((O) => (console.error(`Error loading LOD ${e} from ${f}
470
- `, O), g(null)));
471
- if (!S)
472
- return g(null);
473
- const Z = S.parser;
474
- s && console.log("Loading finished " + f, b.guid);
475
- let C = 0;
476
- if (S.parser.json.textures) {
477
- let O = !1;
478
- for (const m of S.parser.json.textures) {
479
- if (m != null && m.extensions) {
480
- const p = m == null ? void 0 : m.extensions[W];
481
- if (p != null && p.guid && p.guid === b.guid) {
482
- O = !0;
483
- break;
484
- }
485
- }
486
- C++;
487
- }
488
- if (O) {
489
- let m = await Z.getDependency("texture", C);
490
- return m && _.assignLODInformation(n.url, m, r, e, void 0), s && console.log('change "' + t.name + '" → "' + m.name + '"', f, C, m, D), t instanceof ne && (m = this.copySettings(t, m)), m && (m.guid = b.guid), g(m);
491
- } else L && console.warn("Could not find texture with guid", b.guid, S.parser.json);
492
- }
493
- if (C = 0, S.parser.json.meshes) {
494
- let O = !1;
495
- for (const m of S.parser.json.meshes) {
496
- if (m != null && m.extensions) {
497
- const p = m == null ? void 0 : m.extensions[W];
498
- if (p != null && p.guid && p.guid === b.guid) {
499
- O = !0;
500
- break;
501
- }
502
- }
503
- C++;
504
- }
505
- if (O) {
506
- const m = await Z.getDependency("mesh", C);
507
- if (s && console.log(`Loaded Mesh "${m.name}"`, f, C, m, D), m.isMesh === !0) {
508
- const p = m.geometry;
509
- return _.assignLODInformation(n.url, p, r, e, 0), g(p);
510
- } else {
511
- const p = new Array();
512
- for (let M = 0; M < m.children.length; M++) {
513
- const E = m.children[M];
514
- if (E.isMesh === !0) {
515
- const T = E.geometry;
516
- _.assignLODInformation(n.url, T, r, e, M), p.push(T);
517
- }
518
- }
519
- return g(p);
520
- }
521
- } else L && console.warn("Could not find mesh with guid", b.guid, S.parser.json);
522
- }
523
- return g(null);
524
- });
525
- return this.previouslyLoaded.set(D, B), P.use(B), await B;
526
- } else if (t instanceof ne) {
527
- s && console.log("Load texture from uri: " + f);
528
- const v = await new Je().loadAsync(f);
529
- return v ? (v.guid = i.guid, v.flipY = !1, v.needsUpdate = !0, v.colorSpace = t.colorSpace, s && console.log(i, v)) : L && console.warn("failed loading", f), v;
530
- }
531
- } else
532
- L && console.warn(`Can not load LOD ${e}: no LOD info found for "${r}" ${t.name}`, t.type);
533
- return null;
534
- }
535
- static assignLODInformation(t, e, s, n, r) {
536
- if (!e) return;
537
- e.userData || (e.userData = {});
538
- const i = new Lt(t, s, n, r);
539
- e.userData.LODS = i, "source" in e && typeof e.source == "object" && (e.source.LODS = i);
540
- }
541
- static getAssignedLODInformation(t) {
542
- var e, s;
543
- return t ? (e = t.userData) != null && e.LODS ? t.userData.LODS : "source" in t && ((s = t.source) != null && s.LODS) ? t.source.LODS : null : null;
544
- }
545
- // private static readonly _copiedTextures: WeakMap<Texture, Texture> = new Map();
546
- static copySettings(t, e) {
547
- return e ? (L && console.warn(`Copy texture settings
548
- `, t.uuid, `
549
- `, e.uuid), e = e.clone(), e.offset = t.offset, e.repeat = t.repeat, e.colorSpace = t.colorSpace, e.magFilter = t.magFilter, e.minFilter = t.minFilter, e.wrapS = t.wrapS, e.wrapT = t.wrapT, e.flipY = t.flipY, e.anisotropy = t.anisotropy, e.mipmaps || (e.generateMipmaps = t.generateMipmaps), e) : t;
550
- }
551
- };
552
- /**
553
- * Register a texture with LOD information
554
- */
555
- u(_, "registerTexture", (t, e, s, n, r) => {
556
- var a, l, c, d, h, f, D, v;
557
- if (!e) {
558
- L && console.error("gltf-progressive: Called register texture without texture");
559
- return;
560
- }
561
- if (L) {
562
- const P = ((a = e.image) == null ? void 0 : a.width) || ((c = (l = e.source) == null ? void 0 : l.data) == null ? void 0 : c.width) || 0, b = ((d = e.image) == null ? void 0 : d.height) || ((f = (h = e.source) == null ? void 0 : h.data) == null ? void 0 : f.height) || 0;
563
- console.log(`> Progressive: register texture[${n}] "${e.name || e.uuid}", Current: ${P}x${b}, Max: ${(D = r.lods[0]) == null ? void 0 : D.width}x${(v = r.lods[0]) == null ? void 0 : v.height}, uuid: ${e.uuid}`, r, e);
564
- }
565
- e.source && (e.source[Oe] = r);
566
- const i = r.guid;
567
- _.assignLODInformation(t, e, i, s, n), _.lodInfos.set(i, r), _.lowresCache.set(i, e);
568
- }), /**
569
- * Register a mesh with LOD information
570
- */
571
- u(_, "registerMesh", (t, e, s, n, r, i) => {
572
- var c;
573
- const a = s.geometry;
574
- if (!a) {
575
- L && console.warn("gltf-progressive: Register mesh without geometry");
576
- return;
577
- }
578
- a.userData || (a.userData = {}), L && console.log("> Progressive: register mesh " + s.name, { index: r, uuid: s.uuid }, i, s), _.assignLODInformation(t, a, e, n, r), _.lodInfos.set(e, i);
579
- let l = _.lowresCache.get(e);
580
- l ? l.push(s.geometry) : l = [s.geometry], _.lowresCache.set(e, l), n > 0 && !de(s) && pt(s, a);
581
- for (const d of Q)
582
- (c = d.onRegisteredNewMesh) == null || c.call(d, s, i);
583
- }), /** A map of key = asset uuid and value = LOD information */
584
- u(_, "lodInfos", /* @__PURE__ */ new Map()), /** cache of already loaded mesh lods */
585
- u(_, "previouslyLoaded", /* @__PURE__ */ new Map()), /** this contains the geometry/textures that were originally loaded */
586
- u(_, "lowresCache", /* @__PURE__ */ new Map()), u(_, "queue", new ht(100, { debug: L != !1 }));
587
- let z = _;
588
- class Lt {
589
- constructor(t, e, s, n) {
590
- u(this, "url");
591
- /** the key to lookup the LOD information */
592
- u(this, "key");
593
- u(this, "level");
594
- /** For multi objects (e.g. a group of meshes) this is the index of the object */
595
- u(this, "index");
596
- this.url = t, this.key = e, this.level = s, n != null && (this.index = n);
597
- }
598
- }
599
- class me {
600
- constructor(t, e) {
601
- u(this, "frame_start");
602
- u(this, "frame_capture_end");
603
- u(this, "ready");
604
- u(this, "_resolve");
605
- u(this, "_signal");
606
- u(this, "_resolved", !1);
607
- u(this, "_addedCount", 0);
608
- u(this, "_resolvedCount", 0);
609
- /** These promises are currently being awaited */
610
- u(this, "_awaiting", []);
611
- u(this, "_maxPromisesPerObject", 1);
612
- u(this, "_currentFrame", 0);
613
- u(this, "_seen", /* @__PURE__ */ new WeakMap());
614
- var r;
615
- const n = Math.max(e.frames ?? 2, 2);
616
- this.frame_start = t, this.frame_capture_end = t + n, this.ready = new Promise((i) => {
617
- this._resolve = i;
618
- }), this.ready.finally(() => {
619
- this._resolved = !0, this._awaiting.length = 0;
620
- }), this._signal = e.signal, (r = this._signal) == null || r.addEventListener("abort", () => {
621
- this.resolveNow();
622
- }), this._maxPromisesPerObject = Math.max(1, e.maxPromisesPerObject ?? 1);
623
- }
624
- /**
625
- * The number of promises that have been added to this group so far.
626
- */
627
- get awaitedCount() {
628
- return this._addedCount;
629
- }
630
- get resolvedCount() {
631
- return this._resolvedCount;
632
- }
633
- get currentlyAwaiting() {
634
- return this._awaiting.length;
635
- }
636
- update(t) {
637
- var e;
638
- this._currentFrame = t, ((e = this._signal) != null && e.aborted || this._currentFrame > this.frame_capture_end && this._awaiting.length === 0) && this.resolveNow();
639
- }
640
- add(t, e, s) {
641
- if (this._resolved) {
642
- L && console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");
643
- return;
644
- }
645
- if (!(this._currentFrame > this.frame_capture_end)) {
646
- if (this._maxPromisesPerObject >= 1)
647
- if (this._seen.has(e)) {
648
- let n = this._seen.get(e);
649
- if (n >= this._maxPromisesPerObject) {
650
- L && console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");
651
- return;
652
- }
653
- this._seen.set(e, n + 1);
654
- } else
655
- this._seen.set(e, 1);
656
- this._awaiting.push(s), this._addedCount++, s.finally(() => {
657
- this._resolvedCount++, this._awaiting.splice(this._awaiting.indexOf(s), 1);
658
- });
659
- }
660
- }
661
- resolveNow() {
662
- var t, e;
663
- this._resolved || (e = this._resolve) == null || e.call(this, {
664
- awaited_count: this._addedCount,
665
- resolved_count: this._resolvedCount,
666
- cancelled: ((t = this._signal) == null ? void 0 : t.aborted) ?? !1
667
- });
668
- }
669
- }
670
- u(me, "addPromise", (t, e, s, n) => {
671
- n.forEach((r) => {
672
- r.add(t, e, s);
673
- });
674
- });
675
- const k = ue("debugprogressive"), xt = ue("noprogressive"), be = Symbol("Needle:LODSManager"), Se = Symbol("Needle:LODState"), H = Symbol("Needle:CurrentLOD"), $ = { mesh_lod: -1, texture_lod: -1 };
676
- var y, I, X, we, j, re, _e, K;
677
- let xe = (y = class {
678
- // readonly plugins: NEEDLE_progressive_plugin[] = [];
679
- constructor(t, e) {
680
- u(this, "renderer");
681
- u(this, "context");
682
- u(this, "projectionScreenMatrix", new Ie());
683
- /**
684
- * The target triangle density is the desired max amount of triangles on screen when the mesh is filling the screen.
685
- * @default 200_000
686
- */
687
- u(this, "targetTriangleDensity", 2e5);
688
- /**
689
- * The interval in frames to automatically update the bounds of skinned meshes.
690
- * Set to 0 or a negative value to disable automatic bounds updates.
691
- * @default 30
692
- */
693
- u(this, "skinnedMeshAutoUpdateBoundsInterval", 30);
694
- /**
695
- * The update interval in frames. If set to 0, the LODs will be updated every frame. If set to 2, the LODs will be updated every second frame, etc.
696
- * @default "auto"
697
- */
698
- u(this, "updateInterval", "auto");
699
- Y(this, I, 1);
700
- /**
701
- * If set to true, the LODsManager will not update the LODs.
702
- * @default false
703
- */
704
- u(this, "pause", !1);
705
- /**
706
- * When set to true the LODsManager will not update the LODs. This can be used to manually update the LODs using the `update` method.
707
- * Otherwise the LODs will be updated automatically when the renderer renders the scene.
708
- * @default false
709
- */
710
- u(this, "manual", !1);
711
- u(this, "_newPromiseGroups", []);
712
- u(this, "_promiseGroupIds", 0);
713
- u(this, "_lodchangedlisteners", []);
714
- Y(this, X);
715
- Y(this, we, new Ze());
716
- Y(this, j, 0);
717
- Y(this, re, 0);
718
- Y(this, _e, 0);
719
- Y(this, K, 0);
720
- u(this, "_fpsBuffer", [60, 60, 60, 60, 60]);
721
- // private testIfLODLevelsAreAvailable() {
722
- u(this, "_sphere", new tt());
723
- u(this, "_tempBox", new Ge());
724
- u(this, "_tempBox2", new Ge());
725
- u(this, "tempMatrix", new Ie());
726
- u(this, "_tempWorldPosition", new V());
727
- u(this, "_tempBoxSize", new V());
728
- u(this, "_tempBox2Size", new V());
729
- this.renderer = t, this.context = { ...e };
730
- }
731
- /** @internal */
732
- static getObjectLODState(t) {
733
- return t[Se];
734
- }
735
- static addPlugin(t) {
736
- Q.push(t);
737
- }
738
- static removePlugin(t) {
739
- const e = Q.indexOf(t);
740
- e >= 0 && Q.splice(e, 1);
741
- }
742
- /**
743
- * Gets the LODsManager for the given renderer. If the LODsManager does not exist yet, it will be created.
744
- * @param renderer The renderer to get the LODsManager for.
745
- * @returns The LODsManager instance.
746
- */
747
- static get(t, e) {
748
- if (t[be])
749
- return console.debug("[gltf-progressive] LODsManager already exists for this renderer"), t[be];
750
- const s = new y(t, {
751
- engine: "unknown",
752
- ...e
753
- });
754
- return t[be] = s, s;
755
- }
756
- /** @deprecated use static `LODsManager.addPlugin()` method. This getter will be removed in later versions */
757
- get plugins() {
758
- return Q;
759
- }
760
- /**
761
- * Call to await LODs loading during the next render cycle.
762
- */
763
- awaitLoading(t) {
764
- const e = this._promiseGroupIds++, s = new me(x(this, j), { ...t });
765
- this._newPromiseGroups.push(s);
766
- const n = performance.now();
767
- return s.ready.finally(() => {
768
- const r = this._newPromiseGroups.indexOf(s);
769
- r >= 0 && (this._newPromiseGroups.splice(r, 1), Be() && performance.measure("LODsManager:awaitLoading", {
770
- start: n,
771
- detail: { id: e, name: t == null ? void 0 : t.name, awaited: s.awaitedCount, resolved: s.resolvedCount }
772
- }));
773
- }), s.ready;
774
- }
775
- _postprocessPromiseGroups() {
776
- if (this._newPromiseGroups.length !== 0)
777
- for (let t = this._newPromiseGroups.length - 1; t >= 0; t--)
778
- this._newPromiseGroups[t].update(x(this, j));
779
- }
780
- addEventListener(t, e) {
781
- t === "changed" && this._lodchangedlisteners.push(e);
782
- }
783
- removeEventListener(t, e) {
784
- if (t === "changed") {
785
- const s = this._lodchangedlisteners.indexOf(e);
786
- s >= 0 && this._lodchangedlisteners.splice(s, 1);
787
- }
788
- }
789
- /**
790
- * Enable the LODsManager. This will replace the render method of the renderer with a method that updates the LODs.
791
- */
792
- enable() {
793
- if (x(this, X)) return;
794
- console.debug("[gltf-progressive] Enabling LODsManager for renderer");
795
- let t = 0;
796
- U(this, X, this.renderer.render);
797
- const e = this;
798
- ze(this.renderer), this.renderer.render = function(s, n) {
799
- const r = e.renderer.getRenderTarget();
800
- (r == null || "isXRRenderTarget" in r && r.isXRRenderTarget) && (t = 0, U(e, j, x(e, j) + 1), U(e, re, x(e, we).getDelta()), U(e, _e, x(e, _e) + x(e, re)), e._fpsBuffer.shift(), e._fpsBuffer.push(1 / x(e, re)), U(e, K, e._fpsBuffer.reduce((a, l) => a + l) / e._fpsBuffer.length), k && x(e, j) % 200 === 0 && console.log("FPS", Math.round(x(e, K)), "Interval:", x(e, I)));
801
- const i = t++;
802
- x(e, X).call(this, s, n), e.onAfterRender(s, n, i);
803
- };
804
- }
805
- disable() {
806
- x(this, X) && (console.debug("[gltf-progressive] Disabling LODsManager for renderer"), this.renderer.render = x(this, X), U(this, X, void 0));
807
- }
808
- update(t, e) {
809
- this.internalUpdate(t, e);
810
- }
811
- onAfterRender(t, e, s) {
812
- if (this.pause) return;
813
- const r = this.renderer.renderLists.get(t, 0).opaque;
814
- let i = !0;
815
- if (r.length === 1) {
816
- const a = r[0].material;
817
- (a.name === "EffectMaterial" || a.name === "CopyShader") && (i = !1);
818
- }
819
- if ((e.parent && e.parent.type === "CubeCamera" || s >= 1 && e.type === "OrthographicCamera") && (i = !1), i) {
820
- if (xt || (this.updateInterval === "auto" ? x(this, K) < 40 && x(this, I) < 10 ? (U(this, I, x(this, I) + 1), k && console.warn("↓ Reducing LOD updates", x(this, I), x(this, K).toFixed(0))) : x(this, K) >= 60 && x(this, I) > 1 && (U(this, I, x(this, I) - 1), k && console.warn("↑ Increasing LOD updates", x(this, I), x(this, K).toFixed(0))) : U(this, I, this.updateInterval), x(this, I) > 0 && x(this, j) % x(this, I) != 0))
821
- return;
822
- this.internalUpdate(t, e), this._postprocessPromiseGroups();
823
- }
824
- }
825
- /**
826
- * Update LODs in a scene
827
- */
828
- internalUpdate(t, e) {
829
- var l, c;
830
- const s = this.renderer.renderLists.get(t, 0), n = s.opaque;
831
- this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix, e.matrixWorldInverse);
832
- const r = this.targetTriangleDensity;
833
- for (const d of n) {
834
- if (d.material && (((l = d.geometry) == null ? void 0 : l.type) === "BoxGeometry" || ((c = d.geometry) == null ? void 0 : c.type) === "BufferGeometry") && (d.material.name === "SphericalGaussianBlur" || d.material.name == "BackgroundCubeMaterial" || d.material.name === "CubemapFromEquirect" || d.material.name === "EquirectangularToCubeUV")) {
835
- k && (d.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] || (d.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] = !0, console.warn("Ignoring skybox or BLIT object", d, d.material.name, d.material.type)));
836
- continue;
837
- }
838
- switch (d.material.type) {
839
- case "LineBasicMaterial":
840
- case "LineDashedMaterial":
841
- case "PointsMaterial":
842
- case "ShadowMaterial":
843
- case "MeshDistanceMaterial":
844
- case "MeshDepthMaterial":
845
- continue;
846
- }
847
- if (k === "color" && d.material && !d.object.progressive_debug_color) {
848
- d.object.progressive_debug_color = !0;
849
- const f = Math.random() * 16777215, D = new et({ color: f });
850
- d.object.material = D;
851
- }
852
- const h = d.object;
853
- (h instanceof te || h.isMesh) && this.updateLODs(t, e, h, r);
854
- }
855
- const i = s.transparent;
856
- for (const d of i) {
857
- const h = d.object;
858
- (h instanceof te || h.isMesh) && this.updateLODs(t, e, h, r);
859
- }
860
- const a = s.transmissive;
861
- for (const d of a) {
862
- const h = d.object;
863
- (h instanceof te || h.isMesh) && this.updateLODs(t, e, h, r);
864
- }
865
- }
866
- /** Update the LOD levels for the renderer. */
867
- updateLODs(t, e, s, n) {
868
- var a, l;
869
- s.userData || (s.userData = {});
870
- let r = s[Se];
871
- if (r || (r = new wt(), s[Se] = r), r.frames++ < 2)
872
- return;
873
- for (const c of Q)
874
- (a = c.onBeforeUpdateLOD) == null || a.call(c, this.renderer, t, e, s);
875
- const i = y.overrideGlobalLodLevel !== void 0 ? y.overrideGlobalLodLevel : ee;
876
- i >= 0 ? ($.mesh_lod = i, $.texture_lod = i) : (this.calculateLodLevel(e, s, r, n, $), $.mesh_lod = Math.round($.mesh_lod), $.texture_lod = Math.round($.texture_lod)), $.mesh_lod >= 0 && this.loadProgressiveMeshes(s, $.mesh_lod), s.material && $.texture_lod >= 0 && this.loadProgressiveTextures(s.material, $.texture_lod), L && s.material && !s.isGizmo && We(s.material);
877
- for (const c of Q)
878
- (l = c.onAfterUpdatedLOD) == null || l.call(c, this.renderer, t, e, s, $);
879
- r.lastLodLevel_Mesh = $.mesh_lod, r.lastLodLevel_Texture = $.texture_lod;
880
- }
881
- /** Load progressive textures for the given material
882
- * @param material the material to load the textures for
883
- * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
884
- * @returns Promise with true if the LOD was loaded, false if not
885
- */
886
- loadProgressiveTextures(t, e) {
887
- if (!t) return;
888
- if (Array.isArray(t)) {
889
- for (const r of t)
890
- this.loadProgressiveTextures(r, e);
891
- return;
892
- }
893
- let s = !1;
894
- (t[H] === void 0 || e < t[H]) && (s = !0);
895
- const n = t["DEBUG:LOD"];
896
- if (n != null && (s = t[H] != n, e = n), s) {
897
- t[H] = e;
898
- const r = z.assignTextureLOD(t, e).then((i) => {
899
- this._lodchangedlisteners.forEach((a) => a({ type: "texture", level: e, object: t }));
900
- });
901
- me.addPromise("texture", t, r, this._newPromiseGroups);
902
- }
903
- }
904
- /** Load progressive meshes for the given mesh
905
- * @param mesh the mesh to load the LOD for
906
- * @param index the index of the mesh if it's part of a group
907
- * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
908
- * @returns Promise with true if the LOD was loaded, false if not
909
- */
910
- loadProgressiveMeshes(t, e) {
911
- if (!t) return Promise.resolve(null);
912
- let s = t[H] !== e;
913
- const n = t["DEBUG:LOD"];
914
- if (n != null && (s = t[H] != n, e = n), s) {
915
- t[H] = e;
916
- const r = t.geometry, i = z.assignMeshLOD(t, e).then((a) => (a && t[H] == e && r != t.geometry && this._lodchangedlisteners.forEach((l) => l({ type: "mesh", level: e, object: t })), a));
917
- return me.addPromise("mesh", t, i, this._newPromiseGroups), i;
918
- }
919
- return Promise.resolve(null);
920
- }
921
- static isInside(t, e) {
922
- const s = t.min, n = t.max, r = (s.x + n.x) * 0.5, i = (s.y + n.y) * 0.5;
923
- return this._tempPtInside.set(r, i, s.z).applyMatrix4(e).z < 0;
924
- }
925
- calculateLodLevel(t, e, s, n, r) {
926
- var b, B, J;
927
- if (!e) {
928
- r.mesh_lod = -1, r.texture_lod = -1;
929
- return;
930
- }
931
- if (!t) {
932
- r.mesh_lod = -1, r.texture_lod = -1;
933
- return;
934
- }
935
- let a = 10 + 1, l = !1;
936
- if (k && e["DEBUG:LOD"] != null)
937
- return e["DEBUG:LOD"];
938
- const c = (b = z.getMeshLODExtension(e.geometry)) == null ? void 0 : b.lods, d = z.getPrimitiveIndex(e.geometry), h = c && c.length > 0, f = z.getMaterialMinMaxLODsCount(e.material), D = (f == null ? void 0 : f.min_count) != 1 / 0 && f.min_count > 0 && f.max_count > 0;
939
- if (!h && !D) {
940
- r.mesh_lod = 0, r.texture_lod = 0;
941
- return;
942
- }
943
- h || (l = !0, a = 0);
944
- const v = this.renderer.domElement.clientHeight || this.renderer.domElement.height;
945
- let P = e.geometry.boundingBox;
946
- if (e.type === "SkinnedMesh") {
947
- const g = e;
948
- if (!g.boundingBox)
949
- g.computeBoundingBox();
950
- else if (this.skinnedMeshAutoUpdateBoundsInterval > 0) {
951
- if (!g[y.$skinnedMeshBoundsOffset]) {
952
- const A = y.skinnedMeshBoundsFrameOffsetCounter++;
953
- g[y.$skinnedMeshBoundsOffset] = A;
954
- }
955
- const w = g[y.$skinnedMeshBoundsOffset];
956
- if ((s.frames + w) % this.skinnedMeshAutoUpdateBoundsInterval === 0) {
957
- const A = de(g), F = g.geometry;
958
- A && (g.geometry = A), g.computeBoundingBox(), g.geometry = F;
959
- }
960
- }
961
- P = g.boundingBox;
962
- }
963
- if (P) {
964
- const g = t;
965
- if (e.geometry.attributes.color && e.geometry.attributes.color.count < 100 && e.geometry.boundingSphere) {
966
- this._sphere.copy(e.geometry.boundingSphere), this._sphere.applyMatrix4(e.matrixWorld);
967
- const p = t.getWorldPosition(this._tempWorldPosition);
968
- if (this._sphere.containsPoint(p)) {
969
- r.mesh_lod = 0, r.texture_lod = 0;
970
- return;
971
- }
972
- }
973
- if (this._tempBox.copy(P), this._tempBox.applyMatrix4(e.matrixWorld), g.isPerspectiveCamera && y.isInside(this._tempBox, this.projectionScreenMatrix)) {
974
- r.mesh_lod = 0, r.texture_lod = 0;
975
- return;
976
- }
977
- if (this._tempBox.applyMatrix4(this.projectionScreenMatrix), this.renderer.xr.enabled && g.isPerspectiveCamera && g.fov > 70) {
978
- const p = this._tempBox.min, M = this._tempBox.max;
979
- let E = p.x, T = p.y, N = M.x, ie = M.y;
980
- const ce = 2, De = 1.5, fe = (p.x + M.x) * 0.5, he = (p.y + M.y) * 0.5;
981
- E = (E - fe) * ce + fe, T = (T - he) * ce + he, N = (N - fe) * ce + fe, ie = (ie - he) * ce + he;
982
- const Ye = E < 0 && N > 0 ? 0 : Math.min(Math.abs(p.x), Math.abs(M.x)), He = T < 0 && ie > 0 ? 0 : Math.min(Math.abs(p.y), Math.abs(M.y)), Me = Math.max(Ye, He);
983
- s.lastCentrality = (De - Me) * (De - Me) * (De - Me);
984
- } else
985
- s.lastCentrality = 1;
986
- const w = this._tempBox.getSize(this._tempBoxSize);
987
- w.multiplyScalar(0.5), screen.availHeight > 0 && v > 0 && w.multiplyScalar(v / screen.availHeight), t.isPerspectiveCamera ? w.x *= t.aspect : t.isOrthographicCamera;
988
- const A = t.matrixWorldInverse, F = this._tempBox2;
989
- F.copy(P), F.applyMatrix4(e.matrixWorld), F.applyMatrix4(A);
990
- const S = F.getSize(this._tempBox2Size), Z = Math.max(S.x, S.y);
991
- if (Math.max(w.x, w.y) != 0 && Z != 0 && (w.z = S.z / Math.max(S.x, S.y) * Math.max(w.x, w.y)), s.lastScreenCoverage = Math.max(w.x, w.y, w.z), s.lastScreenspaceVolume.copy(w), s.lastScreenCoverage *= s.lastCentrality, k && y.debugDrawLine) {
992
- const p = this.tempMatrix.copy(this.projectionScreenMatrix);
993
- p.invert();
994
- const M = y.corner0, E = y.corner1, T = y.corner2, N = y.corner3;
995
- M.copy(this._tempBox.min), E.copy(this._tempBox.max), E.x = M.x, T.copy(this._tempBox.max), T.y = M.y, N.copy(this._tempBox.max);
996
- const ie = (M.z + N.z) * 0.5;
997
- M.z = E.z = T.z = N.z = ie, M.applyMatrix4(p), E.applyMatrix4(p), T.applyMatrix4(p), N.applyMatrix4(p), y.debugDrawLine(M, E, 255), y.debugDrawLine(M, T, 255), y.debugDrawLine(E, N, 255), y.debugDrawLine(T, N, 255);
998
- }
999
- let O = 999;
1000
- if (c && s.lastScreenCoverage > 0)
1001
- for (let p = 0; p < c.length; p++) {
1002
- const M = c[p], T = (((B = M.densities) == null ? void 0 : B[d]) || M.density || 1e-5) / s.lastScreenCoverage;
1003
- if (d > 0 && Be() && !M.densities && !globalThis["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"] && (window["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"] = !0, console.warn("[Needle Progressive] Detected usage of mesh without primitive densities. This might cause incorrect LOD level selection: Consider re-optimizing your model by updating your Needle Integration, Needle glTF Pipeline or running optimization again on Needle Cloud.")), T < n) {
1004
- O = p;
1005
- break;
1006
- }
1007
- }
1008
- O < a && (a = O, l = !0);
1009
- }
1010
- if (l ? r.mesh_lod = a : r.mesh_lod = s.lastLodLevel_Mesh, k && r.mesh_lod != s.lastLodLevel_Mesh) {
1011
- const w = c == null ? void 0 : c[r.mesh_lod];
1012
- w && console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} → ${r.mesh_lod} (${w.density.toFixed(0)}) - ${e.name}`);
1013
- }
1014
- if (D) {
1015
- const g = "saveData" in globalThis.navigator && globalThis.navigator.saveData === !0;
1016
- if (s.lastLodLevel_Texture < 0) {
1017
- if (r.texture_lod = f.max_count - 1, k) {
1018
- const w = f.lods[f.max_count - 1];
1019
- k && console.log(`First Texture LOD ${r.texture_lod} (${w.max_height}px) - ${e.name}`);
1020
- }
1021
- } else {
1022
- const w = s.lastScreenspaceVolume.x + s.lastScreenspaceVolume.y + s.lastScreenspaceVolume.z;
1023
- let A = s.lastScreenCoverage * 4;
1024
- ((J = this.context) == null ? void 0 : J.engine) === "model-viewer" && (A *= 1.5);
1025
- const S = v / window.devicePixelRatio * A;
1026
- let Z = !1;
1027
- for (let C = f.lods.length - 1; C >= 0; C--) {
1028
- const O = f.lods[C];
1029
- if (!(g && O.max_height >= 2048) && !(ft() && O.max_height > 4096) && (O.max_height > S || !Z && C === 0)) {
1030
- if (Z = !0, r.texture_lod = C, r.texture_lod < s.lastLodLevel_Texture) {
1031
- const m = O.max_height;
1032
- k && console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} → ${r.texture_lod} = ${m}px
1033
- Screensize: ${S.toFixed(0)}px, Coverage: ${(100 * s.lastScreenCoverage).toFixed(2)}%, Volume ${w.toFixed(1)}
1034
- ${e.name}`);
1035
- }
1036
- break;
1037
- }
1038
- }
1039
- }
1040
- } else
1041
- r.texture_lod = 0;
1042
- }
1043
- }, I = new WeakMap(), X = new WeakMap(), we = new WeakMap(), j = new WeakMap(), re = new WeakMap(), _e = new WeakMap(), K = new WeakMap(), /**
1044
- * Assign a function to draw debug lines for the LODs. This function will be called with the start and end position of the line and the color of the line when the `debugprogressive` query parameter is set.
1045
- */
1046
- u(y, "debugDrawLine"), /**
1047
- * Force override the LOD level for all objects in the scene
1048
- */
1049
- u(y, "overrideGlobalLodLevel"), u(y, "corner0", new V()), u(y, "corner1", new V()), u(y, "corner2", new V()), u(y, "corner3", new V()), u(y, "_tempPtInside", new V()), u(y, "skinnedMeshBoundsFrameOffsetCounter", 0), u(y, "$skinnedMeshBoundsOffset", Symbol("gltf-progressive-skinnedMeshBoundsOffset")), y);
1050
- class wt {
1051
- constructor() {
1052
- u(this, "frames", 0);
1053
- u(this, "lastLodLevel_Mesh", -1);
1054
- u(this, "lastLodLevel_Texture", -1);
1055
- u(this, "lastScreenCoverage", 0);
1056
- u(this, "lastScreenspaceVolume", new V());
1057
- u(this, "lastCentrality", 0);
1058
- }
1059
- }
1060
- const ke = Symbol("NEEDLE_mesh_lod"), ge = Symbol("NEEDLE_texture_lod");
1061
- let le = null;
1062
- function Xe() {
1063
- const o = _t();
1064
- o && (o.mapURLs(function(t) {
1065
- return Re(), t;
1066
- }), Re(), le == null || le.disconnect(), le = new MutationObserver((t) => {
1067
- t.forEach((e) => {
1068
- e.addedNodes.forEach((s) => {
1069
- s instanceof HTMLElement && s.tagName.toLowerCase() === "model-viewer" && Ke(s);
1070
- });
1071
- });
1072
- }), le.observe(document, { childList: !0, subtree: !0 }));
1073
- }
1074
- function _t() {
1075
- if (typeof customElements > "u") return null;
1076
- const o = customElements.get("model-viewer");
1077
- return o || (customElements.whenDefined("model-viewer").then(() => {
1078
- console.debug("[gltf-progressive] model-viewer defined"), Xe();
1079
- }), null);
1080
- }
1081
- function Re() {
1082
- if (typeof document > "u") return;
1083
- document.querySelectorAll("model-viewer").forEach((t) => {
1084
- Ke(t);
1085
- });
1086
- }
1087
- const Fe = /* @__PURE__ */ new WeakSet();
1088
- let Dt = 0;
1089
- function Ke(o) {
1090
- if (!o || Fe.has(o))
1091
- return null;
1092
- Fe.add(o), console.debug("[gltf-progressive] found new model-viewer..." + ++Dt + `
1093
- `, o.getAttribute("src"));
1094
- let t = null, e = null, s = null;
1095
- for (let n = o; n != null; n = Object.getPrototypeOf(n)) {
1096
- const r = Object.getOwnPropertySymbols(n), i = r.find((c) => c.toString() == "Symbol(renderer)"), a = r.find((c) => c.toString() == "Symbol(scene)"), l = r.find((c) => c.toString() == "Symbol(needsRender)");
1097
- !t && i != null && (t = o[i].threeRenderer), !e && a != null && (e = o[a]), !s && l != null && (s = o[l]);
1098
- }
1099
- if (t && e) {
1100
- let n = function() {
1101
- if (s) {
1102
- let i = 0, a = setInterval(() => {
1103
- if (i++ > 5) {
1104
- clearInterval(a);
1105
- return;
1106
- }
1107
- s == null || s.call(o);
1108
- }, 300);
1109
- }
1110
- };
1111
- console.debug("[gltf-progressive] setup model-viewer");
1112
- const r = xe.get(t, { engine: "model-viewer" });
1113
- return xe.addPlugin(new Mt()), r.enable(), r.addEventListener("changed", () => {
1114
- s == null || s.call(o);
1115
- }), o.addEventListener("model-visibility", (i) => {
1116
- i.detail.visible && (s == null || s.call(o));
1117
- }), o.addEventListener("load", () => {
1118
- n();
1119
- }), () => {
1120
- r.disable();
1121
- };
1122
- }
1123
- return null;
1124
- }
1125
- class Mt {
1126
- constructor() {
1127
- u(this, "_didWarnAboutMissingUrl", !1);
1128
- }
1129
- onBeforeUpdateLOD(t, e, s, n) {
1130
- this.tryParseMeshLOD(e, n), this.tryParseTextureLOD(e, n);
1131
- }
1132
- getUrl(t) {
1133
- if (!t)
1134
- return null;
1135
- let e = t.getAttribute("src");
1136
- return e || (e = t.src), e || (this._didWarnAboutMissingUrl || console.warn("No url found in modelviewer", t), this._didWarnAboutMissingUrl = !0), e;
1137
- }
1138
- tryGetCurrentGLTF(t) {
1139
- return t._currentGLTF;
1140
- }
1141
- tryGetCurrentModelViewer(t) {
1142
- return t.element;
1143
- }
1144
- tryParseTextureLOD(t, e) {
1145
- if (e[ge] == !0) return;
1146
- e[ge] = !0;
1147
- const s = this.tryGetCurrentGLTF(t), n = this.tryGetCurrentModelViewer(t), r = this.getUrl(n);
1148
- if (r && s && e.material) {
1149
- let i = function(l) {
1150
- var d, h, f;
1151
- if (l[ge] == !0) return;
1152
- l[ge] = !0, l.userData && (l.userData.LOD = -1);
1153
- const c = Object.keys(l);
1154
- for (let D = 0; D < c.length; D++) {
1155
- const v = c[D], P = l[v];
1156
- if ((P == null ? void 0 : P.isTexture) === !0) {
1157
- const b = (h = (d = P.userData) == null ? void 0 : d.associations) == null ? void 0 : h.textures;
1158
- if (b == null) continue;
1159
- const B = s.parser.json.textures[b];
1160
- if (!B) {
1161
- console.warn("Texture data not found for texture index " + b);
1162
- continue;
1163
- }
1164
- if ((f = B == null ? void 0 : B.extensions) != null && f[W]) {
1165
- const J = B.extensions[W];
1166
- J && r && z.registerTexture(r, P, J.lods.length, b, J);
1167
- }
1168
- }
1169
- }
1170
- };
1171
- const a = e.material;
1172
- if (Array.isArray(a)) for (const l of a) i(l);
1173
- else i(a);
1174
- }
1175
- }
1176
- tryParseMeshLOD(t, e) {
1177
- var i, a;
1178
- if (e[ke] == !0) return;
1179
- e[ke] = !0;
1180
- const s = this.tryGetCurrentModelViewer(t), n = this.getUrl(s);
1181
- if (!n)
1182
- return;
1183
- const r = (a = (i = e.userData) == null ? void 0 : i.gltfExtensions) == null ? void 0 : a[W];
1184
- if (r && n) {
1185
- const l = e.uuid;
1186
- z.registerMesh(n, l, e, 0, r.lods.length, r);
1187
- }
1188
- }
1189
- }
1190
- function vt(o, t, e, s) {
1191
- ze(t), qe(e), Ve(e, {
1192
- progressive: !0,
1193
- ...s == null ? void 0 : s.hints
1194
- }), e.register((r) => new z(r, o));
1195
- const n = xe.get(t);
1196
- return (s == null ? void 0 : s.enableLODsManager) !== !1 && n.enable(), n;
1197
- }
1198
- Xe();
1199
- if (!gt) {
1200
- const o = {
1201
- gltfProgressive: {
1202
- useNeedleProgressive: vt,
1203
- LODsManager: xe,
1204
- configureLoader: Ve,
1205
- getRaycastMesh: de,
1206
- useRaycastMeshes: mt
1207
- }
1208
- };
1209
- if (!globalThis.Needle)
1210
- globalThis.Needle = o;
1211
- else
1212
- for (const t in o)
1213
- globalThis.Needle[t] = o[t];
1214
- }
1215
- export {
1216
- xe as LODsManager,
1217
- z as NEEDLE_progressive,
1218
- qe as addDracoAndKTX2Loaders,
1219
- Ve as configureLoader,
1220
- ze as createLoaders,
1221
- de as getRaycastMesh,
1222
- lt as setDracoDecoderLocation,
1223
- ut as setKTX2TranscoderLocation
1224
- };