@nebula-spatial/viewer 0.4.4 → 0.4.5

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.
@@ -0,0 +1,3238 @@
1
+ var ln = Object.defineProperty;
2
+ var un = (n, t, i) => t in n ? ln(n, t, { enumerable: !0, configurable: !0, writable: !0, value: i }) : n[t] = i;
3
+ var $ = (n, t, i) => un(n, typeof t != "symbol" ? t + "" : t, i);
4
+ import { d as fn, b as dn, e as oi, c as pn, a as ri, r as mn, S as ai, p as hn } from "./session-DNyPmQOW.js";
5
+ import { Quaternion as K, Euler as Zt, LoadingManager as ji, Group as ut, Mesh as C, MeshLambertMaterial as yn, MeshPhongMaterial as ci, MeshStandardMaterial as Je, Matrix4 as H, TextureLoader as gn, SRGBColorSpace as wn, RepeatWrapping as bn, BoxGeometry as He, SphereGeometry as Ze, CylinderGeometry as Ci, CapsuleGeometry as Ni, Vector3 as z, MathUtils as xn, Matrix3 as li, Box3 as it, BufferAttribute as qi, Line3 as ft, Plane as Oi, Vector2 as gt, Triangle as $t, BackSide as An, DoubleSide as Mn, REVISION as Vi, Ray as vn, FrontSide as ui, LineSegments as Qe, LineLoop as Wi, Line as Ye, Points as Gi, Sphere as Pn, BatchedMesh as Sn, AxesHelper as Tn, ArrowHelper as fi, BufferGeometry as Rn, LineBasicMaterial as di, Float32BufferAttribute as _n, MeshBasicMaterial as pi, EdgesGeometry as Bn } from "three";
6
+ import { GLTFLoader as En } from "three/examples/jsm/loaders/GLTFLoader.js";
7
+ import { ColladaLoader as zn } from "three/examples/jsm/loaders/ColladaLoader.js";
8
+ import { d as dt, S as Fn } from "./stage-BPiGudYP.js";
9
+ import { OBJLoader as Un } from "three/examples/jsm/loaders/OBJLoader.js";
10
+ import { STLLoader as $n } from "three/examples/jsm/loaders/STLLoader.js";
11
+ function Xi(n) {
12
+ const t = new Map(n.map((o) => [o.id, o])), i = /* @__PURE__ */ new Map(), e = /* @__PURE__ */ new Set(), s = (o) => {
13
+ throw Object.assign(new Error(`Invalid URDF mimic relationship: ${o}`), { code: "E_URDF_MIMIC" });
14
+ }, r = (o) => {
15
+ var l;
16
+ const f = i.get(o);
17
+ if (f) return f;
18
+ const a = t.get(o);
19
+ if (!a || e.has(o)) return s(o);
20
+ e.add(o);
21
+ let u = { root: o, multiplier: 1, offset: 0 };
22
+ if (a.mimic) {
23
+ const p = a.mimic;
24
+ if (![p.multiplier, p.offset].every(Number.isFinite) || !["revolute", "continuous", "prismatic"].includes(a.type) || !["revolute", "continuous", "prismatic"].includes(((l = t.get(p.joint)) == null ? void 0 : l.type) ?? "")) return s(o);
25
+ const c = r(p.joint);
26
+ if (u = { root: c.root, multiplier: p.multiplier * c.multiplier, offset: p.multiplier * c.offset + p.offset }, ![u.multiplier, u.offset].every(Number.isFinite)) return s(o);
27
+ }
28
+ return e.delete(o), i.set(o, u), u;
29
+ };
30
+ for (const o of n) r(o.id);
31
+ return i;
32
+ }
33
+ function xe(n) {
34
+ const t = Xi(n), i = /* @__PURE__ */ new Map();
35
+ for (const e of n) {
36
+ const s = t.get(e.id);
37
+ if (i.has(s.root) || i.set(s.root, { lower: -1 / 0, upper: 1 / 0 }), e.type === "continuous" || !e.limits || e.limits.lower > e.limits.upper) continue;
38
+ const r = i.get(s.root);
39
+ if (s.multiplier === 0) {
40
+ if (s.offset < e.limits.lower || s.offset > e.limits.upper) throw new Error(`URDF mimic constant violates limits: ${e.id}`);
41
+ continue;
42
+ }
43
+ const o = (e.limits.lower - s.offset) / s.multiplier, f = (e.limits.upper - s.offset) / s.multiplier;
44
+ if (r.lower = Math.max(r.lower, Math.min(o, f)), r.upper = Math.min(r.upper, Math.max(o, f)), r.lower > r.upper) throw new Error(`URDF mimic limits have no feasible range: ${s.root}`);
45
+ }
46
+ return i;
47
+ }
48
+ function Ke(n, t = {}) {
49
+ const i = Xi(n), e = xe(n);
50
+ return Object.fromEntries(n.map((s) => {
51
+ const r = i.get(s.id), o = e.get(r.root), f = Math.max(o.lower, Math.min(o.upper, t[r.root] ?? 0));
52
+ return [s.id, f * r.multiplier + r.offset];
53
+ }));
54
+ }
55
+ function Qt(n) {
56
+ return n.rotationQuaternion ? new K().fromArray(n.rotationQuaternion).normalize() : new K().setFromEuler(new Zt(n.rotationRpy[0], n.rotationRpy[1], n.rotationRpy[2], "ZYX"));
57
+ }
58
+ function In(n) {
59
+ const t = /* @__PURE__ */ new Map(), i = (e) => {
60
+ if (!(e instanceof yn || e instanceof ci)) return e;
61
+ const s = t.get(e);
62
+ if (s) return s;
63
+ const r = new Je({
64
+ name: e.name,
65
+ color: e.color.clone(),
66
+ emissive: e.emissive.clone(),
67
+ emissiveIntensity: e.emissiveIntensity,
68
+ map: e.map,
69
+ emissiveMap: e.emissiveMap,
70
+ normalMap: e.normalMap,
71
+ bumpMap: e.bumpMap,
72
+ bumpScale: e.bumpScale,
73
+ alphaMap: e.alphaMap,
74
+ aoMap: e.aoMap,
75
+ aoMapIntensity: e.aoMapIntensity,
76
+ lightMap: e.lightMap,
77
+ lightMapIntensity: e.lightMapIntensity,
78
+ opacity: e.opacity,
79
+ transparent: e.transparent,
80
+ alphaTest: e.alphaTest,
81
+ side: e.side,
82
+ depthWrite: e.depthWrite,
83
+ vertexColors: e.vertexColors,
84
+ flatShading: e.flatShading,
85
+ roughness: e instanceof ci ? Math.sqrt(2 / (Math.max(0, e.shininess) + 2)) : 0.5,
86
+ metalness: 0
87
+ });
88
+ return r.normalScale.copy(e.normalScale), r.normalMapType = e.normalMapType, r.userData = { ...e.userData, colladaSourceMaterial: e.type }, t.set(e, r), r;
89
+ };
90
+ n.traverse((e) => {
91
+ e instanceof C && (e.material = Array.isArray(e.material) ? e.material.map(i) : i(e.material));
92
+ });
93
+ for (const e of t.keys()) e.dispose();
94
+ }
95
+ async function Dn(n, t) {
96
+ var p, c, d;
97
+ const i = await t.text(n), e = new DOMParser().parseFromString(i, "application/xml");
98
+ if (e.querySelector("parsererror") || e.documentElement.localName !== "COLLADA")
99
+ throw new Error(`Invalid URDF COLLADA document: ${n}`);
100
+ const s = ((c = (p = e.querySelector("asset > up_axis")) == null ? void 0 : p.textContent) == null ? void 0 : c.trim()) ?? "Y_UP";
101
+ if (!["X_UP", "Y_UP", "Z_UP"].includes(s)) throw new Error(`Unsupported COLLADA up-axis: ${s}`);
102
+ const r = /* @__PURE__ */ new Map();
103
+ for (const y of e.querySelectorAll("library_images image init_from")) {
104
+ const g = (d = y.textContent) == null ? void 0 : d.trim();
105
+ if (!g || g.startsWith("data:")) continue;
106
+ const x = t.resolve(g, n);
107
+ await t.ensure(x), r.set(g, t.objectUrl(x));
108
+ }
109
+ const o = new ji();
110
+ o.setURLModifier((y) => {
111
+ if (y.startsWith("data:")) return y;
112
+ const g = r.get(y);
113
+ if (!g) throw new Error(`Unresolved COLLADA image: ${y}`);
114
+ return g;
115
+ });
116
+ let f;
117
+ const a = new Promise((y) => {
118
+ f = y;
119
+ });
120
+ let u;
121
+ o.onLoad = f, o.onError = (y) => {
122
+ u = y;
123
+ }, o.itemStart("urdf-collada-parse");
124
+ const l = new ut();
125
+ try {
126
+ const y = new zn(o).parse(i, "");
127
+ if (!(y != null && y.scene)) throw new Error(`COLLADA has no scene: ${n}`);
128
+ if (l.add(y.scene), s === "X_UP" ? y.scene.rotateY(-Math.PI / 2) : y.scene.rotateX(Math.PI / 2), o.itemEnd("urdf-collada-parse"), await a, u) throw new Error(`COLLADA texture failed to load: ${u}`);
129
+ let g = 0;
130
+ if (l.traverse((x) => {
131
+ x instanceof C && g++;
132
+ }), !g) throw new Error(`COLLADA has no visual meshes: ${n}`);
133
+ return In(l), l.updateMatrixWorld(!0), l;
134
+ } catch (y) {
135
+ throw dt(l), y;
136
+ }
137
+ }
138
+ function Ji(n) {
139
+ const [t, i, e, s, r, o] = n;
140
+ if (![t, i, e, s, r, o].every(Number.isFinite)) return !1;
141
+ const f = t * i - s * s, a = t * (i * e - o * o) - s * (s * e - o * r) + r * (s * o - i * r);
142
+ return t > 0 && f > 0 && a > 0 ? t <= i + e + 1e-12 && i <= t + e + 1e-12 && e <= t + i + 1e-12 : !1;
143
+ }
144
+ function Ln(n, t) {
145
+ if (!(t > 0) || !Number.isFinite(t) || n.length !== 6 || !n.every(Number.isFinite)) return null;
146
+ const i = [[n[0], n[3], n[4]], [n[3], n[1], n[5]], [n[4], n[5], n[2]]], e = [[1, 0, 0], [0, 1, 0], [0, 0, 1]], s = Math.max(...n.map(Math.abs));
147
+ for (let a = 0; a < 40; a++) {
148
+ let u = 0, l = 1;
149
+ for (const [w, m] of [[0, 1], [0, 2], [1, 2]]) Math.abs(i[w][m]) > Math.abs(i[u][l]) && (u = w, l = m);
150
+ if (Math.abs(i[u][l]) <= s * 1e-14) break;
151
+ const p = 0.5 * Math.atan2(2 * i[u][l], i[l][l] - i[u][u]), c = Math.cos(p), d = Math.sin(p), y = i[u][u], g = i[l][l], x = i[u][l];
152
+ for (let w = 0; w < 3; w++) {
153
+ if (w !== u && w !== l) {
154
+ const b = i[w][u], A = i[w][l];
155
+ i[w][u] = i[u][w] = c * b - d * A, i[w][l] = i[l][w] = d * b + c * A;
156
+ }
157
+ const m = e[w][u], h = e[w][l];
158
+ e[w][u] = c * m - d * h, e[w][l] = d * m + c * h;
159
+ }
160
+ i[u][u] = c * c * y - 2 * d * c * x + d * d * g, i[l][l] = d * d * y + 2 * d * c * x + c * c * g, i[u][l] = i[l][u] = 0;
161
+ }
162
+ const r = [i[0][0], i[1][1], i[2][2]], o = r.map((a, u) => 5 * (r[(u + 1) % 3] + r[(u + 2) % 3] - a) / (2 * t));
163
+ if (r.some((a) => a <= 0) || o.some((a) => a < -s * 1e-10 / t)) return null;
164
+ const f = new H().set(e[0][0], e[0][1], e[0][2], 0, e[1][0], e[1][1], e[1][2], 0, e[2][0], e[2][1], e[2][2], 0, 0, 0, 0, 1);
165
+ return { radii: o.map((a) => Math.sqrt(Math.max(0, a))), rotation: new K().setFromRotationMatrix(f) };
166
+ }
167
+ function kn(n, t) {
168
+ const i = Ln(n, t);
169
+ return i ? { size: i.radii.map((e) => e * Math.sqrt(12 / 5)), rotation: i.rotation } : null;
170
+ }
171
+ function Lt(n, t) {
172
+ if (!n) return [...t];
173
+ const i = n.trim().split(/\s+/).map(Number);
174
+ if (i.some((e) => !Number.isFinite(e))) throw O(`Invalid numeric value: ${n}`, "E_URDF_PARSE");
175
+ return i;
176
+ }
177
+ function he(n) {
178
+ const t = (n == null ? void 0 : n.querySelector("origin")) ?? null, i = Lt((t == null ? void 0 : t.getAttribute("quat_xyzw")) ?? null, []);
179
+ if (i.length !== 0 && i.length !== 4) throw O("URDF origin quat_xyzw requires four values.", "E_URDF_PARSE");
180
+ if (i.length && (t != null && t.hasAttribute("rpy"))) throw O("URDF origin cannot declare both rpy and quat_xyzw.", "E_URDF_PARSE");
181
+ return {
182
+ position: Lt((t == null ? void 0 : t.getAttribute("xyz")) ?? null, [0, 0, 0]),
183
+ rotationRpy: Lt((t == null ? void 0 : t.getAttribute("rpy")) ?? null, [0, 0, 0]),
184
+ ...i.length ? { rotationQuaternion: i } : {}
185
+ };
186
+ }
187
+ function mi(n, t, i) {
188
+ const e = n.querySelector("geometry"), s = e == null ? void 0 : e.querySelector("box");
189
+ if (s) return { type: "box", size: Xn(s.getAttribute("size"), 3, "box size") };
190
+ const r = e == null ? void 0 : e.querySelector("sphere");
191
+ if (r) return { type: "sphere", radius: jt(r.getAttribute("radius"), "sphere radius") };
192
+ const o = e == null ? void 0 : e.querySelector("cylinder");
193
+ if (o) return { type: "cylinder", radius: jt(o.getAttribute("radius"), "cylinder radius"), length: jt(o.getAttribute("length"), "cylinder length") };
194
+ const f = e == null ? void 0 : e.querySelector("capsule");
195
+ if (f) return { type: "capsule", radius: jt(f.getAttribute("radius"), "capsule radius"), length: jt(f.getAttribute("length"), "capsule length") };
196
+ const a = e == null ? void 0 : e.querySelector("mesh"), u = a == null ? void 0 : a.getAttribute("filename");
197
+ return u ? { type: "mesh", resourcePath: i.resolve(u, t), scale: Lt(a.getAttribute("scale"), [1, 1, 1]) } : null;
198
+ }
199
+ function jn(n, t, i) {
200
+ const s = Gn(n, "URDF").querySelector("robot");
201
+ if (!s) throw O("URDF requires a robot root element.", "E_URDF_PARSE");
202
+ const r = dn(), o = /* @__PURE__ */ new Map();
203
+ for (const u of s.children) if (u.tagName === "material" && u.getAttribute("name")) {
204
+ const l = u.getAttribute("name");
205
+ if (o.has(l)) throw O(`Duplicate URDF material: ${l}`, "E_URDF_MATERIAL");
206
+ o.set(l, u);
207
+ }
208
+ const f = [...s.querySelectorAll("link")].map((u) => ({
209
+ id: ot(u, "name"),
210
+ name: ot(u, "name"),
211
+ inertial: (() => {
212
+ const l = Jn(u);
213
+ return l && (!(l.mass > 0) || !Number.isFinite(l.mass) || !Ji(l.tensor)) && r.errors.push({ code: "E_URDF_INERTIA", message: `连杆 ${u.getAttribute("name")} 的质量或惯性张量无效。`, source: u.getAttribute("name") ?? void 0 }), l;
214
+ })(),
215
+ visuals: [...u.querySelectorAll("visual")].map((l) => {
216
+ const p = mi(l, t, i), c = l.querySelector("material"), d = c == null ? void 0 : c.getAttribute("name"), y = d ? o.get(d) : void 0, g = (c == null ? void 0 : c.querySelector("color")) ?? (y == null ? void 0 : y.querySelector("color")), x = (c == null ? void 0 : c.querySelector("texture")) ?? (y == null ? void 0 : y.querySelector("texture"));
217
+ d && !y && !g && !x && r.warnings.push({ code: "URDF_MATERIAL_UNRESOLVED", message: `Undefined material: ${d}`, source: u.getAttribute("name") ?? void 0 });
218
+ const w = g ? (g.getAttribute("rgba") ?? "").trim().split(/\s+/).map(Number) : x ? [1, 1, 1, 1] : void 0;
219
+ if (w && (w.length !== 4 || w.some((b) => !Number.isFinite(b) || b < 0 || b > 1))) throw O(`Invalid URDF material RGBA: ${d ?? ""}`, "E_URDF_MATERIAL");
220
+ const m = x == null ? void 0 : x.getAttribute("filename");
221
+ if (x && !m) throw O("URDF texture requires a filename", "E_URDF_MATERIAL");
222
+ const h = m ? i.resolve(m, t) : void 0;
223
+ return p ? { origin: he(l), geometry: p, color: w, texturePath: h } : null;
224
+ }).filter((l) => !!l),
225
+ collisions: [...u.querySelectorAll("collision")].map((l) => {
226
+ const p = mi(l, t, i);
227
+ return p ? { origin: he(l), geometry: p } : null;
228
+ }).filter((l) => !!l)
229
+ })), a = [...s.querySelectorAll("joint")].map((u) => {
230
+ var w;
231
+ const l = u.querySelector("limit"), p = u.querySelector("mimic"), c = p ? { joint: ot(p, "joint"), multiplier: Yt(p.getAttribute("multiplier"), "mimic multiplier") ?? 1, offset: Yt(p.getAttribute("offset"), "mimic offset") ?? 0 } : void 0, d = u.querySelector("dynamics"), y = d ? gi(d.getAttribute("damping"), 0) : 0, g = d ? gi(d.getAttribute("friction"), 0) : 0, x = d && (y > 0 || g > 0) ? { damping: y, friction: g } : void 0;
232
+ return {
233
+ id: ot(u, "name"),
234
+ type: u.getAttribute("type") ?? "fixed",
235
+ parent: ot(u.querySelector("parent"), "link"),
236
+ child: ot(u.querySelector("child"), "link"),
237
+ origin: he(u),
238
+ axis: Lt(((w = u.querySelector("axis")) == null ? void 0 : w.getAttribute("xyz")) ?? null, [1, 0, 0]),
239
+ ...l ? {
240
+ limits: { lower: Le(l.getAttribute("lower"), `Joint ${ot(u, "name")} limit lower`), upper: Le(l.getAttribute("upper"), `Joint ${ot(u, "name")} limit upper`) },
241
+ effort: Yt(l.getAttribute("effort"), `Joint ${ot(u, "name")} limit effort`),
242
+ velocity: Yt(l.getAttribute("velocity"), `Joint ${ot(u, "name")} limit velocity`)
243
+ } : {},
244
+ ...x ? { dynamics: x } : {},
245
+ ...c ? { mimic: c } : {}
246
+ };
247
+ });
248
+ return xe(a), s.querySelector("transmission, gazebo") && r.droppedFeatures.push({ code: "UNSUPPORTED_URDF_EXTENSION", message: "URDF transmission/gazebo extensions are not compiled." }), fn({ id: s.getAttribute("name") || t, name: s.getAttribute("name") || t, source: { format: "urdf", uri: t }, links: f, joints: a, diagnostics: r, extension: { files: i } }, { allowInvalidGraph: !0 });
249
+ }
250
+ function hi(n) {
251
+ const t = Qt(n);
252
+ return `quat="${t.w} ${t.x} ${t.y} ${t.z}"`;
253
+ }
254
+ function Ie(n) {
255
+ const t = new H(), i = Qt(n);
256
+ return t.compose(new z().fromArray(n.position), i, new z(1, 1, 1));
257
+ }
258
+ function Cn(n) {
259
+ if (n.type === "continuous" || !n.limits) return 0;
260
+ const { lower: t, upper: i } = n.limits;
261
+ return !Number.isFinite(t) || !Number.isFinite(i) ? 0 : xn.clamp(0, t, i);
262
+ }
263
+ function Nn(n) {
264
+ let t;
265
+ if (n.type === "box")
266
+ t = [n.size[0] / 2, n.size[1] / 2, n.size[2] / 2];
267
+ else if (n.type === "sphere")
268
+ t = [n.radius, n.radius, n.radius];
269
+ else if (n.type === "cylinder")
270
+ t = [n.radius, n.radius, n.length / 2];
271
+ else
272
+ return null;
273
+ const i = [];
274
+ for (const e of [-t[0], t[0]])
275
+ for (const s of [-t[1], t[1]])
276
+ for (const r of [-t[2], t[2]])
277
+ i.push(new z(e, s, r));
278
+ return i;
279
+ }
280
+ function Hi(n, t, i) {
281
+ let e = 0;
282
+ const s = new Map(n.links.map((l) => [l.id, l])), r = Ke(n.joints), o = (l) => {
283
+ let p = 1 / 0;
284
+ const c = (d, y) => {
285
+ const g = s.get(d);
286
+ if (g) {
287
+ for (const x of g.collisions) {
288
+ const w = Nn(x.geometry);
289
+ if (!w) {
290
+ l && (e += 1);
291
+ continue;
292
+ }
293
+ const m = y.clone().multiply(Ie(x.origin));
294
+ for (const h of w)
295
+ p = Math.min(p, h.applyMatrix4(m).z);
296
+ }
297
+ for (const x of i.get(d) ?? []) {
298
+ const w = y.clone().multiply(Ie(x.origin)), m = l ? r[x.id] : 0;
299
+ m && x.type === "revolute" ? w.multiply(new H().makeRotationAxis(new z().fromArray(x.axis).normalize(), m)) : m && x.type === "prismatic" && w.multiply(new H().makeTranslation(x.axis[0] * m, x.axis[1] * m, x.axis[2] * m)), c(x.child, w);
300
+ }
301
+ }
302
+ };
303
+ return c(t, new H()), p;
304
+ }, f = o(!0), a = o(!1), u = Math.min(f, a);
305
+ return e && n.diagnostics.warnings.push({
306
+ code: "GROUNDING_IGNORED_MESH_COLLIDERS",
307
+ message: `自动落地忽略了 ${e} 个网格碰撞体`
308
+ }), Number.isFinite(u) ? Math.max(0, 0.015 - u) : 0;
309
+ }
310
+ async function qn(n) {
311
+ const t = n.extension.files, i = /* @__PURE__ */ new Map(), e = new Set(n.joints.map((w) => w.child));
312
+ for (const w of n.joints) i.set(w.parent, [...i.get(w.parent) ?? [], w]);
313
+ const s = n.links.filter((w) => !e.has(w.id));
314
+ if (s.length !== 1) throw O(`URDF requires exactly one root link; found ${s.length}.`, "E_URDF_COMPILE");
315
+ const r = Hi(n, s[0].id, i);
316
+ r > 0 && n.diagnostics.approximations.push({
317
+ code: "AUTO_GROUNDED_FREE_ROOT",
318
+ message: `自由根初始高度自动抬升 ${r.toFixed(4)} m`
319
+ });
320
+ const o = n.joints.filter((w) => Cn(w) !== 0);
321
+ o.length && n.diagnostics.approximations.push({
322
+ code: "JOINT_REFERENCE_CLAMPED",
323
+ message: `${o.length} 个关节的默认参考值已夹到合法限位`
324
+ });
325
+ const f = /* @__PURE__ */ new Map(), a = /* @__PURE__ */ new Map(), u = [], l = Ke(n.joints), p = async (w) => {
326
+ var A;
327
+ if (w.type === "box") return `type="box" size="${w.size.map((P) => P / 2).join(" ")}"`;
328
+ if (w.type === "sphere") return `type="sphere" size="${w.radius}"`;
329
+ if (w.type === "cylinder") return `type="cylinder" size="${w.radius} ${w.length / 2}"`;
330
+ if (w.type === "capsule") return `type="capsule" size="${w.radius} ${w.length / 2}"`;
331
+ const m = (A = w.resourcePath.split(".").pop()) == null ? void 0 : A.toLowerCase();
332
+ if (m !== "stl" && m !== "obj") return null;
333
+ const h = `${w.resourcePath}|${w.scale.join(" ")}`;
334
+ let b = a.get(h);
335
+ if (!b) {
336
+ const P = { name: `mesh_${a.size}`, path: w.resourcePath, scale: w.scale };
337
+ a.set(h, P);
338
+ const M = await t.bytes(w.resourcePath);
339
+ f.set(`${P.name}.${m}`, M), b = P;
340
+ }
341
+ return `type="mesh" mesh="${b.name}"`;
342
+ }, c = async (w, m) => {
343
+ var M, T;
344
+ const h = n.links.find((R) => R.id === w), b = [...(m == null ? void 0 : m.origin.position) ?? [0, 0, 0]];
345
+ m || (b[2] += r);
346
+ const A = (m == null ? void 0 : m.origin) ?? { rotationRpy: [0, 0, 0] }, P = [`<body name="${St(w)}" pos="${b.join(" ")}" ${hi(A)}>`];
347
+ if (h.inertial) {
348
+ const { origin: R, mass: v, tensor: _ } = h.inertial, S = new li().setFromMatrix4(new H().makeRotationFromQuaternion(Qt(R))), B = new li().set(_[0], _[3], _[4], _[3], _[1], _[5], _[4], _[5], _[2]);
349
+ B.premultiply(S).multiply(S.clone().transpose());
350
+ const E = B.elements;
351
+ P.push(`<inertial pos="${R.position.join(" ")}" mass="${v}" fullinertia="${[E[0], E[4], E[8], E[3], E[6], E[7]].join(" ")}"/>`);
352
+ }
353
+ if (!m) P.push("<freejoint/>");
354
+ else if (["fixed", "planar", "floating"].includes(m.type))
355
+ (m == null ? void 0 : m.type) === "floating" && (P.push("<freejoint/>"), u.push(0, 0, 0, 1, 0, 0, 0));
356
+ else {
357
+ const R = m.type === "prismatic" ? "slide" : "hinge", v = m.type !== "continuous" && !!m.limits && Number.isFinite(m.limits.lower) && Number.isFinite(m.limits.upper), _ = l[m.id];
358
+ u.push(_);
359
+ const S = ((M = m.dynamics) == null ? void 0 : M.damping) ?? 0, B = ((T = m.dynamics) == null ? void 0 : T.friction) ?? 0;
360
+ P.push(`<joint name="${St(m.id)}" type="${R}" axis="${m.axis.join(" ")}"${v ? ` limited="true" range="${m.limits.lower} ${m.limits.upper}" ref="0"` : ""} damping="${S}" frictionloss="${B}"/>`);
361
+ }
362
+ for (const R of h.collisions) {
363
+ const v = await p(R.geometry);
364
+ if (v) {
365
+ const _ = ` ${hi(R.origin)}`;
366
+ P.push(`<geom ${v} pos="${R.origin.position.join(" ")}"${_} rgba="0.55 0.62 0.59 1"/>`);
367
+ }
368
+ }
369
+ for (const R of i.get(w) ?? []) P.push(await c(R.child, R));
370
+ return P.push("</body>"), P.join("");
371
+ }, d = await c(s[0].id), y = [...a.values()].map((w) => {
372
+ var m;
373
+ return `<mesh name="${w.name}" file="${w.name}.${(m = w.path.split(".").pop()) == null ? void 0 : m.toLowerCase()}" scale="${w.scale.join(" ")}"/>`;
374
+ }).join(""), g = `<keyframe><key name="home" qpos="0 0 ${r} 1 0 0 0 ${u.join(" ")}"/></keyframe>`, x = n.joints.filter((w) => w.mimic).map((w) => {
375
+ const m = w.mimic;
376
+ return `<joint name="mimic_${St(w.id)}" joint1="${St(w.id)}" joint2="${St(m.joint)}" polycoef="${m.offset} ${m.multiplier} 0 0 0"/>`;
377
+ }).join("");
378
+ return {
379
+ format: "mjcf",
380
+ files: f,
381
+ xml: `<mujoco model="${St(n.name)}"><compiler angle="radian" autolimits="true"/><option gravity="0 0 -9.81"/><asset>${y}</asset><worldbody><geom name="__viewer_default_ground__" type="plane" size="5 5 0.1" contype="1" conaffinity="1" friction="0.8 0.01 0.0002"/>${d}</worldbody>${x ? `<equality>${x}</equality>` : ""}${g}</mujoco>`
382
+ };
383
+ }
384
+ async function Zi(n) {
385
+ const t = n.extension.files, i = new ut();
386
+ i.name = "URDF authored collisions";
387
+ const e = /* @__PURE__ */ new Map(), s = pn();
388
+ let r = 0;
389
+ for (const o of n.links) {
390
+ const f = new ut();
391
+ f.name = o.id, f.userData.urdfEntityId = `link:${o.id}`, e.set(o.id, f), i.add(f);
392
+ for (const a of o.collisions) {
393
+ const u = new ut();
394
+ if (u.matrixAutoUpdate = !1, u.matrix.copy(Ie(a.origin)), f.add(u), a.geometry.type === "mesh") {
395
+ const l = await De(a.geometry, t, new Je());
396
+ l.updateMatrixWorld(!0), l.traverse((p) => {
397
+ if (!(p instanceof C)) return;
398
+ const c = ri(p.geometry, s, "mesh");
399
+ c.matrixAutoUpdate = !1, c.matrix.copy(p.matrixWorld), c.name = `Collision:${o.id}`, c.userData.urdfLink = o.id, u.add(c), r += 1;
400
+ }), dt(l);
401
+ } else {
402
+ const l = Vn(a.geometry);
403
+ if (!l) continue;
404
+ const p = ri(l, s, "feature");
405
+ l.dispose(), p.name = `Collision:${o.id}`, p.userData.urdfLink = o.id, u.add(p), r += 1;
406
+ }
407
+ }
408
+ }
409
+ if (r === 0) {
410
+ s.dispose(), dt(i);
411
+ return;
412
+ }
413
+ return { root: i, bindings: e, expectedLinkCount: e.size };
414
+ }
415
+ async function On(n, t) {
416
+ const i = await Zi(n);
417
+ if (!i) return;
418
+ const e = () => {
419
+ t.root.updateMatrixWorld(!0);
420
+ for (const [s, r] of i.bindings) {
421
+ const o = t.bindings.get(s);
422
+ o && (r.matrixAutoUpdate = !1, r.matrix.copy(o.matrixWorld));
423
+ }
424
+ i.root.updateMatrixWorld(!0);
425
+ };
426
+ return e(), i.root.visible = !1, { root: i.root, sync: e, dispose() {
427
+ dt(i.root);
428
+ } };
429
+ }
430
+ function Vn(n) {
431
+ if (n.type === "box") return new He(...n.size);
432
+ if (n.type === "sphere") return new Ze(n.radius, 24, 16);
433
+ if (n.type === "cylinder") {
434
+ const t = new Ci(n.radius, n.radius, n.length, 24);
435
+ return t.rotateX(Math.PI / 2), t;
436
+ }
437
+ if (n.type === "capsule") {
438
+ const t = new Ni(n.radius, n.length, 8, 24);
439
+ return t.rotateX(Math.PI / 2), t;
440
+ }
441
+ return null;
442
+ }
443
+ async function yi(n) {
444
+ const t = n.extension.files, i = new ut();
445
+ i.name = n.name;
446
+ const e = /* @__PURE__ */ new Map();
447
+ try {
448
+ for (const s of n.links) {
449
+ const r = new ut();
450
+ r.name = s.id, r.userData.urdfEntityId = `link:${s.id}`, e.set(s.id, r), i.add(r);
451
+ for (const o of s.visuals) {
452
+ const f = await Wn(o, t, n.diagnostics), a = new ut();
453
+ a.position.fromArray(o.origin.position), a.quaternion.copy(Qt(o.origin)), a.add(f), r.add(a);
454
+ }
455
+ }
456
+ return { root: i, bindings: e, expectedLinkCount: n.links.length };
457
+ } catch (s) {
458
+ throw dt(i), s;
459
+ }
460
+ }
461
+ async function Wn(n, t, i) {
462
+ var r;
463
+ if (n.geometry.type === "mesh" && /\.gl(?:tf|b)$/i.test(n.geometry.resourcePath)) {
464
+ (n.color || n.texturePath) && i.warnings.push({ code: "URDF_EMBEDDED_MATERIAL_PRESERVED", message: "Embedded glTF materials take precedence over the URDF visual material.", source: n.geometry.resourcePath });
465
+ const o = oi();
466
+ try {
467
+ return await De(n.geometry, t, o);
468
+ } finally {
469
+ o.dispose();
470
+ }
471
+ }
472
+ const e = oi({ color: n.color });
473
+ let s;
474
+ try {
475
+ if (n.texturePath && (await t.ensure(n.texturePath), e.map = await new gn().loadAsync(t.objectUrl(n.texturePath)), e.transparent = !0, e.map.colorSpace = wn, e.map.wrapS = e.map.wrapT = bn), s = await De(n.geometry, t, e), n.geometry.type === "mesh" && /\.dae$/i.test(n.geometry.resourcePath))
476
+ if (n.color || n.texturePath) {
477
+ const o = /* @__PURE__ */ new Set(), f = /* @__PURE__ */ new Set();
478
+ s.traverse((a) => {
479
+ if (a instanceof C) {
480
+ for (const u of Array.isArray(a.material) ? a.material : [a.material]) o.add(u);
481
+ a.material = e;
482
+ }
483
+ });
484
+ for (const a of o) {
485
+ for (const u of Object.values(a)) u != null && u.isTexture && f.add(u);
486
+ a.dispose();
487
+ }
488
+ for (const a of f) a.dispose();
489
+ } else e.dispose();
490
+ return e.map && s.traverse((o) => {
491
+ if (o instanceof C && !o.geometry.getAttribute("uv")) throw O(`URDF texture requires authored UVs: ${n.texturePath}`, "E_URDF_TEXTURE_UV");
492
+ }), s;
493
+ } catch (o) {
494
+ throw s ? dt(s) : ((r = e.map) == null || r.dispose(), e.dispose()), o;
495
+ }
496
+ }
497
+ async function De(n, t, i) {
498
+ var r;
499
+ if (n.type === "box") return new C(new He(...n.size), i);
500
+ if (n.type === "sphere") return new C(new Ze(n.radius, 24, 16), i);
501
+ if (n.type === "cylinder") {
502
+ const o = new C(new Ci(n.radius, n.radius, n.length, 24), i);
503
+ return o.quaternion.copy(new K().setFromEuler(new Zt(Math.PI / 2, 0, 0))), o;
504
+ }
505
+ if (n.type === "capsule") {
506
+ const o = new C(new Ni(n.radius, n.length, 8, 24), i);
507
+ return o.quaternion.copy(new K().setFromEuler(new Zt(Math.PI / 2, 0, 0))), o;
508
+ }
509
+ const e = (r = n.resourcePath.split(".").pop()) == null ? void 0 : r.toLowerCase();
510
+ await t.ensure(n.resourcePath);
511
+ let s;
512
+ if (e === "stl") s = new C(new $n().parse(await t.getBlob(n.resourcePath).arrayBuffer()), i);
513
+ else if (e === "obj")
514
+ s = new Un().parse(await t.getBlob(n.resourcePath).text()), s.traverse((o) => {
515
+ if (o instanceof C) {
516
+ for (const f of Array.isArray(o.material) ? o.material : [o.material]) f.dispose();
517
+ o.material = i;
518
+ }
519
+ });
520
+ else if (e === "gltf" || e === "glb") {
521
+ const o = new ji();
522
+ o.setURLModifier((f) => {
523
+ try {
524
+ return t.objectUrl(t.resolve(f, n.resourcePath));
525
+ } catch {
526
+ return f;
527
+ }
528
+ }), s = (await new En(o).parseAsync(await t.getBlob(n.resourcePath).arrayBuffer(), "")).scene;
529
+ } else if (e === "dae") s = await Dn(n.resourcePath, t);
530
+ else throw O(`Unsupported URDF visual mesh: .${e ?? ""}`, "E_URDF_VISUAL");
531
+ return s.scale.fromArray(n.scale), s;
532
+ }
533
+ function Gn(n, t) {
534
+ const i = new DOMParser().parseFromString(n, "application/xml"), e = i.querySelector("parsererror");
535
+ if (e) throw O(`${t} XML parse failed: ${e.textContent ?? ""}`, `E_${t}_PARSE`);
536
+ return i;
537
+ }
538
+ function ot(n, t) {
539
+ const i = n == null ? void 0 : n.getAttribute(t);
540
+ if (!i) throw O(`Missing ${t}.`, "E_URDF_PARSE");
541
+ return i;
542
+ }
543
+ function gi(n, t) {
544
+ const i = Number(n);
545
+ return Number.isFinite(i) ? i : t;
546
+ }
547
+ function Le(n, t) {
548
+ if (n === null || n.trim() === "") throw O(`${t} is required.`, "E_URDF_PARSE");
549
+ const i = Number(n);
550
+ if (!Number.isFinite(i)) throw O(`${t} must be finite.`, "E_URDF_PARSE");
551
+ return i;
552
+ }
553
+ function jt(n, t) {
554
+ const i = Le(n, t);
555
+ if (!(i > 0)) throw O(`${t} must be greater than zero.`, "E_URDF_PARSE");
556
+ return i;
557
+ }
558
+ function Xn(n, t, i) {
559
+ if (n === null || n.trim() === "") throw O(`${i} is required.`, "E_URDF_PARSE");
560
+ const e = Lt(n, []);
561
+ if (e.length !== t || e.some((s) => !(s > 0))) throw O(`${i} requires ${t} values greater than zero.`, "E_URDF_PARSE");
562
+ return e;
563
+ }
564
+ function Yt(n, t) {
565
+ if (n === null || n.trim() === "") return;
566
+ const i = Number(n);
567
+ if (!Number.isFinite(i)) throw O(`${t} must be finite.`, "E_URDF_PARSE");
568
+ return i;
569
+ }
570
+ function St(n) {
571
+ return n.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
572
+ }
573
+ function O(n, t) {
574
+ return Object.assign(new Error(n), { code: t });
575
+ }
576
+ function Jn(n) {
577
+ var o;
578
+ const t = n.querySelector("inertial");
579
+ if (!t) return;
580
+ const i = t.querySelector("inertia"), e = (o = t.querySelector("mass")) == null ? void 0 : o.getAttribute("value"), s = e == null || e.trim() === "" ? Number.NaN : Number(e), r = ["ixx", "iyy", "izz", "ixy", "ixz", "iyz"].map((f) => {
581
+ const a = i == null ? void 0 : i.getAttribute(f);
582
+ return a == null || a.trim() === "" ? Number.NaN : Number(a);
583
+ });
584
+ return { origin: he(t), mass: s, tensor: r };
585
+ }
586
+ const Qi = 0, Hn = 1, Zn = 2, wi = 2, Pe = 1.25, bi = 1, X = 6 * 4 + 4 + 4, N = X / 4, Yi = 65535, ye = Math.pow(2, -24), ti = Symbol("SKIP_GENERATION"), Ki = {
587
+ strategy: Qi,
588
+ maxDepth: 40,
589
+ maxLeafSize: 10,
590
+ useSharedArrayBuffer: !1,
591
+ setBoundingBox: !0,
592
+ onProgress: null,
593
+ indirect: !1,
594
+ verbose: !0,
595
+ range: null,
596
+ [ti]: !1
597
+ };
598
+ function k(n, t, i) {
599
+ return i.min.x = t[n], i.min.y = t[n + 1], i.min.z = t[n + 2], i.max.x = t[n + 3], i.max.y = t[n + 4], i.max.z = t[n + 5], i;
600
+ }
601
+ function xi(n) {
602
+ let t = -1, i = -1 / 0;
603
+ for (let e = 0; e < 3; e++) {
604
+ const s = n[e + 3] - n[e];
605
+ s > i && (i = s, t = e);
606
+ }
607
+ return t;
608
+ }
609
+ function Ai(n, t) {
610
+ t.set(n);
611
+ }
612
+ function Mi(n, t, i) {
613
+ let e, s;
614
+ for (let r = 0; r < 3; r++) {
615
+ const o = r + 3;
616
+ e = n[r], s = t[r], i[r] = e < s ? e : s, e = n[o], s = t[o], i[o] = e > s ? e : s;
617
+ }
618
+ }
619
+ function Kt(n, t, i) {
620
+ for (let e = 0; e < 3; e++) {
621
+ const s = t[n + 2 * e], r = t[n + 2 * e + 1], o = s - r, f = s + r;
622
+ o < i[e] && (i[e] = o), f > i[e + 3] && (i[e + 3] = f);
623
+ }
624
+ }
625
+ function Ct(n) {
626
+ const t = n[3] - n[0], i = n[4] - n[1], e = n[5] - n[2];
627
+ return 2 * (t * i + i * e + e * t);
628
+ }
629
+ function q(n, t) {
630
+ return t[n + 15] === Yi;
631
+ }
632
+ function J(n, t) {
633
+ return t[n + 6];
634
+ }
635
+ function Z(n, t) {
636
+ return t[n + 14];
637
+ }
638
+ function V(n) {
639
+ return n + N;
640
+ }
641
+ function W(n, t) {
642
+ const i = t[n + 6];
643
+ return n + i * N;
644
+ }
645
+ function ei(n, t) {
646
+ return t[n + 7];
647
+ }
648
+ function Se(n, t, i, e, s) {
649
+ let r = 1 / 0, o = 1 / 0, f = 1 / 0, a = -1 / 0, u = -1 / 0, l = -1 / 0, p = 1 / 0, c = 1 / 0, d = 1 / 0, y = -1 / 0, g = -1 / 0, x = -1 / 0;
650
+ const w = n.offset || 0;
651
+ for (let m = (t - w) * 6, h = (t + i - w) * 6; m < h; m += 6) {
652
+ const b = n[m + 0], A = n[m + 1], P = b - A, M = b + A;
653
+ P < r && (r = P), M > a && (a = M), b < p && (p = b), b > y && (y = b);
654
+ const T = n[m + 2], R = n[m + 3], v = T - R, _ = T + R;
655
+ v < o && (o = v), _ > u && (u = _), T < c && (c = T), T > g && (g = T);
656
+ const S = n[m + 4], B = n[m + 5], E = S - B, U = S + B;
657
+ E < f && (f = E), U > l && (l = U), S < d && (d = S), S > x && (x = S);
658
+ }
659
+ e[0] = r, e[1] = o, e[2] = f, e[3] = a, e[4] = u, e[5] = l, s[0] = p, s[1] = c, s[2] = d, s[3] = y, s[4] = g, s[5] = x;
660
+ }
661
+ const ct = 32, Qn = (n, t) => n.candidate - t.candidate, mt = /* @__PURE__ */ new Array(ct).fill().map(() => ({
662
+ count: 0,
663
+ bounds: new Float32Array(6),
664
+ rightCacheBounds: new Float32Array(6),
665
+ leftCacheBounds: new Float32Array(6),
666
+ candidate: 0
667
+ })), te = /* @__PURE__ */ new Float32Array(6);
668
+ function Yn(n, t, i, e, s, r) {
669
+ let o = -1, f = 0;
670
+ if (r === Qi)
671
+ o = xi(t), o !== -1 && (f = (t[o] + t[o + 3]) / 2);
672
+ else if (r === Hn)
673
+ o = xi(n), o !== -1 && (f = Kn(i, e, s, o));
674
+ else if (r === Zn) {
675
+ const a = Ct(n);
676
+ let u = Pe * s;
677
+ const l = i.offset || 0, p = (e - l) * 6, c = (e + s - l) * 6;
678
+ for (let d = 0; d < 3; d++) {
679
+ const y = t[d], w = (t[d + 3] - y) / ct;
680
+ if (s < ct / 4) {
681
+ const m = [...mt];
682
+ m.length = s;
683
+ let h = 0;
684
+ for (let A = p; A < c; A += 6, h++) {
685
+ const P = m[h];
686
+ P.candidate = i[A + 2 * d], P.count = 0;
687
+ const {
688
+ bounds: M,
689
+ leftCacheBounds: T,
690
+ rightCacheBounds: R
691
+ } = P;
692
+ for (let v = 0; v < 3; v++)
693
+ R[v] = 1 / 0, R[v + 3] = -1 / 0, T[v] = 1 / 0, T[v + 3] = -1 / 0, M[v] = 1 / 0, M[v + 3] = -1 / 0;
694
+ Kt(A, i, M);
695
+ }
696
+ m.sort(Qn);
697
+ let b = s;
698
+ for (let A = 0; A < b; A++) {
699
+ const P = m[A];
700
+ for (; A + 1 < b && m[A + 1].candidate === P.candidate; )
701
+ m.splice(A + 1, 1), b--;
702
+ }
703
+ for (let A = p; A < c; A += 6) {
704
+ const P = i[A + 2 * d];
705
+ for (let M = 0; M < b; M++) {
706
+ const T = m[M];
707
+ P >= T.candidate ? Kt(A, i, T.rightCacheBounds) : (Kt(A, i, T.leftCacheBounds), T.count++);
708
+ }
709
+ }
710
+ for (let A = 0; A < b; A++) {
711
+ const P = m[A], M = P.count, T = s - P.count, R = P.leftCacheBounds, v = P.rightCacheBounds;
712
+ let _ = 0;
713
+ M !== 0 && (_ = Ct(R) / a);
714
+ let S = 0;
715
+ T !== 0 && (S = Ct(v) / a);
716
+ const B = bi + Pe * (_ * M + S * T);
717
+ B < u && (o = d, u = B, f = P.candidate);
718
+ }
719
+ } else {
720
+ for (let b = 0; b < ct; b++) {
721
+ const A = mt[b];
722
+ A.count = 0, A.candidate = y + w + b * w;
723
+ const P = A.bounds;
724
+ for (let M = 0; M < 3; M++)
725
+ P[M] = 1 / 0, P[M + 3] = -1 / 0;
726
+ }
727
+ for (let b = p; b < c; b += 6) {
728
+ let M = ~~((i[b + 2 * d] - y) / w);
729
+ M >= ct && (M = ct - 1);
730
+ const T = mt[M];
731
+ T.count++, Kt(b, i, T.bounds);
732
+ }
733
+ const m = mt[ct - 1];
734
+ Ai(m.bounds, m.rightCacheBounds);
735
+ for (let b = ct - 2; b >= 0; b--) {
736
+ const A = mt[b], P = mt[b + 1];
737
+ Mi(A.bounds, P.rightCacheBounds, A.rightCacheBounds);
738
+ }
739
+ let h = 0;
740
+ for (let b = 0; b < ct - 1; b++) {
741
+ const A = mt[b], P = A.count, M = A.bounds, R = mt[b + 1].rightCacheBounds;
742
+ P !== 0 && (h === 0 ? Ai(M, te) : Mi(M, te, te)), h += P;
743
+ let v = 0, _ = 0;
744
+ h !== 0 && (v = Ct(te) / a);
745
+ const S = s - h;
746
+ S !== 0 && (_ = Ct(R) / a);
747
+ const B = bi + Pe * (v * h + _ * S);
748
+ B < u && (o = d, u = B, f = A.candidate);
749
+ }
750
+ }
751
+ }
752
+ } else
753
+ console.warn(`BVH: Invalid build strategy value ${r} used.`);
754
+ return { axis: o, pos: f };
755
+ }
756
+ function Kn(n, t, i, e) {
757
+ let s = 0;
758
+ const r = n.offset;
759
+ for (let o = t, f = t + i; o < f; o++)
760
+ s += n[(o - r) * 6 + e * 2];
761
+ return s / i;
762
+ }
763
+ class Te {
764
+ constructor() {
765
+ this.boundingData = new Float32Array(6);
766
+ }
767
+ }
768
+ function ts(n, t, i, e, s, r) {
769
+ let o = e, f = e + s - 1;
770
+ const a = r.pos, u = r.axis * 2, l = i.offset || 0;
771
+ for (; ; ) {
772
+ for (; o <= f && i[(o - l) * 6 + u] < a; )
773
+ o++;
774
+ for (; o <= f && i[(f - l) * 6 + u] >= a; )
775
+ f--;
776
+ if (o < f) {
777
+ for (let p = 0; p < t; p++) {
778
+ let c = n[o * t + p];
779
+ n[o * t + p] = n[f * t + p], n[f * t + p] = c;
780
+ }
781
+ for (let p = 0; p < 6; p++) {
782
+ const c = o - l, d = f - l, y = i[c * 6 + p];
783
+ i[c * 6 + p] = i[d * 6 + p], i[d * 6 + p] = y;
784
+ }
785
+ o++, f--;
786
+ } else
787
+ return o;
788
+ }
789
+ }
790
+ let tn, ge, ke, en;
791
+ const es = Math.pow(2, 32);
792
+ function je(n) {
793
+ return "count" in n ? 1 : 1 + je(n.left) + je(n.right);
794
+ }
795
+ function is(n, t, i) {
796
+ return tn = new Float32Array(i), ge = new Uint32Array(i), ke = new Uint16Array(i), en = new Uint8Array(i), Ce(n, t);
797
+ }
798
+ function Ce(n, t) {
799
+ const i = n / 4, e = n / 2, s = "count" in t, r = t.boundingData;
800
+ for (let o = 0; o < 6; o++)
801
+ tn[i + o] = r[o];
802
+ if (s)
803
+ return t.buffer ? (en.set(new Uint8Array(t.buffer), n), n + t.buffer.byteLength) : (ge[i + 6] = t.offset, ke[e + 14] = t.count, ke[e + 15] = Yi, n + X);
804
+ {
805
+ const { left: o, right: f, splitAxis: a } = t, u = n + X;
806
+ let l = Ce(u, o);
807
+ const p = n / X, d = l / X - p;
808
+ if (d > es)
809
+ throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");
810
+ return ge[i + 6] = d, ge[i + 7] = a, Ce(l, f);
811
+ }
812
+ }
813
+ function ns(n, t, i, e, s, r) {
814
+ const {
815
+ maxDepth: o,
816
+ verbose: f,
817
+ maxLeafSize: a,
818
+ strategy: u,
819
+ onProgress: l
820
+ } = s, p = n.primitiveBuffer, c = n.primitiveBufferStride, d = new Float32Array(6);
821
+ let y = !1;
822
+ const g = new Te();
823
+ return Se(t, i, e, g.boundingData, d), w(g, i, e, d), g;
824
+ function x(m) {
825
+ l && l((m - r.offset) / r.count);
826
+ }
827
+ function w(m, h, b, A = null, P = 0) {
828
+ if (!y && P >= o && (y = !0, f && console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`)), b <= a || P >= o)
829
+ return x(h + b), m.offset = h, m.count = b, m;
830
+ const M = Yn(m.boundingData, A, t, h, b, u);
831
+ if (M.axis === -1)
832
+ return x(h + b), m.offset = h, m.count = b, m;
833
+ const T = ts(p, c, t, h, b, M);
834
+ if (T === h || T === h + b)
835
+ x(h + b), m.offset = h, m.count = b;
836
+ else {
837
+ m.splitAxis = M.axis;
838
+ const R = new Te(), v = h, _ = T - h;
839
+ m.left = R, Se(t, v, _, R.boundingData, d), w(R, v, _, d, P + 1);
840
+ const S = new Te(), B = T, E = b - _;
841
+ m.right = S, Se(t, B, E, S.boundingData, d), w(S, B, E, d, P + 1);
842
+ }
843
+ return m;
844
+ }
845
+ }
846
+ function ss(n, t) {
847
+ const i = t.useSharedArrayBuffer ? SharedArrayBuffer : ArrayBuffer, e = n.getRootRanges(t.range), s = e[0], r = e[e.length - 1], o = {
848
+ offset: s.offset,
849
+ count: r.offset + r.count - s.offset
850
+ }, f = new Float32Array(6 * o.count);
851
+ f.offset = o.offset, n.computePrimitiveBounds(o.offset, o.count, f), n._roots = e.map((a) => {
852
+ const u = ns(n, f, a.offset, a.count, t, o), l = je(u), p = new i(X * l);
853
+ return is(0, u, p), p;
854
+ });
855
+ }
856
+ class ii {
857
+ constructor(t) {
858
+ this._getNewPrimitive = t, this._primitives = [];
859
+ }
860
+ getPrimitive() {
861
+ const t = this._primitives;
862
+ return t.length === 0 ? this._getNewPrimitive() : t.pop();
863
+ }
864
+ releasePrimitive(t) {
865
+ this._primitives.push(t);
866
+ }
867
+ }
868
+ class os {
869
+ constructor() {
870
+ this.float32Array = null, this.uint16Array = null, this.uint32Array = null;
871
+ const t = [];
872
+ let i = null;
873
+ this.setBuffer = (e) => {
874
+ i && t.push(i), i = e, this.float32Array = new Float32Array(e), this.uint16Array = new Uint16Array(e), this.uint32Array = new Uint32Array(e);
875
+ }, this.clearBuffer = () => {
876
+ i = null, this.float32Array = null, this.uint16Array = null, this.uint32Array = null, t.length !== 0 && this.setBuffer(t.pop());
877
+ };
878
+ }
879
+ }
880
+ const I = /* @__PURE__ */ new os();
881
+ let yt, Dt;
882
+ const Tt = [], ee = /* @__PURE__ */ new ii(() => new it());
883
+ function rs(n, t, i, e, s, r) {
884
+ yt = ee.getPrimitive(), Dt = ee.getPrimitive(), Tt.push(yt, Dt), I.setBuffer(n._roots[t]);
885
+ const o = Ne(0, n.geometry, i, e, s, r);
886
+ I.clearBuffer(), ee.releasePrimitive(yt), ee.releasePrimitive(Dt), Tt.pop(), Tt.pop();
887
+ const f = Tt.length;
888
+ return f > 0 && (Dt = Tt[f - 1], yt = Tt[f - 2]), o;
889
+ }
890
+ function Ne(n, t, i, e, s = null, r = 0, o = 0) {
891
+ const { float32Array: f, uint16Array: a, uint32Array: u } = I;
892
+ let l = n * 2;
893
+ if (q(l, a)) {
894
+ const c = J(n, u), d = Z(l, a);
895
+ return k(n, f, yt), e(c, d, !1, o, r + n / N, yt);
896
+ } else {
897
+ let v = function(S) {
898
+ const { uint16Array: B, uint32Array: E } = I;
899
+ let U = S * 2;
900
+ for (; !q(U, B); )
901
+ S = V(S), U = S * 2;
902
+ return J(S, E);
903
+ }, _ = function(S) {
904
+ const { uint16Array: B, uint32Array: E } = I;
905
+ let U = S * 2;
906
+ for (; !q(U, B); )
907
+ S = W(S, E), U = S * 2;
908
+ return J(S, E) + Z(U, B);
909
+ };
910
+ const c = V(n), d = W(n, u);
911
+ let y = c, g = d, x, w, m, h;
912
+ if (s && (m = yt, h = Dt, k(y, f, m), k(g, f, h), x = s(m), w = s(h), w < x)) {
913
+ y = d, g = c;
914
+ const S = x;
915
+ x = w, w = S, m = h;
916
+ }
917
+ m || (m = yt, k(y, f, m));
918
+ const b = q(y * 2, a), A = i(m, b, x, o + 1, r + y / N);
919
+ let P;
920
+ if (A === wi) {
921
+ const S = v(y), E = _(y) - S;
922
+ P = e(S, E, !0, o + 1, r + y / N, m);
923
+ } else
924
+ P = A && Ne(
925
+ y,
926
+ t,
927
+ i,
928
+ e,
929
+ s,
930
+ r,
931
+ o + 1
932
+ );
933
+ if (P) return !0;
934
+ h = Dt, k(g, f, h);
935
+ const M = q(g * 2, a), T = i(h, M, w, o + 1, r + g / N);
936
+ let R;
937
+ if (T === wi) {
938
+ const S = v(g), E = _(g) - S;
939
+ R = e(S, E, !0, o + 1, r + g / N, h);
940
+ } else
941
+ R = T && Ne(
942
+ g,
943
+ t,
944
+ i,
945
+ e,
946
+ s,
947
+ r,
948
+ o + 1
949
+ );
950
+ return !!R;
951
+ }
952
+ }
953
+ const Ht = /* @__PURE__ */ new I.constructor(), we = /* @__PURE__ */ new I.constructor(), ht = /* @__PURE__ */ new ii(() => new it()), Rt = /* @__PURE__ */ new it(), _t = /* @__PURE__ */ new it(), Re = /* @__PURE__ */ new it(), _e = /* @__PURE__ */ new it();
954
+ let Be = !1;
955
+ function as(n, t, i, e) {
956
+ if (Be)
957
+ throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");
958
+ Be = !0;
959
+ const s = n._roots, r = t._roots;
960
+ let o, f = 0, a = 0;
961
+ const u = new H().copy(i).invert();
962
+ for (let l = 0, p = s.length; l < p; l++) {
963
+ Ht.setBuffer(s[l]), a = 0;
964
+ const c = ht.getPrimitive();
965
+ k(0, Ht.float32Array, c), c.applyMatrix4(u);
966
+ for (let d = 0, y = r.length; d < y && (we.setBuffer(r[d]), o = nt(
967
+ 0,
968
+ 0,
969
+ i,
970
+ u,
971
+ e,
972
+ f,
973
+ a,
974
+ 0,
975
+ 0,
976
+ c
977
+ ), we.clearBuffer(), a += r[d].byteLength / X, !o); d++)
978
+ ;
979
+ if (ht.releasePrimitive(c), Ht.clearBuffer(), f += s[l].byteLength / X, o)
980
+ break;
981
+ }
982
+ return Be = !1, o;
983
+ }
984
+ function nt(n, t, i, e, s, r = 0, o = 0, f = 0, a = 0, u = null, l = !1) {
985
+ let p, c;
986
+ l ? (p = we, c = Ht) : (p = Ht, c = we);
987
+ const d = p.float32Array, y = p.uint32Array, g = p.uint16Array, x = c.float32Array, w = c.uint32Array, m = c.uint16Array, h = n * 2, b = t * 2, A = q(h, g), P = q(b, m);
988
+ let M = !1;
989
+ if (P && A)
990
+ l ? M = s(
991
+ J(t, w),
992
+ Z(t * 2, m),
993
+ J(n, y),
994
+ Z(n * 2, g),
995
+ a,
996
+ o + t / N,
997
+ f,
998
+ r + n / N
999
+ ) : M = s(
1000
+ J(n, y),
1001
+ Z(n * 2, g),
1002
+ J(t, w),
1003
+ Z(t * 2, m),
1004
+ f,
1005
+ r + n / N,
1006
+ a,
1007
+ o + t / N
1008
+ );
1009
+ else if (P) {
1010
+ const T = ht.getPrimitive();
1011
+ k(t, x, T), T.applyMatrix4(i);
1012
+ const R = V(n), v = W(n, y);
1013
+ k(R, d, Rt), k(v, d, _t);
1014
+ const _ = T.intersectsBox(Rt), S = T.intersectsBox(_t);
1015
+ M = _ && nt(
1016
+ t,
1017
+ R,
1018
+ e,
1019
+ i,
1020
+ s,
1021
+ o,
1022
+ r,
1023
+ a,
1024
+ f + 1,
1025
+ T,
1026
+ !l
1027
+ ) || S && nt(
1028
+ t,
1029
+ v,
1030
+ e,
1031
+ i,
1032
+ s,
1033
+ o,
1034
+ r,
1035
+ a,
1036
+ f + 1,
1037
+ T,
1038
+ !l
1039
+ ), ht.releasePrimitive(T);
1040
+ } else {
1041
+ const T = V(t), R = W(t, w);
1042
+ k(T, x, Re), k(R, x, _e);
1043
+ const v = u.intersectsBox(Re), _ = u.intersectsBox(_e);
1044
+ if (v && _)
1045
+ M = nt(
1046
+ n,
1047
+ T,
1048
+ i,
1049
+ e,
1050
+ s,
1051
+ r,
1052
+ o,
1053
+ f,
1054
+ a + 1,
1055
+ u,
1056
+ l
1057
+ ) || nt(
1058
+ n,
1059
+ R,
1060
+ i,
1061
+ e,
1062
+ s,
1063
+ r,
1064
+ o,
1065
+ f,
1066
+ a + 1,
1067
+ u,
1068
+ l
1069
+ );
1070
+ else if (v)
1071
+ if (A)
1072
+ M = nt(
1073
+ n,
1074
+ T,
1075
+ i,
1076
+ e,
1077
+ s,
1078
+ r,
1079
+ o,
1080
+ f,
1081
+ a + 1,
1082
+ u,
1083
+ l
1084
+ );
1085
+ else {
1086
+ const S = ht.getPrimitive();
1087
+ S.copy(Re).applyMatrix4(i);
1088
+ const B = V(n), E = W(n, y);
1089
+ k(B, d, Rt), k(E, d, _t);
1090
+ const U = S.intersectsBox(Rt), D = S.intersectsBox(_t);
1091
+ M = U && nt(
1092
+ T,
1093
+ B,
1094
+ e,
1095
+ i,
1096
+ s,
1097
+ o,
1098
+ r,
1099
+ a,
1100
+ f + 1,
1101
+ S,
1102
+ !l
1103
+ ) || D && nt(
1104
+ T,
1105
+ E,
1106
+ e,
1107
+ i,
1108
+ s,
1109
+ o,
1110
+ r,
1111
+ a,
1112
+ f + 1,
1113
+ S,
1114
+ !l
1115
+ ), ht.releasePrimitive(S);
1116
+ }
1117
+ else if (_)
1118
+ if (A)
1119
+ M = nt(
1120
+ n,
1121
+ R,
1122
+ i,
1123
+ e,
1124
+ s,
1125
+ r,
1126
+ o,
1127
+ f,
1128
+ a + 1,
1129
+ u,
1130
+ l
1131
+ );
1132
+ else {
1133
+ const S = ht.getPrimitive();
1134
+ S.copy(_e).applyMatrix4(i);
1135
+ const B = V(n), E = W(n, y);
1136
+ k(B, d, Rt), k(E, d, _t);
1137
+ const U = S.intersectsBox(Rt), D = S.intersectsBox(_t);
1138
+ M = U && nt(
1139
+ R,
1140
+ B,
1141
+ e,
1142
+ i,
1143
+ s,
1144
+ o,
1145
+ r,
1146
+ a,
1147
+ f + 1,
1148
+ S,
1149
+ !l
1150
+ ) || D && nt(
1151
+ R,
1152
+ E,
1153
+ e,
1154
+ i,
1155
+ s,
1156
+ o,
1157
+ r,
1158
+ a,
1159
+ f + 1,
1160
+ S,
1161
+ !l
1162
+ ), ht.releasePrimitive(S);
1163
+ }
1164
+ }
1165
+ return M;
1166
+ }
1167
+ const vi = /* @__PURE__ */ new it(), Bt = /* @__PURE__ */ new Float32Array(6);
1168
+ class cs {
1169
+ constructor() {
1170
+ this._roots = null, this.primitiveBuffer = null, this.primitiveBufferStride = null;
1171
+ }
1172
+ init(t) {
1173
+ t = {
1174
+ ...Ki,
1175
+ ...t
1176
+ }, ss(this, t);
1177
+ }
1178
+ getRootRanges() {
1179
+ throw new Error("BVH: getRootRanges() not implemented");
1180
+ }
1181
+ // write the i-th primitive bounds in a 6-value min / max format to the buffer
1182
+ // starting at the given "writeOffset"
1183
+ writePrimitiveBounds() {
1184
+ throw new Error("BVH: writePrimitiveBounds() not implemented");
1185
+ }
1186
+ // writes the union bounds of all primitives in the given range in a min / max format
1187
+ // to the buffer
1188
+ writePrimitiveRangeBounds(t, i, e, s) {
1189
+ let r = 1 / 0, o = 1 / 0, f = 1 / 0, a = -1 / 0, u = -1 / 0, l = -1 / 0;
1190
+ for (let p = t, c = t + i; p < c; p++) {
1191
+ this.writePrimitiveBounds(p, Bt, 0);
1192
+ const [d, y, g, x, w, m] = Bt;
1193
+ d < r && (r = d), x > a && (a = x), y < o && (o = y), w > u && (u = w), g < f && (f = g), m > l && (l = m);
1194
+ }
1195
+ return e[s + 0] = r, e[s + 1] = o, e[s + 2] = f, e[s + 3] = a, e[s + 4] = u, e[s + 5] = l, e;
1196
+ }
1197
+ computePrimitiveBounds(t, i, e) {
1198
+ const s = e.offset || 0;
1199
+ for (let r = t, o = t + i; r < o; r++) {
1200
+ this.writePrimitiveBounds(r, Bt, 0);
1201
+ const [f, a, u, l, p, c] = Bt, d = (f + l) / 2, y = (a + p) / 2, g = (u + c) / 2, x = (l - f) / 2, w = (p - a) / 2, m = (c - u) / 2, h = (r - s) * 6;
1202
+ e[h + 0] = d, e[h + 1] = x + (Math.abs(d) + x) * ye, e[h + 2] = y, e[h + 3] = w + (Math.abs(y) + w) * ye, e[h + 4] = g, e[h + 5] = m + (Math.abs(g) + m) * ye;
1203
+ }
1204
+ return e;
1205
+ }
1206
+ shiftPrimitiveOffsets(t) {
1207
+ const i = this._indirectBuffer;
1208
+ if (i)
1209
+ for (let e = 0, s = i.length; e < s; e++)
1210
+ i[e] += t;
1211
+ else {
1212
+ const e = this._roots;
1213
+ for (let s = 0; s < e.length; s++) {
1214
+ const r = e[s], o = new Uint32Array(r), f = new Uint16Array(r), a = r.byteLength / X;
1215
+ for (let u = 0; u < a; u++) {
1216
+ const l = N * u, p = 2 * l;
1217
+ q(p, f) && (o[l + 6] += t);
1218
+ }
1219
+ }
1220
+ }
1221
+ }
1222
+ traverse(t, i = 0) {
1223
+ const e = this._roots[i], s = new Uint32Array(e), r = new Uint16Array(e);
1224
+ o(0);
1225
+ function o(f, a = 0) {
1226
+ const u = f * 2, l = q(u, r);
1227
+ if (l) {
1228
+ const p = s[f + 6], c = r[u + 14];
1229
+ t(a, l, new Float32Array(e, f * 4, 6), p, c);
1230
+ } else {
1231
+ const p = V(f), c = W(f, s), d = ei(f, s);
1232
+ t(a, l, new Float32Array(e, f * 4, 6), d) || (o(p, a + 1), o(c, a + 1));
1233
+ }
1234
+ }
1235
+ }
1236
+ refit() {
1237
+ const t = this._roots;
1238
+ for (let i = 0, e = t.length; i < e; i++) {
1239
+ const s = t[i], r = new Uint32Array(s), o = new Uint16Array(s), f = new Float32Array(s), a = s.byteLength / X;
1240
+ for (let u = a - 1; u >= 0; u--) {
1241
+ const l = u * N, p = l * 2;
1242
+ if (q(p, o)) {
1243
+ const d = J(l, r), y = Z(p, o);
1244
+ this.writePrimitiveRangeBounds(d, y, Bt, 0), f.set(Bt, l);
1245
+ } else {
1246
+ const d = V(l), y = W(l, r);
1247
+ for (let g = 0; g < 3; g++) {
1248
+ const x = f[d + g], w = f[d + g + 3], m = f[y + g], h = f[y + g + 3];
1249
+ f[l + g] = x < m ? x : m, f[l + g + 3] = w > h ? w : h;
1250
+ }
1251
+ }
1252
+ }
1253
+ }
1254
+ }
1255
+ getBoundingBox(t) {
1256
+ return t.makeEmpty(), this._roots.forEach((e) => {
1257
+ k(0, new Float32Array(e), vi), t.union(vi);
1258
+ }), t;
1259
+ }
1260
+ // Base shapecast implementation that can be used by subclasses
1261
+ // TODO: see if we can get rid of "iterateFunc" here as well as the primitive so the function
1262
+ // API aligns with the "shapecast" implementation
1263
+ shapecast(t) {
1264
+ let {
1265
+ boundsTraverseOrder: i,
1266
+ intersectsBounds: e,
1267
+ intersectsRange: s,
1268
+ intersectsPrimitive: r,
1269
+ scratchPrimitive: o,
1270
+ iterate: f
1271
+ } = t;
1272
+ if (s && r) {
1273
+ const p = s;
1274
+ s = (c, d, y, g, x) => p(c, d, y, g, x) ? !0 : f(c, d, this, r, y, g, o);
1275
+ } else s || (r ? s = (p, c, d, y) => f(p, c, this, r, d, y, o) : s = (p, c, d) => d);
1276
+ let a = !1, u = 0;
1277
+ const l = this._roots;
1278
+ for (let p = 0, c = l.length; p < c; p++) {
1279
+ const d = l[p];
1280
+ if (a = rs(this, p, e, s, i, u), a)
1281
+ break;
1282
+ u += d.byteLength / X;
1283
+ }
1284
+ return a;
1285
+ }
1286
+ bvhcast(t, i, e) {
1287
+ let { intersectsRanges: s } = e;
1288
+ return as(this, t, i, s);
1289
+ }
1290
+ }
1291
+ function ls() {
1292
+ return typeof SharedArrayBuffer < "u";
1293
+ }
1294
+ function ni(n) {
1295
+ return n.index ? n.index.count : n.attributes.position.count;
1296
+ }
1297
+ function Ae(n) {
1298
+ return ni(n) / 3;
1299
+ }
1300
+ function us(n, t = ArrayBuffer) {
1301
+ return n > 65535 ? new Uint32Array(new t(4 * n)) : new Uint16Array(new t(2 * n));
1302
+ }
1303
+ function fs(n, t) {
1304
+ if (!n.index) {
1305
+ const i = n.attributes.position.count, e = t.useSharedArrayBuffer ? SharedArrayBuffer : ArrayBuffer, s = us(i, e);
1306
+ n.setIndex(new qi(s, 1));
1307
+ for (let r = 0; r < i; r++)
1308
+ s[r] = r;
1309
+ }
1310
+ }
1311
+ function ds(n, t, i) {
1312
+ const e = ni(n) / i, s = t || n.drawRange, r = s.start / i, o = (s.start + s.count) / i, f = Math.max(0, r), a = Math.min(e, o) - f;
1313
+ return {
1314
+ offset: Math.floor(f),
1315
+ count: Math.floor(a)
1316
+ };
1317
+ }
1318
+ function ps(n, t) {
1319
+ return n.groups.map((i) => ({
1320
+ offset: i.start / t,
1321
+ count: i.count / t
1322
+ }));
1323
+ }
1324
+ function Pi(n, t, i) {
1325
+ const e = ds(n, t, i), s = ps(n, i);
1326
+ if (!s.length)
1327
+ return [e];
1328
+ const r = [], o = e.offset, f = e.offset + e.count, a = ni(n) / i, u = [];
1329
+ for (const c of s) {
1330
+ const { offset: d, count: y } = c, g = d, x = isFinite(y) ? y : a - d, w = d + x;
1331
+ g < f && w > o && (u.push({ pos: Math.max(o, g), isStart: !0 }), u.push({ pos: Math.min(f, w), isStart: !1 }));
1332
+ }
1333
+ u.sort((c, d) => c.pos !== d.pos ? c.pos - d.pos : c.type === "end" ? -1 : 1);
1334
+ let l = 0, p = null;
1335
+ for (const c of u) {
1336
+ const d = c.pos;
1337
+ l !== 0 && d !== p && r.push({
1338
+ offset: p,
1339
+ count: d - p
1340
+ }), l += c.isStart ? 1 : -1, p = d;
1341
+ }
1342
+ return r;
1343
+ }
1344
+ function ms(n, t) {
1345
+ const i = n[n.length - 1], e = i.offset + i.count > 2 ** 16, s = n.reduce((u, l) => u + l.count, 0), r = e ? 4 : 2, o = t ? new SharedArrayBuffer(s * r) : new ArrayBuffer(s * r), f = e ? new Uint32Array(o) : new Uint16Array(o);
1346
+ let a = 0;
1347
+ for (let u = 0; u < n.length; u++) {
1348
+ const { offset: l, count: p } = n[u];
1349
+ for (let c = 0; c < p; c++)
1350
+ f[a + c] = l + c;
1351
+ a += p;
1352
+ }
1353
+ return f;
1354
+ }
1355
+ class hs extends cs {
1356
+ get indirect() {
1357
+ return !!this._indirectBuffer;
1358
+ }
1359
+ get primitiveStride() {
1360
+ return null;
1361
+ }
1362
+ get primitiveBufferStride() {
1363
+ return this.indirect ? 1 : this.primitiveStride;
1364
+ }
1365
+ set primitiveBufferStride(t) {
1366
+ }
1367
+ get primitiveBuffer() {
1368
+ return this.indirect ? this._indirectBuffer : this.geometry.index.array;
1369
+ }
1370
+ set primitiveBuffer(t) {
1371
+ }
1372
+ constructor(t, i = {}) {
1373
+ if (t.isBufferGeometry) {
1374
+ if (t.index && t.index.isInterleavedBufferAttribute)
1375
+ throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.");
1376
+ } else throw new Error("BVH: Only BufferGeometries are supported.");
1377
+ if (i.useSharedArrayBuffer && !ls())
1378
+ throw new Error("BVH: SharedArrayBuffer is not available.");
1379
+ super(), this.geometry = t, this.resolvePrimitiveIndex = i.indirect ? (e) => this._indirectBuffer[e] : (e) => e, this.primitiveBuffer = null, this.primitiveBufferStride = null, this._indirectBuffer = null, i = {
1380
+ ...Ki,
1381
+ ...i
1382
+ }, i[ti] || this.init(i);
1383
+ }
1384
+ init(t) {
1385
+ const { geometry: i, primitiveStride: e } = this;
1386
+ if (t.indirect) {
1387
+ const s = Pi(i, t.range, e), r = ms(s, t.useSharedArrayBuffer);
1388
+ this._indirectBuffer = r;
1389
+ } else
1390
+ fs(i, t);
1391
+ super.init(t), !i.boundingBox && t.setBoundingBox && (i.boundingBox = this.getBoundingBox(new it()));
1392
+ }
1393
+ // Abstract methods to be implemented by subclasses
1394
+ getRootRanges(t) {
1395
+ return this.indirect ? [{ offset: 0, count: this._indirectBuffer.length }] : Pi(this.geometry, t, this.primitiveStride);
1396
+ }
1397
+ raycastObject3D() {
1398
+ throw new Error("BVH: raycastObject3D() not implemented");
1399
+ }
1400
+ }
1401
+ class pt {
1402
+ constructor() {
1403
+ this.min = 1 / 0, this.max = -1 / 0;
1404
+ }
1405
+ setFromPointsField(t, i) {
1406
+ let e = 1 / 0, s = -1 / 0;
1407
+ for (let r = 0, o = t.length; r < o; r++) {
1408
+ const a = t[r][i];
1409
+ e = a < e ? a : e, s = a > s ? a : s;
1410
+ }
1411
+ this.min = e, this.max = s;
1412
+ }
1413
+ setFromPoints(t, i) {
1414
+ let e = 1 / 0, s = -1 / 0;
1415
+ for (let r = 0, o = i.length; r < o; r++) {
1416
+ const f = i[r], a = t.dot(f);
1417
+ e = a < e ? a : e, s = a > s ? a : s;
1418
+ }
1419
+ this.min = e, this.max = s;
1420
+ }
1421
+ isSeparated(t) {
1422
+ return this.min > t.max || t.min > this.max;
1423
+ }
1424
+ }
1425
+ pt.prototype.setFromBox = /* @__PURE__ */ function() {
1426
+ const n = /* @__PURE__ */ new z();
1427
+ return function(i, e) {
1428
+ const s = e.min, r = e.max;
1429
+ let o = 1 / 0, f = -1 / 0;
1430
+ for (let a = 0; a <= 1; a++)
1431
+ for (let u = 0; u <= 1; u++)
1432
+ for (let l = 0; l <= 1; l++) {
1433
+ n.x = s.x * a + r.x * (1 - a), n.y = s.y * u + r.y * (1 - u), n.z = s.z * l + r.z * (1 - l);
1434
+ const p = i.dot(n);
1435
+ o = Math.min(p, o), f = Math.max(p, f);
1436
+ }
1437
+ this.min = o, this.max = f;
1438
+ };
1439
+ }();
1440
+ const ys = /* @__PURE__ */ function() {
1441
+ const n = /* @__PURE__ */ new z(), t = /* @__PURE__ */ new z(), i = /* @__PURE__ */ new z();
1442
+ return function(s, r, o) {
1443
+ const f = s.start, a = n, u = r.start, l = t;
1444
+ i.subVectors(f, u), n.subVectors(s.end, s.start), t.subVectors(r.end, r.start);
1445
+ const p = i.dot(l), c = l.dot(a), d = l.dot(l), y = i.dot(a), x = a.dot(a) * d - c * c;
1446
+ let w, m;
1447
+ x !== 0 ? w = (p * c - y * d) / x : w = 0, m = (p + w * c) / d, o.x = w, o.y = m;
1448
+ };
1449
+ }(), si = /* @__PURE__ */ function() {
1450
+ const n = /* @__PURE__ */ new gt(), t = /* @__PURE__ */ new z(), i = /* @__PURE__ */ new z();
1451
+ return function(s, r, o, f) {
1452
+ ys(s, r, n);
1453
+ let a = n.x, u = n.y;
1454
+ if (a >= 0 && a <= 1 && u >= 0 && u <= 1) {
1455
+ s.at(a, o), r.at(u, f);
1456
+ return;
1457
+ } else if (a >= 0 && a <= 1) {
1458
+ u < 0 ? r.at(0, f) : r.at(1, f), s.closestPointToPoint(f, !0, o);
1459
+ return;
1460
+ } else if (u >= 0 && u <= 1) {
1461
+ a < 0 ? s.at(0, o) : s.at(1, o), r.closestPointToPoint(o, !0, f);
1462
+ return;
1463
+ } else {
1464
+ let l;
1465
+ a < 0 ? l = s.start : l = s.end;
1466
+ let p;
1467
+ u < 0 ? p = r.start : p = r.end;
1468
+ const c = t, d = i;
1469
+ if (s.closestPointToPoint(p, !0, t), r.closestPointToPoint(l, !0, i), c.distanceToSquared(p) <= d.distanceToSquared(l)) {
1470
+ o.copy(c), f.copy(p);
1471
+ return;
1472
+ } else {
1473
+ o.copy(l), f.copy(d);
1474
+ return;
1475
+ }
1476
+ }
1477
+ };
1478
+ }(), gs = /* @__PURE__ */ function() {
1479
+ const n = /* @__PURE__ */ new z(), t = /* @__PURE__ */ new z(), i = /* @__PURE__ */ new Oi(), e = /* @__PURE__ */ new ft();
1480
+ return function(r, o) {
1481
+ const { radius: f, center: a } = r, { a: u, b: l, c: p } = o;
1482
+ if (e.start = u, e.end = l, e.closestPointToPoint(a, !0, n).distanceTo(a) <= f || (e.start = u, e.end = p, e.closestPointToPoint(a, !0, n).distanceTo(a) <= f) || (e.start = l, e.end = p, e.closestPointToPoint(a, !0, n).distanceTo(a) <= f)) return !0;
1483
+ const g = o.getPlane(i);
1484
+ if (Math.abs(g.distanceToPoint(a)) <= f) {
1485
+ const w = g.projectPoint(a, t);
1486
+ if (o.containsPoint(w)) return !0;
1487
+ }
1488
+ return !1;
1489
+ };
1490
+ }(), ws = ["x", "y", "z"], lt = 1e-15, Si = lt * lt;
1491
+ function tt(n) {
1492
+ return Math.abs(n) < lt;
1493
+ }
1494
+ class st extends $t {
1495
+ constructor(...t) {
1496
+ super(...t), this.isExtendedTriangle = !0, this.satAxes = new Array(4).fill().map(() => new z()), this.satBounds = new Array(4).fill().map(() => new pt()), this.points = [this.a, this.b, this.c], this.plane = new Oi(), this.isDegenerateIntoSegment = !1, this.isDegenerateIntoPoint = !1, this.degenerateSegment = new ft(), this.needsUpdate = !0;
1497
+ }
1498
+ intersectsSphere(t) {
1499
+ return gs(t, this);
1500
+ }
1501
+ update() {
1502
+ const t = this.a, i = this.b, e = this.c, s = this.points, r = this.satAxes, o = this.satBounds, f = r[0], a = o[0];
1503
+ this.getNormal(f), a.setFromPoints(f, s);
1504
+ const u = r[1], l = o[1];
1505
+ u.subVectors(t, i), l.setFromPoints(u, s);
1506
+ const p = r[2], c = o[2];
1507
+ p.subVectors(i, e), c.setFromPoints(p, s);
1508
+ const d = r[3], y = o[3];
1509
+ d.subVectors(e, t), y.setFromPoints(d, s);
1510
+ const g = u.length(), x = p.length(), w = d.length();
1511
+ this.isDegenerateIntoPoint = !1, this.isDegenerateIntoSegment = !1, g < lt ? x < lt || w < lt ? this.isDegenerateIntoPoint = !0 : (this.isDegenerateIntoSegment = !0, this.degenerateSegment.start.copy(t), this.degenerateSegment.end.copy(e)) : x < lt ? w < lt ? this.isDegenerateIntoPoint = !0 : (this.isDegenerateIntoSegment = !0, this.degenerateSegment.start.copy(i), this.degenerateSegment.end.copy(t)) : w < lt && (this.isDegenerateIntoSegment = !0, this.degenerateSegment.start.copy(e), this.degenerateSegment.end.copy(i)), this.plane.setFromNormalAndCoplanarPoint(f, t), this.needsUpdate = !1;
1512
+ }
1513
+ }
1514
+ st.prototype.closestPointToSegment = /* @__PURE__ */ function() {
1515
+ const n = /* @__PURE__ */ new z(), t = /* @__PURE__ */ new z(), i = /* @__PURE__ */ new ft();
1516
+ return function(s, r = null, o = null) {
1517
+ const { start: f, end: a } = s, u = this.points;
1518
+ let l, p = 1 / 0;
1519
+ for (let c = 0; c < 3; c++) {
1520
+ const d = (c + 1) % 3;
1521
+ i.start.copy(u[c]), i.end.copy(u[d]), si(i, s, n, t), l = n.distanceToSquared(t), l < p && (p = l, r && r.copy(n), o && o.copy(t));
1522
+ }
1523
+ return this.closestPointToPoint(f, n), l = f.distanceToSquared(n), l < p && (p = l, r && r.copy(n), o && o.copy(f)), this.closestPointToPoint(a, n), l = a.distanceToSquared(n), l < p && (p = l, r && r.copy(n), o && o.copy(a)), Math.sqrt(p);
1524
+ };
1525
+ }();
1526
+ st.prototype.intersectsTriangle = /* @__PURE__ */ function() {
1527
+ const n = /* @__PURE__ */ new st(), t = /* @__PURE__ */ new pt(), i = /* @__PURE__ */ new pt(), e = /* @__PURE__ */ new z(), s = /* @__PURE__ */ new z(), r = /* @__PURE__ */ new z(), o = /* @__PURE__ */ new z(), f = /* @__PURE__ */ new ft(), a = /* @__PURE__ */ new ft(), u = /* @__PURE__ */ new z(), l = /* @__PURE__ */ new gt(), p = /* @__PURE__ */ new gt();
1528
+ function c(h, b, A, P) {
1529
+ const M = e;
1530
+ !h.isDegenerateIntoPoint && !h.isDegenerateIntoSegment ? M.copy(h.plane.normal) : M.copy(b.plane.normal);
1531
+ const T = h.satBounds, R = h.satAxes;
1532
+ for (let S = 1; S < 4; S++) {
1533
+ const B = T[S], E = R[S];
1534
+ if (t.setFromPoints(E, b.points), B.isSeparated(t) || (o.copy(M).cross(E), t.setFromPoints(o, h.points), i.setFromPoints(o, b.points), t.isSeparated(i))) return !1;
1535
+ }
1536
+ const v = b.satBounds, _ = b.satAxes;
1537
+ for (let S = 1; S < 4; S++) {
1538
+ const B = v[S], E = _[S];
1539
+ if (t.setFromPoints(E, h.points), B.isSeparated(t) || (o.crossVectors(M, E), t.setFromPoints(o, h.points), i.setFromPoints(o, b.points), t.isSeparated(i))) return !1;
1540
+ }
1541
+ return A && (P || console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."), A.start.set(0, 0, 0), A.end.set(0, 0, 0)), !0;
1542
+ }
1543
+ function d(h, b, A, P, M, T, R, v, _, S, B) {
1544
+ let E = R / (R - v);
1545
+ S.x = P + (M - P) * E, B.start.subVectors(b, h).multiplyScalar(E).add(h), E = R / (R - _), S.y = P + (T - P) * E, B.end.subVectors(A, h).multiplyScalar(E).add(h);
1546
+ }
1547
+ function y(h, b, A, P, M, T, R, v, _, S, B) {
1548
+ if (M > 0)
1549
+ d(h.c, h.a, h.b, P, b, A, _, R, v, S, B);
1550
+ else if (T > 0)
1551
+ d(h.b, h.a, h.c, A, b, P, v, R, _, S, B);
1552
+ else if (v * _ > 0 || R != 0)
1553
+ d(h.a, h.b, h.c, b, A, P, R, v, _, S, B);
1554
+ else if (v != 0)
1555
+ d(h.b, h.a, h.c, A, b, P, v, R, _, S, B);
1556
+ else if (_ != 0)
1557
+ d(h.c, h.a, h.b, P, b, A, _, R, v, S, B);
1558
+ else
1559
+ return !0;
1560
+ return !1;
1561
+ }
1562
+ function g(h, b, A, P) {
1563
+ const M = b.degenerateSegment, T = h.plane.distanceToPoint(M.start), R = h.plane.distanceToPoint(M.end);
1564
+ return tt(T) ? tt(R) ? c(h, b, A, P) : (A && (A.start.copy(M.start), A.end.copy(M.start)), h.containsPoint(M.start)) : tt(R) ? (A && (A.start.copy(M.end), A.end.copy(M.end)), h.containsPoint(M.end)) : h.plane.intersectLine(M, e) != null ? (A && (A.start.copy(e), A.end.copy(e)), h.containsPoint(e)) : !1;
1565
+ }
1566
+ function x(h, b, A) {
1567
+ const P = b.a;
1568
+ return tt(h.plane.distanceToPoint(P)) && h.containsPoint(P) ? (A && (A.start.copy(P), A.end.copy(P)), !0) : !1;
1569
+ }
1570
+ function w(h, b, A) {
1571
+ const P = h.degenerateSegment, M = b.a;
1572
+ return P.closestPointToPoint(M, !0, e), M.distanceToSquared(e) < Si ? (A && (A.start.copy(M), A.end.copy(M)), !0) : !1;
1573
+ }
1574
+ function m(h, b, A, P) {
1575
+ if (h.isDegenerateIntoSegment)
1576
+ if (b.isDegenerateIntoSegment) {
1577
+ const M = h.degenerateSegment, T = b.degenerateSegment, R = s, v = r;
1578
+ M.delta(R), T.delta(v);
1579
+ const _ = e.subVectors(T.start, M.start), S = R.x * v.y - R.y * v.x;
1580
+ if (tt(S))
1581
+ return !1;
1582
+ const B = (_.x * v.y - _.y * v.x) / S, E = -(R.x * _.y - R.y * _.x) / S;
1583
+ if (B < 0 || B > 1 || E < 0 || E > 1)
1584
+ return !1;
1585
+ const U = M.start.z + R.z * B, D = T.start.z + v.z * E;
1586
+ return tt(U - D) ? (A && (A.start.copy(M.start).addScaledVector(R, B), A.end.copy(M.start).addScaledVector(R, B)), !0) : !1;
1587
+ } else return b.isDegenerateIntoPoint ? w(h, b, A) : g(b, h, A, P);
1588
+ else {
1589
+ if (h.isDegenerateIntoPoint)
1590
+ return b.isDegenerateIntoPoint ? b.a.distanceToSquared(h.a) < Si ? (A && (A.start.copy(h.a), A.end.copy(h.a)), !0) : !1 : b.isDegenerateIntoSegment ? w(b, h, A) : x(b, h, A);
1591
+ if (b.isDegenerateIntoPoint)
1592
+ return x(h, b, A);
1593
+ if (b.isDegenerateIntoSegment)
1594
+ return g(h, b, A, P);
1595
+ }
1596
+ }
1597
+ return function(b, A = null, P = !1) {
1598
+ this.needsUpdate && this.update(), b.isExtendedTriangle ? b.needsUpdate && b.update() : (n.copy(b), n.update(), b = n);
1599
+ const M = m(this, b, A, P);
1600
+ if (M !== void 0)
1601
+ return M;
1602
+ const T = this.plane, R = b.plane;
1603
+ let v = R.distanceToPoint(this.a), _ = R.distanceToPoint(this.b), S = R.distanceToPoint(this.c);
1604
+ tt(v) && (v = 0), tt(_) && (_ = 0), tt(S) && (S = 0);
1605
+ const B = v * _, E = v * S;
1606
+ if (B > 0 && E > 0)
1607
+ return !1;
1608
+ let U = T.distanceToPoint(b.a), D = T.distanceToPoint(b.b), F = T.distanceToPoint(b.c);
1609
+ tt(U) && (U = 0), tt(D) && (D = 0), tt(F) && (F = 0);
1610
+ const L = U * D, Y = U * F;
1611
+ if (L > 0 && Y > 0)
1612
+ return !1;
1613
+ s.copy(T.normal), r.copy(R.normal);
1614
+ const Mt = s.cross(r);
1615
+ let vt = 0, Pt = Math.abs(Mt.x);
1616
+ const rt = Math.abs(Mt.y);
1617
+ rt > Pt && (Pt = rt, vt = 1), Math.abs(Mt.z) > Pt && (vt = 2);
1618
+ const at = ws[vt], nn = this.a[at], sn = this.b[at], on = this.c[at], rn = b.a[at], an = b.b[at], cn = b.c[at];
1619
+ if (y(this, nn, sn, on, B, E, v, _, S, l, f))
1620
+ return c(this, b, A, P);
1621
+ if (y(b, rn, an, cn, L, Y, U, D, F, p, a))
1622
+ return c(this, b, A, P);
1623
+ if (l.y < l.x) {
1624
+ const ve = l.y;
1625
+ l.y = l.x, l.x = ve, u.copy(f.start), f.start.copy(f.end), f.end.copy(u);
1626
+ }
1627
+ if (p.y < p.x) {
1628
+ const ve = p.y;
1629
+ p.y = p.x, p.x = ve, u.copy(a.start), a.start.copy(a.end), a.end.copy(u);
1630
+ }
1631
+ return l.y < p.x || p.y < l.x ? !1 : (A && (p.x > l.x ? A.start.copy(a.start) : A.start.copy(f.start), p.y < l.y ? A.end.copy(a.end) : A.end.copy(f.end)), !0);
1632
+ };
1633
+ }();
1634
+ st.prototype.distanceToPoint = /* @__PURE__ */ function() {
1635
+ const n = /* @__PURE__ */ new z();
1636
+ return function(i) {
1637
+ return this.closestPointToPoint(i, n), i.distanceTo(n);
1638
+ };
1639
+ }();
1640
+ st.prototype.distanceToTriangle = /* @__PURE__ */ function() {
1641
+ const n = /* @__PURE__ */ new z(), t = /* @__PURE__ */ new z(), i = ["a", "b", "c"], e = /* @__PURE__ */ new ft(), s = /* @__PURE__ */ new ft();
1642
+ return function(o, f = null, a = null) {
1643
+ const u = f || a ? e : null;
1644
+ if (this.intersectsTriangle(o, u))
1645
+ return (f || a) && (f && u.getCenter(f), a && u.getCenter(a)), 0;
1646
+ let l = 1 / 0;
1647
+ for (let p = 0; p < 3; p++) {
1648
+ let c;
1649
+ const d = i[p], y = o[d];
1650
+ this.closestPointToPoint(y, n), c = y.distanceToSquared(n), c < l && (l = c, f && f.copy(n), a && a.copy(y));
1651
+ const g = this[d];
1652
+ o.closestPointToPoint(g, n), c = g.distanceToSquared(n), c < l && (l = c, f && f.copy(g), a && a.copy(n));
1653
+ }
1654
+ for (let p = 0; p < 3; p++) {
1655
+ const c = i[p], d = i[(p + 1) % 3];
1656
+ e.set(this[c], this[d]);
1657
+ for (let y = 0; y < 3; y++) {
1658
+ const g = i[y], x = i[(y + 1) % 3];
1659
+ s.set(o[g], o[x]), si(e, s, n, t);
1660
+ const w = n.distanceToSquared(t);
1661
+ w < l && (l = w, f && f.copy(n), a && a.copy(t));
1662
+ }
1663
+ }
1664
+ return Math.sqrt(l);
1665
+ };
1666
+ }();
1667
+ class Q {
1668
+ constructor(t, i, e) {
1669
+ this.isOrientedBox = !0, this.min = new z(), this.max = new z(), this.matrix = new H(), this.invMatrix = new H(), this.points = new Array(8).fill().map(() => new z()), this.satAxes = new Array(3).fill().map(() => new z()), this.satBounds = new Array(3).fill().map(() => new pt()), this.alignedSatBounds = new Array(3).fill().map(() => new pt()), this.needsUpdate = !1, t && this.min.copy(t), i && this.max.copy(i), e && this.matrix.copy(e);
1670
+ }
1671
+ set(t, i, e) {
1672
+ this.min.copy(t), this.max.copy(i), this.matrix.copy(e), this.needsUpdate = !0;
1673
+ }
1674
+ copy(t) {
1675
+ this.min.copy(t.min), this.max.copy(t.max), this.matrix.copy(t.matrix), this.needsUpdate = !0;
1676
+ }
1677
+ }
1678
+ Q.prototype.update = /* @__PURE__ */ function() {
1679
+ return function() {
1680
+ const t = this.matrix, i = this.min, e = this.max, s = this.points;
1681
+ for (let u = 0; u <= 1; u++)
1682
+ for (let l = 0; l <= 1; l++)
1683
+ for (let p = 0; p <= 1; p++) {
1684
+ const c = 1 * u | 2 * l | 4 * p, d = s[c];
1685
+ d.x = u ? e.x : i.x, d.y = l ? e.y : i.y, d.z = p ? e.z : i.z, d.applyMatrix4(t);
1686
+ }
1687
+ const r = this.satBounds, o = this.satAxes, f = s[0];
1688
+ for (let u = 0; u < 3; u++) {
1689
+ const l = o[u], p = r[u], c = 1 << u, d = s[c];
1690
+ l.subVectors(f, d), p.setFromPoints(l, s);
1691
+ }
1692
+ const a = this.alignedSatBounds;
1693
+ a[0].setFromPointsField(s, "x"), a[1].setFromPointsField(s, "y"), a[2].setFromPointsField(s, "z"), this.invMatrix.copy(this.matrix).invert(), this.needsUpdate = !1;
1694
+ };
1695
+ }();
1696
+ Q.prototype.intersectsBox = /* @__PURE__ */ function() {
1697
+ const n = /* @__PURE__ */ new pt();
1698
+ return function(i) {
1699
+ this.needsUpdate && this.update();
1700
+ const e = i.min, s = i.max, r = this.satBounds, o = this.satAxes, f = this.alignedSatBounds;
1701
+ if (n.min = e.x, n.max = s.x, f[0].isSeparated(n) || (n.min = e.y, n.max = s.y, f[1].isSeparated(n)) || (n.min = e.z, n.max = s.z, f[2].isSeparated(n))) return !1;
1702
+ for (let a = 0; a < 3; a++) {
1703
+ const u = o[a], l = r[a];
1704
+ if (n.setFromBox(u, i), l.isSeparated(n)) return !1;
1705
+ }
1706
+ return !0;
1707
+ };
1708
+ }();
1709
+ Q.prototype.intersectsTriangle = /* @__PURE__ */ function() {
1710
+ const n = /* @__PURE__ */ new st(), t = /* @__PURE__ */ new Array(3), i = /* @__PURE__ */ new pt(), e = /* @__PURE__ */ new pt(), s = /* @__PURE__ */ new z();
1711
+ return function(o) {
1712
+ this.needsUpdate && this.update(), o.isExtendedTriangle ? o.needsUpdate && o.update() : (n.copy(o), n.update(), o = n);
1713
+ const f = this.satBounds, a = this.satAxes;
1714
+ t[0] = o.a, t[1] = o.b, t[2] = o.c;
1715
+ for (let c = 0; c < 3; c++) {
1716
+ const d = f[c], y = a[c];
1717
+ if (i.setFromPoints(y, t), d.isSeparated(i)) return !1;
1718
+ }
1719
+ const u = o.satBounds, l = o.satAxes, p = this.points;
1720
+ for (let c = 0; c < 3; c++) {
1721
+ const d = u[c], y = l[c];
1722
+ if (i.setFromPoints(y, p), d.isSeparated(i)) return !1;
1723
+ }
1724
+ for (let c = 0; c < 3; c++) {
1725
+ const d = a[c];
1726
+ for (let y = 0; y < 4; y++) {
1727
+ const g = l[y];
1728
+ if (s.crossVectors(d, g), i.setFromPoints(s, t), e.setFromPoints(s, p), i.isSeparated(e)) return !1;
1729
+ }
1730
+ }
1731
+ return !0;
1732
+ };
1733
+ }();
1734
+ Q.prototype.closestPointToPoint = /* @__PURE__ */ function() {
1735
+ return function(t, i) {
1736
+ return this.needsUpdate && this.update(), i.copy(t).applyMatrix4(this.invMatrix).clamp(this.min, this.max).applyMatrix4(this.matrix), i;
1737
+ };
1738
+ }();
1739
+ Q.prototype.distanceToPoint = function() {
1740
+ const n = new z();
1741
+ return function(i) {
1742
+ return this.closestPointToPoint(i, n), i.distanceTo(n);
1743
+ };
1744
+ }();
1745
+ Q.prototype.distanceToBox = /* @__PURE__ */ function() {
1746
+ const n = ["x", "y", "z"], t = /* @__PURE__ */ new Array(12).fill().map(() => new ft()), i = /* @__PURE__ */ new Array(12).fill().map(() => new ft()), e = /* @__PURE__ */ new z(), s = /* @__PURE__ */ new z();
1747
+ return function(o, f = 0, a = null, u = null) {
1748
+ if (this.needsUpdate && this.update(), this.intersectsBox(o))
1749
+ return (a || u) && (o.getCenter(s), this.closestPointToPoint(s, e), o.closestPointToPoint(e, s), a && a.copy(e), u && u.copy(s)), 0;
1750
+ const l = f * f, p = o.min, c = o.max, d = this.points;
1751
+ let y = 1 / 0;
1752
+ for (let x = 0; x < 8; x++) {
1753
+ const w = d[x];
1754
+ s.copy(w).clamp(p, c);
1755
+ const m = w.distanceToSquared(s);
1756
+ if (m < y && (y = m, a && a.copy(w), u && u.copy(s), m < l))
1757
+ return Math.sqrt(m);
1758
+ }
1759
+ let g = 0;
1760
+ for (let x = 0; x < 3; x++)
1761
+ for (let w = 0; w <= 1; w++)
1762
+ for (let m = 0; m <= 1; m++) {
1763
+ const h = (x + 1) % 3, b = (x + 2) % 3, A = w << h | m << b, P = 1 << x | w << h | m << b, M = d[A], T = d[P];
1764
+ t[g].set(M, T);
1765
+ const v = n[x], _ = n[h], S = n[b], B = i[g], E = B.start, U = B.end;
1766
+ E[v] = p[v], E[_] = w ? p[_] : c[_], E[S] = m ? p[S] : c[_], U[v] = c[v], U[_] = w ? p[_] : c[_], U[S] = m ? p[S] : c[_], g++;
1767
+ }
1768
+ for (let x = 0; x <= 1; x++)
1769
+ for (let w = 0; w <= 1; w++)
1770
+ for (let m = 0; m <= 1; m++) {
1771
+ s.x = x ? c.x : p.x, s.y = w ? c.y : p.y, s.z = m ? c.z : p.z, this.closestPointToPoint(s, e);
1772
+ const h = s.distanceToSquared(e);
1773
+ if (h < y && (y = h, a && a.copy(e), u && u.copy(s), h < l))
1774
+ return Math.sqrt(h);
1775
+ }
1776
+ for (let x = 0; x < 12; x++) {
1777
+ const w = t[x];
1778
+ for (let m = 0; m < 12; m++) {
1779
+ const h = i[m];
1780
+ si(w, h, e, s);
1781
+ const b = e.distanceToSquared(s);
1782
+ if (b < y && (y = b, a && a.copy(e), u && u.copy(s), b < l))
1783
+ return Math.sqrt(b);
1784
+ }
1785
+ }
1786
+ return Math.sqrt(y);
1787
+ };
1788
+ }();
1789
+ class bs extends ii {
1790
+ constructor() {
1791
+ super(() => new st());
1792
+ }
1793
+ }
1794
+ const et = /* @__PURE__ */ new bs(), Nt = /* @__PURE__ */ new z(), Ee = /* @__PURE__ */ new z();
1795
+ function xs(n, t, i = {}, e = 0, s = 1 / 0) {
1796
+ const r = e * e, o = s * s;
1797
+ let f = 1 / 0, a = null;
1798
+ if (n.shapecast(
1799
+ {
1800
+ boundsTraverseOrder: (l) => (Nt.copy(t).clamp(l.min, l.max), Nt.distanceToSquared(t)),
1801
+ intersectsBounds: (l, p, c) => c < f && c < o,
1802
+ intersectsTriangle: (l, p) => {
1803
+ l.closestPointToPoint(t, Nt);
1804
+ const c = t.distanceToSquared(Nt);
1805
+ return c < f && (Ee.copy(Nt), f = c, a = p), c < r;
1806
+ }
1807
+ }
1808
+ ), f === 1 / 0) return null;
1809
+ const u = Math.sqrt(f);
1810
+ return i.point ? i.point.copy(Ee) : i.point = Ee.clone(), i.distance = u, i.faceIndex = a, i;
1811
+ }
1812
+ const ie = parseInt(Vi) >= 169, As = parseInt(Vi) <= 161, bt = /* @__PURE__ */ new z(), xt = /* @__PURE__ */ new z(), At = /* @__PURE__ */ new z(), ne = /* @__PURE__ */ new gt(), se = /* @__PURE__ */ new gt(), oe = /* @__PURE__ */ new gt(), Ti = /* @__PURE__ */ new z(), Ri = /* @__PURE__ */ new z(), _i = /* @__PURE__ */ new z(), qt = /* @__PURE__ */ new z();
1813
+ function Ms(n, t, i, e, s, r, o, f) {
1814
+ let a;
1815
+ if (r === An ? a = n.intersectTriangle(e, i, t, !0, s) : a = n.intersectTriangle(t, i, e, r !== Mn, s), a === null) return null;
1816
+ const u = n.origin.distanceTo(s);
1817
+ return u < o || u > f ? null : {
1818
+ distance: u,
1819
+ point: s.clone()
1820
+ };
1821
+ }
1822
+ function Bi(n, t, i, e, s, r, o, f, a, u, l) {
1823
+ bt.fromBufferAttribute(t, r), xt.fromBufferAttribute(t, o), At.fromBufferAttribute(t, f);
1824
+ const p = Ms(n, bt, xt, At, qt, a, u, l);
1825
+ if (p) {
1826
+ if (e) {
1827
+ ne.fromBufferAttribute(e, r), se.fromBufferAttribute(e, o), oe.fromBufferAttribute(e, f), p.uv = new gt();
1828
+ const d = $t.getInterpolation(qt, bt, xt, At, ne, se, oe, p.uv);
1829
+ ie || (p.uv = d);
1830
+ }
1831
+ if (s) {
1832
+ ne.fromBufferAttribute(s, r), se.fromBufferAttribute(s, o), oe.fromBufferAttribute(s, f), p.uv1 = new gt();
1833
+ const d = $t.getInterpolation(qt, bt, xt, At, ne, se, oe, p.uv1);
1834
+ ie || (p.uv1 = d), As && (p.uv2 = p.uv1);
1835
+ }
1836
+ if (i) {
1837
+ Ti.fromBufferAttribute(i, r), Ri.fromBufferAttribute(i, o), _i.fromBufferAttribute(i, f), p.normal = new z();
1838
+ const d = $t.getInterpolation(qt, bt, xt, At, Ti, Ri, _i, p.normal);
1839
+ p.normal.dot(n.direction) > 0 && p.normal.multiplyScalar(-1), ie || (p.normal = d);
1840
+ }
1841
+ const c = {
1842
+ a: r,
1843
+ b: o,
1844
+ c: f,
1845
+ normal: new z(),
1846
+ materialIndex: 0
1847
+ };
1848
+ if ($t.getNormal(bt, xt, At, c.normal), p.face = c, p.faceIndex = r, ie) {
1849
+ const d = new z();
1850
+ $t.getBarycoord(qt, bt, xt, At, d), p.barycoord = d;
1851
+ }
1852
+ }
1853
+ return p;
1854
+ }
1855
+ function Ei(n) {
1856
+ return n && n.isMaterial ? n.side : n;
1857
+ }
1858
+ function Me(n, t, i, e, s, r, o) {
1859
+ const f = e * 3;
1860
+ let a = f + 0, u = f + 1, l = f + 2;
1861
+ const { index: p, groups: c } = n;
1862
+ n.index && (a = p.getX(a), u = p.getX(u), l = p.getX(l));
1863
+ const { position: d, normal: y, uv: g, uv1: x } = n.attributes;
1864
+ if (Array.isArray(t)) {
1865
+ const w = e * 3;
1866
+ for (let m = 0, h = c.length; m < h; m++) {
1867
+ const { start: b, count: A, materialIndex: P } = c[m];
1868
+ if (w >= b && w < b + A) {
1869
+ const M = Ei(t[P]), T = Bi(i, d, y, g, x, a, u, l, M, r, o);
1870
+ if (T)
1871
+ if (T.faceIndex = e, T.face.materialIndex = P, s)
1872
+ s.push(T);
1873
+ else
1874
+ return T;
1875
+ }
1876
+ }
1877
+ } else {
1878
+ const w = Ei(t), m = Bi(i, d, y, g, x, a, u, l, w, r, o);
1879
+ if (m)
1880
+ if (m.faceIndex = e, m.face.materialIndex = 0, s)
1881
+ s.push(m);
1882
+ else
1883
+ return m;
1884
+ }
1885
+ return null;
1886
+ }
1887
+ function j(n, t, i, e) {
1888
+ const s = n.a, r = n.b, o = n.c;
1889
+ let f = t, a = t + 1, u = t + 2;
1890
+ i && (f = i.getX(f), a = i.getX(a), u = i.getX(u)), s.x = e.getX(f), s.y = e.getY(f), s.z = e.getZ(f), r.x = e.getX(a), r.y = e.getY(a), r.z = e.getZ(a), o.x = e.getX(u), o.y = e.getY(u), o.z = e.getZ(u);
1891
+ }
1892
+ function vs(n, t, i, e, s, r, o, f) {
1893
+ const { geometry: a, _indirectBuffer: u } = n;
1894
+ for (let l = e, p = e + s; l < p; l++)
1895
+ Me(a, t, i, l, r, o, f);
1896
+ }
1897
+ function Ps(n, t, i, e, s, r, o) {
1898
+ const { geometry: f, _indirectBuffer: a } = n;
1899
+ let u = 1 / 0, l = null;
1900
+ for (let p = e, c = e + s; p < c; p++) {
1901
+ let d;
1902
+ d = Me(f, t, i, p, null, r, o), d && d.distance < u && (l = d, u = d.distance);
1903
+ }
1904
+ return l;
1905
+ }
1906
+ function Ss(n, t, i, e, s, r, o) {
1907
+ const { geometry: f } = i, { index: a } = f, u = f.attributes.position;
1908
+ for (let l = n, p = t + n; l < p; l++) {
1909
+ let c;
1910
+ if (c = l, j(o, c * 3, a, u), o.needsUpdate = !0, e(o, c, s, r))
1911
+ return !0;
1912
+ }
1913
+ return !1;
1914
+ }
1915
+ function Ts(n, t = null) {
1916
+ t && Array.isArray(t) && (t = new Set(t));
1917
+ const i = n.geometry, e = i.index ? i.index.array : null, s = i.attributes.position;
1918
+ let r, o, f, a, u = 0;
1919
+ const l = n._roots;
1920
+ for (let c = 0, d = l.length; c < d; c++)
1921
+ r = l[c], o = new Uint32Array(r), f = new Uint16Array(r), a = new Float32Array(r), p(0, u), u += r.byteLength;
1922
+ function p(c, d, y = !1) {
1923
+ const g = c * 2;
1924
+ if (q(g, f)) {
1925
+ const x = J(c, o), w = Z(g, f);
1926
+ let m = 1 / 0, h = 1 / 0, b = 1 / 0, A = -1 / 0, P = -1 / 0, M = -1 / 0;
1927
+ for (let T = 3 * x, R = 3 * (x + w); T < R; T++) {
1928
+ let v = e[T];
1929
+ const _ = s.getX(v), S = s.getY(v), B = s.getZ(v);
1930
+ _ < m && (m = _), _ > A && (A = _), S < h && (h = S), S > P && (P = S), B < b && (b = B), B > M && (M = B);
1931
+ }
1932
+ return a[c + 0] !== m || a[c + 1] !== h || a[c + 2] !== b || a[c + 3] !== A || a[c + 4] !== P || a[c + 5] !== M ? (a[c + 0] = m, a[c + 1] = h, a[c + 2] = b, a[c + 3] = A, a[c + 4] = P, a[c + 5] = M, !0) : !1;
1933
+ } else {
1934
+ const x = V(c), w = W(c, o);
1935
+ let m = y, h = !1, b = !1;
1936
+ if (t) {
1937
+ if (!m) {
1938
+ const v = x / N + d / X, _ = w / N + d / X;
1939
+ h = t.has(v), b = t.has(_), m = !h && !b;
1940
+ }
1941
+ } else
1942
+ h = !0, b = !0;
1943
+ const A = m || h, P = m || b;
1944
+ let M = !1;
1945
+ A && (M = p(x, d, m));
1946
+ let T = !1;
1947
+ P && (T = p(w, d, m));
1948
+ const R = M || T;
1949
+ if (R)
1950
+ for (let v = 0; v < 3; v++) {
1951
+ const _ = x + v, S = w + v, B = a[_], E = a[_ + 3], U = a[S], D = a[S + 3];
1952
+ a[c + v] = B < U ? B : U, a[c + v + 3] = E > D ? E : D;
1953
+ }
1954
+ return R;
1955
+ }
1956
+ }
1957
+ }
1958
+ function wt(n, t, i, e, s) {
1959
+ let r, o, f, a, u, l;
1960
+ const p = 1 / i.direction.x, c = 1 / i.direction.y, d = 1 / i.direction.z, y = i.origin.x, g = i.origin.y, x = i.origin.z;
1961
+ let w = t[n], m = t[n + 3], h = t[n + 1], b = t[n + 3 + 1], A = t[n + 2], P = t[n + 3 + 2];
1962
+ return p >= 0 ? (r = (w - y) * p, o = (m - y) * p) : (r = (m - y) * p, o = (w - y) * p), c >= 0 ? (f = (h - g) * c, a = (b - g) * c) : (f = (b - g) * c, a = (h - g) * c), r > a || f > o || ((f > r || isNaN(r)) && (r = f), (a < o || isNaN(o)) && (o = a), d >= 0 ? (u = (A - x) * d, l = (P - x) * d) : (u = (P - x) * d, l = (A - x) * d), r > l || u > o) ? !1 : ((u > r || r !== r) && (r = u), (l < o || o !== o) && (o = l), r <= s && o >= e);
1963
+ }
1964
+ function Rs(n, t, i, e, s, r, o, f) {
1965
+ const { geometry: a, _indirectBuffer: u } = n;
1966
+ for (let l = e, p = e + s; l < p; l++) {
1967
+ let c = u ? u[l] : l;
1968
+ Me(a, t, i, c, r, o, f);
1969
+ }
1970
+ }
1971
+ function _s(n, t, i, e, s, r, o) {
1972
+ const { geometry: f, _indirectBuffer: a } = n;
1973
+ let u = 1 / 0, l = null;
1974
+ for (let p = e, c = e + s; p < c; p++) {
1975
+ let d;
1976
+ d = Me(f, t, i, a ? a[p] : p, null, r, o), d && d.distance < u && (l = d, u = d.distance);
1977
+ }
1978
+ return l;
1979
+ }
1980
+ function Bs(n, t, i, e, s, r, o) {
1981
+ const { geometry: f } = i, { index: a } = f, u = f.attributes.position;
1982
+ for (let l = n, p = t + n; l < p; l++) {
1983
+ let c;
1984
+ if (c = i.resolveTriangleIndex(l), j(o, c * 3, a, u), o.needsUpdate = !0, e(o, c, s, r))
1985
+ return !0;
1986
+ }
1987
+ return !1;
1988
+ }
1989
+ function Es(n, t, i, e, s, r, o) {
1990
+ I.setBuffer(n._roots[t]), qe(0, n, i, e, s, r, o), I.clearBuffer();
1991
+ }
1992
+ function qe(n, t, i, e, s, r, o) {
1993
+ const { float32Array: f, uint16Array: a, uint32Array: u } = I, l = n * 2;
1994
+ if (q(l, a)) {
1995
+ const c = J(n, u), d = Z(l, a);
1996
+ vs(t, i, e, c, d, s, r, o);
1997
+ } else {
1998
+ const c = V(n);
1999
+ wt(c, f, e, r, o) && qe(c, t, i, e, s, r, o);
2000
+ const d = W(n, u);
2001
+ wt(d, f, e, r, o) && qe(d, t, i, e, s, r, o);
2002
+ }
2003
+ }
2004
+ const zs = ["x", "y", "z"];
2005
+ function Fs(n, t, i, e, s, r) {
2006
+ I.setBuffer(n._roots[t]);
2007
+ const o = Oe(0, n, i, e, s, r);
2008
+ return I.clearBuffer(), o;
2009
+ }
2010
+ function Oe(n, t, i, e, s, r) {
2011
+ const { float32Array: o, uint16Array: f, uint32Array: a } = I;
2012
+ let u = n * 2;
2013
+ if (q(u, f)) {
2014
+ const p = J(n, a), c = Z(u, f);
2015
+ return Ps(t, i, e, p, c, s, r);
2016
+ } else {
2017
+ const p = ei(n, a), c = zs[p], y = e.direction[c] >= 0;
2018
+ let g, x;
2019
+ y ? (g = V(n), x = W(n, a)) : (g = W(n, a), x = V(n));
2020
+ const m = wt(g, o, e, s, r) ? Oe(g, t, i, e, s, r) : null;
2021
+ if (m) {
2022
+ const A = m.point[c];
2023
+ if (y ? A <= o[x + p] : (
2024
+ // min bounding data
2025
+ A >= o[x + p + 3]
2026
+ ))
2027
+ return m;
2028
+ }
2029
+ const b = wt(x, o, e, s, r) ? Oe(x, t, i, e, s, r) : null;
2030
+ return m && b ? m.distance <= b.distance ? m : b : m || b || null;
2031
+ }
2032
+ }
2033
+ const re = /* @__PURE__ */ new it(), Et = /* @__PURE__ */ new st(), zt = /* @__PURE__ */ new st(), Ot = /* @__PURE__ */ new H(), zi = /* @__PURE__ */ new Q(), ae = /* @__PURE__ */ new Q();
2034
+ function Us(n, t, i, e) {
2035
+ I.setBuffer(n._roots[t]);
2036
+ const s = Ve(0, n, i, e);
2037
+ return I.clearBuffer(), s;
2038
+ }
2039
+ function Ve(n, t, i, e, s = null) {
2040
+ const { float32Array: r, uint16Array: o, uint32Array: f } = I;
2041
+ let a = n * 2;
2042
+ if (s === null && (i.boundingBox || i.computeBoundingBox(), zi.set(i.boundingBox.min, i.boundingBox.max, e), s = zi), q(a, o)) {
2043
+ const l = t.geometry, p = l.index, c = l.attributes.position, d = i.index, y = i.attributes.position, g = J(n, f), x = Z(a, o);
2044
+ if (Ot.copy(e).invert(), i.boundsTree)
2045
+ return k(n, r, ae), ae.matrix.copy(Ot), ae.needsUpdate = !0, i.boundsTree.shapecast({
2046
+ intersectsBounds: (m) => ae.intersectsBox(m),
2047
+ intersectsTriangle: (m) => {
2048
+ m.a.applyMatrix4(e), m.b.applyMatrix4(e), m.c.applyMatrix4(e), m.needsUpdate = !0;
2049
+ for (let h = g * 3, b = (x + g) * 3; h < b; h += 3)
2050
+ if (j(zt, h, p, c), zt.needsUpdate = !0, m.intersectsTriangle(zt))
2051
+ return !0;
2052
+ return !1;
2053
+ }
2054
+ });
2055
+ {
2056
+ const w = Ae(i);
2057
+ for (let m = g * 3, h = (x + g) * 3; m < h; m += 3) {
2058
+ j(Et, m, p, c), Et.a.applyMatrix4(Ot), Et.b.applyMatrix4(Ot), Et.c.applyMatrix4(Ot), Et.needsUpdate = !0;
2059
+ for (let b = 0, A = w * 3; b < A; b += 3)
2060
+ if (j(zt, b, d, y), zt.needsUpdate = !0, Et.intersectsTriangle(zt))
2061
+ return !0;
2062
+ }
2063
+ }
2064
+ } else {
2065
+ const l = V(n), p = W(n, f);
2066
+ return k(l, r, re), !!(s.intersectsBox(re) && Ve(l, t, i, e, s) || (k(p, r, re), s.intersectsBox(re) && Ve(p, t, i, e, s)));
2067
+ }
2068
+ }
2069
+ const ce = /* @__PURE__ */ new H(), ze = /* @__PURE__ */ new Q(), Vt = /* @__PURE__ */ new Q(), $s = /* @__PURE__ */ new z(), Is = /* @__PURE__ */ new z(), Ds = /* @__PURE__ */ new z(), Ls = /* @__PURE__ */ new z();
2070
+ function ks(n, t, i, e = {}, s = {}, r = 0, o = 1 / 0) {
2071
+ t.boundingBox || t.computeBoundingBox(), ze.set(t.boundingBox.min, t.boundingBox.max, i), ze.needsUpdate = !0;
2072
+ const f = n.geometry, a = f.attributes.position, u = f.index, l = t.attributes.position, p = t.index, c = et.getPrimitive(), d = et.getPrimitive();
2073
+ let y = $s, g = Is, x = null, w = null;
2074
+ s && (x = Ds, w = Ls);
2075
+ let m = 1 / 0, h = null, b = null;
2076
+ return ce.copy(i).invert(), Vt.matrix.copy(ce), n.shapecast(
2077
+ {
2078
+ boundsTraverseOrder: (A) => ze.distanceToBox(A),
2079
+ intersectsBounds: (A, P, M) => M < m && M < o ? (P && (Vt.min.copy(A.min), Vt.max.copy(A.max), Vt.needsUpdate = !0), !0) : !1,
2080
+ intersectsRange: (A, P) => {
2081
+ if (t.boundsTree)
2082
+ return t.boundsTree.shapecast({
2083
+ boundsTraverseOrder: (T) => Vt.distanceToBox(T),
2084
+ intersectsBounds: (T, R, v) => v < m && v < o,
2085
+ intersectsRange: (T, R) => {
2086
+ for (let v = T, _ = T + R; v < _; v++) {
2087
+ j(d, 3 * v, p, l), d.a.applyMatrix4(i), d.b.applyMatrix4(i), d.c.applyMatrix4(i), d.needsUpdate = !0;
2088
+ for (let S = A, B = A + P; S < B; S++) {
2089
+ j(c, 3 * S, u, a), c.needsUpdate = !0;
2090
+ const E = c.distanceToTriangle(d, y, x);
2091
+ if (E < m && (g.copy(y), w && w.copy(x), m = E, h = S, b = v), E < r)
2092
+ return !0;
2093
+ }
2094
+ }
2095
+ }
2096
+ });
2097
+ {
2098
+ const M = Ae(t);
2099
+ for (let T = 0, R = M; T < R; T++) {
2100
+ j(d, 3 * T, p, l), d.a.applyMatrix4(i), d.b.applyMatrix4(i), d.c.applyMatrix4(i), d.needsUpdate = !0;
2101
+ for (let v = A, _ = A + P; v < _; v++) {
2102
+ j(c, 3 * v, u, a), c.needsUpdate = !0;
2103
+ const S = c.distanceToTriangle(d, y, x);
2104
+ if (S < m && (g.copy(y), w && w.copy(x), m = S, h = v, b = T), S < r)
2105
+ return !0;
2106
+ }
2107
+ }
2108
+ }
2109
+ }
2110
+ }
2111
+ ), et.releasePrimitive(c), et.releasePrimitive(d), m === 1 / 0 ? null : (e.point ? e.point.copy(g) : e.point = g.clone(), e.distance = m, e.faceIndex = h, s && (s.point ? s.point.copy(w) : s.point = w.clone(), s.point.applyMatrix4(ce), g.applyMatrix4(ce), s.distance = g.sub(s.point).length(), s.faceIndex = b), e);
2112
+ }
2113
+ function js(n, t = null) {
2114
+ t && Array.isArray(t) && (t = new Set(t));
2115
+ const i = n.geometry, e = i.index ? i.index.array : null, s = i.attributes.position;
2116
+ let r, o, f, a, u = 0;
2117
+ const l = n._roots;
2118
+ for (let c = 0, d = l.length; c < d; c++)
2119
+ r = l[c], o = new Uint32Array(r), f = new Uint16Array(r), a = new Float32Array(r), p(0, u), u += r.byteLength;
2120
+ function p(c, d, y = !1) {
2121
+ const g = c * 2;
2122
+ if (q(g, f)) {
2123
+ const x = J(c, o), w = Z(g, f);
2124
+ let m = 1 / 0, h = 1 / 0, b = 1 / 0, A = -1 / 0, P = -1 / 0, M = -1 / 0;
2125
+ for (let T = x, R = x + w; T < R; T++) {
2126
+ const v = 3 * n.resolveTriangleIndex(T);
2127
+ for (let _ = 0; _ < 3; _++) {
2128
+ let S = v + _;
2129
+ S = e ? e[S] : S;
2130
+ const B = s.getX(S), E = s.getY(S), U = s.getZ(S);
2131
+ B < m && (m = B), B > A && (A = B), E < h && (h = E), E > P && (P = E), U < b && (b = U), U > M && (M = U);
2132
+ }
2133
+ }
2134
+ return a[c + 0] !== m || a[c + 1] !== h || a[c + 2] !== b || a[c + 3] !== A || a[c + 4] !== P || a[c + 5] !== M ? (a[c + 0] = m, a[c + 1] = h, a[c + 2] = b, a[c + 3] = A, a[c + 4] = P, a[c + 5] = M, !0) : !1;
2135
+ } else {
2136
+ const x = V(c), w = W(c, o);
2137
+ let m = y, h = !1, b = !1;
2138
+ if (t) {
2139
+ if (!m) {
2140
+ const v = x / N + d / X, _ = w / N + d / X;
2141
+ h = t.has(v), b = t.has(_), m = !h && !b;
2142
+ }
2143
+ } else
2144
+ h = !0, b = !0;
2145
+ const A = m || h, P = m || b;
2146
+ let M = !1;
2147
+ A && (M = p(x, d, m));
2148
+ let T = !1;
2149
+ P && (T = p(w, d, m));
2150
+ const R = M || T;
2151
+ if (R)
2152
+ for (let v = 0; v < 3; v++) {
2153
+ const _ = x + v, S = w + v, B = a[_], E = a[_ + 3], U = a[S], D = a[S + 3];
2154
+ a[c + v] = B < U ? B : U, a[c + v + 3] = E > D ? E : D;
2155
+ }
2156
+ return R;
2157
+ }
2158
+ }
2159
+ }
2160
+ function Cs(n, t, i, e, s, r, o) {
2161
+ I.setBuffer(n._roots[t]), We(0, n, i, e, s, r, o), I.clearBuffer();
2162
+ }
2163
+ function We(n, t, i, e, s, r, o) {
2164
+ const { float32Array: f, uint16Array: a, uint32Array: u } = I, l = n * 2;
2165
+ if (q(l, a)) {
2166
+ const c = J(n, u), d = Z(l, a);
2167
+ Rs(t, i, e, c, d, s, r, o);
2168
+ } else {
2169
+ const c = V(n);
2170
+ wt(c, f, e, r, o) && We(c, t, i, e, s, r, o);
2171
+ const d = W(n, u);
2172
+ wt(d, f, e, r, o) && We(d, t, i, e, s, r, o);
2173
+ }
2174
+ }
2175
+ const Ns = ["x", "y", "z"];
2176
+ function qs(n, t, i, e, s, r) {
2177
+ I.setBuffer(n._roots[t]);
2178
+ const o = Ge(0, n, i, e, s, r);
2179
+ return I.clearBuffer(), o;
2180
+ }
2181
+ function Ge(n, t, i, e, s, r) {
2182
+ const { float32Array: o, uint16Array: f, uint32Array: a } = I;
2183
+ let u = n * 2;
2184
+ if (q(u, f)) {
2185
+ const p = J(n, a), c = Z(u, f);
2186
+ return _s(t, i, e, p, c, s, r);
2187
+ } else {
2188
+ const p = ei(n, a), c = Ns[p], y = e.direction[c] >= 0;
2189
+ let g, x;
2190
+ y ? (g = V(n), x = W(n, a)) : (g = W(n, a), x = V(n));
2191
+ const m = wt(g, o, e, s, r) ? Ge(g, t, i, e, s, r) : null;
2192
+ if (m) {
2193
+ const A = m.point[c];
2194
+ if (y ? A <= o[x + p] : (
2195
+ // min bounding data
2196
+ A >= o[x + p + 3]
2197
+ ))
2198
+ return m;
2199
+ }
2200
+ const b = wt(x, o, e, s, r) ? Ge(x, t, i, e, s, r) : null;
2201
+ return m && b ? m.distance <= b.distance ? m : b : m || b || null;
2202
+ }
2203
+ }
2204
+ const le = /* @__PURE__ */ new it(), Ft = /* @__PURE__ */ new st(), Ut = /* @__PURE__ */ new st(), Wt = /* @__PURE__ */ new H(), Fi = /* @__PURE__ */ new Q(), ue = /* @__PURE__ */ new Q();
2205
+ function Os(n, t, i, e) {
2206
+ I.setBuffer(n._roots[t]);
2207
+ const s = Xe(0, n, i, e);
2208
+ return I.clearBuffer(), s;
2209
+ }
2210
+ function Xe(n, t, i, e, s = null) {
2211
+ const { float32Array: r, uint16Array: o, uint32Array: f } = I;
2212
+ let a = n * 2;
2213
+ if (s === null && (i.boundingBox || i.computeBoundingBox(), Fi.set(i.boundingBox.min, i.boundingBox.max, e), s = Fi), q(a, o)) {
2214
+ const l = t.geometry, p = l.index, c = l.attributes.position, d = i.index, y = i.attributes.position, g = J(n, f), x = Z(a, o);
2215
+ if (Wt.copy(e).invert(), i.boundsTree)
2216
+ return k(n, r, ue), ue.matrix.copy(Wt), ue.needsUpdate = !0, i.boundsTree.shapecast({
2217
+ intersectsBounds: (m) => ue.intersectsBox(m),
2218
+ intersectsTriangle: (m) => {
2219
+ m.a.applyMatrix4(e), m.b.applyMatrix4(e), m.c.applyMatrix4(e), m.needsUpdate = !0;
2220
+ for (let h = g, b = x + g; h < b; h++)
2221
+ if (j(Ut, 3 * t.resolveTriangleIndex(h), p, c), Ut.needsUpdate = !0, m.intersectsTriangle(Ut))
2222
+ return !0;
2223
+ return !1;
2224
+ }
2225
+ });
2226
+ {
2227
+ const w = Ae(i);
2228
+ for (let m = g, h = x + g; m < h; m++) {
2229
+ const b = t.resolveTriangleIndex(m);
2230
+ j(Ft, 3 * b, p, c), Ft.a.applyMatrix4(Wt), Ft.b.applyMatrix4(Wt), Ft.c.applyMatrix4(Wt), Ft.needsUpdate = !0;
2231
+ for (let A = 0, P = w * 3; A < P; A += 3)
2232
+ if (j(Ut, A, d, y), Ut.needsUpdate = !0, Ft.intersectsTriangle(Ut))
2233
+ return !0;
2234
+ }
2235
+ }
2236
+ } else {
2237
+ const l = V(n), p = W(n, f);
2238
+ return k(l, r, le), !!(s.intersectsBox(le) && Xe(l, t, i, e, s) || (k(p, r, le), s.intersectsBox(le) && Xe(p, t, i, e, s)));
2239
+ }
2240
+ }
2241
+ const fe = /* @__PURE__ */ new H(), Fe = /* @__PURE__ */ new Q(), Gt = /* @__PURE__ */ new Q(), Vs = /* @__PURE__ */ new z(), Ws = /* @__PURE__ */ new z(), Gs = /* @__PURE__ */ new z(), Xs = /* @__PURE__ */ new z();
2242
+ function Js(n, t, i, e = {}, s = {}, r = 0, o = 1 / 0) {
2243
+ t.boundingBox || t.computeBoundingBox(), Fe.set(t.boundingBox.min, t.boundingBox.max, i), Fe.needsUpdate = !0;
2244
+ const f = n.geometry, a = f.attributes.position, u = f.index, l = t.attributes.position, p = t.index, c = et.getPrimitive(), d = et.getPrimitive();
2245
+ let y = Vs, g = Ws, x = null, w = null;
2246
+ s && (x = Gs, w = Xs);
2247
+ let m = 1 / 0, h = null, b = null;
2248
+ return fe.copy(i).invert(), Gt.matrix.copy(fe), n.shapecast(
2249
+ {
2250
+ boundsTraverseOrder: (A) => Fe.distanceToBox(A),
2251
+ intersectsBounds: (A, P, M) => M < m && M < o ? (P && (Gt.min.copy(A.min), Gt.max.copy(A.max), Gt.needsUpdate = !0), !0) : !1,
2252
+ intersectsRange: (A, P) => {
2253
+ if (t.boundsTree) {
2254
+ const M = t.boundsTree;
2255
+ return M.shapecast({
2256
+ boundsTraverseOrder: (T) => Gt.distanceToBox(T),
2257
+ intersectsBounds: (T, R, v) => v < m && v < o,
2258
+ intersectsRange: (T, R) => {
2259
+ for (let v = T, _ = T + R; v < _; v++) {
2260
+ const S = M.resolveTriangleIndex(v);
2261
+ j(d, 3 * S, p, l), d.a.applyMatrix4(i), d.b.applyMatrix4(i), d.c.applyMatrix4(i), d.needsUpdate = !0;
2262
+ for (let B = A, E = A + P; B < E; B++) {
2263
+ const U = n.resolveTriangleIndex(B);
2264
+ j(c, 3 * U, u, a), c.needsUpdate = !0;
2265
+ const D = c.distanceToTriangle(d, y, x);
2266
+ if (D < m && (g.copy(y), w && w.copy(x), m = D, h = B, b = v), D < r)
2267
+ return !0;
2268
+ }
2269
+ }
2270
+ }
2271
+ });
2272
+ } else {
2273
+ const M = Ae(t);
2274
+ for (let T = 0, R = M; T < R; T++) {
2275
+ j(d, 3 * T, p, l), d.a.applyMatrix4(i), d.b.applyMatrix4(i), d.c.applyMatrix4(i), d.needsUpdate = !0;
2276
+ for (let v = A, _ = A + P; v < _; v++) {
2277
+ const S = n.resolveTriangleIndex(v);
2278
+ j(c, 3 * S, u, a), c.needsUpdate = !0;
2279
+ const B = c.distanceToTriangle(d, y, x);
2280
+ if (B < m && (g.copy(y), w && w.copy(x), m = B, h = v, b = T), B < r)
2281
+ return !0;
2282
+ }
2283
+ }
2284
+ }
2285
+ }
2286
+ }
2287
+ ), et.releasePrimitive(c), et.releasePrimitive(d), m === 1 / 0 ? null : (e.point ? e.point.copy(g) : e.point = g.clone(), e.distance = m, e.faceIndex = h, s && (s.point ? s.point.copy(w) : s.point = w.clone(), s.point.applyMatrix4(fe), g.applyMatrix4(fe), s.distance = g.sub(s.point).length(), s.faceIndex = b), e);
2288
+ }
2289
+ function Ui(n, t, i) {
2290
+ return n === null ? null : (n.point.applyMatrix4(t.matrixWorld), n.distance = n.point.distanceTo(i.ray.origin), n.object = t, n);
2291
+ }
2292
+ const de = /* @__PURE__ */ new Q(), pe = /* @__PURE__ */ new vn(), $i = /* @__PURE__ */ new z(), Ii = /* @__PURE__ */ new H(), Di = /* @__PURE__ */ new z(), Ue = ["getX", "getY", "getZ"];
2293
+ class be extends hs {
2294
+ static serialize(t, i = {}) {
2295
+ i = {
2296
+ cloneBuffers: !0,
2297
+ ...i
2298
+ };
2299
+ const e = t.geometry, s = t._roots, r = t._indirectBuffer, o = e.getIndex(), f = {
2300
+ version: 1,
2301
+ roots: null,
2302
+ index: null,
2303
+ indirectBuffer: null
2304
+ };
2305
+ return i.cloneBuffers ? (f.roots = s.map((a) => a.slice()), f.index = o ? o.array.slice() : null, f.indirectBuffer = r ? r.slice() : null) : (f.roots = s, f.index = o ? o.array : null, f.indirectBuffer = r), f;
2306
+ }
2307
+ static deserialize(t, i, e = {}) {
2308
+ e = {
2309
+ setIndex: !0,
2310
+ indirect: !!t.indirectBuffer,
2311
+ ...e
2312
+ };
2313
+ const { index: s, roots: r, indirectBuffer: o } = t;
2314
+ t.version || (console.warn(
2315
+ "MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."
2316
+ ), a(r));
2317
+ const f = new be(i, { ...e, [ti]: !0 });
2318
+ if (f._roots = r, f._indirectBuffer = o || null, e.setIndex) {
2319
+ const u = i.getIndex();
2320
+ if (u === null) {
2321
+ const l = new qi(t.index, 1, !1);
2322
+ i.setIndex(l);
2323
+ } else u.array !== s && (u.array.set(s), u.needsUpdate = !0);
2324
+ }
2325
+ return f;
2326
+ function a(u) {
2327
+ for (let l = 0; l < u.length; l++) {
2328
+ const p = u[l], c = new Uint32Array(p), d = new Uint16Array(p);
2329
+ for (let y = 0, g = p.byteLength / X; y < g; y++) {
2330
+ const x = N * y, w = 2 * x;
2331
+ q(w, d) || (c[x + 6] = c[x + 6] / N - y);
2332
+ }
2333
+ }
2334
+ }
2335
+ }
2336
+ get primitiveStride() {
2337
+ return 3;
2338
+ }
2339
+ get resolveTriangleIndex() {
2340
+ return this.resolvePrimitiveIndex;
2341
+ }
2342
+ constructor(t, i = {}) {
2343
+ i.maxLeafTris && (console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'), i = {
2344
+ ...i,
2345
+ maxLeafSize: i.maxLeafTris
2346
+ }), super(t, i);
2347
+ }
2348
+ // implement abstract methods from BVH base class
2349
+ shiftTriangleOffsets(t) {
2350
+ return super.shiftPrimitiveOffsets(t);
2351
+ }
2352
+ // write primitive bounds to the buffer - used only for validateBounds at the moment
2353
+ writePrimitiveBounds(t, i, e) {
2354
+ const s = this.geometry, r = this._indirectBuffer, o = s.attributes.position, f = s.index ? s.index.array : null, u = (r ? r[t] : t) * 3;
2355
+ let l = u + 0, p = u + 1, c = u + 2;
2356
+ f && (l = f[l], p = f[p], c = f[c]);
2357
+ for (let d = 0; d < 3; d++) {
2358
+ const y = o[Ue[d]](l), g = o[Ue[d]](p), x = o[Ue[d]](c);
2359
+ let w = y;
2360
+ g < w && (w = g), x < w && (w = x);
2361
+ let m = y;
2362
+ g > m && (m = g), x > m && (m = x), i[e + d] = w, i[e + d + 3] = m;
2363
+ }
2364
+ return i;
2365
+ }
2366
+ // precomputes the bounding box for each triangle; required for quickly calculating tree splits.
2367
+ // result is an array of size count * 6 where triangle i maps to a
2368
+ // [x_center, x_delta, y_center, y_delta, z_center, z_delta] tuple starting at index (i - offset) * 6,
2369
+ // representing the center and half-extent in each dimension of triangle i
2370
+ computePrimitiveBounds(t, i, e) {
2371
+ const s = this.geometry, r = this._indirectBuffer, o = s.attributes.position, f = s.index ? s.index.array : null, a = o.normalized;
2372
+ if (t < 0 || i + t - e.offset > e.length / 6)
2373
+ throw new Error("MeshBVH: compute triangle bounds range is invalid.");
2374
+ const u = o.array, l = o.offset || 0;
2375
+ let p = 3;
2376
+ o.isInterleavedBufferAttribute && (p = o.data.stride);
2377
+ const c = ["getX", "getY", "getZ"], d = e.offset;
2378
+ for (let y = t, g = t + i; y < g; y++) {
2379
+ const w = (r ? r[y] : y) * 3, m = (y - d) * 6;
2380
+ let h = w + 0, b = w + 1, A = w + 2;
2381
+ f && (h = f[h], b = f[b], A = f[A]), a || (h = h * p + l, b = b * p + l, A = A * p + l);
2382
+ for (let P = 0; P < 3; P++) {
2383
+ let M, T, R;
2384
+ a ? (M = o[c[P]](h), T = o[c[P]](b), R = o[c[P]](A)) : (M = u[h + P], T = u[b + P], R = u[A + P]);
2385
+ let v = M;
2386
+ T < v && (v = T), R < v && (v = R);
2387
+ let _ = M;
2388
+ T > _ && (_ = T), R > _ && (_ = R);
2389
+ const S = (_ - v) / 2, B = P * 2;
2390
+ e[m + B + 0] = v + S, e[m + B + 1] = S + (Math.abs(v) + S) * ye;
2391
+ }
2392
+ }
2393
+ return e;
2394
+ }
2395
+ raycastObject3D(t, i, e = []) {
2396
+ const { material: s } = t;
2397
+ if (s === void 0)
2398
+ return;
2399
+ Ii.copy(t.matrixWorld).invert(), pe.copy(i.ray).applyMatrix4(Ii), Di.setFromMatrixScale(t.matrixWorld), $i.copy(pe.direction).multiply(Di);
2400
+ const r = $i.length(), o = i.near / r, f = i.far / r;
2401
+ if (i.firstHitOnly === !0) {
2402
+ let a = this.raycastFirst(pe, s, o, f);
2403
+ a = Ui(a, t, i), a && e.push(a);
2404
+ } else {
2405
+ const a = this.raycast(pe, s, o, f);
2406
+ for (let u = 0, l = a.length; u < l; u++) {
2407
+ const p = Ui(a[u], t, i);
2408
+ p && e.push(p);
2409
+ }
2410
+ }
2411
+ return e;
2412
+ }
2413
+ refit(t = null) {
2414
+ return (this.indirect ? js : Ts)(this, t);
2415
+ }
2416
+ /* Core Cast Functions */
2417
+ raycast(t, i = ui, e = 0, s = 1 / 0) {
2418
+ const r = this._roots, o = [], f = this.indirect ? Cs : Es;
2419
+ for (let a = 0, u = r.length; a < u; a++)
2420
+ f(this, a, i, t, o, e, s);
2421
+ return o;
2422
+ }
2423
+ raycastFirst(t, i = ui, e = 0, s = 1 / 0) {
2424
+ const r = this._roots;
2425
+ let o = null;
2426
+ const f = this.indirect ? qs : Fs;
2427
+ for (let a = 0, u = r.length; a < u; a++) {
2428
+ const l = f(this, a, i, t, e, s);
2429
+ l != null && (o == null || l.distance < o.distance) && (o = l);
2430
+ }
2431
+ return o;
2432
+ }
2433
+ intersectsGeometry(t, i) {
2434
+ let e = !1;
2435
+ const s = this._roots, r = this.indirect ? Os : Us;
2436
+ for (let o = 0, f = s.length; o < f && (e = r(this, o, t, i), !e); o++)
2437
+ ;
2438
+ return e;
2439
+ }
2440
+ shapecast(t) {
2441
+ const i = et.getPrimitive(), e = super.shapecast(
2442
+ {
2443
+ ...t,
2444
+ intersectsPrimitive: t.intersectsTriangle,
2445
+ scratchPrimitive: i,
2446
+ // TODO: is the performance significant enough for the added complexity here?
2447
+ // can we just use one function?
2448
+ iterate: this.indirect ? Bs : Ss
2449
+ }
2450
+ );
2451
+ return et.releasePrimitive(i), e;
2452
+ }
2453
+ bvhcast(t, i, e) {
2454
+ let {
2455
+ intersectsRanges: s,
2456
+ intersectsTriangles: r
2457
+ } = e;
2458
+ const o = et.getPrimitive(), f = this.geometry.index, a = this.geometry.attributes.position, u = this.indirect ? (y) => {
2459
+ const g = this.resolveTriangleIndex(y);
2460
+ j(o, g * 3, f, a);
2461
+ } : (y) => {
2462
+ j(o, y * 3, f, a);
2463
+ }, l = et.getPrimitive(), p = t.geometry.index, c = t.geometry.attributes.position, d = t.indirect ? (y) => {
2464
+ const g = t.resolveTriangleIndex(y);
2465
+ j(l, g * 3, p, c);
2466
+ } : (y) => {
2467
+ j(l, y * 3, p, c);
2468
+ };
2469
+ if (r) {
2470
+ if (!(t instanceof be))
2471
+ throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');
2472
+ const y = (g, x, w, m, h, b, A, P) => {
2473
+ for (let M = w, T = w + m; M < T; M++) {
2474
+ d(M), l.a.applyMatrix4(i), l.b.applyMatrix4(i), l.c.applyMatrix4(i), l.needsUpdate = !0;
2475
+ for (let R = g, v = g + x; R < v; R++)
2476
+ if (u(R), o.needsUpdate = !0, r(o, l, R, M, h, b, A, P))
2477
+ return !0;
2478
+ }
2479
+ return !1;
2480
+ };
2481
+ if (s) {
2482
+ const g = s;
2483
+ s = function(x, w, m, h, b, A, P, M) {
2484
+ return g(x, w, m, h, b, A, P, M) ? !0 : y(x, w, m, h, b, A, P, M);
2485
+ };
2486
+ } else
2487
+ s = y;
2488
+ }
2489
+ return super.bvhcast(t, i, { intersectsRanges: s });
2490
+ }
2491
+ /* Derived Cast Functions */
2492
+ intersectsBox(t, i) {
2493
+ return de.set(t.min, t.max, i), de.needsUpdate = !0, this.shapecast(
2494
+ {
2495
+ intersectsBounds: (e) => de.intersectsBox(e),
2496
+ intersectsTriangle: (e) => de.intersectsTriangle(e)
2497
+ }
2498
+ );
2499
+ }
2500
+ intersectsSphere(t) {
2501
+ return this.shapecast(
2502
+ {
2503
+ intersectsBounds: (i) => t.intersectsBox(i),
2504
+ intersectsTriangle: (i) => i.intersectsSphere(t)
2505
+ }
2506
+ );
2507
+ }
2508
+ closestPointToGeometry(t, i, e = {}, s = {}, r = 0, o = 1 / 0) {
2509
+ return (this.indirect ? Js : ks)(
2510
+ this,
2511
+ t,
2512
+ i,
2513
+ e,
2514
+ s,
2515
+ r,
2516
+ o
2517
+ );
2518
+ }
2519
+ closestPointToPoint(t, i = {}, e = 0, s = 1 / 0) {
2520
+ return xs(
2521
+ this,
2522
+ t,
2523
+ i,
2524
+ e,
2525
+ s
2526
+ );
2527
+ }
2528
+ }
2529
+ const It = {
2530
+ Mesh: C.prototype.raycast,
2531
+ Line: Ye.prototype.raycast,
2532
+ LineSegments: Qe.prototype.raycast,
2533
+ LineLoop: Wi.prototype.raycast,
2534
+ Points: Gi.prototype.raycast,
2535
+ BatchedMesh: Sn.prototype.raycast
2536
+ }, G = /* @__PURE__ */ new C(), me = [];
2537
+ function Hs(n, t) {
2538
+ if (this.isBatchedMesh)
2539
+ Zs.call(this, n, t);
2540
+ else {
2541
+ const { geometry: i } = this;
2542
+ if (i.boundsTree)
2543
+ i.boundsTree.raycastObject3D(this, n, t);
2544
+ else {
2545
+ let e;
2546
+ if (this instanceof C)
2547
+ e = It.Mesh;
2548
+ else if (this instanceof Qe)
2549
+ e = It.LineSegments;
2550
+ else if (this instanceof Wi)
2551
+ e = It.LineLoop;
2552
+ else if (this instanceof Ye)
2553
+ e = It.Line;
2554
+ else if (this instanceof Gi)
2555
+ e = It.Points;
2556
+ else
2557
+ throw new Error("BVH: Fallback raycast function not found.");
2558
+ e.call(this, n, t);
2559
+ }
2560
+ }
2561
+ }
2562
+ function Zs(n, t) {
2563
+ if (this.boundsTrees) {
2564
+ const i = this.boundsTrees, e = this._drawInfo || this._instanceInfo, s = this._drawRanges || this._geometryInfo, r = this.matrixWorld;
2565
+ G.material = this.material, G.geometry = this.geometry;
2566
+ const o = G.geometry.boundsTree, f = G.geometry.drawRange;
2567
+ G.geometry.boundingSphere === null && (G.geometry.boundingSphere = new Pn());
2568
+ for (let a = 0, u = e.length; a < u; a++) {
2569
+ if (!this.getVisibleAt(a))
2570
+ continue;
2571
+ const l = e[a].geometryIndex;
2572
+ if (G.geometry.boundsTree = i[l], this.getMatrixAt(a, G.matrixWorld).premultiply(r), !G.geometry.boundsTree) {
2573
+ this.getBoundingBoxAt(l, G.geometry.boundingBox), this.getBoundingSphereAt(l, G.geometry.boundingSphere);
2574
+ const p = s[l];
2575
+ G.geometry.setDrawRange(p.start, p.count);
2576
+ }
2577
+ G.raycast(n, me);
2578
+ for (let p = 0, c = me.length; p < c; p++) {
2579
+ const d = me[p];
2580
+ d.object = this, d.batchId = a, t.push(d);
2581
+ }
2582
+ me.length = 0;
2583
+ }
2584
+ G.geometry.boundsTree = o, G.geometry.drawRange = f, G.material = null, G.geometry = null;
2585
+ } else
2586
+ It.BatchedMesh.call(this, n, t);
2587
+ }
2588
+ function $e(n) {
2589
+ return n.type === "continuous" || !n.limits ? 0 : Math.max(n.limits.lower, Math.min(n.limits.upper, 0));
2590
+ }
2591
+ class Qs {
2592
+ constructor(t, i) {
2593
+ $(this, "root");
2594
+ $(this, "visual");
2595
+ $(this, "joints", /* @__PURE__ */ new Map());
2596
+ $(this, "values", /* @__PURE__ */ new Map());
2597
+ $(this, "specs", /* @__PURE__ */ new Map());
2598
+ $(this, "pickMeshes", []);
2599
+ $(this, "disposed", !1);
2600
+ $(this, "initialRoots", /* @__PURE__ */ new Map());
2601
+ this.visual = i, this.root = i.root;
2602
+ const e = new Set(t.links.map((d) => d.id)), s = t.joints.filter((d) => e.has(d.parent) && e.has(d.child) && d.parent !== d.child), r = new Set(s.map((d) => d.child)), o = t.links.filter((d) => !r.has(d.id)), f = /* @__PURE__ */ new Map(), a = /* @__PURE__ */ new Set();
2603
+ for (const d of s)
2604
+ a.has(d.child) || (a.add(d.child), f.set(d.parent, [...f.get(d.parent) ?? [], d]));
2605
+ const u = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Set(), p = (d) => {
2606
+ if (l.has(d)) return;
2607
+ l.add(d), u.add(d);
2608
+ const y = i.bindings.get(d);
2609
+ if (!y) {
2610
+ l.delete(d);
2611
+ return;
2612
+ }
2613
+ for (const g of f.get(d) ?? []) {
2614
+ if (l.has(g.child) || u.has(g.child)) continue;
2615
+ const x = i.bindings.get(g.child);
2616
+ if (!x) continue;
2617
+ y.add(x);
2618
+ const w = {
2619
+ joint: g,
2620
+ child: x,
2621
+ originPosition: new z().fromArray(g.origin.position),
2622
+ originQuaternion: Qt(g.origin),
2623
+ axis: new z().fromArray(g.axis).normalize()
2624
+ };
2625
+ this.joints.set(g.id, w), this.specs.set(g.id, g), this.values.set(g.id, $e(g)), this.apply(w, this.values.get(g.id)), p(g.child);
2626
+ }
2627
+ l.delete(d);
2628
+ }, c = o.length ? o : t.links;
2629
+ for (const d of c) {
2630
+ if (u.has(d.id)) continue;
2631
+ const y = i.bindings.get(d.id);
2632
+ y && (this.root.add(y), p(d.id));
2633
+ }
2634
+ for (const d of t.links) {
2635
+ if (u.has(d.id)) continue;
2636
+ const y = i.bindings.get(d.id);
2637
+ y && (this.root.add(y), p(d.id));
2638
+ }
2639
+ if (o.length === 1) {
2640
+ const d = Hi(t, o[0].id, f), y = i.bindings.get(o[0].id);
2641
+ y && d > 0 && (y.position.z += d);
2642
+ }
2643
+ for (const d of i.bindings.values()) d.parent === this.root && this.initialRoots.set(d, { position: d.position.clone(), quaternion: d.quaternion.clone() });
2644
+ this.applyAll(), this.preparePicking(), this.root.updateMatrixWorld(!0);
2645
+ }
2646
+ pickRoots() {
2647
+ return this.pickMeshes;
2648
+ }
2649
+ value(t) {
2650
+ return this.values.get(t);
2651
+ }
2652
+ valuesSnapshot() {
2653
+ return Object.freeze(Object.fromEntries(this.values));
2654
+ }
2655
+ setJointValue(t, i) {
2656
+ if (this.disposed) throw Xt("URDF kinematic binding has been disposed.", "E_URDF_INACTIVE");
2657
+ const e = this.joints.get(t);
2658
+ if (!e) throw Xt(`Unknown URDF joint: ${t}`, "E_URDF_JOINT_UNKNOWN");
2659
+ if (!Number.isFinite(i)) throw Xt(`Joint value must be finite: ${t}`, "E_URDF_JOINT_VALUE");
2660
+ let s = i;
2661
+ if (e.joint.type !== "continuous" && e.joint.limits && (s = Math.max(e.joint.limits.lower, Math.min(e.joint.limits.upper, i))), ["revolute", "continuous", "prismatic"].includes(e.joint.type) || (s = 0), e.joint.mimic) throw Xt(`Mimic joint is controlled by ${e.joint.mimic.joint}: ${t}`, "E_URDF_MIMIC_READONLY");
2662
+ const r = xe([...this.specs.values()]).get(t);
2663
+ return r && (s = Math.max(r.lower, Math.min(r.upper, s))), this.values.set(t, s), this.applyAll(), this.root.updateMatrixWorld(!0), s;
2664
+ }
2665
+ resetJoint(t) {
2666
+ const i = this.joints.get(t);
2667
+ if (!i) throw Xt(`Unknown URDF joint: ${t}`, "E_URDF_JOINT_UNKNOWN");
2668
+ this.setJointValue(t, $e(i.joint));
2669
+ }
2670
+ syncPhysicsPose(t, i) {
2671
+ for (const [e, s] of Object.entries(t)) {
2672
+ const r = this.joints.get(e);
2673
+ r && Number.isFinite(s) && (this.values.set(e, s), this.apply(r, s));
2674
+ }
2675
+ for (const e of this.initialRoots.keys()) {
2676
+ const s = i.get(e.name);
2677
+ s && (e.position.copy(s.position), e.quaternion.copy(s.quaternion));
2678
+ }
2679
+ this.root.updateMatrixWorld(!0);
2680
+ }
2681
+ resetPose() {
2682
+ for (const [t, i] of this.initialRoots)
2683
+ t.position.copy(i.position), t.quaternion.copy(i.quaternion);
2684
+ for (const t of this.joints.values()) {
2685
+ const i = $e(t.joint);
2686
+ t.joint.mimic || this.values.set(t.joint.id, i);
2687
+ }
2688
+ this.applyAll(), this.root.updateMatrixWorld(!0);
2689
+ }
2690
+ objectForEntity(t) {
2691
+ var i;
2692
+ return t.startsWith("link:") ? this.visual.bindings.get(t.slice(5)) ?? null : t.startsWith("joint:") ? ((i = this.joints.get(t.slice(6))) == null ? void 0 : i.child) ?? null : t.startsWith("robot:") ? this.root : null;
2693
+ }
2694
+ jointWorldFrame(t) {
2695
+ const i = this.joints.get(t);
2696
+ if (!i) return null;
2697
+ const e = i.child.parent;
2698
+ if (!e) return null;
2699
+ e.updateMatrixWorld(!0);
2700
+ const s = i.originPosition.clone().applyMatrix4(e.matrixWorld), r = e.getWorldQuaternion(new K()).multiply(i.originQuaternion);
2701
+ return { position: s, quaternion: r, axis: i.axis.clone().applyQuaternion(r).normalize() };
2702
+ }
2703
+ dispose() {
2704
+ if (!this.disposed) {
2705
+ this.disposed = !0, this.joints.clear(), this.values.clear(), this.specs.clear();
2706
+ for (const t of this.pickMeshes) {
2707
+ const i = t.geometry;
2708
+ delete i.boundsTree;
2709
+ }
2710
+ this.pickMeshes.length = 0, dt(this.root);
2711
+ }
2712
+ }
2713
+ applyAll() {
2714
+ const t = Ke([...this.specs.values()], Object.fromEntries(this.values));
2715
+ for (const [i, e] of this.joints)
2716
+ this.values.set(i, t[i]), this.apply(e, t[i]);
2717
+ }
2718
+ preparePicking() {
2719
+ const t = /* @__PURE__ */ new Set();
2720
+ this.root.traverse((i) => {
2721
+ if (!(i instanceof C) || !i.geometry) return;
2722
+ const e = i.geometry;
2723
+ !e.boundsTree && !t.has(e) && (e.boundsTree = new be(e, { maxLeafSize: 20, indirect: !0, verbose: !1 }), t.add(e)), i.raycast = Hs, this.pickMeshes.push(i);
2724
+ });
2725
+ }
2726
+ apply(t, i) {
2727
+ t.child.position.copy(t.originPosition), t.child.quaternion.copy(t.originQuaternion), t.joint.type === "revolute" || t.joint.type === "continuous" ? t.child.quaternion.multiply(new K().setFromAxisAngle(t.axis, i)) : t.joint.type === "prismatic" && t.child.position.addScaledVector(t.axis, i);
2728
+ }
2729
+ }
2730
+ function Xt(n, t) {
2731
+ return Object.assign(new Error(n), { code: t });
2732
+ }
2733
+ function Ys(n, t, i = n.source.uri) {
2734
+ var m;
2735
+ const e = io(t, i), s = new Set(n.links.map((h) => h.id)), r = n.joints.filter((h) => s.has(h.parent) && s.has(h.child) && h.parent !== h.child), o = /* @__PURE__ */ new Map();
2736
+ for (const h of r) o.has(h.child) || o.set(h.child, h);
2737
+ const f = n.links.filter((h) => !o.has(h.id)), a = /* @__PURE__ */ new Map();
2738
+ for (const h of o.values()) a.set(h.parent, [...a.get(h.parent) ?? [], h]);
2739
+ const u = [], l = /* @__PURE__ */ new Set(), p = (h) => {
2740
+ if (!l.has(h)) {
2741
+ l.add(h);
2742
+ for (const b of a.get(h) ?? []) p(b.child);
2743
+ }
2744
+ };
2745
+ for (const h of f)
2746
+ u.push(h), p(h.id);
2747
+ for (const h of n.links) l.has(h.id) || (u.push(h), p(h.id));
2748
+ const c = new Set(u.map((h) => h.id)), d = `robot:${n.name}`, y = /* @__PURE__ */ new Map();
2749
+ for (const h of n.joints) y.set(h.parent, [...y.get(h.parent) ?? [], `joint:${h.id}`]);
2750
+ const g = [], x = Object.freeze({
2751
+ id: d,
2752
+ kind: "robot",
2753
+ name: n.name,
2754
+ childIds: u.map((h) => `link:${h.id}`),
2755
+ rootLinkIds: u.map((h) => h.id),
2756
+ source: e.robot
2757
+ });
2758
+ g.push(x);
2759
+ for (const h of n.links) g.push(Ks(h, n, e.links.get(h.id), y, c, o));
2760
+ const w = xe(n.joints);
2761
+ for (const h of n.joints) g.push(to({ ...h, controlLimits: w.get(h.id) }, e.joints.get(h.id), ((m = o.get(h.child)) == null ? void 0 : m.id) === h.id));
2762
+ return Object.freeze({
2763
+ robotName: n.name,
2764
+ sourcePath: i,
2765
+ sourceText: t,
2766
+ nodes: Object.freeze(g),
2767
+ rootEntityId: d,
2768
+ issues: Object.freeze(eo(n, e))
2769
+ });
2770
+ }
2771
+ function Ks(n, t, i, e, s, r) {
2772
+ var f, a, u, l;
2773
+ const o = r.get(n.id);
2774
+ return Object.freeze({
2775
+ id: `link:${n.id}`,
2776
+ kind: "link",
2777
+ name: n.name,
2778
+ parentId: o ? `joint:${o.id}` : `robot:${t.name}`,
2779
+ childIds: Object.freeze(e.get(n.id) ?? []),
2780
+ source: i,
2781
+ mass: (f = n.inertial) == null ? void 0 : f.mass,
2782
+ centerOfMass: (a = n.inertial) == null ? void 0 : a.origin.position,
2783
+ inertiaTensor: (u = n.inertial) == null ? void 0 : u.tensor,
2784
+ inertiaMass: (l = n.inertial) == null ? void 0 : l.mass,
2785
+ inertialRotationRpy: n.inertial ? Object.freeze([...n.inertial.origin.rotationRpy]) : void 0,
2786
+ visualCount: n.visuals.length,
2787
+ collisionCount: n.collisions.length
2788
+ });
2789
+ }
2790
+ function to(n, t, i) {
2791
+ return Object.freeze({
2792
+ id: `joint:${n.id}`,
2793
+ kind: "joint",
2794
+ name: n.id,
2795
+ parentId: `link:${n.parent}`,
2796
+ childIds: Object.freeze([`link:${n.child}`]),
2797
+ source: t,
2798
+ jointType: n.type,
2799
+ parentLink: n.parent,
2800
+ childLink: n.child,
2801
+ axis: Object.freeze([...n.axis]),
2802
+ originPosition: Object.freeze([...n.origin.position]),
2803
+ originRotationRpy: Object.freeze([...n.origin.rotationRpy]),
2804
+ limits: n.limits,
2805
+ effort: n.effort,
2806
+ velocity: n.velocity,
2807
+ controlLimits: n.controlLimits,
2808
+ movable: ["revolute", "continuous", "prismatic"].includes(n.type),
2809
+ ...n.mimic ? { mimic: Object.freeze({ ...n.mimic }) } : {}
2810
+ });
2811
+ }
2812
+ function eo(n, t) {
2813
+ const i = [], e = (c, d, y, g, x, w) => {
2814
+ i.push(Object.freeze({ id: `${c}:${g}`, ruleId: c, severity: "error", title: d, message: y, entityId: g, source: x, values: w ? Object.freeze(w) : void 0 }));
2815
+ }, s = new Set(n.links.map((c) => c.id));
2816
+ for (const c of n.joints)
2817
+ s.has(c.parent) || e("joint.parent.missing", "父连杆不存在", `${c.id} 引用了不存在的 parent link ${c.parent}。`, `joint:${c.id}`, t.joints.get(c.id), { parent: c.parent }), s.has(c.child) || e("joint.child.missing", "子连杆不存在", `${c.id} 引用了不存在的 child link ${c.child}。`, `joint:${c.id}`, t.joints.get(c.id), { child: c.child });
2818
+ const r = n.links.filter((c) => !n.joints.some((d) => s.has(d.parent) && d.child === c.id));
2819
+ r.length !== 1 && e("robot.root.count", "根连杆数量无效", `URDF 必须恰好有一个根连杆,当前为 ${r.length} 个。`, `robot:${n.name}`, t.robot, { roots: r.map((c) => c.id) });
2820
+ const o = /* @__PURE__ */ new Map();
2821
+ for (const c of n.joints) s.has(c.parent) && s.has(c.child) && o.set(c.parent, [...o.get(c.parent) ?? [], c.child]);
2822
+ const f = /* @__PURE__ */ new Set(), a = /* @__PURE__ */ new Set();
2823
+ let u = null;
2824
+ const l = (c, d) => {
2825
+ if (!u) {
2826
+ if (a.has(c)) {
2827
+ const y = d.indexOf(c);
2828
+ u = [...d.slice(Math.max(0, y)), c];
2829
+ return;
2830
+ }
2831
+ if (!f.has(c)) {
2832
+ a.add(c);
2833
+ for (const y of o.get(c) ?? []) l(y, [...d, c]);
2834
+ a.delete(c), f.add(c);
2835
+ }
2836
+ }
2837
+ };
2838
+ for (const c of n.links) l(c.id, []);
2839
+ u && e("robot.graph.cycle", "运动学结构存在环", `运动学链形成循环:${u.join(" → ")}。`, `robot:${n.name}`, t.robot, { cycle: u });
2840
+ const p = /* @__PURE__ */ new Map();
2841
+ for (const c of n.joints) {
2842
+ if (p.set(c.child, [...p.get(c.child) ?? [], c.id]), c.parent === c.child && e("joint.self-reference", "关节父子连杆相同", `${c.id} 的 parent 和 child 都是 ${c.parent}。`, `joint:${c.id}`, t.joints.get(c.id)), ["revolute", "continuous", "prismatic"].includes(c.type)) {
2843
+ const d = c.axis.reduce((y, g) => y + g * g, 0);
2844
+ (!Number.isFinite(d) || d <= Number.EPSILON) && e("joint.axis.zero", "关节轴无效", `${c.id} 的 axis 是零向量。`, `joint:${c.id}`, t.joints.get(c.id), { axis: c.axis });
2845
+ }
2846
+ c.type !== "continuous" && c.limits && c.limits.lower > c.limits.upper && e("joint.limit.order", "关节限位上下界无效", `${c.id} 的 lower ${c.limits.lower} 大于 upper ${c.limits.upper}。`, `joint:${c.id}`, t.joints.get(c.id), { ...c.limits });
2847
+ }
2848
+ for (const [c, d] of p) d.length > 1 && e("link.multiple-parents", "连杆存在多个父关节", `${c} 同时被 ${d.join("、")} 作为 child。`, `link:${c}`, t.links.get(c), { joints: d });
2849
+ for (const c of n.links) {
2850
+ const d = c.inertial;
2851
+ d && ((!(d.mass > 0) || !Number.isFinite(d.mass)) && e("inertial.mass.invalid", "质量无效", `${c.id} 的质量必须是大于零的有限数。`, `link:${c.id}`, t.links.get(c.id), { mass: d.mass }), Ji(d.tensor) || e("inertial.tensor.invalid", "惯性张量无效", `${c.id} 的惯性张量不是正定的物理惯性张量。`, `link:${c.id}`, t.links.get(c.id), { tensor: d.tensor }));
2852
+ }
2853
+ return i;
2854
+ }
2855
+ function io(n, t) {
2856
+ const i = { robot: void 0, links: /* @__PURE__ */ new Map(), joints: /* @__PURE__ */ new Map() };
2857
+ i.robot = Li(n, "robot", void 0, t);
2858
+ for (const e of ["link", "joint"]) {
2859
+ const s = new RegExp(`<${e}\\b[^>]*\\bname\\s*=\\s*(["'])(.*?)\\1[^>]*>`, "gi");
2860
+ for (const r of n.matchAll(s)) {
2861
+ const o = r[2], f = Li(n, e, o, t, r.index);
2862
+ f && i[e === "link" ? "links" : "joints"].set(o, f);
2863
+ }
2864
+ }
2865
+ return i;
2866
+ }
2867
+ function Li(n, t, i, e, s) {
2868
+ const r = s ?? n.search(new RegExp(`<${t}\\b`, "i"));
2869
+ if (r < 0) return;
2870
+ const o = n.indexOf(">", r);
2871
+ if (o < 0) return;
2872
+ const a = n.slice(r, o + 1).trimEnd().endsWith("/>") ? o + 1 : n.indexOf(`</${t}>`, o + 1), u = a < 0 ? o + 1 : a + t.length + 3, l = ki(n, r), p = ki(n, u);
2873
+ return Object.freeze({ file: e, startOffset: r, endOffset: u, startLine: l.line, startColumn: l.column, endLine: p.line, endColumn: p.column });
2874
+ }
2875
+ function ki(n, t) {
2876
+ const e = n.slice(0, t).split(/\r?\n/);
2877
+ return { line: e.length, column: e.at(-1).length + 1 };
2878
+ }
2879
+ class no {
2880
+ constructor(t, i, e, s, r) {
2881
+ $(this, "kind", "urdf");
2882
+ $(this, "overlayRoot", new ut());
2883
+ $(this, "listeners", /* @__PURE__ */ new Set());
2884
+ $(this, "revision", 0);
2885
+ $(this, "selectedEntityId");
2886
+ $(this, "overlays", Object.freeze({ collision: !1, jointAxis: !1, centerOfMass: !1, inertia: !1 }));
2887
+ $(this, "mode");
2888
+ $(this, "dynamicsAvailable");
2889
+ $(this, "dynamicsMessage");
2890
+ $(this, "highlightedMaterials", /* @__PURE__ */ new Map());
2891
+ $(this, "selectionMaterials", /* @__PURE__ */ new Map());
2892
+ $(this, "guideBindings", []);
2893
+ $(this, "guideMatrix", new H());
2894
+ $(this, "overlayInverse", new H());
2895
+ $(this, "guideSizes", /* @__PURE__ */ new Map());
2896
+ $(this, "labelAnchors", /* @__PURE__ */ new Map());
2897
+ $(this, "modelSize", 1);
2898
+ $(this, "disposed", !1);
2899
+ var o, f;
2900
+ this.asset = t, this.document = i, this.binding = e, this.options = s, this.selectedEntityId = ((o = i.nodes.find((a) => a.kind === "joint")) == null ? void 0 : o.id) ?? ((f = i.nodes.find((a) => a.kind === "link")) == null ? void 0 : f.id) ?? i.rootEntityId, this.mode = "kinematic", this.dynamicsAvailable = r, this.overlayRoot.name = "URDF review overlays", this.measureGuideSizes(), this.rebuildOverlay();
2901
+ }
2902
+ getSnapshot() {
2903
+ return Object.freeze({
2904
+ revision: this.revision,
2905
+ kind: "urdf",
2906
+ robotName: this.document.robotName,
2907
+ sourcePath: this.document.sourcePath,
2908
+ sourceText: this.document.sourceText,
2909
+ nodes: this.document.nodes,
2910
+ rootEntityId: this.document.rootEntityId,
2911
+ selectedEntityId: this.selectedEntityId,
2912
+ jointValues: this.binding.valuesSnapshot(),
2913
+ overlays: this.overlays,
2914
+ issues: this.document.issues,
2915
+ mode: this.mode,
2916
+ dynamicsAvailable: this.dynamicsAvailable,
2917
+ ...this.dynamicsMessage ? { dynamicsMessage: this.dynamicsMessage } : {}
2918
+ });
2919
+ }
2920
+ subscribe(t) {
2921
+ return this.listeners.add(t), () => this.listeners.delete(t);
2922
+ }
2923
+ select(t) {
2924
+ if (!(this.mode === "dynamics-running" || this.mode === "dynamics-initializing")) {
2925
+ if (t !== null && !this.document.nodes.some((i) => i.id === t)) throw so(`Unknown URDF entity: ${t}`, "E_URDF_ENTITY_UNKNOWN");
2926
+ this.selectedEntityId !== t && (this.selectedEntityId = t, this.rebuildOverlay(), this.publish());
2927
+ }
2928
+ }
2929
+ setJointValue(t, i) {
2930
+ this.mode === "dynamics-running" || this.mode === "dynamics-initializing" || (this.options.enterKinematicPreview(), this.binding.setJointValue(t, i), this.mode = "kinematic", this.rebuildGuides(), this.publish());
2931
+ }
2932
+ resetJoint(t) {
2933
+ this.mode === "dynamics-running" || this.mode === "dynamics-initializing" || (this.options.enterKinematicPreview(), this.binding.resetJoint(t), this.mode = "kinematic", this.rebuildOverlay(), this.publish());
2934
+ }
2935
+ resetPose() {
2936
+ this.options.enterKinematicPreview(), this.binding.resetPose(), this.mode = "kinematic", this.rebuildOverlay(), this.publish();
2937
+ }
2938
+ setOverlay(t, i) {
2939
+ this.overlays[t] !== i && (this.overlays = Object.freeze({ ...this.overlays, [t]: i }), t === "collision" && this.options.setCollisionVisible(i), this.rebuildOverlay(), this.publish());
2940
+ }
2941
+ enterKinematicPreview() {
2942
+ this.options.enterKinematicPreview(), this.mode = "kinematic", this.overlayRoot.visible = !0, this.publish();
2943
+ }
2944
+ setMode(t, i) {
2945
+ t === "dynamics-unavailable" ? (this.mode = "kinematic", this.dynamicsAvailable = !1) : this.mode = t, this.overlayRoot.visible = this.mode !== "dynamics-initializing", (t === "dynamics-running" || t === "dynamics-initializing") && (this.selectedEntityId = null), this.dynamicsMessage = i, this.rebuildOverlay(), this.publish();
2946
+ }
2947
+ jointWorldFrame(t) {
2948
+ return this.binding.jointWorldFrame(t);
2949
+ }
2950
+ pickRoots() {
2951
+ var t, i;
2952
+ return ((i = (t = this.options).pickRoots) == null ? void 0 : i.call(t)) ?? this.binding.pickRoots();
2953
+ }
2954
+ selectionObject() {
2955
+ return this.selectedEntityId ? this.binding.objectForEntity(this.selectedEntityId) : null;
2956
+ }
2957
+ dispose() {
2958
+ if (!this.disposed) {
2959
+ this.disposed = !0, this.listeners.clear(), this.restoreSelectionMaterials();
2960
+ for (const t of this.selectionMaterials.values()) t.dispose();
2961
+ this.selectionMaterials.clear(), dt(this.overlayRoot), this.overlayRoot.removeFromParent();
2962
+ }
2963
+ }
2964
+ publish() {
2965
+ if (this.disposed) return;
2966
+ this.revision += 1;
2967
+ const t = this.getSnapshot();
2968
+ for (const i of this.listeners) i(t);
2969
+ this.options.requestRender();
2970
+ }
2971
+ rebuildOverlay() {
2972
+ if (this.overlayRoot.visible = this.mode !== "dynamics-initializing", this.restoreSelectionMaterials(), this.clearGuides(), this.buildMassGuides(), this.buildJointGuides(), this.syncGuides(), !this.selectedEntityId) return;
2973
+ const t = this.document.nodes.find((e) => e.id === this.selectedEntityId);
2974
+ if (!t) return;
2975
+ const i = this.binding.objectForEntity(t.id);
2976
+ i && t.kind !== "robot" && this.applySelectionMaterials(i);
2977
+ }
2978
+ rebuildGuides() {
2979
+ this.overlayRoot.visible = this.mode !== "dynamics-initializing", this.clearGuides(), this.buildMassGuides(), this.buildJointGuides(), this.syncGuides(), this.selectedEntityId && this.document.nodes.find((t) => t.id === this.selectedEntityId);
2980
+ }
2981
+ /** Update transforms only: physics ticks must not rebuild geometry or publish UI state. */
2982
+ syncGuides() {
2983
+ if (!(this.disposed || !this.overlayRoot.visible || !this.guideBindings.length)) {
2984
+ this.overlayRoot.updateWorldMatrix(!0, !1), this.overlayInverse.copy(this.overlayRoot.matrixWorld).invert();
2985
+ for (const { guide: t, source: i, local: e } of this.guideBindings)
2986
+ i.updateWorldMatrix(!0, !1), this.guideMatrix.multiplyMatrices(this.overlayInverse, i.matrixWorld).multiply(e), this.guideMatrix.decompose(t.position, t.quaternion, t.scale), t.updateMatrixWorld(!0);
2987
+ }
2988
+ }
2989
+ linkObject(t) {
2990
+ var i, e;
2991
+ return ((e = (i = this.options).linkObject) == null ? void 0 : e.call(i, t)) ?? this.binding.objectForEntity(`link:${t}`);
2992
+ }
2993
+ trackGuide(t, i) {
2994
+ i.updateWorldMatrix(!0, !1), this.overlayRoot.updateWorldMatrix(!0, !1), t.updateWorldMatrix(!0, !1);
2995
+ const e = i.matrixWorld.clone().invert().multiply(t.matrixWorld);
2996
+ this.guideBindings.push({ guide: t, source: i, local: e });
2997
+ }
2998
+ clearGuides() {
2999
+ this.guideBindings.length = 0, dt(this.overlayRoot), this.overlayRoot.clear();
3000
+ }
3001
+ /** Cache own-link bounds once; exclude child links and never traverse meshes per physics tick. */
3002
+ measureGuideSizes() {
3003
+ const t = new it();
3004
+ for (const e of this.document.nodes) {
3005
+ if (e.kind !== "link") continue;
3006
+ const s = this.binding.objectForEntity(e.id);
3007
+ if (!s) continue;
3008
+ s.updateWorldMatrix(!0, !0);
3009
+ const r = new it(), o = (a) => {
3010
+ if (!(a !== s && typeof a.userData.urdfEntityId == "string")) {
3011
+ a instanceof C && (a.geometry.boundingBox || a.geometry.computeBoundingBox(), a.geometry.boundingBox && r.union(a.geometry.boundingBox.clone().applyMatrix4(a.matrixWorld)));
3012
+ for (const u of a.children) o(u);
3013
+ }
3014
+ };
3015
+ if (o(s), r.isEmpty()) continue;
3016
+ this.labelAnchors.set(e.name, r.getCenter(new z()).applyMatrix4(s.matrixWorld.clone().invert()));
3017
+ const f = r.getSize(new z()).length();
3018
+ Number.isFinite(f) && f > 0 && (this.guideSizes.set(e.name, f), t.union(r));
3019
+ }
3020
+ const i = t.getSize(new z()).length();
3021
+ Number.isFinite(i) && i > 0 && (this.modelSize = i);
3022
+ }
3023
+ linkWorldPosition(t, i) {
3024
+ const e = this.linkObject(t);
3025
+ return !e || this.disposed || this.mode === "dynamics-initializing" ? !1 : (e.updateWorldMatrix(!0, !1), i.copy(this.labelAnchors.get(t) ?? new z()).applyMatrix4(e.matrixWorld), !0);
3026
+ }
3027
+ guideSize(t) {
3028
+ const i = this.guideSizes.get(t) ?? this.modelSize * 0.1;
3029
+ return Math.max(this.modelSize * 3e-3, Math.min(i, this.modelSize * 0.35));
3030
+ }
3031
+ buildJointGuides() {
3032
+ const t = this.document.nodes.find((e) => e.id === this.selectedEntityId), i = (t == null ? void 0 : t.kind) === "joint" ? t : (t == null ? void 0 : t.kind) === "link" ? this.document.nodes.find((e) => e.kind === "joint" && e.childLink === t.name) : void 0;
3033
+ for (const e of this.document.nodes) {
3034
+ if (e.kind !== "joint" || !this.overlays.jointAxis && e.id !== (i == null ? void 0 : i.id)) continue;
3035
+ const s = this.linkObject(e.parentLink), r = s ? (() => {
3036
+ s.updateWorldMatrix(!0, !1);
3037
+ const u = s.getWorldQuaternion(new K()).multiply(new K().setFromEuler(new Zt(...e.originRotationRpy, "ZYX")));
3038
+ return { position: new z().fromArray(e.originPosition).applyMatrix4(s.matrixWorld), quaternion: u, axis: new z().fromArray(e.axis).applyQuaternion(u).normalize() };
3039
+ })() : this.binding.jointWorldFrame(e.name);
3040
+ if (!r) continue;
3041
+ const o = new ut();
3042
+ o.name = `Joint guide:${e.name}`;
3043
+ const f = this.guideSize(e.childLink), a = new Tn(0.18 * f);
3044
+ if (a.name = `Joint frame:${e.name}`, a.position.copy(r.position), a.quaternion.copy(r.quaternion), o.add(a), ["revolute", "continuous", "prismatic"].includes(e.jointType)) {
3045
+ const u = r.axis.clone().normalize(), l = new fi(u, r.position, 0.28 * f, 5625523, 0.045 * f, 0.022 * f);
3046
+ if (l.name = `Joint axis:${e.name}`, o.add(l), e.jointType !== "prismatic") {
3047
+ const c = (Math.abs(u.z) < 0.9 ? new z(0, 0, 1) : new z(0, 1, 0)).cross(u).normalize(), d = u.clone().cross(c).normalize(), y = 0.09 * f, g = Math.PI * 1.65, x = r.position.clone().addScaledVector(u, 0.085 * f), w = Array.from({ length: 33 }, (A, P) => {
3048
+ const M = g * P / 32;
3049
+ return x.clone().addScaledVector(c, y * Math.cos(M)).addScaledVector(d, y * Math.sin(M));
3050
+ }), m = new Ye(new Rn().setFromPoints(w), new di({ color: 16761963 }));
3051
+ m.name = `Positive rotation:${e.name}`;
3052
+ const h = c.clone().multiplyScalar(-Math.sin(g)).addScaledVector(d, Math.cos(g)), b = new fi(h, w[32], 0.03 * f, 16761963, 0.03 * f, 0.022 * f);
3053
+ b.name = `Positive rotation arrow:${e.name}`, o.add(m, b);
3054
+ }
3055
+ }
3056
+ o.traverse((u) => {
3057
+ u.renderOrder = 1001;
3058
+ const l = u.material;
3059
+ for (const p of Array.isArray(l) ? l : l ? [l] : [])
3060
+ p.depthTest = !1, p.depthWrite = !1, p.transparent = !0;
3061
+ }), this.overlayRoot.add(o), s && this.trackGuide(o, s);
3062
+ }
3063
+ }
3064
+ buildMassGuides() {
3065
+ if (!this.overlays.centerOfMass && !this.overlays.inertia) return;
3066
+ const t = this.document.nodes.find((e) => e.id === this.selectedEntityId), i = (t == null ? void 0 : t.kind) === "link" ? t.name : (t == null ? void 0 : t.kind) === "joint" ? t.childLink : void 0;
3067
+ for (const e of this.asset.links) {
3068
+ const s = e.inertial, r = this.linkObject(e.id);
3069
+ if (!s || !r) continue;
3070
+ r.updateWorldMatrix(!0, !1);
3071
+ const o = new z().fromArray(s.origin.position).applyMatrix4(r.matrixWorld), f = e.id === i;
3072
+ if (this.overlays.centerOfMass) {
3073
+ const d = new Ze(0.025 * this.guideSize(e.id), 32, 16), y = d.toNonIndexed();
3074
+ d.dispose();
3075
+ const g = y.getAttribute("position"), x = new Float32Array(g.count * 3);
3076
+ for (let m = 0; m < g.count; m += 3) {
3077
+ let h = 0, b = 0, A = 0;
3078
+ for (let M = 0; M < 3; M++)
3079
+ h += g.getX(m + M), b += g.getY(m + M), A += g.getZ(m + M);
3080
+ const P = h * b * A >= 0 ? 1 : 0.015;
3081
+ for (let M = 0; M < 9; M++) x[m * 3 + M] = P;
3082
+ }
3083
+ y.setAttribute("color", new _n(x, 3));
3084
+ const w = new C(y, new pi({ color: f ? 16739210 : 16777215, vertexColors: !0, depthTest: !1, depthWrite: !1 }));
3085
+ w.quaternion.copy(r.getWorldQuaternion(new K())), w.position.copy(o), w.renderOrder = 1002, w.name = `Center of mass:${e.id}`, this.overlayRoot.add(w), this.trackGuide(w, r);
3086
+ }
3087
+ const a = this.overlays.inertia ? kn(s.tensor, s.mass) : null;
3088
+ if (!a) continue;
3089
+ const u = new He(1, 1, 1), l = new Qe(new Bn(u), new di({ color: f ? 16736135 : 2211300, transparent: !0, opacity: f ? 0.98 : 0.82, depthTest: !0, depthWrite: !1 })), p = new C(u, new pi({ color: f ? 16739210 : 3262699, transparent: !0, opacity: f ? 0.28 : 0.16, depthTest: !0, depthWrite: !1 }));
3090
+ p.name = `Inertia fill:${e.id}`;
3091
+ const c = s.origin.rotationQuaternion ? new K().fromArray(s.origin.rotationQuaternion) : new K().setFromEuler(new Zt(...s.origin.rotationRpy, "ZYX"));
3092
+ l.position.copy(o), l.scale.fromArray(a.size), l.quaternion.copy(r.getWorldQuaternion(new K())).multiply(c).multiply(a.rotation), l.renderOrder = 1001, l.name = `Inertia:${e.id}`, p.position.copy(l.position), p.quaternion.copy(l.quaternion), p.scale.copy(l.scale), p.renderOrder = 1e3, this.overlayRoot.add(p, l), this.trackGuide(p, r), this.trackGuide(l, r);
3093
+ }
3094
+ }
3095
+ applySelectionMaterials(t) {
3096
+ const i = (e, s) => {
3097
+ if (!(!s && typeof e.userData.urdfEntityId == "string")) {
3098
+ e instanceof C && e.material && (this.highlightedMaterials.set(e, e.material), e.material = Array.isArray(e.material) ? e.material.map((r) => this.createSelectionMaterial(r)) : this.createSelectionMaterial(e.material));
3099
+ for (const r of e.children) i(r, !1);
3100
+ }
3101
+ };
3102
+ i(t, !0);
3103
+ }
3104
+ createSelectionMaterial(t) {
3105
+ var r;
3106
+ const i = this.selectionMaterials.get(t);
3107
+ if (i) return i;
3108
+ const e = t.clone(), s = e;
3109
+ return (r = s.color) == null || r.set(9425919), s.emissive ? (s.emissive.set(2793430), s.emissiveIntensity = Math.max(s.emissiveIntensity ?? 0, 0.34)) : e instanceof Je && (e.emissive.set(2793430), e.emissiveIntensity = 0.34), e.transparent = t.transparent, e.opacity = t.opacity, e.depthWrite = t.depthWrite, e.needsUpdate = !0, this.selectionMaterials.set(t, e), e;
3110
+ }
3111
+ restoreSelectionMaterials() {
3112
+ for (const [t, i] of this.highlightedMaterials) t.material = i;
3113
+ this.highlightedMaterials.clear();
3114
+ }
3115
+ }
3116
+ function so(n, t) {
3117
+ return Object.assign(new Error(n), { code: t });
3118
+ }
3119
+ async function mo(n, t, i) {
3120
+ var B, E, U, D;
3121
+ const e = n.entryPath ?? n.filename ?? "asset.urdf";
3122
+ (B = t.reportProgress) == null || B.call(t, "fetch", "正在读取模型描述与依赖资源...");
3123
+ let s = await mn(n, i);
3124
+ const r = t.format === "xacro";
3125
+ if (r) {
3126
+ (E = t.reportProgress) == null || E.call(t, "xacro", "正在展开 Xacro 宏与依赖文件...");
3127
+ const { expandXacro: F } = await import("./xacro-DrBtv-gK.js");
3128
+ s = await F(s, e, i, t.options.xacro, t.signal);
3129
+ }
3130
+ if (t.signal.aborted) throw Jt();
3131
+ (U = t.reportProgress) == null || U.call(t, "parse", "正在解析 URDF 结构与连杆...");
3132
+ const o = jn(s, e, i);
3133
+ (D = t.reportProgress) == null || D.call(t, "visual", "正在构建运动学预览...");
3134
+ const f = await yi(o), a = new Qs(o, f), u = await On(o, f), l = o.diagnostics.errors.find((F) => F.code === "E_URDF_INERTIA"), p = o.links.some((F) => F.inertial), c = p && !l, d = new Fn(a.root, t.options.simulationTheme, void 0);
3135
+ u && (u.root.visible = !1, d.attachAuxiliary(u.root));
3136
+ let y = null, g = null, x = null;
3137
+ const w = o.diagnostics.warnings[0], m = w ? { ...w, stage: "visual-material" } : null;
3138
+ let h = l ? { code: l.code, message: l.message, stage: "physics-validation" } : m, b = l ? { status: "unavailable", issue: h } : p ? { status: "available" } : { status: "not-authored" }, A = !1, P = null, M = !1, T = !1;
3139
+ const R = () => {
3140
+ var L;
3141
+ const F = A || !a.root.visible;
3142
+ A = !1, d.setRuntime(void 0), g && (g.root.visible = !1), d.replaceModel(a.root, !1), a.root.visible = !0, u && u.sync(), u != null && u.root && (u.root.visible = v.getSnapshot().overlays.collision), x && (x.root.visible = !1), F && ((L = t.reportSessionState) == null || L.call(t)), t.requestRender();
3143
+ }, v = new no(o, Ys(o, s, r ? `${e} (expanded URDF)` : e), a, {
3144
+ requestRender() {
3145
+ a.root.visible && (u == null || u.sync()), t.requestRender();
3146
+ },
3147
+ setCollisionVisible(F) {
3148
+ u && (u.root.visible = F && a.root.visible), x && (x.root.visible = F && (g == null ? void 0 : g.root.visible) === !0);
3149
+ },
3150
+ enterKinematicPreview: R,
3151
+ linkObject: (F) => g != null && g.root.visible ? g.objectForLink(F) : a.objectForEntity(`link:${F}`),
3152
+ pickRoots: () => A || b.status === "initializing" ? [] : a.pickRoots()
3153
+ }, c);
3154
+ l && v.setMode("dynamics-unavailable", l.message), d.attachAuxiliary(v.overlayRoot);
3155
+ const _ = () => !y || !g ? !1 : (y.setJointValues(v.getSnapshot().jointValues), g == null || g.sync(), d.replaceModel(g.root, !1), d.setRuntime(y), a.root.visible = !1, g.root.visible = !0, u && (u.root.visible = !1), x && (x.root.visible = v.getSnapshot().overlays.collision), !0), S = async () => {
3156
+ var Mt, vt, Pt;
3157
+ if (y || M || !c) return;
3158
+ v.setMode("dynamics-initializing"), b = { status: "initializing" }, (Mt = t.reportSessionState) == null || Mt.call(t);
3159
+ let F = null, L = null, Y = null;
3160
+ try {
3161
+ const rt = await qn(o);
3162
+ if (t.signal.aborted || M) throw Jt();
3163
+ const kt = await import("./mujoco-runtime-C29PXDOl.js");
3164
+ if (F = new kt.MujocoRuntime(), await F.initialize(rt, t.options.mujocoBaseUrl), t.signal.aborted || M || (L = new ai(F, await yi(o)), t.signal.aborted || M)) throw Jt();
3165
+ const at = await Zi(o);
3166
+ if (Y = at ? new ai(F, at) : null, t.signal.aborted || M) throw Jt();
3167
+ y = F, F = null, g = L, L = null, g.root.visible = !1, x = Y, Y = null, x && (x.root.visible = !1, d.attachAuxiliary(x.root)), b = { status: "ready" }, h = m, T && (_(), A = !0, v.setMode("dynamics-running")), (vt = t.reportSessionState) == null || vt.call(t), t.requestRender();
3168
+ } catch (rt) {
3169
+ if (Y == null || Y.dispose(), L == null || L.dispose(), F == null || F.dispose(), M || t.signal.aborted || rt instanceof Error && rt.name === "AbortError") return;
3170
+ const kt = hn(rt, t.signal, "urdf-physics");
3171
+ d.setRuntime(void 0), y == null || y.dispose(), y = null, g == null || g.dispose(), g = null, x && (d.detachAuxiliary(x.root), x.dispose(), x = null), R(), h = { ...kt, stage: "physics-fallback" }, b = { status: "unavailable", issue: h }, v.setMode("dynamics-unavailable", h.message), (Pt = t.reportSessionState) == null || Pt.call(t), t.reportError(rt, { fatal: !1, stage: "physics-start", code: kt.code });
3172
+ }
3173
+ };
3174
+ return {
3175
+ asset: o,
3176
+ stage: d,
3177
+ inspection: v,
3178
+ autoPlay: !1,
3179
+ root: d.root,
3180
+ get capabilities() {
3181
+ const F = b.status === "initializing", L = b.status === "unavailable" || b.status === "not-authored";
3182
+ return { canPlay: !F && !L, canPause: y !== null, canReset: !0, hasPhysics: y !== null, canToggleGround: !0, canToggleCollision: u !== void 0 || x !== null };
3183
+ },
3184
+ get physics() {
3185
+ return b;
3186
+ },
3187
+ get warning() {
3188
+ return h;
3189
+ },
3190
+ isPlaying: () => A,
3191
+ play() {
3192
+ var F;
3193
+ if (!(M || b.status === "unavailable" || b.status === "not-authored")) {
3194
+ if (T = !0, v.select(null), !y) {
3195
+ P ?? (P = S().finally(() => {
3196
+ P = null;
3197
+ }));
3198
+ return;
3199
+ }
3200
+ _() && (A = !0, v.setMode("dynamics-running"), (F = t.reportSessionState) == null || F.call(t));
3201
+ }
3202
+ },
3203
+ pause() {
3204
+ var F;
3205
+ T = !1, A = !1, d.endGrab(), y && (a.syncPhysicsPose(y.getJointValues(o.joints.map((L) => L.id)), g.bodyPoses()), R(), v.setMode("dynamics-paused")), (F = t.reportSessionState) == null || F.call(t), t.requestRender();
3206
+ },
3207
+ reset() {
3208
+ var F;
3209
+ T = !1, d.endGrab(), y && (y.reset(), g == null || g.sync(), x == null || x.sync()), v.resetPose(), d.resetGround(), (F = t.reportSessionState) == null || F.call(t), t.requestRender();
3210
+ },
3211
+ step(F) {
3212
+ if (!y || !A) return !1;
3213
+ const L = y.step(F);
3214
+ return L && (g == null || g.sync(), x == null || x.sync(), v.syncGuides(), d.updateForceLine()), L;
3215
+ },
3216
+ beginGrab(F, L, Y) {
3217
+ return !!(y && d.beginGrab(F, L, Y));
3218
+ },
3219
+ moveGrab(F, L, Y) {
3220
+ y && d.moveGrab(F, L, Y);
3221
+ },
3222
+ endGrab() {
3223
+ d.endGrab();
3224
+ },
3225
+ setCollisionVisible(F) {
3226
+ u && (u.root.visible = F && a.root.visible), x && (x.root.visible = F && (g == null ? void 0 : g.root.visible) === !0);
3227
+ },
3228
+ dispose() {
3229
+ M || (M = !0, A = !1, v.dispose(), u && (d.detachAuxiliary(u.root), u.dispose()), x && (d.detachAuxiliary(x.root), x.dispose()), d.setRuntime(void 0), g == null || g.dispose(), a.dispose(), y == null || y.dispose(), d.dispose());
3230
+ }
3231
+ };
3232
+ }
3233
+ function Jt() {
3234
+ return Object.assign(new Error("Simulation load aborted."), { name: "AbortError", code: "E_ABORTED" });
3235
+ }
3236
+ export {
3237
+ mo as loadUrdfSimulation
3238
+ };