@nebula-spatial/viewer 0.2.4 → 0.4.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.
@@ -0,0 +1,762 @@
1
+ var Ee = Object.defineProperty;
2
+ var Se = (o, e, t) => e in o ? Ee(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
+ var D = (o, e, t) => Se(o, typeof e != "symbol" ? e + "" : e, t);
4
+ import { d as Ae, S as le } from "./stage-BxROW_dP.js";
5
+ import { ConvexGeometry as ve } from "three/examples/jsm/geometries/ConvexGeometry.js";
6
+ import { LineBasicMaterial as Me, LineSegments as Oe, EdgesGeometry as $e, Group as z, MeshStandardMaterial as he, Mesh as I, PlaneGeometry as Re, BoxGeometry as X, SphereGeometry as ee, CylinderGeometry as te, CapsuleGeometry as ye, Vector3 as T, BufferGeometry as Pe, BufferAttribute as ue, Euler as J, MathUtils as Ue, Matrix3 as ce, Matrix4 as k, Quaternion as be, LoadingManager as Fe } from "three";
7
+ import { GLTFLoader as qe } from "three/examples/jsm/loaders/GLTFLoader.js";
8
+ import { OBJLoader as De } from "three/examples/jsm/loaders/OBJLoader.js";
9
+ import { STLLoader as Ce } from "three/examples/jsm/loaders/STLLoader.js";
10
+ class W {
11
+ constructor(e, t) {
12
+ D(this, "root");
13
+ D(this, "bodies", /* @__PURE__ */ new Map());
14
+ D(this, "disposed", !1);
15
+ this.runtime = e, this.root = t.root;
16
+ const r = e.mujoco, n = e.model;
17
+ for (const [l, u] of t.bindings) {
18
+ const c = r.mj_name2id(n, r.mjtObj.mjOBJ_BODY.value, l);
19
+ if (c < 0) throw fe(`Physics body missing for visual link: ${l}`, "E_SIMULATION_BIND");
20
+ u.userData.bodyId = c, this.bodies.set(c, u);
21
+ }
22
+ if (this.bodies.size !== t.expectedLinkCount) throw fe("Visual body binding count mismatch.", "E_SIMULATION_BIND");
23
+ this.sync();
24
+ }
25
+ sync() {
26
+ if (this.disposed || !this.runtime.data) return;
27
+ const { xpos: e, xquat: t } = this.runtime.data;
28
+ for (const [r, n] of this.bodies) {
29
+ const l = r * 3, u = r * 4;
30
+ n.position.set(e[l], e[l + 1], e[l + 2]), n.quaternion.set(t[u + 1], t[u + 2], t[u + 3], t[u]);
31
+ }
32
+ this.root.updateMatrixWorld(!0);
33
+ }
34
+ dispose() {
35
+ this.disposed || (this.disposed = !0, this.bodies.clear(), Ae(this.root));
36
+ }
37
+ }
38
+ function fe(o, e) {
39
+ return Object.assign(new Error(o), { code: e });
40
+ }
41
+ class Ge {
42
+ constructor(e) {
43
+ D(this, "entries", /* @__PURE__ */ new Map());
44
+ D(this, "objectUrls", /* @__PURE__ */ new Map());
45
+ this.source = e;
46
+ const t = e.original;
47
+ if (Ne(t))
48
+ for (const r of t.files) this.entries.set(A(r.path), r.file);
49
+ else typeof Blob < "u" && t instanceof Blob ? this.entries.set(e.entryPath ?? e.filename ?? "asset", t) : t instanceof ArrayBuffer ? this.entries.set(e.entryPath ?? e.filename ?? "asset", new Blob([t])) : typeof t == "object" && t !== null && "kind" in t && t.kind === "buffer" && this.entries.set(e.entryPath ?? e.filename ?? "asset", new Blob([t.buffer]));
50
+ }
51
+ paths() {
52
+ return [...this.entries.keys()];
53
+ }
54
+ hasLocalFiles() {
55
+ return this.entries.size > 0;
56
+ }
57
+ put(e, t) {
58
+ this.entries.set(A(e), t);
59
+ }
60
+ asSourceRecord(e = "") {
61
+ const t = A(e), r = t ? `${t}/` : "", n = {};
62
+ for (const [l, u] of this.entries)
63
+ (!r || l.startsWith(r)) && (n[r ? l.slice(r.length) : l] = u);
64
+ return n;
65
+ }
66
+ resolve(e, t = "") {
67
+ const r = this.find(e, t);
68
+ if (r) return r;
69
+ const n = A(t).split("/").slice(0, -1).join("/");
70
+ if (this.source.url) return A(`${n}/${e.replace(/^package:\/\//, "")}`);
71
+ throw U(`Simulation resource not found: ${e}`, "E_ASSET_RESOURCE_NOT_FOUND");
72
+ }
73
+ find(e, t = "") {
74
+ const r = A(e.replace(/^package:\/\//, "")), n = A(t).split("/").slice(0, -1).join("/");
75
+ for (const u of [A(`${n}/${e.replace(/^package:\/\//, "")}`), r])
76
+ if (this.entries.has(u)) return u;
77
+ const l = this.paths().filter(
78
+ (u) => u === r || u.endsWith(`/${r}`) || r.endsWith(`/${u}`)
79
+ );
80
+ return l.length === 1 ? l[0] : null;
81
+ }
82
+ async text(e) {
83
+ await this.ensure(e);
84
+ const t = this.entries.get(this.resolve(e));
85
+ if (!t) throw U(`Simulation resource not found: ${e}`, "E_ASSET_RESOURCE_NOT_FOUND");
86
+ return t.text();
87
+ }
88
+ async bytes(e) {
89
+ await this.ensure(e);
90
+ const t = this.entries.get(this.resolve(e));
91
+ if (!t) throw U(`Simulation resource not found: ${e}`, "E_ASSET_RESOURCE_NOT_FOUND");
92
+ return new Uint8Array(await t.arrayBuffer());
93
+ }
94
+ getBlob(e) {
95
+ const t = this.resolve(e), r = this.entries.get(t);
96
+ if (!r) throw U(`Simulation resource not found: ${e}`, "E_ASSET_RESOURCE_NOT_FOUND");
97
+ return r;
98
+ }
99
+ async ensure(e) {
100
+ const t = A(e);
101
+ if (this.entries.has(t)) return;
102
+ const r = await this.source.resolve(t);
103
+ if (!/^https?:\/\//i.test(r) && !/^blob:/i.test(r))
104
+ throw U(`Simulation resource not found: ${e}. Upload the complete asset folder or provide a resourceResolver/baseUrl.`, "E_ASSET_RESOURCE_NOT_FOUND");
105
+ const n = await fetch(r, { signal: this.source.signal });
106
+ if (!n.ok) throw U(`Simulation resource request failed (${n.status}): ${r}`, "E_ASSET_FETCH");
107
+ const l = await n.blob();
108
+ this.source.signal.throwIfAborted(), this.entries.set(t, l);
109
+ }
110
+ objectUrl(e) {
111
+ const t = this.resolve(e);
112
+ let r = this.objectUrls.get(t);
113
+ return r || (r = URL.createObjectURL(this.getBlob(t)), this.objectUrls.set(t, r)), r;
114
+ }
115
+ objectUrlIfPresent(e, t = "") {
116
+ const r = A(t), n = r ? `${r}/` : "", l = A(e), u = n ? this.paths().filter((i) => {
117
+ if (!i.startsWith(n)) return !1;
118
+ const s = i.slice(n.length);
119
+ return s === l || l.endsWith(`/${s}`);
120
+ }) : [], c = u.length === 1 ? u[0] : this.find(e);
121
+ return c ? this.objectUrl(c) : null;
122
+ }
123
+ dispose() {
124
+ for (const e of this.objectUrls.values()) URL.revokeObjectURL(e);
125
+ this.objectUrls.clear(), this.entries.clear();
126
+ }
127
+ }
128
+ async function Le(o, e) {
129
+ if (e.hasLocalFiles()) return e.text(o.entryPath ?? o.filename ?? e.paths()[0]);
130
+ const t = await fetch(o.url ?? await o.resolve(o.entryPath ?? ""), { signal: o.signal });
131
+ if (!t.ok) throw U(`Simulation asset request failed: ${t.status}`, "E_ASSET_FETCH");
132
+ return t.text();
133
+ }
134
+ function A(o) {
135
+ const e = [];
136
+ for (const t of o.replaceAll("\\", "/").split("/"))
137
+ !t || t === "." || (t === ".." && e.length && e.at(-1) !== ".." ? e.pop() : e.push(t));
138
+ return e.join("/");
139
+ }
140
+ function Ne(o) {
141
+ return typeof o == "object" && o !== null && "kind" in o && o.kind === "files";
142
+ }
143
+ function U(o, e) {
144
+ return Object.assign(new Error(o), { code: e });
145
+ }
146
+ function ge() {
147
+ return { errors: [], warnings: [], approximations: [], droppedFeatures: [] };
148
+ }
149
+ function we(o) {
150
+ const e = Object.freeze({ schemaVersion: 1, ...o });
151
+ return Ie(e), e;
152
+ }
153
+ function Ie(o) {
154
+ if (!o.id.trim() || !o.name.trim()) throw x("Asset IR id and name are required.", "E_ASSET_IR_INVALID");
155
+ if (o.source.format !== "usd" && o.links.length === 0) throw x("Asset IR requires at least one link.", "E_ASSET_IR_INVALID");
156
+ const e = /* @__PURE__ */ new Set();
157
+ for (const r of o.links) {
158
+ if (!r.id || e.has(r.id)) throw x(`Invalid or duplicate link: ${r.id}`, "E_ASSET_IR_INVALID");
159
+ e.add(r.id);
160
+ }
161
+ const t = /* @__PURE__ */ new Set();
162
+ for (const r of o.joints) {
163
+ if (!r.id || t.has(r.id) || !e.has(r.parent) || !e.has(r.child))
164
+ throw x(`Invalid joint: ${r.id}`, "E_ASSET_IR_INVALID");
165
+ t.add(r.id);
166
+ }
167
+ }
168
+ function x(o, e) {
169
+ return Object.assign(new Error(o), { code: e });
170
+ }
171
+ async function ze(o, e, t) {
172
+ var i;
173
+ const r = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Set(), u = async (s, m) => {
174
+ if (l.has(s)) throw Q(`MJCF include cycle: ${s}`, "E_MJCF_INCLUDE_CYCLE");
175
+ l.add(s);
176
+ const b = Ve(m, s);
177
+ r.set(s, b);
178
+ for (const h of b.querySelectorAll("worldbody body[name]")) n.add(h.getAttribute("name"));
179
+ for (const h of b.querySelectorAll("include[file]")) {
180
+ const p = t.resolve(h.getAttribute("file"), s);
181
+ await u(p, await t.text(p));
182
+ }
183
+ l.delete(s);
184
+ };
185
+ await u(e, o);
186
+ const c = (i = r.get(e)) == null ? void 0 : i.querySelector("mujoco");
187
+ if (!c || n.size === 0) throw Q("MJCF requires a mujoco root and at least one named body.", "E_MJCF_PARSE");
188
+ return we({
189
+ id: c.getAttribute("model") || e,
190
+ name: c.getAttribute("model") || e,
191
+ source: { format: "mjcf", uri: e },
192
+ links: [...n].map((s) => ({ id: s, name: s, visuals: [], collisions: [] })),
193
+ joints: [],
194
+ diagnostics: ge(),
195
+ extension: { files: t, xml: o, documents: r }
196
+ });
197
+ }
198
+ async function ke(o) {
199
+ const e = o.extension.files, t = o.source.uri, r = t.split("/").slice(0, -1).join("/"), n = /* @__PURE__ */ new Map(), l = o.extension.documents;
200
+ for (const [i, s] of l) {
201
+ const m = s.querySelector("compiler");
202
+ for (const b of s.querySelectorAll("asset [file]")) {
203
+ const h = (m == null ? void 0 : m.getAttribute(b.tagName === "texture" ? "texturedir" : "meshdir")) ?? (m == null ? void 0 : m.getAttribute("assetdir")) ?? "", p = e.resolve(`${h}/${b.getAttribute("file")}`, i);
204
+ await e.bytes(p);
205
+ }
206
+ }
207
+ for (const i of xe(e.paths(), l)) {
208
+ if (i === t) continue;
209
+ const s = r && i.startsWith(`${r}/`) ? i.slice(r.length + 1) : i;
210
+ n.set(s, await e.bytes(i));
211
+ }
212
+ const u = o.extension.xml;
213
+ return { format: "mjcf", xml: Te(l) ? Be(u) : u, files: n };
214
+ }
215
+ function Te(o) {
216
+ return o.size === 0 || ![...o.values()].some((t) => t.querySelector("freejoint, actuator") ? !0 : [...t.querySelectorAll("joint")].some(
217
+ (r) => (r.getAttribute("type") ?? "hinge").toLowerCase() !== "fixed"
218
+ )) ? !1 : ![...o.values()].some(
219
+ (t) => [...t.querySelectorAll("worldbody geom")].some((r) => {
220
+ var n;
221
+ return ((n = r.getAttribute("type")) == null ? void 0 : n.toLowerCase()) === "plane";
222
+ })
223
+ );
224
+ }
225
+ function Be(o) {
226
+ const e = '<geom name="__viewer_default_ground__" type="plane" size="5 5 0.1" contype="1" conaffinity="1" friction="0.8 0.01 0.0002"/>';
227
+ return /<worldbody\b[^>]*>/i.test(o) ? o.replace(/(<worldbody\b[^>]*>)/i, `$1${e}`) : o.replace(/<\/mujoco\s*>/i, `<worldbody>${e}</worldbody></mujoco>`);
228
+ }
229
+ function xe(o, e) {
230
+ const t = (c) => c.replaceAll("\\", "/").split("/").pop() ?? "", r = /* @__PURE__ */ new Map();
231
+ for (const c of o) {
232
+ const i = t(c), s = r.get(i) ?? [];
233
+ s.push(c), r.set(i, s);
234
+ }
235
+ const n = new Set(e.keys()), l = /* @__PURE__ */ new Set(["include", "mesh", "texture", "hfield", "skin"]), u = /* @__PURE__ */ new Set(["fileleft", "fileright", "fileup", "filedown", "filefront", "fileback"]);
236
+ for (const c of e.values()) {
237
+ if (c.querySelector("plugin, extension, model, attach")) return o;
238
+ for (const i of c.querySelectorAll("*"))
239
+ for (const s of i.attributes) {
240
+ if (!s.name.startsWith("file")) continue;
241
+ if (s.name === "file") {
242
+ if (!l.has(i.tagName)) return o;
243
+ } else if (!(i.tagName === "texture" && u.has(s.name)))
244
+ return o;
245
+ if (!s.value) continue;
246
+ const m = r.get(t(s.value));
247
+ if (!m) return o;
248
+ for (const b of m) n.add(b);
249
+ }
250
+ }
251
+ return o.filter((c) => n.has(c));
252
+ }
253
+ function Ve(o, e) {
254
+ const t = new DOMParser().parseFromString(o, "application/xml"), r = t.querySelector("parsererror");
255
+ if (r) throw Q(`MJCF XML parse failed (${e}): ${r.textContent ?? ""}`, "E_MJCF_PARSE");
256
+ return t;
257
+ }
258
+ function Q(o, e) {
259
+ return Object.assign(new Error(o), { code: e });
260
+ }
261
+ const Xe = 1476466, Je = 0.72, He = 20;
262
+ function We() {
263
+ return new Me({
264
+ color: Xe,
265
+ transparent: !0,
266
+ opacity: Je,
267
+ depthTest: !1
268
+ });
269
+ }
270
+ function Ye(o, e) {
271
+ const t = new Oe(
272
+ new $e(o, He),
273
+ e
274
+ );
275
+ return t.renderOrder = 9, t;
276
+ }
277
+ const me = 0.68;
278
+ function Ze(o, e) {
279
+ if (e < 0) return me;
280
+ const t = o.mat_roughness[e];
281
+ if (t >= 0) return t;
282
+ const r = o.mat_shininess[e];
283
+ return !Number.isFinite(r) || r <= 0 ? me : Math.sqrt(2 / (r + 2));
284
+ }
285
+ function Qe(o, e) {
286
+ if (e < 0) return 0;
287
+ const t = o.mat_metallic[e];
288
+ return Number.isFinite(t) && t >= 0 ? t : 0;
289
+ }
290
+ function Y(o, e = !1) {
291
+ const t = o.model, r = o.mujoco, n = new z();
292
+ n.name = "MuJoCo scene";
293
+ const l = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map();
294
+ for (let c = 1; c < t.nbody; c += 1) {
295
+ const i = r.mj_id2name(t, r.mjtObj.mjOBJ_BODY.value, c);
296
+ if (!i) continue;
297
+ const s = new z();
298
+ s.name = i, s.userData.bodyId = c, l.set(c, s), u.set(i, s), n.add(s);
299
+ }
300
+ if (e && l.set(0, n), e) {
301
+ const c = We();
302
+ let i = 0;
303
+ for (let s = 0; s < t.ngeom; s += 1) {
304
+ if (r.mj_id2name(t, r.mjtObj.mjOBJ_GEOM.value, s) === "__viewer_default_ground__" || t.geom_contype[s] === 0 && t.geom_conaffinity[s] === 0) continue;
305
+ const b = l.get(t.geom_bodyid[s]), h = Ke(o, s);
306
+ if (!b || !h) continue;
307
+ const p = Ye(h, c);
308
+ h.dispose(), p.userData.geomId = s, i += 1;
309
+ const f = s * 3, a = s * 4;
310
+ p.position.fromArray(t.geom_pos, f), p.quaternion.set(t.geom_quat[a + 1], t.geom_quat[a + 2], t.geom_quat[a + 3], t.geom_quat[a]), b.add(p);
311
+ }
312
+ i === 0 && c.dispose();
313
+ } else
314
+ for (let c = 0; c < t.ngeom; c += 1) {
315
+ if (t.geom_group[c] > 2) continue;
316
+ const i = l.get(t.geom_bodyid[c]), s = et(o, c);
317
+ if (!i || !s) continue;
318
+ const m = c * 4, b = t.geom_matid[c], h = new he({
319
+ opacity: t.geom_rgba[m + 3],
320
+ transparent: t.geom_rgba[m + 3] < 1,
321
+ roughness: Ze(t, b),
322
+ metalness: Qe(t, b)
323
+ });
324
+ if (h.color.setRGB(t.geom_rgba[m], t.geom_rgba[m + 1], t.geom_rgba[m + 2]), b >= 0 && [0.5, 0.5, 0.5, 1].every((d, _) => t.geom_rgba[m + _] === d)) {
325
+ const d = b * 4;
326
+ h.color.setRGB(t.mat_rgba[d], t.mat_rgba[d + 1], t.mat_rgba[d + 2]), h.opacity = t.mat_rgba[d + 3], h.transparent = h.opacity < 1;
327
+ }
328
+ const p = new I(s, h), f = c * 3, a = c * 4;
329
+ p.position.fromArray(t.geom_pos, f), p.quaternion.set(t.geom_quat[a + 1], t.geom_quat[a + 2], t.geom_quat[a + 3], t.geom_quat[a]), i.add(p);
330
+ }
331
+ return { root: n, bindings: u, expectedLinkCount: u.size };
332
+ }
333
+ function Ke(o, e) {
334
+ const t = o.model, r = o.mujoco, n = e * 3, l = t.geom_size[n], u = t.geom_size[n + 1], c = t.geom_size[n + 2], i = t.geom_type[e];
335
+ if (i === r.mjtGeom.mjGEOM_PLANE.value)
336
+ return new Re(Math.max(l * 2, 2), Math.max(u * 2, 2), 10, 10);
337
+ if (i === r.mjtGeom.mjGEOM_BOX.value) return new X(l * 2, u * 2, c * 2);
338
+ if (i === r.mjtGeom.mjGEOM_SPHERE.value) return new ee(l, 20, 12);
339
+ if (i === r.mjtGeom.mjGEOM_CYLINDER.value) {
340
+ const s = new te(l, l, u * 2, 24);
341
+ return s.rotateX(Math.PI / 2), s;
342
+ }
343
+ if (i === r.mjtGeom.mjGEOM_CAPSULE.value) {
344
+ const s = new ye(l, u * 2, 6, 16);
345
+ return s.rotateX(Math.PI / 2), s;
346
+ }
347
+ if (i === r.mjtGeom.mjGEOM_MESH.value) {
348
+ const s = t.geom_dataid[e], m = t.mesh_vertadr[s], b = t.mesh_vertnum[s];
349
+ t.mesh_faceadr[s], t.mesh_facenum[s];
350
+ const h = [];
351
+ for (let p = m; p < m + b; p++) h.push(new T(t.mesh_vert[p * 3], t.mesh_vert[p * 3 + 1], t.mesh_vert[p * 3 + 2]));
352
+ return new ve(h);
353
+ }
354
+ return new X(Math.max(l * 2, 0.02), Math.max(u * 2, 0.02), Math.max(c * 2, 0.02));
355
+ }
356
+ function et(o, e) {
357
+ const t = o.model, r = o.mujoco, n = e * 3, l = t.geom_size[n], u = t.geom_size[n + 1], c = t.geom_size[n + 2], i = t.geom_type[e];
358
+ if (i === r.mjtGeom.mjGEOM_BOX.value) return new X(l * 2, u * 2, c * 2);
359
+ if (i === r.mjtGeom.mjGEOM_SPHERE.value) return new ee(l, 24, 16);
360
+ if (i === r.mjtGeom.mjGEOM_CYLINDER.value) {
361
+ const a = new te(l, l, u * 2, 24);
362
+ return a.rotateX(Math.PI / 2), a;
363
+ }
364
+ if (i === r.mjtGeom.mjGEOM_CAPSULE.value) {
365
+ const a = new ye(l, u * 2, 6, 16);
366
+ return a.rotateX(Math.PI / 2), a;
367
+ }
368
+ if (i !== r.mjtGeom.mjGEOM_MESH.value) return null;
369
+ const s = t.geom_dataid[e], m = t.mesh_vertadr[s], b = t.mesh_vertnum[s], h = t.mesh_faceadr[s], p = t.mesh_facenum[s], f = new Pe();
370
+ return f.setAttribute("position", new ue(Float32Array.from(t.mesh_vert.subarray(m * 3, (m + b) * 3)), 3)), f.setIndex(new ue(Uint32Array.from(t.mesh_face.subarray(h * 3, (h + p) * 3)), 1)), f.computeVertexNormals(), f;
371
+ }
372
+ function G(o, e) {
373
+ if (!o) return [...e];
374
+ const t = o.trim().split(/\s+/).map(Number);
375
+ if (t.some((r) => !Number.isFinite(r))) throw q(`Invalid numeric value: ${o}`, "E_URDF_PARSE");
376
+ return t;
377
+ }
378
+ function V(o) {
379
+ const e = (o == null ? void 0 : o.querySelector("origin")) ?? null;
380
+ return { position: G((e == null ? void 0 : e.getAttribute("xyz")) ?? null, [0, 0, 0]), rotationRpy: G((e == null ? void 0 : e.getAttribute("rpy")) ?? null, [0, 0, 0]) };
381
+ }
382
+ function de(o, e, t) {
383
+ const r = o.querySelector("geometry"), n = r == null ? void 0 : r.querySelector("box");
384
+ if (n) return { type: "box", size: G(n.getAttribute("size"), [1, 1, 1]) };
385
+ const l = r == null ? void 0 : r.querySelector("sphere");
386
+ if (l) return { type: "sphere", radius: F(l.getAttribute("radius"), 1) };
387
+ const u = r == null ? void 0 : r.querySelector("cylinder");
388
+ if (u) return { type: "cylinder", radius: F(u.getAttribute("radius"), 1), length: F(u.getAttribute("length"), 1) };
389
+ const c = r == null ? void 0 : r.querySelector("mesh"), i = c == null ? void 0 : c.getAttribute("filename");
390
+ return i ? { type: "mesh", resourcePath: t.resolve(i, e), scale: G(c.getAttribute("scale"), [1, 1, 1]) } : null;
391
+ }
392
+ function tt(o, e, t) {
393
+ const n = at(o, "URDF").querySelector("robot");
394
+ if (!n) throw q("URDF requires a robot root element.", "E_URDF_PARSE");
395
+ const l = ge(), u = [...n.querySelectorAll("link")].map((i) => ({
396
+ id: N(i, "name"),
397
+ name: N(i, "name"),
398
+ inertial: lt(i),
399
+ visuals: [...i.querySelectorAll("visual")].map((s) => {
400
+ var h;
401
+ const m = de(s, e, t), b = G(((h = s.querySelector("color")) == null ? void 0 : h.getAttribute("rgba")) ?? null, [0.68, 0.72, 0.7, 1]);
402
+ return m ? { origin: V(s), geometry: m, color: b } : null;
403
+ }).filter((s) => !!s),
404
+ collisions: [...i.querySelectorAll("collision")].map((s) => {
405
+ const m = de(s, e, t);
406
+ return m ? { origin: V(s), geometry: m } : null;
407
+ }).filter((s) => !!s)
408
+ })), c = [...n.querySelectorAll("joint")].map((i) => {
409
+ var f;
410
+ const s = i.querySelector("limit"), m = i.querySelector("dynamics"), b = m ? F(m.getAttribute("damping"), 0) : 0, h = m ? F(m.getAttribute("friction"), 0) : 0, p = m && (b > 0 || h > 0) ? { damping: b, friction: h } : void 0;
411
+ return {
412
+ id: N(i, "name"),
413
+ type: i.getAttribute("type") ?? "fixed",
414
+ parent: N(i.querySelector("parent"), "link"),
415
+ child: N(i.querySelector("child"), "link"),
416
+ origin: V(i),
417
+ axis: G(((f = i.querySelector("axis")) == null ? void 0 : f.getAttribute("xyz")) ?? null, [1, 0, 0]),
418
+ ...s ? { limits: { lower: F(s.getAttribute("lower"), 0), upper: F(s.getAttribute("upper"), 0) } } : {},
419
+ ...p ? { dynamics: p } : {}
420
+ };
421
+ });
422
+ return n.querySelector("transmission, gazebo") && l.droppedFeatures.push({ code: "UNSUPPORTED_URDF_EXTENSION", message: "URDF transmission/gazebo extensions are not compiled." }), we({ id: n.getAttribute("name") || e, name: n.getAttribute("name") || e, source: { format: "urdf", uri: e }, links: u, joints: c, diagnostics: l, extension: { files: t } });
423
+ }
424
+ function pe(o) {
425
+ const e = new k(), t = new be().setFromEuler(new J(...o.rotationRpy, "XYZ"));
426
+ return e.compose(new T().fromArray(o.position), t, new T(1, 1, 1));
427
+ }
428
+ function K(o) {
429
+ if (o.type === "continuous" || !o.limits) return 0;
430
+ const { lower: e, upper: t } = o.limits;
431
+ return !Number.isFinite(e) || !Number.isFinite(t) ? 0 : Ue.clamp(0, e, t);
432
+ }
433
+ function rt(o) {
434
+ let e;
435
+ if (o.type === "box")
436
+ e = [o.size[0] / 2, o.size[1] / 2, o.size[2] / 2];
437
+ else if (o.type === "sphere")
438
+ e = [o.radius, o.radius, o.radius];
439
+ else if (o.type === "cylinder")
440
+ e = [o.radius, o.radius, o.length / 2];
441
+ else
442
+ return null;
443
+ const t = [];
444
+ for (const r of [-e[0], e[0]])
445
+ for (const n of [-e[1], e[1]])
446
+ for (const l of [-e[2], e[2]])
447
+ t.push(new T(r, n, l));
448
+ return t;
449
+ }
450
+ function ot(o, e, t) {
451
+ let r = 0;
452
+ const n = new Map(o.links.map((s) => [s.id, s])), l = (s) => {
453
+ let m = 1 / 0;
454
+ const b = (h, p) => {
455
+ const f = n.get(h);
456
+ if (f) {
457
+ for (const a of f.collisions) {
458
+ const d = rt(a.geometry);
459
+ if (!d) {
460
+ s && (r += 1);
461
+ continue;
462
+ }
463
+ const _ = p.clone().multiply(pe(a.origin));
464
+ for (const y of d)
465
+ m = Math.min(m, y.applyMatrix4(_).z);
466
+ }
467
+ for (const a of t.get(h) ?? []) {
468
+ const d = p.clone().multiply(pe(a.origin)), _ = s ? K(a) : 0;
469
+ _ && a.type === "revolute" ? d.multiply(new k().makeRotationAxis(new T().fromArray(a.axis).normalize(), _)) : _ && a.type === "prismatic" && d.multiply(new k().makeTranslation(a.axis[0] * _, a.axis[1] * _, a.axis[2] * _)), b(a.child, d);
470
+ }
471
+ }
472
+ };
473
+ return b(e, new k()), m;
474
+ }, u = l(!0), c = l(!1), i = Math.min(u, c);
475
+ return r && o.diagnostics.warnings.push({
476
+ code: "GROUNDING_IGNORED_MESH_COLLIDERS",
477
+ message: `自动落地忽略了 ${r} 个网格碰撞体`
478
+ }), Number.isFinite(i) ? Math.max(0, 0.015 - i) : 0;
479
+ }
480
+ async function st(o) {
481
+ const e = o.extension.files, t = /* @__PURE__ */ new Map(), r = new Set(o.joints.map((a) => a.child));
482
+ for (const a of o.joints) t.set(a.parent, [...t.get(a.parent) ?? [], a]);
483
+ const n = o.links.filter((a) => !r.has(a.id));
484
+ if (n.length !== 1) throw q(`URDF requires exactly one root link; found ${n.length}.`, "E_URDF_COMPILE");
485
+ const l = ot(o, n[0].id, t);
486
+ l > 0 && o.diagnostics.approximations.push({
487
+ code: "AUTO_GROUNDED_FREE_ROOT",
488
+ message: `自由根初始高度自动抬升 ${l.toFixed(4)} m`
489
+ });
490
+ const u = o.joints.filter((a) => K(a) !== 0);
491
+ u.length && o.diagnostics.approximations.push({
492
+ code: "JOINT_REFERENCE_CLAMPED",
493
+ message: `${u.length} 个关节的默认参考值已夹到合法限位`
494
+ });
495
+ const c = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), s = [], m = async (a) => {
496
+ var g;
497
+ if (a.type === "box") return `type="box" size="${a.size.map((j) => j / 2).join(" ")}"`;
498
+ if (a.type === "sphere") return `type="sphere" size="${a.radius}"`;
499
+ if (a.type === "cylinder") return `type="cylinder" size="${a.radius} ${a.length / 2}"`;
500
+ const d = (g = a.resourcePath.split(".").pop()) == null ? void 0 : g.toLowerCase();
501
+ if (d !== "stl" && d !== "obj") return null;
502
+ const _ = `${a.resourcePath}|${a.scale.join(" ")}`;
503
+ let y = i.get(_);
504
+ if (!y) {
505
+ const j = { name: `mesh_${i.size}`, path: a.resourcePath, scale: a.scale };
506
+ i.set(_, j), c.set(`${j.name}.${d}`, await e.bytes(a.resourcePath)), y = j;
507
+ }
508
+ return `type="mesh" mesh="${y.name}"`;
509
+ }, b = async (a, d) => {
510
+ var j, $;
511
+ const _ = o.links.find((w) => w.id === a), y = [...(d == null ? void 0 : d.origin.position) ?? [0, 0, 0]];
512
+ d || (y[2] += l);
513
+ const g = [`<body name="${Z(a)}" pos="${y.join(" ")}" euler="${((d == null ? void 0 : d.origin.rotationRpy) ?? [0, 0, 0]).join(" ")}">`];
514
+ if (_.inertial) {
515
+ const { origin: w, mass: v, tensor: S } = _.inertial, R = new ce().setFromMatrix4(new k().makeRotationFromEuler(new J(...w.rotationRpy, "XYZ"))), P = new ce().set(S[0], S[3], S[4], S[3], S[1], S[5], S[4], S[5], S[2]);
516
+ P.premultiply(R).multiply(R.clone().transpose());
517
+ const M = P.elements;
518
+ g.push(`<inertial pos="${w.position.join(" ")}" mass="${v}" fullinertia="${[M[0], M[4], M[8], M[3], M[6], M[7]].join(" ")}"/>`);
519
+ }
520
+ if (!d) g.push("<freejoint/>");
521
+ else if (["fixed", "planar", "floating"].includes(d.type))
522
+ (d == null ? void 0 : d.type) === "floating" && (g.push("<freejoint/>"), s.push(0, 0, 0, 1, 0, 0, 0));
523
+ else {
524
+ const w = d.type === "prismatic" ? "slide" : "hinge", v = d.type !== "continuous" && !!d.limits && Number.isFinite(d.limits.lower) && Number.isFinite(d.limits.upper), S = K(d);
525
+ s.push(S);
526
+ const R = ((j = d.dynamics) == null ? void 0 : j.damping) ?? 0, P = (($ = d.dynamics) == null ? void 0 : $.friction) ?? 0;
527
+ g.push(`<joint name="${Z(d.id)}" type="${w}" axis="${d.axis.join(" ")}"${v ? ` limited="true" range="${d.limits.lower} ${d.limits.upper}" ref="${S}"` : ""} damping="${R}" frictionloss="${P}"/>`);
528
+ }
529
+ for (const w of _.collisions) {
530
+ const v = await m(w.geometry);
531
+ v && g.push(`<geom ${v} pos="${w.origin.position.join(" ")}" euler="${w.origin.rotationRpy.join(" ")}" rgba="0.55 0.62 0.59 1"/>`);
532
+ }
533
+ for (const w of t.get(a) ?? []) g.push(await b(w.child, w));
534
+ return g.push("</body>"), g.join("");
535
+ }, h = await b(n[0].id), p = [...i.values()].map((a) => {
536
+ var d;
537
+ return `<mesh name="${a.name}" file="${a.name}.${(d = a.path.split(".").pop()) == null ? void 0 : d.toLowerCase()}" scale="${a.scale.join(" ")}"/>`;
538
+ }).join(""), f = `<keyframe><key name="home" qpos="0 0 ${l} 1 0 0 0 ${s.join(" ")}"/></keyframe>`;
539
+ return {
540
+ format: "mjcf",
541
+ files: c,
542
+ xml: `<mujoco model="${Z(o.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"/>${h}</worldbody>${f}</mujoco>`
543
+ };
544
+ }
545
+ async function nt(o) {
546
+ const e = o.extension.files, t = new z();
547
+ t.name = o.name;
548
+ const r = /* @__PURE__ */ new Map();
549
+ for (const n of o.links) {
550
+ const l = new z();
551
+ l.name = n.id, r.set(n.id, l), t.add(l);
552
+ for (const u of n.visuals) {
553
+ const c = await it(u, e), i = new z();
554
+ i.position.fromArray(u.origin.position), i.quaternion.setFromEuler(new J(...u.origin.rotationRpy, "XYZ")), i.add(c), l.add(i);
555
+ }
556
+ }
557
+ return { root: t, bindings: r, expectedLinkCount: o.links.length };
558
+ }
559
+ async function it(o, e) {
560
+ var u, c, i;
561
+ const t = new he({ color: o.color ? void 0 : 11385011, opacity: ((u = o.color) == null ? void 0 : u[3]) ?? 1, transparent: (((c = o.color) == null ? void 0 : c[3]) ?? 1) < 1 });
562
+ o.color && t.color.setRGB(o.color[0], o.color[1], o.color[2]);
563
+ const r = o.geometry;
564
+ if (r.type === "box") return new I(new X(...r.size), t);
565
+ if (r.type === "sphere") return new I(new ee(r.radius, 24, 16), t);
566
+ if (r.type === "cylinder") {
567
+ const s = new I(new te(r.radius, r.radius, r.length, 24), t);
568
+ return s.quaternion.copy(new be().setFromEuler(new J(Math.PI / 2, 0, 0))), s;
569
+ }
570
+ const n = (i = r.resourcePath.split(".").pop()) == null ? void 0 : i.toLowerCase();
571
+ await e.ensure(r.resourcePath);
572
+ let l;
573
+ if (n === "stl") l = new I(new Ce().parse(await e.getBlob(r.resourcePath).arrayBuffer()), t);
574
+ else if (n === "obj")
575
+ l = new De().parse(await e.getBlob(r.resourcePath).text()), l.traverse((s) => {
576
+ "material" in s && (s.material = t);
577
+ });
578
+ else if (n === "gltf" || n === "glb") {
579
+ const s = new Fe();
580
+ s.setURLModifier((m) => {
581
+ try {
582
+ return e.objectUrl(e.resolve(m, r.resourcePath));
583
+ } catch {
584
+ return m;
585
+ }
586
+ }), l = (await new qe(s).parseAsync(await e.getBlob(r.resourcePath).arrayBuffer(), "")).scene;
587
+ } else throw q(`Unsupported URDF visual mesh: .${n ?? ""}`, "E_URDF_VISUAL");
588
+ return l.scale.fromArray(r.scale), l;
589
+ }
590
+ function at(o, e) {
591
+ const t = new DOMParser().parseFromString(o, "application/xml"), r = t.querySelector("parsererror");
592
+ if (r) throw q(`${e} XML parse failed: ${r.textContent ?? ""}`, `E_${e}_PARSE`);
593
+ return t;
594
+ }
595
+ function N(o, e) {
596
+ const t = o == null ? void 0 : o.getAttribute(e);
597
+ if (!t) throw q(`Missing ${e}.`, "E_URDF_PARSE");
598
+ return t;
599
+ }
600
+ function F(o, e) {
601
+ const t = Number(o);
602
+ return Number.isFinite(t) ? t : e;
603
+ }
604
+ function Z(o) {
605
+ return o.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
606
+ }
607
+ function q(o, e) {
608
+ return Object.assign(new Error(o), { code: e });
609
+ }
610
+ function lt(o) {
611
+ var l;
612
+ const e = o.querySelector("inertial");
613
+ if (!e) return;
614
+ const t = e.querySelector("inertia"), r = Number((l = e.querySelector("mass")) == null ? void 0 : l.getAttribute("value")), n = ["ixx", "iyy", "izz", "ixy", "ixz", "iyz"].map((u) => Number(t == null ? void 0 : t.getAttribute(u)));
615
+ if (!(r > 0) || n.some((u) => !Number.isFinite(u))) throw q("Invalid URDF inertia.", "E_URDF_PARSE");
616
+ return { origin: V(e), mass: r, tensor: n };
617
+ }
618
+ function ut(o, e) {
619
+ const t = new Ge(o);
620
+ let r = null, n = null, l = null, u = null, c = null, i = !1, s = !0, m = !1, b = null, h, p = null, f = null, a = null;
621
+ const d = () => {
622
+ i = !0, s = !1;
623
+ }, _ = (async () => {
624
+ var y, g, j, $, w, v, S, R, P, M, re, oe;
625
+ try {
626
+ const O = e.format;
627
+ if (O === "usd" || O === "usda" || O === "usdc" || O === "usdz") {
628
+ (y = e.reportProgress) == null || y.call(e, "usd", "正在解析 USD 场景与物理刚体...");
629
+ const E = await (await import("./usd-session-Dcd20Z6G.js")).loadUsdSimulation(o, e, t);
630
+ if (i || e.signal.aborted)
631
+ throw E.dispose(), _e();
632
+ p = E.asset, n = E.binding, l = E.dispose, u = E.hasPhysics ? E.step : null, c = E.reset, s = E.hasPhysics, m = E.hasPhysics, b = E.fallback ? { ...E.fallback, stage: "physics-fallback" } : null, (g = e.reportProgress) == null || g.call(e, "stage", "正在构建三维场景与环境光影..."), f = new le(n.root, e.options.simulationTheme, E.runtime), E.runtime ? (r = E.runtime, a = new W(r, Y(r, !0))) : a = E.collision ?? null, a && (a.root.visible = !1, f.attachAuxiliary(a.root));
633
+ return;
634
+ }
635
+ let L = o.entryPath ?? o.filename;
636
+ if (!L && O === "mjcf") {
637
+ const ne = t.paths().filter((E) => E.toLowerCase().endsWith(".xml"));
638
+ for (const E of ["scene.xml", "model.xml", "main.xml"]) {
639
+ const ie = ne.find((ae) => ae.toLowerCase().endsWith(`/${E}`) || ae.toLowerCase() === E);
640
+ if (ie) {
641
+ L = ie;
642
+ break;
643
+ }
644
+ }
645
+ }
646
+ L ?? (L = O === "urdf" ? "asset.urdf" : "asset.xml"), (j = e.reportProgress) == null || j.call(e, "fetch", "正在读取模型描述与依赖资源...");
647
+ const { MujocoRuntime: je } = await import("./mujoco-runtime-s85kwjo7.js");
648
+ r = new je();
649
+ const se = await Le(o, t);
650
+ C(i, e.signal);
651
+ let B, H;
652
+ O === "urdf" ? (($ = e.reportProgress) == null || $.call(e, "parse", "正在解析 URDF 结构与连杆..."), p = tt(se, L, t), (w = e.reportProgress) == null || w.call(e, "compile", "正在编译物理碰撞体与惯性矩阵..."), B = await st(p), C(i, e.signal), (v = e.reportProgress) == null || v.call(e, "runtime", "正在初始化物理内核..."), await r.initialize(B, e.options.mujocoBaseUrl), m = !0, C(i, e.signal), (S = e.reportProgress) == null || S.call(e, "visual", "正在构建视觉渲染网格..."), H = await nt(p)) : ((R = e.reportProgress) == null || R.call(e, "parse", "正在解析 MJCF 场景与连杆..."), p = await ze(se, L, t), (P = e.reportProgress) == null || P.call(e, "compile", "正在编译物理模型与参数..."), B = await ke(p), C(i, e.signal), (M = e.reportProgress) == null || M.call(e, "runtime", "正在初始化物理内核..."), await r.initialize(B, e.options.mujocoBaseUrl), m = !0, C(i, e.signal), (re = e.reportProgress) == null || re.call(e, "visual", "正在构建视觉渲染网格..."), H = Y(r)), C(i, e.signal), (oe = e.reportProgress) == null || oe.call(e, "stage", "正在构建三维场景与环境光影..."), n = new W(r, H), f = new le(n.root, e.options.simulationTheme, r), a = new W(r, Y(r, !0)), a.root.visible = !1, f.attachAuxiliary(a.root);
653
+ } catch (O) {
654
+ throw f == null || f.dispose(), f = null, n == null || n.dispose(), n = null, r == null || r.dispose(), t.dispose(), O;
655
+ }
656
+ })();
657
+ return _.catch(() => {
658
+ }), {
659
+ id: `simulation-${Math.random().toString(36).slice(2)}`,
660
+ opened: _,
661
+ get root() {
662
+ return (f == null ? void 0 : f.root) ?? null;
663
+ },
664
+ getFitBounds() {
665
+ return (f == null ? void 0 : f.getModelBounds()) ?? null;
666
+ },
667
+ beforeRender(y, g, j) {
668
+ return f == null ? void 0 : f.beforeRender(y, g, j);
669
+ },
670
+ get capabilities() {
671
+ return { canPlay: m, canPause: m, canReset: m, hasPhysics: m, canToggleGround: !0, canToggleCollision: a !== null };
672
+ },
673
+ get warning() {
674
+ return b;
675
+ },
676
+ setTheme(y) {
677
+ f == null || f.setTheme(y);
678
+ },
679
+ setGroundVisible(y) {
680
+ f == null || f.setGroundVisible(y);
681
+ },
682
+ getGroundVisible() {
683
+ return (f == null ? void 0 : f.getGroundVisible()) ?? !0;
684
+ },
685
+ presentation: { preferredViewMode: "3d", interactionMode: "simulation", uiProfile: "simulation", fitPolicy: "fit-on-ready" },
686
+ beginDispose: d,
687
+ setCollisionVisible(y) {
688
+ if (i || !a) throw new Error("This asset has no collision display.");
689
+ a.root.visible = y;
690
+ },
691
+ getPhysicsProperties() {
692
+ if (i || !(r != null && r.model) || !r.mujoco) return null;
693
+ const y = r.model, g = r.mujoco;
694
+ return structuredClone({
695
+ units: { length: "m", mass: "kg", time: "s" },
696
+ timestep: y.opt.timestep,
697
+ gravity: Array.from(y.opt.gravity),
698
+ bodyCount: y.nbody - 1,
699
+ jointCount: y.njnt,
700
+ geomCount: y.ngeom,
701
+ bodies: Array.from({ length: y.nbody - 1 }, (j, $) => {
702
+ const w = $ + 1;
703
+ return { id: w, name: g.mj_id2name(y, g.mjtObj.mjOBJ_BODY.value, w), mass: y.body_mass[w], inertia: Array.from(y.body_inertia.slice(w * 3, w * 3 + 3)) };
704
+ }),
705
+ diagnostics: p == null ? void 0 : p.diagnostics
706
+ });
707
+ },
708
+ get update() {
709
+ return r != null && r.model || u ? (y) => {
710
+ if (i || !s || !n) return !1;
711
+ if (u) {
712
+ const j = u(y);
713
+ return j && (a == null || a.sync()), j;
714
+ }
715
+ const g = r.step(y);
716
+ return g && (n.sync(), a == null || a.sync(), f == null || f.updateForceLine()), g;
717
+ } : void 0;
718
+ },
719
+ play() {
720
+ !i && m && (s = !0);
721
+ },
722
+ pause() {
723
+ s = !1;
724
+ },
725
+ reset() {
726
+ i || !n || (c ? c() : (r == null || r.reset(), n.sync()), a == null || a.sync(), f == null || f.updateForceLine());
727
+ },
728
+ beginGrab(y, g, j) {
729
+ return (f == null ? void 0 : f.beginGrab(y, g, j)) ?? !1;
730
+ },
731
+ moveGrab(y, g, j) {
732
+ f == null || f.moveGrab(y, g, j);
733
+ },
734
+ endGrab() {
735
+ f == null || f.endGrab();
736
+ },
737
+ dispose() {
738
+ return d(), h ?? (h = _.catch(() => {
739
+ }).then(() => {
740
+ f == null || f.dispose(), f = null, a == null || a.root.removeFromParent(), a == null || a.dispose(), a = null, l ? (l(), l = null, n = null) : (n == null || n.dispose(), n = null, r == null || r.dispose()), t.dispose(), p = null, u = null, c = null, m = !1, b = null;
741
+ })), h;
742
+ }
743
+ };
744
+ }
745
+ function C(o, e) {
746
+ if (o || e.aborted) throw _e();
747
+ }
748
+ function _e() {
749
+ return Object.assign(new Error("Simulation load aborted."), { name: "AbortError", code: "E_ABORTED" });
750
+ }
751
+ const bt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
752
+ __proto__: null,
753
+ createSimulationSession: ut
754
+ }, Symbol.toStringTag, { value: "Module" }));
755
+ export {
756
+ W as S,
757
+ Ye as a,
758
+ ge as b,
759
+ We as c,
760
+ we as d,
761
+ bt as s
762
+ };