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