@needle-tools/engine 4.13.1 → 4.14.0-beta

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 (141) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/components.needle.json +1 -1
  3. package/dist/generateMeshBVH.worker-DiCnZlf3.js +21 -0
  4. package/dist/gltf-progressive-Bm_6aEi4.js +1528 -0
  5. package/dist/gltf-progressive-BttGBXw6.umd.cjs +10 -0
  6. package/dist/gltf-progressive-T5WKTux5.min.js +10 -0
  7. package/dist/loader.worker-BqODMeeW.js +23 -0
  8. package/dist/{materialx-B9ddsHcF.min.js → materialx-CJyQZtjt.min.js} +1 -1
  9. package/dist/{materialx-fkoFuRh3.js → materialx-DMs1E08Z.js} +2 -2
  10. package/dist/{materialx-BF23AVE8.umd.cjs → materialx-DaKKOoVk.umd.cjs} +1 -1
  11. package/dist/needle-engine.bundle-BW2VusZV.min.js +1646 -0
  12. package/dist/{needle-engine.bundle-tjI5Fq2c.umd.cjs → needle-engine.bundle-Cb5bKEqa.umd.cjs} +152 -159
  13. package/dist/{needle-engine.bundle-DauZUYl7.js → needle-engine.bundle-D9VPvp5o.js} +7798 -7497
  14. package/dist/needle-engine.d.ts +779 -42
  15. package/dist/needle-engine.js +416 -415
  16. package/dist/needle-engine.min.js +1 -1
  17. package/dist/needle-engine.umd.cjs +1 -1
  18. package/dist/{postprocessing-BVNrgYZK.min.js → postprocessing-CctM1XIO.min.js} +1 -1
  19. package/dist/{postprocessing-DdM-tz1j.js → postprocessing-DGm6qJ-I.js} +2 -2
  20. package/dist/{postprocessing-CI2TjWpu.umd.cjs → postprocessing-Dbl2PJpd.umd.cjs} +1 -1
  21. package/dist/{three-BW2s1Yl-.umd.cjs → three-BjYim-vL.umd.cjs} +4 -4
  22. package/dist/{three-VvRoMeIN.js → three-Bvk2VKbF.js} +4210 -4210
  23. package/dist/{three-I__hSXzr.min.js → three-IG2qPafA.min.js} +33 -33
  24. package/dist/{three-examples-Bpfu6ke_.umd.cjs → three-examples-BMmNgNCN.umd.cjs} +1 -1
  25. package/dist/{three-examples-BhfOE7NG.js → three-examples-CMYCd5nH.js} +1 -1
  26. package/dist/{three-examples-D8zAE_7t.min.js → three-examples-CQl1fFZp.min.js} +1 -1
  27. package/dist/{three-mesh-ui-C3QbemOV.min.js → three-mesh-ui-5HVE2RV-.min.js} +1 -1
  28. package/dist/{three-mesh-ui-CcMp-FQm.js → three-mesh-ui-BlakAItG.js} +1 -1
  29. package/dist/{three-mesh-ui-BU55xDxJ.umd.cjs → three-mesh-ui-D828VbQp.umd.cjs} +1 -1
  30. package/dist/{vendor-DW7zqjuT.min.js → vendor-BxK0WKmT.min.js} +1 -1
  31. package/dist/{vendor-COVQl0b8.umd.cjs → vendor-CIDkyBaO.umd.cjs} +1 -1
  32. package/dist/{vendor-BiyIZ61v.js → vendor-ixwD-vv2.js} +1 -1
  33. package/lib/engine/api.d.ts +1 -0
  34. package/lib/engine/api.js +1 -0
  35. package/lib/engine/api.js.map +1 -1
  36. package/lib/engine/engine_context.js +12 -2
  37. package/lib/engine/engine_context.js.map +1 -1
  38. package/lib/engine/engine_lightdata.js +8 -6
  39. package/lib/engine/engine_lightdata.js.map +1 -1
  40. package/lib/engine/engine_materialpropertyblock.d.ts +259 -0
  41. package/lib/engine/engine_materialpropertyblock.js +682 -0
  42. package/lib/engine/engine_materialpropertyblock.js.map +1 -0
  43. package/lib/engine/engine_utils.d.ts +1 -0
  44. package/lib/engine/engine_utils.js +1 -0
  45. package/lib/engine/engine_utils.js.map +1 -1
  46. package/lib/engine/engine_utils_screenshot.d.ts +171 -14
  47. package/lib/engine/engine_utils_screenshot.js +65 -0
  48. package/lib/engine/engine_utils_screenshot.js.map +1 -1
  49. package/lib/engine/engine_utils_screenshot.xr.d.ts +1 -1
  50. package/lib/engine/engine_utils_screenshot.xr.js +1 -1
  51. package/lib/engine/extensions/NEEDLE_techniques_webgl.js +3 -0
  52. package/lib/engine/extensions/NEEDLE_techniques_webgl.js.map +1 -1
  53. package/lib/engine/xr/NeedleXRSession.d.ts +5 -0
  54. package/lib/engine/xr/NeedleXRSession.js +5 -0
  55. package/lib/engine/xr/NeedleXRSession.js.map +1 -1
  56. package/lib/engine-components/Camera.js.map +1 -1
  57. package/lib/engine-components/DropListener.js.map +1 -1
  58. package/lib/engine-components/Duplicatable.js.map +1 -1
  59. package/lib/engine-components/GroundProjection.js.map +1 -1
  60. package/lib/engine-components/NeedleMenu.js.map +1 -1
  61. package/lib/engine-components/NestedGltf.js.map +1 -1
  62. package/lib/engine-components/ReflectionProbe.d.ts +32 -4
  63. package/lib/engine-components/ReflectionProbe.js +58 -88
  64. package/lib/engine-components/ReflectionProbe.js.map +1 -1
  65. package/lib/engine-components/Renderer.d.ts +2 -0
  66. package/lib/engine-components/Renderer.js +30 -6
  67. package/lib/engine-components/Renderer.js.map +1 -1
  68. package/lib/engine-components/RendererLightmap.d.ts +13 -9
  69. package/lib/engine-components/RendererLightmap.js +67 -81
  70. package/lib/engine-components/RendererLightmap.js.map +1 -1
  71. package/lib/engine-components/SeeThrough.d.ts +0 -2
  72. package/lib/engine-components/SeeThrough.js +114 -88
  73. package/lib/engine-components/SeeThrough.js.map +1 -1
  74. package/lib/engine-components/SmoothFollow.js.map +1 -1
  75. package/lib/engine-components/VideoPlayer.js +6 -0
  76. package/lib/engine-components/VideoPlayer.js.map +1 -1
  77. package/lib/engine-components/ui/Button.js.map +1 -1
  78. package/lib/engine-components/ui/Raycaster.js.map +1 -1
  79. package/lib/engine-components/utils/OpenURL.d.ts +1 -0
  80. package/lib/engine-components/utils/OpenURL.js +1 -0
  81. package/lib/engine-components/utils/OpenURL.js.map +1 -1
  82. package/lib/engine-components/web/CursorFollow.d.ts +1 -0
  83. package/lib/engine-components/web/CursorFollow.js +1 -0
  84. package/lib/engine-components/web/CursorFollow.js.map +1 -1
  85. package/lib/engine-components/web/ScrollFollow.d.ts +1 -0
  86. package/lib/engine-components/web/ScrollFollow.js +1 -0
  87. package/lib/engine-components/web/ScrollFollow.js.map +1 -1
  88. package/lib/engine-components/web/ViewBox.d.ts +2 -2
  89. package/lib/engine-components/web/ViewBox.js +2 -2
  90. package/lib/engine-components/web/ViewBox.js.map +1 -1
  91. package/lib/engine-components/webxr/WebARCameraBackground.d.ts +9 -0
  92. package/lib/engine-components/webxr/WebARCameraBackground.js +9 -0
  93. package/lib/engine-components/webxr/WebARCameraBackground.js.map +1 -1
  94. package/lib/engine-components/webxr/WebXR.d.ts +1 -0
  95. package/lib/engine-components/webxr/WebXR.js +1 -0
  96. package/lib/engine-components/webxr/WebXR.js.map +1 -1
  97. package/lib/engine-components/webxr/WebXRPlaneTracking.js.map +1 -1
  98. package/lib/engine-components/webxr/controllers/XRControllerFollow.js.map +1 -1
  99. package/lib/engine-components/webxr/controllers/XRControllerMovement.js.map +1 -1
  100. package/package.json +5 -5
  101. package/plugins/vite/build-pipeline.js +16 -2
  102. package/src/engine/api.ts +1 -0
  103. package/src/engine/engine_context.ts +17 -3
  104. package/src/engine/engine_lightdata.ts +8 -6
  105. package/src/engine/engine_materialpropertyblock.ts +866 -0
  106. package/src/engine/engine_utils.ts +1 -0
  107. package/src/engine/engine_utils_screenshot.ts +241 -17
  108. package/src/engine/engine_utils_screenshot.xr.ts +1 -1
  109. package/src/engine/extensions/NEEDLE_techniques_webgl.ts +3 -0
  110. package/src/engine/xr/NeedleXRSession.ts +5 -0
  111. package/src/engine-components/Camera.ts +2 -2
  112. package/src/engine-components/ContactShadows.ts +1 -1
  113. package/src/engine-components/DropListener.ts +1 -1
  114. package/src/engine-components/Duplicatable.ts +1 -1
  115. package/src/engine-components/GroundProjection.ts +3 -0
  116. package/src/engine-components/NeedleMenu.ts +3 -0
  117. package/src/engine-components/NestedGltf.ts +1 -1
  118. package/src/engine-components/ReflectionProbe.ts +64 -105
  119. package/src/engine-components/Renderer.ts +34 -6
  120. package/src/engine-components/RendererLightmap.ts +75 -87
  121. package/src/engine-components/SeeThrough.ts +124 -109
  122. package/src/engine-components/SmoothFollow.ts +2 -2
  123. package/src/engine-components/VideoPlayer.ts +6 -0
  124. package/src/engine-components/ui/Button.ts +1 -1
  125. package/src/engine-components/ui/Raycaster.ts +1 -1
  126. package/src/engine-components/utils/OpenURL.ts +1 -0
  127. package/src/engine-components/web/CursorFollow.ts +1 -0
  128. package/src/engine-components/web/ScrollFollow.ts +1 -0
  129. package/src/engine-components/web/ViewBox.ts +9 -2
  130. package/src/engine-components/webxr/WebARCameraBackground.ts +12 -3
  131. package/src/engine-components/webxr/WebXR.ts +1 -0
  132. package/src/engine-components/webxr/WebXRPlaneTracking.ts +3 -3
  133. package/src/engine-components/webxr/controllers/XRControllerFollow.ts +1 -1
  134. package/src/engine-components/webxr/controllers/XRControllerMovement.ts +4 -4
  135. package/dist/generateMeshBVH.worker-iyfPIK6R.js +0 -21
  136. package/dist/gltf-progressive-BURrJW0U.umd.cjs +0 -8
  137. package/dist/gltf-progressive-DHLDFNvQ.min.js +0 -8
  138. package/dist/gltf-progressive-eiJCrjLb.js +0 -1400
  139. package/dist/loader.worker-C1GG9A7C.js +0 -23
  140. package/dist/needle-engine.bundle-BNIUpreS.min.js +0 -1653
  141. package/src/include/three/DragControls.js +0 -232
@@ -0,0 +1,1528 @@
1
+ import { BufferGeometry as V, Mesh as X, Box3 as pe, Vector3 as A, Sphere as Se, CompressedTexture as Fe, Texture as F, Matrix3 as We, InterleavedBuffer as Ue, InterleavedBufferAttribute as ze, BufferAttribute as Ne, TextureLoader as qe, Matrix4 as Me, Clock as Ee, MeshStandardMaterial as Ve } from "./three-Bvk2VKbF.js";
2
+ import { DRACOLoader as Xe, KTX2Loader as je, MeshoptDecoder as Ke, GLTFLoader as we } from "./three-examples-CMYCd5nH.js";
3
+ const Ye = "";
4
+ globalThis.GLTF_PROGRESSIVE_VERSION = Ye;
5
+ console.debug("[gltf-progressive] version -");
6
+ let I = "https://www.gstatic.com/draco/versioned/decoders/1.5.7/", j = "https://cdn.needle.tools/static/three/0.179.1/basis2/";
7
+ const He = I, Qe = j, Pe = new URL(I + "draco_decoder.js");
8
+ Pe.searchParams.append("range", "true");
9
+ fetch(Pe, {
10
+ method: "GET",
11
+ headers: {
12
+ Range: "bytes=0-1"
13
+ }
14
+ }).catch((o) => {
15
+ console.debug(`Failed to fetch remote Draco decoder from ${I} (offline: ${typeof navigator < "u" ? navigator.onLine : "unknown"})`), I === He && Ze("./include/draco/"), j === Qe && et("./include/ktx2/");
16
+ }).finally(() => {
17
+ Ce();
18
+ });
19
+ const Je = () => ({
20
+ dracoDecoderPath: I,
21
+ ktx2TranscoderPath: j
22
+ });
23
+ function Ze(o) {
24
+ I = o, C && C[me] != I ? (console.debug("Updating Draco decoder path to " + o), C[me] = I, C.setDecoderPath(I), C.preload()) : console.debug("Setting Draco decoder path to " + o);
25
+ }
26
+ function et(o) {
27
+ j = o, $ && $.transcoderPath != j ? (console.debug("Updating KTX2 transcoder path to " + o), $.setTranscoderPath(j), $.init()) : console.debug("Setting KTX2 transcoder path to " + o);
28
+ }
29
+ function Le(o) {
30
+ return Ce(), o ? $.detectSupport(o) : o !== null && console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"), { dracoLoader: C, ktx2Loader: $, meshoptDecoder: ne };
31
+ }
32
+ function Te(o) {
33
+ o.dracoLoader || o.setDRACOLoader(C), o.ktx2Loader || o.setKTX2Loader($), o.meshoptDecoder || o.setMeshoptDecoder(ne);
34
+ }
35
+ const me = /* @__PURE__ */ Symbol("dracoDecoderPath");
36
+ let C, ne, $;
37
+ function Ce() {
38
+ C || (C = new Xe(), C[me] = I, C.setDecoderPath(I), C.setDecoderConfig({ type: "js" }), C.preload()), $ || ($ = new je(), $.setTranscoderPath(j), $.init()), ne || (ne = Ke);
39
+ }
40
+ const ye = /* @__PURE__ */ new WeakMap();
41
+ function Ae(o, t) {
42
+ let e = ye.get(o);
43
+ e ? e = Object.assign(e, t) : e = t, ye.set(o, e);
44
+ }
45
+ const tt = we.prototype.load;
46
+ function st(...o) {
47
+ const t = ye.get(this);
48
+ let e = o[0];
49
+ const s = new URL(e, window.location.href);
50
+ if (s.hostname.endsWith("needle.tools")) {
51
+ const i = t?.progressive !== void 0 ? t.progressive : !0, n = t?.usecase ? t.usecase : "default";
52
+ i ? this.requestHeader.Accept = `*/*;progressive=allowed;usecase=${n}` : this.requestHeader.Accept = `*/*;usecase=${n}`, e = s.toString();
53
+ }
54
+ return o[0] = e, tt?.call(this, ...o);
55
+ }
56
+ we.prototype.load = st;
57
+ N("debugprogressive");
58
+ function N(o) {
59
+ if (typeof window > "u") return !1;
60
+ const e = new URL(window.location.href).searchParams.get(o);
61
+ return e == null || e === "0" || e === "false" ? !1 : e === "" ? !0 : e;
62
+ }
63
+ function rt(o, t) {
64
+ if (t === void 0 || o === void 0 || t.startsWith("./") || t.startsWith("http") || t.startsWith("data:") || t.startsWith("blob:"))
65
+ return t;
66
+ const e = o.lastIndexOf("/");
67
+ if (e >= 0) {
68
+ const s = o.substring(0, e + 1);
69
+ for (; s.endsWith("/") && t.startsWith("/"); ) t = t.substring(1);
70
+ return s + t;
71
+ }
72
+ return t;
73
+ }
74
+ function ke() {
75
+ return H !== void 0 || (H = /iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent), N("debugprogressive") && console.log("[glTF Progressive]: isMobileDevice", H)), H;
76
+ }
77
+ let H;
78
+ function ve() {
79
+ if (typeof window > "u") return !1;
80
+ 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);
81
+ return o.hostname === "127.0.0.1" || t;
82
+ }
83
+ class it {
84
+ constructor(t = 100, e = {}) {
85
+ this.maxConcurrent = t, this.debug = e.debug ?? !1, window.requestAnimationFrame(this.tick);
86
+ }
87
+ _running = /* @__PURE__ */ new Map();
88
+ _queue = [];
89
+ debug = !1;
90
+ tick = () => {
91
+ this.internalUpdate(), setTimeout(this.tick, 10);
92
+ };
93
+ /**
94
+ * 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.
95
+ */
96
+ slot(t) {
97
+ return this.debug && console.debug(`[PromiseQueue]: Requesting slot for key ${t}, running: ${this._running.size}, waiting: ${this._queue.length}`), new Promise((e) => {
98
+ this._queue.push({ key: t, resolve: e });
99
+ });
100
+ }
101
+ add(t, e) {
102
+ this._running.has(t) || (this._running.set(t, e), e.finally(() => {
103
+ this._running.delete(t), this.debug && console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${t})`);
104
+ }), this.debug && console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${t})`));
105
+ }
106
+ internalUpdate() {
107
+ const t = this.maxConcurrent - this._running.size;
108
+ for (let e = 0; e < t && this._queue.length > 0; e++) {
109
+ this.debug && console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);
110
+ const { key: s, resolve: r } = this._queue.shift();
111
+ r({
112
+ use: (i) => this.add(s, i)
113
+ });
114
+ }
115
+ }
116
+ }
117
+ function nt(o) {
118
+ const t = o.image?.width ?? 0, e = o.image?.height ?? 0, s = o.image?.depth ?? 1, r = Math.floor(Math.log2(Math.max(t, e, s))) + 1, i = ot(o);
119
+ return t * e * s * i * (1 - Math.pow(0.25, r)) / (1 - 0.25);
120
+ }
121
+ function ot(o) {
122
+ let t = 4;
123
+ const e = o.format;
124
+ e === 1024 || e === 1025 ? t = 1 : e === 1026 || e === 1027 ? t = 2 : e === 1022 || e === 1029 ? t = 3 : (e === 1023 || e === 1033) && (t = 4);
125
+ let s = 1;
126
+ const r = o.type;
127
+ return r === 1009 || r === 1010 ? s = 1 : r === 1011 || r === 1012 ? s = 2 : r === 1013 || r === 1014 || r === 1015 ? s = 4 : r === 1016 && (s = 2), t * s;
128
+ }
129
+ const at = typeof window > "u" && typeof document > "u", xe = /* @__PURE__ */ Symbol("needle:raycast-mesh");
130
+ function ee(o) {
131
+ return o?.[xe] instanceof V ? o[xe] : null;
132
+ }
133
+ function lt(o, t) {
134
+ if ((o.type === "Mesh" || o.type === "SkinnedMesh") && !ee(o)) {
135
+ const s = ct(t);
136
+ s.userData = { isRaycastMesh: !0 }, o[xe] = s;
137
+ }
138
+ }
139
+ function ut(o = !0) {
140
+ if (o) {
141
+ if (Q) return;
142
+ const t = Q = X.prototype.raycast;
143
+ X.prototype.raycast = function(e, s) {
144
+ const r = this, i = ee(r);
145
+ let n;
146
+ i && r.isMesh && (n = r.geometry, r.geometry = i), t.call(this, e, s), n && (r.geometry = n);
147
+ };
148
+ } else {
149
+ if (!Q) return;
150
+ X.prototype.raycast = Q, Q = null;
151
+ }
152
+ }
153
+ let Q = null;
154
+ function ct(o) {
155
+ const t = new V();
156
+ for (const e in o.attributes)
157
+ t.setAttribute(e, o.getAttribute(e));
158
+ return t.setIndex(o.getIndex()), t;
159
+ }
160
+ const z = new Array(), f = N("debugprogressive");
161
+ let Z, E = -1;
162
+ if (f) {
163
+ let o = function() {
164
+ E += 1, E >= t && (E = -1), console.log(`Toggle LOD level [${E}]`);
165
+ }, t = 6;
166
+ window.addEventListener("keyup", (e) => {
167
+ e.key === "p" && o(), e.key === "w" && (Z = !Z, console.log(`Toggle wireframe [${Z}]`));
168
+ const s = parseInt(e.key);
169
+ !isNaN(s) && s >= 0 && (E = s, console.log(`Set LOD level to [${E}]`));
170
+ });
171
+ }
172
+ function Re(o) {
173
+ if (f && Z !== void 0)
174
+ if (Array.isArray(o))
175
+ for (const t of o)
176
+ Re(t);
177
+ else o && "wireframe" in o && (o.wireframe = Z === !0);
178
+ }
179
+ const J = new Array();
180
+ let dt = 0;
181
+ const ft = ke() ? 2 : 10;
182
+ function ht(o) {
183
+ if (J.length < ft) {
184
+ const s = J.length;
185
+ f && console.warn(`[Worker] Creating new worker #${s}`);
186
+ const r = _e.createWorker(o || {});
187
+ return J.push(r), r;
188
+ }
189
+ const t = dt++ % J.length;
190
+ return J[t];
191
+ }
192
+ class _e {
193
+ constructor(t, e) {
194
+ this.worker = t, this._debug = e.debug ?? !1, t.onmessage = (s) => {
195
+ const r = s.data;
196
+ switch (this._debug && console.log("[Worker] EVENT", r), r.type) {
197
+ case "loaded-gltf":
198
+ for (const i of this._running)
199
+ if (i.url === r.result.url) {
200
+ gt(r.result), i.resolve(r.result);
201
+ const n = i.url;
202
+ n.startsWith("blob:") && URL.revokeObjectURL(n);
203
+ }
204
+ }
205
+ }, t.onerror = (s) => {
206
+ console.error("[Worker] Error in gltf-progressive worker:", s);
207
+ }, t.postMessage({
208
+ type: "init"
209
+ });
210
+ }
211
+ static async createWorker(t) {
212
+ const e = /* new-worker */ new Worker(URL.createObjectURL(new Blob(["import '" + `${new URL('./loader.worker-BqODMeeW.js', import.meta.url).toString()}` + "';"], { type: 'text/javascript' })), {
213
+ type: "module"
214
+ });
215
+ return new _e(e, t);
216
+ }
217
+ _running = [];
218
+ _webglRenderer = null;
219
+ async load(t, e) {
220
+ const s = Je();
221
+ let r = e?.renderer;
222
+ r || (this._webglRenderer ??= (async () => {
223
+ const { WebGLRenderer: u } = await import("./three-Bvk2VKbF.js").then((c) => c.THREE);
224
+ return new u();
225
+ })(), r = await this._webglRenderer);
226
+ const l = Le(r).ktx2Loader.workerConfig;
227
+ t instanceof URL ? t = t.toString() : t.startsWith("file:") ? t = URL.createObjectURL(new Blob([t])) : !t.startsWith("blob:") && !t.startsWith("http:") && !t.startsWith("https:") && (t = new URL(t, window.location.href).toString());
228
+ const a = {
229
+ type: "load",
230
+ url: t,
231
+ dracoDecoderPath: s.dracoDecoderPath,
232
+ ktx2TranscoderPath: s.ktx2TranscoderPath,
233
+ ktx2LoaderConfig: l
234
+ };
235
+ return this._debug && console.debug("[Worker] Sending load request", a), this.worker.postMessage(a), new Promise((u) => {
236
+ this._running.push({
237
+ url: t.toString(),
238
+ resolve: u
239
+ });
240
+ });
241
+ }
242
+ _debug = !1;
243
+ }
244
+ function gt(o) {
245
+ for (const t of o.geometries) {
246
+ const e = t.geometry, s = new V();
247
+ if (s.name = e.name || "", e.index) {
248
+ const r = e.index;
249
+ s.setIndex(ue(r));
250
+ }
251
+ for (const r in e.attributes) {
252
+ const i = e.attributes[r], n = ue(i);
253
+ s.setAttribute(r, n);
254
+ }
255
+ if (e.morphAttributes)
256
+ for (const r in e.morphAttributes) {
257
+ const n = e.morphAttributes[r].map((l) => ue(l));
258
+ s.morphAttributes[r] = n;
259
+ }
260
+ if (s.morphTargetsRelative = e.morphTargetsRelative ?? !1, s.boundingBox = new pe(), s.boundingBox.min = new A(
261
+ e.boundingBox?.min.x,
262
+ e.boundingBox?.min.y,
263
+ e.boundingBox?.min.z
264
+ ), s.boundingBox.max = new A(
265
+ e.boundingBox?.max.x,
266
+ e.boundingBox?.max.y,
267
+ e.boundingBox?.max.z
268
+ ), s.boundingSphere = new Se(
269
+ new A(
270
+ e.boundingSphere?.center.x,
271
+ e.boundingSphere?.center.y,
272
+ e.boundingSphere?.center.z
273
+ ),
274
+ e.boundingSphere?.radius
275
+ ), e.groups)
276
+ for (const r of e.groups)
277
+ s.addGroup(r.start, r.count, r.materialIndex);
278
+ e.userData && (s.userData = e.userData), t.geometry = s;
279
+ }
280
+ for (const t of o.textures) {
281
+ const e = t.texture;
282
+ let s = null;
283
+ if (e.isCompressedTexture) {
284
+ const r = e.mipmaps, i = e.image?.width || e.source?.data?.width || -1, n = e.image?.height || e.source?.data?.height || -1;
285
+ s = new Fe(
286
+ r,
287
+ i,
288
+ n,
289
+ e.format,
290
+ e.type,
291
+ e.mapping,
292
+ e.wrapS,
293
+ e.wrapT,
294
+ e.magFilter,
295
+ e.minFilter,
296
+ e.anisotropy,
297
+ e.colorSpace
298
+ );
299
+ } else
300
+ s = new F(
301
+ e.image,
302
+ e.mapping,
303
+ e.wrapS,
304
+ e.wrapT,
305
+ e.magFilter,
306
+ e.minFilter,
307
+ e.format,
308
+ e.type,
309
+ e.anisotropy,
310
+ e.colorSpace
311
+ ), s.mipmaps = e.mipmaps, s.channel = e.channel, s.source.data = e.source.data, s.flipY = e.flipY, s.premultiplyAlpha = e.premultiplyAlpha, s.unpackAlignment = e.unpackAlignment, s.matrix = new We(...e.matrix.elements);
312
+ if (!s) {
313
+ console.error("[Worker] Failed to create new texture from received data. Texture is not a CompressedTexture or Texture.");
314
+ continue;
315
+ }
316
+ t.texture = s;
317
+ }
318
+ return o;
319
+ }
320
+ function ue(o) {
321
+ let t = o;
322
+ if ("isInterleavedBufferAttribute" in o && o.isInterleavedBufferAttribute) {
323
+ const e = o.data, s = e.array, r = new Ue(s, e.stride);
324
+ t = new ze(r, o.itemSize, s.byteOffset, o.normalized), t.offset = o.offset;
325
+ } else "isBufferAttribute" in o && o.isBufferAttribute && (t = new Ne(o.array, o.itemSize, o.normalized), t.usage = o.usage, t.gpuType = o.gpuType, t.updateRanges = o.updateRanges);
326
+ return t;
327
+ }
328
+ const pt = N("gltf-progressive-worker");
329
+ N("gltf-progressive-reduce-mipmaps");
330
+ const K = N("gltf-progressive-gc"), ce = /* @__PURE__ */ Symbol("needle-progressive-texture"), W = "NEEDLE_progressive";
331
+ class y {
332
+ /** The name of the extension */
333
+ get name() {
334
+ return W;
335
+ }
336
+ // #region PUBLIC API
337
+ static getMeshLODExtension(t) {
338
+ const e = this.getAssignedLODInformation(t);
339
+ return e?.key ? this.lodInfos.get(e.key) : null;
340
+ }
341
+ static getPrimitiveIndex(t) {
342
+ const e = this.getAssignedLODInformation(t)?.index;
343
+ return e ?? -1;
344
+ }
345
+ static getMaterialMinMaxLODsCount(t, e) {
346
+ const s = this, r = "LODS:minmax", i = t[r];
347
+ if (i != null) return i;
348
+ if (e || (e = {
349
+ min_count: 1 / 0,
350
+ max_count: 0,
351
+ lods: []
352
+ }), Array.isArray(t)) {
353
+ for (const l of t)
354
+ this.getMaterialMinMaxLODsCount(l, e);
355
+ return t[r] = e, e;
356
+ }
357
+ if (f === "verbose" && console.log("getMaterialMinMaxLODsCount", t), t.type === "ShaderMaterial" || t.type === "RawShaderMaterial") {
358
+ const l = t;
359
+ for (const a of Object.keys(l.uniforms)) {
360
+ const u = l.uniforms[a].value;
361
+ u?.isTexture === !0 && n(u, e);
362
+ }
363
+ } else if (t.isMaterial)
364
+ for (const l of Object.keys(t)) {
365
+ const a = t[l];
366
+ a?.isTexture === !0 && n(a, e);
367
+ }
368
+ else
369
+ f && console.warn(`[getMaterialMinMaxLODsCount] Unsupported material type: ${t.type}`);
370
+ return t[r] = e, e;
371
+ function n(l, a) {
372
+ const u = s.getAssignedLODInformation(l);
373
+ if (u) {
374
+ const c = s.lodInfos.get(u.key);
375
+ if (c && c.lods) {
376
+ a.min_count = Math.min(a.min_count, c.lods.length), a.max_count = Math.max(a.max_count, c.lods.length);
377
+ for (let m = 0; m < c.lods.length; m++) {
378
+ const w = c.lods[m];
379
+ w.width && (a.lods[m] = a.lods[m] || { min_height: 1 / 0, max_height: 0 }, a.lods[m].min_height = Math.min(a.lods[m].min_height, w.height), a.lods[m].max_height = Math.max(a.lods[m].max_height, w.height));
380
+ }
381
+ }
382
+ }
383
+ }
384
+ }
385
+ /** Check if a LOD level is available for a mesh or a texture
386
+ * @param obj the mesh or texture to check
387
+ * @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
388
+ * @returns true if the LOD level is available (or if any LOD level is available if level is undefined)
389
+ */
390
+ static hasLODLevelAvailable(t, e) {
391
+ if (Array.isArray(t)) {
392
+ for (const i of t)
393
+ if (this.hasLODLevelAvailable(i, e)) return !0;
394
+ return !1;
395
+ }
396
+ if (t.isMaterial === !0) {
397
+ for (const i of Object.keys(t)) {
398
+ const n = t[i];
399
+ if (n && n.isTexture && this.hasLODLevelAvailable(n, e))
400
+ return !0;
401
+ }
402
+ return !1;
403
+ } else if (t.isGroup === !0) {
404
+ for (const i of t.children)
405
+ if (i.isMesh === !0 && this.hasLODLevelAvailable(i, e))
406
+ return !0;
407
+ }
408
+ let s, r;
409
+ if (t.isMesh ? s = t.geometry : (t.isBufferGeometry || t.isTexture) && (s = t), s && s?.userData?.LODS) {
410
+ const i = s.userData.LODS;
411
+ if (r = this.lodInfos.get(i.key), e === void 0) return r != null;
412
+ if (r)
413
+ return Array.isArray(r.lods) ? e < r.lods.length : e === 0;
414
+ }
415
+ return !1;
416
+ }
417
+ /** Load a different resolution of a mesh (if available)
418
+ * @param context the context
419
+ * @param source the sourceid of the file from which the mesh is loaded (this is usually the component's sourceId)
420
+ * @param mesh the mesh to load the LOD for
421
+ * @param level the level of detail to load (0 is the highest resolution)
422
+ * @returns a promise that resolves to the mesh with the requested LOD level
423
+ * @example
424
+ * ```javascript
425
+ * const mesh = this.gameObject as Mesh;
426
+ * NEEDLE_progressive.assignMeshLOD(context, sourceId, mesh, 1).then(mesh => {
427
+ * console.log("Mesh with LOD level 1 loaded", mesh);
428
+ * });
429
+ * ```
430
+ */
431
+ static assignMeshLOD(t, e) {
432
+ if (!t) return Promise.resolve(null);
433
+ if (t instanceof X || t.isMesh === !0) {
434
+ const s = t.geometry, r = this.getAssignedLODInformation(s);
435
+ if (!r)
436
+ return Promise.resolve(null);
437
+ for (const i of z)
438
+ i.onBeforeGetLODMesh?.(t, e);
439
+ return t["LOD:requested level"] = e, y.getOrLoadLOD(s, e).then((i) => {
440
+ if (Array.isArray(i)) {
441
+ const n = r.index || 0;
442
+ i = i[n];
443
+ }
444
+ return t["LOD:requested level"] === e && (delete t["LOD:requested level"], i && s != i && (i?.isBufferGeometry ? t.geometry = i : f && console.error("Invalid LOD geometry", i))), i;
445
+ }).catch((i) => (console.error("Error loading mesh LOD", t, i), null));
446
+ } else f && console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh", t);
447
+ return Promise.resolve(null);
448
+ }
449
+ static assignTextureLOD(t, e = 0) {
450
+ if (!t) return Promise.resolve(null);
451
+ if (t.isMesh === !0) {
452
+ const s = t;
453
+ if (Array.isArray(s.material)) {
454
+ const r = new Array();
455
+ for (const i of s.material) {
456
+ const n = this.assignTextureLOD(i, e);
457
+ r.push(n);
458
+ }
459
+ return Promise.all(r).then((i) => {
460
+ const n = new Array();
461
+ for (const l of i)
462
+ Array.isArray(l) && n.push(...l);
463
+ return n;
464
+ });
465
+ } else
466
+ return this.assignTextureLOD(s.material, e);
467
+ }
468
+ if (t.isMaterial === !0) {
469
+ const s = t, r = [], i = new Array();
470
+ if (s.uniforms && (s.isRawShaderMaterial || s.isShaderMaterial === !0)) {
471
+ const n = s;
472
+ for (const l of Object.keys(n.uniforms)) {
473
+ const a = n.uniforms[l].value;
474
+ if (a?.isTexture === !0) {
475
+ const u = this.assignTextureLODForSlot(a, e, s, l).then((c) => (c && n.uniforms[l].value != c && (n.uniforms[l].value = c, n.uniformsNeedUpdate = !0), c));
476
+ r.push(u), i.push(l);
477
+ }
478
+ }
479
+ } else
480
+ for (const n of Object.keys(s)) {
481
+ const l = s[n];
482
+ if (l?.isTexture === !0) {
483
+ const a = this.assignTextureLODForSlot(l, e, s, n);
484
+ r.push(a), i.push(n);
485
+ }
486
+ }
487
+ return Promise.all(r).then((n) => {
488
+ const l = new Array();
489
+ for (let a = 0; a < n.length; a++) {
490
+ const u = n[a], c = i[a];
491
+ u && u.isTexture === !0 ? l.push({ material: s, slot: c, texture: u, level: e }) : l.push({ material: s, slot: c, texture: null, level: e });
492
+ }
493
+ return l;
494
+ });
495
+ }
496
+ if (t instanceof F || t.isTexture === !0) {
497
+ const s = t;
498
+ return this.assignTextureLODForSlot(s, e, null, null);
499
+ }
500
+ return Promise.resolve(null);
501
+ }
502
+ // #region INTERNAL
503
+ static assignTextureLODForSlot(t, e, s, r) {
504
+ return t?.isTexture !== !0 ? Promise.resolve(null) : r === "glyphMap" ? Promise.resolve(t) : y.getOrLoadLOD(t, e).then((i) => {
505
+ if (Array.isArray(i))
506
+ return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen..."), null;
507
+ if (i?.isTexture === !0) {
508
+ if (i != t && s && r) {
509
+ const n = s[r];
510
+ if (n && !f) {
511
+ const l = this.getAssignedLODInformation(n);
512
+ if (l && l?.level < e)
513
+ return f === "verbose" && console.warn("Assigned texture level is already higher: ", l.level, e, s, n, i), i && i !== n && ((f || K) && console.log(`[gltf-progressive] Disposing rejected lower-quality texture LOD ${e} (assigned is ${l.level})`, i.uuid), i.dispose()), null;
514
+ }
515
+ if (this.trackTextureUsage(i), n && n !== i && this.untrackTextureUsage(n) && (f || K)) {
516
+ const a = this.getAssignedLODInformation(n);
517
+ console.log(`[gltf-progressive] Disposed old texture LOD ${a?.level ?? "?"} → ${e} for ${s.name || s.type}.${r}`, n.uuid);
518
+ }
519
+ s[r] = i;
520
+ }
521
+ return i;
522
+ } else f == "verbose" && console.warn("No LOD found for", t, e);
523
+ return null;
524
+ }).catch((i) => (console.error("Error loading LOD", t, i), null));
525
+ }
526
+ parser;
527
+ url;
528
+ constructor(t) {
529
+ const e = t.options.path;
530
+ f && console.log("Progressive extension registered for", e), this.parser = t, this.url = e;
531
+ }
532
+ _isLoadingMesh;
533
+ loadMesh = (t) => {
534
+ if (this._isLoadingMesh) return null;
535
+ const e = this.parser.json.meshes[t]?.extensions?.[W];
536
+ return e ? (this._isLoadingMesh = !0, this.parser.getDependency("mesh", t).then((s) => (this._isLoadingMesh = !1, s && y.registerMesh(this.url, e.guid, s, e.lods?.length, 0, e), s))) : null;
537
+ };
538
+ // private _isLoadingTexture;
539
+ // loadTexture = (textureIndex: number) => {
540
+ // if (this._isLoadingTexture) return null;
541
+ // const ext = this.parser.json.textures[textureIndex]?.extensions?.[EXTENSION_NAME] as NEEDLE_ext_progressive_texture;
542
+ // if (!ext) return null;
543
+ // this._isLoadingTexture = true;
544
+ // return this.parser.getDependency("texture", textureIndex).then(tex => {
545
+ // this._isLoadingTexture = false;
546
+ // if (tex) {
547
+ // NEEDLE_progressive.registerTexture(this.url, tex as Texture, ext.lods?.length, textureIndex, ext);
548
+ // }
549
+ // return tex;
550
+ // });
551
+ // }
552
+ afterRoot(t) {
553
+ return f && console.log("AFTER", this.url, t), this.parser.json.textures?.forEach((e, s) => {
554
+ if (e?.extensions) {
555
+ const r = e?.extensions[W];
556
+ if (r) {
557
+ if (!r.lods) {
558
+ f && console.warn("Texture has no LODs", r);
559
+ return;
560
+ }
561
+ let i = !1;
562
+ for (const n of this.parser.associations.keys())
563
+ n.isTexture === !0 && this.parser.associations.get(n)?.textures === s && (i = !0, y.registerTexture(this.url, n, r.lods?.length, s, r));
564
+ i || this.parser.getDependency("texture", s).then((n) => {
565
+ n && y.registerTexture(this.url, n, r.lods?.length, s, r);
566
+ });
567
+ }
568
+ }
569
+ }), this.parser.json.meshes?.forEach((e, s) => {
570
+ if (e?.extensions) {
571
+ const r = e?.extensions[W];
572
+ if (r && r.lods) {
573
+ for (const i of this.parser.associations.keys())
574
+ if (i.isMesh) {
575
+ const n = this.parser.associations.get(i);
576
+ n?.meshes === s && y.registerMesh(this.url, r.guid, i, r.lods.length, n.primitives, r);
577
+ }
578
+ }
579
+ }
580
+ }), null;
581
+ }
582
+ /**
583
+ * Register a texture with LOD information
584
+ */
585
+ static registerTexture = (t, e, s, r, i) => {
586
+ if (!e) {
587
+ f && console.error("!! gltf-progressive: Called register texture without texture");
588
+ return;
589
+ }
590
+ if (f) {
591
+ const l = e.image?.width || e.source?.data?.width || 0, a = e.image?.height || e.source?.data?.height || 0;
592
+ console.log(`> gltf-progressive: register texture[${r}] "${e.name || e.uuid}", Current: ${l}x${a}, Max: ${i.lods[0]?.width}x${i.lods[0]?.height}, uuid: ${e.uuid}`, i, e);
593
+ }
594
+ e.source && (e.source[ce] = i);
595
+ const n = i.guid;
596
+ y.assignLODInformation(t, e, n, s, r), y.lodInfos.set(n, i), y.lowresCache.set(n, new WeakRef(e));
597
+ };
598
+ /**
599
+ * Register a mesh with LOD information
600
+ */
601
+ static registerMesh = (t, e, s, r, i, n) => {
602
+ const l = s.geometry;
603
+ if (!l) {
604
+ f && console.warn("gltf-progressive: Register mesh without geometry");
605
+ return;
606
+ }
607
+ l.userData || (l.userData = {}), f && console.log("> Progressive: register mesh " + s.name, { index: i, uuid: s.uuid }, n, s), y.assignLODInformation(t, l, e, r, i), y.lodInfos.set(e, n);
608
+ let u = y.lowresCache.get(e)?.deref();
609
+ u ? u.push(s.geometry) : u = [s.geometry], y.lowresCache.set(e, new WeakRef(u)), r > 0 && !ee(s) && lt(s, l);
610
+ for (const c of z)
611
+ c.onRegisteredNewMesh?.(s, n);
612
+ };
613
+ /**
614
+ * Dispose cached resources to free memory.
615
+ * Call this when a model is removed from the scene to allow garbage collection of its LOD resources.
616
+ * Calls three.js `.dispose()` on cached Textures and BufferGeometries to free GPU memory.
617
+ * Also clears reference counts for disposed textures.
618
+ * @param guid Optional GUID to dispose resources for a specific model. If omitted, all cached resources are cleared.
619
+ */
620
+ static dispose(t) {
621
+ if (t) {
622
+ this.lodInfos.delete(t);
623
+ const e = this.lowresCache.get(t);
624
+ if (e) {
625
+ const s = e.deref();
626
+ if (s) {
627
+ if (s.isTexture) {
628
+ const r = s;
629
+ this.textureRefCounts.delete(r.uuid), r.dispose();
630
+ } else if (Array.isArray(s))
631
+ for (const r of s) r.dispose();
632
+ }
633
+ this.lowresCache.delete(t);
634
+ }
635
+ for (const [s, r] of this.cache)
636
+ s.includes(t) && (this._disposeCacheEntry(r), this.cache.delete(s));
637
+ } else {
638
+ this.lodInfos.clear();
639
+ for (const [, e] of this.lowresCache) {
640
+ const s = e.deref();
641
+ if (s) {
642
+ if (s.isTexture) {
643
+ const r = s;
644
+ this.textureRefCounts.delete(r.uuid), r.dispose();
645
+ } else if (Array.isArray(s))
646
+ for (const r of s) r.dispose();
647
+ }
648
+ }
649
+ this.lowresCache.clear();
650
+ for (const [, e] of this.cache)
651
+ this._disposeCacheEntry(e);
652
+ this.cache.clear(), this.textureRefCounts.clear();
653
+ }
654
+ }
655
+ /** Dispose a single cache entry's three.js resource(s) to free GPU memory. */
656
+ static _disposeCacheEntry(t) {
657
+ if (t instanceof WeakRef) {
658
+ const e = t.deref();
659
+ e && (e.isTexture && this.textureRefCounts.delete(e.uuid), e.dispose());
660
+ } else
661
+ t.then((e) => {
662
+ if (e)
663
+ if (Array.isArray(e))
664
+ for (const s of e) s.dispose();
665
+ else
666
+ e.isTexture && this.textureRefCounts.delete(e.uuid), e.dispose();
667
+ }).catch(() => {
668
+ });
669
+ }
670
+ /** A map of key = asset uuid and value = LOD information */
671
+ static lodInfos = /* @__PURE__ */ new Map();
672
+ /** cache of already loaded mesh lods. Uses WeakRef for single resources to allow garbage collection when unused. */
673
+ static cache = /* @__PURE__ */ new Map();
674
+ /** this contains the geometry/textures that were originally loaded. Uses WeakRef to allow garbage collection when unused. */
675
+ static lowresCache = /* @__PURE__ */ new Map();
676
+ /** Reference counting for textures to track usage across multiple materials/objects */
677
+ static textureRefCounts = /* @__PURE__ */ new Map();
678
+ /**
679
+ * FinalizationRegistry to automatically clean up `previouslyLoaded` cache entries
680
+ * when their associated three.js resources are garbage collected by the browser.
681
+ * The held value is the cache key string used in `previouslyLoaded`.
682
+ */
683
+ static _resourceRegistry = new FinalizationRegistry((t) => {
684
+ const e = y.cache.get(t);
685
+ (f || K) && console.debug(`[gltf-progressive] Memory: Resource GC'd
686
+ ${t}`), e instanceof WeakRef && (e.deref() || (y.cache.delete(t), (f || K) && console.log("[gltf-progressive] ↪ Cache entry deleted (GC)")));
687
+ });
688
+ /**
689
+ * Track texture usage by incrementing reference count
690
+ */
691
+ static trackTextureUsage(t) {
692
+ const e = t.uuid, s = this.textureRefCounts.get(e) || 0;
693
+ this.textureRefCounts.set(e, s + 1), f === "verbose" && console.log(`[gltf-progressive] Track texture ${e}, refCount: ${s} → ${s + 1}`);
694
+ }
695
+ /**
696
+ * Untrack texture usage by decrementing reference count.
697
+ * Automatically disposes the texture when reference count reaches zero.
698
+ * @returns true if the texture was disposed, false otherwise
699
+ */
700
+ static untrackTextureUsage(t) {
701
+ const e = t.uuid, s = this.textureRefCounts.get(e);
702
+ if (!s)
703
+ return (f === "verbose" || K) && i("[gltf-progressive] Memory: Untrack untracked texture (dispose immediately)", 0), t.dispose(), !0;
704
+ const r = s - 1;
705
+ if (r <= 0)
706
+ return this.textureRefCounts.delete(e), (f || K) && i("[gltf-progressive] Memory: Dispose texture", r), t.dispose(), !0;
707
+ return this.textureRefCounts.set(e, r), f === "verbose" && i("[gltf-progressive] Memory: Untrack texture", r), !1;
708
+ function i(n, l) {
709
+ let a = t.image?.width || t.source?.data?.width || 0, u = t.image?.height || t.source?.data?.height || 0;
710
+ const c = a && u ? `${a}x${u}` : "N/A";
711
+ let m = "N/A";
712
+ a && u && (m = `~${(nt(t) / (1024 * 1024)).toFixed(2)} MB`), console.log(`${n} — ${t.name} ${c} (${m}), refCount: ${s} → ${l}
713
+ ${e}`);
714
+ }
715
+ }
716
+ static workers = [];
717
+ static _workersIndex = 0;
718
+ static async getOrLoadLOD(t, e) {
719
+ const s = f == "verbose", r = this.getAssignedLODInformation(t);
720
+ if (!r)
721
+ return f && console.warn(`[gltf-progressive] No LOD information found: ${t.name}, uuid: ${t.uuid}, type: ${t.type}`, t), null;
722
+ const i = r?.key;
723
+ let n;
724
+ if (t.isTexture === !0) {
725
+ const a = t;
726
+ a.source && a.source[ce] && (n = a.source[ce]);
727
+ }
728
+ if (n || (n = y.lodInfos.get(i)), !n)
729
+ f && console.warn(`Can not load LOD ${e}: no LOD info found for "${i}" ${t.name}`, t.type, y.lodInfos);
730
+ else {
731
+ if (e > 0) {
732
+ let c = !1;
733
+ const m = Array.isArray(n.lods);
734
+ if (m && e >= n.lods.length ? c = !0 : m || (c = !0), c) {
735
+ const w = this.lowresCache.get(i);
736
+ if (w) {
737
+ const L = w.deref();
738
+ if (L) return L;
739
+ this.lowresCache.delete(i), f && console.log(`[gltf-progressive] Lowres cache entry was GC'd: ${i}`);
740
+ }
741
+ return null;
742
+ }
743
+ }
744
+ const a = Array.isArray(n.lods) ? n.lods[e]?.path : n.lods;
745
+ if (!a)
746
+ return f && !n["missing:uri"] && (n["missing:uri"] = !0, console.warn("Missing uri for progressive asset for LOD " + e, n)), null;
747
+ const u = rt(r.url, a);
748
+ if (u.endsWith(".glb") || u.endsWith(".gltf")) {
749
+ if (!n.guid)
750
+ return console.warn("missing pointer for glb/gltf texture", n), null;
751
+ const c = u + "_" + n.guid, m = await this.queue.slot(u), w = this.cache.get(c);
752
+ if (w !== void 0)
753
+ if (s && console.log(`LOD ${e} was already loading/loaded: ${c}`), w instanceof WeakRef) {
754
+ const d = w.deref();
755
+ if (d) {
756
+ let g = d, M = !1;
757
+ if (g instanceof F && t instanceof F ? g.image?.data || g.source?.data ? g = this.copySettings(t, g) : M = !0 : g instanceof V && t instanceof V && (g.attributes.position?.array || (M = !0)), !M)
758
+ return g;
759
+ }
760
+ this.cache.delete(c), f && console.log(`[gltf-progressive] Re-loading GC'd/disposed resource: ${c}`);
761
+ } else {
762
+ let d = await w.catch((M) => (console.error(`Error loading LOD ${e} from ${u}
763
+ `, M), null)), g = !1;
764
+ if (d == null || (d instanceof F && t instanceof F ? d.image?.data || d.source?.data ? d = this.copySettings(t, d) : (g = !0, this.cache.delete(c)) : d instanceof V && t instanceof V && (d.attributes.position?.array || (g = !0, this.cache.delete(c)))), !g)
765
+ return d;
766
+ }
767
+ if (!m.use)
768
+ return f && console.log(`LOD ${e} was aborted: ${u}`), null;
769
+ const L = n, k = new Promise(async (d, g) => {
770
+ if (pt) {
771
+ const x = await (await ht({})).load(u);
772
+ if (x.textures.length > 0)
773
+ for (const h of x.textures) {
774
+ let p = h.texture;
775
+ return y.assignLODInformation(r.url, p, i, e, void 0), t instanceof F && (p = this.copySettings(t, p)), p && (p.guid = L.guid), d(p);
776
+ }
777
+ if (x.geometries.length > 0) {
778
+ const h = new Array();
779
+ for (const p of x.geometries) {
780
+ const b = p.geometry;
781
+ y.assignLODInformation(r.url, b, i, e, p.primitiveIndex), h.push(b);
782
+ }
783
+ return d(h);
784
+ }
785
+ return d(null);
786
+ }
787
+ const M = new we();
788
+ Te(M), f && (await new Promise((_) => setTimeout(_, 1e3)), s && console.warn("Start loading (delayed) " + u, L.guid));
789
+ let B = u;
790
+ if (L && Array.isArray(L.lods)) {
791
+ const _ = L.lods[e];
792
+ _.hash && (B += "?v=" + _.hash);
793
+ }
794
+ const D = await M.loadAsync(B).catch((_) => (console.error(`Error loading LOD ${e} from ${u}
795
+ `, _), d(null)));
796
+ if (!D)
797
+ return d(null);
798
+ const q = D.parser;
799
+ s && console.log("Loading finished " + u, L.guid);
800
+ let P = 0;
801
+ if (D.parser.json.textures) {
802
+ let _ = !1;
803
+ for (const x of D.parser.json.textures) {
804
+ if (x?.extensions) {
805
+ const h = x?.extensions[W];
806
+ if (h?.guid && h.guid === L.guid) {
807
+ _ = !0;
808
+ break;
809
+ }
810
+ }
811
+ P++;
812
+ }
813
+ if (_) {
814
+ let x = await q.getDependency("texture", P);
815
+ return x && y.assignLODInformation(r.url, x, i, e, void 0), s && console.log('change "' + t.name + '" → "' + x.name + '"', u, P, x, c), t instanceof F && (x = this.copySettings(t, x)), x && (x.guid = L.guid), d(x);
816
+ } else f && console.warn("Could not find texture with guid", L.guid, D.parser.json);
817
+ }
818
+ if (P = 0, D.parser.json.meshes) {
819
+ let _ = !1;
820
+ for (const x of D.parser.json.meshes) {
821
+ if (x?.extensions) {
822
+ const h = x?.extensions[W];
823
+ if (h?.guid && h.guid === L.guid) {
824
+ _ = !0;
825
+ break;
826
+ }
827
+ }
828
+ P++;
829
+ }
830
+ if (_) {
831
+ const x = await q.getDependency("mesh", P);
832
+ if (s && console.log(`Loaded Mesh "${x.name}"`, u, P, x, c), x.isMesh === !0) {
833
+ const h = x.geometry;
834
+ return y.assignLODInformation(r.url, h, i, e, 0), d(h);
835
+ } else {
836
+ const h = new Array();
837
+ for (let p = 0; p < x.children.length; p++) {
838
+ const b = x.children[p];
839
+ if (b.isMesh === !0) {
840
+ const S = b.geometry;
841
+ y.assignLODInformation(r.url, S, i, e, p), h.push(S);
842
+ }
843
+ }
844
+ return d(h);
845
+ }
846
+ } else f && console.warn("Could not find mesh with guid", L.guid, D.parser.json);
847
+ }
848
+ return d(null);
849
+ });
850
+ this.cache.set(c, k), m.use(k);
851
+ const v = await k;
852
+ return v != null ? v instanceof F ? (this.cache.set(c, new WeakRef(v)), y._resourceRegistry.register(v, c)) : Array.isArray(v) ? this.cache.set(c, Promise.resolve(v)) : this.cache.set(c, Promise.resolve(v)) : this.cache.set(c, Promise.resolve(null)), v;
853
+ } else if (t instanceof F) {
854
+ s && console.log("Load texture from uri: " + u);
855
+ const m = await new qe().loadAsync(u);
856
+ return m ? (m.guid = n.guid, m.flipY = !1, m.needsUpdate = !0, m.colorSpace = t.colorSpace, s && console.log(n, m)) : f && console.warn("failed loading", u), m;
857
+ }
858
+ }
859
+ return null;
860
+ }
861
+ static maxConcurrent = 50;
862
+ static queue = new it(y.maxConcurrent, { debug: f != !1 });
863
+ static assignLODInformation(t, e, s, r, i) {
864
+ if (!e) return;
865
+ e.userData || (e.userData = {});
866
+ const n = new mt(t, s, r, i);
867
+ e.userData.LODS = n, "source" in e && typeof e.source == "object" && (e.source.LODS = n);
868
+ }
869
+ static getAssignedLODInformation(t) {
870
+ return t ? t.userData?.LODS ? t.userData.LODS : "source" in t && t.source?.LODS ? t.source.LODS : null : null;
871
+ }
872
+ // private static readonly _copiedTextures: WeakMap<Texture, Texture> = new Map();
873
+ static copySettings(t, e) {
874
+ return e ? (f === "verbose" && console.debug(`Copy texture settings
875
+ `, t.uuid, `
876
+ `, 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;
877
+ }
878
+ }
879
+ class mt {
880
+ url;
881
+ /** the key to lookup the LOD information */
882
+ key;
883
+ level;
884
+ /** For multi objects (e.g. a group of meshes) this is the index of the object */
885
+ index;
886
+ constructor(t, e, s, r) {
887
+ this.url = t, this.key = e, this.level = s, r != null && (this.index = r);
888
+ }
889
+ }
890
+ class de {
891
+ static addPromise = (t, e, s, r) => {
892
+ r.forEach((i) => {
893
+ i.add(t, e, s);
894
+ });
895
+ };
896
+ ready;
897
+ /** The number of promises that have been added to this group so far */
898
+ get awaitedCount() {
899
+ return this._addedCount;
900
+ }
901
+ /** The number of promises that have been resolved */
902
+ get resolvedCount() {
903
+ return this._resolvedCount;
904
+ }
905
+ /** The number of promises that are in-flight */
906
+ get currentlyAwaiting() {
907
+ return this._awaiting.length;
908
+ }
909
+ _resolve;
910
+ _signal;
911
+ /** start frame can be undefined if the user configured this group to wait for the first promise.
912
+ * Then the start frame will be set when the first promise has been added to the group */
913
+ _frame_start;
914
+ /** How many frames to capture since the start frame */
915
+ _frames_to_capture;
916
+ _resolved = !1;
917
+ _addedCount = 0;
918
+ _resolvedCount = 0;
919
+ /** These promises are currently being awaited */
920
+ _awaiting = [];
921
+ _maxPromisesPerObject = 1;
922
+ constructor(t, e) {
923
+ const r = Math.max(e.frames ?? 2, 2);
924
+ this._frame_start = e.waitForFirstCapture ? void 0 : t, this._frames_to_capture = r, this.ready = new Promise((i) => {
925
+ this._resolve = i;
926
+ }), this.ready.finally(() => {
927
+ this._resolved = !0, this._awaiting.length = 0;
928
+ }), this._signal = e.signal, this._signal?.addEventListener("abort", () => {
929
+ this.resolveNow();
930
+ }), this._maxPromisesPerObject = Math.max(1, e.maxPromisesPerObject ?? 1);
931
+ }
932
+ _currentFrame = 0;
933
+ update(t) {
934
+ this._currentFrame = t, this._frame_start === void 0 && this._addedCount > 0 && (this._frame_start = t), (this._signal?.aborted || this._awaiting.length === 0 && this._frame_start !== void 0 && t > this._frame_start + this._frames_to_capture) && this.resolveNow();
935
+ }
936
+ _seen = /* @__PURE__ */ new WeakMap();
937
+ add(t, e, s) {
938
+ if (this._resolved) {
939
+ f && console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");
940
+ return;
941
+ }
942
+ if (!(this._frame_start !== void 0 && this._currentFrame > this._frame_start + this._frames_to_capture)) {
943
+ if (this._maxPromisesPerObject >= 1)
944
+ if (this._seen.has(e)) {
945
+ let r = this._seen.get(e);
946
+ if (r >= this._maxPromisesPerObject) {
947
+ f && console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");
948
+ return;
949
+ }
950
+ this._seen.set(e, r + 1);
951
+ } else
952
+ this._seen.set(e, 1);
953
+ this._awaiting.push(s), this._addedCount++, s.finally(() => {
954
+ this._resolvedCount++, this._awaiting.splice(this._awaiting.indexOf(s), 1);
955
+ });
956
+ }
957
+ }
958
+ resolveNow() {
959
+ this._resolved || this._resolve?.({
960
+ awaited_count: this._addedCount,
961
+ resolved_count: this._resolvedCount,
962
+ cancelled: this._signal?.aborted ?? !1
963
+ });
964
+ }
965
+ }
966
+ const R = N("debugprogressive"), yt = N("noprogressive"), fe = /* @__PURE__ */ Symbol("Needle:LODSManager"), he = /* @__PURE__ */ Symbol("Needle:LODState"), U = /* @__PURE__ */ Symbol("Needle:CurrentLOD"), T = { mesh_lod: -1, texture_lod: -1 };
967
+ let oe = class O {
968
+ /**
969
+ * 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.
970
+ */
971
+ static debugDrawLine;
972
+ /** @internal */
973
+ static getObjectLODState(t) {
974
+ return t[he];
975
+ }
976
+ static addPlugin(t) {
977
+ z.push(t);
978
+ }
979
+ static removePlugin(t) {
980
+ const e = z.indexOf(t);
981
+ e >= 0 && z.splice(e, 1);
982
+ }
983
+ /**
984
+ * Gets the LODsManager for the given renderer. If the LODsManager does not exist yet, it will be created.
985
+ * @param renderer The renderer to get the LODsManager for.
986
+ * @returns The LODsManager instance.
987
+ */
988
+ static get(t, e) {
989
+ if (t[fe])
990
+ return console.debug("[gltf-progressive] LODsManager already exists for this renderer"), t[fe];
991
+ const s = new O(t, {
992
+ engine: "unknown",
993
+ ...e
994
+ });
995
+ return t[fe] = s, s;
996
+ }
997
+ renderer;
998
+ context;
999
+ projectionScreenMatrix = new Me();
1000
+ /** @deprecated use static `LODsManager.addPlugin()` method. This getter will be removed in later versions */
1001
+ get plugins() {
1002
+ return z;
1003
+ }
1004
+ /**
1005
+ * Force override the LOD level for all objects (meshes + textures) rendered in the scene
1006
+ * @default undefined automatically calculate LOD level
1007
+ */
1008
+ overrideLodLevel = void 0;
1009
+ /**
1010
+ * The target triangle density is the desired max amount of triangles on screen when the mesh is filling the screen.
1011
+ * @default 200_000
1012
+ */
1013
+ targetTriangleDensity = 2e5;
1014
+ /**
1015
+ * The interval in frames to automatically update the bounds of skinned meshes.
1016
+ * Set to 0 or a negative value to disable automatic bounds updates.
1017
+ * @default 30
1018
+ */
1019
+ skinnedMeshAutoUpdateBoundsInterval = 30;
1020
+ /**
1021
+ * 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.
1022
+ * @default "auto"
1023
+ */
1024
+ updateInterval = "auto";
1025
+ #e = 1;
1026
+ /**
1027
+ * If set to true, the LODsManager will not update the LODs.
1028
+ * @default false
1029
+ */
1030
+ pause = !1;
1031
+ /**
1032
+ * When set to true the LODsManager will not update the LODs. This can be used to manually update the LODs using the `update` method.
1033
+ * Otherwise the LODs will be updated automatically when the renderer renders the scene.
1034
+ * @default false
1035
+ */
1036
+ manual = !1;
1037
+ _newPromiseGroups = [];
1038
+ _promiseGroupIds = 0;
1039
+ /**
1040
+ * Call to await LODs loading during the next render cycle.
1041
+ */
1042
+ awaitLoading(t) {
1043
+ const e = this._promiseGroupIds++, s = new de(this.#r, { ...t });
1044
+ this._newPromiseGroups.push(s);
1045
+ const r = performance.now();
1046
+ return s.ready.finally(() => {
1047
+ const i = this._newPromiseGroups.indexOf(s);
1048
+ i >= 0 && (this._newPromiseGroups.splice(i, 1), ve() && performance.measure("LODsManager:awaitLoading", {
1049
+ start: r,
1050
+ detail: { id: e, name: t?.name, awaited: s.awaitedCount, resolved: s.resolvedCount }
1051
+ }));
1052
+ }), s.ready;
1053
+ }
1054
+ _postprocessPromiseGroups() {
1055
+ if (this._newPromiseGroups.length !== 0)
1056
+ for (let t = this._newPromiseGroups.length - 1; t >= 0; t--)
1057
+ this._newPromiseGroups[t].update(this.#r);
1058
+ }
1059
+ _lodchangedlisteners = [];
1060
+ addEventListener(t, e) {
1061
+ t === "changed" && this._lodchangedlisteners.push(e);
1062
+ }
1063
+ removeEventListener(t, e) {
1064
+ if (t === "changed") {
1065
+ const s = this._lodchangedlisteners.indexOf(e);
1066
+ s >= 0 && this._lodchangedlisteners.splice(s, 1);
1067
+ }
1068
+ }
1069
+ // readonly plugins: NEEDLE_progressive_plugin[] = [];
1070
+ constructor(t, e) {
1071
+ this.renderer = t, this.context = { ...e };
1072
+ }
1073
+ #t;
1074
+ #n = new Ee();
1075
+ #r = 0;
1076
+ #i = 0;
1077
+ #o = 0;
1078
+ #s = 0;
1079
+ _fpsBuffer = [60, 60, 60, 60, 60];
1080
+ /**
1081
+ * Enable the LODsManager. This will replace the render method of the renderer with a method that updates the LODs.
1082
+ */
1083
+ enable() {
1084
+ if (this.#t) return;
1085
+ console.debug("[gltf-progressive] Enabling LODsManager for renderer");
1086
+ let t = 0;
1087
+ this.#t = this.renderer.render;
1088
+ const e = this;
1089
+ Le(this.renderer), this.renderer.render = function(s, r) {
1090
+ const i = e.renderer.getRenderTarget();
1091
+ (i == null || "isXRRenderTarget" in i && i.isXRRenderTarget) && (t = 0, e.#r += 1, e.#i = e.#n.getDelta(), e.#o += e.#i, e._fpsBuffer.shift(), e._fpsBuffer.push(1 / e.#i), e.#s = e._fpsBuffer.reduce((l, a) => l + a) / e._fpsBuffer.length, R && e.#r % 200 === 0 && console.log("FPS", Math.round(e.#s), "Interval:", e.#e));
1092
+ const n = t++;
1093
+ e.#t.call(this, s, r), e.onAfterRender(s, r, n);
1094
+ };
1095
+ }
1096
+ disable() {
1097
+ this.#t && (console.debug("[gltf-progressive] Disabling LODsManager for renderer"), this.renderer.render = this.#t, this.#t = void 0);
1098
+ }
1099
+ update(t, e) {
1100
+ this.internalUpdate(t, e);
1101
+ }
1102
+ onAfterRender(t, e, s) {
1103
+ if (this.pause) return;
1104
+ const i = this.renderer.renderLists.get(t, 0).opaque;
1105
+ let n = !0;
1106
+ if (i.length === 1) {
1107
+ const l = i[0].material;
1108
+ (l.name === "EffectMaterial" || l.name === "CopyShader") && (n = !1);
1109
+ }
1110
+ if ((e.parent && e.parent.type === "CubeCamera" || s >= 1 && e.type === "OrthographicCamera") && (n = !1), n) {
1111
+ if (yt || (this.updateInterval === "auto" ? this.#s < 40 && this.#e < 10 ? (this.#e += 1, R && console.warn("↓ Reducing LOD updates", this.#e, this.#s.toFixed(0))) : this.#s >= 60 && this.#e > 1 && (this.#e -= 1, R && console.warn("↑ Increasing LOD updates", this.#e, this.#s.toFixed(0))) : this.#e = this.updateInterval, this.#e > 0 && this.#r % this.#e != 0))
1112
+ return;
1113
+ this.internalUpdate(t, e), this._postprocessPromiseGroups();
1114
+ }
1115
+ }
1116
+ /**
1117
+ * Update LODs in a scene
1118
+ */
1119
+ internalUpdate(t, e) {
1120
+ const s = this.renderer.renderLists.get(t, 0), r = s.opaque;
1121
+ this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix, e.matrixWorldInverse);
1122
+ const i = this.targetTriangleDensity;
1123
+ for (const a of r) {
1124
+ if (a.material && (a.geometry?.type === "BoxGeometry" || a.geometry?.type === "BufferGeometry") && (a.material.name === "SphericalGaussianBlur" || a.material.name == "BackgroundCubeMaterial" || a.material.name === "CubemapFromEquirect" || a.material.name === "EquirectangularToCubeUV")) {
1125
+ R && (a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] || (a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] = !0, console.warn("Ignoring skybox or BLIT object", a, a.material.name, a.material.type)));
1126
+ continue;
1127
+ }
1128
+ switch (a.material.type) {
1129
+ case "LineBasicMaterial":
1130
+ case "LineDashedMaterial":
1131
+ case "PointsMaterial":
1132
+ case "ShadowMaterial":
1133
+ case "MeshDistanceMaterial":
1134
+ case "MeshDepthMaterial":
1135
+ continue;
1136
+ }
1137
+ if (R === "color" && a.material && !a.object.progressive_debug_color) {
1138
+ a.object.progressive_debug_color = !0;
1139
+ const c = Math.random() * 16777215, m = new Ve({ color: c });
1140
+ a.object.material = m;
1141
+ }
1142
+ const u = a.object;
1143
+ (u instanceof X || u.isMesh) && this.updateLODs(t, e, u, i);
1144
+ }
1145
+ const n = s.transparent;
1146
+ for (const a of n) {
1147
+ const u = a.object;
1148
+ (u instanceof X || u.isMesh) && this.updateLODs(t, e, u, i);
1149
+ }
1150
+ const l = s.transmissive;
1151
+ for (const a of l) {
1152
+ const u = a.object;
1153
+ (u instanceof X || u.isMesh) && this.updateLODs(t, e, u, i);
1154
+ }
1155
+ }
1156
+ /** Update the LOD levels for the renderer. */
1157
+ updateLODs(t, e, s, r) {
1158
+ s.userData || (s.userData = {});
1159
+ let i = s[he];
1160
+ if (i || (i = new xt(), s[he] = i), i.frames++ < 2)
1161
+ return;
1162
+ for (const l of z)
1163
+ l.onBeforeUpdateLOD?.(this.renderer, t, e, s);
1164
+ const n = this.overrideLodLevel !== void 0 ? this.overrideLodLevel : E;
1165
+ n >= 0 ? (T.mesh_lod = n, T.texture_lod = n) : (this.calculateLodLevel(e, s, i, r, T), T.mesh_lod = Math.round(T.mesh_lod), T.texture_lod = Math.round(T.texture_lod)), T.mesh_lod >= 0 && this.loadProgressiveMeshes(s, T.mesh_lod), s.material && T.texture_lod >= 0 && this.loadProgressiveTextures(s.material, T.texture_lod, n), f && s.material && !s.isGizmo && Re(s.material);
1166
+ for (const l of z)
1167
+ l.onAfterUpdatedLOD?.(this.renderer, t, e, s, T);
1168
+ i.lastLodLevel_Mesh = T.mesh_lod, i.lastLodLevel_Texture = T.texture_lod;
1169
+ }
1170
+ /** Load progressive textures for the given material
1171
+ * @param material the material to load the textures for
1172
+ * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
1173
+ * @returns Promise with true if the LOD was loaded, false if not
1174
+ */
1175
+ loadProgressiveTextures(t, e, s) {
1176
+ if (!t) return;
1177
+ if (Array.isArray(t)) {
1178
+ for (const i of t)
1179
+ this.loadProgressiveTextures(i, e);
1180
+ return;
1181
+ }
1182
+ let r = !1;
1183
+ if ((t[U] === void 0 || e < t[U]) && (r = !0), s !== void 0 && s >= 0 && (r = t[U] != s, e = s), r) {
1184
+ t[U] = e;
1185
+ const i = y.assignTextureLOD(t, e).then((n) => {
1186
+ this._lodchangedlisteners.forEach((l) => l({ type: "texture", level: e, object: t }));
1187
+ });
1188
+ de.addPromise("texture", t, i, this._newPromiseGroups);
1189
+ }
1190
+ }
1191
+ /** Load progressive meshes for the given mesh
1192
+ * @param mesh the mesh to load the LOD for
1193
+ * @param index the index of the mesh if it's part of a group
1194
+ * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
1195
+ * @returns Promise with true if the LOD was loaded, false if not
1196
+ */
1197
+ loadProgressiveMeshes(t, e) {
1198
+ if (!t) return Promise.resolve(null);
1199
+ let s = t[U] !== e;
1200
+ const r = t["DEBUG:LOD"];
1201
+ if (r != null && (s = t[U] != r, e = r), s) {
1202
+ t[U] = e;
1203
+ const i = t.geometry, n = y.assignMeshLOD(t, e).then((l) => (l && t[U] == e && i != t.geometry && this._lodchangedlisteners.forEach((a) => a({ type: "mesh", level: e, object: t })), l));
1204
+ return de.addPromise("mesh", t, n, this._newPromiseGroups), n;
1205
+ }
1206
+ return Promise.resolve(null);
1207
+ }
1208
+ // private testIfLODLevelsAreAvailable() {
1209
+ _sphere = new Se();
1210
+ _tempBox = new pe();
1211
+ _tempBox2 = new pe();
1212
+ tempMatrix = new Me();
1213
+ _tempWorldPosition = new A();
1214
+ _tempBoxSize = new A();
1215
+ _tempBox2Size = new A();
1216
+ static corner0 = new A();
1217
+ static corner1 = new A();
1218
+ static corner2 = new A();
1219
+ static corner3 = new A();
1220
+ static _tempPtInside = new A();
1221
+ static isInside(t, e) {
1222
+ const s = t.min, r = t.max, i = (s.x + r.x) * 0.5, n = (s.y + r.y) * 0.5;
1223
+ return this._tempPtInside.set(i, n, s.z).applyMatrix4(e).z < 0;
1224
+ }
1225
+ static skinnedMeshBoundsFrameOffsetCounter = 0;
1226
+ static $skinnedMeshBoundsOffset = /* @__PURE__ */ Symbol("gltf-progressive-skinnedMeshBoundsOffset");
1227
+ // #region calculateLodLevel
1228
+ calculateLodLevel(t, e, s, r, i) {
1229
+ if (!e) {
1230
+ i.mesh_lod = -1, i.texture_lod = -1;
1231
+ return;
1232
+ }
1233
+ if (!t) {
1234
+ i.mesh_lod = -1, i.texture_lod = -1;
1235
+ return;
1236
+ }
1237
+ let l = 10 + 1, a = !1;
1238
+ if (R && e["DEBUG:LOD"] != null)
1239
+ return e["DEBUG:LOD"];
1240
+ const u = y.getMeshLODExtension(e.geometry)?.lods, c = y.getPrimitiveIndex(e.geometry), m = u && u.length > 0, w = y.getMaterialMinMaxLODsCount(e.material), L = w.min_count !== 1 / 0 && w.min_count >= 0 && w.max_count >= 0;
1241
+ if (!m && !L) {
1242
+ i.mesh_lod = 0, i.texture_lod = 0;
1243
+ return;
1244
+ }
1245
+ m || (a = !0, l = 0);
1246
+ const k = this.renderer.domElement.clientHeight || this.renderer.domElement.height;
1247
+ let v = e.geometry.boundingBox;
1248
+ if (e.type === "SkinnedMesh") {
1249
+ const d = e;
1250
+ if (!d.boundingBox)
1251
+ d.computeBoundingBox();
1252
+ else if (this.skinnedMeshAutoUpdateBoundsInterval > 0) {
1253
+ if (!d[O.$skinnedMeshBoundsOffset]) {
1254
+ const M = O.skinnedMeshBoundsFrameOffsetCounter++;
1255
+ d[O.$skinnedMeshBoundsOffset] = M;
1256
+ }
1257
+ const g = d[O.$skinnedMeshBoundsOffset];
1258
+ if ((s.frames + g) % this.skinnedMeshAutoUpdateBoundsInterval === 0) {
1259
+ const M = ee(d), B = d.geometry;
1260
+ M && (d.geometry = M), d.computeBoundingBox(), d.geometry = B;
1261
+ }
1262
+ }
1263
+ v = d.boundingBox;
1264
+ }
1265
+ if (v) {
1266
+ const d = t;
1267
+ if (e.geometry.attributes.color && e.geometry.attributes.color.count < 100 && e.geometry.boundingSphere) {
1268
+ this._sphere.copy(e.geometry.boundingSphere), this._sphere.applyMatrix4(e.matrixWorld);
1269
+ const h = t.getWorldPosition(this._tempWorldPosition);
1270
+ if (this._sphere.containsPoint(h)) {
1271
+ i.mesh_lod = 0, i.texture_lod = 0;
1272
+ return;
1273
+ }
1274
+ }
1275
+ if (this._tempBox.copy(v), this._tempBox.applyMatrix4(e.matrixWorld), d.isPerspectiveCamera && O.isInside(this._tempBox, this.projectionScreenMatrix)) {
1276
+ i.mesh_lod = 0, i.texture_lod = 0;
1277
+ return;
1278
+ }
1279
+ if (this._tempBox.applyMatrix4(this.projectionScreenMatrix), this.renderer.xr.enabled && d.isPerspectiveCamera && d.fov > 70) {
1280
+ const h = this._tempBox.min, p = this._tempBox.max;
1281
+ let b = h.x, S = h.y, G = p.x, Y = p.y;
1282
+ const te = 2, ae = 1.5, se = (h.x + p.x) * 0.5, re = (h.y + p.y) * 0.5;
1283
+ b = (b - se) * te + se, S = (S - re) * te + re, G = (G - se) * te + se, Y = (Y - re) * te + re;
1284
+ const Be = b < 0 && G > 0 ? 0 : Math.min(Math.abs(h.x), Math.abs(p.x)), Ge = S < 0 && Y > 0 ? 0 : Math.min(Math.abs(h.y), Math.abs(p.y)), le = Math.max(Be, Ge);
1285
+ s.lastCentrality = (ae - le) * (ae - le) * (ae - le);
1286
+ } else
1287
+ s.lastCentrality = 1;
1288
+ const g = this._tempBox.getSize(this._tempBoxSize);
1289
+ g.multiplyScalar(0.5), screen.availHeight > 0 && k > 0 && g.multiplyScalar(k / screen.availHeight), t.isPerspectiveCamera ? g.x *= t.aspect : t.isOrthographicCamera;
1290
+ const M = t.matrixWorldInverse, B = this._tempBox2;
1291
+ B.copy(v), B.applyMatrix4(e.matrixWorld), B.applyMatrix4(M);
1292
+ const D = B.getSize(this._tempBox2Size), q = Math.max(D.x, D.y);
1293
+ if (Math.max(g.x, g.y) != 0 && q != 0 && (g.z = D.z / Math.max(D.x, D.y) * Math.max(g.x, g.y)), s.lastScreenCoverage = Math.max(g.x, g.y, g.z), s.lastScreenspaceVolume.copy(g), s.lastScreenCoverage *= s.lastCentrality, R && O.debugDrawLine) {
1294
+ const h = this.tempMatrix.copy(this.projectionScreenMatrix);
1295
+ h.invert();
1296
+ const p = O.corner0, b = O.corner1, S = O.corner2, G = O.corner3;
1297
+ p.copy(this._tempBox.min), b.copy(this._tempBox.max), b.x = p.x, S.copy(this._tempBox.max), S.y = p.y, G.copy(this._tempBox.max);
1298
+ const Y = (p.z + G.z) * 0.5;
1299
+ p.z = b.z = S.z = G.z = Y, p.applyMatrix4(h), b.applyMatrix4(h), S.applyMatrix4(h), G.applyMatrix4(h), O.debugDrawLine(p, b, 255), O.debugDrawLine(p, S, 255), O.debugDrawLine(b, G, 255), O.debugDrawLine(S, G, 255);
1300
+ }
1301
+ let _ = 999;
1302
+ if (u && s.lastScreenCoverage > 0)
1303
+ for (let h = 0; h < u.length; h++) {
1304
+ const p = u[h], S = (p.densities?.[c] || p.density || 1e-5) / s.lastScreenCoverage;
1305
+ if (c > 0 && ve() && !p.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.")), S < r) {
1306
+ _ = h;
1307
+ break;
1308
+ }
1309
+ }
1310
+ _ < l && (l = _, a = !0);
1311
+ }
1312
+ if (a ? i.mesh_lod = l : i.mesh_lod = s.lastLodLevel_Mesh, R && i.mesh_lod != s.lastLodLevel_Mesh) {
1313
+ const g = u?.[i.mesh_lod];
1314
+ g && console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} → ${i.mesh_lod} (density: ${g.densities?.[c].toFixed(0)}) | ${e.name}`);
1315
+ }
1316
+ if (L) {
1317
+ const d = "saveData" in globalThis.navigator && globalThis.navigator.saveData === !0;
1318
+ if (s.lastLodLevel_Texture < 0) {
1319
+ if (i.texture_lod = w.max_count - 1, R) {
1320
+ const g = w.lods[w.max_count - 1];
1321
+ R && console.log(`First Texture LOD ${i.texture_lod} (${g.max_height}px) - ${e.name}`);
1322
+ }
1323
+ } else {
1324
+ const g = s.lastScreenspaceVolume.x + s.lastScreenspaceVolume.y + s.lastScreenspaceVolume.z;
1325
+ let M = s.lastScreenCoverage * 4;
1326
+ this.context?.engine === "model-viewer" && (M *= 1.5);
1327
+ const D = k / window.devicePixelRatio * M;
1328
+ let q = !1;
1329
+ for (let P = w.lods.length - 1; P >= 0; P--) {
1330
+ const _ = w.lods[P];
1331
+ if (!(d && _.max_height >= 2048) && !(ke() && _.max_height > 4096) && (_.max_height > D || !q && P === 0)) {
1332
+ if (q = !0, i.texture_lod = P, R && i.texture_lod < s.lastLodLevel_Texture) {
1333
+ const x = _.max_height;
1334
+ console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} → ${i.texture_lod} = ${x}px
1335
+ Screensize: ${D.toFixed(0)}px, Coverage: ${(100 * s.lastScreenCoverage).toFixed(2)}%, Volume ${g.toFixed(1)}
1336
+ ${e.name}`);
1337
+ }
1338
+ break;
1339
+ }
1340
+ }
1341
+ }
1342
+ } else
1343
+ i.texture_lod = 0;
1344
+ }
1345
+ };
1346
+ class xt {
1347
+ frames = 0;
1348
+ lastLodLevel_Mesh = -1;
1349
+ lastLodLevel_Texture = -1;
1350
+ lastScreenCoverage = 0;
1351
+ lastScreenspaceVolume = new A();
1352
+ lastCentrality = 0;
1353
+ }
1354
+ const De = /* @__PURE__ */ Symbol("NEEDLE_mesh_lod"), ie = /* @__PURE__ */ Symbol("NEEDLE_texture_lod");
1355
+ let ge = null;
1356
+ function Ie() {
1357
+ const o = wt();
1358
+ o && (o.mapURLs(function(t) {
1359
+ return be(), t;
1360
+ }), be(), ge?.disconnect(), ge = new MutationObserver((t) => {
1361
+ t.forEach((e) => {
1362
+ e.addedNodes.forEach((s) => {
1363
+ s instanceof HTMLElement && s.tagName.toLowerCase() === "model-viewer" && $e(s);
1364
+ });
1365
+ });
1366
+ }), ge.observe(document, { childList: !0, subtree: !0 }));
1367
+ }
1368
+ function wt() {
1369
+ if (typeof customElements > "u") return null;
1370
+ const o = customElements.get("model-viewer");
1371
+ return o || (customElements.whenDefined("model-viewer").then(() => {
1372
+ console.debug("[gltf-progressive] model-viewer defined"), Ie();
1373
+ }), null);
1374
+ }
1375
+ function be() {
1376
+ if (typeof document > "u") return;
1377
+ document.querySelectorAll("model-viewer").forEach((t) => {
1378
+ $e(t);
1379
+ });
1380
+ }
1381
+ const Oe = /* @__PURE__ */ new WeakSet();
1382
+ let Lt = 0;
1383
+ function $e(o) {
1384
+ if (!o || Oe.has(o))
1385
+ return null;
1386
+ Oe.add(o), console.debug("[gltf-progressive] found new model-viewer..." + ++Lt + `
1387
+ `, o.getAttribute("src"));
1388
+ let t = null, e = null, s = null;
1389
+ for (let r = o; r != null; r = Object.getPrototypeOf(r)) {
1390
+ const i = Object.getOwnPropertySymbols(r), n = i.find((u) => u.toString() == "Symbol(renderer)"), l = i.find((u) => u.toString() == "Symbol(scene)"), a = i.find((u) => u.toString() == "Symbol(needsRender)");
1391
+ !t && n != null && (t = o[n].threeRenderer), !e && l != null && (e = o[l]), !s && a != null && (s = o[a]);
1392
+ }
1393
+ if (t && e) {
1394
+ let r = function() {
1395
+ if (s) {
1396
+ let n = 0, l = setInterval(() => {
1397
+ if (n++ > 5) {
1398
+ clearInterval(l);
1399
+ return;
1400
+ }
1401
+ s?.call(o);
1402
+ }, 300);
1403
+ }
1404
+ };
1405
+ console.debug("[gltf-progressive] setup model-viewer");
1406
+ const i = oe.get(t, { engine: "model-viewer" });
1407
+ return oe.addPlugin(new _t()), i.enable(), i.addEventListener("changed", () => {
1408
+ s?.call(o);
1409
+ }), o.addEventListener("model-visibility", (n) => {
1410
+ n.detail.visible && s?.call(o);
1411
+ }), o.addEventListener("load", () => {
1412
+ r();
1413
+ }), () => {
1414
+ i.disable();
1415
+ };
1416
+ }
1417
+ return null;
1418
+ }
1419
+ class _t {
1420
+ _didWarnAboutMissingUrl = !1;
1421
+ onBeforeUpdateLOD(t, e, s, r) {
1422
+ this.tryParseMeshLOD(e, r), this.tryParseTextureLOD(e, r);
1423
+ }
1424
+ getUrl(t) {
1425
+ if (!t)
1426
+ return null;
1427
+ let e = t.getAttribute("src");
1428
+ return e || (e = t.src), e || (this._didWarnAboutMissingUrl || console.warn("No url found in modelviewer", t), this._didWarnAboutMissingUrl = !0), e;
1429
+ }
1430
+ tryGetCurrentGLTF(t) {
1431
+ return t._currentGLTF;
1432
+ }
1433
+ tryGetCurrentModelViewer(t) {
1434
+ return t.element;
1435
+ }
1436
+ tryParseTextureLOD(t, e) {
1437
+ if (e[ie] == !0) return;
1438
+ e[ie] = !0;
1439
+ const s = this.tryGetCurrentGLTF(t), r = this.tryGetCurrentModelViewer(t), i = this.getUrl(r);
1440
+ if (i && s && e.material) {
1441
+ let n = function(a) {
1442
+ if (a[ie] == !0) return;
1443
+ a[ie] = !0, a.userData && (a.userData.LOD = -1);
1444
+ const u = Object.keys(a);
1445
+ for (let c = 0; c < u.length; c++) {
1446
+ const m = u[c], w = a[m];
1447
+ if (w?.isTexture === !0) {
1448
+ const L = w.userData?.associations?.textures;
1449
+ if (L == null) continue;
1450
+ const k = s.parser.json.textures[L];
1451
+ if (!k) {
1452
+ console.warn("Texture data not found for texture index " + L);
1453
+ continue;
1454
+ }
1455
+ if (k?.extensions?.[W]) {
1456
+ const v = k.extensions[W];
1457
+ v && i && y.registerTexture(i, w, v.lods.length, L, v);
1458
+ }
1459
+ }
1460
+ }
1461
+ };
1462
+ const l = e.material;
1463
+ if (Array.isArray(l)) for (const a of l) n(a);
1464
+ else n(l);
1465
+ }
1466
+ }
1467
+ tryParseMeshLOD(t, e) {
1468
+ if (e[De] == !0) return;
1469
+ e[De] = !0;
1470
+ const s = this.tryGetCurrentModelViewer(t), r = this.getUrl(s);
1471
+ if (!r)
1472
+ return;
1473
+ const i = e.userData?.gltfExtensions?.[W];
1474
+ if (i && r) {
1475
+ const n = e.uuid;
1476
+ y.registerMesh(r, n, e, 0, i.lods.length, i);
1477
+ }
1478
+ }
1479
+ }
1480
+ function Mt(...o) {
1481
+ let t, e, s, r;
1482
+ switch (o.length) {
1483
+ case 2:
1484
+ [s, e] = o, r = {};
1485
+ break;
1486
+ case 3:
1487
+ [s, e, r] = o;
1488
+ break;
1489
+ case 4:
1490
+ [t, e, s, r] = o;
1491
+ break;
1492
+ default:
1493
+ throw new Error("Invalid arguments");
1494
+ }
1495
+ Le(e), Te(s), Ae(s, {
1496
+ progressive: !0,
1497
+ ...r?.hints
1498
+ }), s.register((n) => new y(n));
1499
+ const i = oe.get(e);
1500
+ return r?.enableLODsManager !== !1 && i.enable(), i;
1501
+ }
1502
+ Ie();
1503
+ if (!at) {
1504
+ const o = {
1505
+ gltfProgressive: {
1506
+ useNeedleProgressive: Mt,
1507
+ LODsManager: oe,
1508
+ configureLoader: Ae,
1509
+ getRaycastMesh: ee,
1510
+ useRaycastMeshes: ut
1511
+ }
1512
+ };
1513
+ if (!globalThis.Needle)
1514
+ globalThis.Needle = o;
1515
+ else
1516
+ for (const t in o)
1517
+ globalThis.Needle[t] = o[t];
1518
+ }
1519
+ export {
1520
+ oe as LODsManager,
1521
+ y as NEEDLE_progressive,
1522
+ Te as addDracoAndKTX2Loaders,
1523
+ Ae as configureLoader,
1524
+ Le as createLoaders,
1525
+ ee as getRaycastMesh,
1526
+ Ze as setDracoDecoderLocation,
1527
+ et as setKTX2TranscoderLocation
1528
+ };