@khr3/core 0.2.10 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +8 -0
  2. package/dist/{physicsEcs-Bi0ikONC.js → KhrAssembly-CKW8I_2z.js} +1136 -625
  3. package/dist/KhrAssembly-CKW8I_2z.js.map +1 -0
  4. package/dist/KhrAssembly.d.ts +46 -8
  5. package/dist/KhrCollider.d.ts +21 -7
  6. package/dist/clone.d.ts +40 -0
  7. package/dist/{khrExporter.d.ts → exporter.d.ts} +2 -2
  8. package/dist/{khrGlb.d.ts → glb.d.ts} +4 -3
  9. package/dist/index.d.ts +10 -9
  10. package/dist/index.js +734 -1083
  11. package/dist/index.js.map +1 -1
  12. package/dist/{khrInertia.d.ts → inertia.d.ts} +22 -8
  13. package/dist/{jointDynamics.d.ts → joints.d.ts} +8 -7
  14. package/dist/loader.d.ts +9 -0
  15. package/dist/types.d.ts +282 -0
  16. package/dist/useKhrGlb.d.ts +6 -1
  17. package/dist/vehicle.d.ts +35 -2
  18. package/dist/vehicle.js +435 -526
  19. package/dist/vehicle.js.map +1 -1
  20. package/dist/wheelLoads.d.ts +5 -4
  21. package/package.json +4 -16
  22. package/dist/AssemblyRootBody.d.ts +0 -16
  23. package/dist/BundleSceneHost.d.ts +0 -23
  24. package/dist/KhrVehicle.d.ts +0 -20
  25. package/dist/assemblyPlan.d.ts +0 -61
  26. package/dist/curves.d.ts +0 -378
  27. package/dist/curves.js +0 -542
  28. package/dist/curves.js.map +0 -1
  29. package/dist/khrBundleFinalize.d.ts +0 -15
  30. package/dist/khrClone.d.ts +0 -14
  31. package/dist/khrConfigTypes.d.ts +0 -62
  32. package/dist/khrExportEncoders.d.ts +0 -8
  33. package/dist/khrExtras.d.ts +0 -22
  34. package/dist/khrJointParser.d.ts +0 -3
  35. package/dist/khrLoader.d.ts +0 -7
  36. package/dist/khrMassProps.d.ts +0 -16
  37. package/dist/khrParsers.d.ts +0 -10
  38. package/dist/khrPlugin.d.ts +0 -8
  39. package/dist/khrPluginHelpers.d.ts +0 -26
  40. package/dist/khrRotorDecoders.d.ts +0 -4
  41. package/dist/khrShapeParser.d.ts +0 -8
  42. package/dist/khrTypes.d.ts +0 -141
  43. package/dist/khrVehicleChassis.d.ts +0 -20
  44. package/dist/khrVehicleJointHelpers.d.ts +0 -37
  45. package/dist/khrVehicleJoints.d.ts +0 -30
  46. package/dist/khrVehicleRotors.d.ts +0 -22
  47. package/dist/khrVehicleSlots.d.ts +0 -41
  48. package/dist/khrVehicleTypes.d.ts +0 -52
  49. package/dist/pacejka.d.ts +0 -22
  50. package/dist/physicsEcs-Bi0ikONC.js.map +0 -1
  51. package/dist/physicsEcs.d.ts +0 -25
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef } from "react";
1
+ import { useMemo } from "react";
2
2
  import { useFrame, useLoader } from "@react-three/fiber";
3
- import { Physics, RigidBody, useRapier } from "@react-three/rapier";
3
+ import { Physics, useRapier } from "@react-three/rapier";
4
4
  import { TimeControl } from "@pinkaphant/ecctrl/time";
5
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
- import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
7
- import { C as computeRelativePose, D as KhrValidationError, E as readUnitQuat, S as computeBodyInertia, T as readFiniteVec3, _ as releaseBundleMount, a as MountSubtreeSlot, b as assertUnitScale, c as planAssembly, f as KhrCollider, h as disposeKhrBundle, i as BundleSceneHost, m as cloneKhrBundle, n as buildJointRuntime, o as captureSubtreeOrigins, p as claimBundleMount, r as createRapierImpulseJoint, t as JointRegistryContext, v as assertIdentityWorldScale, w as extractMeshColliderShape, x as computeAssemblyMassAndCom, y as assertSceneIdentityWorldScale } from "./physicsEcs-Bi0ikONC.js";
5
+ import { A as computeShapeInertia, B as isObj, C as assertSceneIdentityWorldScale, D as computeBodyInertia, E as computeAssemblyMassAndCom, F as JointRegistryContext, H as optFiniteNum, I as KhrValidationError, L as assignRef, M as readFiniteVec3, N as readUnitQuat, P as COMBINE_MODES, R as isFiniteNum, S as assertIdentityWorldScale, V as isPosNum, _ as cloneKhrBundle, a as DETACHED_PANEL_INTERACTION_GROUPS, b as releaseBundleMount, c as createRapierImpulseJoint, d as openTargetForLimits, f as KhrCollider, g as claimBundleMount, i as ATTACHED_PANEL_INTERACTION_GROUPS, j as extractMeshColliderShape, k as computeRelativePose, l as isJointOpen, n as planAssembly, o as buildJointRuntime, s as configureJointDrive, t as KhrAssembly, u as measureJointCoordinate, v as disposeKhrBundle, w as assertUnitScale, z as isNonNegNum } from "./KhrAssembly-CKW8I_2z.js";
6
+ import { jsx, jsxs } from "react/jsx-runtime";
8
7
  import * as THREE from "three";
8
+ import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
9
9
  import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js";
10
10
  // src/PhysicsWorld.tsx
11
11
  var readVal = (v) => typeof v === "number" ? v : v.current;
@@ -14,7 +14,7 @@ function TimestepPresync({ paused, timeScale, maxDelta }) {
14
14
  useFrame((_, delta) => {
15
15
  const md = Math.max(0, readVal(maxDelta));
16
16
  const ts = readVal(timeScale);
17
- world.timestep = !paused && ts > 0 && md > 0 && delta > 0 ? Math.min(delta, md) * ts : 0;
17
+ world.timestep = !paused && Number.isFinite(ts) && ts > 0 && md > 0 && delta > 0 ? Math.min(delta, md) * ts : 0;
18
18
  });
19
19
  return null;
20
20
  }
@@ -23,75 +23,111 @@ function PhysicsWorld({ paused = false, timeScale = 1, maxDelta = 1 / 30, gravit
23
23
  -9.81,
24
24
  0
25
25
  ], children, ...physicsProps }) {
26
- return /* @__PURE__ */ jsxs(Physics, {
27
- ...physicsProps,
28
- paused: true,
29
- timeStep: "vary",
30
- gravity,
31
- children: [
32
- /* @__PURE__ */ jsx(TimestepPresync, {
33
- paused,
34
- timeScale,
35
- maxDelta
36
- }),
37
- children,
38
- /* @__PURE__ */ jsx(TimeControl, {
39
- paused,
40
- timeScale,
41
- maxDelta
42
- })
43
- ]
26
+ const jointRegistry = useMemo(() => /* @__PURE__ */ new Set(), []);
27
+ return /* @__PURE__ */ jsx(JointRegistryContext.Provider, {
28
+ value: jointRegistry,
29
+ children: /* @__PURE__ */ jsxs(Physics, {
30
+ ...physicsProps,
31
+ paused: true,
32
+ timeStep: "vary",
33
+ gravity,
34
+ children: [
35
+ /* @__PURE__ */ jsx(TimestepPresync, {
36
+ paused,
37
+ timeScale,
38
+ maxDelta
39
+ }),
40
+ children,
41
+ /* @__PURE__ */ jsx(TimeControl, {
42
+ paused,
43
+ timeScale,
44
+ maxDelta
45
+ })
46
+ ]
47
+ })
44
48
  });
45
49
  }
46
- // src/khrGlb.ts
50
+ // src/glb.ts
51
+ /** ASCII "glTF" little-endian fourCC. */
47
52
  var GLB_MAGIC = 0x46546c67;
53
+ /** ASCII "JSON" little-endian fourCC. */
48
54
  var GLB_JSON_CHUNK = 0x4e4f534a;
55
+ /** ASCII "BIN\0" little-endian fourCC. */
49
56
  var GLB_BIN_CHUNK = 5130562;
50
- function validateGlbHeader(buffer) {
51
- if (buffer.byteLength < 20) throw new KhrValidationError("GLB buffer shorter than 20-byte header");
52
- const view = new DataView(buffer);
57
+ function validateGlbHeader(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) {
58
+ if (byteLength < 20) throw new KhrValidationError("GLB buffer shorter than 20-byte header");
59
+ const view = new DataView(buffer, byteOffset, byteLength);
53
60
  if (view.getUint32(0, true) !== 0x46546c67) throw new KhrValidationError("Invalid GLB magic");
54
61
  if (view.getUint32(4, true) !== 2) throw new KhrValidationError("Unsupported glTF version");
55
62
  const jsonLen = view.getUint32(12, true);
56
63
  if (view.getUint32(16, true) !== 0x4e4f534a) throw new KhrValidationError("Missing GLB JSON chunk");
57
- if (20 + jsonLen > buffer.byteLength) throw new KhrValidationError("Truncated GLB JSON chunk");
64
+ if (20 + jsonLen > byteLength) throw new KhrValidationError("Truncated GLB JSON chunk");
58
65
  return jsonLen;
59
66
  }
67
+ function bytesToBase64(bytes) {
68
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
69
+ const CHUNK = 32768;
70
+ const chunks = [];
71
+ for (let i = 0; i < bytes.length; i += CHUNK) chunks.push(String.fromCharCode(...bytes.subarray(i, i + CHUNK)));
72
+ return btoa(chunks.join(""));
73
+ }
60
74
  function ensureHeadlessFileReader() {
61
75
  if (globalThis.FileReader !== void 0) return;
62
- class PolyfillFileReader {
76
+ class HeadlessFileReader extends EventTarget {
77
+ static EMPTY = 0;
78
+ static LOADING = 1;
79
+ static DONE = 2;
80
+ EMPTY = 0;
81
+ LOADING = 1;
82
+ DONE = 2;
83
+ readyState = 0;
63
84
  result = null;
64
85
  error = null;
65
86
  onload = null;
66
87
  onloadend = null;
67
88
  onerror = null;
89
+ abort() {
90
+ this.readyState = 2;
91
+ }
68
92
  readAsArrayBuffer(blob) {
93
+ this.readyState = 1;
69
94
  blob.arrayBuffer().then((buf) => {
70
95
  this.result = buf;
96
+ this.readyState = 2;
71
97
  this.onload?.({ target: this });
72
- this.onloadend?.();
98
+ this.dispatchEvent(new Event("load"));
99
+ this.onloadend?.({ target: this });
100
+ this.dispatchEvent(new Event("loadend"));
73
101
  }, (err) => {
74
102
  this.error = err;
103
+ this.readyState = 2;
75
104
  this.onerror?.(err);
76
- this.onloadend?.();
105
+ this.dispatchEvent(new Event("error"));
106
+ this.onloadend?.({ target: this });
107
+ this.dispatchEvent(new Event("loadend"));
77
108
  });
78
109
  }
79
110
  readAsDataURL(blob) {
111
+ this.readyState = 1;
80
112
  blob.arrayBuffer().then((buf) => {
81
- const bytes = new Uint8Array(buf);
82
- let bin = "";
83
- for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
84
- this.result = `data:${blob.type || "application/octet-stream"};base64,${btoa(bin)}`;
113
+ const b64 = bytesToBase64(new Uint8Array(buf));
114
+ this.result = `data:${blob.type || "application/octet-stream"};base64,${b64}`;
115
+ this.readyState = 2;
85
116
  this.onload?.({ target: this });
86
- this.onloadend?.();
117
+ this.dispatchEvent(new Event("load"));
118
+ this.onloadend?.({ target: this });
119
+ this.dispatchEvent(new Event("loadend"));
87
120
  }, (err) => {
88
121
  this.error = err;
122
+ this.readyState = 2;
89
123
  this.onerror?.(err);
90
- this.onloadend?.();
124
+ this.dispatchEvent(new Event("error"));
125
+ this.onloadend?.({ target: this });
126
+ this.dispatchEvent(new Event("loadend"));
91
127
  });
92
128
  }
93
129
  }
94
- globalThis.FileReader = PolyfillFileReader;
130
+ globalThis.FileReader = HeadlessFileReader;
95
131
  }
96
132
  function packJsonToGlb(gltf) {
97
133
  const jsonBytes = new TextEncoder().encode(JSON.stringify(gltf));
@@ -110,12 +146,14 @@ function packJsonToGlb(gltf) {
110
146
  return out;
111
147
  }
112
148
  function patchGlbJsonChunk(source, mutator) {
113
- const rawBuf = source instanceof ArrayBuffer ? source : source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
114
- const jsonLen = validateGlbHeader(rawBuf);
115
- const dv = new DataView(rawBuf);
149
+ const buf = source instanceof ArrayBuffer ? source : source.buffer;
150
+ const byteOffset = source instanceof ArrayBuffer ? 0 : source.byteOffset;
151
+ const byteLength = source.byteLength;
152
+ const jsonLen = validateGlbHeader(buf, byteOffset, byteLength);
153
+ const dv = new DataView(buf, byteOffset, byteLength);
116
154
  let gltf;
117
155
  try {
118
- gltf = JSON.parse(new TextDecoder().decode(new Uint8Array(rawBuf, 20, jsonLen)));
156
+ gltf = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, byteOffset + 20, jsonLen)));
119
157
  } catch {
120
158
  throw new KhrValidationError("Malformed GLB JSON chunk");
121
159
  }
@@ -123,10 +161,16 @@ function patchGlbJsonChunk(source, mutator) {
123
161
  const nextJson = new TextEncoder().encode(JSON.stringify(gltf));
124
162
  const paddedJsonLen = nextJson.byteLength + 3 & -4;
125
163
  const binHeaderOff = 20 + jsonLen;
126
- const hasBin = binHeaderOff + 8 <= rawBuf.byteLength;
127
- const binLen = hasBin ? Math.min(dv.getUint32(binHeaderOff, true), rawBuf.byteLength - (binHeaderOff + 8)) : 0;
128
- const binTag = hasBin ? dv.getUint32(binHeaderOff + 4, true) : GLB_BIN_CHUNK;
129
- const binData = hasBin ? new Uint8Array(rawBuf, binHeaderOff + 8, binLen) : /* @__PURE__ */ new Uint8Array();
164
+ const hasBin = binHeaderOff < byteLength;
165
+ let binTag = GLB_BIN_CHUNK;
166
+ let binData = /* @__PURE__ */ new Uint8Array(0);
167
+ if (hasBin) {
168
+ if (binHeaderOff + 8 > byteLength) throw new KhrValidationError("Truncated GLB binary chunk header");
169
+ const binLen = dv.getUint32(binHeaderOff, true);
170
+ binTag = dv.getUint32(binHeaderOff + 4, true);
171
+ if (binHeaderOff + 8 + binLen > byteLength) throw new KhrValidationError("Truncated GLB binary chunk payload");
172
+ binData = new Uint8Array(buf, byteOffset + binHeaderOff + 8, binLen);
173
+ }
130
174
  const paddedBinLen = binData.byteLength + 3 & -4;
131
175
  const totalLen = 20 + paddedJsonLen + (hasBin ? 8 + paddedBinLen : 0);
132
176
  const out = new ArrayBuffer(totalLen);
@@ -146,248 +190,188 @@ function patchGlbJsonChunk(source, mutator) {
146
190
  }
147
191
  return out;
148
192
  }
149
- // src/khrRotorDecoders.ts
150
- var _quat$1 = new THREE.Quaternion();
151
- var _invParentQuat = new THREE.Quaternion();
152
- var isObj$4 = (v) => typeof v === "object" && !!v && !Array.isArray(v);
153
- var isFiniteNum$1 = (v) => typeof v === "number" && Number.isFinite(v);
154
- function getRelativeQuatArray(obj, parent) {
155
- obj.updateWorldMatrix(true, false);
156
- obj.getWorldQuaternion(_quat$1);
157
- if (parent) {
158
- parent.updateWorldMatrix(true, false);
159
- _quat$1.premultiply(parent.getWorldQuaternion(_invParentQuat).invert());
160
- }
161
- if (_quat$1.lengthSq() > 0) _quat$1.normalize();
162
- else _quat$1.identity();
163
- return [
164
- _quat$1.x || 0,
165
- _quat$1.y || 0,
166
- _quat$1.z || 0,
167
- _quat$1.w || 0
168
- ];
193
+ // src/loader.ts
194
+ var KHR_BUNDLE_USERDATA_KEY = "khrBundle";
195
+ var HEADLESS_TEXTURE_EXT_NAMES = [
196
+ "EXT_texture_webp",
197
+ "EXT_texture_avif",
198
+ "KHR_texture_basisu"
199
+ ];
200
+ function isHeadlessTextureEnv() {
201
+ return typeof document === "undefined" && (typeof createImageBitmap === "undefined" || typeof self === "undefined");
169
202
  }
170
- function optNum$3(obj, key, tagKind, owner, strictlyPos = false) {
171
- const val = obj[key];
172
- if (val === void 0) return void 0;
173
- if (!isFiniteNum$1(val) || (strictlyPos ? val <= 0 : val < 0)) throw new KhrValidationError(`${tagKind} "${owner}" has invalid ${key}: ${tagKind}.${key}`);
174
- return val;
203
+ function stubTextureInParser(parser, textureIndex) {
204
+ const tex = new THREE.Texture();
205
+ tex.flipY = false;
206
+ parser.associations.set(tex, { textures: textureIndex });
207
+ return Promise.resolve(tex);
175
208
  }
176
- function reqNum(obj, key, tagKind, owner, strictlyPos = false) {
177
- const val = obj[key];
178
- if (!isFiniteNum$1(val) || (strictlyPos ? val <= 0 : val < 0)) throw new KhrValidationError(`${tagKind} "${owner}" is missing valid ${tagKind}.${key}`);
179
- return val;
209
+ function patchHeadlessTexturePlugins(parser) {
210
+ const plugins = parser.plugins;
211
+ if (!plugins) return;
212
+ for (const extName of HEADLESS_TEXTURE_EXT_NAMES) {
213
+ const existing = plugins[extName];
214
+ if (!existing) continue;
215
+ existing.loadTexture = (textureIndex) => {
216
+ if (!(parser.json?.textures?.[textureIndex])?.extensions?.[extName]) return null;
217
+ return stubTextureInParser(parser, textureIndex);
218
+ };
219
+ }
180
220
  }
181
- function optBool(obj, key, tagKind, owner) {
182
- const val = obj[key];
183
- if (val === void 0) return void 0;
184
- if (typeof val !== "boolean") throw new KhrValidationError(`${tagKind} "${owner}" has non-boolean ${tagKind}.${key}`);
221
+ function reqArr(val, label) {
222
+ if (val === void 0) return [];
223
+ if (!Array.isArray(val)) throw new KhrValidationError(`${label} must be an array`);
185
224
  return val;
186
225
  }
187
- function optBoolOrNumFlag(obj, key, tagKind, owner) {
188
- const val = obj[key];
189
- if (val === void 0) return void 0;
190
- if (typeof val === "boolean") return { flag: val };
191
- if (isFiniteNum$1(val) && val >= 0) return {
192
- flag: val !== 0,
193
- numeric: val
194
- };
195
- throw new KhrValidationError(`${tagKind} "${owner}" has invalid ${tagKind}.${key}`);
196
- }
197
- function reqBool(obj, key, tagKind, owner) {
198
- const val = obj[key];
199
- if (typeof val !== "boolean") throw new KhrValidationError(`${tagKind} "${owner}" is missing boolean ${tagKind}.${key}`);
200
- return val;
226
+ function decodeShape(raw, idx) {
227
+ if (!isObj(raw)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] must be an object`);
228
+ const type = raw.type;
229
+ if (type === "box") {
230
+ if (raw.box !== void 0 && !isObj(raw.box)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid box`);
231
+ const box = isObj(raw.box) ? raw.box : {};
232
+ const size = box.size === void 0 ? [
233
+ 1,
234
+ 1,
235
+ 1
236
+ ] : box.size;
237
+ if (!Array.isArray(size) || size.length !== 3 || !size.every(isPosNum)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid box.size`);
238
+ return {
239
+ type: "box",
240
+ size: [
241
+ size[0],
242
+ size[1],
243
+ size[2]
244
+ ]
245
+ };
246
+ }
247
+ if (type === "sphere") {
248
+ if (raw.sphere !== void 0 && !isObj(raw.sphere)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid sphere`);
249
+ const sphere = isObj(raw.sphere) ? raw.sphere : {};
250
+ const radius = sphere.radius === void 0 ? .5 : sphere.radius;
251
+ if (!isPosNum(radius)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid sphere.radius`);
252
+ return {
253
+ type: "sphere",
254
+ radius
255
+ };
256
+ }
257
+ if (type === "cylinder" || type === "capsule") {
258
+ if (raw[type] !== void 0 && !isObj(raw[type])) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}`);
259
+ const g = isObj(raw[type]) ? raw[type] : {};
260
+ const height = g.height === void 0 ? type === "cylinder" ? 2 : 1 : g.height;
261
+ if (!isPosNum(height)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.height`);
262
+ const radiusTop = g.radiusTop === void 0 ? .5 : g.radiusTop;
263
+ const radiusBottom = g.radiusBottom === void 0 ? .5 : g.radiusBottom;
264
+ if (!isPosNum(radiusTop)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radiusTop`);
265
+ if (!isPosNum(radiusBottom)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radiusBottom`);
266
+ if (Math.abs(radiusTop - radiusBottom) > 1e-6) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] tapered ${type} (${radiusTop} !== ${radiusBottom}) is unsupported`);
267
+ return {
268
+ type,
269
+ height,
270
+ radiusTop,
271
+ radiusBottom
272
+ };
273
+ }
274
+ throw new KhrValidationError(`KHR_implicit_shapes[${idx}] unsupported shape type "${String(type)}"`);
201
275
  }
202
- function optCurve(val, key, owner) {
203
- if (val === void 0) return void 0;
204
- if (!isObj$4(val) || !Array.isArray(val.points) || val.points.length === 0) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid ecctrlWheel.${key}`);
205
- for (const pt of val.points) if (!isObj$4(pt) || !isFiniteNum$1(pt.x) || !isFiniteNum$1(pt.y)) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid point in ecctrlWheel.${key}`);
206
- if (val.samples !== void 0 && (!isFiniteNum$1(val.samples) || val.samples <= 0)) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid samples in ecctrlWheel.${key}`);
207
- return val;
276
+ function optCombineMode(v, label) {
277
+ if (v === void 0) return void 0;
278
+ if (typeof v !== "string" || !COMBINE_MODES.has(v)) throw new KhrValidationError(`Invalid ${label}: "${String(v)}"`);
279
+ return v;
208
280
  }
209
- function decodeWheelTag(obj, name, rawWheel, scene, rawOmiWheel) {
210
- assertIdentityWorldScale(obj, name);
211
- const hasOmi = rawOmiWheel !== void 0;
212
- if (hasOmi && !isObj$4(rawOmiWheel)) throw new KhrValidationError(`OMI_vehicle_wheel "${name}" must be an object`);
213
- if (rawWheel !== void 0 && !isObj$4(rawWheel)) throw new KhrValidationError(`ecctrlWheel "${name}" must be an object`);
214
- if (!hasOmi && rawWheel === void 0) throw new KhrValidationError(`ecctrlWheel "${name}" must be an object`);
215
- const ec = isObj$4(rawWheel) ? rawWheel : {};
216
- const omi = isObj$4(rawOmiWheel) ? rawOmiWheel : void 0;
217
- const radius = omi ? optNum$3(ec, "radius", "ecctrlWheel", name, true) ?? reqNum(omi, "radius", "OMI_vehicle_wheel", name, true) : reqNum(ec, "radius", "ecctrlWheel", name, true);
218
- const width = omi ? optNum$3(ec, "width", "ecctrlWheel", name, true) ?? reqNum(omi, "width", "OMI_vehicle_wheel", name, true) : reqNum(ec, "width", "ecctrlWheel", name, true);
219
- if (omi) {
220
- reqNum(omi, "radius", "OMI_vehicle_wheel", name, true);
221
- reqNum(omi, "width", "OMI_vehicle_wheel", name, true);
222
- }
223
- const omiTravel = omi ? optNum$3(omi, "suspensionTravel", "OMI_vehicle_wheel", name) : void 0;
224
- const omiMaxForce = omi ? optNum$3(omi, "maxForce", "OMI_vehicle_wheel", name) : void 0;
225
- const omiMaxSteerRaw = omi ? optNum$3(omi, "maxSteeringAngle", "OMI_vehicle_wheel", name) : void 0;
226
- const omiStiffness = omi ? optNum$3(omi, "suspensionStiffness", "OMI_vehicle_wheel", name) : void 0;
227
- const omiDampComp = omi ? optNum$3(omi, "suspensionDampingCompression", "OMI_vehicle_wheel", name) : void 0;
228
- const omiDampReb = omi ? optNum$3(omi, "suspensionDampingRebound", "OMI_vehicle_wheel", name) : void 0;
229
- const omiSteer = omi ? optBoolOrNumFlag(omi, "steering", "OMI_vehicle_wheel", name) : void 0;
230
- const omiProp = omi ? optBoolOrNumFlag(omi, "propulsion", "OMI_vehicle_wheel", name) : void 0;
231
- const omiSteering = omiSteer?.flag;
232
- const omiPropulsion = omiProp?.flag;
233
- const omiMaxSteer = omiMaxSteerRaw ?? (omiSteer?.numeric !== void 0 && omiSteer.numeric > 0 ? omiSteer.numeric : void 0);
234
- const travel = omi ? optNum$3(ec, "travel", "ecctrlWheel", name) ?? omiTravel ?? .25 : reqNum(ec, "travel", "ecctrlWheel", name);
235
- const sag = omi ? optNum$3(ec, "sag", "ecctrlWheel", name) ?? (travel > 0 ? Math.min(travel * .4, .1) : 0) : reqNum(ec, "sag", "ecctrlWheel", name);
236
- if (sag > travel) throw new KhrValidationError(`ecctrlWheel "${name}" has invalid sag (${sag}) > travel (${travel})`);
237
- const steer = omi ? optBool(ec, "steer", "ecctrlWheel", name) ?? omiSteering ?? (omiMaxSteer !== void 0 ? omiMaxSteer > 0 : false) : reqBool(ec, "steer", "ecctrlWheel", name);
238
- const drive = omi ? optBool(ec, "drive", "ecctrlWheel", name) ?? omiPropulsion ?? false : reqBool(ec, "drive", "ecctrlWheel", name);
239
- const brake = omi ? optBool(ec, "brake", "ecctrlWheel", name) ?? true : reqBool(ec, "brake", "ecctrlWheel", name);
240
- const omiDamping = omiDampComp !== void 0 && omiDampReb !== void 0 ? .5 * (omiDampComp + omiDampReb) : omiDampComp ?? omiDampReb;
241
- const springK = optNum$3(ec, "springK", "ecctrlWheel", name) ?? omiStiffness;
242
- const dampingC = optNum$3(ec, "dampingC", "ecctrlWheel", name) ?? omiDamping;
243
- const maxBrakeTorque = optNum$3(ec, "maxBrakeTorque", "ecctrlWheel", name) ?? (omiMaxForce !== void 0 ? omiMaxForce * radius : void 0);
244
- const maxSteeringAngle = optNum$3(ec, "maxSteeringAngle", "ecctrlWheel", name) ?? omiMaxSteer;
245
- const box = new THREE.Box3().setFromObject(obj);
246
- const center = box.isEmpty() ? obj.getWorldPosition(new THREE.Vector3()) : box.getCenter(new THREE.Vector3());
281
+ function decodePhysicsMaterial(rawMaterials, idx, ownerName) {
282
+ if (idx === void 0) return {};
283
+ if (typeof idx !== "number" || !Number.isInteger(idx) || idx < 0 || idx >= rawMaterials.length) throw new KhrValidationError(`Node "${ownerName}" references out-of-bounds physicsMaterial ${String(idx)}`);
284
+ const mat = rawMaterials[idx];
285
+ if (!isObj(mat)) throw new KhrValidationError(`Invalid physicsMaterials[${idx}] on "${ownerName}"`);
286
+ const dynF = optFiniteNum(mat.dynamicFriction, `physicsMaterials[${idx}].dynamicFriction`, true);
287
+ const statF = optFiniteNum(mat.staticFriction, `physicsMaterials[${idx}].staticFriction`, true);
288
+ const rest = optFiniteNum(mat.restitution, `physicsMaterials[${idx}].restitution`, true);
289
+ const frictionCombine = optCombineMode(mat.frictionCombine, `physicsMaterials[${idx}].frictionCombine`);
290
+ const restitutionCombine = optCombineMode(mat.restitutionCombine, `physicsMaterials[${idx}].restitutionCombine`);
247
291
  return {
248
- nodeName: name,
249
- object: obj,
250
- position: [
251
- center.x,
252
- center.y,
253
- center.z
254
- ],
255
- quaternion: getRelativeQuatArray(obj, scene),
256
- radius,
257
- width,
258
- steer,
259
- steerInvert: optBool(ec, "steerInvert", "ecctrlWheel", name),
260
- drive,
261
- driveInvert: optBool(ec, "driveInvert", "ecctrlWheel", name),
262
- brake,
263
- travel,
264
- sag,
265
- springK,
266
- dampingC,
267
- maxBrakeTorque,
268
- ...maxSteeringAngle === void 0 ? {} : { maxSteeringAngle },
269
- rollingResistanceCoef: optNum$3(ec, "rollingResistanceCoef", "ecctrlWheel", name),
270
- wheelDensity: optNum$3(ec, "wheelDensity", "ecctrlWheel", name, true),
271
- driveTorqueWeight: optNum$3(ec, "driveTorqueWeight", "ecctrlWheel", name),
272
- tireGripFactor: optNum$3(ec, "tireGripFactor", "ecctrlWheel", name),
273
- latFrictionEllipseScale: optNum$3(ec, "latFrictionEllipseScale", "ecctrlWheel", name),
274
- relaxLngRate: optNum$3(ec, "relaxLngRate", "ecctrlWheel", name),
275
- relaxLatRate: optNum$3(ec, "relaxLatRate", "ecctrlWheel", name),
276
- lngSlipRatioCurveData: optCurve(ec.lngSlipRatioCurveData, "lngSlipRatioCurveData", name),
277
- latSlipRatioCurveData: optCurve(ec.latSlipRatioCurveData, "latSlipRatioCurveData", name)
292
+ ...dynF !== void 0 || statF !== void 0 ? { friction: dynF ?? statF } : {},
293
+ ...rest === void 0 ? {} : { restitution: rest },
294
+ ...frictionCombine === void 0 ? {} : { frictionCombine },
295
+ ...restitutionCombine === void 0 ? {} : { restitutionCombine }
278
296
  };
279
297
  }
280
- function decodePropellerTag(obj, name, rawPropeller, scene) {
281
- assertIdentityWorldScale(obj, name);
282
- if (!isObj$4(rawPropeller)) throw new KhrValidationError(`ecctrlPropeller "${name}" must be an object`);
283
- if (!isFiniteNum$1(rawPropeller.maxThrust) || rawPropeller.maxThrust <= 0) throw new KhrValidationError(`ecctrlPropeller "${name}" is missing positive finite ecctrlPropeller.maxThrust`);
284
- let torqueRatio;
285
- if (rawPropeller.torqueRatio !== void 0) {
286
- if (!isFiniteNum$1(rawPropeller.torqueRatio)) throw new KhrValidationError(`ecctrlPropeller "${name}" has invalid ecctrlPropeller.torqueRatio`);
287
- torqueRatio = rawPropeller.torqueRatio;
288
- }
289
- const box = new THREE.Box3().setFromObject(obj);
290
- const center = box.isEmpty() ? obj.getWorldPosition(new THREE.Vector3()) : box.getCenter(new THREE.Vector3());
291
- return {
292
- nodeName: name,
293
- object: obj,
294
- position: [
295
- center.x,
296
- center.y,
297
- center.z
298
- ],
299
- quaternion: getRelativeQuatArray(obj, scene),
300
- maxThrust: rawPropeller.maxThrust,
301
- torqueRatio,
302
- invertThrust: optBool(rawPropeller, "invertThrust", "ecctrlPropeller", name),
303
- invertTorque: optBool(rawPropeller, "invertTorque", "ecctrlPropeller", name)
298
+ function decodeCollisionGroups(rawFilters) {
299
+ const collisionSystemIds = /* @__PURE__ */ new Map([["default", 0]]);
300
+ let nextCollisionBit = 1;
301
+ const bitFor = (sys) => {
302
+ const hit = collisionSystemIds.get(sys);
303
+ if (hit !== void 0) return hit;
304
+ if (nextCollisionBit > 15) throw new KhrValidationError(`Exceeded Rapier 16-group limit for collisionSystem "${sys}"`);
305
+ const b = nextCollisionBit++;
306
+ collisionSystemIds.set(sys, b);
307
+ return b;
304
308
  };
305
- }
306
- // src/khrExtras.ts
307
- function decodeBreakawaySpec(raw) {
308
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
309
- const rec = raw;
310
- if (typeof rec.breakImpulseNs !== "number" || !Number.isFinite(rec.breakImpulseNs) || rec.breakImpulseNs <= 0) return void 0;
311
- const latch = typeof rec.latchImpulseNs === "number" && Number.isFinite(rec.latchImpulseNs) && rec.latchImpulseNs > 0 ? rec.latchImpulseNs : void 0;
312
- return {
313
- ...latch === void 0 ? {} : { latchImpulseNs: latch },
314
- breakImpulseNs: rec.breakImpulseNs
309
+ const maskFor = (arr, label) => {
310
+ if (arr === void 0) return 0;
311
+ if (!Array.isArray(arr)) throw new KhrValidationError(`collisionFilter.${label} must be an array`);
312
+ let mask = 0;
313
+ for (const s of arr) {
314
+ if (typeof s !== "string" || s.length === 0) throw new KhrValidationError(`collisionFilter.${label} has invalid system`);
315
+ mask |= 1 << bitFor(s);
316
+ }
317
+ return mask;
315
318
  };
316
- }
317
- var templateMetaMap = /* @__PURE__ */ new WeakMap();
318
- function registerKhrTemplateMeta(scene, meta) {
319
- templateMetaMap.set(scene, meta);
320
- }
321
- function setSocket(sockets, key, pos) {
322
- Object.defineProperty(sockets, key, {
323
- value: pos,
324
- enumerable: true,
325
- configurable: true,
326
- writable: true
319
+ return rawFilters.map((f, idx) => {
320
+ if (!isObj(f)) throw new KhrValidationError(`collisionFilters[${idx}] must be an object`);
321
+ if (f.collideWithSystems !== void 0 && f.notCollideWithSystems !== void 0) throw new KhrValidationError(`collisionFilters[${idx}] cannot specify both collideWithSystems and notCollideWithSystems`);
322
+ const membership = maskFor(f.collisionSystems, "collisionSystems");
323
+ const filter = f.collideWithSystems === void 0 ? 65535 & ~maskFor(f.notCollideWithSystems, "notCollideWithSystems") : maskFor(f.collideWithSystems, "collideWithSystems");
324
+ return (membership & 65535) << 16 | filter & 65535;
327
325
  });
328
326
  }
329
- function applyKhrCustomExtractors(clonedBundle, templateBundle, extractRole, isSocketNode) {
330
- const meta = templateMetaMap.get(templateBundle.scene);
331
- if (!meta) return;
332
- if (extractRole) for (let i = 0; i < clonedBundle.bodies.length; i++) {
333
- const rawBody = meta.bodies[i];
334
- const dstBody = clonedBundle.bodies[i];
335
- if (!rawBody || !dstBody) continue;
336
- const role = extractRole(rawBody.nodeName, rawBody.extras) ?? (typeof rawBody.extras.role === "string" ? rawBody.extras.role : null);
337
- dstBody.role = role;
338
- if (dstBody.joint) dstBody.joint.role = role;
339
- }
340
- if (isSocketNode) {
341
- const sockets = {};
342
- for (const node of meta.nodes) {
343
- const custom = isSocketNode(node.nodeName, node.extras);
344
- if (custom || node.extras.isIkAnchor === true || typeof node.extras.socketId === "string") setSocket(sockets, typeof custom === "string" && custom.length > 0 ? custom : typeof node.extras.socketId === "string" ? node.extras.socketId : node.nodeName, [...node.worldPosition]);
345
- if (node.contactDots) for (const [role, pos] of node.contactDots) setSocket(sockets, role, [...pos]);
346
- }
347
- for (const [key, pos] of meta.ikSockets) setSocket(sockets, key, [...pos]);
348
- clonedBundle.sockets = sockets;
327
+ function decodeMotion(motion, hasMotion, name) {
328
+ if (motion.isKinematic !== void 0 && typeof motion.isKinematic !== "boolean") throw new KhrValidationError(`Node "${name}" has non-boolean motion.isKinematic`);
329
+ const isKinematic = !hasMotion || Boolean(motion.isKinematic);
330
+ let mass = 0;
331
+ if (!isKinematic) {
332
+ if (!isPosNum(motion.mass)) throw new KhrValidationError(`Dynamic node "${name}" is missing positive finite motion.mass`);
333
+ mass = motion.mass;
334
+ } else if (motion.mass !== void 0) {
335
+ if (!isNonNegNum(motion.mass)) throw new KhrValidationError(`Kinematic node "${name}" has invalid motion.mass`);
336
+ mass = motion.mass;
349
337
  }
350
- }
351
- var _dotVec = new THREE.Vector3();
352
- var _quat = new THREE.Quaternion();
353
- var isObj$3 = (v) => typeof v === "object" && !!v && !Array.isArray(v);
354
- var isFiniteNum = (v) => typeof v === "number" && Number.isFinite(v);
355
- function collectNodeSockets(obj, name, extras, sockets, isSocketNode) {
356
- if (extras.socketId !== void 0 && (typeof extras.socketId !== "string" || extras.socketId.length === 0)) throw new KhrValidationError(`Node "${name}" has invalid extras.socketId`);
357
- const wp = obj.getWorldPosition(new THREE.Vector3());
358
- const worldPosition = [
359
- wp.x,
360
- wp.y,
361
- wp.z
338
+ const centerOfMass = motion.centerOfMass === void 0 ? [
339
+ 0,
340
+ 0,
341
+ 0
342
+ ] : readFiniteVec3(motion.centerOfMass, `${name}.motion.centerOfMass`);
343
+ const inertiaOrientation = motion.inertiaOrientation === void 0 ? [
344
+ 0,
345
+ 0,
346
+ 0,
347
+ 1
348
+ ] : readUnitQuat(motion.inertiaOrientation, `${name}.motion.inertiaOrientation`);
349
+ let inertiaDiagonal = [
350
+ 0,
351
+ 0,
352
+ 0
362
353
  ];
363
- const custom = isSocketNode?.(name, extras);
364
- if (custom || extras.isIkAnchor === true || typeof extras.socketId === "string") setSocket(sockets, typeof custom === "string" && custom.length > 0 ? custom : typeof extras.socketId === "string" ? extras.socketId : name, [...worldPosition]);
365
- let contactDots;
366
- if (extras.contactDots !== void 0) {
367
- if (!Array.isArray(extras.contactDots)) throw new KhrValidationError(`Node "${name}" has invalid extras.contactDots (expected array)`);
368
- obj.getWorldQuaternion(_quat);
369
- contactDots = [];
370
- for (const dot of extras.contactDots) {
371
- if (!isObj$3(dot) || typeof dot.role !== "string" || dot.role.length === 0 || !Array.isArray(dot.pos) || dot.pos.length !== 3 || !dot.pos.every(isFiniteNum)) throw new KhrValidationError(`Node "${name}" has invalid entry in extras.contactDots`);
372
- _dotVec.set(dot.pos[0], dot.pos[1], dot.pos[2]).applyQuaternion(_quat).add(wp);
373
- const dotPos = [
374
- _dotVec.x,
375
- _dotVec.y,
376
- _dotVec.z
377
- ];
378
- setSocket(sockets, dot.role, dotPos);
379
- contactDots.push([dot.role, dotPos]);
380
- }
354
+ const hasExplicitInertia = motion.inertiaDiagonal !== void 0;
355
+ if (hasExplicitInertia) {
356
+ inertiaDiagonal = readFiniteVec3(motion.inertiaDiagonal, `${name}.motion.inertiaDiagonal`);
357
+ if (inertiaDiagonal.some((n) => isKinematic ? n < 0 : n <= 0)) throw new KhrValidationError(`Node "${name}" has invalid motion.inertiaDiagonal`);
381
358
  }
359
+ const linearVelocity = motion.linearVelocity === void 0 ? void 0 : readFiniteVec3(motion.linearVelocity, `${name}.motion.linearVelocity`);
360
+ const angularVelocity = motion.angularVelocity === void 0 ? void 0 : readFiniteVec3(motion.angularVelocity, `${name}.motion.angularVelocity`);
361
+ const gravityFactor = optFiniteNum(motion.gravityFactor, `${name}.motion.gravityFactor`);
382
362
  return {
383
- nodeName: name,
384
- extras,
385
- worldPosition,
386
- ...contactDots ? { contactDots } : {}
363
+ isKinematic,
364
+ hasExplicitMotion: hasMotion,
365
+ mass,
366
+ centerOfMass,
367
+ inertiaDiagonal,
368
+ inertiaOrientation,
369
+ hasExplicitInertia,
370
+ ...linearVelocity ? { linearVelocity } : {},
371
+ ...angularVelocity ? { angularVelocity } : {},
372
+ ...gravityFactor === void 0 ? {} : { gravityFactor }
387
373
  };
388
374
  }
389
- // src/khrJointParser.ts
390
- var isObj$2 = (v) => typeof v === "object" && !!v && !Array.isArray(v);
391
375
  var axisVector = (axis) => axis === 0 ? [
392
376
  1,
393
377
  0,
@@ -401,25 +385,19 @@ var axisVector = (axis) => axis === 0 ? [
401
385
  0,
402
386
  1
403
387
  ];
404
- function optNum$2(v, label, nonNeg = false) {
405
- if (v !== void 0) {
406
- if (typeof v !== "number" || !Number.isFinite(v) || nonNeg && v < 0) throw new KhrValidationError(`Invalid ${label}`);
407
- return v;
408
- }
409
- }
410
388
  function decodeJointDrives(rawDrives, jointIdx, nodeName) {
411
389
  return rawDrives.map((d, i) => {
412
390
  const label = `physicsJoints[${jointIdx}].drives[${i}] on "${nodeName}"`;
413
- if (!isObj$2(d)) throw new KhrValidationError(`${label} must be an object`);
391
+ if (!isObj(d)) throw new KhrValidationError(`${label} must be an object`);
414
392
  if (d.mode !== "force" && d.mode !== "acceleration") throw new KhrValidationError(`${label} missing valid drive.mode`);
415
393
  if (d.axis !== 0 && d.axis !== 1 && d.axis !== 2) throw new KhrValidationError(`${label} missing valid drive.axis (0|1|2)`);
416
394
  if (d.type !== void 0 && d.type !== "linear" && d.type !== "angular") throw new KhrValidationError(`${label} invalid drive.type`);
417
- const positionTarget = optNum$2(d.positionTarget, `${label} drive.positionTarget`);
418
- const velocityTarget = optNum$2(d.velocityTarget, `${label} drive.velocityTarget`);
395
+ const positionTarget = optFiniteNum(d.positionTarget, `${label} drive.positionTarget`);
396
+ const velocityTarget = optFiniteNum(d.velocityTarget, `${label} drive.velocityTarget`);
419
397
  if (positionTarget === void 0 && velocityTarget === void 0) throw new KhrValidationError(`${label} requires finite drive.positionTarget or drive.velocityTarget`);
420
- const stiffness = optNum$2(d.stiffness, `${label} drive.stiffness`, true);
421
- const damping = optNum$2(d.damping, `${label} drive.damping`, true);
422
- const maxForce = optNum$2(d.maxForce, `${label} drive.maxForce`, true);
398
+ const stiffness = optFiniteNum(d.stiffness, `${label} drive.stiffness`, true);
399
+ const damping = optFiniteNum(d.damping, `${label} drive.damping`, true);
400
+ const maxForce = optFiniteNum(d.maxForce, `${label} drive.maxForce`, true);
423
401
  return {
424
402
  ...d.type ? { type: d.type } : {},
425
403
  mode: d.mode,
@@ -434,7 +412,7 @@ function decodeJointDrives(rawDrives, jointIdx, nodeName) {
434
412
  }
435
413
  function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, enableCollision, role, connectedNodeName = connectedNode.name) {
436
414
  const raw = rawJoints[jointIdx];
437
- if (!isObj$2(raw)) throw new KhrValidationError(`physicsJoints[${jointIdx}] out of bounds for "${nodeName}"`);
415
+ if (!isObj(raw)) throw new KhrValidationError(`physicsJoints[${jointIdx}] out of bounds for "${nodeName}"`);
438
416
  if (raw.limits !== void 0 && !Array.isArray(raw.limits)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits on "${nodeName}" must be an array`);
439
417
  if (raw.drives !== void 0 && !Array.isArray(raw.drives)) throw new KhrValidationError(`physicsJoints[${jointIdx}].drives on "${nodeName}" must be an array`);
440
418
  const rawLimits = raw.limits ?? [];
@@ -466,12 +444,12 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
466
444
  if (ax !== 0 && ax !== 1 && ax !== 2) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits invalid axis ${String(ax)} on "${nodeName}"`);
467
445
  return ax;
468
446
  });
469
- const min = optNum$2(lim.min, `physicsJoints[${jointIdx}] limit.min on "${nodeName}"`);
470
- const max = optNum$2(lim.max, `physicsJoints[${jointIdx}] limit.max on "${nodeName}"`);
447
+ const min = optFiniteNum(lim.min, `physicsJoints[${jointIdx}] limit.min on "${nodeName}"`);
448
+ const max = optFiniteNum(lim.max, `physicsJoints[${jointIdx}] limit.max on "${nodeName}"`);
471
449
  if ((lim.min !== void 0 || lim.max !== void 0) && (min === void 0 || max === void 0)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits on "${nodeName}" must specify both min and max`);
472
450
  if (min !== void 0 && max !== void 0 && min > max) throw new KhrValidationError(`physicsJoints[${jointIdx}] limit.min > limit.max on "${nodeName}"`);
473
- const stiffness = optNum$2(lim.stiffness, `physicsJoints[${jointIdx}] limit.stiffness on "${nodeName}"`, true);
474
- const damping = optNum$2(lim.damping, `physicsJoints[${jointIdx}] limit.damping on "${nodeName}"`, true);
451
+ const stiffness = optFiniteNum(lim.stiffness, `physicsJoints[${jointIdx}] limit.stiffness on "${nodeName}"`, true);
452
+ const damping = optFiniteNum(lim.damping, `physicsJoints[${jointIdx}] limit.damping on "${nodeName}"`, true);
475
453
  const locked = min !== void 0 && max !== void 0 && max - min <= 1e-6;
476
454
  if (!locked && axes.length > 1) throw new KhrValidationError(`physicsJoints[${jointIdx}] coupled multi-axis limit on "${nodeName}" is unsupported`);
477
455
  for (const ax of axes) {
@@ -483,7 +461,7 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
483
461
  }
484
462
  };
485
463
  for (const lim of rawLimits) {
486
- if (!isObj$2(lim)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits entry on "${nodeName}" must be an object`);
464
+ if (!isObj(lim)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits entry on "${nodeName}" must be an object`);
487
465
  applyAxes(lim.linearAxes, lim, lin, linGain);
488
466
  applyAxes(lim.angularAxes, lim, ang, angGain);
489
467
  }
@@ -520,7 +498,7 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
520
498
  gain = linGain[freeLin[0]];
521
499
  } else throw new KhrValidationError(`physicsJoints[${jointIdx}] unsupported DOF (${freeLin.length} lin, ${freeAng.length} ang) on "${nodeName}"`);
522
500
  const drives = decodeJointDrives(rawDrives, jointIdx, nodeName);
523
- if (isObj$2(raw.extras) && Array.isArray(raw.extras.jointAxis) && raw.extras.jointAxis.length === 3 && raw.extras.jointAxis.every((n) => typeof n === "number" && Number.isFinite(n))) {
501
+ if (isObj(raw.extras) && Array.isArray(raw.extras.jointAxis) && raw.extras.jointAxis.length === 3 && raw.extras.jointAxis.every(isFiniteNum)) {
524
502
  const [jx, jy, jz] = raw.extras.jointAxis;
525
503
  const jLen = Math.hypot(jx, jy, jz);
526
504
  if (jLen > 1e-8) axis = [
@@ -555,228 +533,258 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
555
533
  ]
556
534
  };
557
535
  }
558
- // src/khrShapeParser.ts
559
- var isObj$1 = (v) => typeof v === "object" && !!v && !Array.isArray(v);
560
- var isPos$2 = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
561
- var COMBINE_MODES$1 = /* @__PURE__ */ new Set([
562
- "average",
563
- "minimum",
564
- "maximum",
565
- "multiply"
566
- ]);
567
- function optNum$1(v, label, nonNeg = false) {
568
- if (v !== void 0) {
569
- if (typeof v !== "number" || !Number.isFinite(v) || nonNeg && v < 0) throw new KhrValidationError(`Invalid ${label}`);
570
- return v;
536
+ var _quat = new THREE.Quaternion();
537
+ var _invParentQuat = new THREE.Quaternion();
538
+ var _localOrigin = new THREE.Vector3(0, 0, 0);
539
+ function getRelativeQuatArray(obj, parent) {
540
+ obj.updateWorldMatrix(true, false);
541
+ obj.getWorldQuaternion(_quat);
542
+ if (parent) {
543
+ parent.updateWorldMatrix(true, false);
544
+ _quat.premultiply(parent.getWorldQuaternion(_invParentQuat).invert());
571
545
  }
546
+ if (_quat.lengthSq() > 0) _quat.normalize();
547
+ else _quat.identity();
548
+ return [
549
+ _quat.x,
550
+ _quat.y,
551
+ _quat.z,
552
+ _quat.w
553
+ ];
572
554
  }
573
- function optCombineMode(v, label) {
574
- if (v === void 0) return void 0;
575
- if (typeof v !== "string" || !COMBINE_MODES$1.has(v)) throw new KhrValidationError(`Invalid ${label}: "${String(v)}"`);
576
- return v;
555
+ /**
556
+ * Resolves the physical hub shaft center of a wheel or propeller node:
557
+ * uses the authored glTF node origin (`getWorldPosition`) whenever the node has a non-zero transform
558
+ * or its local mesh bounds contain `(0, 0, 0)` (preventing 3-blade rotor / caliper AABB wobble),
559
+ * falling back to mesh AABB center only when an uncentered mesh was exported with its node left at `(0, 0, 0)`.
560
+ */
561
+ function resolveRotorHubPosition(obj) {
562
+ const wp = obj.getWorldPosition(new THREE.Vector3());
563
+ if (wp.lengthSq() > 1e-8) return [
564
+ wp.x,
565
+ wp.y,
566
+ wp.z
567
+ ];
568
+ const invObj = obj.matrixWorld.clone().invert();
569
+ const rel = new THREE.Matrix4();
570
+ const v = new THREE.Vector3();
571
+ const localBox = new THREE.Box3();
572
+ obj.traverse((child) => {
573
+ const mesh = child;
574
+ if (!mesh.isMesh || !mesh.geometry) return;
575
+ const pos = mesh.geometry.getAttribute("position");
576
+ if (!pos) return;
577
+ rel.multiplyMatrices(invObj, mesh.matrixWorld);
578
+ for (let i = 0; i < pos.count; i++) localBox.expandByPoint(v.fromBufferAttribute(pos, i).applyMatrix4(rel));
579
+ });
580
+ if (localBox.isEmpty() || localBox.containsPoint(_localOrigin)) return [
581
+ wp.x,
582
+ wp.y,
583
+ wp.z
584
+ ];
585
+ const c = new THREE.Box3().setFromObject(obj).getCenter(new THREE.Vector3());
586
+ return [
587
+ c.x,
588
+ c.y,
589
+ c.z
590
+ ];
577
591
  }
578
- function decodeShape(raw, idx) {
579
- if (!isObj$1(raw)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] must be an object`);
580
- const type = raw.type;
581
- if (type === "box") {
582
- if (raw.box !== void 0 && !isObj$1(raw.box)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid box`);
583
- const box = isObj$1(raw.box) ? raw.box : {};
584
- const size = box.size === void 0 ? [
585
- 1,
586
- 1,
587
- 1
588
- ] : box.size;
589
- if (!Array.isArray(size) || size.length !== 3 || !size.every(isPos$2)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid box.size`);
590
- return {
591
- type: "box",
592
- size: [
593
- size[0],
594
- size[1],
595
- size[2]
596
- ]
597
- };
598
- }
599
- if (type === "sphere") {
600
- if (raw.sphere !== void 0 && !isObj$1(raw.sphere)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid sphere`);
601
- const sphere = isObj$1(raw.sphere) ? raw.sphere : {};
602
- const radius = sphere.radius === void 0 ? .5 : sphere.radius;
603
- if (!isPos$2(radius)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid sphere.radius`);
604
- return {
605
- type: "sphere",
606
- radius
607
- };
608
- }
609
- if (type === "cylinder" || type === "capsule") {
610
- if (raw[type] !== void 0 && !isObj$1(raw[type])) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}`);
611
- const g = isObj$1(raw[type]) ? raw[type] : {};
612
- const height = g.height === void 0 ? type === "cylinder" ? 2 : 1 : g.height;
613
- if (!isPos$2(height)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.height`);
614
- if (g.radius !== void 0 && !isPos$2(g.radius)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radius`);
615
- const baseR = g.radius === void 0 ? .5 : g.radius;
616
- const radiusTop = g.radiusTop === void 0 ? baseR : g.radiusTop;
617
- const radiusBottom = g.radiusBottom === void 0 ? baseR : g.radiusBottom;
618
- if (!isPos$2(radiusTop)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radiusTop`);
619
- if (!isPos$2(radiusBottom)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radiusBottom`);
620
- if (Math.abs(radiusTop - radiusBottom) > 1e-6) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] tapered ${type} (${radiusTop} !== ${radiusBottom}) is unsupported`);
621
- return {
622
- type,
623
- height,
624
- radiusTop,
625
- radiusBottom
626
- };
627
- }
628
- throw new KhrValidationError(`KHR_implicit_shapes[${idx}] unsupported shape type "${String(type)}"`);
592
+ function optRotorNum(obj, key, tagKind, owner, strictlyPos = false) {
593
+ const val = obj[key];
594
+ if (val === void 0) return void 0;
595
+ if (!isFiniteNum(val) || (strictlyPos ? val <= 0 : val < 0)) throw new KhrValidationError(`${tagKind} "${owner}" has invalid ${tagKind}.${key}`);
596
+ return val;
629
597
  }
630
- function decodePhysicsMaterial(rawMaterials, idx, ownerName) {
631
- if (idx === void 0) return {};
632
- if (typeof idx !== "number" || !Number.isInteger(idx) || idx < 0 || idx >= rawMaterials.length) throw new KhrValidationError(`Node "${ownerName}" references out-of-bounds physicsMaterial ${String(idx)}`);
633
- const mat = rawMaterials[idx];
634
- if (!isObj$1(mat)) throw new KhrValidationError(`Invalid physicsMaterials[${idx}] on "${ownerName}"`);
635
- const dynF = optNum$1(mat.dynamicFriction, `physicsMaterials[${idx}].dynamicFriction`, true);
636
- const statF = optNum$1(mat.staticFriction, `physicsMaterials[${idx}].staticFriction`, true);
637
- const rest = optNum$1(mat.restitution, `physicsMaterials[${idx}].restitution`, true);
638
- const frictionCombine = optCombineMode(mat.frictionCombine, `physicsMaterials[${idx}].frictionCombine`);
639
- const restitutionCombine = optCombineMode(mat.restitutionCombine, `physicsMaterials[${idx}].restitutionCombine`);
640
- return {
641
- ...dynF !== void 0 || statF !== void 0 ? { friction: dynF ?? statF } : {},
642
- ...rest === void 0 ? {} : { restitution: rest },
643
- ...frictionCombine === void 0 ? {} : { frictionCombine },
644
- ...restitutionCombine === void 0 ? {} : { restitutionCombine }
645
- };
598
+ function reqRotorNum(obj, key, tagKind, owner, strictlyPos = false) {
599
+ const val = obj[key];
600
+ if (!isFiniteNum(val) || (strictlyPos ? val <= 0 : val < 0)) throw new KhrValidationError(`${tagKind} "${owner}" is missing valid ${tagKind}.${key}`);
601
+ return val;
646
602
  }
647
- // src/khrParsers.ts
648
- var isPos$1 = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
649
- var isNonNeg$1 = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
650
- function optNum(v, label, nonNeg = false) {
651
- if (v !== void 0) {
652
- if (typeof v !== "number" || !Number.isFinite(v) || nonNeg && v < 0) throw new KhrValidationError(`Invalid ${label}`);
653
- return v;
654
- }
603
+ function optRotorBool(obj, key, tagKind, owner) {
604
+ const val = obj[key];
605
+ if (val === void 0) return void 0;
606
+ if (typeof val !== "boolean") throw new KhrValidationError(`${tagKind} "${owner}" has non-boolean ${tagKind}.${key}`);
607
+ return val;
655
608
  }
656
- function decodeMotion(motion, hasMotion, name) {
657
- if (motion.isKinematic !== void 0 && typeof motion.isKinematic !== "boolean") throw new KhrValidationError(`Node "${name}" has non-boolean motion.isKinematic`);
658
- const isKinematic = !hasMotion || Boolean(motion.isKinematic);
659
- let mass = 0;
660
- if (!isKinematic) {
661
- if (!isPos$1(motion.mass)) throw new KhrValidationError(`Dynamic node "${name}" is missing positive finite motion.mass`);
662
- mass = motion.mass;
663
- } else if (motion.mass !== void 0) {
664
- if (!isNonNeg$1(motion.mass)) throw new KhrValidationError(`Kinematic node "${name}" has invalid motion.mass`);
665
- mass = motion.mass;
666
- }
667
- const centerOfMass = motion.centerOfMass === void 0 ? [
668
- 0,
669
- 0,
670
- 0
671
- ] : readFiniteVec3(motion.centerOfMass, `${name}.motion.centerOfMass`);
672
- const inertiaOrientation = motion.inertiaOrientation === void 0 ? [
673
- 0,
674
- 0,
675
- 0,
676
- 1
677
- ] : readUnitQuat(motion.inertiaOrientation, `${name}.motion.inertiaOrientation`);
678
- let inertiaDiagonal = [
679
- 0,
680
- 0,
681
- 0
682
- ];
683
- const hasExplicitInertia = motion.inertiaDiagonal !== void 0;
684
- if (hasExplicitInertia) {
685
- inertiaDiagonal = readFiniteVec3(motion.inertiaDiagonal, `${name}.motion.inertiaDiagonal`);
686
- if (inertiaDiagonal.some((n) => isKinematic ? n < 0 : n <= 0)) throw new KhrValidationError(`Node "${name}" has invalid motion.inertiaDiagonal`);
687
- }
688
- const linearVelocity = motion.linearVelocity === void 0 ? void 0 : readFiniteVec3(motion.linearVelocity, `${name}.motion.linearVelocity`);
689
- const angularVelocity = motion.angularVelocity === void 0 ? void 0 : readFiniteVec3(motion.angularVelocity, `${name}.motion.angularVelocity`);
690
- const gravityFactor = optNum(motion.gravityFactor, `${name}.motion.gravityFactor`);
691
- return {
692
- isKinematic,
693
- mass,
694
- centerOfMass,
695
- inertiaDiagonal,
696
- inertiaOrientation,
697
- hasExplicitInertia,
698
- ...linearVelocity ? { linearVelocity } : {},
699
- ...angularVelocity ? { angularVelocity } : {},
700
- ...gravityFactor === void 0 ? {} : { gravityFactor }
701
- };
609
+ function reqRotorBool(obj, key, tagKind, owner) {
610
+ const val = obj[key];
611
+ if (typeof val !== "boolean") throw new KhrValidationError(`${tagKind} "${owner}" is missing boolean ${tagKind}.${key}`);
612
+ return val;
702
613
  }
703
- function decodeCollisionGroups(rawFilters) {
704
- const collisionSystemIds = /* @__PURE__ */ new Map([["default", 0]]);
705
- let nextCollisionBit = 1;
706
- const bitFor = (sys) => {
707
- const hit = collisionSystemIds.get(sys);
708
- if (hit !== void 0) return hit;
709
- if (nextCollisionBit > 15) throw new KhrValidationError(`Exceeded Rapier 16-group limit for collisionSystem "${sys}"`);
710
- const b = nextCollisionBit++;
711
- collisionSystemIds.set(sys, b);
712
- return b;
713
- };
714
- const maskFor = (arr, label) => {
715
- if (arr === void 0) return 0;
716
- if (!Array.isArray(arr)) throw new KhrValidationError(`collisionFilter.${label} must be an array`);
717
- let mask = 0;
718
- for (const s of arr) {
719
- if (typeof s !== "string" || s.length === 0) throw new KhrValidationError(`collisionFilter.${label} has invalid system`);
720
- mask |= 1 << bitFor(s);
721
- }
722
- return mask;
614
+ function optBoolOrNumFlag(obj, key, tagKind, owner) {
615
+ const val = obj[key];
616
+ if (val === void 0) return void 0;
617
+ if (typeof val === "boolean") return { flag: val };
618
+ if (isNonNegNum(val)) return {
619
+ flag: val !== 0,
620
+ numeric: val
723
621
  };
724
- return rawFilters.map((f, idx) => {
725
- if (!f || typeof f !== "object" || Array.isArray(f)) throw new KhrValidationError(`collisionFilters[${idx}] must be an object`);
726
- if (f.collideWithSystems !== void 0 && f.notCollideWithSystems !== void 0) throw new KhrValidationError(`collisionFilters[${idx}] cannot specify both collideWithSystems and notCollideWithSystems`);
727
- const membership = maskFor(f.collisionSystems, "collisionSystems");
728
- const filter = f.collideWithSystems === void 0 ? 65535 & ~maskFor(f.notCollideWithSystems, "notCollideWithSystems") : maskFor(f.collideWithSystems, "collideWithSystems");
729
- return (membership & 65535) << 16 | filter & 65535;
730
- });
622
+ throw new KhrValidationError(`${tagKind} "${owner}" has invalid ${tagKind}.${key}`);
731
623
  }
732
- // src/khrPluginHelpers.ts
733
- var isPlainObject = (v) => typeof v === "object" && !!v && !Array.isArray(v);
734
- function reqArr(val, label) {
735
- if (val === void 0) return [];
736
- if (!Array.isArray(val)) throw new KhrValidationError(`${label} must be an array`);
624
+ function optCurve(val, key, owner) {
625
+ if (val === void 0) return void 0;
626
+ if (!isObj(val) || !Array.isArray(val.points) || val.points.length === 0) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid ecctrlWheel.${key}`);
627
+ for (const pt of val.points) if (!isObj(pt) || !isFiniteNum(pt.x) || !isFiniteNum(pt.y)) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid point in ecctrlWheel.${key}`);
628
+ if (val.samples !== void 0 && !isPosNum(val.samples)) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid samples in ecctrlWheel.${key}`);
737
629
  return val;
738
630
  }
739
- var HEADLESS_TEXTURE_EXT_NAMES = [
740
- "EXT_texture_webp",
741
- "EXT_texture_avif",
742
- "KHR_texture_basisu"
743
- ];
744
- function isHeadlessTextureEnv() {
745
- return typeof document === "undefined" && (typeof createImageBitmap === "undefined" || typeof self === "undefined");
631
+ function decodeWheelTag(obj, name, rawWheel, scene, rawOmiWheel) {
632
+ assertIdentityWorldScale(obj, name);
633
+ const hasOmi = rawOmiWheel !== void 0;
634
+ if (hasOmi && !isObj(rawOmiWheel)) throw new KhrValidationError(`OMI_vehicle_wheel "${name}" must be an object`);
635
+ if (rawWheel !== void 0 && !isObj(rawWheel)) throw new KhrValidationError(`ecctrlWheel "${name}" must be an object`);
636
+ if (!hasOmi && rawWheel === void 0) throw new KhrValidationError(`ecctrlWheel "${name}" must be an object`);
637
+ const ec = isObj(rawWheel) ? rawWheel : {};
638
+ const omi = isObj(rawOmiWheel) ? rawOmiWheel : void 0;
639
+ const omiRadius = omi ? optRotorNum(omi, "radius", "OMI_vehicle_wheel", name, true) : void 0;
640
+ const omiWidth = omi ? optRotorNum(omi, "width", "OMI_vehicle_wheel", name, true) : void 0;
641
+ const radius = optRotorNum(ec, "radius", "ecctrlWheel", name, true) ?? omiRadius;
642
+ const width = optRotorNum(ec, "width", "ecctrlWheel", name, true) ?? omiWidth;
643
+ if (radius === void 0) throw new KhrValidationError(`Wheel "${name}" is missing positive finite radius`);
644
+ if (width === void 0) throw new KhrValidationError(`Wheel "${name}" is missing positive finite width`);
645
+ const omiTravel = omi ? optRotorNum(omi, "suspensionTravel", "OMI_vehicle_wheel", name) : void 0;
646
+ const omiMaxForce = omi ? optRotorNum(omi, "maxForce", "OMI_vehicle_wheel", name) : void 0;
647
+ const omiMaxSteerRaw = omi ? optRotorNum(omi, "maxSteeringAngle", "OMI_vehicle_wheel", name) : void 0;
648
+ const omiStiffness = omi ? optRotorNum(omi, "suspensionStiffness", "OMI_vehicle_wheel", name) : void 0;
649
+ const omiDampComp = omi ? optRotorNum(omi, "suspensionDampingCompression", "OMI_vehicle_wheel", name) : void 0;
650
+ const omiDampReb = omi ? optRotorNum(omi, "suspensionDampingRebound", "OMI_vehicle_wheel", name) : void 0;
651
+ const omiSteer = omi ? optBoolOrNumFlag(omi, "steering", "OMI_vehicle_wheel", name) : void 0;
652
+ const omiProp = omi ? optBoolOrNumFlag(omi, "propulsion", "OMI_vehicle_wheel", name) : void 0;
653
+ const omiMaxSteer = omiMaxSteerRaw ?? (omiSteer?.numeric !== void 0 && omiSteer.numeric > 0 ? omiSteer.numeric : void 0);
654
+ const travel = omi ? optRotorNum(ec, "travel", "ecctrlWheel", name) ?? omiTravel ?? .25 : reqRotorNum(ec, "travel", "ecctrlWheel", name);
655
+ const sag = omi ? optRotorNum(ec, "sag", "ecctrlWheel", name) ?? (travel > 0 ? Math.min(travel * .4, .1) : 0) : reqRotorNum(ec, "sag", "ecctrlWheel", name);
656
+ if (sag > travel) throw new KhrValidationError(`ecctrlWheel "${name}" has invalid sag (${sag}) > travel (${travel})`);
657
+ const steer = omi ? optRotorBool(ec, "steer", "ecctrlWheel", name) ?? omiSteer?.flag ?? (omiMaxSteer !== void 0 ? omiMaxSteer > 0 : false) : reqRotorBool(ec, "steer", "ecctrlWheel", name);
658
+ const drive = omi ? optRotorBool(ec, "drive", "ecctrlWheel", name) ?? omiProp?.flag ?? false : reqRotorBool(ec, "drive", "ecctrlWheel", name);
659
+ const brake = omi ? optRotorBool(ec, "brake", "ecctrlWheel", name) ?? true : reqRotorBool(ec, "brake", "ecctrlWheel", name);
660
+ const omiDamping = omiDampComp !== void 0 && omiDampReb !== void 0 ? .5 * (omiDampComp + omiDampReb) : omiDampComp ?? omiDampReb;
661
+ const springK = optRotorNum(ec, "springK", "ecctrlWheel", name) ?? omiStiffness;
662
+ const dampingC = optRotorNum(ec, "dampingC", "ecctrlWheel", name) ?? omiDamping;
663
+ const maxBrakeTorque = optRotorNum(ec, "maxBrakeTorque", "ecctrlWheel", name) ?? (omiMaxForce !== void 0 ? omiMaxForce * radius : void 0);
664
+ const maxSteeringAngle = optRotorNum(ec, "maxSteeringAngle", "ecctrlWheel", name) ?? omiMaxSteer;
665
+ return {
666
+ nodeName: name,
667
+ object: obj,
668
+ position: resolveRotorHubPosition(obj),
669
+ quaternion: getRelativeQuatArray(obj, scene),
670
+ radius,
671
+ width,
672
+ steer,
673
+ steerInvert: optRotorBool(ec, "steerInvert", "ecctrlWheel", name),
674
+ drive,
675
+ driveInvert: optRotorBool(ec, "driveInvert", "ecctrlWheel", name),
676
+ brake,
677
+ travel,
678
+ sag,
679
+ springK,
680
+ dampingC,
681
+ maxBrakeTorque,
682
+ ...maxSteeringAngle === void 0 ? {} : { maxSteeringAngle },
683
+ rollingResistanceCoef: optRotorNum(ec, "rollingResistanceCoef", "ecctrlWheel", name),
684
+ wheelDensity: optRotorNum(ec, "wheelDensity", "ecctrlWheel", name, true),
685
+ driveTorqueWeight: optRotorNum(ec, "driveTorqueWeight", "ecctrlWheel", name),
686
+ tireGripFactor: optRotorNum(ec, "tireGripFactor", "ecctrlWheel", name),
687
+ latFrictionEllipseScale: optRotorNum(ec, "latFrictionEllipseScale", "ecctrlWheel", name),
688
+ relaxLngRate: optRotorNum(ec, "relaxLngRate", "ecctrlWheel", name),
689
+ relaxLatRate: optRotorNum(ec, "relaxLatRate", "ecctrlWheel", name),
690
+ lngSlipRatioCurveData: optCurve(ec.lngSlipRatioCurveData, "lngSlipRatioCurveData", name),
691
+ latSlipRatioCurveData: optCurve(ec.latSlipRatioCurveData, "latSlipRatioCurveData", name)
692
+ };
746
693
  }
747
- function stubTextureInParser(parser, textureIndex) {
748
- const tex = new THREE.Texture();
749
- tex.flipY = false;
750
- parser.associations.set(tex, { textures: textureIndex });
751
- return Promise.resolve(tex);
694
+ function decodePropellerTag(obj, name, rawPropeller, scene) {
695
+ assertIdentityWorldScale(obj, name);
696
+ if (!isObj(rawPropeller)) throw new KhrValidationError(`ecctrlPropeller "${name}" must be an object`);
697
+ if (!isPosNum(rawPropeller.maxThrust)) throw new KhrValidationError(`ecctrlPropeller "${name}" is missing positive finite ecctrlPropeller.maxThrust`);
698
+ const torqueRatio = optFiniteNum(rawPropeller.torqueRatio, `ecctrlPropeller "${name}".torqueRatio`);
699
+ return {
700
+ nodeName: name,
701
+ object: obj,
702
+ position: resolveRotorHubPosition(obj),
703
+ quaternion: getRelativeQuatArray(obj, scene),
704
+ maxThrust: rawPropeller.maxThrust,
705
+ torqueRatio,
706
+ invertThrust: optRotorBool(rawPropeller, "invertThrust", "ecctrlPropeller", name),
707
+ invertTorque: optRotorBool(rawPropeller, "invertTorque", "ecctrlPropeller", name)
708
+ };
752
709
  }
753
- function patchHeadlessTexturePlugins(parser) {
754
- const plugins = parser.plugins;
755
- if (!plugins) return;
756
- for (const extName of HEADLESS_TEXTURE_EXT_NAMES) {
757
- const existing = plugins[extName];
758
- if (!existing) continue;
759
- existing.loadTexture = (textureIndex) => {
760
- if (!(parser.json?.textures?.[textureIndex])?.extensions?.[extName]) return null;
761
- return stubTextureInParser(parser, textureIndex);
762
- };
710
+ function decodeBreakawaySpec(raw) {
711
+ if (!isObj(raw) || !isPosNum(raw.breakImpulseNs)) return void 0;
712
+ const latch = isPosNum(raw.latchImpulseNs) ? raw.latchImpulseNs : void 0;
713
+ return {
714
+ ...latch === void 0 ? {} : { latchImpulseNs: latch },
715
+ breakImpulseNs: raw.breakImpulseNs
716
+ };
717
+ }
718
+ var templateMetaMap = /* @__PURE__ */ new WeakMap();
719
+ function applyKhrCustomExtractors(clonedBundle, templateBundle, extractRole, isSocketNode) {
720
+ const meta = templateMetaMap.get(templateBundle.scene);
721
+ if (!meta) return;
722
+ if (extractRole) for (let i = 0; i < clonedBundle.bodies.length; i++) {
723
+ const rawBody = meta.bodies[i];
724
+ const dstBody = clonedBundle.bodies[i];
725
+ if (!rawBody || !dstBody) continue;
726
+ const role = extractRole(rawBody.nodeName, rawBody.extras) ?? (typeof rawBody.extras.role === "string" ? rawBody.extras.role : null);
727
+ dstBody.role = role;
728
+ if (dstBody.joint) dstBody.joint.role = role;
729
+ }
730
+ if (isSocketNode) {
731
+ const sockets = Object.create(null);
732
+ for (const node of meta.nodes) {
733
+ const custom = isSocketNode(node.nodeName, node.extras);
734
+ if (custom || node.extras.isIkAnchor === true || typeof node.extras.socketId === "string") {
735
+ const key = typeof custom === "string" && custom.length > 0 ? custom : typeof node.extras.socketId === "string" ? node.extras.socketId : node.nodeName;
736
+ sockets[key] = [...node.worldPosition];
737
+ }
738
+ if (node.contactDots) for (const [role, pos] of node.contactDots) sockets[role] = [...pos];
739
+ }
740
+ for (const [key, pos] of meta.ikSockets) sockets[key] = [...pos];
741
+ clonedBundle.sockets = sockets;
763
742
  }
764
743
  }
765
- function createHeadlessTexturePlugin() {
766
- return (parser) => ({
767
- name: "khr3_headless_texture",
768
- beforeRoot() {
769
- patchHeadlessTexturePlugins(parser);
770
- return null;
771
- },
772
- loadTexture: (textureIndex) => stubTextureInParser(parser, textureIndex)
773
- });
744
+ var _dotVec = new THREE.Vector3();
745
+ var _dotQuat = new THREE.Quaternion();
746
+ function collectNodeSockets(obj, name, extras, sockets, isSocketNode) {
747
+ if (extras.socketId !== void 0 && (typeof extras.socketId !== "string" || extras.socketId.length === 0)) throw new KhrValidationError(`Node "${name}" has invalid extras.socketId`);
748
+ const wp = obj.getWorldPosition(new THREE.Vector3());
749
+ const worldPosition = [
750
+ wp.x,
751
+ wp.y,
752
+ wp.z
753
+ ];
754
+ const custom = isSocketNode?.(name, extras);
755
+ if (custom || extras.isIkAnchor === true || typeof extras.socketId === "string") {
756
+ const key = typeof custom === "string" && custom.length > 0 ? custom : typeof extras.socketId === "string" ? extras.socketId : name;
757
+ sockets[key] = [...worldPosition];
758
+ }
759
+ let contactDots;
760
+ if (extras.contactDots !== void 0) {
761
+ if (!Array.isArray(extras.contactDots)) throw new KhrValidationError(`Node "${name}" has invalid extras.contactDots (expected array)`);
762
+ obj.getWorldQuaternion(_dotQuat);
763
+ contactDots = [];
764
+ for (const dot of extras.contactDots) {
765
+ if (!isObj(dot) || typeof dot.role !== "string" || dot.role.length === 0 || !Array.isArray(dot.pos) || dot.pos.length !== 3 || !dot.pos.every(isFiniteNum)) throw new KhrValidationError(`Node "${name}" has invalid entry in extras.contactDots`);
766
+ _dotVec.set(dot.pos[0], dot.pos[1], dot.pos[2]).applyQuaternion(_dotQuat).add(wp);
767
+ const dotPos = [
768
+ _dotVec.x,
769
+ _dotVec.y,
770
+ _dotVec.z
771
+ ];
772
+ sockets[dot.role] = dotPos;
773
+ contactDots.push([dot.role, dotPos]);
774
+ }
775
+ }
776
+ return {
777
+ nodeName: name,
778
+ extras,
779
+ worldPosition,
780
+ ...contactDots ? { contactDots } : {}
781
+ };
774
782
  }
775
- function buildNodeGraphLookup(gltf, rawNodes, rawGltf = gltf.parser?.json) {
783
+ function buildNodeGraphLookup(gltf, rawNodes, rawGltf) {
776
784
  const parentIdx = new Int32Array(rawNodes.length).fill(-1);
777
785
  for (let i = 0; i < rawNodes.length; i++) {
778
786
  const node = rawNodes[i];
779
- if (!isPlainObject(node)) throw new KhrValidationError(`GLTF node[${i}] must be an object`);
787
+ if (!isObj(node)) throw new KhrValidationError(`GLTF node[${i}] must be an object`);
780
788
  const label = typeof node.name === "string" && node.name.length > 0 ? node.name : String(i);
781
789
  if (node.children !== void 0) {
782
790
  if (!Array.isArray(node.children)) throw new KhrValidationError(`GLTF node "${label}" children must be an array`);
@@ -788,7 +796,7 @@ function buildNodeGraphLookup(gltf, rawNodes, rawGltf = gltf.parser?.json) {
788
796
  if (Array.isArray(rawGltf?.scenes)) {
789
797
  const sceneIdx = rawGltf.scene ?? 0;
790
798
  const sceneDef = rawGltf.scenes[sceneIdx];
791
- if (!isPlainObject(sceneDef)) throw new KhrValidationError(`GLTF scene[${sceneIdx}] must be an object`);
799
+ if (!isObj(sceneDef)) throw new KhrValidationError(`GLTF scene[${sceneIdx}] must be an object`);
792
800
  if (sceneDef.nodes !== void 0 && !Array.isArray(sceneDef.nodes)) throw new KhrValidationError(`GLTF scene[${sceneIdx}].nodes must be an array`);
793
801
  sceneRoots = (sceneDef.nodes ?? []).map((n, pos) => {
794
802
  if (typeof n !== "number" || !Number.isInteger(n) || n < 0 || n >= rawNodes.length) throw new KhrValidationError(`GLTF scene[${sceneIdx}].nodes[${pos}] has invalid node index ${String(n)}`);
@@ -839,20 +847,6 @@ function buildNodeGraphLookup(gltf, rawNodes, rawGltf = gltf.parser?.json) {
839
847
  if (typeof nIdx === "number" && inActiveScene.has(nIdx) && !byNodeIdx.has(nIdx)) byNodeIdx.set(nIdx, obj);
840
848
  if (obj.name && !byName.has(obj.name)) byName.set(obj.name, obj);
841
849
  });
842
- if (sceneRoots && gltf.scene.children.length === sceneRoots.length) {
843
- const seen = /* @__PURE__ */ new Set();
844
- const matchTree = (idx, obj) => {
845
- if (seen.has(idx)) return;
846
- seen.add(idx);
847
- if (!byNodeIdx.has(idx)) byNodeIdx.set(idx, obj);
848
- const children = rawNodes[idx].children;
849
- if (!children || children.length === 0) return;
850
- const offset = obj.children.length - children.length;
851
- if (offset < 0) return;
852
- for (let k = 0; k < children.length; k++) matchTree(children[k], obj.children[offset + k]);
853
- };
854
- for (let k = 0; k < sceneRoots.length; k++) matchTree(sceneRoots[k], gltf.scene.children[k]);
855
- }
856
850
  return {
857
851
  parentIdx,
858
852
  nodeNames,
@@ -866,32 +860,13 @@ function buildNodeGraphLookup(gltf, rawNodes, rawGltf = gltf.parser?.json) {
866
860
  }
867
861
  };
868
862
  }
869
- function resolveColliderShape(col, ownerName, shapes, nodeNames, resolveObj) {
870
- if (!isPlainObject(col)) throw new KhrValidationError(`Node "${ownerName}" has invalid collider (expected object)`);
871
- const geo = col.geometry;
872
- if (!isPlainObject(geo)) throw new KhrValidationError(`Node "${ownerName}" is missing collider.geometry object`);
873
- if (geo.shape !== void 0) {
874
- if (typeof geo.shape !== "number" || !Number.isInteger(geo.shape) || geo.shape < 0 || geo.shape >= shapes.length) throw new KhrValidationError(`Node "${ownerName}" references missing collider.geometry.shape ${String(geo.shape)}`);
875
- return shapes[geo.shape];
876
- }
877
- if (geo.node !== void 0) {
878
- if (typeof geo.node !== "number" || !Number.isInteger(geo.node)) throw new KhrValidationError(`Node "${ownerName}" has invalid collider.geometry.node`);
879
- if (geo.convexHull !== void 0 && typeof geo.convexHull !== "boolean") throw new KhrValidationError(`Node "${ownerName}" has non-boolean collider.geometry.convexHull`);
880
- const target = resolveObj(geo.node);
881
- const meshName = nodeNames[geo.node] ?? `node_${geo.node}`;
882
- if (!target) throw new KhrValidationError(`Node "${ownerName}" references missing mesh node "${meshName}"`);
883
- return extractMeshColliderShape(target, meshName, Boolean(geo.convexHull));
884
- }
885
- throw new KhrValidationError(`Node "${ownerName}" collider.geometry must specify shape or node`);
886
- }
887
- // src/khrBundleFinalize.ts
888
863
  function findOwnerBodyIdx(idx, parentIdx, rawNodes) {
889
864
  for (let p = parentIdx[idx]; p !== -1; p = parentIdx[p]) if (rawNodes[p].extensions?.KHR_physics_rigid_bodies?.motion) return p;
890
865
  return -1;
891
866
  }
892
867
  function resolveConnectedBodyIdx(cIdx, parentIdx, rawNodes) {
893
868
  const phys = rawNodes[cIdx]?.extensions?.KHR_physics_rigid_bodies;
894
- if (isPlainObject(phys) && (phys.motion !== void 0 || (phys.collider !== void 0 || phys.joint !== void 0) && findOwnerBodyIdx(cIdx, parentIdx, rawNodes) === -1)) return cIdx;
869
+ if (isObj(phys) && (phys.motion !== void 0 || (phys.collider !== void 0 || phys.joint !== void 0) && findOwnerBodyIdx(cIdx, parentIdx, rawNodes) === -1)) return cIdx;
895
870
  const owner = findOwnerBodyIdx(cIdx, parentIdx, rawNodes);
896
871
  return owner !== -1 ? owner : cIdx;
897
872
  }
@@ -899,87 +874,41 @@ function isInsideRotor(idx, parentIdx, rawNodes) {
899
874
  for (let p = idx; p !== -1; p = parentIdx[p]) {
900
875
  const node = rawNodes[p];
901
876
  const ex = node.extras;
902
- if (isPlainObject(ex) && (ex.ecctrlWheel !== void 0 || ex.ecctrlPropeller !== void 0)) return true;
903
- if (isPlainObject(node.extensions) && node.extensions.OMI_vehicle_wheel !== void 0) return true;
877
+ if (isObj(ex) && (ex.ecctrlWheel !== void 0 || ex.ecctrlPropeller !== void 0)) return true;
878
+ if (isObj(node.extensions) && node.extensions.OMI_vehicle_wheel !== void 0) return true;
904
879
  }
905
880
  return false;
906
881
  }
907
- function attachBodyColliders(rawNodes, parentIdx, nodeNames, resolveObj, bodyByIdx, shapes, materials, collisionGroups) {
908
- for (let i = 0; i < rawNodes.length; i++) {
909
- if (isInsideRotor(i, parentIdx, rawNodes)) continue;
910
- const rawCol = rawNodes[i].extensions?.KHR_physics_rigid_bodies?.collider;
911
- if (rawCol === void 0) continue;
912
- const obj = resolveObj(i);
913
- if (!obj) continue;
914
- const ownerIdx = bodyByIdx.has(i) ? i : findOwnerBodyIdx(i, parentIdx, rawNodes);
915
- const owner = bodyByIdx.get(ownerIdx);
916
- if (!owner) continue;
917
- const shape = resolveColliderShape(rawCol, nodeNames[i], shapes, nodeNames, resolveObj);
918
- const colDef = rawCol;
919
- const rel = ownerIdx === i ? {
920
- localPosition: [
921
- 0,
922
- 0,
923
- 0
924
- ],
925
- localQuaternion: [
926
- 0,
927
- 0,
928
- 0,
929
- 1
930
- ]
931
- } : computeRelativePose(owner.object, obj);
932
- const mat = decodePhysicsMaterial(materials, colDef.physicsMaterial, nodeNames[i]);
933
- let colGroups;
934
- if (colDef.collisionFilter !== void 0) {
935
- if (typeof colDef.collisionFilter !== "number" || !Number.isInteger(colDef.collisionFilter) || colDef.collisionFilter < 0 || colDef.collisionFilter >= collisionGroups.length) throw new KhrValidationError(`Node "${nodeNames[i]}" references out-of-bounds collisionFilter ${String(colDef.collisionFilter)}`);
936
- colGroups = collisionGroups[colDef.collisionFilter];
937
- }
938
- owner.colliders.push({
939
- shape,
940
- localPosition: rel.localPosition,
941
- localQuaternion: rel.localQuaternion,
942
- ...mat,
943
- ...colGroups === void 0 ? {} : { collisionGroups: colGroups }
944
- });
882
+ function resolveColliderShape(col, ownerName, shapes, nodeNames, resolveObj) {
883
+ if (!isObj(col)) throw new KhrValidationError(`Node "${ownerName}" has invalid collider (expected object)`);
884
+ const geo = col.geometry;
885
+ if (!isObj(geo)) throw new KhrValidationError(`Node "${ownerName}" is missing collider.geometry object`);
886
+ if (geo.shape !== void 0) {
887
+ if (typeof geo.shape !== "number" || !Number.isInteger(geo.shape) || geo.shape < 0 || geo.shape >= shapes.length) throw new KhrValidationError(`Node "${ownerName}" references missing collider.geometry.shape ${String(geo.shape)}`);
888
+ return shapes[geo.shape];
945
889
  }
946
- }
947
- function computeMissingBodyInertias(bodyByIdx, explicitInertiaSet) {
948
- for (const [idx, body] of bodyByIdx) if (!explicitInertiaSet.has(idx) && !body.isKinematic) body.inertiaDiagonal = computeBodyInertia(body.colliders, body.mass, body.centerOfMass, body.inertiaOrientation, body.nodeName);
949
- }
950
- function extractSceneExtras(json, sockets) {
951
- const ikSockets = [];
952
- const sceneExtras = json.scenes?.[json.scene ?? 0]?.extras ?? json.extras;
953
- if (sceneExtras?.ikSockets !== void 0) {
954
- if (!isPlainObject(sceneExtras.ikSockets)) throw new KhrValidationError("scene.extras.ikSockets must be an object");
955
- for (const [k, v] of Object.entries(sceneExtras.ikSockets)) {
956
- const pos = readFiniteVec3(v, `scene.extras.ikSockets.${k}`);
957
- setSocket(sockets, k, pos);
958
- ikSockets.push([k, pos]);
959
- }
890
+ if (geo.node !== void 0) {
891
+ if (typeof geo.node !== "number" || !Number.isInteger(geo.node)) throw new KhrValidationError(`Node "${ownerName}" has invalid collider.geometry.node`);
892
+ if (geo.convexHull !== void 0 && typeof geo.convexHull !== "boolean") throw new KhrValidationError(`Node "${ownerName}" has non-boolean collider.geometry.convexHull`);
893
+ const target = resolveObj(geo.node);
894
+ const meshName = nodeNames[geo.node] ?? `node_${geo.node}`;
895
+ if (!target) throw new KhrValidationError(`Node "${ownerName}" references missing mesh node "${meshName}"`);
896
+ return extractMeshColliderShape(target, meshName, Boolean(geo.convexHull));
960
897
  }
961
- return {
962
- ikSockets,
963
- tune: isPlainObject(sceneExtras?.tune) ? sceneExtras.tune : void 0,
964
- droneTune: isPlainObject(sceneExtras?.droneTune) ? sceneExtras.droneTune : void 0
965
- };
898
+ throw new KhrValidationError(`Node "${ownerName}" collider.geometry must specify shape or node`);
966
899
  }
967
- // src/khrPlugin.ts
968
- var KHR_BUNDLE_USERDATA_KEY = "khrBundle";
969
900
  function extractKhrBundleFromGltf(gltf, options) {
970
901
  if (!gltf.scene) throw new KhrValidationError("GLTF asset has no active scene");
971
- gltf.scene.updateMatrixWorld(true);
972
902
  assertSceneIdentityWorldScale(gltf.scene);
973
903
  const json = gltf.parser?.json;
974
904
  if (!json) throw new KhrValidationError("GLTFParser is missing parsed JSON");
975
- if (json.extensions !== void 0 && !isPlainObject(json.extensions)) throw new KhrValidationError("glTF extensions must be an object");
905
+ if (json.extensions !== void 0 && !isObj(json.extensions)) throw new KhrValidationError("glTF extensions must be an object");
976
906
  const khrPhys = json.extensions?.KHR_physics_rigid_bodies;
977
- if (khrPhys !== void 0 && !isPlainObject(khrPhys)) throw new KhrValidationError("KHR_physics_rigid_bodies extension must be an object");
907
+ if (khrPhys !== void 0 && !isObj(khrPhys)) throw new KhrValidationError("KHR_physics_rigid_bodies extension must be an object");
978
908
  const khrShapes = json.extensions?.KHR_implicit_shapes;
979
- if (khrShapes !== void 0 && !isPlainObject(khrShapes)) throw new KhrValidationError("KHR_implicit_shapes extension must be an object");
909
+ if (khrShapes !== void 0 && !isObj(khrShapes)) throw new KhrValidationError("KHR_implicit_shapes extension must be an object");
980
910
  const omiExt = json.extensions?.OMI_vehicle_wheel;
981
- if (omiExt !== void 0 && !isPlainObject(omiExt)) throw new KhrValidationError("OMI_vehicle_wheel extension must be an object");
982
- if (omiExt !== void 0 && !Array.isArray(omiExt.wheels)) throw new KhrValidationError("OMI_vehicle_wheel.wheels must be an array");
911
+ if (omiExt !== void 0 && (!isObj(omiExt) || !Array.isArray(omiExt.wheels))) throw new KhrValidationError("OMI_vehicle_wheel.wheels must be an array");
983
912
  const omiWheels = omiExt ? omiExt.wheels : [];
984
913
  const shapes = reqArr(khrShapes?.shapes, "KHR_implicit_shapes.shapes").map((s, i) => decodeShape(s, i));
985
914
  const materials = reqArr(khrPhys?.physicsMaterials, "KHR_physics_rigid_bodies.physicsMaterials");
@@ -987,21 +916,14 @@ function extractKhrBundleFromGltf(gltf, options) {
987
916
  const joints = reqArr(khrPhys?.physicsJoints, "KHR_physics_rigid_bodies.physicsJoints");
988
917
  const rawNodes = reqArr(json.nodes, "glTF nodes");
989
918
  const { parentIdx, nodeNames, resolveObj } = buildNodeGraphLookup(gltf, rawNodes, json);
990
- gltf.scene.traverse((child) => {
991
- if (child.userData && Object.getPrototypeOf(child.userData) !== Object.prototype) Object.setPrototypeOf(child.userData, Object.prototype);
992
- });
993
919
  const nodeMetas = [];
994
- const sockets = {};
920
+ const sockets = Object.create(null);
995
921
  for (let i = 0; i < rawNodes.length; i++) {
996
922
  const obj = resolveObj(i);
997
923
  if (!obj) continue;
998
- if (Object.getPrototypeOf(obj.userData) !== Object.prototype) Object.setPrototypeOf(obj.userData, Object.prototype);
999
924
  const rawExt = rawNodes[i].extensions;
1000
- if (rawExt !== void 0 && !isPlainObject(rawExt)) throw new KhrValidationError(`Node "${nodeNames[i]}" has invalid extensions`);
1001
- if (isPlainObject(rawExt)) {
1002
- if (Object.hasOwn(rawExt, "KOLMO_emitter") && rawExt.KOLMO_emitter !== void 0 && !Object.hasOwn(obj.userData, "KOLMO_emitter")) obj.userData.KOLMO_emitter = structuredClone(rawExt.KOLMO_emitter);
1003
- }
1004
- const extras = isPlainObject(rawNodes[i].extras) ? rawNodes[i].extras : {};
925
+ if (rawExt !== void 0 && !isObj(rawExt)) throw new KhrValidationError(`Node "${nodeNames[i]}" has invalid extensions`);
926
+ const extras = isObj(rawNodes[i].extras) ? rawNodes[i].extras : {};
1005
927
  nodeMetas.push(collectNodeSockets(obj, nodeNames[i], extras, sockets, options?.isSocketNode));
1006
928
  }
1007
929
  const bodies = [];
@@ -1015,8 +937,8 @@ function extractKhrBundleFromGltf(gltf, options) {
1015
937
  const name = nodeNames[i];
1016
938
  const obj = resolveObj(i);
1017
939
  if (!obj) continue;
1018
- const extras = isPlainObject(raw.extras) ? raw.extras : {};
1019
- const hasOmiWheel = isPlainObject(raw.extensions) && raw.extensions.OMI_vehicle_wheel !== void 0;
940
+ const extras = isObj(raw.extras) ? raw.extras : {};
941
+ const hasOmiWheel = isObj(raw.extensions) && raw.extensions.OMI_vehicle_wheel !== void 0;
1020
942
  if (extras.ecctrlWheel !== void 0 || extras.ecctrlPropeller !== void 0 || hasOmiWheel) {
1021
943
  if (parentIdx[i] !== -1 && isInsideRotor(parentIdx[i], parentIdx, rawNodes)) throw new KhrValidationError(`Nested rotor "${name}" inside detached rotor is unsupported`);
1022
944
  if (extras.ecctrlPropeller !== void 0 && (extras.ecctrlWheel !== void 0 || hasOmiWheel)) throw new KhrValidationError(`Node "${name}" cannot be both wheel and propeller`);
@@ -1025,7 +947,7 @@ function extractKhrBundleFromGltf(gltf, options) {
1025
947
  let rawOmiWheel;
1026
948
  if (hasOmiWheel) {
1027
949
  const omiRef = raw.extensions.OMI_vehicle_wheel;
1028
- if (!isPlainObject(omiRef) || typeof omiRef.wheel !== "number" || !Number.isInteger(omiRef.wheel) || omiRef.wheel < 0 || omiRef.wheel >= omiWheels.length) throw new KhrValidationError(`Node "${name}" references invalid OMI_vehicle_wheel.wheel ${String(isPlainObject(omiRef) ? omiRef.wheel : omiRef)}`);
950
+ if (!isObj(omiRef) || typeof omiRef.wheel !== "number" || !Number.isInteger(omiRef.wheel) || omiRef.wheel < 0 || omiRef.wheel >= omiWheels.length) throw new KhrValidationError(`Node "${name}" references invalid OMI_vehicle_wheel.wheel ${String(isObj(omiRef) ? omiRef.wheel : omiRef)}`);
1029
951
  rawOmiWheel = omiWheels[omiRef.wheel];
1030
952
  }
1031
953
  wheels.push(decodeWheelTag(obj, name, extras.ecctrlWheel, gltf.scene, rawOmiWheel));
@@ -1035,19 +957,19 @@ function extractKhrBundleFromGltf(gltf, options) {
1035
957
  if (isInsideRotor(i, parentIdx, rawNodes)) continue;
1036
958
  const phys = raw.extensions?.KHR_physics_rigid_bodies;
1037
959
  if (phys === void 0) continue;
1038
- if (!isPlainObject(phys)) throw new KhrValidationError(`Node "${name}" has invalid KHR_physics_rigid_bodies`);
960
+ if (!isObj(phys)) throw new KhrValidationError(`Node "${name}" has invalid KHR_physics_rigid_bodies`);
1039
961
  if (phys.motion === void 0 && phys.collider === void 0 && phys.joint === void 0) continue;
1040
962
  if (phys.motion === void 0 && findOwnerBodyIdx(i, parentIdx, rawNodes) !== -1) {
1041
963
  if (phys.joint !== void 0) throw new KhrValidationError(`Node "${name}" has joint without motion`);
1042
964
  continue;
1043
965
  }
1044
- if (phys.motion !== void 0 && !isPlainObject(phys.motion)) throw new KhrValidationError(`Node "${name}" has invalid motion`);
966
+ if (phys.motion !== void 0 && !isObj(phys.motion)) throw new KhrValidationError(`Node "${name}" has invalid motion`);
1045
967
  const { hasExplicitInertia, ...motion } = decodeMotion(phys.motion ?? {}, phys.motion !== void 0, name);
1046
968
  if (hasExplicitInertia) explicitInertiaSet.add(i);
1047
969
  const role = options?.extractRole?.(name, extras) ?? (typeof extras.role === "string" ? extras.role : null);
1048
970
  let joint = null;
1049
971
  if (phys.joint !== void 0) {
1050
- if (!isPlainObject(phys.joint)) throw new KhrValidationError(`Node "${name}" has invalid joint`);
972
+ if (!isObj(phys.joint)) throw new KhrValidationError(`Node "${name}" has invalid joint`);
1051
973
  const rawJ = phys.joint;
1052
974
  if (typeof rawJ.joint !== "number" || !Number.isInteger(rawJ.joint)) throw new KhrValidationError(`Joint on "${name}" is missing numeric joint index`);
1053
975
  if (typeof rawJ.connectedNode !== "number" || !Number.isInteger(rawJ.connectedNode)) throw new KhrValidationError(`Joint on "${name}" is missing numeric connectedNode index`);
@@ -1089,11 +1011,59 @@ function extractKhrBundleFromGltf(gltf, options) {
1089
1011
  });
1090
1012
  bodyByIdx.set(i, spec);
1091
1013
  }
1092
- attachBodyColliders(rawNodes, parentIdx, nodeNames, resolveObj, bodyByIdx, shapes, materials, collisionGroups);
1093
- computeMissingBodyInertias(bodyByIdx, explicitInertiaSet);
1014
+ for (let i = 0; i < rawNodes.length; i++) {
1015
+ if (isInsideRotor(i, parentIdx, rawNodes)) continue;
1016
+ const rawCol = rawNodes[i].extensions?.KHR_physics_rigid_bodies?.collider;
1017
+ if (rawCol === void 0) continue;
1018
+ const obj = resolveObj(i);
1019
+ if (!obj) continue;
1020
+ const ownerIdx = bodyByIdx.has(i) ? i : findOwnerBodyIdx(i, parentIdx, rawNodes);
1021
+ const owner = bodyByIdx.get(ownerIdx);
1022
+ if (!owner) continue;
1023
+ const shape = resolveColliderShape(rawCol, nodeNames[i], shapes, nodeNames, resolveObj);
1024
+ const colDef = rawCol;
1025
+ const rel = ownerIdx === i ? {
1026
+ localPosition: [
1027
+ 0,
1028
+ 0,
1029
+ 0
1030
+ ],
1031
+ localQuaternion: [
1032
+ 0,
1033
+ 0,
1034
+ 0,
1035
+ 1
1036
+ ]
1037
+ } : computeRelativePose(owner.object, obj);
1038
+ const mat = decodePhysicsMaterial(materials, colDef.physicsMaterial, nodeNames[i]);
1039
+ let colGroups;
1040
+ if (colDef.collisionFilter !== void 0) {
1041
+ if (typeof colDef.collisionFilter !== "number" || !Number.isInteger(colDef.collisionFilter) || colDef.collisionFilter < 0 || colDef.collisionFilter >= collisionGroups.length) throw new KhrValidationError(`Node "${nodeNames[i]}" references out-of-bounds collisionFilter ${String(colDef.collisionFilter)}`);
1042
+ colGroups = collisionGroups[colDef.collisionFilter];
1043
+ }
1044
+ owner.colliders.push({
1045
+ shape,
1046
+ localPosition: rel.localPosition,
1047
+ localQuaternion: rel.localQuaternion,
1048
+ ...mat,
1049
+ ...colGroups === void 0 ? {} : { collisionGroups: colGroups }
1050
+ });
1051
+ }
1052
+ for (const [idx, body] of bodyByIdx) if (!explicitInertiaSet.has(idx) && !body.isKinematic) body.inertiaDiagonal = computeBodyInertia(body.colliders, body.mass, body.centerOfMass, body.inertiaOrientation, body.nodeName);
1094
1053
  const { totalDynamicMass, centerOfMass } = computeAssemblyMassAndCom(bodies);
1095
- const { ikSockets, tune, droneTune } = extractSceneExtras(json, sockets);
1096
- registerKhrTemplateMeta(gltf.scene, {
1054
+ const ikSockets = [];
1055
+ const sceneExtras = json.scenes?.[json.scene ?? 0]?.extras ?? json.extras;
1056
+ if (sceneExtras?.ikSockets !== void 0) {
1057
+ if (!isObj(sceneExtras.ikSockets)) throw new KhrValidationError("scene.extras.ikSockets must be an object");
1058
+ for (const [k, v] of Object.entries(sceneExtras.ikSockets)) {
1059
+ const pos = readFiniteVec3(v, `scene.extras.ikSockets.${k}`);
1060
+ sockets[k] = pos;
1061
+ ikSockets.push([k, pos]);
1062
+ }
1063
+ }
1064
+ const tune = isObj(sceneExtras?.tune) ? sceneExtras.tune : isObj(sceneExtras?.ecctrl) ? sceneExtras.ecctrl : void 0;
1065
+ const droneTune = isObj(sceneExtras?.droneTune) ? sceneExtras.droneTune : void 0;
1066
+ templateMetaMap.set(gltf.scene, {
1097
1067
  nodes: nodeMetas,
1098
1068
  bodies: bodyMetas,
1099
1069
  ikSockets
@@ -1106,8 +1076,8 @@ function extractKhrBundleFromGltf(gltf, options) {
1106
1076
  sockets,
1107
1077
  totalDynamicMass,
1108
1078
  centerOfMass,
1109
- tune,
1110
- droneTune
1079
+ ...tune ? { tune } : {},
1080
+ ...droneTune ? { droneTune } : {}
1111
1081
  };
1112
1082
  }
1113
1083
  function createKhrGltfPlugin(options) {
@@ -1128,27 +1098,16 @@ function createKhrGltfPlugin(options) {
1128
1098
  };
1129
1099
  };
1130
1100
  }
1131
- // src/khrLoader.ts
1132
- var headlessPlugin$1 = createHeadlessTexturePlugin();
1133
- function createDefaultGltfLoader() {
1134
- const loader = new GLTFLoader();
1135
- if (isHeadlessTextureEnv()) loader.register(headlessPlugin$1);
1136
- return loader;
1137
- }
1138
1101
  async function loadKhrGlb(source, options) {
1139
- const bytes = source instanceof Uint8Array ? source : new Uint8Array(source);
1140
- const buf = new ArrayBuffer(bytes.byteLength);
1141
- new Uint8Array(buf).set(bytes);
1102
+ const buf = source instanceof ArrayBuffer ? source : source.byteOffset === 0 && source.byteLength === source.buffer.byteLength && source.buffer instanceof ArrayBuffer ? source.buffer : source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
1142
1103
  validateGlbHeader(buf);
1143
- const loader = options?.loader ?? createDefaultGltfLoader();
1104
+ const loader = options?.loader ?? new GLTFLoader();
1144
1105
  const plugin = createKhrGltfPlugin(options);
1145
1106
  loader.register(plugin);
1146
1107
  try {
1147
1108
  const toErr = (err) => err instanceof KhrValidationError ? err : new KhrValidationError(err instanceof Error ? err.message : "Failed to parse GLB");
1148
1109
  const bundle = (await new Promise((resolve, reject) => {
1149
1110
  loader.parse(buf, "", resolve, (err) => reject(toErr(err)));
1150
- }).catch((err) => {
1151
- throw toErr(err);
1152
1111
  })).userData[KHR_BUNDLE_USERDATA_KEY];
1153
1112
  if (!bundle) throw new KhrValidationError("Missing parsed KHR bundle on GLTF userData");
1154
1113
  return bundle;
@@ -1156,21 +1115,7 @@ async function loadKhrGlb(source, options) {
1156
1115
  loader.unregister(plugin);
1157
1116
  }
1158
1117
  }
1159
- // src/khrExportEncoders.ts
1160
- var isPosNum = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
1161
- var isObj = (v) => typeof v === "object" && !!v && !Array.isArray(v);
1162
- var COMBINE_MODES = /* @__PURE__ */ new Set([
1163
- "average",
1164
- "minimum",
1165
- "maximum",
1166
- "multiply"
1167
- ]);
1168
- function optFinite(v, label, nonNeg = false) {
1169
- if (v !== void 0) {
1170
- if (typeof v !== "number" || !Number.isFinite(v) || nonNeg && v < 0) throw new KhrValidationError(`exportKhrGlb: ${label} must be finite${nonNeg ? " >= 0" : ""}`);
1171
- return v;
1172
- }
1173
- }
1118
+ // src/exporter.ts
1174
1119
  function encodeShape(shape, nodeName) {
1175
1120
  if (shape.type === "box") {
1176
1121
  if (!Array.isArray(shape.size) || shape.size.length !== 3 || !shape.size.every(isPosNum)) throw new KhrValidationError(`exportKhrGlb: invalid box.size on "${nodeName}"`);
@@ -1198,7 +1143,7 @@ function encodeShape(shape, nodeName) {
1198
1143
  };
1199
1144
  }
1200
1145
  function normalizeJointAxis(axis, kind, nodeName) {
1201
- if (!Array.isArray(axis) || axis.length !== 3 || !axis.every((n) => typeof n === "number" && Number.isFinite(n))) throw new KhrValidationError(`exportKhrGlb: ${kind} joint on "${nodeName}" requires a finite axis`);
1146
+ if (!Array.isArray(axis) || axis.length !== 3 || !axis.every(isFiniteNum)) throw new KhrValidationError(`exportKhrGlb: ${kind} joint on "${nodeName}" requires a finite axis`);
1202
1147
  const len = Math.hypot(axis[0], axis[1], axis[2]);
1203
1148
  if (len <= 1e-8) throw new KhrValidationError(`exportKhrGlb: ${kind} joint on "${nodeName}" requires non-zero axis`);
1204
1149
  const ux = axis[0] / len, uy = axis[1] / len, uz = axis[2] / len;
@@ -1219,12 +1164,12 @@ function encodeJointDrive(drive, defaultType, defaultAxis, nodeName) {
1219
1164
  if (drive.mode !== "force" && drive.mode !== "acceleration") throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" requires drive.mode ("force" | "acceleration")`);
1220
1165
  if (drive.type !== void 0 && drive.type !== "linear" && drive.type !== "angular") throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" has invalid drive.type`);
1221
1166
  if (drive.axis !== void 0 && drive.axis !== 0 && drive.axis !== 1 && drive.axis !== 2) throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" has invalid drive.axis`);
1222
- const positionTarget = optFinite(drive.positionTarget, `joint drive.positionTarget on "${nodeName}"`);
1223
- const velocityTarget = optFinite(drive.velocityTarget, `joint drive.velocityTarget on "${nodeName}"`);
1167
+ const positionTarget = optFiniteNum(drive.positionTarget, `joint drive.positionTarget on "${nodeName}"`);
1168
+ const velocityTarget = optFiniteNum(drive.velocityTarget, `joint drive.velocityTarget on "${nodeName}"`);
1224
1169
  if (positionTarget === void 0 && velocityTarget === void 0) throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" requires finite positionTarget or velocityTarget`);
1225
- const stiffness = optFinite(drive.stiffness, `joint drive.stiffness on "${nodeName}"`, true);
1226
- const damping = optFinite(drive.damping, `joint drive.damping on "${nodeName}"`, true);
1227
- const maxForce = optFinite(drive.maxForce, `joint drive.maxForce on "${nodeName}"`, true);
1170
+ const stiffness = optFiniteNum(drive.stiffness, `joint drive.stiffness on "${nodeName}"`, true);
1171
+ const damping = optFiniteNum(drive.damping, `joint drive.damping on "${nodeName}"`, true);
1172
+ const maxForce = optFiniteNum(drive.maxForce, `joint drive.maxForce on "${nodeName}"`, true);
1228
1173
  return {
1229
1174
  type: drive.type ?? defaultType,
1230
1175
  mode: drive.mode,
@@ -1265,8 +1210,8 @@ function encodeJoint(j, nodeName) {
1265
1210
  2
1266
1211
  ].filter((i) => i !== ax);
1267
1212
  if (j.limits && (!Number.isFinite(j.limits[0]) || !Number.isFinite(j.limits[1]) || j.limits[0] > j.limits[1])) throw new KhrValidationError(`exportKhrGlb: joint on "${nodeName}" has invalid joint.limits`);
1268
- const stiffness = optFinite(j.limitStiffness, `joint.limitStiffness on "${nodeName}"`, true);
1269
- const damping = optFinite(j.limitDamping, `joint.limitDamping on "${nodeName}"`, true);
1213
+ const stiffness = optFiniteNum(j.limitStiffness, `joint.limitStiffness on "${nodeName}"`, true);
1214
+ const damping = optFiniteNum(j.limitDamping, `joint.limitDamping on "${nodeName}"`, true);
1270
1215
  const freeKey = j.kind === "revolute" ? "angularAxes" : "linearAxes";
1271
1216
  const freeLimit = j.limits || stiffness !== void 0 || damping !== void 0 ? [{
1272
1217
  [freeKey]: [ax],
@@ -1320,9 +1265,9 @@ function encodeJoint(j, nodeName) {
1320
1265
  function encodeMotion(m, nodeName) {
1321
1266
  const isKinematic = Boolean(m.isKinematic);
1322
1267
  if (!isKinematic && !isPosNum(m.mass)) throw new KhrValidationError(`exportKhrGlb: dynamic node "${nodeName}" requires positive finite motion.mass`);
1323
- if (isKinematic && m.mass !== void 0) optFinite(m.mass, `kinematic motion.mass on "${nodeName}"`, true);
1268
+ if (isKinematic && m.mass !== void 0) optFiniteNum(m.mass, `kinematic motion.mass on "${nodeName}"`, true);
1324
1269
  if (m.inertiaDiagonal && readFiniteVec3(m.inertiaDiagonal, `${nodeName}.motion.inertiaDiagonal`).some((n) => isKinematic ? n < 0 : n <= 0)) throw new KhrValidationError(`exportKhrGlb: invalid motion.inertiaDiagonal on "${nodeName}"`);
1325
- if (m.gravityFactor !== void 0 && (typeof m.gravityFactor !== "number" || !Number.isFinite(m.gravityFactor))) throw new KhrValidationError(`exportKhrGlb: invalid motion.gravityFactor on "${nodeName}"`);
1270
+ const gravityFactor = optFiniteNum(m.gravityFactor, `motion.gravityFactor on "${nodeName}"`);
1326
1271
  return {
1327
1272
  isKinematic,
1328
1273
  ...m.mass === void 0 ? {} : { mass: m.mass },
@@ -1331,12 +1276,12 @@ function encodeMotion(m, nodeName) {
1331
1276
  ...m.inertiaOrientation ? { inertiaOrientation: readUnitQuat(m.inertiaOrientation, `${nodeName}.motion.inertiaOrientation`) } : {},
1332
1277
  ...m.linearVelocity ? { linearVelocity: readFiniteVec3(m.linearVelocity, `${nodeName}.motion.linearVelocity`) } : {},
1333
1278
  ...m.angularVelocity ? { angularVelocity: readFiniteVec3(m.angularVelocity, `${nodeName}.motion.angularVelocity`) } : {},
1334
- ...m.gravityFactor === void 0 ? {} : { gravityFactor: m.gravityFactor }
1279
+ ...gravityFactor === void 0 ? {} : { gravityFactor }
1335
1280
  };
1336
1281
  }
1337
1282
  function encodePhysicsMaterial(col, nodeName) {
1338
- const friction = optFinite(col.friction, `collider.friction on "${nodeName}"`, true);
1339
- const restitution = optFinite(col.restitution, `collider.restitution on "${nodeName}"`, true);
1283
+ const friction = optFiniteNum(col.friction, `collider.friction on "${nodeName}"`, true);
1284
+ const restitution = optFiniteNum(col.restitution, `collider.restitution on "${nodeName}"`, true);
1340
1285
  for (const [k, v] of [["frictionCombine", col.frictionCombine], ["restitutionCombine", col.restitutionCombine]]) if (v !== void 0 && (typeof v !== "string" || !COMBINE_MODES.has(v))) throw new KhrValidationError(`exportKhrGlb: invalid collider.${k} "${String(v)}" on "${nodeName}"`);
1341
1286
  if (friction === void 0 && restitution === void 0 && col.frictionCombine === void 0 && col.restitutionCombine === void 0) return null;
1342
1287
  return {
@@ -1349,17 +1294,17 @@ function encodePhysicsMaterial(col, nodeName) {
1349
1294
  ...col.restitutionCombine === void 0 ? {} : { restitutionCombine: col.restitutionCombine }
1350
1295
  };
1351
1296
  }
1352
- function validateSystemList(arr, label, nodeName) {
1297
+ function validateCanonicalSystems(arr, label, nodeName) {
1353
1298
  if (!Array.isArray(arr) || arr.some((s) => typeof s !== "string" || s.length === 0)) throw new KhrValidationError(`exportKhrGlb: collider.${label} on "${nodeName}" must be an array of non-empty strings`);
1354
- return arr;
1299
+ return [...new Set(arr)];
1355
1300
  }
1356
1301
  function encodeCollisionFilter(col, nodeName) {
1357
1302
  if (col.collideWithSystems !== void 0 && col.notCollideWithSystems !== void 0) throw new KhrValidationError(`exportKhrGlb: collider on "${nodeName}" cannot specify both collideWithSystems and notCollideWithSystems`);
1358
1303
  if (col.collisionSystems === void 0 && col.collideWithSystems === void 0 && col.notCollideWithSystems === void 0) return null;
1359
1304
  return {
1360
- ...col.collisionSystems === void 0 ? {} : { collisionSystems: validateSystemList(col.collisionSystems, "collisionSystems", nodeName) },
1361
- ...col.collideWithSystems === void 0 ? {} : { collideWithSystems: validateSystemList(col.collideWithSystems, "collideWithSystems", nodeName) },
1362
- ...col.notCollideWithSystems === void 0 ? {} : { notCollideWithSystems: validateSystemList(col.notCollideWithSystems, "notCollideWithSystems", nodeName) }
1305
+ ...col.collisionSystems === void 0 ? {} : { collisionSystems: validateCanonicalSystems(col.collisionSystems, "collisionSystems", nodeName) },
1306
+ ...col.collideWithSystems === void 0 ? {} : { collideWithSystems: validateCanonicalSystems(col.collideWithSystems, "collideWithSystems", nodeName) },
1307
+ ...col.notCollideWithSystems === void 0 ? {} : { notCollideWithSystems: validateCanonicalSystems(col.notCollideWithSystems, "notCollideWithSystems", nodeName) }
1363
1308
  };
1364
1309
  }
1365
1310
  function encodeOmiWheel(wheel, nodeName) {
@@ -1367,12 +1312,12 @@ function encodeOmiWheel(wheel, nodeName) {
1367
1312
  if (!isPosNum(wheel.radius)) throw new KhrValidationError(`exportKhrGlb: wheel.radius on "${nodeName}" must be > 0`);
1368
1313
  if (!isPosNum(wheel.width)) throw new KhrValidationError(`exportKhrGlb: wheel.width on "${nodeName}" must be > 0`);
1369
1314
  for (const [k, v] of [["steering", wheel.steering], ["propulsion", wheel.propulsion]]) if (v !== void 0 && typeof v !== "boolean") throw new KhrValidationError(`exportKhrGlb: wheel.${k} on "${nodeName}" must be boolean`);
1370
- const maxForce = optFinite(wheel.maxForce, `wheel.maxForce on "${nodeName}"`, true);
1371
- const maxSteeringAngle = optFinite(wheel.maxSteeringAngle, `wheel.maxSteeringAngle on "${nodeName}"`, true);
1372
- const suspensionStiffness = optFinite(wheel.suspensionStiffness, `wheel.suspensionStiffness on "${nodeName}"`, true);
1373
- const suspensionDampingCompression = optFinite(wheel.suspensionDampingCompression, `wheel.suspensionDampingCompression on "${nodeName}"`, true);
1374
- const suspensionDampingRebound = optFinite(wheel.suspensionDampingRebound, `wheel.suspensionDampingRebound on "${nodeName}"`, true);
1375
- const suspensionTravel = optFinite(wheel.suspensionTravel, `wheel.suspensionTravel on "${nodeName}"`, true);
1315
+ const maxForce = optFiniteNum(wheel.maxForce, `wheel.maxForce on "${nodeName}"`, true);
1316
+ const maxSteeringAngle = optFiniteNum(wheel.maxSteeringAngle, `wheel.maxSteeringAngle on "${nodeName}"`, true);
1317
+ const suspensionStiffness = optFiniteNum(wheel.suspensionStiffness, `wheel.suspensionStiffness on "${nodeName}"`, true);
1318
+ const suspensionDampingCompression = optFiniteNum(wheel.suspensionDampingCompression, `wheel.suspensionDampingCompression on "${nodeName}"`, true);
1319
+ const suspensionDampingRebound = optFiniteNum(wheel.suspensionDampingRebound, `wheel.suspensionDampingRebound on "${nodeName}"`, true);
1320
+ const suspensionTravel = optFiniteNum(wheel.suspensionTravel, `wheel.suspensionTravel on "${nodeName}"`, true);
1376
1321
  return {
1377
1322
  radius: wheel.radius,
1378
1323
  width: wheel.width,
@@ -1386,24 +1331,20 @@ function encodeOmiWheel(wheel, nodeName) {
1386
1331
  ...suspensionTravel === void 0 ? {} : { suspensionTravel }
1387
1332
  };
1388
1333
  }
1389
- // src/khrExporter.ts
1390
- var isPos = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
1391
- var isNonNeg = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
1392
1334
  function synthesizeOmiWheel(raw) {
1393
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
1394
- const ec = raw;
1395
- if (!isPos(ec.radius) || !isPos(ec.width) || !isNonNeg(ec.travel) || !isNonNeg(ec.sag) || ec.sag > ec.travel) return null;
1396
- if (typeof ec.steer !== "boolean" || typeof ec.drive !== "boolean" || typeof ec.brake !== "boolean") return null;
1397
- const springK = isNonNeg(ec.springK) ? ec.springK : void 0;
1398
- const dampingC = isNonNeg(ec.dampingC) ? ec.dampingC : void 0;
1399
- const maxForce = isNonNeg(ec.maxBrakeTorque) ? ec.maxBrakeTorque / ec.radius : void 0;
1400
- const maxSteeringAngle = isNonNeg(ec.maxSteeringAngle) ? ec.maxSteeringAngle : void 0;
1335
+ if (!isObj(raw)) return null;
1336
+ if (!isPosNum(raw.radius) || !isPosNum(raw.width) || !isNonNegNum(raw.travel) || !isNonNegNum(raw.sag) || raw.sag > raw.travel) return null;
1337
+ if (typeof raw.steer !== "boolean" || typeof raw.drive !== "boolean" || typeof raw.brake !== "boolean") return null;
1338
+ const springK = isNonNegNum(raw.springK) ? raw.springK : void 0;
1339
+ const dampingC = isNonNegNum(raw.dampingC) ? raw.dampingC : void 0;
1340
+ const maxForce = isNonNegNum(raw.maxBrakeTorque) ? raw.maxBrakeTorque / raw.radius : void 0;
1341
+ const maxSteeringAngle = isNonNegNum(raw.maxSteeringAngle) ? raw.maxSteeringAngle : void 0;
1401
1342
  return {
1402
- radius: ec.radius,
1403
- width: ec.width,
1404
- steering: ec.steer,
1405
- propulsion: ec.drive,
1406
- suspensionTravel: ec.travel,
1343
+ radius: raw.radius,
1344
+ width: raw.width,
1345
+ steering: raw.steer,
1346
+ propulsion: raw.drive,
1347
+ suspensionTravel: raw.travel,
1407
1348
  ...maxForce === void 0 ? {} : { maxForce },
1408
1349
  ...maxSteeringAngle === void 0 ? {} : { maxSteeringAngle },
1409
1350
  ...springK === void 0 ? {} : { suspensionStiffness: springK },
@@ -1413,39 +1354,86 @@ function synthesizeOmiWheel(raw) {
1413
1354
  }
1414
1355
  };
1415
1356
  }
1416
- function stripUnloadedTextures(root) {
1417
- const stripped = [];
1357
+ /**
1358
+ * Replaces meshes' material references with shallow material clones ONLY when an unloaded headless Texture
1359
+ * (`!tex.image`) is present, keeping live WebGL materials untouched across async export.
1360
+ */
1361
+ function isolateUnloadedTextures(root) {
1362
+ const swaps = [];
1363
+ const clonedByMat = /* @__PURE__ */ new Map();
1364
+ const sanitizeMat = (mat) => {
1365
+ const cached = clonedByMat.get(mat);
1366
+ if (cached) return cached;
1367
+ const rec = mat;
1368
+ let hasUnloaded = false;
1369
+ for (const slot of Object.keys(rec)) {
1370
+ const val = rec[slot];
1371
+ if (val && typeof val === "object" && val.isTexture && !val.image) {
1372
+ hasUnloaded = true;
1373
+ break;
1374
+ }
1375
+ }
1376
+ if (!hasUnloaded) return mat;
1377
+ const clone = mat.clone();
1378
+ const cloneRec = clone;
1379
+ for (const slot of Object.keys(cloneRec)) {
1380
+ const val = cloneRec[slot];
1381
+ if (val && typeof val === "object" && val.isTexture && !val.image) cloneRec[slot] = null;
1382
+ }
1383
+ clonedByMat.set(mat, clone);
1384
+ return clone;
1385
+ };
1418
1386
  root.traverse((obj) => {
1419
- const rawMat = obj.material;
1420
- for (const m of Array.isArray(rawMat) ? rawMat : rawMat ? [rawMat] : []) {
1421
- if (!m || typeof m !== "object") continue;
1422
- const rec = m;
1423
- for (const slot of Object.keys(rec)) {
1424
- const val = rec[slot];
1425
- if (val && typeof val === "object" && val.isTexture && !val.image) {
1426
- stripped.push({
1427
- rec,
1428
- slot,
1429
- tex: val
1430
- });
1431
- rec[slot] = null;
1432
- }
1387
+ const mesh = obj;
1388
+ if (!mesh.isMesh || !mesh.material) return;
1389
+ if (Array.isArray(mesh.material)) {
1390
+ const next = mesh.material.map(sanitizeMat);
1391
+ if (next.some((m, idx) => m !== mesh.material[idx])) {
1392
+ swaps.push({
1393
+ mesh,
1394
+ origMat: mesh.material,
1395
+ clones: next.filter((m, idx) => m !== mesh.material[idx])
1396
+ });
1397
+ mesh.material = next;
1398
+ }
1399
+ } else {
1400
+ const next = sanitizeMat(mesh.material);
1401
+ if (next !== mesh.material) {
1402
+ swaps.push({
1403
+ mesh,
1404
+ origMat: mesh.material,
1405
+ clones: [next]
1406
+ });
1407
+ mesh.material = next;
1433
1408
  }
1434
1409
  }
1435
1410
  });
1436
- return stripped;
1411
+ return swaps;
1412
+ }
1413
+ function internJson(table, map, item) {
1414
+ const key = JSON.stringify(item);
1415
+ let idx = map.get(key);
1416
+ if (idx === void 0) {
1417
+ idx = table.length;
1418
+ table.push(item);
1419
+ map.set(key, idx);
1420
+ }
1421
+ return idx;
1437
1422
  }
1438
1423
  async function exportKhrGlb(root, specs, sceneExtras) {
1439
1424
  ensureHeadlessFileReader();
1440
1425
  root.updateMatrixWorld(true);
1441
1426
  const exporter = new GLTFExporter();
1442
- const stripped = stripUnloadedTextures(root);
1427
+ const swaps = isolateUnloadedTextures(root);
1443
1428
  let rawBuf;
1444
1429
  try {
1445
1430
  const res = await exporter.parseAsync(root, { binary: true });
1446
1431
  rawBuf = res instanceof ArrayBuffer ? res : packJsonToGlb(res);
1447
1432
  } finally {
1448
- for (const item of stripped) item.rec[item.slot] = item.tex;
1433
+ for (const s of swaps) {
1434
+ s.mesh.material = s.origMat;
1435
+ for (const c of s.clones) c.dispose();
1436
+ }
1449
1437
  }
1450
1438
  return patchGlbJsonChunk(rawBuf, (gltf) => {
1451
1439
  const nodes = gltf.nodes ?? [];
@@ -1463,17 +1451,19 @@ async function exportKhrGlb(root, specs, sceneExtras) {
1463
1451
  return list[0];
1464
1452
  };
1465
1453
  const shapes = [];
1466
- const shapeIndexByJson = /* @__PURE__ */ new Map();
1454
+ const shapeMap = /* @__PURE__ */ new Map();
1467
1455
  const materials = [];
1468
- const matIndexByJson = /* @__PURE__ */ new Map();
1456
+ const matMap = /* @__PURE__ */ new Map();
1469
1457
  const filters = [];
1470
- const filterIndexByJson = /* @__PURE__ */ new Map();
1458
+ const filterMap = /* @__PURE__ */ new Map();
1471
1459
  const joints = [];
1460
+ const jointMap = /* @__PURE__ */ new Map();
1472
1461
  const omiWheels = [];
1462
+ const wheelMap = /* @__PURE__ */ new Map();
1473
1463
  const seenSpecNodes = /* @__PURE__ */ new Set();
1474
1464
  const used = new Set(gltf.extensionsUsed ?? []);
1475
1465
  let hasPhysics = false;
1476
- const hasPreIndexedOmiWheel = specs.some((s) => s.extensions && typeof s.extensions === "object" && !Array.isArray(s.extensions) && Object.hasOwn(s.extensions, "OMI_vehicle_wheel") && s.extensions.OMI_vehicle_wheel !== void 0);
1466
+ const hasPreIndexedOmiWheel = specs.some((s) => isObj(s.extensions) && Object.hasOwn(s.extensions, "OMI_vehicle_wheel") && s.extensions.OMI_vehicle_wheel !== void 0);
1477
1467
  for (const spec of specs) {
1478
1468
  if (seenSpecNodes.has(spec.nodeName)) throw new KhrValidationError(`exportKhrGlb: duplicate spec for node "${spec.nodeName}"`);
1479
1469
  seenSpecNodes.add(spec.nodeName);
@@ -1483,7 +1473,7 @@ async function exportKhrGlb(root, specs, sceneExtras) {
1483
1473
  ...spec.extras
1484
1474
  };
1485
1475
  if (spec.extensions !== void 0) {
1486
- if (!spec.extensions || typeof spec.extensions !== "object" || Array.isArray(spec.extensions)) throw new KhrValidationError(`exportKhrGlb: extensions on "${spec.nodeName}" must be an object`);
1476
+ if (!isObj(spec.extensions)) throw new KhrValidationError(`exportKhrGlb: extensions on "${spec.nodeName}" must be an object`);
1487
1477
  if (Object.hasOwn(spec.extensions, "OMI_vehicle_wheel") && spec.extensions.OMI_vehicle_wheel !== void 0 && spec.wheel !== void 0) throw new KhrValidationError(`exportKhrGlb: node "${spec.nodeName}" cannot specify both wheel and extensions.OMI_vehicle_wheel`);
1488
1478
  if (Object.hasOwn(spec.extensions, "KHR_physics_rigid_bodies") && spec.extensions.KHR_physics_rigid_bodies !== void 0 && (spec.motion !== void 0 || spec.collider !== void 0 || spec.joint !== void 0)) throw new KhrValidationError(`exportKhrGlb: node "${spec.nodeName}" cannot specify both extensions.KHR_physics_rigid_bodies and motion/collider/joint`);
1489
1479
  node.extensions = {
@@ -1500,17 +1490,8 @@ async function exportKhrGlb(root, specs, sceneExtras) {
1500
1490
  if (spec.collider) {
1501
1491
  hasPhysics = true;
1502
1492
  const col = {};
1503
- if (spec.collider.shape) {
1504
- const encoded = encodeShape(spec.collider.shape, spec.nodeName);
1505
- const key = JSON.stringify(encoded);
1506
- let sIdx = shapeIndexByJson.get(key);
1507
- if (sIdx === void 0) {
1508
- sIdx = shapes.length;
1509
- shapes.push(encoded);
1510
- shapeIndexByJson.set(key, sIdx);
1511
- }
1512
- col.geometry = { shape: sIdx };
1513
- } else if (spec.collider.meshNodeName) {
1493
+ if (spec.collider.shape) col.geometry = { shape: internJson(shapes, shapeMap, encodeShape(spec.collider.shape, spec.nodeName)) };
1494
+ else if (spec.collider.meshNodeName) {
1514
1495
  if (typeof spec.collider.convexHull !== "boolean") throw new KhrValidationError(`exportKhrGlb: mesh collider on "${spec.nodeName}" requires explicit boolean convexHull`);
1515
1496
  col.geometry = {
1516
1497
  node: requireNodeIdx(spec.collider.meshNodeName),
@@ -1518,43 +1499,23 @@ async function exportKhrGlb(root, specs, sceneExtras) {
1518
1499
  };
1519
1500
  } else throw new KhrValidationError(`exportKhrGlb: collider on "${spec.nodeName}" requires shape or meshNodeName`);
1520
1501
  const mat = encodePhysicsMaterial(spec.collider, spec.nodeName);
1521
- if (mat) {
1522
- const key = JSON.stringify(mat);
1523
- let mIdx = matIndexByJson.get(key);
1524
- if (mIdx === void 0) {
1525
- mIdx = materials.length;
1526
- materials.push(mat);
1527
- matIndexByJson.set(key, mIdx);
1528
- }
1529
- col.physicsMaterial = mIdx;
1530
- }
1502
+ if (mat) col.physicsMaterial = internJson(materials, matMap, mat);
1531
1503
  const filter = encodeCollisionFilter(spec.collider, spec.nodeName);
1532
- if (filter) {
1533
- const key = JSON.stringify(filter);
1534
- let fIdx = filterIndexByJson.get(key);
1535
- if (fIdx === void 0) {
1536
- fIdx = filters.length;
1537
- filters.push(filter);
1538
- filterIndexByJson.set(key, fIdx);
1539
- }
1540
- col.collisionFilter = fIdx;
1541
- }
1504
+ if (filter) col.collisionFilter = internJson(filters, filterMap, filter);
1542
1505
  khr.collider = col;
1543
1506
  }
1544
1507
  if (spec.joint) {
1545
1508
  hasPhysics = true;
1546
1509
  const connIdx = requireNodeIdx(spec.joint.connectedNodeName);
1547
- joints.push(encodeJoint(spec.joint, spec.nodeName));
1548
1510
  khr.joint = {
1549
- joint: joints.length - 1,
1511
+ joint: internJson(joints, jointMap, encodeJoint(spec.joint, spec.nodeName)),
1550
1512
  connectedNode: connIdx,
1551
1513
  enableCollision: Boolean(spec.joint.enableCollision)
1552
1514
  };
1553
1515
  }
1554
1516
  const wheelSpec = spec.wheel ?? (!hasPreIndexedOmiWheel ? synthesizeOmiWheel(spec.extras?.ecctrlWheel) : null);
1555
1517
  if (wheelSpec) {
1556
- const wIdx = omiWheels.length;
1557
- omiWheels.push(encodeOmiWheel(wheelSpec, spec.nodeName));
1518
+ const wIdx = internJson(omiWheels, wheelMap, encodeOmiWheel(wheelSpec, spec.nodeName));
1558
1519
  used.add("OMI_vehicle_wheel");
1559
1520
  node.extensions = {
1560
1521
  ...node.extensions,
@@ -1598,370 +1559,60 @@ async function exportKhrGlb(root, specs, sceneExtras) {
1598
1559
  if (used.size > 0) gltf.extensionsUsed = [...used];
1599
1560
  });
1600
1561
  }
1601
- // src/AssemblyRootBody.tsx
1602
- function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBodyRef, origin, onBody, onJointReady }) {
1603
- const { rapier, world } = useRapier();
1604
- const registry = useContext(JointRegistryContext);
1605
- const childRef = useRef(null);
1606
- const rtRef = useRef(null);
1607
- const worldPose = useMemo(() => {
1608
- const rq = new THREE.Quaternion(rootQuat[0], rootQuat[1], rootQuat[2], rootQuat[3]).normalize();
1609
- const pos = new THREE.Vector3().fromArray(part.restRelRootPos).applyQuaternion(rq).add(new THREE.Vector3(rootPos[0], rootPos[1], rootPos[2]));
1610
- return {
1611
- pos: [
1612
- pos.x,
1613
- pos.y,
1614
- pos.z
1615
- ],
1616
- quat: [
1617
- rq.x,
1618
- rq.y,
1619
- rq.z,
1620
- rq.w
1621
- ]
1622
- };
1623
- }, [
1624
- part.restRelRootPos,
1625
- rootPos,
1626
- rootQuat
1627
- ]);
1628
- useEffect(() => {
1629
- onBody(part.spec.nodeName, childRef);
1630
- return () => onBody(part.spec.nodeName, null);
1631
- }, [part.spec.nodeName, onBody]);
1632
- useEffect(() => {
1633
- const rb = childRef.current;
1634
- const pm = part.partMass;
1635
- if (rb && pm) {
1636
- rb.setAdditionalMassProperties(pm.mass, pm.centerOfMass, pm.principalAngularInertia, pm.angularInertiaLocalFrame, true);
1637
- rb.recomputeMassPropertiesFromColliders();
1638
- }
1639
- }, [part.partMass]);
1640
- useEffect(() => {
1641
- const parentBody = parentBodyRef.current;
1642
- const childBody = childRef.current;
1643
- if (!parentBody || !childBody) return;
1644
- const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
1645
- 0,
1646
- 0,
1647
- 0
1648
- ], part.axisParent, part.axisChild, part.restRelParentQuat);
1649
- const rt = buildJointRuntime({
1650
- rapier,
1651
- world,
1652
- nodeName: part.spec.nodeName,
1653
- role: part.joint.role,
1654
- kind: part.joint.kind,
1655
- object: part.spec.object,
1656
- axisParent: part.axisParent,
1657
- anchorParent: part.restRelParentPos,
1658
- restRelQuat: [
1659
- 0,
1660
- 0,
1661
- 0,
1662
- 1
1663
- ],
1664
- limits: part.joint.limits,
1665
- drive: part.joint.drive,
1666
- breakaway: part.spec.breakaway,
1667
- rapierJoint: imp,
1668
- parentBody,
1669
- childBody
1670
- });
1671
- rtRef.current = rt;
1672
- registry?.add(rt);
1673
- onJointReady(rt.nodeName, rt);
1674
- return () => {
1675
- rtRef.current = null;
1676
- registry?.delete(rt);
1677
- onJointReady(rt.nodeName, null);
1678
- if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
1679
- };
1680
- }, [
1681
- rapier,
1682
- world,
1683
- part,
1684
- parentBodyRef,
1685
- registry,
1686
- onJointReady
1687
- ]);
1688
- const onForce = part.spec.breakaway ? (p) => {
1689
- rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * Math.max(world.timestep, 1 / 240));
1690
- } : void 0;
1691
- const linVel = part.spec.linearVelocity ?? rootSpec.linearVelocity;
1692
- const angVel = part.spec.angularVelocity ?? rootSpec.angularVelocity;
1693
- const gravScale = part.spec.gravityFactor ?? rootSpec.gravityFactor;
1694
- return /* @__PURE__ */ jsxs(RigidBody, {
1695
- ref: childRef,
1696
- type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
1697
- position: worldPose.pos,
1698
- quaternion: worldPose.quat,
1699
- colliders: false,
1700
- onContactForce: onForce,
1701
- ...linVel ? { linearVelocity: linVel } : {},
1702
- ...angVel ? { angularVelocity: angVel } : {},
1703
- ...gravScale === void 0 ? {} : { gravityScale: gravScale },
1704
- children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
1705
- object: part.spec.object,
1706
- position: [
1707
- 0,
1708
- 0,
1709
- 0
1710
- ],
1711
- quaternion: part.restRelRootQuat,
1712
- origin
1713
- }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
1714
- c: col.spec,
1715
- position: col.position,
1716
- quaternion: col.quaternion,
1717
- massProperties: col.massProperties
1718
- }, `${part.spec.nodeName}:${cIdx}`))]
1719
- });
1720
- }
1721
- function AssemblyRootBody({ plan, position, quaternion, fixedRoot, rigidBodyProps, onBody, onJoints, children }) {
1722
- const rbRef = useRef(null);
1723
- const partBodyRefs = useMemo(() => new Map(plan.parts.map((p) => [p.spec.nodeName, { current: null }])), [plan]);
1724
- const partOrigins = useMemo(() => plan.parts.length > 0 ? captureSubtreeOrigins(plan.parts.map((p) => p.spec.object)) : null, [plan.parts]);
1725
- const jointsMapRef = useRef(/* @__PURE__ */ new Map());
1726
- const rootSpec = plan.spec;
1727
- useEffect(() => {
1728
- onBody(rootSpec.nodeName, rbRef);
1729
- onJoints(rootSpec.nodeName, jointsMapRef.current);
1730
- return () => {
1731
- onBody(rootSpec.nodeName, null);
1732
- onJoints(rootSpec.nodeName, null);
1733
- };
1734
- }, [
1735
- rootSpec.nodeName,
1736
- onBody,
1737
- onJoints
1738
- ]);
1739
- useEffect(() => {
1740
- const rb = rbRef.current;
1741
- const rm = plan.rootMass;
1742
- if (rb && rm) {
1743
- rb.setAdditionalMassProperties(rm.mass, rm.centerOfMass, rm.principalAngularInertia, rm.angularInertiaLocalFrame, true);
1744
- rb.recomputeMassPropertiesFromColliders();
1745
- }
1746
- }, [plan.rootMass]);
1747
- const handlePartBody = useCallback((nodeName, refObj) => {
1748
- const slot = partBodyRefs.get(nodeName);
1749
- if (slot) slot.current = refObj?.current ?? null;
1750
- onBody(nodeName, refObj);
1751
- }, [partBodyRefs, onBody]);
1752
- const handleJointReady = useCallback((nodeName, rt) => {
1753
- if (rt) jointsMapRef.current.set(nodeName, rt);
1754
- else jointsMapRef.current.delete(nodeName);
1755
- }, []);
1756
- const bodyType = rootSpec.isKinematic ? fixedRoot ? "fixed" : "kinematicPosition" : "dynamic";
1757
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(RigidBody, {
1758
- ...rigidBodyProps,
1759
- ref: rbRef,
1760
- type: bodyType,
1761
- position,
1762
- quaternion,
1763
- colliders: false,
1764
- ...rootSpec.linearVelocity ? { linearVelocity: rootSpec.linearVelocity } : {},
1765
- ...rootSpec.angularVelocity ? { angularVelocity: rootSpec.angularVelocity } : {},
1766
- ...rootSpec.gravityFactor === void 0 ? {} : { gravityScale: rootSpec.gravityFactor },
1767
- children: [children, plan.colliders.map((col, idx) => /* @__PURE__ */ jsx(KhrCollider, {
1768
- c: col.spec,
1769
- position: col.position,
1770
- quaternion: col.quaternion,
1771
- massProperties: col.massProperties
1772
- }, `r${idx}`))]
1773
- }), plan.parts.map((part) => /* @__PURE__ */ jsx(ArticulatedPartBody, {
1774
- part,
1775
- rootSpec,
1776
- rootPos: position,
1777
- rootQuat: quaternion,
1778
- parentBodyRef: part.parent ? partBodyRefs.get(part.parent.spec.nodeName) : rbRef,
1779
- origin: partOrigins?.get(part.spec.object),
1780
- onBody: handlePartBody,
1781
- onJointReady: handleJointReady
1782
- }, part.spec.nodeName))] });
1783
- }
1784
- // src/KhrAssembly.tsx
1785
- function KhrAssembly({ ref, bundle, position = [
1786
- 0,
1787
- 0,
1788
- 0
1789
- ], rotation, quaternion, scale, fixedRoot = false, rigidBodyProps, children, ...groupProps }) {
1790
- assertUnitScale(scale, "KhrAssembly");
1791
- bundle.scene.updateMatrixWorld(true);
1792
- assertSceneIdentityWorldScale(bundle.scene);
1793
- const plans = useMemo(() => planAssembly(bundle), [bundle]);
1794
- const origins = useMemo(() => plans.length > 1 ? captureSubtreeOrigins(plans.map((p) => p.mountNode)) : null, [plans]);
1795
- const [px, py, pz] = position;
1796
- const [rx, ry, rz] = rotation ?? [
1797
- 0,
1798
- 0,
1799
- 0
1800
- ];
1801
- const [qx, qy, qz, qw] = quaternion ?? [
1802
- NaN,
1803
- NaN,
1804
- NaN,
1805
- NaN
1806
- ];
1807
- const spawnQuat = useMemo(() => quaternion ? new THREE.Quaternion(qx, qy, qz, qw) : new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), [
1808
- qx,
1809
- qy,
1810
- qz,
1811
- qw,
1812
- rx,
1813
- ry,
1814
- rz
1815
- ]);
1816
- const rootPoses = useMemo(() => plans.map((p) => {
1817
- const pos = new THREE.Vector3().fromArray(p.spec.localPosition).applyQuaternion(spawnQuat).add(new THREE.Vector3(px, py, pz));
1818
- const quat = spawnQuat.clone().multiply(new THREE.Quaternion().fromArray(p.spec.localQuaternion));
1819
- return {
1820
- position: [
1821
- pos.x,
1822
- pos.y,
1823
- pos.z
1824
- ],
1825
- quaternion: [
1826
- quat.x,
1827
- quat.y,
1828
- quat.z,
1829
- quat.w
1830
- ]
1831
- };
1832
- }), [
1833
- plans,
1834
- spawnQuat,
1835
- px,
1836
- py,
1837
- pz
1838
- ]);
1839
- const bodiesRef = useRef(/* @__PURE__ */ new Map());
1840
- const jointsRef = useRef(/* @__PURE__ */ new Map());
1841
- const nodeToRoot = useMemo(() => {
1842
- const m = /* @__PURE__ */ new Map();
1843
- for (const p of plans) {
1844
- m.set(p.spec.nodeName, p.spec.nodeName);
1845
- for (const part of p.parts) m.set(part.spec.nodeName, p.spec.nodeName);
1846
- }
1847
- return m;
1848
- }, [plans]);
1849
- const handleBody = useCallback((nodeName, rb) => {
1850
- if (rb) bodiesRef.current.set(nodeName, rb);
1851
- else bodiesRef.current.delete(nodeName);
1852
- }, []);
1853
- const handleJoints = useCallback((rootName, map) => {
1854
- if (map) jointsRef.current.set(rootName, map);
1855
- else jointsRef.current.delete(rootName);
1856
- }, []);
1857
- useImperativeHandle(ref, () => ({
1858
- getBody: (nodeName) => bodiesRef.current.get(nodeName)?.current ?? null,
1859
- setJointTarget: (nodeName, target) => {
1860
- const rt = jointsRef.current.get(nodeToRoot.get(nodeName) ?? "")?.get(nodeName);
1861
- if (rt) rt.applyTarget(target);
1862
- },
1863
- setRoleTarget: (role, target) => {
1864
- for (const map of jointsRef.current.values()) for (const rt of map.values()) if (rt.role === role) rt.applyTarget(target);
1865
- }
1866
- }), [nodeToRoot]);
1867
- if (plans.length === 1) {
1868
- const plan = plans[0];
1869
- return /* @__PURE__ */ jsx("group", {
1870
- ...groupProps,
1871
- children: /* @__PURE__ */ jsx(AssemblyRootBody, {
1872
- plan,
1873
- position: rootPoses[0].position,
1874
- quaternion: rootPoses[0].quaternion,
1875
- fixedRoot,
1876
- rigidBodyProps,
1877
- onBody: handleBody,
1878
- onJoints: handleJoints,
1879
- children: /* @__PURE__ */ jsxs("group", {
1880
- position: plan.sceneInRootPos,
1881
- quaternion: plan.sceneInRootQuat,
1882
- children: [/* @__PURE__ */ jsx(BundleSceneHost, {
1883
- bundle,
1884
- owner: "KhrAssembly"
1885
- }), children]
1886
- })
1887
- }, `${bundle.scene.uuid}:${plan.spec.nodeName}`)
1888
- });
1889
- }
1890
- return /* @__PURE__ */ jsxs("group", {
1891
- ...groupProps,
1892
- children: [/* @__PURE__ */ jsxs("group", {
1893
- position,
1894
- quaternion: [
1895
- spawnQuat.x,
1896
- spawnQuat.y,
1897
- spawnQuat.z,
1898
- spawnQuat.w
1899
- ],
1900
- children: [/* @__PURE__ */ jsx(BundleSceneHost, {
1901
- bundle,
1902
- owner: "KhrAssembly"
1903
- }), children]
1904
- }), plans.map((plan, idx) => /* @__PURE__ */ jsx(AssemblyRootBody, {
1905
- plan,
1906
- position: rootPoses[idx].position,
1907
- quaternion: rootPoses[idx].quaternion,
1908
- fixedRoot,
1909
- rigidBodyProps,
1910
- onBody: handleBody,
1911
- onJoints: handleJoints,
1912
- children: /* @__PURE__ */ jsx(MountSubtreeSlot, {
1913
- object: plan.mountNode,
1914
- position: plan.mountPosition,
1915
- quaternion: plan.mountQuaternion,
1916
- origin: origins?.get(plan.mountNode)
1917
- })
1918
- }, `${bundle.scene.uuid}:${plan.spec.nodeName}`))]
1919
- });
1920
- }
1921
1562
  // src/useKhrGlb.ts
1922
1563
  var KhrGLTFLoader = class extends GLTFLoader {
1923
1564
  static khrLoaderScope = Symbol("KhrGLTFLoader");
1924
1565
  };
1925
- var headlessPlugin = createHeadlessTexturePlugin();
1926
1566
  var khrPlugin = createKhrGltfPlugin();
1927
1567
  var configuredLoaders = /* @__PURE__ */ new WeakSet();
1928
1568
  var customExtendedLoaders = /* @__PURE__ */ new WeakSet();
1929
- var customLoaderRegistry = /* @__PURE__ */ new Map();
1569
+ var fnIds = /* @__PURE__ */ new WeakMap();
1570
+ var nextFnId = 1;
1571
+ var scopedRegistry = /* @__PURE__ */ new Map();
1930
1572
  function configureKhrLoader(loader) {
1931
1573
  if (configuredLoaders.has(loader)) return;
1932
1574
  configuredLoaders.add(loader);
1933
- if (isHeadlessTextureEnv()) loader.register(headlessPlugin);
1934
1575
  loader.register(khrPlugin);
1935
1576
  }
1936
1577
  function hasCustomLoaderOpts(options) {
1937
1578
  return Boolean(options?.extendLoader || options?.cacheKey !== void 0);
1938
1579
  }
1939
1580
  function getLoaderCacheKey(options) {
1940
- return options.cacheKey === void 0 ? `src:${Function.prototype.toString.call(options.extendLoader)}` : `key:${options.cacheKey}`;
1581
+ if (options.cacheKey !== void 0) return `key:${options.cacheKey}`;
1582
+ const fn = options.extendLoader;
1583
+ let id = fnIds.get(fn);
1584
+ if (id === void 0) {
1585
+ id = nextFnId++;
1586
+ fnIds.set(fn, id);
1587
+ }
1588
+ return `fn:${id}`;
1589
+ }
1590
+ function createScopedGltfLoaderClass() {
1591
+ return class ScopedKhrGLTFLoader extends GLTFLoader {};
1941
1592
  }
1942
1593
  function getScopedLoaderEntry(url, options) {
1943
1594
  const key = getLoaderCacheKey(options);
1944
- let urlMap = customLoaderRegistry.get(url);
1595
+ let urlMap = scopedRegistry.get(url);
1945
1596
  if (!urlMap) {
1946
1597
  urlMap = /* @__PURE__ */ new Map();
1947
- customLoaderRegistry.set(url, urlMap);
1598
+ scopedRegistry.set(url, urlMap);
1948
1599
  }
1949
1600
  let entry = urlMap.get(key);
1950
1601
  if (!entry) {
1951
- const loader = new GLTFLoader();
1602
+ const Proto = createScopedGltfLoaderClass();
1952
1603
  const extend = options.extendLoader;
1953
1604
  const created = {
1954
- loader,
1605
+ Proto,
1955
1606
  registerExtensions: (target) => {
1956
1607
  configureKhrLoader(target);
1957
1608
  if (extend && !customExtendedLoaders.has(target)) try {
1958
1609
  extend(target);
1959
1610
  customExtendedLoaders.add(target);
1960
1611
  } catch (err) {
1961
- const map = customLoaderRegistry.get(url);
1612
+ const map = scopedRegistry.get(url);
1962
1613
  if (map?.get(key) === created) {
1963
1614
  map.delete(key);
1964
- if (map.size === 0) customLoaderRegistry.delete(url);
1615
+ if (map.size === 0) scopedRegistry.delete(url);
1965
1616
  }
1966
1617
  throw err;
1967
1618
  }
@@ -1976,9 +1627,9 @@ function useKhrGlb(url, options) {
1976
1627
  const extractRole = options?.extractRole;
1977
1628
  const isSocketNode = options?.isSocketNode;
1978
1629
  const scoped = hasCustomLoaderOpts(options) ? getScopedLoaderEntry(url, options) : null;
1979
- const loader = scoped ? scoped.loader : KhrGLTFLoader;
1630
+ const Proto = scoped ? scoped.Proto : KhrGLTFLoader;
1980
1631
  const reg = scoped ? scoped.registerExtensions : configureKhrLoader;
1981
- const template = useLoader(loader, url, reg).userData[KHR_BUNDLE_USERDATA_KEY];
1632
+ const template = useLoader(Proto, url, reg).userData[KHR_BUNDLE_USERDATA_KEY];
1982
1633
  if (!template) throw new KhrValidationError(`useKhrGlb: missing "${KHR_BUNDLE_USERDATA_KEY}" on loaded GLTF for "${url}"`);
1983
1634
  return useMemo(() => {
1984
1635
  const cloned = cloneKhrBundle(template);
@@ -1993,33 +1644,33 @@ function useKhrGlb(url, options) {
1993
1644
  (function(_useKhrGlb) {
1994
1645
  _useKhrGlb.preload = (url, options) => {
1995
1646
  const scoped = hasCustomLoaderOpts(options) ? getScopedLoaderEntry(url, options) : null;
1996
- const loader = scoped ? scoped.loader : KhrGLTFLoader;
1647
+ const Proto = scoped ? scoped.Proto : KhrGLTFLoader;
1997
1648
  const reg = scoped ? scoped.registerExtensions : configureKhrLoader;
1998
- useLoader.preload(loader, url, reg);
1649
+ useLoader.preload(Proto, url, reg);
1999
1650
  };
2000
1651
  _useKhrGlb.clear = (url, options) => {
2001
1652
  if (hasCustomLoaderOpts(options)) {
2002
- const urlMap = customLoaderRegistry.get(url);
1653
+ const urlMap = scopedRegistry.get(url);
2003
1654
  if (!urlMap) return;
2004
1655
  const key = getLoaderCacheKey(options);
2005
1656
  const entry = urlMap.get(key);
2006
1657
  if (entry) {
2007
- useLoader.clear(entry.loader, url);
1658
+ useLoader.clear(entry.Proto, url);
2008
1659
  urlMap.delete(key);
2009
- if (urlMap.size === 0) customLoaderRegistry.delete(url);
1660
+ if (urlMap.size === 0) scopedRegistry.delete(url);
2010
1661
  }
2011
1662
  } else {
2012
1663
  useLoader.clear(KhrGLTFLoader, url);
2013
1664
  if (options === void 0) {
2014
- const urlMap = customLoaderRegistry.get(url);
1665
+ const urlMap = scopedRegistry.get(url);
2015
1666
  if (urlMap) {
2016
- for (const entry of urlMap.values()) useLoader.clear(entry.loader, url);
2017
- customLoaderRegistry.delete(url);
1667
+ for (const entry of urlMap.values()) useLoader.clear(entry.Proto, url);
1668
+ scopedRegistry.delete(url);
2018
1669
  }
2019
1670
  }
2020
1671
  }
2021
1672
  };
2022
1673
  })(useKhrGlb || (useKhrGlb = {}));
2023
- export { JointRegistryContext, KhrAssembly, KhrCollider, KhrValidationError, PhysicsWorld, assertIdentityWorldScale, assertSceneIdentityWorldScale, assertUnitScale, claimBundleMount, cloneKhrBundle, createKhrGltfPlugin, disposeKhrBundle, exportKhrGlb, loadKhrGlb, patchGlbJsonChunk, releaseBundleMount, useKhrGlb };
1674
+ export { ATTACHED_PANEL_INTERACTION_GROUPS, DETACHED_PANEL_INTERACTION_GROUPS, JointRegistryContext, KhrAssembly, KhrCollider, KhrGLTFLoader, KhrValidationError, PhysicsWorld, assertIdentityWorldScale, assertSceneIdentityWorldScale, assertUnitScale, assignRef, buildJointRuntime, claimBundleMount, cloneKhrBundle, computeShapeInertia, configureJointDrive, createKhrGltfPlugin, createRapierImpulseJoint, createScopedGltfLoaderClass, disposeKhrBundle, exportKhrGlb, isJointOpen, loadKhrGlb, measureJointCoordinate, openTargetForLimits, patchGlbJsonChunk, planAssembly, releaseBundleMount, useKhrGlb };
2024
1675
 
2025
1676
  //# sourceMappingURL=index.js.map