@nebula-spatial/viewer 0.5.17 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +63 -22
  2. package/USD-VISUAL-MATERIAL-SUPPORT.md +5 -1
  3. package/dist/asset-ir-BEDGD9CL.js +637 -0
  4. package/dist/assets/source-types.d.ts +10 -0
  5. package/dist/assets/types.d.ts +59 -6
  6. package/dist/index-DoxM1Msk.js +17223 -0
  7. package/dist/index.d.ts +20 -1
  8. package/dist/index.js +29 -18
  9. package/dist/{mjcf-visual-C0PWP0vB.js → mjcf-visual-CQEeWkL_.js} +12 -13
  10. package/dist/mujoco-runtime-BmuEJ_ST.js +791 -0
  11. package/dist/physics-guide-size-CplAlsve.js +12 -0
  12. package/dist/scene/instances.d.ts +36 -0
  13. package/dist/scene/joints.d.ts +129 -0
  14. package/dist/scene/session.d.ts +26 -0
  15. package/dist/scene/types.d.ts +284 -0
  16. package/dist/session-BnNntPUE.js +9169 -0
  17. package/dist/{session-D44z2smp.js → session-Cz4tFSlO.js} +6 -8
  18. package/dist/session-sBOJEWpK.js +559 -0
  19. package/dist/simulation/physics-runtime-state.d.ts +73 -0
  20. package/dist/simulation/types.d.ts +151 -0
  21. package/dist/simulation/usd-dependency-probe.d.ts +42 -0
  22. package/dist/simulation/usd-inspection.d.ts +66 -0
  23. package/dist/types.d.ts +46 -1
  24. package/dist/ui/camera-axis-gizmo.d.ts +5 -0
  25. package/dist/urdf-session-HKelZnMM.js +1230 -0
  26. package/dist/usd-session-Cn6whyh4.js +10875 -0
  27. package/dist/version.d.ts +1 -1
  28. package/dist/visual/classification.d.ts +20 -0
  29. package/dist/{xacro-CjMp9HT5.js → xacro-Cl7vUCSC.js} +1 -1
  30. package/package.json +2 -1
  31. package/runtime-assets.d.mts +9 -9
  32. package/runtime-assets.mjs +11 -11
  33. package/vite.d.mts +7 -7
  34. package/vite.mjs +115 -115
  35. package/dist/collision-debug-CHPrPNT3.js +0 -2947
  36. package/dist/index-cM9KArXm.js +0 -11499
  37. package/dist/mujoco-runtime-BV2xR38M.js +0 -739
  38. package/dist/resources-CHhCm2f7.js +0 -27
  39. package/dist/session-CKva1mAh.js +0 -801
  40. package/dist/stage-pxmOnL0U.js +0 -592
  41. package/dist/urdf-session-ChpRmt69.js +0 -1264
  42. package/dist/usd-session-auH_xmOc.js +0 -10526
@@ -0,0 +1,1230 @@
1
+ var We = Object.defineProperty;
2
+ var Ce = (i, e, s) => e in i ? We(i, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : i[e] = s;
3
+ var R = (i, e, s) => Ce(i, typeof e != "symbol" ? e + "" : e, s);
4
+ import { c as Ge, b as Te, d as Ve, w as ye, e as ge, p as Je } from "./asset-ir-BEDGD9CL.js";
5
+ import { d as I, N as Pe, O as be, t as Be, u as Qe, v as we, M as Xe, P as Ke, i as Ze, B as Ye, Q as ve, S as Me } from "./index-DoxM1Msk.js";
6
+ import { Quaternion as P, Euler as X, LoadingManager as _e, Group as L, Mesh as z, MeshLambertMaterial as He, MeshPhongMaterial as Re, MeshStandardMaterial as oe, TextureLoader as et, SRGBColorSpace as tt, RepeatWrapping as it, BoxGeometry as re, SphereGeometry as ae, CylinderGeometry as De, CapsuleGeometry as qe, Matrix4 as W, Vector3 as O, MathUtils as st, Matrix3 as Ae, Box3 as $e, AxesHelper as nt, ArrowHelper as Ee, Line as ot, BufferGeometry as rt, LineBasicMaterial as je, Float32BufferAttribute as at, MeshBasicMaterial as Se, LineSegments as lt, EdgesGeometry as ct } from "three";
7
+ import { GLTFLoader as ut } from "three/examples/jsm/loaders/GLTFLoader.js";
8
+ import { ColladaLoader as dt } from "three/examples/jsm/loaders/ColladaLoader.js";
9
+ import { OBJLoader as pt } from "three/examples/jsm/loaders/OBJLoader.js";
10
+ import { STLLoader as ft } from "three/examples/jsm/loaders/STLLoader.js";
11
+ import { k as mt } from "./physics-guide-size-CplAlsve.js";
12
+ function Le(i) {
13
+ const e = new Map(i.map((o) => [o.id, o])), s = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Set(), n = (o) => {
14
+ throw Object.assign(new Error(`Invalid URDF mimic relationship: ${o}`), { code: "E_URDF_MIMIC" });
15
+ }, a = (o) => {
16
+ var d;
17
+ const m = s.get(o);
18
+ if (m) return m;
19
+ const u = e.get(o);
20
+ if (!u || t.has(o)) return n(o);
21
+ t.add(o);
22
+ let c = { root: o, multiplier: 1, offset: 0 };
23
+ if (u.mimic) {
24
+ const b = u.mimic;
25
+ if (![b.multiplier, b.offset].every(Number.isFinite) || !["revolute", "continuous", "prismatic"].includes(u.type) || !["revolute", "continuous", "prismatic"].includes(((d = e.get(b.joint)) == null ? void 0 : d.type) ?? "")) return n(o);
26
+ const l = a(b.joint);
27
+ if (c = { root: l.root, multiplier: b.multiplier * l.multiplier, offset: b.multiplier * l.offset + b.offset }, ![c.multiplier, c.offset].every(Number.isFinite)) return n(o);
28
+ }
29
+ return t.delete(o), s.set(o, c), c;
30
+ };
31
+ for (const o of i) a(o.id);
32
+ return s;
33
+ }
34
+ function ee(i) {
35
+ const e = Le(i), s = /* @__PURE__ */ new Map();
36
+ for (const t of i) {
37
+ const n = e.get(t.id);
38
+ if (s.has(n.root) || s.set(n.root, { lower: -1 / 0, upper: 1 / 0 }), t.type === "continuous" || !t.limits || t.limits.lower > t.limits.upper) continue;
39
+ const a = s.get(n.root);
40
+ if (n.multiplier === 0) {
41
+ if (n.offset < t.limits.lower || n.offset > t.limits.upper) throw new Error(`URDF mimic constant violates limits: ${t.id}`);
42
+ continue;
43
+ }
44
+ const o = (t.limits.lower - n.offset) / n.multiplier, m = (t.limits.upper - n.offset) / n.multiplier;
45
+ if (a.lower = Math.max(a.lower, Math.min(o, m)), a.upper = Math.min(a.upper, Math.max(o, m)), a.lower > a.upper) throw new Error(`URDF mimic limits have no feasible range: ${n.root}`);
46
+ }
47
+ return s;
48
+ }
49
+ function le(i, e = {}) {
50
+ const s = Le(i), t = ee(i);
51
+ return Object.fromEntries(i.map((n) => {
52
+ const a = s.get(n.id), o = t.get(a.root), m = Math.max(o.lower, Math.min(o.upper, e[a.root] ?? 0));
53
+ return [n.id, m * a.multiplier + a.offset];
54
+ }));
55
+ }
56
+ function K(i) {
57
+ return i.rotationQuaternion ? new P().fromArray(i.rotationQuaternion).normalize() : new P().setFromEuler(new X(i.rotationRpy[0], i.rotationRpy[1], i.rotationRpy[2], "ZYX"));
58
+ }
59
+ function ht(i) {
60
+ const e = /* @__PURE__ */ new Map(), s = (t) => {
61
+ if (!(t instanceof He || t instanceof Re)) return t;
62
+ const n = e.get(t);
63
+ if (n) return n;
64
+ const a = new oe({
65
+ name: t.name,
66
+ color: t.color.clone(),
67
+ emissive: t.emissive.clone(),
68
+ emissiveIntensity: t.emissiveIntensity,
69
+ map: t.map,
70
+ emissiveMap: t.emissiveMap,
71
+ normalMap: t.normalMap,
72
+ bumpMap: t.bumpMap,
73
+ bumpScale: t.bumpScale,
74
+ alphaMap: t.alphaMap,
75
+ aoMap: t.aoMap,
76
+ aoMapIntensity: t.aoMapIntensity,
77
+ lightMap: t.lightMap,
78
+ lightMapIntensity: t.lightMapIntensity,
79
+ opacity: t.opacity,
80
+ transparent: t.transparent,
81
+ alphaTest: t.alphaTest,
82
+ side: t.side,
83
+ depthWrite: t.depthWrite,
84
+ vertexColors: t.vertexColors,
85
+ flatShading: t.flatShading,
86
+ roughness: t instanceof Re ? Math.sqrt(2 / (Math.max(0, t.shininess) + 2)) : 0.5,
87
+ metalness: 0
88
+ });
89
+ return a.normalScale.copy(t.normalScale), a.normalMapType = t.normalMapType, a.userData = { ...t.userData, colladaSourceMaterial: t.type }, e.set(t, a), a;
90
+ };
91
+ i.traverse((t) => {
92
+ t instanceof z && (t.material = Array.isArray(t.material) ? t.material.map(s) : s(t.material));
93
+ });
94
+ for (const t of e.keys()) t.dispose();
95
+ }
96
+ async function yt(i, e) {
97
+ var b, l, r;
98
+ const s = await e.text(i), t = new DOMParser().parseFromString(s, "application/xml");
99
+ if (t.querySelector("parsererror") || t.documentElement.localName !== "COLLADA")
100
+ throw new Error(`Invalid URDF COLLADA document: ${i}`);
101
+ const n = ((l = (b = t.querySelector("asset > up_axis")) == null ? void 0 : b.textContent) == null ? void 0 : l.trim()) ?? "Y_UP";
102
+ if (!["X_UP", "Y_UP", "Z_UP"].includes(n)) throw new Error(`Unsupported COLLADA up-axis: ${n}`);
103
+ const a = /* @__PURE__ */ new Map();
104
+ for (const p of t.querySelectorAll("library_images image init_from")) {
105
+ const f = (r = p.textContent) == null ? void 0 : r.trim();
106
+ if (!f || f.startsWith("data:")) continue;
107
+ const h = e.resolve(f, i);
108
+ await e.ensure(h), a.set(f, e.objectUrl(h));
109
+ }
110
+ const o = new _e();
111
+ o.setURLModifier((p) => {
112
+ if (p.startsWith("data:")) return p;
113
+ const f = a.get(p);
114
+ if (!f) throw new Error(`Unresolved COLLADA image: ${p}`);
115
+ return f;
116
+ });
117
+ let m;
118
+ const u = new Promise((p) => {
119
+ m = p;
120
+ });
121
+ let c;
122
+ o.onLoad = m, o.onError = (p) => {
123
+ c = p;
124
+ }, o.itemStart("urdf-collada-parse");
125
+ const d = new L();
126
+ try {
127
+ const p = new dt(o).parse(s, "");
128
+ if (!(p != null && p.scene)) throw new Error(`COLLADA has no scene: ${i}`);
129
+ if (d.add(p.scene), n === "X_UP" ? p.scene.rotateY(-Math.PI / 2) : p.scene.rotateX(Math.PI / 2), o.itemEnd("urdf-collada-parse"), await u, c) throw new Error(`COLLADA texture failed to load: ${c}`);
130
+ let f = 0;
131
+ if (d.traverse((h) => {
132
+ h instanceof z && f++;
133
+ }), !f) throw new Error(`COLLADA has no visual meshes: ${i}`);
134
+ return ht(d), d.updateMatrixWorld(!0), d;
135
+ } catch (p) {
136
+ throw I(d), p;
137
+ }
138
+ }
139
+ function V(i, e) {
140
+ if (!i) return [...e];
141
+ const s = i.trim().split(/\s+/).map(Number);
142
+ if (s.some((t) => !Number.isFinite(t))) throw x(`Invalid numeric value: ${i}`, "E_URDF_PARSE");
143
+ return s;
144
+ }
145
+ function H(i) {
146
+ const e = (i == null ? void 0 : i.querySelector("origin")) ?? null, s = V((e == null ? void 0 : e.getAttribute("quat_xyzw")) ?? null, []);
147
+ if (s.length !== 0 && s.length !== 4) throw x("URDF origin quat_xyzw requires four values.", "E_URDF_PARSE");
148
+ if (s.length && (e != null && e.hasAttribute("rpy"))) throw x("URDF origin cannot declare both rpy and quat_xyzw.", "E_URDF_PARSE");
149
+ return {
150
+ position: V((e == null ? void 0 : e.getAttribute("xyz")) ?? null, [0, 0, 0]),
151
+ rotationRpy: V((e == null ? void 0 : e.getAttribute("rpy")) ?? null, [0, 0, 0]),
152
+ ...s.length ? { rotationQuaternion: s } : {}
153
+ };
154
+ }
155
+ function ke(i, e, s) {
156
+ const t = i.querySelector("geometry"), n = t == null ? void 0 : t.querySelector("box");
157
+ if (n) return { type: "box", size: Et(n.getAttribute("size"), 3, "box size") };
158
+ const a = t == null ? void 0 : t.querySelector("sphere");
159
+ if (a) return { type: "sphere", radius: J(a.getAttribute("radius"), "sphere radius") };
160
+ const o = t == null ? void 0 : t.querySelector("cylinder");
161
+ if (o) return { type: "cylinder", radius: J(o.getAttribute("radius"), "cylinder radius"), length: J(o.getAttribute("length"), "cylinder length") };
162
+ const m = t == null ? void 0 : t.querySelector("capsule");
163
+ if (m) return { type: "capsule", radius: J(m.getAttribute("radius"), "capsule radius"), length: J(m.getAttribute("length"), "capsule length") };
164
+ const u = t == null ? void 0 : t.querySelector("mesh"), c = u == null ? void 0 : u.getAttribute("filename");
165
+ return c ? { type: "mesh", resourcePath: s.resolve(c, e), scale: V(u.getAttribute("scale"), [1, 1, 1]) } : null;
166
+ }
167
+ function gt(i, e, s) {
168
+ const n = $t(i, "URDF").querySelector("robot");
169
+ if (!n) throw x("URDF requires a robot root element.", "E_URDF_PARSE");
170
+ const a = Te(), o = /* @__PURE__ */ new Map();
171
+ for (const c of n.children) if (c.tagName === "material" && c.getAttribute("name")) {
172
+ const d = c.getAttribute("name");
173
+ if (o.has(d)) throw x(`Duplicate URDF material: ${d}`, "E_URDF_MATERIAL");
174
+ o.set(d, c);
175
+ }
176
+ const m = [...n.querySelectorAll("link")].map((c) => ({
177
+ id: D(c, "name"),
178
+ name: D(c, "name"),
179
+ inertial: (() => {
180
+ const d = jt(c);
181
+ return d && (!(d.mass > 0) || !Number.isFinite(d.mass) || !Pe(d.tensor)) && a.errors.push({ code: "E_URDF_INERTIA", message: `连杆 ${c.getAttribute("name")} 的质量或惯性张量无效。`, source: c.getAttribute("name") ?? void 0 }), d;
182
+ })(),
183
+ visuals: [...c.querySelectorAll("visual")].map((d) => {
184
+ const b = ke(d, e, s), l = d.querySelector("material"), r = l == null ? void 0 : l.getAttribute("name"), p = r ? o.get(r) : void 0, f = (l == null ? void 0 : l.querySelector("color")) ?? (p == null ? void 0 : p.querySelector("color")), h = (l == null ? void 0 : l.querySelector("texture")) ?? (p == null ? void 0 : p.querySelector("texture"));
185
+ r && !p && !f && !h && a.warnings.push({ code: "URDF_MATERIAL_UNRESOLVED", message: `Undefined material: ${r}`, source: c.getAttribute("name") ?? void 0 });
186
+ const g = f ? (f.getAttribute("rgba") ?? "").trim().split(/\s+/).map(Number) : h ? [1, 1, 1, 1] : void 0;
187
+ if (g && (g.length !== 4 || g.some((M) => !Number.isFinite(M) || M < 0 || M > 1))) throw x(`Invalid URDF material RGBA: ${r ?? ""}`, "E_URDF_MATERIAL");
188
+ const w = h == null ? void 0 : h.getAttribute("filename");
189
+ if (h && !w) throw x("URDF texture requires a filename", "E_URDF_MATERIAL");
190
+ const y = w ? s.resolve(w, e) : void 0;
191
+ return b ? { origin: H(d), geometry: b, color: g, texturePath: y } : null;
192
+ }).filter((d) => !!d),
193
+ collisions: [...c.querySelectorAll("collision")].map((d) => {
194
+ const b = ke(d, e, s);
195
+ return b ? { origin: H(d), geometry: b } : null;
196
+ }).filter((d) => !!d)
197
+ })), u = [...n.querySelectorAll("joint")].map((c) => {
198
+ var g;
199
+ const d = c.querySelector("limit"), b = c.querySelector("mimic"), l = b ? { joint: D(b, "joint"), multiplier: Y(b.getAttribute("multiplier"), "mimic multiplier") ?? 1, offset: Y(b.getAttribute("offset"), "mimic offset") ?? 0 } : void 0, r = c.querySelector("dynamics"), p = r ? Ue(r.getAttribute("damping"), 0) : 0, f = r ? Ue(r.getAttribute("friction"), 0) : 0, h = r && (p > 0 || f > 0) ? { damping: p, friction: f } : void 0;
200
+ return {
201
+ id: D(c, "name"),
202
+ type: c.getAttribute("type") ?? "fixed",
203
+ parent: D(c.querySelector("parent"), "link"),
204
+ child: D(c.querySelector("child"), "link"),
205
+ origin: H(c),
206
+ axis: V(((g = c.querySelector("axis")) == null ? void 0 : g.getAttribute("xyz")) ?? null, [1, 0, 0]),
207
+ ...d ? {
208
+ limits: { lower: ne(d.getAttribute("lower"), `Joint ${D(c, "name")} limit lower`), upper: ne(d.getAttribute("upper"), `Joint ${D(c, "name")} limit upper`) },
209
+ effort: Y(d.getAttribute("effort"), `Joint ${D(c, "name")} limit effort`),
210
+ velocity: Y(d.getAttribute("velocity"), `Joint ${D(c, "name")} limit velocity`)
211
+ } : {},
212
+ ...h ? { dynamics: h } : {},
213
+ ...l ? { mimic: l } : {}
214
+ };
215
+ });
216
+ return ee(u), n.querySelector("transmission, gazebo") && a.droppedFeatures.push({ code: "UNSUPPORTED_URDF_EXTENSION", message: "URDF transmission/gazebo extensions are not compiled." }), Ge({ id: n.getAttribute("name") || e, name: n.getAttribute("name") || e, source: { format: "urdf", uri: e }, links: m, joints: u, diagnostics: a, extension: { files: s } }, { allowInvalidGraph: !0 });
217
+ }
218
+ function xe(i) {
219
+ const e = K(i);
220
+ return `quat="${e.w} ${e.x} ${e.y} ${e.z}"`;
221
+ }
222
+ function ie(i) {
223
+ const e = new W(), s = K(i);
224
+ return e.compose(new O().fromArray(i.position), s, new O(1, 1, 1));
225
+ }
226
+ function bt(i) {
227
+ if (i.type === "continuous" || !i.limits) return 0;
228
+ const { lower: e, upper: s } = i.limits;
229
+ return !Number.isFinite(e) || !Number.isFinite(s) ? 0 : st.clamp(0, e, s);
230
+ }
231
+ function wt(i) {
232
+ let e;
233
+ if (i.type === "box")
234
+ e = [i.size[0] / 2, i.size[1] / 2, i.size[2] / 2];
235
+ else if (i.type === "sphere")
236
+ e = [i.radius, i.radius, i.radius];
237
+ else if (i.type === "cylinder")
238
+ e = [i.radius, i.radius, i.length / 2];
239
+ else
240
+ return null;
241
+ const s = [];
242
+ for (const t of [-e[0], e[0]])
243
+ for (const n of [-e[1], e[1]])
244
+ for (const a of [-e[2], e[2]])
245
+ s.push(new O(t, n, a));
246
+ return s;
247
+ }
248
+ function Ie(i, e, s) {
249
+ let t = 0;
250
+ const n = new Map(i.links.map((d) => [d.id, d])), a = le(i.joints), o = (d) => {
251
+ let b = 1 / 0;
252
+ const l = (r, p) => {
253
+ const f = n.get(r);
254
+ if (f) {
255
+ for (const h of f.collisions) {
256
+ const g = wt(h.geometry);
257
+ if (!g) {
258
+ d && (t += 1);
259
+ continue;
260
+ }
261
+ const w = p.clone().multiply(ie(h.origin));
262
+ for (const y of g)
263
+ b = Math.min(b, y.applyMatrix4(w).z);
264
+ }
265
+ for (const h of s.get(r) ?? []) {
266
+ const g = p.clone().multiply(ie(h.origin)), w = d ? a[h.id] : 0;
267
+ w && h.type === "revolute" ? g.multiply(new W().makeRotationAxis(new O().fromArray(h.axis).normalize(), w)) : w && h.type === "prismatic" && g.multiply(new W().makeTranslation(h.axis[0] * w, h.axis[1] * w, h.axis[2] * w)), l(h.child, g);
268
+ }
269
+ }
270
+ };
271
+ return l(e, new W()), b;
272
+ }, m = o(!0), u = o(!1), c = Math.min(m, u);
273
+ return t && i.diagnostics.warnings.push({
274
+ code: "GROUNDING_IGNORED_MESH_COLLIDERS",
275
+ message: `自动落地忽略了 ${t} 个网格碰撞体`
276
+ }), Number.isFinite(c) ? Math.max(0, 0.015 - c) : 0;
277
+ }
278
+ async function vt(i) {
279
+ const e = i.extension.files, s = /* @__PURE__ */ new Map(), t = new Set(i.joints.map((g) => g.child));
280
+ for (const g of i.joints) s.set(g.parent, [...s.get(g.parent) ?? [], g]);
281
+ const n = i.links.filter((g) => !t.has(g.id));
282
+ if (n.length !== 1) throw x(`URDF requires exactly one root link; found ${n.length}.`, "E_URDF_COMPILE");
283
+ const a = Ie(i, n[0].id, s);
284
+ a > 0 && i.diagnostics.approximations.push({
285
+ code: "AUTO_GROUNDED_FREE_ROOT",
286
+ message: `自由根初始高度自动抬升 ${a.toFixed(4)} m`
287
+ });
288
+ const o = i.joints.filter((g) => bt(g) !== 0);
289
+ o.length && i.diagnostics.approximations.push({
290
+ code: "JOINT_REFERENCE_CLAMPED",
291
+ message: `${o.length} 个关节的默认参考值已夹到合法限位`
292
+ });
293
+ const m = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), c = [], d = le(i.joints), b = async (g) => {
294
+ var E;
295
+ if (g.type === "box") return `type="box" size="${g.size.map(($) => $ / 2).join(" ")}"`;
296
+ if (g.type === "sphere") return `type="sphere" size="${g.radius}"`;
297
+ if (g.type === "cylinder") return `type="cylinder" size="${g.radius} ${g.length / 2}"`;
298
+ if (g.type === "capsule") return `type="capsule" size="${g.radius} ${g.length / 2}"`;
299
+ const w = (E = g.resourcePath.split(".").pop()) == null ? void 0 : E.toLowerCase();
300
+ if (w !== "stl" && w !== "obj") return null;
301
+ const y = `${g.resourcePath}|${g.scale.join(" ")}`;
302
+ let M = u.get(y);
303
+ if (!M) {
304
+ const $ = { name: `mesh_${u.size}`, path: g.resourcePath, scale: g.scale };
305
+ u.set(y, $);
306
+ const S = await e.bytes(g.resourcePath);
307
+ m.set(`${$.name}.${w}`, S), M = $;
308
+ }
309
+ return `type="mesh" mesh="${M.name}"`;
310
+ }, l = async (g, w) => {
311
+ var S, k;
312
+ const y = i.links.find((F) => F.id === g), M = [...(w == null ? void 0 : w.origin.position) ?? [0, 0, 0]];
313
+ w || (M[2] += a);
314
+ const E = (w == null ? void 0 : w.origin) ?? { rotationRpy: [0, 0, 0] }, $ = [`<body name="${T(g)}" pos="${M.join(" ")}" ${xe(E)}>`];
315
+ if (y.inertial) {
316
+ const { origin: F, mass: A, tensor: U } = y.inertial, C = new Ae().setFromMatrix4(new W().makeRotationFromQuaternion(K(F))), N = new Ae().set(U[0], U[3], U[4], U[3], U[1], U[5], U[4], U[5], U[2]);
317
+ N.premultiply(C).multiply(C.clone().transpose());
318
+ const q = N.elements;
319
+ $.push(`<inertial pos="${F.position.join(" ")}" mass="${A}" fullinertia="${[q[0], q[4], q[8], q[3], q[6], q[7]].join(" ")}"/>`);
320
+ }
321
+ if (!w) $.push("<freejoint/>");
322
+ else if (["fixed", "planar", "floating"].includes(w.type))
323
+ (w == null ? void 0 : w.type) === "floating" && ($.push("<freejoint/>"), c.push(0, 0, 0, 1, 0, 0, 0));
324
+ else {
325
+ const F = w.type === "prismatic" ? "slide" : "hinge", A = w.type !== "continuous" && !!w.limits && Number.isFinite(w.limits.lower) && Number.isFinite(w.limits.upper), U = d[w.id];
326
+ c.push(U);
327
+ const C = ((S = w.dynamics) == null ? void 0 : S.damping) ?? 0, N = ((k = w.dynamics) == null ? void 0 : k.friction) ?? 0;
328
+ $.push(`<joint name="${T(w.id)}" type="${F}" axis="${w.axis.join(" ")}"${A ? ` limited="true" range="${w.limits.lower} ${w.limits.upper}" ref="0"` : ""} damping="${C}" frictionloss="${N}"/>`);
329
+ }
330
+ for (const F of y.collisions) {
331
+ const A = await b(F.geometry);
332
+ if (A) {
333
+ const U = ` ${xe(F.origin)}`;
334
+ $.push(`<geom ${A} pos="${F.origin.position.join(" ")}"${U} rgba="0.55 0.62 0.59 1"/>`);
335
+ }
336
+ }
337
+ for (const F of s.get(g) ?? []) $.push(await l(F.child, F));
338
+ return $.push("</body>"), $.join("");
339
+ }, r = await l(n[0].id), p = [...u.values()].map((g) => {
340
+ var w;
341
+ return `<mesh name="${g.name}" file="${g.name}.${(w = g.path.split(".").pop()) == null ? void 0 : w.toLowerCase()}" scale="${g.scale.join(" ")}"/>`;
342
+ }).join(""), f = `<keyframe><key name="home" qpos="0 0 ${a} 1 0 0 0 ${c.join(" ")}"/></keyframe>`, h = i.joints.filter((g) => g.mimic).map((g) => {
343
+ const w = g.mimic;
344
+ return `<joint name="mimic_${T(g.id)}" joint1="${T(g.id)}" joint2="${T(w.joint)}" polycoef="${w.offset} ${w.multiplier} 0 0 0"/>`;
345
+ }).join("");
346
+ return {
347
+ format: "mjcf",
348
+ files: m,
349
+ xml: `<mujoco model="${T(i.name)}"><compiler angle="radian" autolimits="true"/><option gravity="0 0 -9.81"/><asset>${p}</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"/>${r}</worldbody>${h ? `<equality>${h}</equality>` : ""}${f}</mujoco>`
350
+ };
351
+ }
352
+ async function Ne(i) {
353
+ const e = i.extension.files, s = new L();
354
+ s.name = "URDF authored collisions";
355
+ const t = /* @__PURE__ */ new Map(), n = Be(), a = Qe();
356
+ let o = 0;
357
+ for (const m of i.links) {
358
+ const u = new L();
359
+ u.name = m.id, u.userData.urdfEntityId = `link:${m.id}`, t.set(m.id, u), s.add(u);
360
+ for (const c of m.collisions) {
361
+ const d = new L();
362
+ if (d.matrixAutoUpdate = !1, d.matrix.copy(ie(c.origin)), u.add(d), c.geometry.type === "mesh") {
363
+ const b = await se(c.geometry, e, new oe());
364
+ b.updateMatrixWorld(!0), b.traverse((l) => {
365
+ if (!(l instanceof z)) return;
366
+ const r = we(l.geometry, n, "mesh", a);
367
+ r.matrixAutoUpdate = !1, r.matrix.copy(l.matrixWorld), r.name = `Collision:${m.id}`, r.userData.urdfLink = m.id, d.add(r), o += 1;
368
+ }), I(b);
369
+ } else {
370
+ const b = Rt(c.geometry);
371
+ if (!b) continue;
372
+ const l = we(b, n, "feature", a);
373
+ b.dispose(), l.name = `Collision:${m.id}`, l.userData.urdfLink = m.id, d.add(l), o += 1;
374
+ }
375
+ }
376
+ }
377
+ if (o === 0) {
378
+ n.dispose(), a.dispose(), I(s);
379
+ return;
380
+ }
381
+ return { root: s, bindings: t, expectedLinkCount: t.size };
382
+ }
383
+ async function Mt(i, e) {
384
+ const s = await Ne(i);
385
+ if (!s) return;
386
+ const t = () => {
387
+ e.root.updateMatrixWorld(!0);
388
+ for (const [n, a] of s.bindings) {
389
+ const o = e.bindings.get(n);
390
+ o && (a.matrixAutoUpdate = !1, a.matrix.copy(o.matrixWorld));
391
+ }
392
+ s.root.updateMatrixWorld(!0);
393
+ };
394
+ return t(), s.root.visible = !1, { root: s.root, sync: t, dispose() {
395
+ I(s.root);
396
+ } };
397
+ }
398
+ function Rt(i) {
399
+ if (i.type === "box") return new re(...i.size);
400
+ if (i.type === "sphere") return new ae(i.radius, 24, 16);
401
+ if (i.type === "cylinder") {
402
+ const e = new De(i.radius, i.radius, i.length, 24);
403
+ return e.rotateX(Math.PI / 2), e;
404
+ }
405
+ if (i.type === "capsule") {
406
+ const e = new qe(i.radius, i.length, 8, 24);
407
+ return e.rotateX(Math.PI / 2), e;
408
+ }
409
+ return null;
410
+ }
411
+ async function Fe(i) {
412
+ const e = i.extension.files, s = new L();
413
+ s.name = i.name;
414
+ const t = /* @__PURE__ */ new Map();
415
+ try {
416
+ for (const n of i.links) {
417
+ const a = new L();
418
+ a.name = n.id, a.userData.urdfEntityId = `link:${n.id}`, t.set(n.id, a), s.add(a);
419
+ for (const o of n.visuals) {
420
+ const m = await At(o, e, i.diagnostics), u = new L();
421
+ u.position.fromArray(o.origin.position), u.quaternion.copy(K(o.origin)), u.add(m), a.add(u);
422
+ }
423
+ }
424
+ return { root: s, bindings: t, expectedLinkCount: i.links.length };
425
+ } catch (n) {
426
+ throw I(s), n;
427
+ }
428
+ }
429
+ async function At(i, e, s) {
430
+ var a;
431
+ if (i.geometry.type === "mesh" && /\.gl(?:tf|b)$/i.test(i.geometry.resourcePath)) {
432
+ (i.color || i.texturePath) && s.warnings.push({ code: "URDF_EMBEDDED_MATERIAL_PRESERVED", message: "Embedded glTF materials take precedence over the URDF visual material.", source: i.geometry.resourcePath });
433
+ const o = be();
434
+ try {
435
+ return await se(i.geometry, e, o);
436
+ } finally {
437
+ o.dispose();
438
+ }
439
+ }
440
+ const t = be({ color: i.color });
441
+ let n;
442
+ try {
443
+ if (i.texturePath && (await e.ensure(i.texturePath), t.map = await new et().loadAsync(e.objectUrl(i.texturePath)), t.transparent = !0, t.map.colorSpace = tt, t.map.wrapS = t.map.wrapT = it), n = await se(i.geometry, e, t), i.geometry.type === "mesh" && /\.dae$/i.test(i.geometry.resourcePath))
444
+ if (i.color || i.texturePath) {
445
+ const o = /* @__PURE__ */ new Set(), m = /* @__PURE__ */ new Set();
446
+ n.traverse((u) => {
447
+ if (u instanceof z) {
448
+ for (const c of Array.isArray(u.material) ? u.material : [u.material]) o.add(c);
449
+ u.material = t;
450
+ }
451
+ });
452
+ for (const u of o) {
453
+ for (const c of Object.values(u)) c != null && c.isTexture && m.add(c);
454
+ u.dispose();
455
+ }
456
+ for (const u of m) u.dispose();
457
+ } else t.dispose();
458
+ return t.map && n.traverse((o) => {
459
+ if (o instanceof z && !o.geometry.getAttribute("uv")) throw x(`URDF texture requires authored UVs: ${i.texturePath}`, "E_URDF_TEXTURE_UV");
460
+ }), n;
461
+ } catch (o) {
462
+ throw n ? I(n) : ((a = t.map) == null || a.dispose(), t.dispose()), o;
463
+ }
464
+ }
465
+ async function se(i, e, s) {
466
+ var a;
467
+ if (i.type === "box") return new z(new re(...i.size), s);
468
+ if (i.type === "sphere") return new z(new ae(i.radius, 24, 16), s);
469
+ if (i.type === "cylinder") {
470
+ const o = new z(new De(i.radius, i.radius, i.length, 24), s);
471
+ return o.quaternion.copy(new P().setFromEuler(new X(Math.PI / 2, 0, 0))), o;
472
+ }
473
+ if (i.type === "capsule") {
474
+ const o = new z(new qe(i.radius, i.length, 8, 24), s);
475
+ return o.quaternion.copy(new P().setFromEuler(new X(Math.PI / 2, 0, 0))), o;
476
+ }
477
+ const t = (a = i.resourcePath.split(".").pop()) == null ? void 0 : a.toLowerCase();
478
+ await e.ensure(i.resourcePath);
479
+ let n;
480
+ if (t === "stl") n = new z(new ft().parse(await e.getBlob(i.resourcePath).arrayBuffer()), s);
481
+ else if (t === "obj")
482
+ n = new pt().parse(await e.getBlob(i.resourcePath).text()), n.traverse((o) => {
483
+ if (o instanceof z) {
484
+ for (const m of Array.isArray(o.material) ? o.material : [o.material]) m.dispose();
485
+ o.material = s;
486
+ }
487
+ });
488
+ else if (t === "gltf" || t === "glb") {
489
+ const o = new _e();
490
+ o.setURLModifier((m) => {
491
+ try {
492
+ return e.objectUrl(e.resolve(m, i.resourcePath));
493
+ } catch {
494
+ return m;
495
+ }
496
+ }), n = (await new ut(o).parseAsync(await e.getBlob(i.resourcePath).arrayBuffer(), "")).scene;
497
+ } else if (t === "dae") n = await yt(i.resourcePath, e);
498
+ else throw x(`Unsupported URDF visual mesh: .${t ?? ""}`, "E_URDF_VISUAL");
499
+ return n.scale.fromArray(i.scale), n;
500
+ }
501
+ function $t(i, e) {
502
+ const s = new DOMParser().parseFromString(i, "application/xml"), t = s.querySelector("parsererror");
503
+ if (t) throw x(`${e} XML parse failed: ${t.textContent ?? ""}`, `E_${e}_PARSE`);
504
+ return s;
505
+ }
506
+ function D(i, e) {
507
+ const s = i == null ? void 0 : i.getAttribute(e);
508
+ if (!s) throw x(`Missing ${e}.`, "E_URDF_PARSE");
509
+ return s;
510
+ }
511
+ function Ue(i, e) {
512
+ const s = Number(i);
513
+ return Number.isFinite(s) ? s : e;
514
+ }
515
+ function ne(i, e) {
516
+ if (i === null || i.trim() === "") throw x(`${e} is required.`, "E_URDF_PARSE");
517
+ const s = Number(i);
518
+ if (!Number.isFinite(s)) throw x(`${e} must be finite.`, "E_URDF_PARSE");
519
+ return s;
520
+ }
521
+ function J(i, e) {
522
+ const s = ne(i, e);
523
+ if (!(s > 0)) throw x(`${e} must be greater than zero.`, "E_URDF_PARSE");
524
+ return s;
525
+ }
526
+ function Et(i, e, s) {
527
+ if (i === null || i.trim() === "") throw x(`${s} is required.`, "E_URDF_PARSE");
528
+ const t = V(i, []);
529
+ if (t.length !== e || t.some((n) => !(n > 0))) throw x(`${s} requires ${e} values greater than zero.`, "E_URDF_PARSE");
530
+ return t;
531
+ }
532
+ function Y(i, e) {
533
+ if (i === null || i.trim() === "") return;
534
+ const s = Number(i);
535
+ if (!Number.isFinite(s)) throw x(`${e} must be finite.`, "E_URDF_PARSE");
536
+ return s;
537
+ }
538
+ function T(i) {
539
+ return i.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
540
+ }
541
+ function x(i, e) {
542
+ return Object.assign(new Error(i), { code: e });
543
+ }
544
+ function jt(i) {
545
+ var o;
546
+ const e = i.querySelector("inertial");
547
+ if (!e) return;
548
+ const s = e.querySelector("inertia"), t = (o = e.querySelector("mass")) == null ? void 0 : o.getAttribute("value"), n = t == null || t.trim() === "" ? Number.NaN : Number(t), a = ["ixx", "iyy", "izz", "ixy", "ixz", "iyz"].map((m) => {
549
+ const u = s == null ? void 0 : s.getAttribute(m);
550
+ return u == null || u.trim() === "" ? Number.NaN : Number(u);
551
+ });
552
+ return { origin: H(e), mass: n, tensor: a };
553
+ }
554
+ function te(i) {
555
+ return i.type === "continuous" || !i.limits ? 0 : Math.max(i.limits.lower, Math.min(i.limits.upper, 0));
556
+ }
557
+ class St {
558
+ constructor(e, s) {
559
+ R(this, "root");
560
+ R(this, "visual");
561
+ R(this, "joints", /* @__PURE__ */ new Map());
562
+ R(this, "values", /* @__PURE__ */ new Map());
563
+ R(this, "specs", /* @__PURE__ */ new Map());
564
+ R(this, "pickMeshes", []);
565
+ R(this, "disposed", !1);
566
+ R(this, "initialRoots", /* @__PURE__ */ new Map());
567
+ this.visual = s, this.root = s.root;
568
+ const t = new Set(e.links.map((r) => r.id)), n = e.joints.filter((r) => t.has(r.parent) && t.has(r.child) && r.parent !== r.child), a = new Set(n.map((r) => r.child)), o = e.links.filter((r) => !a.has(r.id)), m = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Set();
569
+ for (const r of n)
570
+ u.has(r.child) || (u.add(r.child), m.set(r.parent, [...m.get(r.parent) ?? [], r]));
571
+ const c = /* @__PURE__ */ new Set(), d = /* @__PURE__ */ new Set(), b = (r) => {
572
+ if (d.has(r)) return;
573
+ d.add(r), c.add(r);
574
+ const p = s.bindings.get(r);
575
+ if (!p) {
576
+ d.delete(r);
577
+ return;
578
+ }
579
+ for (const f of m.get(r) ?? []) {
580
+ if (d.has(f.child) || c.has(f.child)) continue;
581
+ const h = s.bindings.get(f.child);
582
+ if (!h) continue;
583
+ p.add(h);
584
+ const g = {
585
+ joint: f,
586
+ child: h,
587
+ originPosition: new O().fromArray(f.origin.position),
588
+ originQuaternion: K(f.origin),
589
+ axis: new O().fromArray(f.axis).normalize()
590
+ };
591
+ this.joints.set(f.id, g), this.specs.set(f.id, f), this.values.set(f.id, te(f)), this.apply(g, this.values.get(f.id)), b(f.child);
592
+ }
593
+ d.delete(r);
594
+ }, l = o.length ? o : e.links;
595
+ for (const r of l) {
596
+ if (c.has(r.id)) continue;
597
+ const p = s.bindings.get(r.id);
598
+ p && (this.root.add(p), b(r.id));
599
+ }
600
+ for (const r of e.links) {
601
+ if (c.has(r.id)) continue;
602
+ const p = s.bindings.get(r.id);
603
+ p && (this.root.add(p), b(r.id));
604
+ }
605
+ if (o.length === 1) {
606
+ const r = Ie(e, o[0].id, m), p = s.bindings.get(o[0].id);
607
+ p && r > 0 && (p.position.z += r);
608
+ }
609
+ for (const r of s.bindings.values()) r.parent === this.root && this.initialRoots.set(r, { position: r.position.clone(), quaternion: r.quaternion.clone() });
610
+ this.applyAll(), this.preparePicking(), this.root.updateMatrixWorld(!0);
611
+ }
612
+ pickRoots() {
613
+ return this.pickMeshes;
614
+ }
615
+ value(e) {
616
+ return this.values.get(e);
617
+ }
618
+ valuesSnapshot() {
619
+ return Object.freeze(Object.fromEntries(this.values));
620
+ }
621
+ setJointValue(e, s) {
622
+ if (this.disposed) throw B("URDF kinematic binding has been disposed.", "E_URDF_INACTIVE");
623
+ const t = this.joints.get(e);
624
+ if (!t) throw B(`Unknown URDF joint: ${e}`, "E_URDF_JOINT_UNKNOWN");
625
+ if (!Number.isFinite(s)) throw B(`Joint value must be finite: ${e}`, "E_URDF_JOINT_VALUE");
626
+ let n = s;
627
+ if (t.joint.type !== "continuous" && t.joint.limits && (n = Math.max(t.joint.limits.lower, Math.min(t.joint.limits.upper, s))), ["revolute", "continuous", "prismatic"].includes(t.joint.type) || (n = 0), t.joint.mimic) throw B(`Mimic joint is controlled by ${t.joint.mimic.joint}: ${e}`, "E_URDF_MIMIC_READONLY");
628
+ const a = ee([...this.specs.values()]).get(e);
629
+ return a && (n = Math.max(a.lower, Math.min(a.upper, n))), this.values.set(e, n), this.applyAll(), this.root.updateMatrixWorld(!0), n;
630
+ }
631
+ resetJoint(e) {
632
+ const s = this.joints.get(e);
633
+ if (!s) throw B(`Unknown URDF joint: ${e}`, "E_URDF_JOINT_UNKNOWN");
634
+ this.setJointValue(e, te(s.joint));
635
+ }
636
+ syncPhysicsPose(e, s) {
637
+ for (const [t, n] of Object.entries(e)) {
638
+ const a = this.joints.get(t);
639
+ a && Number.isFinite(n) && (this.values.set(t, n), this.apply(a, n));
640
+ }
641
+ for (const t of this.initialRoots.keys()) {
642
+ const n = s.get(t.name);
643
+ n && (t.position.copy(n.position), t.quaternion.copy(n.quaternion));
644
+ }
645
+ this.root.updateMatrixWorld(!0);
646
+ }
647
+ resetPose() {
648
+ for (const [e, s] of this.initialRoots)
649
+ e.position.copy(s.position), e.quaternion.copy(s.quaternion);
650
+ for (const e of this.joints.values()) {
651
+ const s = te(e.joint);
652
+ e.joint.mimic || this.values.set(e.joint.id, s);
653
+ }
654
+ this.applyAll(), this.root.updateMatrixWorld(!0);
655
+ }
656
+ objectForEntity(e) {
657
+ var s;
658
+ return e.startsWith("link:") ? this.visual.bindings.get(e.slice(5)) ?? null : e.startsWith("joint:") ? ((s = this.joints.get(e.slice(6))) == null ? void 0 : s.child) ?? null : e.startsWith("robot:") ? this.root : null;
659
+ }
660
+ jointWorldFrame(e) {
661
+ const s = this.joints.get(e);
662
+ if (!s) return null;
663
+ const t = s.child.parent;
664
+ if (!t) return null;
665
+ t.updateMatrixWorld(!0);
666
+ const n = s.originPosition.clone().applyMatrix4(t.matrixWorld), a = t.getWorldQuaternion(new P()).multiply(s.originQuaternion);
667
+ return { position: n, quaternion: a, axis: s.axis.clone().applyQuaternion(a).normalize() };
668
+ }
669
+ dispose() {
670
+ if (!this.disposed) {
671
+ this.disposed = !0, this.joints.clear(), this.values.clear(), this.specs.clear();
672
+ for (const e of this.pickMeshes) {
673
+ const s = e.geometry;
674
+ delete s.boundsTree;
675
+ }
676
+ this.pickMeshes.length = 0, I(this.root);
677
+ }
678
+ }
679
+ applyAll() {
680
+ const e = le([...this.specs.values()], Object.fromEntries(this.values));
681
+ for (const [s, t] of this.joints)
682
+ this.values.set(s, e[s]), this.apply(t, e[s]);
683
+ }
684
+ preparePicking() {
685
+ const e = /* @__PURE__ */ new Set();
686
+ this.root.traverse((s) => {
687
+ if (!(s instanceof z) || !s.geometry) return;
688
+ const t = s.geometry;
689
+ !t.boundsTree && !e.has(t) && (t.boundsTree = new Xe(t, { maxLeafSize: 20, indirect: !0, verbose: !1 }), e.add(t)), s.raycast = Ke, this.pickMeshes.push(s);
690
+ });
691
+ }
692
+ apply(e, s) {
693
+ e.child.position.copy(e.originPosition), e.child.quaternion.copy(e.originQuaternion), e.joint.type === "revolute" || e.joint.type === "continuous" ? e.child.quaternion.multiply(new P().setFromAxisAngle(e.axis, s)) : e.joint.type === "prismatic" && e.child.position.addScaledVector(e.axis, s);
694
+ }
695
+ }
696
+ function B(i, e) {
697
+ return Object.assign(new Error(i), { code: e });
698
+ }
699
+ function kt(i, e, s = i.source.uri) {
700
+ var w;
701
+ const t = zt(e, s), n = new Set(i.links.map((y) => y.id)), a = i.joints.filter((y) => n.has(y.parent) && n.has(y.child) && y.parent !== y.child), o = /* @__PURE__ */ new Map();
702
+ for (const y of a) o.has(y.child) || o.set(y.child, y);
703
+ const m = i.links.filter((y) => !o.has(y.id)), u = /* @__PURE__ */ new Map();
704
+ for (const y of o.values()) u.set(y.parent, [...u.get(y.parent) ?? [], y]);
705
+ const c = [], d = /* @__PURE__ */ new Set(), b = (y) => {
706
+ if (!d.has(y)) {
707
+ d.add(y);
708
+ for (const M of u.get(y) ?? []) b(M.child);
709
+ }
710
+ };
711
+ for (const y of m)
712
+ c.push(y), b(y.id);
713
+ for (const y of i.links) d.has(y.id) || (c.push(y), b(y.id));
714
+ const l = new Set(c.map((y) => y.id)), r = `robot:${i.name}`, p = /* @__PURE__ */ new Map();
715
+ for (const y of i.joints) p.set(y.parent, [...p.get(y.parent) ?? [], `joint:${y.id}`]);
716
+ const f = [], h = Object.freeze({
717
+ id: r,
718
+ kind: "robot",
719
+ name: i.name,
720
+ childIds: c.map((y) => `link:${y.id}`),
721
+ rootLinkIds: c.map((y) => y.id),
722
+ source: t.robot
723
+ });
724
+ f.push(h);
725
+ for (const y of i.links) f.push(xt(y, i, t.links.get(y.id), p, l, o));
726
+ const g = ee(i.joints);
727
+ for (const y of i.joints) f.push(Ft({ ...y, controlLimits: g.get(y.id) }, t.joints.get(y.id), ((w = o.get(y.child)) == null ? void 0 : w.id) === y.id));
728
+ return Object.freeze({
729
+ robotName: i.name,
730
+ sourcePath: s,
731
+ sourceText: e,
732
+ nodes: Object.freeze(f),
733
+ rootEntityId: r,
734
+ issues: Object.freeze(Ut(i, t))
735
+ });
736
+ }
737
+ function xt(i, e, s, t, n, a) {
738
+ var m, u, c, d;
739
+ const o = a.get(i.id);
740
+ return Object.freeze({
741
+ id: `link:${i.id}`,
742
+ kind: "link",
743
+ name: i.name,
744
+ parentId: o ? `joint:${o.id}` : `robot:${e.name}`,
745
+ childIds: Object.freeze(t.get(i.id) ?? []),
746
+ source: s,
747
+ mass: (m = i.inertial) == null ? void 0 : m.mass,
748
+ centerOfMass: (u = i.inertial) == null ? void 0 : u.origin.position,
749
+ inertiaTensor: (c = i.inertial) == null ? void 0 : c.tensor,
750
+ inertiaMass: (d = i.inertial) == null ? void 0 : d.mass,
751
+ inertialRotationRpy: i.inertial ? Object.freeze([...i.inertial.origin.rotationRpy]) : void 0,
752
+ visualCount: i.visuals.length,
753
+ collisionCount: i.collisions.length
754
+ });
755
+ }
756
+ function Ft(i, e, s) {
757
+ return Object.freeze({
758
+ id: `joint:${i.id}`,
759
+ kind: "joint",
760
+ name: i.id,
761
+ parentId: `link:${i.parent}`,
762
+ childIds: Object.freeze([`link:${i.child}`]),
763
+ source: e,
764
+ jointType: i.type,
765
+ parentLink: i.parent,
766
+ childLink: i.child,
767
+ axis: Object.freeze([...i.axis]),
768
+ originPosition: Object.freeze([...i.origin.position]),
769
+ originRotationRpy: Object.freeze([...i.origin.rotationRpy]),
770
+ limits: i.limits,
771
+ effort: i.effort,
772
+ velocity: i.velocity,
773
+ controlLimits: i.controlLimits,
774
+ movable: ["revolute", "continuous", "prismatic"].includes(i.type),
775
+ ...i.mimic ? { mimic: Object.freeze({ ...i.mimic }) } : {}
776
+ });
777
+ }
778
+ function Ut(i, e) {
779
+ const s = [], t = (l, r, p, f, h, g) => {
780
+ s.push(Object.freeze({ id: `${l}:${f}`, ruleId: l, severity: "error", title: r, message: p, entityId: f, source: h, values: g ? Object.freeze(g) : void 0 }));
781
+ }, n = new Set(i.links.map((l) => l.id));
782
+ for (const l of i.joints)
783
+ n.has(l.parent) || t("joint.parent.missing", "父连杆不存在", `${l.id} 引用了不存在的 parent link ${l.parent}。`, `joint:${l.id}`, e.joints.get(l.id), { parent: l.parent }), n.has(l.child) || t("joint.child.missing", "子连杆不存在", `${l.id} 引用了不存在的 child link ${l.child}。`, `joint:${l.id}`, e.joints.get(l.id), { child: l.child });
784
+ const a = i.links.filter((l) => !i.joints.some((r) => n.has(r.parent) && r.child === l.id));
785
+ a.length !== 1 && t("robot.root.count", "根连杆数量无效", `URDF 必须恰好有一个根连杆,当前为 ${a.length} 个。`, `robot:${i.name}`, e.robot, { roots: a.map((l) => l.id) });
786
+ const o = /* @__PURE__ */ new Map();
787
+ for (const l of i.joints) n.has(l.parent) && n.has(l.child) && o.set(l.parent, [...o.get(l.parent) ?? [], l.child]);
788
+ const m = /* @__PURE__ */ new Set(), u = /* @__PURE__ */ new Set();
789
+ let c = null;
790
+ const d = (l, r) => {
791
+ if (!c) {
792
+ if (u.has(l)) {
793
+ const p = r.indexOf(l);
794
+ c = [...r.slice(Math.max(0, p)), l];
795
+ return;
796
+ }
797
+ if (!m.has(l)) {
798
+ u.add(l);
799
+ for (const p of o.get(l) ?? []) d(p, [...r, l]);
800
+ u.delete(l), m.add(l);
801
+ }
802
+ }
803
+ };
804
+ for (const l of i.links) d(l.id, []);
805
+ c && t("robot.graph.cycle", "运动学结构存在环", `运动学链形成循环:${c.join(" → ")}。`, `robot:${i.name}`, e.robot, { cycle: c });
806
+ const b = /* @__PURE__ */ new Map();
807
+ for (const l of i.joints) {
808
+ if (b.set(l.child, [...b.get(l.child) ?? [], l.id]), l.parent === l.child && t("joint.self-reference", "关节父子连杆相同", `${l.id} 的 parent 和 child 都是 ${l.parent}。`, `joint:${l.id}`, e.joints.get(l.id)), ["revolute", "continuous", "prismatic"].includes(l.type)) {
809
+ const r = l.axis.reduce((p, f) => p + f * f, 0);
810
+ (!Number.isFinite(r) || r <= Number.EPSILON) && t("joint.axis.zero", "关节轴无效", `${l.id} 的 axis 是零向量。`, `joint:${l.id}`, e.joints.get(l.id), { axis: l.axis });
811
+ }
812
+ l.type !== "continuous" && l.limits && l.limits.lower > l.limits.upper && t("joint.limit.order", "关节限位上下界无效", `${l.id} 的 lower ${l.limits.lower} 大于 upper ${l.limits.upper}。`, `joint:${l.id}`, e.joints.get(l.id), { ...l.limits });
813
+ }
814
+ for (const [l, r] of b) r.length > 1 && t("link.multiple-parents", "连杆存在多个父关节", `${l} 同时被 ${r.join("、")} 作为 child。`, `link:${l}`, e.links.get(l), { joints: r });
815
+ for (const l of i.links) {
816
+ const r = l.inertial;
817
+ r && ((!(r.mass > 0) || !Number.isFinite(r.mass)) && t("inertial.mass.invalid", "质量无效", `${l.id} 的质量必须是大于零的有限数。`, `link:${l.id}`, e.links.get(l.id), { mass: r.mass }), Pe(r.tensor) || t("inertial.tensor.invalid", "惯性张量无效", `${l.id} 的惯性张量不是正定的物理惯性张量。`, `link:${l.id}`, e.links.get(l.id), { tensor: r.tensor }));
818
+ }
819
+ return s;
820
+ }
821
+ function zt(i, e) {
822
+ const s = { robot: void 0, links: /* @__PURE__ */ new Map(), joints: /* @__PURE__ */ new Map() };
823
+ s.robot = ze(i, "robot", void 0, e);
824
+ for (const t of ["link", "joint"]) {
825
+ const n = new RegExp(`<${t}\\b[^>]*\\bname\\s*=\\s*(["'])(.*?)\\1[^>]*>`, "gi");
826
+ for (const a of i.matchAll(n)) {
827
+ const o = a[2], m = ze(i, t, o, e, a.index);
828
+ m && s[t === "link" ? "links" : "joints"].set(o, m);
829
+ }
830
+ }
831
+ return s;
832
+ }
833
+ function ze(i, e, s, t, n) {
834
+ const a = n ?? i.search(new RegExp(`<${e}\\b`, "i"));
835
+ if (a < 0) return;
836
+ const o = i.indexOf(">", a);
837
+ if (o < 0) return;
838
+ const u = i.slice(a, o + 1).trimEnd().endsWith("/>") ? o + 1 : i.indexOf(`</${e}>`, o + 1), c = u < 0 ? o + 1 : u + e.length + 3, d = Oe(i, a), b = Oe(i, c);
839
+ return Object.freeze({ file: t, startOffset: a, endOffset: c, startLine: d.line, startColumn: d.column, endLine: b.line, endColumn: b.column });
840
+ }
841
+ function Oe(i, e) {
842
+ const t = i.slice(0, e).split(/\r?\n/);
843
+ return { line: t.length, column: t.at(-1).length + 1 };
844
+ }
845
+ class Ot {
846
+ constructor(e, s, t, n, a) {
847
+ R(this, "kind", "urdf");
848
+ R(this, "overlayRoot", new L());
849
+ R(this, "listeners", /* @__PURE__ */ new Set());
850
+ R(this, "revision", 0);
851
+ R(this, "selectedEntityId");
852
+ R(this, "overlays", Object.freeze({ collision: !1, jointAxis: !1, centerOfMass: !1, inertia: !1 }));
853
+ R(this, "mode");
854
+ R(this, "dynamicsAvailable");
855
+ R(this, "dynamicsMessage");
856
+ R(this, "highlightedMaterials", /* @__PURE__ */ new Map());
857
+ R(this, "selectionMaterials", /* @__PURE__ */ new Map());
858
+ R(this, "guideBindings", []);
859
+ R(this, "guideMatrix", new W());
860
+ R(this, "overlayInverse", new W());
861
+ R(this, "guideSizes", /* @__PURE__ */ new Map());
862
+ R(this, "labelAnchors", /* @__PURE__ */ new Map());
863
+ R(this, "modelSize", 1);
864
+ R(this, "disposed", !1);
865
+ var o, m;
866
+ this.asset = e, this.document = s, this.binding = t, this.options = n, this.selectedEntityId = ((o = s.nodes.find((u) => u.kind === "joint")) == null ? void 0 : o.id) ?? ((m = s.nodes.find((u) => u.kind === "link")) == null ? void 0 : m.id) ?? s.rootEntityId, this.mode = "kinematic", this.dynamicsAvailable = a, this.overlayRoot.name = "URDF review overlays", this.measureGuideSizes(), this.rebuildOverlay();
867
+ }
868
+ getSnapshot() {
869
+ return Object.freeze({
870
+ revision: this.revision,
871
+ kind: "urdf",
872
+ robotName: this.document.robotName,
873
+ sourcePath: this.document.sourcePath,
874
+ sourceText: this.document.sourceText,
875
+ nodes: this.document.nodes,
876
+ rootEntityId: this.document.rootEntityId,
877
+ selectedEntityId: this.selectedEntityId,
878
+ jointValues: this.binding.valuesSnapshot(),
879
+ overlays: this.overlays,
880
+ issues: this.document.issues,
881
+ mode: this.mode,
882
+ dynamicsAvailable: this.dynamicsAvailable,
883
+ ...this.dynamicsMessage ? { dynamicsMessage: this.dynamicsMessage } : {}
884
+ });
885
+ }
886
+ subscribe(e) {
887
+ return this.listeners.add(e), () => this.listeners.delete(e);
888
+ }
889
+ select(e) {
890
+ if (!(this.mode === "dynamics-running" || this.mode === "dynamics-initializing")) {
891
+ if (e !== null && !this.document.nodes.some((s) => s.id === e)) throw Pt(`Unknown URDF entity: ${e}`, "E_URDF_ENTITY_UNKNOWN");
892
+ this.selectedEntityId !== e && (this.selectedEntityId = e, this.rebuildOverlay(), this.publish());
893
+ }
894
+ }
895
+ setJointValue(e, s) {
896
+ this.mode === "dynamics-running" || this.mode === "dynamics-initializing" || (this.options.enterKinematicPreview(), this.binding.setJointValue(e, s), this.mode = "kinematic", this.rebuildGuides(), this.publish());
897
+ }
898
+ resetJoint(e) {
899
+ this.mode === "dynamics-running" || this.mode === "dynamics-initializing" || (this.options.enterKinematicPreview(), this.binding.resetJoint(e), this.mode = "kinematic", this.rebuildOverlay(), this.publish());
900
+ }
901
+ resetPose() {
902
+ this.options.enterKinematicPreview(), this.binding.resetPose(), this.mode = "kinematic", this.rebuildOverlay(), this.publish();
903
+ }
904
+ setOverlay(e, s) {
905
+ this.overlays[e] !== s && (this.overlays = Object.freeze({ ...this.overlays, [e]: s }), e === "collision" && this.options.setCollisionVisible(s), this.rebuildOverlay(), this.publish());
906
+ }
907
+ enterKinematicPreview() {
908
+ this.options.enterKinematicPreview(), this.mode = "kinematic", this.overlayRoot.visible = !0, this.publish();
909
+ }
910
+ setMode(e, s) {
911
+ e === "dynamics-unavailable" ? (this.mode = "kinematic", this.dynamicsAvailable = !1) : this.mode = e, this.overlayRoot.visible = this.mode !== "dynamics-initializing", (e === "dynamics-running" || e === "dynamics-initializing") && (this.selectedEntityId = null), this.dynamicsMessage = s, this.rebuildOverlay(), this.publish();
912
+ }
913
+ jointWorldFrame(e) {
914
+ return this.binding.jointWorldFrame(e);
915
+ }
916
+ pickRoots() {
917
+ var e, s;
918
+ return ((s = (e = this.options).pickRoots) == null ? void 0 : s.call(e)) ?? this.binding.pickRoots();
919
+ }
920
+ selectionObject() {
921
+ return this.selectedEntityId ? this.binding.objectForEntity(this.selectedEntityId) : null;
922
+ }
923
+ dispose() {
924
+ if (!this.disposed) {
925
+ this.disposed = !0, this.listeners.clear(), this.restoreSelectionMaterials();
926
+ for (const e of this.selectionMaterials.values()) e.dispose();
927
+ this.selectionMaterials.clear(), I(this.overlayRoot), this.overlayRoot.removeFromParent();
928
+ }
929
+ }
930
+ publish() {
931
+ if (this.disposed) return;
932
+ this.revision += 1;
933
+ const e = this.getSnapshot();
934
+ for (const s of this.listeners) s(e);
935
+ this.options.requestRender();
936
+ }
937
+ rebuildOverlay() {
938
+ if (this.overlayRoot.visible = this.mode !== "dynamics-initializing", this.restoreSelectionMaterials(), this.clearGuides(), this.buildMassGuides(), this.buildJointGuides(), this.syncGuides(), !this.selectedEntityId) return;
939
+ const e = this.document.nodes.find((t) => t.id === this.selectedEntityId);
940
+ if (!e) return;
941
+ const s = this.binding.objectForEntity(e.id);
942
+ s && e.kind !== "robot" && this.applySelectionMaterials(s);
943
+ }
944
+ rebuildGuides() {
945
+ this.overlayRoot.visible = this.mode !== "dynamics-initializing", this.clearGuides(), this.buildMassGuides(), this.buildJointGuides(), this.syncGuides(), this.selectedEntityId && this.document.nodes.find((e) => e.id === this.selectedEntityId);
946
+ }
947
+ /** Update transforms only: physics ticks must not rebuild geometry or publish UI state. */
948
+ syncGuides() {
949
+ if (!(this.disposed || !this.overlayRoot.visible || !this.guideBindings.length)) {
950
+ this.overlayRoot.updateWorldMatrix(!0, !1), this.overlayInverse.copy(this.overlayRoot.matrixWorld).invert();
951
+ for (const { guide: e, source: s, local: t } of this.guideBindings)
952
+ s.updateWorldMatrix(!0, !1), this.guideMatrix.multiplyMatrices(this.overlayInverse, s.matrixWorld).multiply(t), this.guideMatrix.decompose(e.position, e.quaternion, e.scale), e.updateMatrixWorld(!0);
953
+ }
954
+ }
955
+ linkObject(e) {
956
+ var s, t;
957
+ return ((t = (s = this.options).linkObject) == null ? void 0 : t.call(s, e)) ?? this.binding.objectForEntity(`link:${e}`);
958
+ }
959
+ trackGuide(e, s) {
960
+ s.updateWorldMatrix(!0, !1), this.overlayRoot.updateWorldMatrix(!0, !1), e.updateWorldMatrix(!0, !1);
961
+ const t = s.matrixWorld.clone().invert().multiply(e.matrixWorld);
962
+ this.guideBindings.push({ guide: e, source: s, local: t });
963
+ }
964
+ clearGuides() {
965
+ this.guideBindings.length = 0, I(this.overlayRoot), this.overlayRoot.clear();
966
+ }
967
+ /** Cache own-link bounds once; exclude child links and never traverse meshes per physics tick. */
968
+ measureGuideSizes() {
969
+ const e = new $e();
970
+ for (const t of this.document.nodes) {
971
+ if (t.kind !== "link") continue;
972
+ const n = this.binding.objectForEntity(t.id);
973
+ if (!n) continue;
974
+ n.updateWorldMatrix(!0, !0);
975
+ const a = new $e(), o = (u) => {
976
+ if (!(u !== n && typeof u.userData.urdfEntityId == "string")) {
977
+ u instanceof z && (u.geometry.boundingBox || u.geometry.computeBoundingBox(), u.geometry.boundingBox && a.union(u.geometry.boundingBox.clone().applyMatrix4(u.matrixWorld)));
978
+ for (const c of u.children) o(c);
979
+ }
980
+ };
981
+ if (o(n), a.isEmpty()) continue;
982
+ this.labelAnchors.set(t.name, a.getCenter(new O()).applyMatrix4(n.matrixWorld.clone().invert()));
983
+ const m = a.getSize(new O()).length();
984
+ Number.isFinite(m) && m > 0 && (this.guideSizes.set(t.name, m), e.union(a));
985
+ }
986
+ const s = e.getSize(new O()).length();
987
+ Number.isFinite(s) && s > 0 && (this.modelSize = s);
988
+ }
989
+ linkWorldPosition(e, s) {
990
+ const t = this.linkObject(e);
991
+ return !t || this.disposed || this.mode === "dynamics-initializing" ? !1 : (t.updateWorldMatrix(!0, !1), s.copy(this.labelAnchors.get(e) ?? new O()).applyMatrix4(t.matrixWorld), !0);
992
+ }
993
+ guideSize(e) {
994
+ const s = this.guideSizes.get(e) ?? this.modelSize * 0.1;
995
+ return Math.max(this.modelSize * 3e-3, Math.min(s, this.modelSize * 0.35));
996
+ }
997
+ buildJointGuides() {
998
+ const e = this.document.nodes.find((t) => t.id === this.selectedEntityId), s = (e == null ? void 0 : e.kind) === "joint" ? e : (e == null ? void 0 : e.kind) === "link" ? this.document.nodes.find((t) => t.kind === "joint" && t.childLink === e.name) : void 0;
999
+ for (const t of this.document.nodes) {
1000
+ if (t.kind !== "joint" || !this.overlays.jointAxis && t.id !== (s == null ? void 0 : s.id)) continue;
1001
+ const n = this.linkObject(t.parentLink), a = n ? (() => {
1002
+ n.updateWorldMatrix(!0, !1);
1003
+ const c = n.getWorldQuaternion(new P()).multiply(new P().setFromEuler(new X(...t.originRotationRpy, "ZYX")));
1004
+ return { position: new O().fromArray(t.originPosition).applyMatrix4(n.matrixWorld), quaternion: c, axis: new O().fromArray(t.axis).applyQuaternion(c).normalize() };
1005
+ })() : this.binding.jointWorldFrame(t.name);
1006
+ if (!a) continue;
1007
+ const o = new L();
1008
+ o.name = `Joint guide:${t.name}`;
1009
+ const m = this.guideSize(t.childLink), u = new nt(0.18 * m);
1010
+ if (u.name = `Joint frame:${t.name}`, u.position.copy(a.position), u.quaternion.copy(a.quaternion), o.add(u), ["revolute", "continuous", "prismatic"].includes(t.jointType)) {
1011
+ const c = a.axis.clone().normalize(), d = new Ee(c, a.position, 0.28 * m, 5625523, 0.045 * m, 0.022 * m);
1012
+ if (d.name = `Joint axis:${t.name}`, o.add(d), t.jointType !== "prismatic") {
1013
+ const l = (Math.abs(c.z) < 0.9 ? new O(0, 0, 1) : new O(0, 1, 0)).cross(c).normalize(), r = c.clone().cross(l).normalize(), p = 0.09 * m, f = Math.PI * 1.65, h = a.position.clone().addScaledVector(c, 0.085 * m), g = Array.from({ length: 33 }, (E, $) => {
1014
+ const S = f * $ / 32;
1015
+ return h.clone().addScaledVector(l, p * Math.cos(S)).addScaledVector(r, p * Math.sin(S));
1016
+ }), w = new ot(new rt().setFromPoints(g), new je({ color: 16761963 }));
1017
+ w.name = `Positive rotation:${t.name}`;
1018
+ const y = l.clone().multiplyScalar(-Math.sin(f)).addScaledVector(r, Math.cos(f)), M = new Ee(y, g[32], 0.03 * m, 16761963, 0.03 * m, 0.022 * m);
1019
+ M.name = `Positive rotation arrow:${t.name}`, o.add(w, M);
1020
+ }
1021
+ }
1022
+ o.traverse((c) => {
1023
+ c.renderOrder = 1001;
1024
+ const d = c.material;
1025
+ for (const b of Array.isArray(d) ? d : d ? [d] : [])
1026
+ b.depthTest = !1, b.depthWrite = !1, b.transparent = !0;
1027
+ }), this.overlayRoot.add(o), n && this.trackGuide(o, n);
1028
+ }
1029
+ }
1030
+ buildMassGuides() {
1031
+ if (!this.overlays.centerOfMass && !this.overlays.inertia) return;
1032
+ const e = this.document.nodes.find((t) => t.id === this.selectedEntityId), s = (e == null ? void 0 : e.kind) === "link" ? e.name : (e == null ? void 0 : e.kind) === "joint" ? e.childLink : void 0;
1033
+ for (const t of this.asset.links) {
1034
+ const n = t.inertial, a = this.linkObject(t.id);
1035
+ if (!n || !a) continue;
1036
+ a.updateWorldMatrix(!0, !1);
1037
+ const o = new O().fromArray(n.origin.position).applyMatrix4(a.matrixWorld), m = t.id === s;
1038
+ if (this.overlays.centerOfMass) {
1039
+ const r = 0.025 * this.guideSize(t.id), p = new ae(r, 32, 16), f = p.toNonIndexed();
1040
+ p.dispose();
1041
+ const h = f.getAttribute("position"), g = new Float32Array(h.count * 3);
1042
+ for (let y = 0; y < h.count; y += 3) {
1043
+ let M = 0, E = 0, $ = 0;
1044
+ for (let k = 0; k < 3; k++)
1045
+ M += h.getX(y + k), E += h.getY(y + k), $ += h.getZ(y + k);
1046
+ const S = M * E * $ >= 0 ? 1 : 0.015;
1047
+ for (let k = 0; k < 9; k++) g[y * 3 + k] = S;
1048
+ }
1049
+ f.setAttribute("color", new at(g, 3));
1050
+ const w = new z(f, new Se({ color: m ? 16739210 : 16777215, vertexColors: !0, depthTest: !1, depthWrite: !1 }));
1051
+ mt(w, r), w.frustumCulled = !1, w.quaternion.copy(a.getWorldQuaternion(new P())), w.position.copy(o), w.renderOrder = 1002, w.name = `Center of mass:${t.id}`, this.overlayRoot.add(w), this.trackGuide(w, a);
1052
+ }
1053
+ const u = this.overlays.inertia ? Ze(n.tensor, n.mass) : null;
1054
+ if (!u) continue;
1055
+ const c = new re(1, 1, 1), d = new lt(new ct(c), new je({ color: m ? 16736135 : 2211300, transparent: !0, opacity: m ? 0.98 : 0.82, depthTest: !0, depthWrite: !1 })), b = new z(c, new Se({ color: m ? 16739210 : 3262699, transparent: !0, opacity: m ? 0.28 : 0.16, depthTest: !0, depthWrite: !1 }));
1056
+ b.name = `Inertia fill:${t.id}`;
1057
+ const l = n.origin.rotationQuaternion ? new P().fromArray(n.origin.rotationQuaternion) : new P().setFromEuler(new X(...n.origin.rotationRpy, "ZYX"));
1058
+ d.position.copy(o), d.scale.fromArray(u.size), d.quaternion.copy(a.getWorldQuaternion(new P())).multiply(l).multiply(u.rotation), d.renderOrder = 1001, d.name = `Inertia:${t.id}`, b.position.copy(d.position), b.quaternion.copy(d.quaternion), b.scale.copy(d.scale), b.renderOrder = 1e3, this.overlayRoot.add(b, d), this.trackGuide(b, a), this.trackGuide(d, a);
1059
+ }
1060
+ }
1061
+ applySelectionMaterials(e) {
1062
+ const s = (t, n) => {
1063
+ if (!(!n && typeof t.userData.urdfEntityId == "string")) {
1064
+ t instanceof z && t.material && (this.highlightedMaterials.set(t, t.material), t.material = Array.isArray(t.material) ? t.material.map((a) => this.createSelectionMaterial(a)) : this.createSelectionMaterial(t.material));
1065
+ for (const a of t.children) s(a, !1);
1066
+ }
1067
+ };
1068
+ s(e, !0);
1069
+ }
1070
+ createSelectionMaterial(e) {
1071
+ var a;
1072
+ const s = this.selectionMaterials.get(e);
1073
+ if (s) return s;
1074
+ const t = e.clone(), n = t;
1075
+ return (a = n.color) == null || a.set(9425919), n.emissive ? (n.emissive.set(2793430), n.emissiveIntensity = Math.max(n.emissiveIntensity ?? 0, 0.34)) : t instanceof oe && (t.emissive.set(2793430), t.emissiveIntensity = 0.34), t.transparent = e.transparent, t.opacity = e.opacity, t.depthWrite = e.depthWrite, t.needsUpdate = !0, this.selectionMaterials.set(e, t), t;
1076
+ }
1077
+ restoreSelectionMaterials() {
1078
+ for (const [e, s] of this.highlightedMaterials) e.material = s;
1079
+ this.highlightedMaterials.clear();
1080
+ }
1081
+ }
1082
+ function Pt(i, e) {
1083
+ return Object.assign(new Error(i), { code: e });
1084
+ }
1085
+ async function Vt(i, e, s) {
1086
+ var N, q, ce, ue;
1087
+ const t = i.entryPath ?? i.filename ?? "asset.urdf";
1088
+ (N = e.reportProgress) == null || N.call(e, "fetch", "正在读取模型描述与依赖资源...");
1089
+ let n = await Ve(i, s);
1090
+ const a = e.format === "xacro";
1091
+ if (a) {
1092
+ (q = e.reportProgress) == null || q.call(e, "xacro", "正在展开 Xacro 宏与依赖文件...");
1093
+ const { expandXacro: v } = await import("./xacro-Cl7vUCSC.js");
1094
+ n = await v(n, t, s, e.options.xacro, e.signal);
1095
+ }
1096
+ if (e.signal.aborted) throw Q();
1097
+ (ce = e.reportProgress) == null || ce.call(e, "parse", "正在解析 URDF 结构与连杆...");
1098
+ const o = gt(n, t, s);
1099
+ (ue = e.reportProgress) == null || ue.call(e, "visual", "正在构建运动学预览...");
1100
+ const m = await Fe(o), u = new St(o, m), c = await Mt(o, m), d = o.diagnostics.errors.find((v) => v.code === "E_URDF_INERTIA"), b = o.links.some((v) => v.inertial), l = b && !d, r = new Ye(
1101
+ u.root,
1102
+ e.options.simulationTheme,
1103
+ void 0,
1104
+ "simulation",
1105
+ l ? "physics" : "visual"
1106
+ );
1107
+ r.setCacheInvalidationCallback(e.invalidateTransmissionCaches), c && (c.root.visible = !1, r.attachAuxiliary(c.root));
1108
+ let p = null, f = null, h = null;
1109
+ const g = o.diagnostics.warnings[0], w = g ? ye(g, "visual-material") : null;
1110
+ let y = d ? {
1111
+ code: d.code,
1112
+ message: d.message,
1113
+ stage: "physics-validation",
1114
+ notice: ge(d.code, d.source)
1115
+ } : w, M = d ? { status: "unavailable", issue: y } : b ? { status: "available" } : { status: "not-authored" }, E = !1, $ = null, S = !1, k = !1;
1116
+ const F = () => {
1117
+ var j;
1118
+ const v = E || !u.root.visible;
1119
+ E = !1, r.setRuntime(void 0), f && (f.root.visible = !1), r.replaceModel(u.root, !1), u.root.visible = !0, c && c.sync(), c != null && c.root && (c.root.visible = A.getSnapshot().overlays.collision), h && (h.root.visible = !1), v && ((j = e.reportSessionState) == null || j.call(e)), e.requestRender();
1120
+ }, A = new Ot(o, kt(o, n, a ? `${t} (expanded URDF)` : t), u, {
1121
+ requestRender() {
1122
+ u.root.visible && (c == null || c.sync()), e.requestRender();
1123
+ },
1124
+ setCollisionVisible(v) {
1125
+ c && (c.root.visible = v && u.root.visible), h && (h.root.visible = v && (f == null ? void 0 : f.root.visible) === !0);
1126
+ },
1127
+ enterKinematicPreview: F,
1128
+ linkObject: (v) => f != null && f.root.visible ? f.objectForLink(v) : u.objectForEntity(`link:${v}`),
1129
+ pickRoots: () => E || M.status === "initializing" ? [] : u.pickRoots()
1130
+ }, l);
1131
+ d && A.setMode(
1132
+ "dynamics-unavailable",
1133
+ ge(d.code, d.source).summary
1134
+ ), r.attachAuxiliary(A.overlayRoot);
1135
+ const U = () => !p || !f ? !1 : (r.endGrab(), p.reset(), A.resetPose(), r.resetGround(), p.setJointValues(A.getSnapshot().jointValues), r.replaceModel(f.root, !1), r.setRuntime(p), f.sync(), h == null || h.sync(), u.root.visible = !1, f.root.visible = !0, c && (c.root.visible = !1), h && (h.root.visible = A.getSnapshot().overlays.collision), !0), C = async () => {
1136
+ var de, pe, fe, me;
1137
+ if (p || S || !l) return;
1138
+ A.setMode("dynamics-initializing"), M = { status: "initializing" }, (de = e.reportSessionState) == null || de.call(e);
1139
+ let v = null, j = null, _ = null;
1140
+ try {
1141
+ const G = await vt(o);
1142
+ if (e.signal.aborted || S) throw Q();
1143
+ const Z = await import("./mujoco-runtime-BmuEJ_ST.js");
1144
+ if (v = new Z.MujocoRuntime(), await v.initialize(G, {
1145
+ baseUrl: e.options.mujocoBaseUrl,
1146
+ wasmModule: e.options.mujocoWasmModule
1147
+ }), v.setWorldRotation(ve(r.getUpAxis())), e.signal.aborted || S || (j = new Me(v, await Fe(o)), e.signal.aborted || S)) throw Q();
1148
+ const he = await Ne(o);
1149
+ if (_ = he ? new Me(v, he, { accelerateRaycast: !1 }) : null, e.signal.aborted || S) throw Q();
1150
+ p = v, v = null, f = j, j = null, f.root.visible = !1, h = _, _ = null, h && (h.root.visible = !1, r.attachAuxiliary(h.root)), M = { status: "ready" }, y = w, k ? (U(), E = !0, A.setMode("dynamics-running")) : A.setMode("kinematic"), (pe = e.reportSessionState) == null || pe.call(e), e.requestRender();
1151
+ } catch (G) {
1152
+ if (k = !1, _ == null || _.dispose(), j == null || j.dispose(), v == null || v.dispose(), S || e.signal.aborted || G instanceof Error && G.name === "AbortError") return;
1153
+ const Z = Je(G, e.signal, "urdf-physics");
1154
+ r.setRuntime(void 0), r.setGroundPlacement("visual"), p == null || p.dispose(), p = null, f == null || f.dispose(), f = null, h && (r.detachAuxiliary(h.root), h.dispose(), h = null), F(), y = ye(Z, "physics-fallback"), M = { status: "unavailable", issue: y }, A.setMode("dynamics-unavailable", ((fe = y.notice) == null ? void 0 : fe.summary) ?? y.message), (me = e.reportSessionState) == null || me.call(e), e.reportError(G, { fatal: !1, stage: "physics-start", code: Z.code });
1155
+ }
1156
+ };
1157
+ return {
1158
+ asset: o,
1159
+ stage: r,
1160
+ inspection: A,
1161
+ autoPlay: !1,
1162
+ root: r.root,
1163
+ get capabilities() {
1164
+ const v = M.status === "initializing", j = M.status === "unavailable" || M.status === "not-authored";
1165
+ return { canPlay: !v && !j, canPause: p !== null, canReset: !0, hasPhysics: p !== null, canToggleGround: !0, canToggleCollision: c !== void 0 || h !== null, canReorientUpAxis: !0 };
1166
+ },
1167
+ get physics() {
1168
+ return M;
1169
+ },
1170
+ get warning() {
1171
+ return y;
1172
+ },
1173
+ isPlaying: () => E,
1174
+ play() {
1175
+ var v;
1176
+ if (!(S || E || k || M.status === "unavailable" || M.status === "not-authored")) {
1177
+ if (k = !0, A.select(null), !p) {
1178
+ r.endGrab(), A.resetPose(), r.resetGround(), $ ?? ($ = C().finally(() => {
1179
+ $ = null;
1180
+ }));
1181
+ return;
1182
+ }
1183
+ U() && (E = !0, A.setMode("dynamics-running"), (v = e.reportSessionState) == null || v.call(e));
1184
+ }
1185
+ },
1186
+ pause() {
1187
+ var v;
1188
+ k = !1, E = !1, r.endGrab(), p && (u.syncPhysicsPose(p.getJointValues(o.joints.map((j) => j.id)), _t(f.bodyPoses(), ve(r.getUpAxis()))), F(), A.setMode("dynamics-paused")), (v = e.reportSessionState) == null || v.call(e), e.requestRender();
1189
+ },
1190
+ reset() {
1191
+ var v;
1192
+ k = !1, r.endGrab(), p && (p.reset(), f == null || f.sync(), h == null || h.sync()), A.resetPose(), r.resetGround(), (v = e.reportSessionState) == null || v.call(e), e.requestRender();
1193
+ },
1194
+ step(v) {
1195
+ if (!p || !E) return !1;
1196
+ const j = p.step(v);
1197
+ return j && (f == null || f.sync(), h == null || h.sync(), A.syncGuides(), r.updateForceLine()), j;
1198
+ },
1199
+ beginGrab(v, j, _) {
1200
+ return !!(E && p && r.beginGrab(v, j, _));
1201
+ },
1202
+ moveGrab(v, j, _) {
1203
+ E && p && r.moveGrab(v, j, _);
1204
+ },
1205
+ endGrab() {
1206
+ r.endGrab();
1207
+ },
1208
+ setCollisionVisible(v) {
1209
+ c && (c.root.visible = v && u.root.visible), h && (h.root.visible = v && (f == null ? void 0 : f.root.visible) === !0);
1210
+ },
1211
+ dispose() {
1212
+ S || (S = !0, E = !1, A.dispose(), c && (r.detachAuxiliary(c.root), c.dispose()), h && (r.detachAuxiliary(h.root), h.dispose()), r.setRuntime(void 0), f == null || f.dispose(), u.dispose(), p == null || p.dispose(), r.dispose());
1213
+ }
1214
+ };
1215
+ }
1216
+ function Q() {
1217
+ return Object.assign(new Error("Simulation load aborted."), { name: "AbortError", code: "E_ABORTED" });
1218
+ }
1219
+ function _t(i, e) {
1220
+ const s = e.clone().invert(), t = /* @__PURE__ */ new Map();
1221
+ for (const [n, a] of i)
1222
+ t.set(n, {
1223
+ position: a.position.clone().applyQuaternion(s),
1224
+ quaternion: s.clone().multiply(a.quaternion)
1225
+ });
1226
+ return t;
1227
+ }
1228
+ export {
1229
+ Vt as loadUrdfSimulation
1230
+ };