@nebula-spatial/viewer 0.5.1 → 0.5.3

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,2392 @@
1
+ import { Mesh as te, FrontSide as Mt, DoubleSide as Ot, MeshPhysicalMaterial as ie, DataTexture as Qe, UnsignedByteType as et, RGBAFormat as tt, NoColorSpace as K, Float32BufferAttribute as Tt, SRGBColorSpace as nt, RepeatWrapping as J, Color as mt, Texture as ht, MeshStandardMaterial as qe, TextureLoader as yt, MirroredRepeatWrapping as gt, ClampToEdgeWrapping as _t, Group as Ee, Vector3 as L, Quaternion as ee, Matrix4 as pe, Box3 as Ne, Sphere as Nt, SphereGeometry as $t, BoxGeometry as Lt, SkinnedMesh as Ie, Skeleton as Ct, AnimationMixer as Gt, LoopRepeat as Bt } from "three";
2
+ import { n as Ft, c as kt, a as Me, b as Vt, p as jt, S as rt, d as zt } from "./session-Boljcc3d.js";
3
+ import { ConvexGeometry as Wt } from "three/examples/jsm/geometries/ConvexGeometry.js";
4
+ import { createUSDLoadedModel as Yt, buildUSDScene as Ht } from "@openusd-wasm/three-loader";
5
+ import { e as Xt, f as qt, c as Jt, g as Zt, h as Kt, d as Qt } from "./index-DmGuwbBM.js";
6
+ import { b as wt } from "./stage-C7B1_qJ0.js";
7
+ function en(e) {
8
+ var r, p;
9
+ const t = e.stage;
10
+ if (!t || !((p = (r = e.pxr) == null ? void 0 : r.Sdf) != null && p.Path)) return;
11
+ const n = /* @__PURE__ */ new Map(), s = (d) => {
12
+ if (!d || d === "/") return "default";
13
+ const f = n.get(d);
14
+ if (f !== void 0) return f;
15
+ const a = new e.pxr.Sdf.Path(d), o = t.GetPrimAtPath(a), i = o.GetAttribute("purpose"), l = e.pxr.Usd.TimeCode.Default();
16
+ let h;
17
+ try {
18
+ i.IsValid() && i.HasAuthoredValue() && (h = String(i.Get(l)));
19
+ } finally {
20
+ l.delete(), i.delete(), o.delete(), a.delete();
21
+ }
22
+ const y = h ?? s(d.slice(0, d.lastIndexOf("/")));
23
+ return n.set(d, y), y;
24
+ };
25
+ e.scene.traverse((d) => {
26
+ var i, l;
27
+ if (!(d instanceof te)) return;
28
+ let f = d, a;
29
+ for (; f && !a; )
30
+ a = (i = f.userData.usd) == null ? void 0 : i.path, f = f.parent;
31
+ if (!a) return;
32
+ const o = s(a) === "guide";
33
+ d.userData.usdPurposeExcluded = o, o ? ((l = d.userData).usdPurposeLayerMask ?? (l.usdPurposeLayerMask = d.layers.mask), d.layers.disableAll()) : d.userData.usdPurposeLayerMask !== void 0 && (d.layers.mask = d.userData.usdPurposeLayerMask, delete d.userData.usdPurposeLayerMask);
34
+ });
35
+ }
36
+ function Je(e, t) {
37
+ return /^https?:$/.test(t.protocol) && e.origin === t.origin && !e.username && !e.password && e.pathname.startsWith(new URL(".", t).pathname);
38
+ }
39
+ function St(e, t, n) {
40
+ const s = [];
41
+ try {
42
+ for (const r of e) for (const p of r.shaders) for (const d of Object.values(p.inputs)) {
43
+ if (!d || typeof d != "object" || Array.isArray(d)) continue;
44
+ const f = d, a = [f.path, f.url, f.resolvedPath].find((i) => typeof i == "string" && i);
45
+ if (!a || /^(?:data|blob):/i.test(a) || /\.mdl(?:[?#].*)?$/i.test(a) || t(a)) continue;
46
+ const o = {};
47
+ for (const i of ["path", "resolvedPath", "url"])
48
+ i in f && (o[i] = f[i], delete f[i]);
49
+ s.push({ asset: f, values: o });
50
+ }
51
+ return n();
52
+ } finally {
53
+ for (const { asset: r, values: p } of s) Object.assign(r, p);
54
+ }
55
+ }
56
+ const tn = 67324752, nn = 33639248, rn = 101010256, Be = 4294967295, sn = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "webp"]);
57
+ function on(e) {
58
+ return e.length > 3 && e[0] === 80 && e[1] === 75;
59
+ }
60
+ async function an(e, t = {}) {
61
+ const n = new DataView(e.buffer, e.byteOffset, e.byteLength), s = fn(n);
62
+ if (s < 0) throw new Error("Not a zip package: end of central directory not found.");
63
+ const r = n.getUint16(s + 10, !0);
64
+ let p = n.getUint32(s + 16, !0);
65
+ if (r === 65535 || p === Be) throw new Error("ZIP64 usdz packages are not supported.");
66
+ const d = /* @__PURE__ */ new Map(), f = [];
67
+ for (let a = 0; a < r; a += 1) {
68
+ if (p + 46 > n.byteLength || n.getUint32(p, !0) !== nn)
69
+ throw new Error(`Corrupt zip central directory at entry ${a}.`);
70
+ const o = n.getUint16(p + 10, !0), i = n.getUint32(p + 20, !0), l = n.getUint16(p + 28, !0), h = n.getUint16(p + 30, !0), y = n.getUint16(p + 32, !0), c = n.getUint32(p + 42, !0);
71
+ if (i === Be || c === Be)
72
+ throw new Error("ZIP64 usdz packages are not supported.");
73
+ const u = new TextDecoder().decode(e.subarray(p + 46, p + 46 + l));
74
+ p += 46 + l + h + y, !u.endsWith("/") && (t.include && !t.include(u) || f.push(un(e, n, c, i, o).then((S) => ({ name: u, data: S }))));
75
+ }
76
+ for (const { name: a, data: o } of await Promise.all(f)) d.set(a, o);
77
+ return d;
78
+ }
79
+ function cn(e) {
80
+ if (typeof URL > "u" || typeof URL.createObjectURL != "function") return null;
81
+ const t = new Map([...e].filter(([d]) => sn.has(Ut(d))));
82
+ if (t.size === 0) return null;
83
+ const n = /* @__PURE__ */ new Map();
84
+ for (const d of t.keys()) {
85
+ const f = d.split("/").pop() ?? d;
86
+ n.set(f, n.has(f) ? null : d);
87
+ }
88
+ const s = /* @__PURE__ */ new Map(), r = (d) => {
89
+ let f = s.get(d);
90
+ if (!f) {
91
+ const a = t.get(d);
92
+ f = URL.createObjectURL(new Blob([new Uint8Array(a)], { type: dn(d) })), s.set(d, f);
93
+ }
94
+ return f;
95
+ }, p = (d) => {
96
+ if (!d) return null;
97
+ const f = pn(ln(d));
98
+ if (!f) return null;
99
+ if (t.has(f)) return r(f);
100
+ const a = [...t.keys()].filter((l) => l.endsWith(`/${f}`));
101
+ if (a.length === 1) return r(a[0]);
102
+ const o = [...t.keys()].filter((l) => f.endsWith(`/${l}`));
103
+ if (o.length === 1) return r(o[0]);
104
+ const i = n.get(f.split("/").pop() ?? "");
105
+ return i ? r(i) : null;
106
+ };
107
+ return {
108
+ resolve: (d) => p(d.resolvedPath) ?? p(d.path) ?? p(d.url) ?? null,
109
+ dispose: () => {
110
+ for (const d of s.values()) URL.revokeObjectURL(d);
111
+ s.clear();
112
+ }
113
+ };
114
+ }
115
+ async function un(e, t, n, s, r) {
116
+ if (t.getUint32(n, !0) !== tn) throw new Error("Corrupt zip local file header.");
117
+ const p = t.getUint16(n + 26, !0), d = t.getUint16(n + 28, !0), f = n + 30 + p + d, a = e.subarray(f, f + s);
118
+ if (r === 0) return a.slice();
119
+ if (r !== 8) throw new Error(`Unsupported zip compression method ${r}.`);
120
+ const o = new Blob([new Uint8Array(a)]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
121
+ return new Uint8Array(await new Response(o).arrayBuffer());
122
+ }
123
+ function ln(e) {
124
+ const t = e.indexOf("[");
125
+ return t >= 0 && e.endsWith("]") ? e.slice(t + 1, -1) : e;
126
+ }
127
+ function pn(e) {
128
+ const t = [];
129
+ for (const n of e.replaceAll("\\", "/").split("/"))
130
+ !n || n === "." || (n === ".." ? t.pop() : t.push(n));
131
+ return t.join("/");
132
+ }
133
+ function Ut(e) {
134
+ const t = e.split(/[?#]/)[0] ?? e, n = t.lastIndexOf(".");
135
+ return n < 0 ? "" : t.slice(n + 1).toLowerCase();
136
+ }
137
+ function dn(e) {
138
+ switch (Ut(e)) {
139
+ case "png":
140
+ return "image/png";
141
+ case "jpg":
142
+ case "jpeg":
143
+ return "image/jpeg";
144
+ case "webp":
145
+ return "image/webp";
146
+ default:
147
+ return "application/octet-stream";
148
+ }
149
+ }
150
+ function fn(e) {
151
+ const t = Math.max(0, e.byteLength - 65535 - 22);
152
+ for (let n = e.byteLength - 22; n >= t; n -= 1)
153
+ if (e.getUint32(n, !0) === rn) return n;
154
+ return -1;
155
+ }
156
+ const mn = /* @__PURE__ */ new Set(["usd", "usda", "usdc", "usdz"]);
157
+ async function hn(e) {
158
+ const t = await import(
159
+ /* @vite-ignore */
160
+ e.moduleUrl
161
+ ), n = t.default ?? t.createOpenUsdProbe, s = await (typeof e.wasmBinary == "function" ? e.wasmBinary() : e.wasmBinary ?? Un(e.wasmUrl)), r = await n({ wasmBinary: s }), p = e.memfsRoot ?? "/asset", d = e.fetchBytes ?? (async (h) => {
162
+ const y = await fetch(h);
163
+ if (!y.ok) throw Object.assign(new Error(`USD resource request failed (${y.status}): ${h}`), {
164
+ code: y.status === 401 || y.status === 403 ? "E_ASSET_AUTH" : "E_ASSET_FETCH"
165
+ });
166
+ const c = new Uint8Array(await y.arrayBuffer()), u = Xt(y.headers.get("content-type"), c);
167
+ if (u) throw qt(`USD resource is not usable (${u}): ${h}`, Jt);
168
+ return c;
169
+ }), f = (h, y, c) => JSON.parse(r.ccall(h, "string", y, c)), a = /* @__PURE__ */ new Set(), o = st(r);
170
+ let i = 0;
171
+ async function l(h, y) {
172
+ const c = new URL(y.sourcePath, "file:///"), u = `${p}/load-${++i}`, S = ve(c.href, u), g = /* @__PURE__ */ new Set(), m = /* @__PURE__ */ new Map();
173
+ let _, U = null;
174
+ const x = () => {
175
+ _ !== void 0 && a.delete(_) && f("usd_probe_stage_release", ["number"], [_]), U == null || U.dispose(), bt(r.FS, u);
176
+ };
177
+ try {
178
+ const A = await at(h);
179
+ ze(r, S, A, g);
180
+ for (const [O, B] of Object.entries(y.files ?? {}))
181
+ ze(r, ve(new URL(O, c).href, u), await at(B), g);
182
+ const D = new Set(g), E = y.externalReferenceMode ?? "complete", I = on(A) ? await an(A, { include: yn }) : null;
183
+ let w = {};
184
+ if (!I && y.autoResolveAssets !== !1) {
185
+ const O = y.resolveBytes ?? ((B) => d(B));
186
+ w = await wn(
187
+ r,
188
+ c,
189
+ u,
190
+ O,
191
+ f,
192
+ g,
193
+ m,
194
+ y.maxFiles ?? 1024,
195
+ y.maxDepth ?? 8,
196
+ E,
197
+ D,
198
+ y.onReferenceSkipped,
199
+ y.onResourceFailed
200
+ );
201
+ }
202
+ U = I ? cn(I) : null;
203
+ const v = y.textureResolver || U ? (O) => {
204
+ var B;
205
+ return ((B = y.textureResolver) == null ? void 0 : B.call(y, O)) ?? (U == null ? void 0 : U.resolve(O)) ?? null;
206
+ } : void 0, M = Object.keys(w).length > 0;
207
+ if (M && typeof r._usd_probe_stage_open_mapped != "function")
208
+ throw Object.assign(new Error("USD dependency mapping requires the matching packaged openusd_probe.js and .wasm runtime."), { code: "E_USD_RUNTIME_VERSION" });
209
+ const $ = M ? f("usd_probe_stage_open_mapped", ["string", "string"], [S, JSON.stringify(w)]) : f("usd_probe_stage_open", ["string"], [S]);
210
+ if (!$.ok) throw new Error($.error ?? `Failed to open ${S}`);
211
+ _ = $.stageId, a.add($.stageId);
212
+ const z = st(r, m), Y = z.openStage($.stageId), H = gn(r, $.stageId, S);
213
+ je(H.materials, m), je(H.lights, m);
214
+ const b = I ? void 0 : y.isTextureAllowed ?? (E === "package" ? (O) => {
215
+ const B = new URL(O, c);
216
+ return D.has(ve(B.href, u)) || Je(B, c);
217
+ } : void 0), T = () => Yt(
218
+ H,
219
+ z,
220
+ S,
221
+ {
222
+ sourcePath: y.sourcePath,
223
+ // `convertZUp` and `loadLights` are opt-in here: the viewer normalises USD
224
+ // to world Z-up itself and draws its own studio lighting. `loadTextures`
225
+ // keeps the reference builder's opt-out default, so omitting it loads
226
+ // textures instead of silently rendering untextured materials.
227
+ convertZUp: y.convertZUp ?? !1,
228
+ loadLights: y.loadLights ?? !1,
229
+ loadTextures: y.loadTextures ?? !0,
230
+ ...y.textureLoader ? { textureLoader: y.textureLoader } : {},
231
+ ...v ? { textureResolver: v } : {}
232
+ },
233
+ Y
234
+ ), R = b ? St(H.materials, b, T) : T(), X = R.dispose.bind(R);
235
+ let P = !1;
236
+ return R.dispose = () => {
237
+ P || (P = !0, X(), x());
238
+ }, R;
239
+ } catch (A) {
240
+ throw x(), A;
241
+ }
242
+ }
243
+ return { runtime: r, pxr: o, parseAsync: l };
244
+ }
245
+ function yn(e) {
246
+ return /\.(?:png|jpe?g|webp)$/i.test(e.split(/[?#]/, 1)[0] ?? e);
247
+ }
248
+ function st(e, t = /* @__PURE__ */ new Map()) {
249
+ const n = (a, o, i) => JSON.parse(e.ccall(a, "string", o, i));
250
+ class s {
251
+ constructor(o) {
252
+ this.path = o;
253
+ }
254
+ delete() {
255
+ }
256
+ }
257
+ const r = (a, o, i) => {
258
+ const l = n("usd_probe_attribute_value", ["number", "string", "string"], [a, o, i]), h = l.valid === !0;
259
+ return {
260
+ IsValid: () => h,
261
+ Get: () => h ? typeof l.value == "string" ? t.get(l.value) ?? l.value : l.value : null,
262
+ HasAuthoredValue: () => l.authored === !0,
263
+ GetName: () => i,
264
+ GetMetadata: (y) => {
265
+ const c = n("usd_probe_attribute_metadata", ["number", "string", "string", "string"], [a, o, i, y]);
266
+ return c.valid === !0 && c.found === !0 ? c.value ?? null : null;
267
+ },
268
+ // The viewer accepts either plain strings or objects with GetString().
269
+ GetConnections: () => n("usd_probe_attribute_connections", ["number", "string", "string"], [a, o, i]).paths ?? [],
270
+ delete: () => {
271
+ }
272
+ };
273
+ }, p = (a, o) => ({
274
+ __path: o,
275
+ __stageId: a,
276
+ IsValid: () => n("usd_probe_prim_info", ["number", "string"], [a, o]).valid === !0,
277
+ GetName: () => String(o.split("/").pop() ?? ""),
278
+ GetPath: () => new s(o),
279
+ GetTypeName: () => String(n("usd_probe_prim_info", ["number", "string"], [a, o]).typeName ?? ""),
280
+ IsInstance: () => n("usd_probe_prim_info", ["number", "string"], [a, o]).instance === !0,
281
+ GetAttribute: (i) => r(a, o, i),
282
+ GetAttributes: () => (n("usd_probe_prim_attributes", ["number", "string"], [a, o]).names ?? []).map((i) => r(a, o, i)),
283
+ GetChildren: () => (n("usd_probe_prim_children", ["number", "string"], [a, o]).paths ?? []).map((i) => p(a, i)),
284
+ GetMetadata: (i) => {
285
+ const l = n("usd_probe_prim_metadata", ["number", "string", "string"], [a, o, i]);
286
+ return l.valid !== !0 ? null : typeof l.text == "string" ? l.text : l.found === !0 ? l.value : null;
287
+ },
288
+ delete: () => {
289
+ }
290
+ }), d = (a) => ({
291
+ GetPrimAtPath: (o) => p(a, typeof o == "string" ? o : o.path),
292
+ GetPseudoRoot: () => Object.assign(p(a, "/"), {
293
+ // Stage-level metadata (metersPerUnit, upAxis, defaultPrim) is authored on
294
+ // the layer, not composed onto the pseudo-root prim.
295
+ GetMetadata: (o) => {
296
+ const i = n("usd_probe_stage_metadata", ["number", "string"], [a, o]);
297
+ return i.found === !0 ? i.value : null;
298
+ },
299
+ GetName: () => "",
300
+ IsValid: () => !0
301
+ }),
302
+ delete: () => {
303
+ }
304
+ }), { FS: f } = e;
305
+ return {
306
+ FS: {
307
+ createDir: (a) => f.mkdirTree(a),
308
+ writeFile: (a, o) => f.writeFile(a, o),
309
+ exists: (a) => f.analyzePath(a, !0).exists,
310
+ listDir: (a) => f.readdir(a).filter((o) => o !== "." && o !== "..").map((o) => {
311
+ const i = `${a.replace(/\/+$/, "")}/${o}`;
312
+ return { path: i, name: o, isDir: f.isDir(f.stat(i).mode) };
313
+ }),
314
+ deleteFile: (a) => f.unlink(a),
315
+ deleteDir: (a) => f.rmdir(a)
316
+ },
317
+ Sdf: { Path: s },
318
+ Usd: { TimeCode: { Default: () => ({ delete: () => {
319
+ } }) } },
320
+ UsdShade: {
321
+ ComputeBoundMaterialPath: (a) => {
322
+ const o = n("usd_probe_bound_material", ["number", "string"], [a.__stageId, a.__path]);
323
+ return o.found !== !0 ? null : {
324
+ materialPath: String(o.materialPath ?? ""),
325
+ resolvedTargetPath: String(o.resolvedTargetPath ?? ""),
326
+ bindingRelationshipPath: String(o.bindingRelationshipPath ?? "")
327
+ };
328
+ }
329
+ },
330
+ UsdUtils: {
331
+ ExtractSanitizedExternalReferences: (a) => n("usd_probe_external_references", ["string"], [a]).paths ?? []
332
+ },
333
+ openStage: d
334
+ };
335
+ }
336
+ function gn(e, t, n) {
337
+ const s = JSON.parse(e.ccall("usd_probe_scene_data", "string", ["number", "string"], [t, n]));
338
+ if (s.error) throw new Error(s.error);
339
+ const r = s;
340
+ for (const p of r.elements)
341
+ p.geometry = Object.fromEntries(
342
+ Object.entries(p.geometry).map(([d, f]) => [d, _n(e, f)])
343
+ );
344
+ return r;
345
+ }
346
+ function _n(e, t) {
347
+ if (!t || typeof t != "object") return t ?? null;
348
+ const { ptr: n, length: s, kind: r } = t;
349
+ return typeof n != "number" ? t : s ? (r === "i32" ? new Int32Array(e.HEAP32.buffer, n, s) : new Float32Array(e.HEAPF32.buffer, n, s)).slice() : r === "i32" ? new Int32Array() : new Float32Array();
350
+ }
351
+ async function wn(e, t, n, s, r, p, d, f, a, o, i, l, h) {
352
+ const y = {}, c = [
353
+ { url: t, depth: 0, recurse: !0, absolute: !1 }
354
+ ], u = /* @__PURE__ */ new Set(), S = /* @__PURE__ */ new Set();
355
+ for (; c.length; ) {
356
+ const g = c.shift(), m = g.absolute ? g.url.href : ot(g.url.href, t);
357
+ if (u.has(m)) continue;
358
+ if (g.depth > a) throw new Error(`USD dependency depth limit exceeded (${a}): ${m}`);
359
+ if (u.size >= f) throw new Error(`USD dependency limit exceeded (${f}).`);
360
+ u.add(m);
361
+ const _ = ve(g.url.href, n);
362
+ if (!p.has(_) || g.absolute && !i.has(_)) {
363
+ let x;
364
+ try {
365
+ x = await s(g.url, m);
366
+ } catch (A) {
367
+ if (!g.owner || !Zt(m) || !Kt(A)) throw A;
368
+ const D = `${n}/__unavailable__/${encodeURIComponent(m)}`;
369
+ y[g.owner.path][g.owner.reference] = D, d.set(D, m), h == null || h(m, A);
370
+ continue;
371
+ }
372
+ ze(e, _, x, p);
373
+ }
374
+ if (d.set(_, m), !g.recurse) continue;
375
+ y[_] ?? (y[_] = {});
376
+ const U = r("usd_probe_external_references", ["string"], [_]).paths ?? [];
377
+ for (const x of U) {
378
+ if (!x || /^(?:data|blob):/i.test(x) || /\.mdl(?:[?#].*)?$/i.test(x)) continue;
379
+ let A;
380
+ try {
381
+ A = new URL(x, g.url);
382
+ } catch {
383
+ continue;
384
+ }
385
+ const D = /^(?:[a-z][a-z\d+.-]*:|\/)/i.test(x), E = ve(A.href, n), I = g.absolute || D;
386
+ if (o === "package" && !i.has(E) && !Je(A, t)) {
387
+ const w = I ? A.href : ot(A.href, t), v = `${n}/__skipped__/${encodeURIComponent(w)}`;
388
+ y[_][x] = v, d.set(v, w), S.has(w) || (S.add(w), l == null || l(w));
389
+ continue;
390
+ }
391
+ y[_][x] = E, c.push({
392
+ url: A,
393
+ depth: g.depth + 1,
394
+ recurse: Sn(A.pathname),
395
+ absolute: I,
396
+ owner: { path: _, reference: x }
397
+ });
398
+ }
399
+ }
400
+ return y;
401
+ }
402
+ function Sn(e) {
403
+ var n, s;
404
+ const t = (s = (n = e.split(/[?#]/, 1)[0]) == null ? void 0 : n.split(".").pop()) == null ? void 0 : s.toLowerCase();
405
+ return t != null && mn.has(t);
406
+ }
407
+ function ot(e, t) {
408
+ const n = new URL(e);
409
+ if (n.protocol !== t.protocol || n.host !== t.host) return n.href;
410
+ const s = new URL(".", t).pathname.split("/").filter(Boolean), r = n.pathname.split("/").filter(Boolean);
411
+ let p = 0;
412
+ for (; p < s.length && s[p] === r[p]; ) p++;
413
+ const d = [...s.slice(p).map(() => ".."), ...r.slice(p)].join("/");
414
+ return decodeURIComponent(d) + n.search + n.hash;
415
+ }
416
+ function ve(e, t) {
417
+ const n = new URL(e), s = encodeURIComponent(`${n.protocol}//${n.host}`);
418
+ let r = n.pathname.split("/").map((p) => decodeURIComponent(p).replaceAll("/", "%2F").replaceAll("\\", "%5C")).join("/");
419
+ if (n.search || n.hash) {
420
+ const p = r.lastIndexOf("."), d = p > r.lastIndexOf("/") ? p : r.length;
421
+ r = `${r.slice(0, d)}.__url_${encodeURIComponent(n.search + n.hash)}${r.slice(d)}`;
422
+ }
423
+ return `${t}/${s}${r}`;
424
+ }
425
+ function je(e, t) {
426
+ if (!e || typeof e != "object" || ArrayBuffer.isView(e)) return;
427
+ const n = e;
428
+ if (typeof n.path == "string" && typeof n.resolvedPath == "string") {
429
+ for (const s of ["path", "resolvedPath"]) {
430
+ const r = n[s];
431
+ n[s] = t.get(r) ?? r;
432
+ }
433
+ return;
434
+ }
435
+ for (const s of Object.values(e)) je(s, t);
436
+ }
437
+ function bt(e, t) {
438
+ if (e.analyzePath(t).exists) {
439
+ for (const n of e.readdir(t)) {
440
+ if (n === "." || n === "..") continue;
441
+ const s = `${t}/${n}`;
442
+ e.isDir(e.stat(s).mode) ? bt(e, s) : e.unlink(s);
443
+ }
444
+ e.rmdir(t);
445
+ }
446
+ }
447
+ function ze(e, t, n, s) {
448
+ s.has(t) || (e.FS.mkdirTree(t.split("/").slice(0, -1).join("/") || "/"), e.FS.writeFile(t, n), s.add(t));
449
+ }
450
+ async function at(e) {
451
+ return typeof e == "string" ? new TextEncoder().encode(e) : ArrayBuffer.isView(e) ? new Uint8Array(e.buffer, e.byteOffset, e.byteLength) : e instanceof ArrayBuffer ? new Uint8Array(e) : new Uint8Array(await e.arrayBuffer());
452
+ }
453
+ async function Un(e) {
454
+ if (!e) throw new Error("createSingleThreadUsd needs wasmUrl or wasmBinary.");
455
+ return (await fetch(e)).arrayBuffer();
456
+ }
457
+ const bn = "/openusd/";
458
+ function xn(e) {
459
+ const t = (e ?? bn).replace(/\/*$/, "/"), n = typeof document > "u" ? new URL(t, "file:///").href : new URL(t, document.baseURI).href;
460
+ return {
461
+ moduleUrl: new URL("openusd_probe.js", n).href,
462
+ wasmUrl: new URL("openusd_probe.wasm", n).href
463
+ };
464
+ }
465
+ function En(e) {
466
+ var f, a;
467
+ const t = e.stage, n = e.pxr;
468
+ if (!t || !((f = n == null ? void 0 : n.Sdf) != null && f.Path) || !((a = n == null ? void 0 : n.Usd) != null && a.TimeCode)) return;
469
+ const s = n.Usd.TimeCode.Default(), r = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Set(), d = (o) => {
470
+ let i, l, h;
471
+ try {
472
+ if (i = new n.Sdf.Path(o), l = t.GetPrimAtPath(i), !l.IsValid() || (h = l.GetAttribute("doubleSided"), !h.IsValid() || typeof h.HasAuthoredValue != "function")) return "unknown";
473
+ if (!h.HasAuthoredValue()) return;
474
+ const y = h.Get(s);
475
+ return typeof y == "boolean" ? y : "unknown";
476
+ } catch {
477
+ return "unknown";
478
+ } finally {
479
+ h == null || h.delete(), l == null || l.delete(), i == null || i.delete();
480
+ }
481
+ };
482
+ try {
483
+ e.scene.traverse((o) => {
484
+ var c;
485
+ if (!(o instanceof te)) return;
486
+ const i = (c = o.userData.usd) == null ? void 0 : c.path;
487
+ if (typeof i != "string") return;
488
+ const l = d(i);
489
+ if (l === "unknown") return;
490
+ const h = l === !1 ? Mt : Ot, y = (u) => {
491
+ if (!(u instanceof ie) || u.transmission <= 0 || u.metalness !== 0 || u.side === h) return u;
492
+ let S = r.get(u);
493
+ S || (S = /* @__PURE__ */ new Map(), r.set(u, S));
494
+ let g = S.get(h);
495
+ return g || (g = u.clone(), g.side = h, g.needsUpdate = !0, g.userData.usdGlassSidePolicy = l === !1 ? "authored-false" : l === !0 ? "authored-true" : "viewer-default-double", S.set(h, g)), p.add(u), g;
496
+ };
497
+ if (Array.isArray(o.material)) {
498
+ const u = o.material, S = u.map(y);
499
+ S.some((g, m) => g !== u[m]) && (o.material = S);
500
+ } else {
501
+ const u = y(o.material);
502
+ u !== o.material && (o.material = u);
503
+ }
504
+ }), e.scene.traverse((o) => {
505
+ if (o instanceof te) for (const i of Array.isArray(o.material) ? o.material : [o.material]) p.delete(i);
506
+ });
507
+ for (const o of p) o.dispose();
508
+ } finally {
509
+ s.delete();
510
+ }
511
+ }
512
+ function vn(e, t) {
513
+ if (!e.stage || t.shaders.length) return null;
514
+ const n = e.stage, s = e.pxr, r = s.Usd.TimeCode.Default(), p = (a, o) => {
515
+ const i = new s.Sdf.Path(a), l = n.GetPrimAtPath(i);
516
+ try {
517
+ if (!l.IsValid()) throw new Error("Missing prim");
518
+ return o(l);
519
+ } finally {
520
+ l.delete(), i.delete();
521
+ }
522
+ }, d = (a) => {
523
+ const o = a.GetConnections();
524
+ try {
525
+ return o.map((i) => typeof i == "string" ? i : i.GetString());
526
+ } finally {
527
+ for (const i of o) typeof i != "string" && i.delete();
528
+ }
529
+ }, f = (a, o = /* @__PURE__ */ new Set()) => {
530
+ if (o.has(a) || o.size >= 32) throw new Error("Cyclic material input");
531
+ o.add(a);
532
+ const i = a.lastIndexOf(".");
533
+ if (i < 0 || !a.slice(i + 1).startsWith("inputs:")) throw new Error("Not a constant input");
534
+ return p(a.slice(0, i), (l) => {
535
+ const h = l.GetAttribute(a.slice(i + 1));
536
+ try {
537
+ if (!h.IsValid()) throw new Error("Missing material input");
538
+ const y = d(h);
539
+ if (y.length > 1) throw new Error("Ambiguous material input");
540
+ const c = y.length ? f(y[0], o) : h.Get(r);
541
+ if (c == null) throw new Error("Unauthored material input");
542
+ return c;
543
+ } finally {
544
+ h.delete();
545
+ }
546
+ });
547
+ };
548
+ try {
549
+ return p(t.path, (a) => {
550
+ if (!a.IsInstance()) return null;
551
+ const o = a.GetAttribute("outputs:surface");
552
+ let i;
553
+ try {
554
+ if (!o.IsValid()) return null;
555
+ i = d(o);
556
+ } finally {
557
+ o.delete();
558
+ }
559
+ if (i.length !== 1 || !i[0].endsWith(".outputs:surface")) return null;
560
+ const l = i[0].slice(0, -16);
561
+ return p(l, (h) => {
562
+ const y = h.GetAttribute("info:id");
563
+ try {
564
+ if (y.Get(r) !== "UsdPreviewSurface") return null;
565
+ } finally {
566
+ y.delete();
567
+ }
568
+ const c = {}, u = h.GetAttributes();
569
+ try {
570
+ for (const g of u) {
571
+ const m = String(g.GetName());
572
+ m.startsWith("inputs:") && (c[m] = f(`${l}.${m}`));
573
+ }
574
+ } finally {
575
+ for (const g of u) g.delete();
576
+ }
577
+ return { ...t, shaders: [{ path: l, id: "UsdPreviewSurface", inputs: c }] };
578
+ });
579
+ });
580
+ } catch {
581
+ return null;
582
+ } finally {
583
+ r.delete();
584
+ }
585
+ }
586
+ function fe(e, t, n = 1, s = 0) {
587
+ var l;
588
+ const r = e.image, p = (r == null ? void 0 : r.naturalWidth) || (r == null ? void 0 : r.width), d = (r == null ? void 0 : r.naturalHeight) || (r == null ? void 0 : r.height);
589
+ if (!Number.isInteger(p) || !Number.isInteger(d) || p <= 0 || d <= 0) throw new Error("Texture has no decoded pixels");
590
+ let f;
591
+ if (e instanceof Qe) {
592
+ if (e.type !== et || e.format !== tt || ((l = r.data) == null ? void 0 : l.length) !== p * d * 4) throw new Error("Unsupported scalar pixel format");
593
+ f = r.data;
594
+ } else {
595
+ const h = document.createElement("canvas");
596
+ h.width = p, h.height = d;
597
+ const y = h.getContext("2d", { willReadFrequently: !0 });
598
+ if (!y) throw new Error("Scalar conversion requires a 2D canvas");
599
+ y.drawImage(r, 0, 0), f = y.getImageData(0, 0, p, d).data;
600
+ }
601
+ const a = new Uint8Array(p * d * 4), o = "rgba".indexOf(t);
602
+ for (let h = 0; h < a.length; h += 4) {
603
+ const y = f[h], c = f[h + 1], u = f[h + 2];
604
+ if (t === "grayscale" && (y !== c || c !== u)) throw new Error("Non-grayscale scalar image needs an explicit mono convention");
605
+ const S = t === "average" ? (y + c + u) / 3 : t === "maximum" ? Math.max(y, c, u) : t === "grayscale" ? y : f[h + o], g = Math.round(255 * Math.min(1, Math.max(0, S / 255 * n + s)));
606
+ a[h] = a[h + 1] = a[h + 2] = g, a[h + 3] = 255;
607
+ }
608
+ const i = new Qe(a, p, d, tt, et);
609
+ return i.wrapS = e.wrapS, i.wrapT = e.wrapT, i.offset.copy(e.offset), i.repeat.copy(e.repeat), i.center.copy(e.center), i.rotation = e.rotation, i.matrix.copy(e.matrix), i.matrixAutoUpdate = e.matrixAutoUpdate, i.channel = e.channel, i.flipY = e.flipY, i.minFilter = e.minFilter, i.magFilter = e.magFilter, i.anisotropy = e.anisotropy, i.generateMipmaps = e.generateMipmaps, i.colorSpace = K, i.needsUpdate = !0, i;
610
+ }
611
+ function An(e, t, n, s = [], r = !1) {
612
+ if (e.some((o) => !Number.isInteger(o) || o < 0) || e.reduce((o, i) => o + i, 0) !== t.length || s.some((o) => !Number.isInteger(o) || o < 0 || o >= e.length))
613
+ throw new Error("Invalid authored face topology");
614
+ const p = [], d = [], f = new Set(s);
615
+ let a = 0;
616
+ if (e.forEach((o, i) => {
617
+ if (!f.has(i)) for (let l = 1; l < o - 1; l++)
618
+ p.push(a, a + (r ? l + 1 : l), a + (r ? l : l + 1)), d.push(i);
619
+ a += o;
620
+ }), p.length !== n.length || p.some((o, i) => t[o] !== n[i]))
621
+ throw new Error("Authored polygon/loader corner correspondence unavailable");
622
+ return { corners: p, faces: d };
623
+ }
624
+ function Pn(e, t, n) {
625
+ if (t.length !== n || t.some((r) => !Number.isInteger(r) || r < 0 || r >= e.length))
626
+ throw new Error("Invalid faceVarying UV indices");
627
+ const s = t.flatMap((r) => e[r]);
628
+ if (s.length !== n * 2 || !s.every(Number.isFinite)) throw new Error("Invalid UV values");
629
+ return s;
630
+ }
631
+ function Dn(e, t) {
632
+ const n = Array(e).fill(0);
633
+ for (const s of t) for (const r of s.faces) {
634
+ if (!Number.isInteger(r) || r < 0 || r >= e || n[r] !== 0)
635
+ throw new Error("Invalid or overlapping material subset faces");
636
+ n[r] = s.slot;
637
+ }
638
+ return n;
639
+ }
640
+ function Rn(e, t, n, s) {
641
+ if (!e.stage) return;
642
+ const r = e.stage, p = e.pxr, d = p.Usd.TimeCode.Default(), f = (o, i) => t.warnings.push({
643
+ code: "USD_VISUAL_TOPOLOGY_UNSUPPORTED",
644
+ source: "usd-visual",
645
+ message: `USD ${o} 的部分视觉拓扑未能安全补齐,未确认部分保留 Loader 输出:${String(i)}`
646
+ }), a = (o, i) => {
647
+ const l = o.GetAttribute(i);
648
+ try {
649
+ return l.IsValid() ? l.Get(d) : null;
650
+ } finally {
651
+ l.delete();
652
+ }
653
+ };
654
+ try {
655
+ for (const o of e.data.elements) {
656
+ const i = e.index.objectsByPath.get(o.path);
657
+ if (!(i instanceof te)) continue;
658
+ const l = new p.Sdf.Path(o.path), h = r.GetPrimAtPath(l);
659
+ let y = [];
660
+ try {
661
+ if (h.GetTypeName() !== "Mesh") continue;
662
+ y = h.GetChildren();
663
+ const c = y.filter((v) => v.GetTypeName() === "GeomSubset" && a(v, "familyName") === "materialBind"), u = h.GetAttribute("primvars:st");
664
+ let S = null, g = null;
665
+ try {
666
+ n(o.material) && u.IsValid() && u.GetMetadata("interpolation") === "faceVarying" && (g = a(h, "primvars:st:indices"), g && (S = u.Get(d)));
667
+ } finally {
668
+ u.delete();
669
+ }
670
+ const m = c.length > 0 && !Array.isArray(i.material) && i.geometry.groups.length === 0;
671
+ if (!S && !m) continue;
672
+ const _ = a(h, "faceVertexCounts"), U = a(h, "faceVertexIndices");
673
+ if (!_ || !U || i.geometry.index) throw new Error("Authored face topology unavailable");
674
+ const x = An(
675
+ _,
676
+ U,
677
+ o.geometry.pointIndices ?? [],
678
+ a(h, "holeIndices") ?? [],
679
+ a(h, "orientation") === "leftHanded"
680
+ );
681
+ if (i.geometry.getAttribute("position").count !== x.corners.length)
682
+ throw new Error("Loader geometry corner count mismatch");
683
+ if (S && g) {
684
+ const v = Pn(S, g, U.length), M = x.corners.flatMap((z) => [v[z * 2], v[z * 2 + 1]]), $ = i.geometry.getAttribute("uv");
685
+ (!$ || $.array.length !== M.length || M.some((z, Y) => Math.abs(z - $.array[Y]) > 1e-6)) && (i.geometry.setAttribute("uv", new Tt(M, 2)), o.geometry.uvs = M);
686
+ }
687
+ if (!m) continue;
688
+ const A = c.map((v) => {
689
+ if (a(v, "elementType") !== "face") throw new Error("Non-face material subset");
690
+ const M = p.UsdShade.ComputeBoundMaterialPath(v), $ = (M == null ? void 0 : M.resolvedTargetPath) || (M == null ? void 0 : M.materialPath);
691
+ if (!$ || !e.index.materialsByPath.has($)) throw new Error("Unresolved subset material");
692
+ const z = a(v, "indices");
693
+ if (!Array.isArray(z)) throw new Error("Missing subset face indices");
694
+ return { materialPath: $, faces: z };
695
+ }), D = [...new Set(A.map((v) => v.materialPath))], E = Dn(_.length, A.map((v) => ({ faces: v.faces, slot: D.indexOf(v.materialPath) + 1 }))), I = x.faces.map((v) => E[v]), w = [i.material];
696
+ try {
697
+ for (const v of D) w.push(s(o, v));
698
+ } catch (v) {
699
+ for (const M of w.slice(1)) M.dispose();
700
+ throw v;
701
+ }
702
+ i.material = w;
703
+ for (let v = 0; v < I.length; ) {
704
+ let M = v + 1;
705
+ for (; M < I.length && I[M] === I[v]; ) M++;
706
+ i.geometry.addGroup(v * 3, (M - v) * 3, I[v]), v = M;
707
+ }
708
+ } catch (c) {
709
+ f(o.path, c);
710
+ } finally {
711
+ for (const c of y) c.delete();
712
+ h.delete(), l.delete();
713
+ }
714
+ }
715
+ } finally {
716
+ d.delete();
717
+ }
718
+ }
719
+ const In = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "webp", "avif", "gif", "bmp"]), $e = /^(?:UsdPreviewSurface|ND_UsdPreviewSurface_surfaceshader)$/i, Mn = /(?:standard.?surface|principled|openpbr|adobe.?standard.?material)/i;
720
+ async function On(e, t) {
721
+ var a;
722
+ it(e.scene);
723
+ const n = /* @__PURE__ */ new Set();
724
+ for (const o of e.data.materials) {
725
+ const i = vn(e, o);
726
+ i && (o.shaders = i.shaders, e.index.materialsByPath.set(o.path, o), n.add(o.path));
727
+ }
728
+ const s = (o, i) => {
729
+ const l = e.data.view.prims.find((g) => g.path === o.path);
730
+ if (!l) throw new Error(`Missing view prim: ${o.path}`);
731
+ const h = e.index.materialsByPath.get(i), y = Fe(h), c = () => Ht({
732
+ ...e.data,
733
+ elements: [{ ...o, material: i }],
734
+ view: { ...e.data.view, prims: [{ ...l, parentPath: null }] },
735
+ animations: [],
736
+ lights: [],
737
+ skels: { ...e.data.skels, bindings: [], skeletons: [], animations: [] }
738
+ }, {
739
+ convertZUp: !1,
740
+ loadLights: !1,
741
+ loadTextures: !y,
742
+ sourcePath: t.sourcePath,
743
+ textureResolver: (g) => {
744
+ for (const m of [g.resolvedPath, g.path, g.url]) {
745
+ if (!m) continue;
746
+ const _ = t.files.objectUrlIfPresent(m, t.entryDirectory ?? "");
747
+ if (_) return _;
748
+ }
749
+ return null;
750
+ }
751
+ }), u = t.isTextureAllowed ? St(e.data.materials, (g) => t.isTextureAllowed(g) && !!t.files.objectUrlIfPresent(g, t.entryDirectory ?? ""), c) : c();
752
+ it(u.scene);
753
+ const S = u.index.objectsByPath.get(o.path);
754
+ if (S.geometry.dispose(), Array.isArray(S.material)) throw new Error("Unexpected scratch material array");
755
+ return S.material;
756
+ }, r = /* @__PURE__ */ new Set();
757
+ for (const o of e.data.elements) {
758
+ const i = e.index.objectsByPath.get(o.path);
759
+ if (!(i instanceof te)) continue;
760
+ const l = (h) => {
761
+ const y = he(h.userData.usdMaterialPath);
762
+ if (!y || !n.has(y) || h.userData.usdSurfaceShaderId) return h;
763
+ const c = s(o, y), u = `Material ${y} has no supported surface shader.`;
764
+ return c.userData.usdInstanceResolvedDiagnostics = [u], c.userData.usdMaterialDiagnostics = Se([
765
+ ...Oe(h.userData.usdMaterialDiagnostics),
766
+ ...Oe(c.userData.usdMaterialDiagnostics)
767
+ ]), r.add(h), c;
768
+ };
769
+ if (Array.isArray(i.material)) {
770
+ const h = i.material.map(l);
771
+ h.some((y, c) => y !== i.material[c]) && (i.material = h);
772
+ } else i.material = l(i.material);
773
+ }
774
+ e.scene.traverse((o) => {
775
+ if (o instanceof te) for (const i of Array.isArray(o.material) ? o.material : [o.material]) r.delete(i);
776
+ });
777
+ for (const o of r) o.dispose();
778
+ Rn(e, t.diagnostics, (o) => {
779
+ if (!o) return !0;
780
+ const i = e.index.materialsByPath.get(o), l = i && Fe(i);
781
+ return !!l && Ae(l) && le(l, /* @__PURE__ */ new Set());
782
+ }, s);
783
+ const p = Cn(e), d = [];
784
+ for (const [o, i] of p) {
785
+ const l = e.index.materialsByPath.get(o);
786
+ if (!l) continue;
787
+ const h = i[0], y = Se(i.flatMap((w) => Oe(w.userData.usdMaterialDiagnostics))), c = he(h.userData.usdSurfaceShaderId);
788
+ if (c && ($e.test(c) || Mn.test(c))) {
789
+ const w = await Ln(l, i, y, t), v = await $n(l, i, t);
790
+ w.applied.push(...v.applied), w.resources.push(...v.resources);
791
+ const M = v.applied.length ? { applied: [], unsupported: [], bounded: !0 } : $e.test(c) ? Tn(e, l, i, t) : Nn(l, i, t);
792
+ w.applied.push(...M.applied);
793
+ const $ = Se(i.flatMap((z) => Oe(z.userData.usdInstanceResolvedDiagnostics)));
794
+ w.resolved.push(...$), $.length && w.applied.push("instance.surface.constants"), d.push({
795
+ materialPath: o,
796
+ sourceShaderId: c,
797
+ action: w.applied.length ? "augmented" : "preserved",
798
+ fidelity: M.bounded || y.some((z) => !w.resolved.includes(z)) ? "bounded-approximation" : "native",
799
+ appliedInputs: w.applied,
800
+ unsupportedNodes: M.unsupported,
801
+ resources: w.resources,
802
+ loaderDiagnostics: y,
803
+ resolvedLoaderDiagnostics: w.resolved
804
+ });
805
+ continue;
806
+ }
807
+ const u = Fe(l);
808
+ if (!u) {
809
+ const w = ut(e, o), v = l.shaders.map((M) => Z(M.inputs["info:mdl:sourceAsset"])).filter(He);
810
+ for (const M of v) t.diagnostics.droppedFeatures.push({ code: "USD_VISUAL_SHADER_NODE_UNSUPPORTED", source: "usd-visual", message: `USD 材质 ${o} 使用尚未支持的 MDL 材质 ${M};保留现有结果,未生成替代内容。` });
811
+ d.push({
812
+ materialPath: o,
813
+ sourceShaderId: v[0] ?? null,
814
+ action: "fallback",
815
+ fidelity: w ? "authored-fallback" : "default-fallback",
816
+ appliedInputs: [],
817
+ unsupportedNodes: Se(l.shaders.map((M) => M.id).filter(He)),
818
+ resources: [],
819
+ loaderDiagnostics: y
820
+ });
821
+ continue;
822
+ }
823
+ if (Ze(u)) {
824
+ const w = Gn(e, i, u), v = w.applied.length ? await Fn(i, u, w, t) : [];
825
+ w.applied.length && v.push(...await Bn(i, u, w, t)), We(t.diagnostics, o, u, w.applied, w.unsupported, v, w.applied.length ? "augmented" : "fallback"), d.push({
826
+ materialPath: o,
827
+ sourceShaderId: "OmniGlass",
828
+ action: w.applied.length ? "augmented" : "fallback",
829
+ fidelity: "bounded-approximation",
830
+ appliedInputs: w.applied,
831
+ unsupportedNodes: [...w.unsupported],
832
+ resources: v,
833
+ loaderDiagnostics: y
834
+ });
835
+ continue;
836
+ }
837
+ const S = [], g = [], m = /* @__PURE__ */ new Set(), _ = jn(i, u, S);
838
+ let U = !1;
839
+ if (Ae(u)) {
840
+ const w = Z(N(u, ["diffuse_texture"]));
841
+ if (w) {
842
+ const b = await se(w, t);
843
+ if (g.push(b.report), b.url && le(u, m) && i.every((T) => W(T) && !T.map)) {
844
+ let T = null;
845
+ try {
846
+ T = await (t.createTexture ?? oe)(b.url, nt);
847
+ } catch (R) {
848
+ if (R instanceof Error && R.name === "AbortError") throw R;
849
+ g[g.length - 1] = { path: w, status: "decode-failed" };
850
+ }
851
+ if (T) {
852
+ for (const R of i)
853
+ W(R) && (R.map = T, R.color.set(16777215), R.needsUpdate = !0, U = !0);
854
+ U ? S.push("diffuse_texture") : T.dispose();
855
+ }
856
+ }
857
+ }
858
+ const v = ae(u, ["enable_ORM_texture"], !1);
859
+ if (v) {
860
+ const b = Z(N(u, ["ORM_texture"])), T = C(u, ["reflection_roughness_texture_influence"]) ?? 0, R = C(u, ["metallic_texture_influence"]) ?? 0;
861
+ C(u, ["ao_to_diffuse"]);
862
+ const X = N(u, ["ORM_texture_colorspace"]);
863
+ if (X !== void 0 && X !== "raw") m.add("OmniPBR.ORM_texture_colorspace");
864
+ else if (T || R)
865
+ if (!b) m.add("OmniPBR.ORM_texture_missing");
866
+ else {
867
+ const P = await se(b, t);
868
+ if (g.push(P.report), P.url && le(u, m)) {
869
+ let O = null, B = !1;
870
+ try {
871
+ O = await (t.createTexture ?? oe)(P.url, K), O.colorSpace = K, O.wrapS = J, O.wrapT = J;
872
+ const k = [
873
+ {
874
+ slot: "roughnessMap",
875
+ scalar: "roughness",
876
+ channel: "g",
877
+ influence: T,
878
+ constant: C(u, ["reflection_roughness_constant"]) ?? 0.5
879
+ },
880
+ {
881
+ slot: "metalnessMap",
882
+ scalar: "metalness",
883
+ channel: "b",
884
+ influence: R,
885
+ constant: C(u, ["metallic_constant"]) ?? 0
886
+ }
887
+ ];
888
+ for (const G of k) {
889
+ if (!Number.isFinite(G.influence) || G.influence < 0 || G.influence > 1 || G.constant < 0 || G.constant > 1) {
890
+ m.add(`OmniPBR.${G.scalar}_ORM_range`);
891
+ continue;
892
+ }
893
+ const ce = i.filter(W).filter((F) => !F[G.slot]);
894
+ if (ce.length) {
895
+ if (G.influence === 0) {
896
+ for (const F of ce) F[G.scalar] = G.constant;
897
+ continue;
898
+ }
899
+ try {
900
+ const F = G.influence === 1 ? O : fe(
901
+ O,
902
+ G.channel,
903
+ G.influence,
904
+ G.constant * (1 - G.influence)
905
+ );
906
+ for (const q of ce)
907
+ q[G.slot] = F, q[G.scalar] = 1, q.needsUpdate = !0;
908
+ F === O && (B = !0), S.push(`${G.scalar}.ORM.${G.channel}`, `ORM.${G.scalar}.influence=${G.influence}`), U = !0;
909
+ } catch {
910
+ m.add(`OmniPBR.${G.scalar}_ORM_conversion`);
911
+ }
912
+ }
913
+ }
914
+ U && S.push("ORM_texture");
915
+ } catch (k) {
916
+ if (k instanceof Error && k.name === "AbortError") throw k;
917
+ g[g.length - 1] = { path: b, status: "decode-failed" };
918
+ } finally {
919
+ B || O == null || O.dispose();
920
+ }
921
+ }
922
+ }
923
+ }
924
+ if (!v && le(u, m))
925
+ for (const b of [
926
+ { file: "reflectionroughness_texture", weight: "reflection_roughness_texture_influence", constant: "reflection_roughness_constant", fallback: 0.5, map: "roughnessMap", scalar: "roughness" },
927
+ { file: "metallic_texture", weight: "metallic_texture_influence", constant: "metallic_constant", fallback: 0, map: "metalnessMap", scalar: "metalness" }
928
+ ]) {
929
+ const T = C(u, [b.weight]) ?? 0;
930
+ if (T === 0) continue;
931
+ if (T < 0 || T > 1) {
932
+ m.add(`OmniPBR.${b.weight}`);
933
+ continue;
934
+ }
935
+ const R = Z(N(u, [b.file]));
936
+ if (!R) continue;
937
+ const X = N(u, [`${b.file}_colorspace`]);
938
+ if (X !== void 0 && X !== "raw") {
939
+ m.add(`OmniPBR.${b.file}_colorspace`);
940
+ continue;
941
+ }
942
+ const P = await se(R, t);
943
+ g.push(P.report);
944
+ const O = i.filter(W).filter((k) => !k[b.map]);
945
+ if (!P.url || !O.length) continue;
946
+ let B = null;
947
+ try {
948
+ B = await (t.createTexture ?? oe)(P.url, K);
949
+ const k = C(u, [b.constant]) ?? b.fallback, G = fe(B, "grayscale", T, k * (1 - T));
950
+ G.wrapS = J, G.wrapT = J;
951
+ for (const ce of O)
952
+ ce[b.map] = G, ce[b.scalar] = 1, ce.needsUpdate = !0;
953
+ S.push(b.file), U = !0;
954
+ } catch (k) {
955
+ if (k instanceof Error && k.name === "AbortError") throw k;
956
+ m.add(`OmniPBR.${b.file}_conversion`);
957
+ } finally {
958
+ B == null || B.dispose();
959
+ }
960
+ }
961
+ const M = ae(u, ["enable_opacity"], !1), $ = C(u, ["opacity_threshold"]) ?? 0;
962
+ if (M && $ >= 0 && ae(u, ["enable_opacity_texture"], !1) && le(u, m)) {
963
+ const b = Z(N(u, ["opacity_texture"])), T = N(u, ["opacity_mode"]) ?? 1, R = T === 0 || T === "mono_alpha" ? "a" : T === 1 || T === "mono_average" ? "average" : T === 3 || T === "mono_maximum" ? "maximum" : null, X = N(u, ["opacity_texture_colorspace"]);
964
+ if (X !== void 0 && X !== "raw") m.add("OmniPBR.opacity_texture_colorspace");
965
+ else if (!R) m.add("OmniPBR.opacity_mode");
966
+ else if (!b) m.add("OmniPBR.opacity_texture_missing");
967
+ else {
968
+ const P = await se(b, t);
969
+ g.push(P.report);
970
+ const O = i.filter(W).filter((k) => !k.alphaMap);
971
+ let B = null;
972
+ if (P.url && O.length) try {
973
+ B = await (t.createTexture ?? oe)(P.url, K);
974
+ const k = fe(B, R);
975
+ k.wrapS = J, k.wrapT = J;
976
+ for (const G of O)
977
+ G.alphaMap = k, G.opacity = 1, G.alphaTest = Math.max(0, $), G.transparent = $ === 0, G.depthWrite = $ > 0, G.needsUpdate = !0;
978
+ S.push("opacity_texture"), U = !0;
979
+ } catch (k) {
980
+ if (k instanceof Error && k.name === "AbortError") throw k;
981
+ g[g.length - 1] = { path: b, status: "decode-failed" };
982
+ } finally {
983
+ B == null || B.dispose();
984
+ }
985
+ }
986
+ }
987
+ const Y = Le(u, ["diffuse_tint"]);
988
+ if (Y) {
989
+ for (const b of i)
990
+ W(b) && (b.map ? b.color.copy(Y) : b.color.copy(Le(u, ["diffuse_color_constant"]) ?? new mt(0.2, 0.2, 0.2)).multiply(Y), b.needsUpdate = !0);
991
+ S.push("diffuse_tint"), U = !0;
992
+ }
993
+ const H = Z(N(u, ["normalmap_texture"]));
994
+ if (H) {
995
+ const b = await se(H, t);
996
+ g.push(b.report);
997
+ const T = N(u, ["normalmap_texture_colorspace"]), R = C(u, ["bump_factor"]) ?? 1;
998
+ if (T !== void 0 && T !== "raw") m.add("OmniPBR.normalmap_texture_colorspace");
999
+ else if (!Number.isFinite(R) || R < 0) m.add("OmniPBR.bump_factor");
1000
+ else if (b.url && le(u, m)) {
1001
+ const X = i.filter(W).filter((P) => !P.normalMap);
1002
+ if (X.length)
1003
+ try {
1004
+ const P = await (t.createTexture ?? oe)(b.url, K);
1005
+ P.colorSpace = K, P.wrapS = J, P.wrapT = J;
1006
+ for (const O of X)
1007
+ O.normalMap = P, O.normalScale.set(
1008
+ R * (ae(u, ["flip_tangent_u"], !1) ? -1 : 1),
1009
+ R * (ae(u, ["flip_tangent_v"], !0) ? -1 : 1)
1010
+ ), O.needsUpdate = !0;
1011
+ S.push("normalmap_texture", "normal.tangent_convention"), U = !0;
1012
+ } catch (P) {
1013
+ if (P instanceof Error && P.name === "AbortError") throw P;
1014
+ g[g.length - 1] = { path: H, status: "decode-failed" };
1015
+ }
1016
+ }
1017
+ }
1018
+ Vn(u, m), U = await kn(i, u, S, m, g, t) || U;
1019
+ }
1020
+ const x = j(u, "diffuseColor") ?? j(u, "baseColor");
1021
+ let A = !1;
1022
+ if (x) {
1023
+ const w = me(l, x);
1024
+ if (w && Et(w)) {
1025
+ const v = Wn(w);
1026
+ if (v) {
1027
+ const M = await se(v.path, t);
1028
+ g.push(M.report);
1029
+ const $ = j(w, "manifold");
1030
+ $ && m.add(((a = me(l, $)) == null ? void 0 : a.id) ?? $.path);
1031
+ const z = Object.keys(w.inputs).filter((b) => !["inputs:filename", "inputs:resultRGB", "inputs:linearize"].includes(b)), Y = w.inputs["inputs:linearize"], H = Y === 0 || Y === 1;
1032
+ if (H || m.add("PxrTexture.colorSpace"), z.length > 0 && !$ && m.add("PxrTexture.controls"), M.url && !$ && z.length === 0 && H && x.outputName === "resultRGB" && i.every((b) => W(b) && !b.map)) {
1033
+ let b = null;
1034
+ try {
1035
+ b = await (t.createTexture ?? oe)(M.url, Y === 1 ? nt : K);
1036
+ } catch (T) {
1037
+ if (T instanceof Error && T.name === "AbortError") throw T;
1038
+ g[g.length - 1] = { path: v.path, status: "decode-failed" };
1039
+ }
1040
+ if (b) {
1041
+ for (const T of i)
1042
+ W(T) && (T.map = b, T.color.set(16777215), T.needsUpdate = !0, A = !0);
1043
+ A ? S.push("diffuseColor.texture") : b.dispose();
1044
+ }
1045
+ }
1046
+ } else
1047
+ m.add(w.id ?? w.path);
1048
+ } else w ? m.add(w.id ?? w.path) : m.add(x.path);
1049
+ }
1050
+ zn(l, u, m);
1051
+ const D = _ || A || U ? "augmented" : "fallback", E = ut(e, o), I = D === "augmented" ? "bounded-approximation" : E ? "authored-fallback" : "default-fallback";
1052
+ We(t.diagnostics, o, u, S, m, g, D), d.push({
1053
+ materialPath: o,
1054
+ sourceShaderId: xt(u),
1055
+ action: D,
1056
+ fidelity: I,
1057
+ appliedInputs: Se(S),
1058
+ unsupportedNodes: [...m],
1059
+ resources: g,
1060
+ loaderDiagnostics: y
1061
+ });
1062
+ }
1063
+ En(e);
1064
+ const f = d.filter((o) => o.loaderDiagnostics.some(
1065
+ (i) => {
1066
+ var l;
1067
+ return !((l = o.resolvedLoaderDiagnostics) != null && l.includes(i)) && !(o.action === "augmented" && i === `Material ${o.materialPath} has no supported surface shader.`);
1068
+ }
1069
+ ));
1070
+ return f.length > 0 && t.diagnostics.droppedFeatures.push({
1071
+ code: "USD_VISUAL_LOADER_DIAGNOSTIC",
1072
+ message: `${f.length} 个 USD 材质仍有尚未被视觉适配层消解的 Loader 限制;具体材质和原始诊断见 visualAdaptation 报告。`,
1073
+ source: "usd-visual"
1074
+ }), Object.freeze({
1075
+ schemaVersion: 1,
1076
+ materials: d,
1077
+ summary: Object.freeze({
1078
+ preserved: d.filter((o) => o.action === "preserved").length,
1079
+ augmented: d.filter((o) => o.action === "augmented").length,
1080
+ fallback: d.filter((o) => o.action === "fallback").length,
1081
+ missingResources: d.flatMap((o) => o.resources).filter((o) => o.status === "missing").length,
1082
+ unsupportedResources: d.flatMap((o) => o.resources).filter((o) => o.status === "unsupported-format").length
1083
+ })
1084
+ });
1085
+ }
1086
+ function it(e) {
1087
+ e == null || e.traverse((t) => {
1088
+ if (!(t instanceof te)) return;
1089
+ const n = Array.isArray(t.material) ? t.material : [t.material];
1090
+ for (const s of n)
1091
+ for (const r of ["map", "normalMap", "roughnessMap", "metalnessMap", "aoMap", "emissiveMap", "alphaMap", "bumpMap", "displacementMap", "clearcoatMap", "clearcoatNormalMap", "clearcoatRoughnessMap", "iridescenceMap", "iridescenceThicknessMap", "specularColorMap", "specularIntensityMap", "transmissionMap", "thicknessMap", "sheenColorMap", "sheenRoughnessMap"]) {
1092
+ const p = s[r];
1093
+ p instanceof ht && (p.matrix.identity(), p.matrixAutoUpdate = !1, p.needsUpdate = !0);
1094
+ }
1095
+ });
1096
+ }
1097
+ function Tn(e, t, n, s) {
1098
+ var y;
1099
+ const r = { applied: [], unsupported: [], bounded: !1 }, p = he((y = n[0]) == null ? void 0 : y.userData.usdSurfaceShaderPath), d = t.shaders.filter((c) => $e.test(c.id ?? "")), f = p ? d.find((c) => c.path === p) : d.length === 1 ? d[0] : void 0;
1100
+ if (!f) return r;
1101
+ const a = C(f, ["opacity"]), o = N(f, ["opacityMode"]) ?? "transparent", i = C(f, ["opacityThreshold"]) ?? 0, l = (c) => (r.bounded = !0, r.unsupported.push(c), s.diagnostics.droppedFeatures.push({
1102
+ code: "USD_VISUAL_PREVIEW_TRANSPARENCY_UNSUPPORTED",
1103
+ source: "usd-visual",
1104
+ message: `USD 材质 ${t.path} 的 ${c} 未完成透明适配,保留 Loader 输出;未生成替代内容。`
1105
+ }), r);
1106
+ if (j(f, "opacity") || j(f, "opacityThreshold") || j(f, "opacityMode")) return l("connected opacity/threshold/mode");
1107
+ if (i > 0 || o === "presence") {
1108
+ if (n.some((u) => !W(u) || u.alphaMap || u.map)) return l("textured coverage/cutout");
1109
+ const c = xe(a ?? 1);
1110
+ for (const u of n)
1111
+ u.opacity = i > 0 ? c >= i ? 1 : 0 : c, u.alphaTest = i > 0 ? 0.5 : 0, u.transparent = i === 0 && c < 1, u.depthWrite = !u.transparent, u instanceof ie && (u.transmission = 0), u.needsUpdate = !0;
1112
+ return r.applied.push(i > 0 ? "PreviewSurface.cutout.constant" : "PreviewSurface.presence.constant"), r;
1113
+ }
1114
+ if (o !== "transparent") return l(`opacityMode=${String(o)}`);
1115
+ if (a === null || a >= 1) return r;
1116
+ if (!j(f, "metallic") && C(f, ["metallic"]) === 1 && !j(f, "useSpecularWorkflow") && [void 0, !1, 0].includes(N(f, ["useSpecularWorkflow"]))) {
1117
+ if (n.some((c) => !W(c) || c.alphaMap || c.map || c.metalnessMap || c.alphaTest > 0)) return l("textured metal transparency");
1118
+ for (const c of n)
1119
+ W(c) && (c.opacity = 1, c.transparent = !1, c.depthWrite = !0, c.metalness = 1, c instanceof ie && (c.transmission = 0), c.needsUpdate = !0);
1120
+ return r.applied.push("PreviewSurface.transparent.pure-metal"), r;
1121
+ }
1122
+ if (j(f, "metallic") || j(f, "useSpecularWorkflow") || j(f, "ior") || (C(f, ["metallic"]) ?? 0) !== 0 || ![void 0, !1, 0].includes(N(f, ["useSpecularWorkflow"]))) return l("non-dielectric or connected transparency");
1123
+ if (n.some((c) => !W(c) || c.alphaMap || c.map || c.metalnessMap || c.alphaTest > 0)) return l("textured or non-standard transparency");
1124
+ const h = /* @__PURE__ */ new Map();
1125
+ for (const c of n) {
1126
+ if (!W(c)) continue;
1127
+ const u = c instanceof ie ? c : new ie();
1128
+ u !== c && (qe.prototype.copy.call(u, c), u.defines = { STANDARD: "", PHYSICAL: "" }, h.set(c, u)), u.opacity = 1, u.transparent = !1, u.transmission = 1 - xe(a), u.ior = C(f, ["ior"]) ?? 1.5, u.depthWrite = !0, u.needsUpdate = !0;
1129
+ }
1130
+ if (h.size) {
1131
+ e.scene.traverse((c) => {
1132
+ c instanceof te && (c.material = Array.isArray(c.material) ? c.material.map((u) => h.get(u) ?? u) : h.get(c.material) ?? c.material);
1133
+ }), n.forEach((c, u) => {
1134
+ n[u] = h.get(c) ?? c;
1135
+ });
1136
+ for (const c of h.keys()) c.dispose();
1137
+ }
1138
+ return r.applied.push("PreviewSurface.transparent.constant-dielectric"), r.bounded = !0, s.diagnostics.approximations.push({
1139
+ code: "USD_VISUAL_PREVIEW_TRANSMISSION_APPROXIMATION",
1140
+ source: "usd-visual",
1141
+ message: `USD 材质 ${t.path} 的常量介质透明已映射为实时透射;保留表面反射;Three.js 透射与反射共用粗糙度,不等同于 PreviewSurface 的零粗糙度透射。不推断壁厚或体积吸收,不保证多层折射与路径追踪等价。`
1142
+ }), r;
1143
+ }
1144
+ function Nn(e, t, n) {
1145
+ var i;
1146
+ const s = { applied: [], unsupported: [], bounded: !1 }, r = he((i = t[0]) == null ? void 0 : i.userData.usdSurfaceShaderPath), p = e.shaders.filter((l) => l.id === "ND_standard_surface_surfaceshader"), d = r ? p.find((l) => l.path === r) : p.length === 1 ? p[0] : void 0;
1147
+ if (!d) return s;
1148
+ const f = (l) => {
1149
+ s.bounded = !0, s.unsupported.push(l), n.diagnostics.droppedFeatures.push({
1150
+ code: "USD_VISUAL_MATERIALX_TRANSPARENCY_UNSUPPORTED",
1151
+ source: "usd-visual",
1152
+ message: `USD 材质 ${e.path} 的 MaterialX ${l} 尚未完整适配;不猜测厚度或生成替代内容。`
1153
+ });
1154
+ }, a = N(d, ["opacity"]);
1155
+ if (j(d, "opacity")) f("connected opacity");
1156
+ else if (Array.isArray(a) && a.length === 3 && a.every((l) => typeof l == "number" && Number.isFinite(l)))
1157
+ if (a[0] !== a[1] || a[1] !== a[2]) f("colored opacity");
1158
+ else if (t.some((l) => !W(l) || l.alphaMap || l.map)) f("textured coverage");
1159
+ else {
1160
+ const l = xe(a[0]);
1161
+ for (const h of t)
1162
+ h.opacity = l, h.transparent = l < 1, h.depthWrite = l === 1, h.needsUpdate = !0;
1163
+ s.applied.push("MaterialX.opacity.achromatic-constant");
1164
+ }
1165
+ const o = C(d, ["transmission"]) ?? 0;
1166
+ return j(d, "transmission") && f("connected transmission"), o > 0 && (s.bounded = !0, Array.isArray(a) && a.some((l) => typeof l == "number" && l > 0 && l < 1) && f("fractional coverage + transmission compositing"), ae(d, ["thin_walled"], !1) ? n.diagnostics.approximations.push({
1167
+ code: "USD_VISUAL_MATERIALX_TRANSMISSION_APPROXIMATION",
1168
+ source: "usd-visual",
1169
+ message: `USD 材质 ${e.path} 的 MaterialX 薄壁透射使用 Loader 的实时近似;并非完整 MaterialX 着色器执行。`
1170
+ }) : f("solid transmission / absorption path length")), s;
1171
+ }
1172
+ async function $n(e, t, n) {
1173
+ var D;
1174
+ const s = { applied: [], resources: [] }, r = he((D = t[0]) == null ? void 0 : D.userData.usdSurfaceShaderPath), p = e.shaders.filter((E) => $e.test(E.id ?? "")), d = r ? p.find((E) => E.path === r) : p.length === 1 ? p[0] : void 0;
1175
+ if (!d || j(d, "opacityThreshold") || j(d, "opacityMode")) return s;
1176
+ const f = C(d, ["opacityThreshold"]) ?? 0;
1177
+ if (f <= 0 && N(d, ["opacityMode"]) !== "presence") return s;
1178
+ const a = j(d, "opacity");
1179
+ if (!(a != null && a.outputName) || !["r", "g", "b", "a"].includes(a.outputName)) return s;
1180
+ const o = me(e, a);
1181
+ if (!o || o.id !== "UsdUVTexture" || N(o, ["sourceColorSpace"]) !== "raw") return s;
1182
+ const i = j(o, "st"), l = i && me(e, i);
1183
+ if (!l || l.id !== "UsdPrimvarReader_float2" || N(l, ["varname"]) !== "st" || t.some((E) => !W(E) || E.map)) return s;
1184
+ const h = "rgba".indexOf(a.outputName), y = (E, I) => {
1185
+ if (j(o, E)) return null;
1186
+ const w = o.inputs[`inputs:${E}`];
1187
+ return w === void 0 ? I : Array.isArray(w) && w.length === 4 && w.every(Number.isFinite) ? w[h] : null;
1188
+ }, c = y("scale", 1), u = y("bias", 0);
1189
+ if (c === null || u === null) return s;
1190
+ const S = (E) => {
1191
+ const I = N(o, [E]);
1192
+ return I === "repeat" ? J : I === "mirror" ? gt : I === "clamp" ? _t : null;
1193
+ }, g = S("wrapS"), m = S("wrapT"), _ = Z(N(o, ["file"]));
1194
+ if (!_ || g === null || m === null) return s;
1195
+ const U = JSON.stringify([o.path, a.outputName, c, u, g, m, f]);
1196
+ if (t.every((E) => {
1197
+ var I;
1198
+ return W(E) && ((I = E.alphaMap) == null ? void 0 : I.userData.usdCoverageConversionKey) === U;
1199
+ }))
1200
+ return s.applied.push(`PreviewSurface.opacity.texture.${a.outputName}->g`), s.resources.push({ path: _, status: "available" }), s;
1201
+ const x = await se(_, n);
1202
+ s.resources.push(x.report);
1203
+ let A = null;
1204
+ try {
1205
+ if (!x.url) return s;
1206
+ A = await (n.createTexture ?? oe)(x.url, K);
1207
+ const E = fe(A, a.outputName, c, u);
1208
+ E.wrapS = g, E.wrapT = m, E.userData.usdCoverageConversionKey = U;
1209
+ for (const I of t)
1210
+ W(I) && (I.alphaMap = E, I.opacity = 1, I.alphaTest = f > 0 ? f : 0, I.transparent = f <= 0, I.depthWrite = f > 0, I instanceof ie && (I.transmission = 0), I.needsUpdate = !0);
1211
+ s.applied.push(`PreviewSurface.opacity.texture.${a.outputName}->g`), n.diagnostics.approximations.push({
1212
+ code: "USD_VISUAL_COVERAGE_TEXTURE_APPROXIMATION",
1213
+ source: "usd-visual",
1214
+ message: `USD 材质 ${e.path} 的透明遮罩已按源通道转换;采用 8 位纹理重排,阈值边缘与过滤结果不保证跨渲染器逐像素一致。`
1215
+ });
1216
+ } catch (E) {
1217
+ if (E instanceof Error && E.name === "AbortError") throw E;
1218
+ s.resources[0] = { path: _, status: "decode-failed" };
1219
+ } finally {
1220
+ A == null || A.dispose();
1221
+ }
1222
+ return s;
1223
+ }
1224
+ async function Ln(e, t, n, s) {
1225
+ var A;
1226
+ const r = { applied: [], resolved: [], resources: [] }, p = he((A = t[0]) == null ? void 0 : A.userData.usdSurfaceShaderPath), d = e.shaders.find((D) => D.path === p) ?? e.shaders.find((D) => D.id === "UsdPreviewSurface");
1227
+ if (!d || d.id !== "UsdPreviewSurface") return r;
1228
+ const f = j(d, "roughness");
1229
+ if (!f || !f.outputName || !["r", "g", "b", "a"].includes(f.outputName)) return r;
1230
+ const a = me(e, f);
1231
+ if (!a || a.id !== "UsdUVTexture") return r;
1232
+ const o = `Texture output ${f.outputName} from ${a.path} cannot be mapped to Three.js roughness without channel repacking.`;
1233
+ if (!n.includes(o) || N(a, ["sourceColorSpace"]) !== "raw") return r;
1234
+ const i = j(a, "st");
1235
+ if (i) {
1236
+ const D = me(e, i);
1237
+ if ((D == null ? void 0 : D.id) !== "UsdPrimvarReader_float2" || N(D, ["varname"]) !== "st") return r;
1238
+ } else if (a.inputs["inputs:st"] !== void 0) return r;
1239
+ const l = "rgba".indexOf(f.outputName);
1240
+ function h(D, E) {
1241
+ if (j(a, D)) return null;
1242
+ const I = a.inputs[`inputs:${D}`];
1243
+ return I === void 0 ? E : Array.isArray(I) && I.length === 4 && I.every(Number.isFinite) ? I[l] : null;
1244
+ }
1245
+ const y = h("scale", 1), c = h("bias", 0);
1246
+ if (y === null || c === null) return r;
1247
+ function u(D) {
1248
+ if (j(a, D)) return null;
1249
+ const E = a.inputs[`inputs:${D}`];
1250
+ return E === "repeat" ? J : E === "mirror" ? gt : E === "clamp" ? _t : null;
1251
+ }
1252
+ const S = u("wrapS"), g = u("wrapT");
1253
+ if (S === null || g === null) return r;
1254
+ const m = Z(N(a, ["file"]));
1255
+ if (!m) return r;
1256
+ const _ = t.filter(W);
1257
+ if (!_.length) return r;
1258
+ if (_.every((D) => {
1259
+ var E;
1260
+ return ((E = D.roughnessMap) == null ? void 0 : E.userData.usdResolvedChannelDiagnostic) === o;
1261
+ }))
1262
+ return r.applied.push(`roughness.texture.${f.outputName}->g`), r.resolved.push(o), r;
1263
+ if (_.some((D) => D.roughnessMap !== null)) return r;
1264
+ const U = await se(m, s);
1265
+ r.resources.push(U.report);
1266
+ let x = null;
1267
+ if (U.url)
1268
+ try {
1269
+ x = await (s.createTexture ?? oe)(U.url, K);
1270
+ const D = fe(x, f.outputName, y, c);
1271
+ D.wrapS = S, D.wrapT = g, D.userData.usdResolvedChannelDiagnostic = o;
1272
+ for (const E of _)
1273
+ E.roughnessMap = D, E.roughness = 1, E.needsUpdate = !0;
1274
+ r.applied.push(`roughness.texture.${f.outputName}->g`), r.resolved.push(o);
1275
+ } catch (D) {
1276
+ if (D instanceof Error && D.name === "AbortError") throw D;
1277
+ r.resources[0] = { path: m, status: "decode-failed" };
1278
+ } finally {
1279
+ x == null || x.dispose();
1280
+ }
1281
+ return We(s.diagnostics, e.path, d, [], /* @__PURE__ */ new Set(), r.resources, "preserved"), r;
1282
+ }
1283
+ function Cn(e) {
1284
+ const t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Set();
1285
+ return e.scene.traverse((s) => {
1286
+ if (s instanceof te)
1287
+ for (const r of Array.isArray(s.material) ? s.material : [s.material]) {
1288
+ if (n.has(r)) continue;
1289
+ n.add(r);
1290
+ const p = he(r.userData.usdMaterialPath);
1291
+ if (!p) continue;
1292
+ const d = t.get(p);
1293
+ d ? d.push(r) : t.set(p, [r]);
1294
+ }
1295
+ }), t;
1296
+ }
1297
+ function Fe(e) {
1298
+ const t = e.shaders.filter((n) => /^PxrSurface$/i.test(n.id ?? "") || Ae(n) || Ze(n));
1299
+ return t.length === 1 ? t[0] : null;
1300
+ }
1301
+ function Ze(e) {
1302
+ var s;
1303
+ const t = Z(e.inputs["info:mdl:sourceAsset"]), n = e.inputs["info:mdl:sourceAsset:subIdentifier"];
1304
+ return ((s = t == null ? void 0 : t.replaceAll("\\", "/").split("/").at(-1)) == null ? void 0 : s.toLowerCase()) === "omniglass.mdl" && (n === void 0 || n === "OmniGlass");
1305
+ }
1306
+ function Gn(e, t, n) {
1307
+ const s = { applied: [], unsupported: /* @__PURE__ */ new Set() }, r = /* @__PURE__ */ new Set(["glass_color", "glass_ior", "frosting_roughness", "thin_walled", "reflection_color", "enable_opacity", "cutout_opacity", "opacity_constant", "opacity_threshold"]);
1308
+ for (const [m, _] of Object.entries(n.inputs)) {
1309
+ if (!m.startsWith("inputs:")) continue;
1310
+ const U = m.slice(7);
1311
+ r.has(U) || ["glass_color_texture", "roughness_texture", "normalmap_texture"].includes(U) && !Z(_) || s.unsupported.add(`OmniGlass.${U}`);
1312
+ }
1313
+ const p = (m) => (s.unsupported.add(`OmniGlass.${m}`), s);
1314
+ for (const m of r) if (j(n, m)) return p(`${m}.connection`);
1315
+ const d = C(n, ["glass_ior"]) ?? 1.491, f = C(n, ["frosting_roughness"]) ?? 0, a = N(n, ["thin_walled"]) ?? !1, o = N(n, ["glass_color"]) ?? [1, 1, 1], i = N(n, ["reflection_color"]) ?? [1, 1, 1];
1316
+ if (!Array.isArray(i) || i.length !== 3 || !i.every((m) => typeof m == "number" && Number.isFinite(m) && m >= 0 && m <= 1)) return p("reflection_color.range");
1317
+ if (N(n, ["glass_ior"]) !== void 0 && C(n, ["glass_ior"]) === null || d < 1 || d > 2.333) return p("glass_ior.range");
1318
+ if (N(n, ["frosting_roughness"]) !== void 0 && C(n, ["frosting_roughness"]) === null || f < 0 || f > 1) return p("frosting_roughness.range");
1319
+ if (typeof a != "boolean") return p("thin_walled.type");
1320
+ if (!Array.isArray(o) || o.length !== 3 || !o.every((m) => typeof m == "number" && Number.isFinite(m) && m >= 0 && m <= 1)) return p("glass_color.range");
1321
+ if (t.some((m) => !W(m))) return p("non-standard-loader-material");
1322
+ if (t.some((m) => W(m) && (m.map || m.alphaMap || m.roughnessMap || m.metalnessMap))) return p("existing-loader-texture-semantics");
1323
+ a || s.unsupported.add("OmniGlass.solid_volume_absorption"), a && o.some((m) => m !== 1) && s.unsupported.add("OmniGlass.tint_reflection_coupling"), !a && o.some((m) => m !== 1) && s.unsupported.add("OmniGlass.glass_color.volume");
1324
+ const l = N(n, ["enable_opacity"]) ?? !1;
1325
+ if (typeof l != "boolean") return p("enable_opacity.type");
1326
+ const h = C(n, ["cutout_opacity"]), y = C(n, ["opacity_constant"]);
1327
+ if (l && h !== null && y !== null && Math.abs(h - y) > 1e-6) return p("opacity.alias-conflict");
1328
+ for (const m of ["cutout_opacity", "opacity_constant", "opacity_threshold"]) if (l && N(n, [m]) !== void 0 && C(n, [m]) === null) return p(`${m}.type`);
1329
+ const c = l ? h ?? y ?? 1 : 1, u = l ? C(n, ["opacity_threshold"]) ?? 0 : 0;
1330
+ if (c < 0 || c > 1 || u < 0 || u > 1) return p("opacity.range");
1331
+ if (l && (Z(N(n, ["opacity_texture"])) || j(n, "opacity_texture"))) return p("opacity_texture");
1332
+ const S = u > 0 ? c >= u ? 1 : 0 : c, g = /* @__PURE__ */ new Map();
1333
+ for (const m of t) {
1334
+ const _ = m instanceof ie ? m : new ie();
1335
+ _ !== m && (qe.prototype.copy.call(_, m), _.defines = { STANDARD: "", PHYSICAL: "" }, g.set(m, _)), _.color.setRGB(...a ? o : [1, 1, 1]), _.specularColor.setRGB(...i), _.metalness = 0, _.roughness = f, _.ior = d, _.opacity = S, _.transparent = u === 0 && S < 1, _.alphaTest = u > 0 ? 0.5 : 0, _.transmission = 1, _.thickness = 0, _.depthWrite = !_.transparent, _.attenuationColor.setRGB(1, 1, 1), _.attenuationDistance = 1 / 0, _.needsUpdate = !0;
1336
+ }
1337
+ e.scene.traverse((m) => {
1338
+ m instanceof te && (m.material = Array.isArray(m.material) ? m.material.map((_) => g.get(_) ?? _) : g.get(m.material) ?? m.material);
1339
+ }), t.forEach((m, _) => {
1340
+ t[_] = g.get(m) ?? m;
1341
+ });
1342
+ for (const m of g.keys()) m.dispose();
1343
+ return s.applied.push("OmniGlass.reflection_color.specular-approximation", "OmniGlass.glass_ior", "OmniGlass.frosting_roughness", "OmniGlass.surface_transmission"), l && s.applied.push("OmniGlass.opacity.constant-coverage"), S > 0 && S < 1 && s.unsupported.add("OmniGlass.fractional_coverage_transmission_compositing"), a && s.applied.push("OmniGlass.thin_walled", "OmniGlass.glass_color.surface-approximation"), s;
1344
+ }
1345
+ async function Bn(e, t, n, s) {
1346
+ const r = [], p = ["normalmap_texture", "normalmap_texture_colorspace", "bump_factor", "flip_tangent_u", "flip_tangent_v"], d = () => p.forEach((u) => n.unsupported.delete(`OmniGlass.${u}`));
1347
+ if (p.some((u) => j(t, u))) return r;
1348
+ const f = Z(N(t, ["normalmap_texture"]));
1349
+ if (!f)
1350
+ return d(), r;
1351
+ const a = C(t, ["bump_factor"]) ?? 1;
1352
+ if (N(t, ["bump_factor"]) !== void 0 && C(t, ["bump_factor"]) === null || a < 0) return r;
1353
+ if (a === 0)
1354
+ return d(), r;
1355
+ const o = N(t, ["flip_tangent_u"]) ?? !1, i = N(t, ["flip_tangent_v"]) ?? !0;
1356
+ if (typeof o != "boolean" || typeof i != "boolean" || N(t, ["normalmap_texture_colorspace"]) !== "raw" || ["project_uvw", "world_or_object", "uv_space_index", "texture_scale", "texture_translate", "texture_rotate"].some((u) => j(t, u)) || !le(t, /* @__PURE__ */ new Set())) return r;
1357
+ const h = e.filter((u) => u instanceof ie);
1358
+ if (!h.length || h.some((u) => u.normalMap))
1359
+ return n.unsupported.add("OmniGlass.existing_normalMap"), r;
1360
+ const y = await se(f, s);
1361
+ if (r.push(y.report), !y.url) return r;
1362
+ let c = null;
1363
+ try {
1364
+ c = await (s.createTexture ?? oe)(y.url, K), c.colorSpace = K, c.wrapS = J, c.wrapT = J, c.channel = 0;
1365
+ for (const u of h)
1366
+ u.normalMap = c, u.normalScale.set(a * (o ? -1 : 1), a * (i ? -1 : 1)), u.needsUpdate = !0;
1367
+ d(), n.applied.push("OmniGlass.normalmap_texture", "OmniGlass.normal.tangent_convention"), c = null;
1368
+ } catch (u) {
1369
+ if (u instanceof Error && u.name === "AbortError") throw u;
1370
+ r[0] = { path: f, status: "decode-failed" };
1371
+ } finally {
1372
+ c == null || c.dispose();
1373
+ }
1374
+ return r;
1375
+ }
1376
+ async function Fn(e, t, n, s) {
1377
+ const r = [], p = Z(N(t, ["roughness_texture"]));
1378
+ if (!p) return r;
1379
+ const d = C(t, ["roughness_texture_influence"]) ?? 1;
1380
+ if (j(t, "roughness_texture_influence") || d < 0 || d > 1 || N(t, ["roughness_texture_influence"]) !== void 0 && C(t, ["roughness_texture_influence"]) === null) return r;
1381
+ if (d === 0)
1382
+ return n.unsupported.delete("OmniGlass.roughness_texture"), n.unsupported.delete("OmniGlass.roughness_texture_influence"), r;
1383
+ if (N(t, ["roughness_texture_colorspace"]) !== "raw" || ["project_uvw", "uv_space_index", "texture_scale", "texture_translate", "texture_rotate"].some((l) => j(t, l)) || !le(t, /* @__PURE__ */ new Set())) return r;
1384
+ const o = await se(p, s);
1385
+ if (r.push(o.report), !o.url) return r;
1386
+ let i = null;
1387
+ try {
1388
+ i = await (s.createTexture ?? oe)(o.url, K);
1389
+ const l = C(t, ["frosting_roughness"]) ?? 0, h = fe(i, "grayscale", d, l * (1 - d));
1390
+ h.wrapS = J, h.wrapT = J;
1391
+ for (const y of e) y instanceof ie && (y.roughnessMap = h, y.roughness = 1, y.needsUpdate = !0);
1392
+ n.applied.push("OmniGlass.roughness_texture.grayscale-linear-blend");
1393
+ for (const y of ["roughness_texture", "roughness_texture_influence", "roughness_texture_colorspace"]) n.unsupported.delete(`OmniGlass.${y}`);
1394
+ } catch (l) {
1395
+ if (l instanceof Error && l.name === "AbortError") throw l;
1396
+ n.unsupported.add("OmniGlass.roughness_texture.pixel-conversion");
1397
+ } finally {
1398
+ i == null || i.dispose();
1399
+ }
1400
+ return r;
1401
+ }
1402
+ function Ae(e) {
1403
+ var n;
1404
+ const t = Z(e.inputs["info:mdl:sourceAsset"]);
1405
+ return ((n = t == null ? void 0 : t.replaceAll("\\", "/").split("/").at(-1)) == null ? void 0 : n.toLowerCase()) === "omnipbr.mdl";
1406
+ }
1407
+ function xt(e) {
1408
+ return Ae(e) ? "OmniPBR" : Ze(e) ? "OmniGlass" : e.id;
1409
+ }
1410
+ function le(e, t) {
1411
+ const n = ct(e, "texture_scale", [1, 1]), s = ct(e, "texture_translate", [0, 0]), r = C(e, ["texture_rotate"]) ?? 0, p = ae(e, ["project_uvw"], !1), d = C(e, ["uv_space_index"]) ?? 0, f = !p && d === 0 && n[0] === 1 && n[1] === 1 && s[0] === 0 && s[1] === 0 && r === 0;
1412
+ return f || t.add("OmniPBR.uvTransform"), f;
1413
+ }
1414
+ async function kn(e, t, n, s, r, p) {
1415
+ const d = () => {
1416
+ for (const y of ["ao_texture", "ao_texture_colorspace", "ao_to_diffuse"]) s.delete(`OmniPBR.${y}`);
1417
+ };
1418
+ if (j(t, "ao_to_diffuse"))
1419
+ return s.add("OmniPBR.ao_to_diffuse.connection"), !1;
1420
+ const f = C(t, ["ao_to_diffuse"]) ?? 0;
1421
+ if (N(t, ["ao_to_diffuse"]) !== void 0 && C(t, ["ao_to_diffuse"]) === null || f < 0 || f > 1)
1422
+ return s.add("OmniPBR.ao_to_diffuse.range"), !1;
1423
+ if (f === 0)
1424
+ return d(), !1;
1425
+ if (j(t, "enable_ORM_texture"))
1426
+ return s.add("OmniPBR.enable_ORM_texture.connection"), !1;
1427
+ const a = ae(t, ["enable_ORM_texture"], !1), o = a ? "ORM_texture" : "ao_texture";
1428
+ if (j(t, o))
1429
+ return s.add(`OmniPBR.${o}.connection`), !1;
1430
+ const i = Z(N(t, [o]));
1431
+ if (!i)
1432
+ return d(), !1;
1433
+ if (N(t, [`${o}_colorspace`]) !== "raw")
1434
+ return s.add(`OmniPBR.${o}_colorspace`), !1;
1435
+ if (!le(t, s)) return !1;
1436
+ const l = await se(i, p);
1437
+ if (r.push(l.report), !l.url) return !1;
1438
+ let h = null;
1439
+ try {
1440
+ h = await (p.createTexture ?? oe)(l.url, K);
1441
+ const y = fe(h, a ? "r" : "grayscale");
1442
+ y.wrapS = J, y.wrapT = J, y.channel = 0;
1443
+ const c = e.filter(W).filter((u) => !u.aoMap);
1444
+ if (!c.length)
1445
+ return y.dispose(), s.add("OmniPBR.existing_aoMap"), !1;
1446
+ for (const u of c)
1447
+ u.aoMap = y, u.aoMapIntensity = f, u.needsUpdate = !0;
1448
+ return d(), n.push(a ? "OmniPBR.ORM.r.aoMap" : "OmniPBR.ao_texture.aoMap"), p.diagnostics.approximations.push({ code: "USD_VISUAL_AO_LIGHTING_APPROXIMATION", source: "usd-visual", message: `USD 材质 AO 已映射为 Three.js 间接光遮蔽(${t.path});并非 OmniPBR 对漫反射贴图的等价调制。` }), !0;
1449
+ } catch (y) {
1450
+ if (y instanceof Error && y.name === "AbortError") throw y;
1451
+ return s.add(`OmniPBR.${o}.pixel-conversion`), !1;
1452
+ } finally {
1453
+ h == null || h.dispose();
1454
+ }
1455
+ }
1456
+ function Vn(e, t) {
1457
+ const n = /* @__PURE__ */ new Set([
1458
+ "inputs:diffuse_color_constant",
1459
+ "inputs:diffuse_texture",
1460
+ "inputs:reflection_roughness_constant",
1461
+ "inputs:metallic_constant",
1462
+ "inputs:opacity_constant",
1463
+ "inputs:enable_opacity",
1464
+ "inputs:enable_emission",
1465
+ "inputs:emissive_color",
1466
+ "inputs:emissive_intensity",
1467
+ "inputs:texture_scale",
1468
+ "inputs:texture_translate",
1469
+ "inputs:texture_rotate",
1470
+ "inputs:project_uvw",
1471
+ "inputs:uv_space_index",
1472
+ "info:mdl:sourceAsset",
1473
+ "inputs:enable_ORM_texture",
1474
+ "inputs:ORM_texture",
1475
+ "inputs:metallic_texture_influence",
1476
+ "inputs:reflection_roughness_texture_influence",
1477
+ "inputs:ao_to_diffuse",
1478
+ "inputs:diffuse_tint",
1479
+ "inputs:normalmap_texture",
1480
+ "inputs:bump_factor",
1481
+ "inputs:flip_tangent_u",
1482
+ "inputs:flip_tangent_v",
1483
+ "inputs:reflectionroughness_texture",
1484
+ "inputs:metallic_texture",
1485
+ "inputs:opacity_texture"
1486
+ ]);
1487
+ (C(e, ["specular_level"]) ?? 0.5) !== 0.5 && t.add("OmniPBR.specular_level"), n.add("inputs:specular_level");
1488
+ const s = /* @__PURE__ */ new Set(["inputs:opacity_mode", "inputs:opacity_threshold", "inputs:enable_opacity_texture"]);
1489
+ ae(e, ["enable_emission"], !1) && t.add("OmniPBR.emission_radiometric_equivalence");
1490
+ const r = {
1491
+ "inputs:albedo_desaturation": 0,
1492
+ "inputs:albedo_add": 0,
1493
+ "inputs:albedo_brightness": 1,
1494
+ "inputs:world_or_object": !1
1495
+ };
1496
+ for (const p of Object.keys(e.inputs))
1497
+ p in r && e.inputs[p] === r[p] || !n.has(p) && !s.has(p) && t.add(`OmniPBR.${p.replace(/^inputs:/, "")}`);
1498
+ }
1499
+ function jn(e, t, n) {
1500
+ let s = !1;
1501
+ const r = Ae(t), p = Le(t, ["diffuseColor", "baseColor", "base_color", "diffuse_color_constant"]), d = C(t, ["roughness", "specularRoughness", "specular_roughness", "reflection_roughness_constant"]) ?? (r ? 0.5 : null), f = C(t, ["metallic", "metalness", "metallicFactor", "metallic_constant"]) ?? (r ? 0 : null), a = C(t, ["opacity_threshold"]) ?? 0, o = ae(t, ["enable_opacity"], !1) && a >= 0, i = C(t, ["opacity", "presence", "opacity_constant"]) ?? (r ? 1 : null), l = r ? o ? a > 0 ? i >= a ? 1 : 0 : i : 1 : i, h = ae(t, ["enable_emission"], !r), y = h ? Le(t, ["emissiveColor", "emissionColor", "emission_color", "emissive_color"]) : null;
1502
+ for (const c of e)
1503
+ W(c) && (p && (c.color.copy(p), s = !0), d !== null && (c.roughness = xe(d), s = !0), f !== null && (c.metalness = xe(f), s = !0), l !== null && (c.opacity = xe(l), c.transparent = c.opacity < 1, c.depthWrite = c.opacity >= 1, s = !0), r && !h && (c.emissive.setRGB(0, 0, 0), c.emissiveIntensity = 0), y && (c.emissive.copy(y), r && (c.emissiveIntensity = Math.max(0, C(t, ["emissive_intensity"]) ?? 40)), s = !0), s && (c.needsUpdate = !0));
1504
+ return p && n.push("diffuseColor.constant"), d !== null && n.push("roughness.constant"), f !== null && n.push("metalness.constant"), l !== null && n.push("opacity.constant"), y && n.push("emissiveColor.constant"), s;
1505
+ }
1506
+ function zn(e, t, n) {
1507
+ const s = /* @__PURE__ */ new Set(), r = (p) => {
1508
+ if (s.has(p.path)) return;
1509
+ s.add(p.path);
1510
+ const d = me(e, p);
1511
+ if (!d) {
1512
+ n.add(p.path);
1513
+ return;
1514
+ }
1515
+ if (!Et(d)) {
1516
+ n.add(d.id ?? d.path);
1517
+ for (const [f, a] of Object.entries(d.inputs)) {
1518
+ if (!f.endsWith(".resolvedConnect") && !f.endsWith(".connect")) continue;
1519
+ const o = Ye(a);
1520
+ o && r(o);
1521
+ }
1522
+ }
1523
+ };
1524
+ for (const [p, d] of Object.entries(t.inputs)) {
1525
+ if (!p.endsWith(".resolvedConnect") && !p.endsWith(".connect") || /(?:diffuseColor|baseColor)/i.test(p)) continue;
1526
+ const f = Ye(d);
1527
+ f && r(f);
1528
+ }
1529
+ }
1530
+ async function se(e, t) {
1531
+ if (t.isTextureAllowed && !t.isTextureAllowed(e)) return { report: { path: e, status: "unresolved" }, url: null };
1532
+ const n = Ft(t.entryDirectory ? `${t.entryDirectory}/${e}` : e);
1533
+ let s = t.files.find(e, t.entryDirectory ?? "") ?? t.files.find(n);
1534
+ if (!s)
1535
+ try {
1536
+ await t.files.ensure(n), s = t.files.find(n) ?? t.files.find(e, t.entryDirectory ?? "");
1537
+ } catch (r) {
1538
+ const p = r == null ? void 0 : r.code;
1539
+ if (r instanceof Error && r.name === "AbortError" || p === "E_ASSET_AUTH") throw r;
1540
+ const d = p === "E_ASSET_RESOURCE_NOT_FOUND" || /\((404|410)\)/.test(String(r));
1541
+ return { report: { path: e, status: d ? "missing" : "unresolved" }, url: null };
1542
+ }
1543
+ return s ? In.has(Yn(e)) ? { report: { path: e, status: "available" }, url: t.files.objectUrl(s) } : { report: { path: e, status: "unsupported-format" }, url: null } : { report: { path: e, status: "unresolved" }, url: null };
1544
+ }
1545
+ function We(e, t, n, s, r, p, d) {
1546
+ d === "augmented" && e.approximations.push({
1547
+ code: "USD_VISUAL_MATERIAL_AUGMENTED",
1548
+ message: `USD 材质 ${t}(${xt(n) ?? "renderer-specific shader"})已通过视觉适配层映射资产明确提供的输入:${Se(s).join(", ")}。这是有限范围的材质映射,不保证与原渲染器完全等价;原始 Loader 诊断保留在 visualAdaptation 报告中。`,
1549
+ source: "usd-visual"
1550
+ });
1551
+ for (const a of p)
1552
+ a.status === "missing" && e.warnings.push({
1553
+ code: "USD_VISUAL_RESOURCE_MISSING",
1554
+ message: `USD 材质资源缺失:${a.path}(${t})。未生成替代内容。`,
1555
+ source: "usd-visual"
1556
+ }), a.status === "unsupported-format" && e.droppedFeatures.push({
1557
+ code: "USD_VISUAL_TEXTURE_FORMAT_UNSUPPORTED",
1558
+ message: `USD 材质纹理格式无法由浏览器直接消费:${a.path}(${t})。需要离线确定性转码。`,
1559
+ source: "usd-visual"
1560
+ }), a.status === "decode-failed" && e.warnings.push({
1561
+ code: "USD_VISUAL_TEXTURE_DECODE_FAILED",
1562
+ message: `USD 纹理解码失败:${a.path}(${t})。保留原材质。`,
1563
+ source: "usd-visual"
1564
+ }), a.status === "unresolved" && e.warnings.push({
1565
+ code: "USD_VISUAL_RESOURCE_UNRESOLVED",
1566
+ message: `无法确认 USD 材质资源是否可用:${a.path}(${t})。未生成替代内容。`,
1567
+ source: "usd-visual"
1568
+ });
1569
+ const f = {
1570
+ "OmniGlass.solid_volume_absorption": "实体玻璃目前仅渲染表面透射:缺少可靠的内部光程,未实现体积吸收。未推断或生成壁厚",
1571
+ "OmniGlass.glass_color.volume": "源玻璃颜色用于体积吸收,当前未还原该体积颜色;未用表面染色替代",
1572
+ "OmniGlass.depth": "源 depth 是体积吸收缩放,不能直接当作 Three.js 壁厚或衰减距离;此输入尚未映射",
1573
+ "OmniGlass.fractional_coverage_transmission_compositing": "覆盖率与透射参数已映射,但其组合使用实时合成近似,不保证与 MDL 渲染等价",
1574
+ "OmniGlass.tint_reflection_coupling": "薄壁玻璃颜色已作表面近似,其反射与透射颜色响应不保证与 MDL 等价"
1575
+ };
1576
+ for (const a of r) e.droppedFeatures.push({
1577
+ code: "USD_VISUAL_SHADER_NODE_UNSUPPORTED",
1578
+ message: f[a] ? `USD 材质 ${t}:${f[a]}。` : `USD 材质功能或节点 ${a} 尚未完成浏览器适配(${t})。未生成替代内容。`,
1579
+ source: "usd-visual"
1580
+ });
1581
+ }
1582
+ function Wn(e) {
1583
+ const t = N(e, ["filename", "file"]), n = Z(t);
1584
+ return n ? { shader: e, path: n } : null;
1585
+ }
1586
+ function j(e, t) {
1587
+ return Ye(e.inputs[`inputs:${t}.resolvedConnect`] ?? e.inputs[`inputs:${t}.connect`]);
1588
+ }
1589
+ function Ye(e) {
1590
+ const t = Array.isArray(e) ? e[0] : e;
1591
+ if (typeof t != "string") return null;
1592
+ const n = /^(.*?)(?:\.outputs:([^/]+))?$/.exec(t);
1593
+ return n ? { path: n[1], outputName: n[2] ?? null } : null;
1594
+ }
1595
+ function me(e, t) {
1596
+ return e.shaders.find((n) => n.path === t.path) ?? null;
1597
+ }
1598
+ function Et(e) {
1599
+ return e.id === "PxrTexture";
1600
+ }
1601
+ function W(e) {
1602
+ return e instanceof qe || e instanceof ie;
1603
+ }
1604
+ async function oe(e, t) {
1605
+ const n = await new yt().loadAsync(e);
1606
+ return n.colorSpace = t, n.flipY = !0, n;
1607
+ }
1608
+ function Le(e, t) {
1609
+ const n = N(e, t);
1610
+ if (!Array.isArray(n) || n.length < 3) return null;
1611
+ const s = n.slice(0, 3);
1612
+ return s.every((r) => typeof r == "number" && Number.isFinite(r)) ? new mt(s[0], s[1], s[2]) : null;
1613
+ }
1614
+ function ae(e, t, n) {
1615
+ const s = N(e, t);
1616
+ return typeof s == "boolean" ? s : n;
1617
+ }
1618
+ function ct(e, t, n) {
1619
+ const s = N(e, [t]);
1620
+ return Array.isArray(s) && s.length >= 2 && s.slice(0, 2).every((r) => typeof r == "number" && Number.isFinite(r)) ? [s[0], s[1]] : n;
1621
+ }
1622
+ function C(e, t) {
1623
+ const n = N(e, t), s = typeof n == "number" ? n : Number.NaN;
1624
+ return Number.isFinite(s) ? s : null;
1625
+ }
1626
+ function N(e, t) {
1627
+ for (const n of t) {
1628
+ if (j(e, n)) return;
1629
+ const s = e.inputs[`inputs:${n}`];
1630
+ if (s !== void 0) return s;
1631
+ }
1632
+ }
1633
+ function Z(e) {
1634
+ if (typeof e == "string") return e;
1635
+ if (!e || typeof e != "object") return null;
1636
+ for (const t of ["path", "resolvedPath", "url"]) {
1637
+ const n = e[t];
1638
+ if (typeof n == "string" && n) return n;
1639
+ }
1640
+ return null;
1641
+ }
1642
+ function ut(e, t) {
1643
+ return e.data.elements.some((n) => n.material === t && n.geometry.displayColor !== null);
1644
+ }
1645
+ function Yn(e) {
1646
+ var t, n;
1647
+ return ((n = (t = e.split(/[?#]/, 1)[0]) == null ? void 0 : t.split(".").pop()) == null ? void 0 : n.toLowerCase()) ?? "";
1648
+ }
1649
+ function xe(e) {
1650
+ return Math.min(1, Math.max(0, e));
1651
+ }
1652
+ function Oe(e) {
1653
+ return Array.isArray(e) ? e.filter(He) : [];
1654
+ }
1655
+ function he(e) {
1656
+ return typeof e == "string" && e ? e : null;
1657
+ }
1658
+ function He(e) {
1659
+ return typeof e == "string" && e.length > 0;
1660
+ }
1661
+ function Se(e) {
1662
+ return [...new Set(e)];
1663
+ }
1664
+ const lt = /* @__PURE__ */ new Map();
1665
+ function Hn(e) {
1666
+ const t = e ?? "";
1667
+ let n = lt.get(t);
1668
+ return n || (n = hn(xn(e)), lt.set(t, n)), n;
1669
+ }
1670
+ async function mr(e, t, n) {
1671
+ var D;
1672
+ const s = n.hasLocalFiles(), r = e.entryPath ?? e.filename ?? "asset.usd", p = s ? r : await ar(e, r), d = s ? n.getBlob(r) : await ir(e), f = r.split("/").pop() || "asset.usd", a = r.split("/").slice(0, -1).join("/"), o = t.options.usdExternalReferenceMode ?? "package", i = new URL(p, "file:///"), l = zt(), h = /* @__PURE__ */ new Set(), y = (E) => {
1673
+ h.has(E) || (h.add(E), l.warnings.push({ code: "USD_EXTERNAL_REFERENCE_SKIPPED", message: `资产包模式已跳过包外 USD 资源:${E}。包内内容继续加载;完整模式可尝试加载该资源。`, source: "usd-resources" }));
1674
+ }, c = (E) => {
1675
+ if (n.find(E, r) || o === "complete") return !0;
1676
+ const I = !s && Je(new URL(E, i), i);
1677
+ return I || y(E), I;
1678
+ }, u = /* @__PURE__ */ new Set(), S = (E, I) => {
1679
+ if (u.has(E)) return;
1680
+ u.add(E);
1681
+ const w = Qt(I);
1682
+ l.warnings.push({
1683
+ code: w === "invalid" ? "USD_VISUAL_RESOURCE_INVALID" : w === "unavailable" ? "USD_VISUAL_RESOURCE_UNAVAILABLE" : "USD_VISUAL_RESOURCE_MISSING",
1684
+ message: `USD 视觉资源不可用:${E}`,
1685
+ source: "usd-resources"
1686
+ });
1687
+ }, { parseAsync: g } = await Hn(t.options.openUsdBaseUrl), m = Xn(t.requestRender);
1688
+ let _ = null, U = null, x = null, A = null;
1689
+ try {
1690
+ if (_ = await g(d, {
1691
+ sourcePath: p,
1692
+ fileName: f,
1693
+ files: s ? n.asSourceRecord(a, !0) : void 0,
1694
+ // The viewer default is the package boundary, not the source kind:
1695
+ // package-local layers/textures are discovered for both File and URL
1696
+ // inputs, while package-external references are filtered before reading.
1697
+ // Complete mode discovers all references. If the host supplied a
1698
+ // resolver, files.ensure() remains the only path to external bytes and
1699
+ // therefore the resolver remains authoritative; without one it falls
1700
+ // through to the source base URL and direct browser fetch.
1701
+ autoResolveAssets: !0,
1702
+ externalReferenceMode: o,
1703
+ onReferenceSkipped: y,
1704
+ onResourceFailed: S,
1705
+ isTextureAllowed: (P) => c(P) && !!n.find(P, r),
1706
+ resolveBytes: async (P, O) => {
1707
+ const B = n.find(O, r);
1708
+ return B ? n.bytes(B) : (await n.ensure(O), n.bytes(O));
1709
+ },
1710
+ textureResolver: (P) => {
1711
+ for (const O of [P.resolvedPath, P.path, P.url]) {
1712
+ if (!O) continue;
1713
+ const B = n.objectUrlIfPresent(O, a);
1714
+ if (B) return B;
1715
+ }
1716
+ return null;
1717
+ },
1718
+ textureLoader: m
1719
+ }), t.signal.aborted) throw Ve();
1720
+ const E = or(_);
1721
+ _.scene.scale.multiplyScalar(E.metersPerUnit), _.data.stage.upAxis.toUpperCase() === "Y" && _.scene.quaternion.setFromAxisAngle(new L(1, 0, 0), Math.PI / 2), _.scene.updateMatrixWorld(!0);
1722
+ const I = _.data.physics.rigidBodies.filter((P) => P.enabled), w = Pt(_, I.map((P) => P.path)), v = await On(_, {
1723
+ files: n,
1724
+ entryDirectory: a,
1725
+ sourcePath: p,
1726
+ isLocalPackage: s,
1727
+ diagnostics: l,
1728
+ isTextureAllowed: t.format === "usdz" ? void 0 : c
1729
+ });
1730
+ if (t.signal.aborted) throw Ve();
1731
+ en(_);
1732
+ const M = Jn(l);
1733
+ I.some((P) => P.startsAsleep === !0) && l.droppedFeatures.push({ code: "E_USD_STARTS_ASLEEP", message: "USD startsAsleep 无法在 MuJoCo 初始化阶段保证完全等价,已按正常初始状态加载。", source: "usd-physics" });
1734
+ const $ = Vt({
1735
+ id: p,
1736
+ name: p.split("/").pop() ?? p,
1737
+ source: { format: "usd", uri: p },
1738
+ links: I.map((P) => ({ id: P.path, name: P.name, visuals: [], collisions: [] })),
1739
+ joints: w.flatMap((P) => P.body0 && P.body1 ? [{
1740
+ id: P.path,
1741
+ type: P.jointType,
1742
+ parent: P.body0,
1743
+ child: P.body1,
1744
+ origin: { position: P.localPos1.map((O) => O * E.metersPerUnit), rotationRpy: [0, 0, 0] },
1745
+ axis: Dt(P.axis).applyQuaternion(Ue(P.localRot1 ?? [1, 0, 0, 0])).toArray(),
1746
+ ...Number.isFinite(P.lowerLimit) && Number.isFinite(P.upperLimit) ? { limits: {
1747
+ lower: P.lowerLimit * (P.jointType === "revolute" ? Math.PI / 180 : E.metersPerUnit),
1748
+ upper: P.upperLimit * (P.jointType === "revolute" ? Math.PI / 180 : E.metersPerUnit)
1749
+ } } : {}
1750
+ }] : []),
1751
+ diagnostics: l,
1752
+ extension: { rigidBodyCount: I.length, jointCount: w.length, visualAdaptation: v }
1753
+ });
1754
+ if (I.length === 0) {
1755
+ pt(_);
1756
+ const P = dt(_, l), O = _.scene, B = _, k = qn(O, t.requestRender);
1757
+ return x = { root: O, sync() {
1758
+ }, dispose() {
1759
+ k == null || k.dispose(), B.dispose();
1760
+ } }, _ = null, ke($, x, !1, () => {
1761
+ }, void 0, void 0, P, M, k);
1762
+ }
1763
+ let z;
1764
+ try {
1765
+ z = nr(_, I.map((O) => O.path), E, w), (D = z.massOverrides) != null && D.length && l.approximations.push({ code: "USD_INFERRED_INERTIA", message: "保留显式总质量;惯量按碰撞几何的密度分布推导并同比缩放,重叠体积会重复计入。", source: "usd-physics" });
1766
+ const { MujocoRuntime: P } = await import("./mujoco-runtime-7xiBQNJm.js");
1767
+ U = new P(), await U.initialize(z, t.options.mujocoBaseUrl), t.signal.throwIfAborted();
1768
+ } catch (P) {
1769
+ const O = jt(P, t.signal, "usd-physics");
1770
+ U == null || U.dispose(), U = null, l.droppedFeatures.push(O), pt(_);
1771
+ const B = dt(_, l), k = _.scene, G = _;
1772
+ return x = { root: k, sync() {
1773
+ }, dispose() {
1774
+ G.dispose();
1775
+ } }, _ = null, ke($, x, !1, () => {
1776
+ }, void 0, O, B, M);
1777
+ }
1778
+ const Y = A = Qn(_, I.map((P) => P.path), l);
1779
+ if (t.signal.aborted) throw Ve();
1780
+ x = new rt(U, Y);
1781
+ const H = At(_, I.map((P) => P.path), l), b = H ? new rt(U, H) : void 0;
1782
+ A = null;
1783
+ const T = _, R = U, X = x;
1784
+ return _ = null, U = null, x = null, ke($, X, !0, () => {
1785
+ R.dispose(), T.dispose();
1786
+ }, R, void 0, b, M);
1787
+ } catch (E) {
1788
+ throw A && wt(A.root), x == null || x.dispose(), U == null || U.dispose(), _ == null || _.dispose(), E;
1789
+ }
1790
+ }
1791
+ function pt(e) {
1792
+ for (const t of e.index.boneHostsBySkeletonPath.values())
1793
+ t.matrix.copy(e.scene.matrixWorld).invert();
1794
+ e.scene.updateMatrixWorld(!0);
1795
+ }
1796
+ function Xn(e) {
1797
+ const n = [];
1798
+ let s = !1;
1799
+ const r = () => {
1800
+ if (s || n.length === 0) return;
1801
+ s = !0;
1802
+ const d = () => {
1803
+ var a;
1804
+ s = !1;
1805
+ let f = 0;
1806
+ for (; n.length; ) {
1807
+ const o = n[0];
1808
+ if (f > 0 && f + o.pixels > 4194304 || ((a = n.shift()) == null || a.apply(), f += o.pixels, f >= 4194304)) break;
1809
+ }
1810
+ n.length && r();
1811
+ };
1812
+ typeof requestAnimationFrame == "function" ? requestAnimationFrame(d) : setTimeout(d, 16);
1813
+ };
1814
+ class p extends yt {
1815
+ load(f, a, o, i) {
1816
+ const l = new ht();
1817
+ return setTimeout(() => {
1818
+ super.load(f, (h) => {
1819
+ var u, S;
1820
+ const y = ((u = h.image) == null ? void 0 : u.width) || 0, c = ((S = h.image) == null ? void 0 : S.height) || 0;
1821
+ n.push({ pixels: Math.max(1, y * c), apply: () => {
1822
+ l.image = h.image, l.source.needsUpdate = !0, l.needsUpdate = !0, h.dispose(), a == null || a(l), e();
1823
+ } }), r();
1824
+ }, o, i);
1825
+ }, 0), l;
1826
+ }
1827
+ }
1828
+ return new p();
1829
+ }
1830
+ function qn(e, t) {
1831
+ const n = e.animations ?? [];
1832
+ if (n.length === 0) return;
1833
+ const s = new Gt(e), r = n.map((p) => s.clipAction(p));
1834
+ for (const p of r) p.reset().setLoop(Bt, 1 / 0).play();
1835
+ return s.setTime(0), {
1836
+ step(p) {
1837
+ return p > 0 ? (s.update(p), t(), !0) : !1;
1838
+ },
1839
+ reset() {
1840
+ s.setTime(0), t();
1841
+ },
1842
+ dispose() {
1843
+ for (const p of r) p.stop();
1844
+ s.stopAllAction(), s.uncacheRoot(e);
1845
+ }
1846
+ };
1847
+ }
1848
+ function Jn(e) {
1849
+ const t = [
1850
+ "USD_VISUAL_RESOURCE_MISSING",
1851
+ "USD_VISUAL_RESOURCE_INVALID",
1852
+ "USD_VISUAL_RESOURCE_UNAVAILABLE",
1853
+ "USD_VISUAL_TEXTURE_FORMAT_UNSUPPORTED",
1854
+ "USD_VISUAL_RESOURCE_UNRESOLVED",
1855
+ "USD_VISUAL_TEXTURE_DECODE_FAILED",
1856
+ "USD_VISUAL_SHADER_NODE_UNSUPPORTED",
1857
+ "USD_VISUAL_LOADER_DIAGNOSTIC",
1858
+ "USD_VISUAL_TOPOLOGY_UNSUPPORTED",
1859
+ "USD_EXTERNAL_REFERENCE_SKIPPED"
1860
+ ], n = [...e.warnings, ...e.droppedFeatures, ...e.approximations];
1861
+ for (const s of t) {
1862
+ const r = n.find((p) => p.code === s);
1863
+ if (r) return r;
1864
+ }
1865
+ }
1866
+ function ke(e, t, n, s, r, p, d, f, a) {
1867
+ let o = !1;
1868
+ return {
1869
+ asset: e,
1870
+ binding: t,
1871
+ hasPhysics: n,
1872
+ hasAnimation: !!a,
1873
+ runtime: r,
1874
+ fallback: p,
1875
+ visualWarning: f,
1876
+ collision: d,
1877
+ step(i) {
1878
+ if (a) return a.step(i);
1879
+ if (!r) return !1;
1880
+ const l = r.step(i);
1881
+ return l && t.sync(), l;
1882
+ },
1883
+ reset() {
1884
+ if (a) {
1885
+ a.reset();
1886
+ return;
1887
+ }
1888
+ r == null || r.reset(), t.sync();
1889
+ },
1890
+ dispose() {
1891
+ o || (o = !0, d == null || d.dispose(), t.dispose(), s());
1892
+ }
1893
+ };
1894
+ }
1895
+ const Zn = /* @__PURE__ */ new Set([
1896
+ "E_USD_PHYSICS_UNSUPPORTED",
1897
+ "E_USD_UNBAKED_BODY_SCALE",
1898
+ "E_USD_INVALID_JOINT_REFERENCE",
1899
+ "E_USD_UNSUPPORTED_JOINT",
1900
+ "E_USD_MULTIPLE_PARENTS",
1901
+ "E_USD_JOINT_CYCLE",
1902
+ "E_USD_UNSUPPORTED_DRIVE",
1903
+ "E_USD_INVALID_MASS",
1904
+ "E_USD_PARTIAL_INERTIA",
1905
+ "E_USD_MISSING_COLLISION_GEOMETRY",
1906
+ "E_USD_UNREACHABLE_BODIES",
1907
+ "E_USD_MULTIPLE_PHYSICS_SCENES",
1908
+ "E_USD_NONUNIFORM_RADIAL_SCALE",
1909
+ "E_USD_UNSUPPORTED_GEOMETRY",
1910
+ "E_USD_CONSTRAINED_INITIAL_VELOCITY",
1911
+ "E_USD_UNSUPPORTED_APPROXIMATION"
1912
+ ]);
1913
+ function hr(e) {
1914
+ const t = Kn(e);
1915
+ return t !== null && Zn.has(t);
1916
+ }
1917
+ function Kn(e) {
1918
+ if (!e || typeof e != "object" || !("code" in e)) return null;
1919
+ const t = e.code;
1920
+ return typeof t == "string" ? t : null;
1921
+ }
1922
+ function Qn(e, t, n) {
1923
+ e.scene.updateMatrixWorld(!0);
1924
+ const s = new Ee();
1925
+ s.name = "USD simulation";
1926
+ const r = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map();
1927
+ for (const c of t) {
1928
+ const u = e.index.objectsByPath.get(c);
1929
+ if (!u) throw V(`USD rigid body node is missing: ${c}`, "E_USD_PHYSICS_UNSUPPORTED");
1930
+ const S = new Ee();
1931
+ S.name = c, s.add(S), r.set(c, S);
1932
+ const g = new L(), m = new ee();
1933
+ u.matrixWorld.decompose(g, m, new L()), p.set(c, new pe().compose(g, m, new L(1, 1, 1)));
1934
+ }
1935
+ const d = er(e, t, n), f = [], a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), l = (c, u) => {
1936
+ var U;
1937
+ const S = c.skeleton, g = S.bones.map((x) => x.uuid).join("|");
1938
+ let m = i.get(g), _;
1939
+ if (m)
1940
+ _ = S.bones.map((x) => o.get(x.uuid));
1941
+ else {
1942
+ m = new Ee(), m.name = `${c.name || "USD"}_BoneHost`, m.matrixAutoUpdate = !1;
1943
+ const x = (U = S.bones[0]) == null ? void 0 : U.parent;
1944
+ m.matrix.copy(u).multiply((x == null ? void 0 : x.matrixWorld) ?? new pe()), s.add(m), i.set(g, m), _ = S.bones.map((A) => {
1945
+ const D = A.clone(!1);
1946
+ return D.matrix.copy(A.matrix), D.matrixAutoUpdate = !1, o.set(A.uuid, D), D;
1947
+ });
1948
+ for (let A = 0; A < _.length; A++) {
1949
+ const D = S.bones[A].parent, E = S.bones.indexOf(D);
1950
+ (E >= 0 ? _[E] : m).add(_[A]);
1951
+ }
1952
+ }
1953
+ return new Ct(_, S.boneInverses.map((x) => x.clone()));
1954
+ };
1955
+ e.scene.traverse((c) => {
1956
+ var _;
1957
+ if (!(c instanceof te) || c.userData.usdPurposeExcluded) return;
1958
+ let u = c, S, g, m = !0;
1959
+ for (; u; ) {
1960
+ m && (m = u.visible);
1961
+ const U = (_ = u.userData.usd) == null ? void 0 : _.path;
1962
+ !g && U && (g = U), !S && U && r.has(U) && (S = U), u = u.parent;
1963
+ }
1964
+ !S && g && (S = d.get(vt(g))), m && f.push([c, S]);
1965
+ });
1966
+ for (const [c, u] of f) {
1967
+ const S = u ? p.get(u).clone().invert() : new pe(), g = c instanceof Ie ? new Ie(c.geometry.clone(), Array.isArray(c.material) ? c.material.map((m) => m.clone()) : c.material.clone()) : c.clone(!1);
1968
+ g.geometry = c.geometry.clone(), g.material = Array.isArray(c.material) ? c.material.map((m) => m.clone()) : c.material.clone(), g instanceof Ie && c instanceof Ie && (g.bindMode = c.bindMode, g.bindMatrix.copy(c.bindMatrix), g.bindMatrixInverse.copy(c.bindMatrixInverse), g.bind(l(c, S), g.bindMatrix), g.frustumCulled = !1), g.matrix.copy(S).multiply(c.matrixWorld), g.matrix.decompose(g.position, g.quaternion, g.scale), (u ? r.get(u) : s).add(g), a.set(c.uuid, g);
1969
+ }
1970
+ const y = (e.scene.animations ?? []).map((c) => {
1971
+ const u = c.clone();
1972
+ return u.tracks = u.tracks.map((S) => {
1973
+ const g = S.name.split(".", 1)[0], m = a.get(g) ?? o.get(g);
1974
+ return m && (S.name = `${m.uuid}${S.name.slice(g.length)}`), S;
1975
+ }), u;
1976
+ });
1977
+ return { root: s, bindings: r, expectedLinkCount: r.size, animations: y };
1978
+ }
1979
+ function er(e, t, n) {
1980
+ var a, o;
1981
+ const s = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map(), p = e.stage, d = e.pxr;
1982
+ if (!p || !((a = d == null ? void 0 : d.Sdf) != null && a.Path) || !((o = e.data.view) != null && o.prims)) return s;
1983
+ const f = new Set(e.data.view.prims.map((i) => i.path));
1984
+ for (const i of t) {
1985
+ const l = `${i}/Visual/`;
1986
+ for (const h of f) {
1987
+ if (!h.startsWith(l)) continue;
1988
+ const y = p.GetPrimAtPath(new d.Sdf.Path(h));
1989
+ try {
1990
+ const c = y.GetMetadata("references"), u = typeof c == "string" ? c : c == null ? void 0 : c.string;
1991
+ if (u == null) {
1992
+ n == null || n.warnings.push({ code: "USD_VISUAL_REFERENCE_MISSING", message: `刚体视觉节点缺少 reference:${h}`, source: "usd-visual-binding" });
1993
+ continue;
1994
+ }
1995
+ const S = tr(u);
1996
+ if (!S) {
1997
+ n == null || n.warnings.push({ code: "USD_VISUAL_REFERENCE_UNRESOLVED", message: `无法解析视觉引用元数据:${h}`, source: "usd-visual-binding" });
1998
+ continue;
1999
+ }
2000
+ if (!S.primPath) continue;
2001
+ const g = vt(S.primPath), m = r.get(g);
2002
+ if (m && m.owner !== i)
2003
+ throw V(`USD visual reference maps to multiple rigid bodies: ${S.primPath} -> ${m.owner}, ${i}`, "E_USD_VISUAL_REFERENCE_AMBIGUOUS");
2004
+ r.set(g, { owner: i, target: S.primPath }), s.set(g, i);
2005
+ } finally {
2006
+ y.delete();
2007
+ }
2008
+ }
2009
+ }
2010
+ return s;
2011
+ }
2012
+ function tr(e) {
2013
+ var n, s;
2014
+ const t = e.match(/SdfReference\(([^,]*),\s*(?:(\/[^,\)]+),\s*)?SdfLayerOffset/);
2015
+ return t ? { identifier: ((n = t[1]) == null ? void 0 : n.trim()) ?? "", primPath: ((s = t[2]) == null ? void 0 : s.trim()) ?? null } : null;
2016
+ }
2017
+ function vt(e) {
2018
+ const t = e.replaceAll("\\", "/");
2019
+ for (const n of ["/Geometry/", "/Visual/"]) {
2020
+ const s = t.indexOf(n);
2021
+ if (s >= 0) return t.slice(s + n.length);
2022
+ }
2023
+ return t;
2024
+ }
2025
+ function At(e, t, n) {
2026
+ e.scene.updateMatrixWorld(!0);
2027
+ const s = new Ee();
2028
+ s.name = "USD authored collisions";
2029
+ const r = kt(), p = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map();
2030
+ for (const a of t) {
2031
+ const o = e.index.objectsByPath.get(a);
2032
+ if (!o) continue;
2033
+ const i = new L(), l = new ee();
2034
+ o.matrixWorld.decompose(i, l, new L()), d.set(a, new pe().compose(i, l, new L(1, 1, 1)));
2035
+ const h = new Ee();
2036
+ h.name = a, h.position.copy(i), h.quaternion.copy(l), p.set(a, h), s.add(h);
2037
+ }
2038
+ let f = 0;
2039
+ for (const a of e.data.physics.colliders) {
2040
+ if (!a.enabled) continue;
2041
+ const o = e.index.objectsByPath.get(a.path);
2042
+ if (!o) continue;
2043
+ const i = a.bodyPath && p.has(a.bodyPath) ? a.bodyPath : null, l = i ? p.get(i) : s, h = i ? d.get(i) : new pe(), y = [];
2044
+ if (o.traverse((g) => {
2045
+ g instanceof te && y.push(g);
2046
+ }), y.length === 0) continue;
2047
+ const c = String(a.typeName ?? o.type).toLowerCase(), u = c.includes("mesh") ? a.approximation ?? "none" : null;
2048
+ if (u === "convexDecomposition" || u === "meshSimplification") {
2049
+ n == null || n.droppedFeatures.push({
2050
+ code: "E_USD_COLLISION_DEBUG_APPROXIMATION_UNAVAILABLE",
2051
+ message: `USD collider ${a.path} 使用 ${u},但资产未提供可唯一还原的最终代理几何。`,
2052
+ source: "usd-collision-debug"
2053
+ });
2054
+ continue;
2055
+ }
2056
+ if (c.includes("mesh") && u !== "none") {
2057
+ const g = [], m = h.clone().invert();
2058
+ for (const _ of y) {
2059
+ const U = m.clone().multiply(_.matrixWorld), x = _.geometry.getAttribute("position");
2060
+ for (let A = 0; A < x.count; A += 1) g.push(new L().fromBufferAttribute(x, A).applyMatrix4(U));
2061
+ }
2062
+ if (g.length >= 4 && u === "convexHull") {
2063
+ const _ = new Wt(g), U = Me(_, r, "mesh");
2064
+ _.dispose(), U.name = `Collision:${a.path}`, U.userData.usdColliderPath = a.path, l.add(U), f += 1;
2065
+ } else if (g.length > 0 && u === "boundingSphere") {
2066
+ const U = new Ne().setFromPoints(g).getBoundingSphere(new Nt()), x = new $t(U.radius, 24, 16);
2067
+ x.translate(U.center.x, U.center.y, U.center.z);
2068
+ const A = Me(x, r, "feature");
2069
+ x.dispose(), A.name = `Collision:${a.path}`, A.userData.usdColliderPath = a.path, l.add(A), f += 1;
2070
+ } else if (g.length > 0 && u === "boundingCube") {
2071
+ const _ = new Ne().setFromPoints(g), U = _.getSize(new L()), x = _.getCenter(new L()), A = new Lt(U.x, U.y, U.z);
2072
+ A.translate(x.x, x.y, x.z);
2073
+ const D = Me(A, r, "feature");
2074
+ A.dispose(), D.name = `Collision:${a.path}`, D.userData.usdColliderPath = a.path, l.add(D), f += 1;
2075
+ } else ["convexHull", "boundingSphere", "boundingCube"].includes(String(u)) || n == null || n.droppedFeatures.push({
2076
+ code: "E_USD_COLLISION_DEBUG_APPROXIMATION_UNAVAILABLE",
2077
+ message: `USD collider ${a.path} 使用未知 approximation=${u}。`,
2078
+ source: "usd-collision-debug"
2079
+ });
2080
+ continue;
2081
+ }
2082
+ const S = c.includes("mesh") ? "mesh" : "feature";
2083
+ for (const g of y) {
2084
+ const m = Me(g.geometry, r, S);
2085
+ m.name = `Collision:${a.path}`, m.matrixAutoUpdate = !1, m.matrix.copy(h).invert().multiply(g.matrixWorld), m.userData.usdColliderPath = a.path, l.add(m), f += 1;
2086
+ }
2087
+ }
2088
+ if (f === 0) {
2089
+ r.dispose();
2090
+ return;
2091
+ }
2092
+ return { root: s, bindings: p, expectedLinkCount: p.size };
2093
+ }
2094
+ function dt(e, t) {
2095
+ const n = At(e, [], t);
2096
+ if (n)
2097
+ return n.root.visible = !1, { root: n.root, sync() {
2098
+ }, dispose() {
2099
+ n.root.removeFromParent(), wt(n.root);
2100
+ } };
2101
+ }
2102
+ function Pt(e, t) {
2103
+ e.scene.updateMatrixWorld(!0);
2104
+ const n = new Set(t);
2105
+ return e.data.joints.filter((s) => s.enabled).map((s) => {
2106
+ const r = { ...s };
2107
+ for (const p of [0, 1]) {
2108
+ const d = p === 0 ? "body0" : "body1", f = p === 0 ? "localPos0" : "localPos1", a = p === 0 ? "localRot0" : "localRot1", o = s[d];
2109
+ if (!o) continue;
2110
+ let i = o;
2111
+ for (; i && !e.index.rigidBodiesByPath.has(i); )
2112
+ i = i.slice(0, i.lastIndexOf("/"));
2113
+ if (i && !n.has(i))
2114
+ throw V(`USD joint references an unknown or disabled rigid body: ${s.path} (${o})`, "E_USD_INVALID_JOINT_REFERENCE");
2115
+ const l = e.index.objectsByPath.get(o), h = i ? e.index.objectsByPath.get(i) : e.scene;
2116
+ if (!l || !h)
2117
+ throw V(`USD joint target node is missing: ${s.path} (${o})`, "E_USD_INVALID_JOINT_REFERENCE");
2118
+ if (i === o) continue;
2119
+ const y = h.matrixWorld.clone().invert().multiply(l.matrixWorld), c = new L(), u = new ee(), S = new L();
2120
+ y.decompose(c, u, S);
2121
+ const g = new pe().compose(c, u, new L(1, 1, 1));
2122
+ if (y.elements.some((_, U) => Math.abs(_ - g.elements[U]) > 1e-5))
2123
+ throw V(`USD joint target has unsupported scale or shear: ${s.path} (${o})`, "E_USD_PHYSICS_UNSUPPORTED");
2124
+ r[d] = i || null, r[f] = new L(...s[f]).applyMatrix4(y).toArray();
2125
+ const m = u.multiply(Ue(s[a] ?? [1, 0, 0, 0])).normalize();
2126
+ r[a] = [m.w, m.x, m.y, m.z];
2127
+ }
2128
+ return r;
2129
+ });
2130
+ }
2131
+ function nr(e, t, n, s = Pt(e, t)) {
2132
+ e.scene.updateMatrixWorld(!0);
2133
+ const r = [], p = [], d = [], f = [], a = [], o = [], i = [], { metersPerUnit: l, kilogramsPerUnit: h } = n, y = new Map(t.map((w) => {
2134
+ const v = e.index.rigidBodiesByPath.get(w);
2135
+ if (!v) throw V(`USD rigid body metadata is missing: ${w}`, "E_USD_PHYSICS_UNSUPPORTED");
2136
+ return [w, v];
2137
+ })), c = /* @__PURE__ */ new Map();
2138
+ for (const w of y.keys()) {
2139
+ const v = e.index.objectsByPath.get(w);
2140
+ if (!v) throw V(`USD rigid body node is missing: ${w}`, "E_USD_PHYSICS_UNSUPPORTED");
2141
+ const M = new L(), $ = new ee(), z = new L();
2142
+ if (v.matrixWorld.decompose(M, $, z), z.clone().divideScalar(l).toArray().some((H) => Math.abs(Math.abs(H) - 1) > 1e-5))
2143
+ throw V(`USD rigid body has unbaked scale: ${w}`, "E_USD_UNBAKED_BODY_SCALE");
2144
+ c.set(w, new pe().compose(M, $, new L(1, 1, 1)));
2145
+ }
2146
+ const u = /* @__PURE__ */ new Map();
2147
+ for (const w of s) {
2148
+ if (!w.body1 || !y.has(w.body1) || w.body0 && !y.has(w.body0))
2149
+ throw V(`USD joint references an unknown rigid body: ${w.path}`, "E_USD_INVALID_JOINT_REFERENCE");
2150
+ if (!["fixed", "revolute", "prismatic"].includes(w.jointType))
2151
+ throw V(`Unsupported USD joint type ${w.jointType}: ${w.path}`, "E_USD_UNSUPPORTED_JOINT");
2152
+ if (u.has(w.body1)) throw V(`USD rigid body has multiple parent joints: ${w.body1}`, "E_USD_MULTIPLE_PARENTS");
2153
+ u.set(w.body1, w), w.body0 && w.collisionEnabled !== !0 && d.push(`<exclude body1="${we(w.body0)}" body2="${we(w.body1)}"/>`);
2154
+ }
2155
+ let S = 0;
2156
+ const g = /* @__PURE__ */ new Set(), m = (w, v = new pe()) => {
2157
+ var O, B, k, G, ce;
2158
+ if (g.has(w)) throw V(`USD joint graph contains a cycle at ${w}`, "E_USD_JOINT_CYCLE");
2159
+ g.add(w);
2160
+ const M = y.get(w), $ = c.get(w), z = v.clone().invert().multiply($), Y = new L(), H = new ee();
2161
+ z.decompose(Y, H, new L());
2162
+ const b = u.get(w), T = [`<body name="${we(w)}" pos="${Q(Y.toArray())}" quat="${be(H)}">`];
2163
+ if (!b && !M.kinematicEnabled && T.push("<freejoint/>"), b && [...M.velocity ?? [], ...M.angularVelocity ?? []].some((F) => F !== 0))
2164
+ throw V(`Constrained USD initial velocity cannot be projected reliably: ${w}`, "E_USD_CONSTRAINED_INITIAL_VELOCITY");
2165
+ if (!b && !M.kinematicEnabled) {
2166
+ const F = new L(...M.velocity ?? [0, 0, 0]).multiplyScalar(l).applyQuaternion(e.scene.quaternion), q = new L(...M.angularVelocity ?? [0, 0, 0]).multiplyScalar(Math.PI / 180).applyQuaternion(e.scene.quaternion).applyQuaternion(new ee().setFromRotationMatrix($).invert());
2167
+ i.push({ body: w, velocity: [...F.toArray(), ...q.toArray()] });
2168
+ }
2169
+ if (b && b.jointType !== "fixed") {
2170
+ const F = b.jointType === "revolute" ? "hinge" : "slide", q = Dt(b.axis).applyQuaternion(Ue(b.localRot1 ?? [1, 0, 0, 0])), ne = F === "hinge" ? Math.PI / 180 : l, ye = b.body0 ? v : e.scene.matrixWorld.clone();
2171
+ if (!b.body0) {
2172
+ const re = new L(), _e = new ee();
2173
+ ye.decompose(re, _e, new L()), ye.compose(re, _e, new L(1, 1, 1));
2174
+ }
2175
+ const Ce = new ee().setFromRotationMatrix(ye), Pe = new ee().setFromRotationMatrix($), ge = Ce.clone().multiply(Ue(b.localRot0 ?? [1, 0, 0, 0])).invert().multiply(Pe).multiply(Ue(b.localRot1 ?? [1, 0, 0, 0]));
2176
+ let de = 0;
2177
+ if (F === "hinge") {
2178
+ const re = b.axis === "Y" ? ge.y : b.axis === "Z" ? ge.z : ge.x;
2179
+ de = 2 * Math.atan2(re, ge.w), de = Math.atan2(Math.sin(de), Math.cos(de));
2180
+ } else {
2181
+ const re = new L(...b.localPos0).multiplyScalar(l).applyMatrix4(ye);
2182
+ de = new L(...b.localPos1).multiplyScalar(l).applyMatrix4($).sub(re).dot(q.clone().applyQuaternion(Pe));
2183
+ }
2184
+ const Ke = Number.isFinite(b.lowerLimit) && Number.isFinite(b.upperLimit) && Math.abs(b.lowerLimit) < 1e20 && Math.abs(b.upperLimit) < 1e20, Rt = Ke && b.lowerLimit < b.upperLimit, De = h * (F === "slide" ? l : l * l), Ge = Te(e, b.path, `physxJointAxis:${F === "slide" ? "linear" : "angular"}:dynamicFrictionEffort`), It = typeof Ge == "number" && Number.isFinite(Ge) ? Ge * De : 0;
2185
+ T.push(`<joint name="${we(b.path)}" type="${F}" pos="${Q(b.localPos1.map((re) => re * l))}" axis="${Q(q.toArray())}" ref="${de}" ${Rt ? `range="${b.lowerLimit * ne} ${b.upperLimit * ne}"` : 'limited="false"'} frictionloss="${It}" armature="0.00001"/>`), Ke && b.lowerLimit === b.upperLimit && p.push(`<joint joint1="${we(b.path)}" polycoef="${b.lowerLimit * ne - de} 0 0 0 0"/>`);
2186
+ const ue = b.drive;
2187
+ if (ue && ((ue.stiffness ?? 0) !== 0 || (ue.damping ?? 0) !== 0)) {
2188
+ if (ue.type === "acceleration") throw V(`Unsupported USD acceleration drive: ${b.path}`, "E_USD_UNSUPPORTED_DRIVE");
2189
+ const re = (ue.stiffness ?? 0) * De / ne, _e = (ue.damping ?? 0) * De / ne, Re = ue.maxForce == null ? null : ue.maxForce * De;
2190
+ a.push(`<general joint="${we(b.path)}" gainprm="1" biastype="affine" biasprm="0 ${-re} ${-_e}" ${Re != null && Number.isFinite(Re) ? `forcelimited="true" forcerange="${-Re} ${Re}"` : ""}/>`), o.push(re * (ue.targetPosition ?? 0) * ne + _e * (ue.targetVelocity ?? 0) * ne);
2191
+ }
2192
+ }
2193
+ const R = M.mass;
2194
+ if ((R == null ? void 0 : R.mass) != null && (!Number.isFinite(R.mass) || R.mass < 0)) throw V(`USD rigid body mass must be finite and non-negative: ${w}`, "E_USD_INVALID_MASS");
2195
+ let X = !1;
2196
+ if ((R == null ? void 0 : R.mass) != null && R.mass > 0 && ((O = R.centerOfMass) == null ? void 0 : O.length) === 3 && R.centerOfMass.every(Number.isFinite) && ((B = R.diagonalInertia) == null ? void 0 : B.length) === 3 && R.diagonalInertia.every((F) => Number.isFinite(F) && F > 0) && ((k = R.principalAxes) == null ? void 0 : k.length) === 4 && R.principalAxes.every(Number.isFinite))
2197
+ X = !0, T.push(`<inertial mass="${R.mass * h}" pos="${Q(R.centerOfMass.map((F) => F * l))}" quat="${be(Ue(R.principalAxes))}" diaginertia="${Q(R.diagonalInertia.map((F) => F * h * l * l))}"/>`);
2198
+ else {
2199
+ if ((G = R == null ? void 0 : R.diagonalInertia) != null && G.some((F) => F > 0))
2200
+ throw V(`USD rigid body has incomplete explicit inertia: ${w}`, "E_USD_PARTIAL_INERTIA");
2201
+ if ((R == null ? void 0 : R.mass) != null && R.mass > 0) {
2202
+ if ((ce = R.centerOfMass) != null && ce.every(Number.isFinite) && R.centerOfMass.some((F) => F !== 0)) throw V(`Custom center of mass requires explicit inertia: ${w}`, "E_USD_PARTIAL_INERTIA");
2203
+ f.push({ body: w, mass: R.mass * h });
2204
+ }
2205
+ }
2206
+ const P = e.data.physics.colliders.filter((F) => F.enabled && F.bodyPath === w);
2207
+ if (!P.length && !X) throw V(`USD rigid body has no authored collision geometry: ${w}`, "E_USD_MISSING_COLLISION_GEOMETRY");
2208
+ for (const F of P) {
2209
+ const q = e.data.physics.materials.find((ge) => ge.path === F.material), ne = (R == null ? void 0 : R.density) != null && R.density > 0 ? R.density : q == null ? void 0 : q.density, ye = ne != null && ne > 0 ? ne * h / l ** 3 : 1e3, Ce = (q == null ? void 0 : q.dynamicFriction) ?? 0.4, Pe = `density="${ye}" group="3" contype="1" conaffinity="1" friction="${Ce} 0.01 0.0002"`;
2210
+ T.push(ft(e, F, w, $, S++, r, Pe));
2211
+ }
2212
+ for (const [F, q] of u) q.body0 === w && T.push(m(F, $));
2213
+ return T.push("</body>"), T.join("");
2214
+ }, _ = e.data.physics.colliders.filter((w) => w.enabled && !w.bodyPath), U = _.map((w) => {
2215
+ const v = e.data.physics.materials.find((Y) => Y.path === w.material), M = (v == null ? void 0 : v.density) != null && v.density > 0 ? v.density * h / l ** 3 : 1e3, $ = (v == null ? void 0 : v.dynamicFriction) ?? 0.4, z = `density="${M}" group="3" contype="1" conaffinity="1" friction="${$} 0.01 0.0002"`;
2216
+ return ft(e, w, "", new pe(), S++, r, z);
2217
+ }).join(""), x = rr(e, t, _) ? `<geom name="__viewer_default_ground__" type="plane" pos="0 0 ${sr(e, t)}" size="1 1 0.1" group="3" contype="1" conaffinity="1" friction="0.8 0.01 0.0002"/>` : "", D = [...y.keys()].filter((w) => {
2218
+ var v;
2219
+ return !((v = u.get(w)) != null && v.body0);
2220
+ }).map((w) => m(w)).join("");
2221
+ if (g.size !== y.size) throw V("USD joint graph contains unreachable bodies or a cycle.", "E_USD_UNREACHABLE_BODIES");
2222
+ if (e.data.physics.scenes.length > 1) throw V("Multiple USD PhysicsScene prims are not supported.", "E_USD_MULTIPLE_PHYSICS_SCENES");
2223
+ const E = e.data.physics.scenes[0], I = E != null && E.gravityDirection && E.gravityMagnitude != null && E.gravityMagnitude >= 0 ? new L(...E.gravityDirection).normalize().multiplyScalar(E.gravityMagnitude * l).applyQuaternion(e.scene.quaternion) : new L(0, 0, -9.81);
2224
+ return {
2225
+ // Do not inflate contact surfaces across authored clearances. PhysX contactOffset
2226
+ // is not a MuJoCo force-generating margin and must not be copied as one.
2227
+ format: "mjcf",
2228
+ files: /* @__PURE__ */ new Map(),
2229
+ initialControls: o,
2230
+ initialVelocities: i,
2231
+ massOverrides: f,
2232
+ xml: `<mujoco><compiler angle="radian" autolimits="true"/><option integrator="implicitfast" gravity="${Q(I.toArray())}"><flag filterparent="disable"/></option><default><geom margin="0" solref="0.004 1"/></default>${r.length ? `<asset>${r.join("")}</asset>` : ""}<worldbody>${x}${U}${D}</worldbody>${d.length ? `<contact>${d.join("")}</contact>` : ""}${p.length ? `<equality>${p.join("")}</equality>` : ""}${a.length ? `<actuator>${a.join("")}</actuator>` : ""}</mujoco>`
2233
+ };
2234
+ }
2235
+ function rr(e, t, n = e.data.physics.colliders.filter((s) => s.enabled && !s.bodyPath)) {
2236
+ if (!t.length || n.some((f) => f.typeName.toLowerCase().includes("plane"))) return !1;
2237
+ const s = Xe(e, e.data.physics.colliders.filter(
2238
+ (f) => f.enabled && f.bodyPath && t.includes(f.bodyPath)
2239
+ ));
2240
+ if (s.isEmpty()) return n.length === 0;
2241
+ const r = Math.max(s.max.x - s.min.x, 1e-6), p = Math.max(s.max.y - s.min.y, 1e-6), d = Math.max(r, p, s.max.z - s.min.z) * 0.05;
2242
+ return !n.some((f) => {
2243
+ const a = Xe(e, [f]);
2244
+ if (a.isEmpty()) return !1;
2245
+ const o = a.max.x >= s.min.x && a.min.x <= s.max.x, i = a.max.y >= s.min.y && a.min.y <= s.max.y;
2246
+ return o && i && a.max.z <= s.min.z + d;
2247
+ });
2248
+ }
2249
+ function sr(e, t) {
2250
+ const n = Xe(e, e.data.physics.colliders.filter(
2251
+ (r) => r.enabled && r.bodyPath && t.includes(r.bodyPath)
2252
+ )), s = n.isEmpty() ? 0 : n.min.z;
2253
+ return Number.isFinite(s) ? String(s) : "0";
2254
+ }
2255
+ function Xe(e, t) {
2256
+ const n = new Ne();
2257
+ for (const s of t) {
2258
+ const r = e.index.objectsByPath.get(s.path);
2259
+ r && n.union(new Ne().setFromObject(r));
2260
+ }
2261
+ return n;
2262
+ }
2263
+ function Dt(e) {
2264
+ return e === "Y" ? new L(0, 1, 0) : e === "Z" ? new L(0, 0, 1) : new L(1, 0, 0);
2265
+ }
2266
+ function ft(e, t, n, s, r, p, d) {
2267
+ const f = e.index.objectsByPath.get(t.path);
2268
+ if (!f) throw V(`USD collider node is missing: ${t.path}`, "E_USD_MISSING_COLLISION_GEOMETRY");
2269
+ const a = s.clone().invert().multiply(f.matrixWorld), o = new L(), i = new ee(), l = new L();
2270
+ a.decompose(o, i, l);
2271
+ const h = t.typeName.replace(/^UsdGeom/, "").toLowerCase(), y = (c, u) => {
2272
+ const S = Te(e, t.path, c);
2273
+ return typeof S == "number" ? S : u;
2274
+ };
2275
+ if (h.includes("cube")) {
2276
+ const c = Math.abs(y("size", 2)) / 2;
2277
+ return `<geom type="box" pos="${Q(o.toArray())}" quat="${be(i)}" size="${Q([Math.abs(l.x) * c, Math.abs(l.y) * c, Math.abs(l.z) * c])}" ${d}/>`;
2278
+ }
2279
+ if (h.includes("plane")) {
2280
+ if (n) throw V(`USD plane collider requires a static world owner: ${t.path}`, "E_USD_UNSUPPORTED_GEOMETRY");
2281
+ const c = String(Te(e, t.path, "axis") ?? "Z").toUpperCase(), S = { X: new L(1, 0, 0), Y: new L(0, 1, 0), Z: new L(0, 0, 1) }[c];
2282
+ if (!S) throw V(`Unsupported USD plane axis: ${c}`, "E_USD_UNSUPPORTED_GEOMETRY");
2283
+ const g = i.clone().multiply(new ee().setFromUnitVectors(new L(0, 0, 1), S));
2284
+ return `<geom type="plane" pos="${Q(o.toArray())}" quat="${be(g)}" size="1 1 0.1" ${d}/>`;
2285
+ }
2286
+ if (h.includes("cone"))
2287
+ throw V(`MuJoCo has no analytic cone geom; a validated mesh conversion is required: ${t.path}`, "E_USD_UNSUPPORTED_GEOMETRY");
2288
+ if (h.includes("sphere")) {
2289
+ const c = [Math.abs(l.x), Math.abs(l.y), Math.abs(l.z)];
2290
+ if (Math.max(...c) - Math.min(...c) > 1e-6) throw V(`USD sphere collider does not support non-uniform scale: ${t.path}`, "E_USD_NONUNIFORM_RADIAL_SCALE");
2291
+ return `<geom type="sphere" pos="${Q(o.toArray())}" quat="${be(i)}" size="${c[0] * y("radius", 1)}" ${d}/>`;
2292
+ }
2293
+ if (h.includes("cylinder") || h.includes("capsule")) {
2294
+ const c = String(Te(e, t.path, "axis") ?? "Z").toUpperCase(), u = { X: 0, Y: 1, Z: 2 }[c];
2295
+ if (u === void 0) throw V(`Unsupported USD collider axis: ${c}`, "E_USD_UNSUPPORTED_GEOMETRY");
2296
+ const S = [Math.abs(l.x), Math.abs(l.y), Math.abs(l.z)], g = S.filter((A, D) => D !== u);
2297
+ if (Math.abs(g[0] - g[1]) > 1e-6) throw V(`USD ${t.typeName} collider does not support non-uniform radial scale: ${t.path}`, "E_USD_NONUNIFORM_RADIAL_SCALE");
2298
+ const m = new L(...{ X: [1, 0, 0], Y: [0, 1, 0], Z: [0, 0, 1] }[c]), _ = i.clone().multiply(new ee().setFromUnitVectors(new L(0, 0, 1), m)), U = y("radius", 1) * g[0], x = y("height", 2) * S[u] / 2;
2299
+ return `<geom type="${h.includes("capsule") ? "capsule" : "cylinder"}" pos="${Q(o.toArray())}" quat="${be(_)}" size="${U} ${x}" ${d}/>`;
2300
+ }
2301
+ if (h.includes("mesh")) {
2302
+ if (t.approximation && !["none", "convexHull"].includes(t.approximation)) throw V(`USD mesh approximation cannot be mapped exactly: ${t.path}`, "E_USD_UNSUPPORTED_APPROXIMATION");
2303
+ const c = [];
2304
+ if (f.traverse((_) => {
2305
+ _ instanceof te && c.push(_);
2306
+ }), !c.length) throw V(`USD collider has no mesh geometry: ${t.path}`, "E_USD_MISSING_COLLISION_GEOMETRY");
2307
+ const u = [], S = [];
2308
+ let g = 0;
2309
+ for (const _ of c) {
2310
+ const U = _.geometry.getAttribute("position");
2311
+ for (let A = 0; A < U.count; A++) {
2312
+ const D = new L().fromBufferAttribute(U, A).applyMatrix4(s.clone().invert().multiply(_.matrixWorld));
2313
+ u.push(D.x, D.y, D.z);
2314
+ }
2315
+ const x = _.geometry.index;
2316
+ for (let A = 0; A < (x ? x.count : U.count); A += 3) S.push(g + (x ? x.getX(A) : A), g + (x ? x.getX(A + 1) : A + 1), g + (x ? x.getX(A + 2) : A + 2));
2317
+ g += U.count;
2318
+ }
2319
+ const m = `collision_${r}`;
2320
+ return p.push(`<mesh name="${m}" vertex="${Q(u)}" face="${Q(S)}"/>`), `<geom type="mesh" mesh="${m}" ${d}/>`;
2321
+ }
2322
+ throw V(`Unsupported USD collider geometry: ${t.typeName}`, "E_USD_UNSUPPORTED_GEOMETRY");
2323
+ }
2324
+ function or(e) {
2325
+ const t = e.stage.GetPseudoRoot();
2326
+ try {
2327
+ const n = Number(t.GetMetadata("metersPerUnit") ?? 0.01), s = Number(t.GetMetadata("kilogramsPerUnit") ?? 1);
2328
+ if (!Number.isFinite(n) || n <= 0) throw V("USD metersPerUnit must be finite and positive.", "E_USD_INVALID_UNITS");
2329
+ if (!Number.isFinite(s) || s <= 0) throw V("USD kilogramsPerUnit must be finite and positive.", "E_USD_INVALID_UNITS");
2330
+ return { metersPerUnit: n, kilogramsPerUnit: s };
2331
+ } finally {
2332
+ t.delete();
2333
+ }
2334
+ }
2335
+ function Ue(e) {
2336
+ const [t = 1, n = 0, s = 0, r = 0] = e;
2337
+ return new ee(n, s, r, t).normalize();
2338
+ }
2339
+ function Q(e) {
2340
+ return e.join(" ");
2341
+ }
2342
+ function be(e) {
2343
+ return `${e.w} ${e.x} ${e.y} ${e.z}`;
2344
+ }
2345
+ function Te(e, t, n) {
2346
+ var a, o;
2347
+ const s = e.stage;
2348
+ if (!s || !((o = (a = e.pxr) == null ? void 0 : a.Sdf) != null && o.Path)) return null;
2349
+ const r = new e.pxr.Sdf.Path(t), p = s.GetPrimAtPath(r), d = p.GetAttribute(n), f = e.pxr.Usd.TimeCode.Default();
2350
+ try {
2351
+ return d.IsValid() ? d.Get(f) : null;
2352
+ } finally {
2353
+ f.delete(), d.delete(), p.delete(), r.delete();
2354
+ }
2355
+ }
2356
+ async function ar(e, t) {
2357
+ var n;
2358
+ if (e.url)
2359
+ try {
2360
+ return new URL(e.url, ((n = globalThis.location) == null ? void 0 : n.href) ?? e.baseUrl ?? void 0).href;
2361
+ } catch {
2362
+ return e.url;
2363
+ }
2364
+ return e.resolve(t);
2365
+ }
2366
+ async function ir(e) {
2367
+ const t = e.url ?? await e.resolve(e.entryPath ?? ""), n = await fetch(t, { signal: e.signal });
2368
+ if (!n.ok) throw V(`USD request failed (${n.status}): ${t}`, n.status === 401 || n.status === 403 ? "E_ASSET_AUTH" : "E_ASSET_FETCH");
2369
+ return n.blob();
2370
+ }
2371
+ function we(e) {
2372
+ return e.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2373
+ }
2374
+ function V(e, t) {
2375
+ return Object.assign(new Error(e), { code: t });
2376
+ }
2377
+ function Ve() {
2378
+ return Object.assign(new Error("USD load aborted."), { name: "AbortError", code: "E_ABORTED" });
2379
+ }
2380
+ export {
2381
+ er as buildUsdVisualReferenceOwners,
2382
+ dt as compileUsdCollisionOverlay,
2383
+ At as compileUsdCollisionVisual,
2384
+ nr as compileUsdPhysics,
2385
+ Qn as compileUsdVisual,
2386
+ Jn as firstUsdVisualWarning,
2387
+ hr as isUsdPhysicsFallbackEligible,
2388
+ mr as loadUsdSimulation,
2389
+ tr as parseUsdReferenceMetadata,
2390
+ Pt as resolveUsdJoints,
2391
+ rr as shouldInjectUsdDefaultGround
2392
+ };