@khr3/launchers 0.2.9 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/AGENTS.md +3 -3
  2. package/CLAUDE.md +1 -5
  3. package/LICENSE +1 -1
  4. package/README.md +39 -32
  5. package/dist/KhrLauncher.d.ts +46 -0
  6. package/dist/KhrLauncher.js +316 -0
  7. package/dist/KhrLauncher.js.map +1 -0
  8. package/dist/armory/engine/assemblyVerifier.d.ts +48 -0
  9. package/dist/armory/engine/assemblyVerifier.js +443 -0
  10. package/dist/armory/engine/assemblyVerifier.js.map +1 -0
  11. package/dist/armory/engine/audioSynth.d.ts +26 -0
  12. package/dist/armory/engine/audioSynth.js +256 -0
  13. package/dist/armory/engine/audioSynth.js.map +1 -0
  14. package/dist/armory/engine/ballistics.d.ts +125 -0
  15. package/dist/armory/engine/ballistics.js +399 -0
  16. package/dist/armory/engine/ballistics.js.map +1 -0
  17. package/dist/armory/engine/bvhExploder.d.ts +43 -0
  18. package/dist/armory/engine/bvhExploder.js +326 -0
  19. package/dist/armory/engine/bvhExploder.js.map +1 -0
  20. package/dist/armory/engine/dispose.d.ts +6 -0
  21. package/dist/armory/engine/dispose.js +54 -0
  22. package/dist/armory/engine/dispose.js.map +1 -0
  23. package/dist/armory/engine/glbPhysicsExporter.d.ts +116 -0
  24. package/dist/armory/engine/glbPhysicsExporter.js +1960 -0
  25. package/dist/armory/engine/glbPhysicsExporter.js.map +1 -0
  26. package/dist/armory/engine/jointGraph.d.ts +5 -0
  27. package/dist/armory/engine/jointGraph.js +50 -0
  28. package/dist/armory/engine/jointGraph.js.map +1 -0
  29. package/dist/armory/engine/materials.d.ts +87 -0
  30. package/dist/armory/engine/materials.js +1089 -0
  31. package/dist/armory/engine/materials.js.map +1 -0
  32. package/dist/armory/engine/meshSegmenter.d.ts +44 -0
  33. package/dist/armory/engine/meshSegmenter.js +527 -0
  34. package/dist/armory/engine/meshSegmenter.js.map +1 -0
  35. package/dist/armory/engine/orthoExtruder.d.ts +33 -0
  36. package/dist/armory/engine/orthoExtruder.js +549 -0
  37. package/dist/armory/engine/orthoExtruder.js.map +1 -0
  38. package/dist/armory/engine/parts/boltRifleBuilder.d.ts +16 -0
  39. package/dist/armory/engine/parts/boltRifleBuilder.js +233 -0
  40. package/dist/armory/engine/parts/boltRifleBuilder.js.map +1 -0
  41. package/dist/armory/engine/parts/cadKernel.d.ts +39 -0
  42. package/dist/armory/engine/parts/cadKernel.js +367 -0
  43. package/dist/armory/engine/parts/cadKernel.js.map +1 -0
  44. package/dist/armory/engine/parts/fireControlGroup.d.ts +29 -0
  45. package/dist/armory/engine/parts/fireControlGroup.js +428 -0
  46. package/dist/armory/engine/parts/fireControlGroup.js.map +1 -0
  47. package/dist/armory/engine/parts/magazineBuilder.d.ts +14 -0
  48. package/dist/armory/engine/parts/magazineBuilder.js +146 -0
  49. package/dist/armory/engine/parts/magazineBuilder.js.map +1 -0
  50. package/dist/armory/engine/parts/muzzleDevices.d.ts +8 -0
  51. package/dist/armory/engine/parts/muzzleDevices.js +72 -0
  52. package/dist/armory/engine/parts/muzzleDevices.js.map +1 -0
  53. package/dist/armory/engine/parts/picatinnyRail.d.ts +49 -0
  54. package/dist/armory/engine/parts/picatinnyRail.js +474 -0
  55. package/dist/armory/engine/parts/picatinnyRail.js.map +1 -0
  56. package/dist/armory/engine/parts/pistolVariants.d.ts +28 -0
  57. package/dist/armory/engine/parts/pistolVariants.js +318 -0
  58. package/dist/armory/engine/parts/pistolVariants.js.map +1 -0
  59. package/dist/armory/engine/parts/revolverBuilder.d.ts +49 -0
  60. package/dist/armory/engine/parts/revolverBuilder.js +475 -0
  61. package/dist/armory/engine/parts/revolverBuilder.js.map +1 -0
  62. package/dist/armory/engine/proceduralGeometry.d.ts +113 -0
  63. package/dist/armory/engine/proceduralGeometry.js +1591 -0
  64. package/dist/armory/engine/proceduralGeometry.js.map +1 -0
  65. package/dist/armory/engine/renderState.d.ts +2 -0
  66. package/dist/armory/engine/renderState.js +20 -0
  67. package/dist/armory/engine/renderState.js.map +1 -0
  68. package/dist/armory/engine/simSolver.d.ts +127 -0
  69. package/dist/armory/engine/simSolver.js +736 -0
  70. package/dist/armory/engine/simSolver.js.map +1 -0
  71. package/dist/armory/engine/weaponSpecs.d.ts +277 -0
  72. package/dist/armory/engine/weaponSpecs.js +1311 -0
  73. package/dist/armory/engine/weaponSpecs.js.map +1 -0
  74. package/dist/armory/engine/webglContext.d.ts +1 -0
  75. package/dist/armory/engine/webglContext.js +14 -0
  76. package/dist/armory/engine/webglContext.js.map +1 -0
  77. package/dist/armory/types/physicsSchema.d.ts +205 -0
  78. package/dist/armory/types/physicsSchema.js +2 -0
  79. package/dist/armory/types/physicsSchema.js.map +1 -0
  80. package/dist/index.d.ts +7 -0
  81. package/dist/index.js +8 -0
  82. package/dist/index.js.map +1 -1
  83. package/dist/inertia.d.ts +3 -9
  84. package/dist/inertia.js +6 -6
  85. package/dist/inertia.js.map +1 -1
  86. package/dist/launcherKhr.d.ts +3 -9
  87. package/dist/launcherKhr.js +3 -15
  88. package/dist/launcherKhr.js.map +1 -1
  89. package/dist/launcherParts.d.ts +3 -8
  90. package/dist/launcherParts.js +19 -39
  91. package/dist/launcherParts.js.map +1 -1
  92. package/dist/react.d.ts +3 -0
  93. package/dist/react.js +4 -0
  94. package/dist/react.js.map +1 -0
  95. package/dist/recipes.d.ts +18 -12
  96. package/dist/recipes.js +103 -2
  97. package/dist/recipes.js.map +1 -1
  98. package/dist/runtime.js +3 -2
  99. package/dist/runtime.js.map +1 -1
  100. package/dist/schema.d.ts +2 -1
  101. package/dist/schema.js +18 -0
  102. package/dist/schema.js.map +1 -1
  103. package/dist/three.d.ts +54 -0
  104. package/dist/three.js +58 -0
  105. package/dist/three.js.map +1 -0
  106. package/docs/api-reference.md +49 -299
  107. package/package.json +64 -8
@@ -0,0 +1,1960 @@
1
+ import * as THREE from 'three';
2
+ import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js';
3
+ import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
4
+ import { validateJointGraph } from './jointGraph.js';
5
+ import { collectObject3DTextures, createAmmoBillboardResources, createArmoryMaterials, disposeObject3DResources, } from './materials.js';
6
+ import { buildSegmentedUploadedScene } from './meshSegmenter.js';
7
+ import { buildCustomCadPartGroup } from './parts/cadKernel.js';
8
+ import { buildAmmoLodChain, buildWeaponRig, } from './proceduralGeometry.js';
9
+ import { buildKhr6DofJoint, buildKhrPhysicsManifest, computePrincipalInertiaDiagonal, getAllArchetypeJoints, IMPORTED_ROLE_SPECS, RECEIVER_COLLIDER_SPECS, WEAPON_ARCHETYPES, } from './weaponSpecs.js';
10
+ const GLB_MAGIC = 0x46546c67; // "glTF"
11
+ const CHUNK_TYPE_JSON = 0x4e4f534a; // "JSON"
12
+ const CHUNK_TYPE_BIN = 0x004e4942; // "BIN\0"
13
+ // Minimal Node.js FileReader polyfill so Three.js GLTFExporter runs identically in headless Node tests
14
+ if (typeof globalThis.FileReader === 'undefined' && typeof Blob !== 'undefined') {
15
+ class NodeFileReader {
16
+ result = null;
17
+ error = null;
18
+ onload = null;
19
+ onloadend = null;
20
+ onerror = null;
21
+ readAsArrayBuffer(blob) {
22
+ blob.arrayBuffer().then((buf) => {
23
+ this.result = buf;
24
+ this.onload?.({ target: this });
25
+ this.onloadend?.({ target: this });
26
+ }, (err) => {
27
+ this.error = err;
28
+ this.onerror?.({ target: this });
29
+ this.onloadend?.({ target: this });
30
+ });
31
+ }
32
+ readAsDataURL(blob) {
33
+ blob.arrayBuffer().then((buf) => {
34
+ const bytes = new Uint8Array(buf);
35
+ let binary = '';
36
+ for (let i = 0; i < bytes.length; i++)
37
+ binary += String.fromCharCode(bytes[i]);
38
+ const b64 = typeof btoa === 'function' ? btoa(binary) : Buffer.from(buf).toString('base64');
39
+ const mime = blob.type || 'application/octet-stream';
40
+ this.result = `data:${mime};base64,${b64}`;
41
+ this.onload?.({ target: this });
42
+ this.onloadend?.({ target: this });
43
+ }, (err) => {
44
+ this.error = err;
45
+ this.onerror?.({ target: this });
46
+ this.onloadend?.({ target: this });
47
+ });
48
+ }
49
+ }
50
+ globalThis.FileReader = NodeFileReader;
51
+ }
52
+ function asRecord(value) {
53
+ if (!value || typeof value !== 'object' || Array.isArray(value))
54
+ return null;
55
+ return value;
56
+ }
57
+ function omiEntries(ext) {
58
+ const rec = asRecord(ext);
59
+ if (!rec)
60
+ return [];
61
+ return Object.entries(rec).filter(([key]) => key.startsWith('OMI_'));
62
+ }
63
+ function placeOmiEntries(target, entries) {
64
+ const placed = [];
65
+ for (const [key, value] of entries) {
66
+ target.extensions = target.extensions ?? {};
67
+ if (target.extensions[key] === undefined)
68
+ target.extensions[key] = value;
69
+ placed.push(key);
70
+ }
71
+ return placed;
72
+ }
73
+ function addOmiExtensionNames(gltf, names) {
74
+ const used = new Set(gltf.extensionsUsed ?? []);
75
+ let changed = false;
76
+ for (const name of names) {
77
+ if (!name.startsWith('OMI_') || used.has(name))
78
+ continue;
79
+ used.add(name);
80
+ changed = true;
81
+ }
82
+ if (changed)
83
+ gltf.extensionsUsed = Array.from(used);
84
+ }
85
+ function stripStuffedOmi(holder) {
86
+ const stuffed = asRecord(holder.extras?.gltfExtensions);
87
+ if (!stuffed)
88
+ return;
89
+ for (const key of Object.keys(stuffed)) {
90
+ if (key.startsWith('OMI_'))
91
+ delete stuffed[key];
92
+ }
93
+ if (Object.keys(stuffed).length === 0 && holder.extras)
94
+ delete holder.extras.gltfExtensions;
95
+ }
96
+ function snapshotParsedOmi(gltf) {
97
+ return {
98
+ root: [
99
+ ...omiEntries(asRecord(gltf.extras)?.gltfExtensions),
100
+ ...omiEntries(gltf.extensions),
101
+ ],
102
+ nodes: (gltf.nodes ?? []).map((node) => [
103
+ ...omiEntries(asRecord(node.extras)?.gltfExtensions),
104
+ ...omiEntries(node.extensions),
105
+ ]),
106
+ used: (gltf.extensionsUsed ?? []).filter((name) => name.startsWith('OMI_')),
107
+ };
108
+ }
109
+ function restoreParsedOmi(gltf, snap) {
110
+ const placed = [
111
+ ...placeOmiEntries(gltf, snap.root),
112
+ ...snap.used,
113
+ ];
114
+ (gltf.nodes ?? []).forEach((node, index) => {
115
+ placed.push(...placeOmiEntries(node, snap.nodes[index] ?? []));
116
+ });
117
+ addOmiExtensionNames(gltf, placed);
118
+ stripStuffedOmi(gltf);
119
+ for (const node of gltf.nodes ?? [])
120
+ stripStuffedOmi(node);
121
+ }
122
+ export function patchGlbJsonChunk(originalBuffer, mutator) {
123
+ const view = new DataView(originalBuffer);
124
+ if (view.getUint32(0, true) !== GLB_MAGIC) {
125
+ throw new Error('Invalid GLB binary header');
126
+ }
127
+ const jsonChunkLen = view.getUint32(12, true);
128
+ if (view.getUint32(16, true) !== CHUNK_TYPE_JSON) {
129
+ throw new Error('Expected JSON chunk at offset 12');
130
+ }
131
+ const jsonBytes = new Uint8Array(originalBuffer, 20, jsonChunkLen);
132
+ const gltf = JSON.parse(new TextDecoder('utf-8').decode(jsonBytes));
133
+ const parsedOmi = snapshotParsedOmi(gltf);
134
+ mutator(gltf);
135
+ restoreParsedOmi(gltf, parsedOmi);
136
+ const rawNewJson = new TextEncoder().encode(JSON.stringify(gltf));
137
+ const paddedJsonLen = (rawNewJson.byteLength + 3) & ~3;
138
+ const paddedJson = new Uint8Array(paddedJsonLen);
139
+ paddedJson.set(rawNewJson);
140
+ for (let i = rawNewJson.byteLength; i < paddedJsonLen; i++) {
141
+ paddedJson[i] = 0x20;
142
+ }
143
+ const binOffset = 20 + jsonChunkLen;
144
+ const hasBin = binOffset + 8 <= originalBuffer.byteLength;
145
+ const binSlice = hasBin ? new Uint8Array(originalBuffer, binOffset) : new Uint8Array(0);
146
+ const totalLen = 12 + 8 + paddedJsonLen + binSlice.byteLength;
147
+ const out = new ArrayBuffer(totalLen);
148
+ const outView = new DataView(out);
149
+ const outBytes = new Uint8Array(out);
150
+ outView.setUint32(0, GLB_MAGIC, true);
151
+ outView.setUint32(4, 2, true);
152
+ outView.setUint32(8, totalLen, true);
153
+ outView.setUint32(12, paddedJsonLen, true);
154
+ outView.setUint32(16, CHUNK_TYPE_JSON, true);
155
+ outBytes.set(paddedJson, 20);
156
+ if (hasBin)
157
+ outBytes.set(binSlice, 20 + paddedJsonLen);
158
+ return out;
159
+ }
160
+ function readGlbJson(buffer) {
161
+ try {
162
+ if (buffer.byteLength < 12)
163
+ return null;
164
+ const view = new DataView(buffer);
165
+ if (view.getUint32(0, true) === GLB_MAGIC) {
166
+ if (buffer.byteLength < 20)
167
+ return null;
168
+ const jsonChunkLen = view.getUint32(12, true);
169
+ if (view.getUint32(16, true) !== CHUNK_TYPE_JSON)
170
+ return null;
171
+ if (20 + jsonChunkLen > buffer.byteLength)
172
+ return null;
173
+ const text = new TextDecoder('utf-8').decode(new Uint8Array(buffer, 20, jsonChunkLen));
174
+ return JSON.parse(text);
175
+ }
176
+ const text = new TextDecoder('utf-8').decode(new Uint8Array(buffer)).trim();
177
+ if (!text.startsWith('{'))
178
+ return null;
179
+ return JSON.parse(text);
180
+ }
181
+ catch {
182
+ return null;
183
+ }
184
+ }
185
+ function copyOmiExtensions(source, gltf, renamedFromOriginal) {
186
+ if (!source)
187
+ return;
188
+ const placed = new Set(placeOmiEntries(gltf, omiEntries(source.extensions)));
189
+ const srcByName = new Map();
190
+ for (const node of source.nodes ?? []) {
191
+ if (node.name && !srcByName.has(node.name))
192
+ srcByName.set(node.name, node);
193
+ }
194
+ const dstByName = new Map();
195
+ for (const node of gltf.nodes ?? []) {
196
+ if (node.name && !dstByName.has(node.name))
197
+ dstByName.set(node.name, node);
198
+ }
199
+ const copyOnto = (srcName, dstNode) => {
200
+ if (!srcName || !dstNode)
201
+ return;
202
+ for (const key of placeOmiEntries(dstNode, omiEntries(srcByName.get(srcName)?.extensions))) {
203
+ placed.add(key);
204
+ }
205
+ };
206
+ for (const node of gltf.nodes ?? [])
207
+ copyOnto(node.name, node);
208
+ if (renamedFromOriginal) {
209
+ for (const [originalSourceName, nodeName] of renamedFromOriginal) {
210
+ if (originalSourceName === nodeName)
211
+ continue;
212
+ copyOnto(originalSourceName, dstByName.get(nodeName));
213
+ }
214
+ }
215
+ addOmiExtensionNames(gltf, placed);
216
+ const required = (source.extensionsRequired ?? []).filter((name) => name.startsWith('OMI_') && placed.has(name));
217
+ if (required.length === 0)
218
+ return;
219
+ const next = new Set(gltf.extensionsRequired ?? []);
220
+ for (const name of required)
221
+ next.add(name);
222
+ gltf.extensionsRequired = Array.from(next);
223
+ }
224
+ function edgeStrictlyPiercesTri(px, py, pz, qx, qy, qz, tri, planeEps, baryMargin) {
225
+ const dp = px * tri.unx + py * tri.uny + pz * tri.unz - tri.planeD;
226
+ const dq = qx * tri.unx + qy * tri.uny + qz * tri.unz - tri.planeD;
227
+ if (Math.abs(dp) <= planeEps || Math.abs(dq) <= planeEps || dp * dq >= 0) {
228
+ return false;
229
+ }
230
+ const t = dp / (dp - dq);
231
+ const ix = px + (qx - px) * t;
232
+ const iy = py + (qy - py) * t;
233
+ const iz = pz + (qz - pz) * t;
234
+ // Barycentric coordinates of I in (A, B, C)
235
+ const v0x = tri.bx - tri.ax;
236
+ const v0y = tri.by - tri.ay;
237
+ const v0z = tri.bz - tri.az;
238
+ const v1x = tri.cx - tri.ax;
239
+ const v1y = tri.cy - tri.ay;
240
+ const v1z = tri.cz - tri.az;
241
+ const v2x = ix - tri.ax;
242
+ const v2y = iy - tri.ay;
243
+ const v2z = iz - tri.az;
244
+ const d00 = v0x * v0x + v0y * v0y + v0z * v0z;
245
+ const d01 = v0x * v1x + v0y * v1y + v0z * v1z;
246
+ const d11 = v1x * v1x + v1y * v1y + v1z * v1z;
247
+ const d20 = v2x * v0x + v2y * v0y + v2z * v0z;
248
+ const d21 = v2x * v1x + v2y * v1y + v2z * v1z;
249
+ const denom = d00 * d11 - d01 * d01;
250
+ if (Math.abs(denom) <= 1e-20)
251
+ return false;
252
+ const invDenom = 1.0 / denom;
253
+ const v = (d11 * d20 - d01 * d21) * invDenom;
254
+ const w = (d00 * d21 - d01 * d20) * invDenom;
255
+ const u = 1.0 - v - w;
256
+ return u > baryMargin && v > baryMargin && w > baryMargin;
257
+ }
258
+ function anyEdgePiercesTri(src, dst, planeEps, baryMargin) {
259
+ return (edgeStrictlyPiercesTri(src.ax, src.ay, src.az, src.bx, src.by, src.bz, dst, planeEps, baryMargin) ||
260
+ edgeStrictlyPiercesTri(src.bx, src.by, src.bz, src.cx, src.cy, src.cz, dst, planeEps, baryMargin) ||
261
+ edgeStrictlyPiercesTri(src.cx, src.cy, src.cz, src.ax, src.ay, src.az, dst, planeEps, baryMargin));
262
+ }
263
+ function trianglesProperlySelfIntersect(a, b, planeEps) {
264
+ if (a.maxX < b.minX - planeEps || a.minX > b.maxX + planeEps ||
265
+ a.maxY < b.minY - planeEps || a.minY > b.maxY + planeEps ||
266
+ a.maxZ < b.minZ - planeEps || a.minZ > b.maxZ + planeEps) {
267
+ return false;
268
+ }
269
+ // Skip topologically adjacent faces that share a quantized vertex
270
+ if (a.k0 === b.k0 || a.k0 === b.k1 || a.k0 === b.k2 ||
271
+ a.k1 === b.k0 || a.k1 === b.k1 || a.k1 === b.k2 ||
272
+ a.k2 === b.k0 || a.k2 === b.k1 || a.k2 === b.k2) {
273
+ return false;
274
+ }
275
+ // Interior edge pierce on either triangle, or mutual boundary-inclusive edge cross
276
+ if (anyEdgePiercesTri(a, b, planeEps, 1e-4) || anyEdgePiercesTri(b, a, planeEps, 1e-4)) {
277
+ return true;
278
+ }
279
+ return anyEdgePiercesTri(a, b, planeEps, -1e-5) && anyEdgePiercesTri(b, a, planeEps, -1e-5);
280
+ }
281
+ /**
282
+ * Production Khronos glTF 2.0 + KHR_physics_rigid_bodies + KHR_implicit_shapes binary validator.
283
+ * Verifies header/chunk alignment, float32 accessor invariants, zero NaN/Inf vertices, strictly unit normals,
284
+ * zero degenerate or coincident duplicate triangles, spatial-hashed 3D intra-mesh self-intersections,
285
+ * scene-graph DAG acyclicity, and semantic + graph-cycle integrity across KHR physics joints & shapes.
286
+ */
287
+ export function validateGlbBinary(buffer, options) {
288
+ const errors = [];
289
+ const warnings = [];
290
+ const stats = {
291
+ byteSize: buffer.byteLength,
292
+ nodes: 0,
293
+ meshes: 0,
294
+ triangles: 0,
295
+ joints: 0,
296
+ shapes: 0,
297
+ textures: 0,
298
+ };
299
+ if (buffer.byteLength < 20) {
300
+ return { valid: false, errors: ['GLB buffer shorter than 20-byte header'], warnings, stats };
301
+ }
302
+ const view = new DataView(buffer);
303
+ const magic = view.getUint32(0, true);
304
+ const version = view.getUint32(4, true);
305
+ const declaredLen = view.getUint32(8, true);
306
+ if (magic !== GLB_MAGIC)
307
+ errors.push(`Invalid GLB magic 0x${magic.toString(16)}`);
308
+ if (version !== 2)
309
+ errors.push(`Unsupported glTF version ${version} (expected 2)`);
310
+ if (declaredLen !== buffer.byteLength) {
311
+ errors.push(`Header length ${declaredLen} !== actual byteLength ${buffer.byteLength}`);
312
+ }
313
+ if (buffer.byteLength % 4 !== 0) {
314
+ errors.push(`Total GLB byteLength ${buffer.byteLength} is not 4-byte aligned`);
315
+ }
316
+ const jsonLen = view.getUint32(12, true);
317
+ const jsonType = view.getUint32(16, true);
318
+ if (jsonType !== CHUNK_TYPE_JSON) {
319
+ errors.push('First GLB chunk is not JSON (0x4E4F534A)');
320
+ return { valid: false, errors, warnings, stats };
321
+ }
322
+ if (jsonLen % 4 !== 0)
323
+ errors.push('JSON chunk byteLength is not 4-byte aligned');
324
+ let gltf;
325
+ try {
326
+ const jsonText = new TextDecoder('utf-8').decode(new Uint8Array(buffer, 20, jsonLen));
327
+ gltf = JSON.parse(jsonText);
328
+ }
329
+ catch (e) {
330
+ errors.push(`JSON chunk parse error: ${e instanceof Error ? e.message : String(e)}`);
331
+ return { valid: false, errors, warnings, stats };
332
+ }
333
+ let binBytes = null;
334
+ const binOffset = 20 + jsonLen;
335
+ if (binOffset + 8 <= buffer.byteLength) {
336
+ const binLen = view.getUint32(binOffset, true);
337
+ const binType = view.getUint32(binOffset + 4, true);
338
+ if (binType !== CHUNK_TYPE_BIN) {
339
+ errors.push(`Second GLB chunk type 0x${binType.toString(16)} is not BIN`);
340
+ }
341
+ else {
342
+ binBytes = new Uint8Array(buffer, binOffset + 8, binLen);
343
+ }
344
+ }
345
+ const nodes = gltf.nodes ?? [];
346
+ const meshes = gltf.meshes ?? [];
347
+ const accessors = gltf.accessors ?? [];
348
+ const bufferViews = gltf.bufferViews ?? [];
349
+ stats.nodes = nodes.length;
350
+ stats.meshes = meshes.length;
351
+ stats.textures = (gltf.textures ?? []).length;
352
+ // 1. Validate scene-graph node bounds, single-parent tree invariant, and DAG acyclicity
353
+ const parentOfNode = new Int32Array(nodes.length).fill(-1);
354
+ for (let u = 0; u < nodes.length; u++) {
355
+ const n = nodes[u];
356
+ if (n.mesh !== undefined && (n.mesh < 0 || n.mesh >= meshes.length)) {
357
+ errors.push(`Node[${u}] "${n.name ?? ''}" references out-of-bounds mesh ${n.mesh}`);
358
+ }
359
+ if (n.children) {
360
+ for (const c of n.children) {
361
+ if (!Number.isInteger(c) || c < 0 || c >= nodes.length) {
362
+ errors.push(`Node[${u}] "${n.name ?? ''}" references out-of-bounds child node ${c}`);
363
+ continue;
364
+ }
365
+ if (c === u) {
366
+ errors.push(`Scene graph cycle: Node[${u}] "${n.name ?? ''}" lists itself in children`);
367
+ continue;
368
+ }
369
+ if (parentOfNode[c] !== -1) {
370
+ errors.push(`glTF node tree violation: Node[${c}] "${nodes[c]?.name ?? ''}" has multiple parents (${parentOfNode[c]} and ${u})`);
371
+ }
372
+ else {
373
+ parentOfNode[c] = u;
374
+ }
375
+ }
376
+ }
377
+ }
378
+ {
379
+ const visitState = new Uint8Array(nodes.length); // 0 = unvisited, 1 = visiting, 2 = done
380
+ let cycleReported = false;
381
+ const dfsScene = (u) => {
382
+ visitState[u] = 1;
383
+ for (const c of nodes[u].children ?? []) {
384
+ if (c < 0 || c >= nodes.length)
385
+ continue;
386
+ if (visitState[c] === 1) {
387
+ if (!cycleReported) {
388
+ errors.push(`Scene graph cycle detected involving Node[${c}] "${nodes[c]?.name ?? ''}"`);
389
+ cycleReported = true;
390
+ }
391
+ }
392
+ else if (visitState[c] === 0) {
393
+ dfsScene(c);
394
+ }
395
+ }
396
+ visitState[u] = 2;
397
+ };
398
+ for (let u = 0; u < nodes.length; u++) {
399
+ if (visitState[u] === 0)
400
+ dfsScene(u);
401
+ }
402
+ }
403
+ // 2. Validate mesh primitives, accessors, triangles, unit normals, duplicate faces, and self-intersections
404
+ let nonUnitNormalCount = 0;
405
+ let nanVertexCount = 0;
406
+ let outOfBoundsIndexCount = 0;
407
+ let degenerateTriCount = 0;
408
+ let duplicateTriCount = 0;
409
+ let selfIntersectingPairCount = 0;
410
+ const degenerateDetails = [];
411
+ const duplicateDetails = [];
412
+ const selfIntersectDetails = [];
413
+ for (let mIdx = 0; mIdx < meshes.length; mIdx++) {
414
+ const mesh = meshes[mIdx];
415
+ const meshLabel = `Mesh[${mIdx}] "${mesh.name ?? 'unnamed'}"`;
416
+ for (let pIdx = 0; pIdx < mesh.primitives.length; pIdx++) {
417
+ const prim = mesh.primitives[pIdx];
418
+ if (prim.mode !== undefined && prim.mode !== 4)
419
+ continue;
420
+ const posIdx = prim.attributes.POSITION;
421
+ const normIdx = prim.attributes.NORMAL;
422
+ if (posIdx === undefined) {
423
+ errors.push(`${meshLabel} prim[${pIdx}] missing POSITION attribute`);
424
+ continue;
425
+ }
426
+ const posAcc = accessors[posIdx];
427
+ if (!posAcc) {
428
+ errors.push(`Out-of-bounds POSITION accessor ${posIdx}`);
429
+ continue;
430
+ }
431
+ if (posAcc.componentType !== 5126 || posAcc.type !== 'VEC3') {
432
+ errors.push(`${meshLabel} prim[${pIdx}] POSITION accessor ${posIdx} must be VEC3 FLOAT (5126), got ${posAcc.type}/${posAcc.componentType}`);
433
+ continue;
434
+ }
435
+ if (prim.indices !== undefined) {
436
+ const idxAcc = accessors[prim.indices];
437
+ if (!idxAcc) {
438
+ errors.push(`Out-of-bounds indices accessor ${prim.indices}`);
439
+ continue;
440
+ }
441
+ if (idxAcc.componentType !== 5121 &&
442
+ idxAcc.componentType !== 5123 &&
443
+ idxAcc.componentType !== 5125) {
444
+ errors.push(`${meshLabel} prim[${pIdx}] indices accessor ${prim.indices} has invalid componentType ${idxAcc.componentType}`);
445
+ continue;
446
+ }
447
+ stats.triangles += Math.floor(idxAcc.count / 3);
448
+ }
449
+ else {
450
+ stats.triangles += Math.floor(posAcc.count / 3);
451
+ }
452
+ if (binBytes && posAcc.bufferView !== undefined) {
453
+ const bv = bufferViews[posAcc.bufferView];
454
+ if (!bv) {
455
+ errors.push(`Out-of-bounds bufferView ${posAcc.bufferView} on POSITION accessor ${posIdx}`);
456
+ continue;
457
+ }
458
+ const byteOff = (bv.byteOffset ?? 0) + (posAcc.byteOffset ?? 0);
459
+ const stride = bv.byteStride ?? 12;
460
+ const dv = new DataView(binBytes.buffer, binBytes.byteOffset, binBytes.byteLength);
461
+ let minX = Infinity;
462
+ let minY = Infinity;
463
+ let minZ = Infinity;
464
+ let maxX = -Infinity;
465
+ let maxY = -Infinity;
466
+ let maxZ = -Infinity;
467
+ for (let i = 0; i < posAcc.count; i++) {
468
+ const o = byteOff + i * stride;
469
+ if (o + 12 > binBytes.byteLength) {
470
+ errors.push(`POSITION accessor ${posIdx} exceeds BIN chunk bounds`);
471
+ break;
472
+ }
473
+ const x = dv.getFloat32(o, true);
474
+ const y = dv.getFloat32(o + 4, true);
475
+ const z = dv.getFloat32(o + 8, true);
476
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) {
477
+ nanVertexCount++;
478
+ }
479
+ else {
480
+ if (x < minX)
481
+ minX = x;
482
+ if (y < minY)
483
+ minY = y;
484
+ if (z < minZ)
485
+ minZ = z;
486
+ if (x > maxX)
487
+ maxX = x;
488
+ if (y > maxY)
489
+ maxY = y;
490
+ if (z > maxZ)
491
+ maxZ = z;
492
+ }
493
+ }
494
+ const hasValidBounds = Number.isFinite(minX) && Number.isFinite(maxX);
495
+ const diagSq = hasValidBounds
496
+ ? (maxX - minX) ** 2 + (maxY - minY) ** 2 + (maxZ - minZ) ** 2
497
+ : 1.0;
498
+ const diag = Math.sqrt(Math.max(1e-12, diagSq));
499
+ const areaTwiceEps = Math.max(1e-12, diagSq * 1e-11);
500
+ const quantScale = 1.0 / Math.max(1e-7, diag * 1e-5);
501
+ const planeEps = Math.max(1e-7, diag * 1e-5);
502
+ const seenOrientedFaceKeys = new Set();
503
+ const seenUnorientedFaceKeys = new Set();
504
+ const extractedTris = [];
505
+ const quantKey = (x, y, z) => `${Math.round(x * quantScale)},${Math.round(y * quantScale)},${Math.round(z * quantScale)}`;
506
+ const checkTri = (triIdx, i0, i1, i2) => {
507
+ if (i0 < 0 || i1 < 0 || i2 < 0 ||
508
+ i0 >= posAcc.count || i1 >= posAcc.count || i2 >= posAcc.count) {
509
+ outOfBoundsIndexCount++;
510
+ return;
511
+ }
512
+ if (i0 === i1 || i1 === i2 || i2 === i0) {
513
+ degenerateTriCount++;
514
+ if (degenerateDetails.length < 4) {
515
+ degenerateDetails.push(`${meshLabel} prim[${pIdx}] tri[${triIdx}] repeated index (${i0},${i1},${i2})`);
516
+ }
517
+ return;
518
+ }
519
+ const o0 = byteOff + i0 * stride;
520
+ const o1 = byteOff + i1 * stride;
521
+ const o2 = byteOff + i2 * stride;
522
+ if (o0 + 12 > binBytes.byteLength ||
523
+ o1 + 12 > binBytes.byteLength ||
524
+ o2 + 12 > binBytes.byteLength) {
525
+ outOfBoundsIndexCount++;
526
+ return;
527
+ }
528
+ const ax = dv.getFloat32(o0, true);
529
+ const ay = dv.getFloat32(o0 + 4, true);
530
+ const az = dv.getFloat32(o0 + 8, true);
531
+ const bx = dv.getFloat32(o1, true);
532
+ const by = dv.getFloat32(o1 + 4, true);
533
+ const bz = dv.getFloat32(o1 + 8, true);
534
+ const cx = dv.getFloat32(o2, true);
535
+ const cy = dv.getFloat32(o2 + 4, true);
536
+ const cz = dv.getFloat32(o2 + 8, true);
537
+ const e1x = bx - ax;
538
+ const e1y = by - ay;
539
+ const e1z = bz - az;
540
+ const e2x = cx - ax;
541
+ const e2y = cy - ay;
542
+ const e2z = cz - az;
543
+ const nx = e1y * e2z - e1z * e2y;
544
+ const ny = e1z * e2x - e1x * e2z;
545
+ const nz = e1x * e2y - e1y * e2x;
546
+ const crossLen = Math.sqrt(nx * nx + ny * ny + nz * nz);
547
+ if (!Number.isFinite(crossLen) || crossLen <= areaTwiceEps) {
548
+ degenerateTriCount++;
549
+ if (degenerateDetails.length < 4) {
550
+ degenerateDetails.push(`${meshLabel} prim[${pIdx}] tri[${triIdx}] zero area`);
551
+ }
552
+ return;
553
+ }
554
+ const k0 = quantKey(ax, ay, az);
555
+ const k1 = quantKey(bx, by, bz);
556
+ const k2 = quantKey(cx, cy, cz);
557
+ // Cyclic canonical winding key catches exact duplicate faces unconditionally
558
+ const orientedKey = k0 <= k1 && k0 <= k2
559
+ ? `${k0}|${k1}|${k2}`
560
+ : k1 <= k0 && k1 <= k2
561
+ ? `${k1}|${k2}|${k0}`
562
+ : `${k2}|${k0}|${k1}`;
563
+ const sorted = [k0, k1, k2].sort();
564
+ const unorientedKey = `${sorted[0]}|${sorted[1]}|${sorted[2]}`;
565
+ if (seenOrientedFaceKeys.has(orientedKey)) {
566
+ duplicateTriCount++;
567
+ if (duplicateDetails.length < 4) {
568
+ duplicateDetails.push(`${meshLabel} prim[${pIdx}] tri[${triIdx}] duplicate coincident face`);
569
+ }
570
+ return;
571
+ }
572
+ seenOrientedFaceKeys.add(orientedKey);
573
+ if (seenUnorientedFaceKeys.has(unorientedKey) && options?.failOnSelfIntersection) {
574
+ duplicateTriCount++;
575
+ if (duplicateDetails.length < 4) {
576
+ duplicateDetails.push(`${meshLabel} prim[${pIdx}] tri[${triIdx}] opposite-winding coincident face`);
577
+ }
578
+ return;
579
+ }
580
+ seenUnorientedFaceKeys.add(unorientedKey);
581
+ const invCross = 1.0 / crossLen;
582
+ const unx = nx * invCross;
583
+ const uny = ny * invCross;
584
+ const unz = nz * invCross;
585
+ extractedTris.push({
586
+ triIdx,
587
+ ax, ay, az,
588
+ bx, by, bz,
589
+ cx, cy, cz,
590
+ unx, uny, unz,
591
+ planeD: unx * ax + uny * ay + unz * az,
592
+ minX: Math.min(ax, bx, cx),
593
+ minY: Math.min(ay, by, cy),
594
+ minZ: Math.min(az, bz, cz),
595
+ maxX: Math.max(ax, bx, cx),
596
+ maxY: Math.max(ay, by, cy),
597
+ maxZ: Math.max(az, bz, cz),
598
+ k0, k1, k2,
599
+ });
600
+ };
601
+ if (prim.indices !== undefined) {
602
+ const idxAcc = accessors[prim.indices];
603
+ if (idxAcc && idxAcc.bufferView !== undefined) {
604
+ const ibv = bufferViews[idxAcc.bufferView];
605
+ const iByteOff = (ibv.byteOffset ?? 0) + (idxAcc.byteOffset ?? 0);
606
+ const elemBytes = idxAcc.componentType === 5121 ? 1 : idxAcc.componentType === 5123 ? 2 : 4;
607
+ const iStride = ibv.byteStride ?? elemBytes;
608
+ const readIdx = (k) => {
609
+ const io = iByteOff + k * iStride;
610
+ if (io + elemBytes > binBytes.byteLength)
611
+ return -1;
612
+ if (idxAcc.componentType === 5121)
613
+ return dv.getUint8(io);
614
+ if (idxAcc.componentType === 5123)
615
+ return dv.getUint16(io, true);
616
+ return dv.getUint32(io, true);
617
+ };
618
+ const triTotal = Math.floor(idxAcc.count / 3);
619
+ for (let t = 0; t < triTotal; t++) {
620
+ checkTri(t, readIdx(t * 3), readIdx(t * 3 + 1), readIdx(t * 3 + 2));
621
+ }
622
+ }
623
+ }
624
+ else {
625
+ const triTotal = Math.floor(posAcc.count / 3);
626
+ for (let t = 0; t < triTotal; t++) {
627
+ checkTri(t, t * 3, t * 3 + 1, t * 3 + 2);
628
+ }
629
+ }
630
+ // Spatial-hashed 3D intra-mesh self-intersection check
631
+ if (hasValidBounds && extractedTris.length >= 2 && extractedTris.length <= 12000) {
632
+ const G = 12;
633
+ const spanX = Math.max(1e-6, maxX - minX);
634
+ const spanY = Math.max(1e-6, maxY - minY);
635
+ const spanZ = Math.max(1e-6, maxZ - minZ);
636
+ const buckets = new Map();
637
+ const clampCell = (v, lo, span) => Math.max(0, Math.min(G - 1, Math.floor(((v - lo) / span) * G)));
638
+ for (let idx = 0; idx < extractedTris.length; idx++) {
639
+ const tr = extractedTris[idx];
640
+ const x0 = clampCell(tr.minX, minX, spanX);
641
+ const x1 = clampCell(tr.maxX, minX, spanX);
642
+ const y0 = clampCell(tr.minY, minY, spanY);
643
+ const y1 = clampCell(tr.maxY, minY, spanY);
644
+ const z0 = clampCell(tr.minZ, minZ, spanZ);
645
+ const z1 = clampCell(tr.maxZ, minZ, spanZ);
646
+ for (let gx = x0; gx <= x1; gx++) {
647
+ for (let gy = y0; gy <= y1; gy++) {
648
+ for (let gz = z0; gz <= z1; gz++) {
649
+ const key = (gx * G + gy) * G + gz;
650
+ let list = buckets.get(key);
651
+ if (!list) {
652
+ list = [];
653
+ buckets.set(key, list);
654
+ }
655
+ list.push(idx);
656
+ }
657
+ }
658
+ }
659
+ }
660
+ const nTris = extractedTris.length;
661
+ const testedPairs = new Set();
662
+ buckets.forEach((list) => {
663
+ if (list.length < 2)
664
+ return;
665
+ for (let i = 0; i < list.length; i++) {
666
+ const aIdx = list[i];
667
+ for (let j = i + 1; j < list.length; j++) {
668
+ const bIdx = list[j];
669
+ const lo = aIdx < bIdx ? aIdx : bIdx;
670
+ const hi = aIdx < bIdx ? bIdx : aIdx;
671
+ const pairKey = lo * nTris + hi;
672
+ if (testedPairs.has(pairKey))
673
+ continue;
674
+ testedPairs.add(pairKey);
675
+ const triA = extractedTris[lo];
676
+ const triB = extractedTris[hi];
677
+ if (trianglesProperlySelfIntersect(triA, triB, planeEps)) {
678
+ selfIntersectingPairCount++;
679
+ if (selfIntersectDetails.length < 4) {
680
+ selfIntersectDetails.push(`${meshLabel} prim[${pIdx}] tri[${triA.triIdx}]x[${triB.triIdx}]`);
681
+ }
682
+ }
683
+ }
684
+ }
685
+ });
686
+ }
687
+ }
688
+ if (normIdx !== undefined) {
689
+ const normAcc = accessors[normIdx];
690
+ if (!normAcc) {
691
+ errors.push(`Out-of-bounds NORMAL accessor ${normIdx}`);
692
+ }
693
+ else if (normAcc.componentType !== 5126 || normAcc.type !== 'VEC3') {
694
+ errors.push(`${meshLabel} prim[${pIdx}] NORMAL accessor ${normIdx} must be VEC3 FLOAT (5126), got ${normAcc.type}/${normAcc.componentType}`);
695
+ }
696
+ else if (binBytes && normAcc.bufferView !== undefined) {
697
+ const bv = bufferViews[normAcc.bufferView];
698
+ if (bv) {
699
+ const byteOff = (bv.byteOffset ?? 0) + (normAcc.byteOffset ?? 0);
700
+ const stride = bv.byteStride ?? 12;
701
+ const dv = new DataView(binBytes.buffer, binBytes.byteOffset, binBytes.byteLength);
702
+ for (let i = 0; i < normAcc.count; i++) {
703
+ const o = byteOff + i * stride;
704
+ if (o + 12 > binBytes.byteLength)
705
+ break;
706
+ const nx = dv.getFloat32(o, true);
707
+ const ny = dv.getFloat32(o + 4, true);
708
+ const nz = dv.getFloat32(o + 8, true);
709
+ const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
710
+ if (!Number.isFinite(len) || Math.abs(len - 1.0) > 0.02) {
711
+ nonUnitNormalCount++;
712
+ }
713
+ }
714
+ }
715
+ }
716
+ }
717
+ if (prim.attributes.TEXCOORD_0 === undefined) {
718
+ warnings.push(`${meshLabel} prim[${pIdx}] missing TEXCOORD_0`);
719
+ }
720
+ }
721
+ }
722
+ if (nanVertexCount > 0)
723
+ errors.push(`${nanVertexCount} non-finite (NaN/Inf) vertex positions found`);
724
+ if (outOfBoundsIndexCount > 0) {
725
+ errors.push(`${outOfBoundsIndexCount} out-of-bounds triangle vertex indices found`);
726
+ }
727
+ if (degenerateTriCount > 0) {
728
+ errors.push(`${degenerateTriCount} degenerate triangles found (${degenerateDetails.join('; ')})`);
729
+ }
730
+ if (duplicateTriCount > 0) {
731
+ errors.push(`${duplicateTriCount} duplicate coincident triangles found (${duplicateDetails.join('; ')})`);
732
+ }
733
+ if (selfIntersectingPairCount > 0) {
734
+ const msg = `${selfIntersectingPairCount} self-intersecting triangle pairs found (${selfIntersectDetails.join('; ')})`;
735
+ if (options?.failOnSelfIntersection) {
736
+ errors.push(msg);
737
+ }
738
+ else {
739
+ warnings.push(msg);
740
+ }
741
+ }
742
+ if (nonUnitNormalCount > 0) {
743
+ errors.push(`${nonUnitNormalCount} non-unit vertex normals (|n| != 1.0) found`);
744
+ }
745
+ const implicitExt = gltf.extensions?.KHR_implicit_shapes;
746
+ const physExt = gltf.extensions?.KHR_physics_rigid_bodies;
747
+ const shapes = implicitExt?.shapes ?? [];
748
+ const joints = physExt?.physicsJoints ?? [];
749
+ const physMats = physExt?.physicsMaterials ?? [];
750
+ const filters = physExt?.collisionFilters ?? [];
751
+ stats.shapes = shapes.length;
752
+ stats.joints = joints.length;
753
+ const extUsed = new Set(gltf.extensionsUsed ?? []);
754
+ if (implicitExt && !extUsed.has('KHR_implicit_shapes')) {
755
+ errors.push('KHR_implicit_shapes used in extensions but missing from extensionsUsed');
756
+ }
757
+ if (physExt && !extUsed.has('KHR_physics_rigid_bodies')) {
758
+ errors.push('KHR_physics_rigid_bodies used in extensions but missing from extensionsUsed');
759
+ }
760
+ shapes.forEach((sh, sIdx) => {
761
+ if (!sh || typeof sh.type !== 'string') {
762
+ errors.push(`KHR_implicit_shapes.shapes[${sIdx}] missing type`);
763
+ return;
764
+ }
765
+ if (sh.type === 'box') {
766
+ const sz = sh.box?.size;
767
+ if (!Array.isArray(sz) || sz.length !== 3 || sz.some((v) => !Number.isFinite(v) || v <= 0)) {
768
+ errors.push(`KHR_implicit_shapes.shapes[${sIdx}] box.size must be 3 positive numbers`);
769
+ }
770
+ }
771
+ else if (sh.type === 'sphere') {
772
+ const r = sh.sphere?.radius;
773
+ if (r === undefined || !Number.isFinite(r) || r <= 0) {
774
+ errors.push(`KHR_implicit_shapes.shapes[${sIdx}] sphere.radius must be > 0`);
775
+ }
776
+ }
777
+ else if (sh.type === 'capsule') {
778
+ const c = sh.capsule;
779
+ if (!c ||
780
+ !Number.isFinite(c.height ?? -1) ||
781
+ (c.height ?? -1) < 0 ||
782
+ !Number.isFinite(c.radiusTop ?? 0) ||
783
+ (c.radiusTop ?? 0) <= 0 ||
784
+ !Number.isFinite(c.radiusBottom ?? 0) ||
785
+ (c.radiusBottom ?? 0) <= 0) {
786
+ errors.push(`KHR_implicit_shapes.shapes[${sIdx}] capsule has invalid dimensions`);
787
+ }
788
+ }
789
+ else if (sh.type === 'cylinder') {
790
+ const c = sh.cylinder;
791
+ if (!c ||
792
+ !Number.isFinite(c.height ?? 0) ||
793
+ (c.height ?? 0) <= 0 ||
794
+ !Number.isFinite(c.radiusTop ?? -1) ||
795
+ (c.radiusTop ?? -1) < 0 ||
796
+ !Number.isFinite(c.radiusBottom ?? -1) ||
797
+ (c.radiusBottom ?? -1) < 0 ||
798
+ (c.radiusTop ?? 0) + (c.radiusBottom ?? 0) <= 0) {
799
+ errors.push(`KHR_implicit_shapes.shapes[${sIdx}] cylinder has invalid dimensions`);
800
+ }
801
+ }
802
+ });
803
+ joints.forEach((jDef, jIdx) => {
804
+ (jDef.limits ?? []).forEach((lim, lIdx) => {
805
+ const lin = lim.linearAxes ?? [];
806
+ const ang = lim.angularAxes ?? [];
807
+ if (lin.length === 0 && ang.length === 0) {
808
+ errors.push(`physicsJoint[${jIdx}] limit[${lIdx}] specifies neither linearAxes nor angularAxes`);
809
+ }
810
+ for (const ax of [...lin, ...ang]) {
811
+ if (!Number.isInteger(ax) || ax < 0 || ax > 2) {
812
+ errors.push(`physicsJoint[${jIdx}] limit[${lIdx}] axis ${ax} out of [0, 1, 2]`);
813
+ }
814
+ }
815
+ if (lim.min !== undefined && !Number.isFinite(lim.min)) {
816
+ errors.push(`physicsJoint[${jIdx}] limit[${lIdx}] min is non-finite`);
817
+ }
818
+ if (lim.max !== undefined && !Number.isFinite(lim.max)) {
819
+ errors.push(`physicsJoint[${jIdx}] limit[${lIdx}] max is non-finite`);
820
+ }
821
+ if (lim.min !== undefined &&
822
+ lim.max !== undefined &&
823
+ Number.isFinite(lim.min) &&
824
+ Number.isFinite(lim.max) &&
825
+ lim.min > lim.max) {
826
+ errors.push(`physicsJoint[${jIdx}] limit[${lIdx}] min (${lim.min}) > max (${lim.max})`);
827
+ }
828
+ if (lim.stiffness !== undefined && (!Number.isFinite(lim.stiffness) || lim.stiffness < 0)) {
829
+ errors.push(`physicsJoint[${jIdx}] limit[${lIdx}] stiffness (${lim.stiffness}) must be >= 0`);
830
+ }
831
+ if (lim.damping !== undefined && (!Number.isFinite(lim.damping) || lim.damping < 0)) {
832
+ errors.push(`physicsJoint[${jIdx}] limit[${lIdx}] damping (${lim.damping}) must be >= 0`);
833
+ }
834
+ });
835
+ (jDef.drives ?? []).forEach((drv, dIdx) => {
836
+ if (drv.type !== 'linear' && drv.type !== 'angular') {
837
+ errors.push(`physicsJoint[${jIdx}] drive[${dIdx}] invalid type "${String(drv.type)}"`);
838
+ }
839
+ if (drv.mode !== 'force' && drv.mode !== 'acceleration') {
840
+ errors.push(`physicsJoint[${jIdx}] drive[${dIdx}] invalid mode "${String(drv.mode)}"`);
841
+ }
842
+ if (!Number.isInteger(drv.axis) || (drv.axis ?? -1) < 0 || (drv.axis ?? -1) > 2) {
843
+ errors.push(`physicsJoint[${jIdx}] drive[${dIdx}] invalid axis ${String(drv.axis)}`);
844
+ }
845
+ if (drv.stiffness !== undefined && (!Number.isFinite(drv.stiffness) || drv.stiffness < 0)) {
846
+ errors.push(`physicsJoint[${jIdx}] drive[${dIdx}] stiffness (${drv.stiffness}) must be >= 0`);
847
+ }
848
+ if (drv.damping !== undefined && (!Number.isFinite(drv.damping) || drv.damping < 0)) {
849
+ errors.push(`physicsJoint[${jIdx}] drive[${dIdx}] damping (${drv.damping}) must be >= 0`);
850
+ }
851
+ if (drv.maxForce !== undefined && (!Number.isFinite(drv.maxForce) || drv.maxForce < 0)) {
852
+ errors.push(`physicsJoint[${jIdx}] drive[${dIdx}] maxForce (${drv.maxForce}) must be >= 0`);
853
+ }
854
+ });
855
+ });
856
+ const jointEdges = new Map();
857
+ const seenJointBindings = new Set();
858
+ nodes.forEach((n, idx) => {
859
+ const nPhys = n.extensions?.KHR_physics_rigid_bodies;
860
+ if (!nPhys)
861
+ return;
862
+ if (nPhys.motion && !nPhys.motion.isKinematic && nPhys.motion.mass !== undefined) {
863
+ if (!Number.isFinite(nPhys.motion.mass) || nPhys.motion.mass <= 0) {
864
+ errors.push(`Node[${idx}] "${n.name}" dynamic motion.mass (${nPhys.motion.mass}) must be > 0`);
865
+ }
866
+ }
867
+ if (nPhys.collider?.geometry?.shape !== undefined) {
868
+ const sIdx = nPhys.collider.geometry.shape;
869
+ if (sIdx < 0 || sIdx >= shapes.length) {
870
+ errors.push(`Node[${idx}] "${n.name}" references out-of-bounds shape ${sIdx}`);
871
+ }
872
+ }
873
+ if (nPhys.collider?.physicsMaterial !== undefined) {
874
+ if (nPhys.collider.physicsMaterial < 0 || nPhys.collider.physicsMaterial >= physMats.length) {
875
+ errors.push(`Node[${idx}] "${n.name}" references out-of-bounds physicsMaterial`);
876
+ }
877
+ }
878
+ if (nPhys.collider?.collisionFilter !== undefined) {
879
+ if (nPhys.collider.collisionFilter < 0 || nPhys.collider.collisionFilter >= filters.length) {
880
+ errors.push(`Node[${idx}] "${n.name}" references out-of-bounds collisionFilter`);
881
+ }
882
+ }
883
+ if (nPhys.joint) {
884
+ const jIdx = nPhys.joint.joint;
885
+ const cIdx = nPhys.joint.connectedNode;
886
+ if (jIdx === undefined || jIdx < 0 || jIdx >= joints.length) {
887
+ errors.push(`Node[${idx}] "${n.name}" references out-of-bounds physicsJoint ${jIdx}`);
888
+ }
889
+ if (cIdx === undefined || cIdx < 0 || cIdx >= nodes.length) {
890
+ errors.push(`Node[${idx}] "${n.name}" joint connectedNode ${cIdx} is out of bounds`);
891
+ }
892
+ else if (cIdx === idx) {
893
+ errors.push(`Node[${idx}] "${n.name}" has self-referential joint connectedNode ${cIdx}`);
894
+ }
895
+ else {
896
+ if (!nodes[cIdx].extensions?.KHR_physics_rigid_bodies) {
897
+ errors.push(`Node[${idx}] "${n.name}" joint connectedNode[${cIdx}] "${nodes[cIdx].name}" lacks KHR_physics_rigid_bodies`);
898
+ }
899
+ const pairKey = `${idx}->${cIdx}:${jIdx ?? -1}`;
900
+ if (seenJointBindings.has(pairKey)) {
901
+ errors.push(`Duplicate KHR joint binding ${pairKey} on Node[${idx}] "${n.name}"`);
902
+ }
903
+ seenJointBindings.add(pairKey);
904
+ jointEdges.set(idx, cIdx);
905
+ }
906
+ }
907
+ });
908
+ errors.push(...validateJointGraph(nodes));
909
+ // Detect directed cycles in the KHR physics joint graph (e.g. A -> B -> A)
910
+ if (jointEdges.size > 0) {
911
+ const jState = new Uint8Array(nodes.length); // 0 = unvisited, 1 = visiting, 2 = done
912
+ let jointCycleReported = false;
913
+ for (const startIdx of jointEdges.keys()) {
914
+ if (jState[startIdx] !== 0)
915
+ continue;
916
+ let curr = startIdx;
917
+ while (curr !== undefined && jState[curr] === 0) {
918
+ jState[curr] = 1;
919
+ curr = jointEdges.get(curr);
920
+ }
921
+ if (curr !== undefined && jState[curr] === 1 && !jointCycleReported) {
922
+ errors.push(`KHR physics joint graph cycle detected involving Node[${curr}] "${nodes[curr]?.name ?? ''}"`);
923
+ jointCycleReported = true;
924
+ }
925
+ let mark = startIdx;
926
+ while (mark !== undefined && jState[mark] === 1) {
927
+ jState[mark] = 2;
928
+ mark = jointEdges.get(mark);
929
+ }
930
+ }
931
+ }
932
+ return {
933
+ valid: errors.length === 0,
934
+ errors,
935
+ warnings,
936
+ stats,
937
+ };
938
+ }
939
+ function downloadBinary(buffer, filename) {
940
+ const blob = new Blob([buffer], { type: 'model/gltf-binary' });
941
+ const url = URL.createObjectURL(blob);
942
+ const a = document.createElement('a');
943
+ a.href = url;
944
+ a.download = filename;
945
+ document.body.appendChild(a);
946
+ a.click();
947
+ document.body.removeChild(a);
948
+ window.setTimeout(() => URL.revokeObjectURL(url), 1500);
949
+ }
950
+ function sanitizeGeometryForFlatGlbExport(geom) {
951
+ const nonIdx = geom.index ? geom.toNonIndexed() : geom.clone();
952
+ const pos = nonIdx.attributes.position;
953
+ if (!pos || pos.count < 3)
954
+ return nonIdx;
955
+ const uv = nonIdx.attributes.uv;
956
+ const triCount = Math.floor(pos.count / 3);
957
+ const validTris = [];
958
+ for (let t = 0; t < triCount; t++) {
959
+ const v0 = t * 3;
960
+ const ax = pos.getX(v0);
961
+ const ay = pos.getY(v0);
962
+ const az = pos.getZ(v0);
963
+ const bx = pos.getX(v0 + 1);
964
+ const by = pos.getY(v0 + 1);
965
+ const bz = pos.getZ(v0 + 1);
966
+ const cx = pos.getX(v0 + 2);
967
+ const cy = pos.getY(v0 + 2);
968
+ const cz = pos.getZ(v0 + 2);
969
+ const e1x = bx - ax;
970
+ const e1y = by - ay;
971
+ const e1z = bz - az;
972
+ const e2x = cx - ax;
973
+ const e2y = cy - ay;
974
+ const e2z = cz - az;
975
+ const nx = e1y * e2z - e1z * e2y;
976
+ const ny = e1z * e2x - e1x * e2z;
977
+ const nz = e1x * e2y - e1y * e2x;
978
+ const crossLen = Math.sqrt(nx * nx + ny * ny + nz * nz);
979
+ if (Number.isFinite(crossLen) && crossLen > 1e-10) {
980
+ validTris.push(t);
981
+ }
982
+ }
983
+ const outCount = validTris.length * 3;
984
+ const outPos = new Float32Array(outCount * 3);
985
+ const outNorm = new Float32Array(outCount * 3);
986
+ const outUv = new Float32Array(outCount * 2);
987
+ for (let i = 0; i < validTris.length; i++) {
988
+ const v0 = validTris[i] * 3;
989
+ const ax = pos.getX(v0);
990
+ const ay = pos.getY(v0);
991
+ const az = pos.getZ(v0);
992
+ const bx = pos.getX(v0 + 1);
993
+ const by = pos.getY(v0 + 1);
994
+ const bz = pos.getZ(v0 + 1);
995
+ const cx = pos.getX(v0 + 2);
996
+ const cy = pos.getY(v0 + 2);
997
+ const cz = pos.getZ(v0 + 2);
998
+ const e1x = bx - ax;
999
+ const e1y = by - ay;
1000
+ const e1z = bz - az;
1001
+ const e2x = cx - ax;
1002
+ const e2y = cy - ay;
1003
+ const e2z = cz - az;
1004
+ let nx = e1y * e2z - e1z * e2y;
1005
+ let ny = e1z * e2x - e1x * e2z;
1006
+ let nz = e1x * e2y - e1y * e2x;
1007
+ const len = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1;
1008
+ nx /= len;
1009
+ ny /= len;
1010
+ nz /= len;
1011
+ const pBase = i * 9;
1012
+ outPos[pBase] = ax;
1013
+ outPos[pBase + 1] = ay;
1014
+ outPos[pBase + 2] = az;
1015
+ outPos[pBase + 3] = bx;
1016
+ outPos[pBase + 4] = by;
1017
+ outPos[pBase + 5] = bz;
1018
+ outPos[pBase + 6] = cx;
1019
+ outPos[pBase + 7] = cy;
1020
+ outPos[pBase + 8] = cz;
1021
+ for (let k = 0; k < 3; k++) {
1022
+ outNorm[pBase + k * 3] = nx;
1023
+ outNorm[pBase + k * 3 + 1] = ny;
1024
+ outNorm[pBase + k * 3 + 2] = nz;
1025
+ const uOff = i * 6 + k * 2;
1026
+ if (uv) {
1027
+ outUv[uOff] = uv.getX(v0 + k);
1028
+ outUv[uOff + 1] = uv.getY(v0 + k);
1029
+ }
1030
+ else {
1031
+ outUv[uOff] = (pos.getZ(v0 + k) * 4) % 1;
1032
+ outUv[uOff + 1] = 0.875;
1033
+ }
1034
+ }
1035
+ }
1036
+ nonIdx.dispose();
1037
+ const clean = new THREE.BufferGeometry();
1038
+ clean.setAttribute('position', new THREE.BufferAttribute(outPos, 3));
1039
+ clean.setAttribute('normal', new THREE.BufferAttribute(outNorm, 3));
1040
+ clean.setAttribute('uv', new THREE.BufferAttribute(outUv, 2));
1041
+ return clean;
1042
+ }
1043
+ function sanitizeExportSceneGeometries(root) {
1044
+ const tempGeos = [];
1045
+ const cache = new Map();
1046
+ root.traverse((obj) => {
1047
+ if (!(obj instanceof THREE.Mesh) || !obj.geometry)
1048
+ return;
1049
+ let clean = cache.get(obj.geometry);
1050
+ if (!clean) {
1051
+ clean = sanitizeGeometryForFlatGlbExport(obj.geometry);
1052
+ cache.set(obj.geometry, clean);
1053
+ tempGeos.push(clean);
1054
+ }
1055
+ obj.geometry = clean;
1056
+ });
1057
+ return tempGeos;
1058
+ }
1059
+ function sanitizeShaderMaterials(root) {
1060
+ const tempMaterials = [];
1061
+ root.traverse((obj) => {
1062
+ if (obj instanceof THREE.Mesh && obj.material instanceof THREE.ShaderMaterial) {
1063
+ const kind = obj.userData.opticLensType;
1064
+ const color = kind === 'red-dot'
1065
+ ? 0xff2d55
1066
+ : kind === 'thermal-ir'
1067
+ ? 0x22c55e
1068
+ : kind === 'zoom-scope'
1069
+ ? 0x0ea5e9
1070
+ : 0x38bdf8;
1071
+ const lensMat = new THREE.MeshStandardMaterial({
1072
+ name: `Mat_OpticLens_${kind ?? 'holo'}`,
1073
+ color,
1074
+ emissive: color,
1075
+ emissiveIntensity: 1.2,
1076
+ roughness: 0.12,
1077
+ metalness: 0.1,
1078
+ transparent: true,
1079
+ opacity: 0.4,
1080
+ side: THREE.DoubleSide,
1081
+ flatShading: true,
1082
+ });
1083
+ tempMaterials.push(lensMat);
1084
+ obj.material = lensMat;
1085
+ }
1086
+ });
1087
+ return tempMaterials;
1088
+ }
1089
+ export async function buildWeaponKhrGlbBuffer(archetypeId, loadout, tuning, ikOffsets, partOffsets, customCadPart, forwardAxis = '+Z', partScales) {
1090
+ const mats = createArmoryMaterials(loadout.finish ?? 'parkerized');
1091
+ const rig = buildWeaponRig(archetypeId, loadout, mats, customCadPart);
1092
+ const cfg = WEAPON_ARCHETYPES[archetypeId];
1093
+ const allJoints = getAllArchetypeJoints(archetypeId, loadout);
1094
+ void RECEIVER_COLLIDER_SPECS[archetypeId];
1095
+ // Bake user Part Shift offsets cleanly into node translations before export
1096
+ if (partOffsets) {
1097
+ Object.keys(partOffsets).forEach((partId) => {
1098
+ const off = partOffsets[partId];
1099
+ const node = rig.movableParts[partId];
1100
+ const base = rig.basePositions[partId];
1101
+ if (off && node && base) {
1102
+ node.position.set(base.x + off[0], base.y + off[1], base.z + off[2]);
1103
+ }
1104
+ });
1105
+ }
1106
+ // Bake user Part Resize scales directly into cloned geometry vertices so exported nodes keep unit scale [1, 1, 1]
1107
+ const bakedScaledGeos = [];
1108
+ if (partScales) {
1109
+ Object.keys(partScales).forEach((partId) => {
1110
+ const sc = partScales[partId];
1111
+ const node = rig.movableParts[partId];
1112
+ if (!sc || !node)
1113
+ return;
1114
+ if (Math.abs(sc[0] - 1) < 1e-6 && Math.abs(sc[1] - 1) < 1e-6 && Math.abs(sc[2] - 1) < 1e-6)
1115
+ return;
1116
+ const scaleMat = new THREE.Matrix4().makeScale(sc[0], sc[1], sc[2]);
1117
+ node.traverse((child) => {
1118
+ if (child !== node) {
1119
+ child.position.set(child.position.x * sc[0], child.position.y * sc[1], child.position.z * sc[2]);
1120
+ }
1121
+ if (child instanceof THREE.Mesh && child.geometry) {
1122
+ const cloned = child.geometry.clone();
1123
+ cloned.applyMatrix4(scaleMat);
1124
+ child.geometry = cloned;
1125
+ bakedScaledGeos.push(cloned);
1126
+ }
1127
+ });
1128
+ node.scale.set(1, 1, 1);
1129
+ });
1130
+ }
1131
+ // Bake user IK anchor gizmo offsets cleanly
1132
+ if (ikOffsets) {
1133
+ Object.keys(ikOffsets).forEach((id) => {
1134
+ const pos = ikOffsets[id];
1135
+ if (pos && rig.ikNodes[id]) {
1136
+ rig.ikNodes[id].position.set(pos[0], pos[1], pos[2]);
1137
+ }
1138
+ });
1139
+ }
1140
+ // Optional -Z forward rotation for Godot 4 / Blender / Unity game workflows
1141
+ if (forwardAxis === '-Z') {
1142
+ rig.root.rotation.y = Math.PI;
1143
+ }
1144
+ const tempLensMats = sanitizeShaderMaterials(rig.root);
1145
+ const sanitizedExportGeos = sanitizeExportSceneGeometries(rig.root);
1146
+ bakedScaledGeos.push(...sanitizedExportGeos);
1147
+ rig.root.updateMatrixWorld(true);
1148
+ const exporter = new GLTFExporter();
1149
+ const manifest = buildKhrPhysicsManifest(archetypeId, tuning, ikOffsets, loadout, partOffsets, customCadPart ?? null, forwardAxis, partScales);
1150
+ return new Promise((resolve, reject) => {
1151
+ exporter.parse(rig.root, (result) => {
1152
+ tempLensMats.forEach((m) => m.dispose());
1153
+ bakedScaledGeos.forEach((g) => g.dispose());
1154
+ rig.dispose();
1155
+ mats.dispose();
1156
+ if (!(result instanceof ArrayBuffer)) {
1157
+ reject(new Error('Expected binary GLB output'));
1158
+ return;
1159
+ }
1160
+ const isStandaloneCustom = customCadPart?.mode === 'standalone';
1161
+ const patched = patchGlbJsonChunk(result, (gltf) => {
1162
+ gltf.asset = {
1163
+ ...(gltf.asset ?? {}),
1164
+ version: '2.0',
1165
+ generator: 'khr-armory (Three.js / R3F)',
1166
+ extras: {
1167
+ coordinateConvention: forwardAxis === '-Z'
1168
+ ? '-Z_forward_+Y_up_+X_right_SI_meters'
1169
+ : '+Z_forward_+Y_up_+X_right_SI_meters',
1170
+ },
1171
+ };
1172
+ if (isStandaloneCustom) {
1173
+ gltf.extras = {
1174
+ ...(gltf.extras ?? {}),
1175
+ customCadSketch2D: customCadPart,
1176
+ userPartOffsets: partOffsets ?? {},
1177
+ userPartScales: partScales ?? {},
1178
+ };
1179
+ return;
1180
+ }
1181
+ const used = new Set(gltf.extensionsUsed ?? []);
1182
+ used.add('KHR_physics_rigid_bodies');
1183
+ used.add('KHR_implicit_shapes');
1184
+ gltf.extensionsUsed = Array.from(used);
1185
+ gltf.extensions = gltf.extensions ?? {};
1186
+ gltf.extensions.KHR_implicit_shapes = manifest.extensions.KHR_implicit_shapes;
1187
+ gltf.extensions.KHR_physics_rigid_bodies =
1188
+ manifest.extensions.KHR_physics_rigid_bodies;
1189
+ const nodes = gltf.nodes ?? [];
1190
+ const nameToIndex = new Map();
1191
+ nodes.forEach((n, idx) => {
1192
+ if (n.name)
1193
+ nameToIndex.set(n.name, idx);
1194
+ });
1195
+ const receiverIdx = nameToIndex.get('Receiver') ?? 0;
1196
+ if (nodes[receiverIdx]) {
1197
+ nodes[receiverIdx].extras = {
1198
+ ...(nodes[receiverIdx].extras ?? {}),
1199
+ weaponRole: 'receiver_root',
1200
+ archetype: archetypeId,
1201
+ loadout,
1202
+ userPartOffsets: partOffsets ?? {},
1203
+ userPartScales: partScales ?? {},
1204
+ customCadSketch2D: customCadPart ?? null,
1205
+ coordinateConvention: forwardAxis === '-Z'
1206
+ ? '-Z_forward_+Y_up_+X_right_SI_meters'
1207
+ : '+Z_forward_+Y_up_+X_right_SI_meters',
1208
+ };
1209
+ // Receiver must be a valid KHR rigid body so child joints can attach.
1210
+ nodes[receiverIdx].extensions = {
1211
+ ...(nodes[receiverIdx].extensions ?? {}),
1212
+ KHR_physics_rigid_bodies: {
1213
+ motion: {
1214
+ isKinematic: true,
1215
+ },
1216
+ collider: {
1217
+ geometry: { shape: allJoints.length },
1218
+ physicsMaterial: 0,
1219
+ collisionFilter: 0,
1220
+ },
1221
+ },
1222
+ };
1223
+ }
1224
+ // Rig moving nodes including Trigger_TransferBar and Sear_Revolute
1225
+ allJoints.forEach((joint, jIdx) => {
1226
+ const nodeIdx = nameToIndex.get(joint.nodeName);
1227
+ const connIdx = nameToIndex.get(joint.connectedNodeName) ?? receiverIdx;
1228
+ if (nodeIdx === undefined || !nodes[nodeIdx])
1229
+ return;
1230
+ nodes[nodeIdx].extras = {
1231
+ ...(nodes[nodeIdx].extras ?? {}),
1232
+ weaponRole: joint.semanticRole,
1233
+ };
1234
+ nodes[nodeIdx].extensions = {
1235
+ ...(nodes[nodeIdx].extensions ?? {}),
1236
+ KHR_physics_rigid_bodies: {
1237
+ motion: {
1238
+ mass: joint.massKg,
1239
+ isKinematic: false,
1240
+ centerOfMass: [0, 0, 0],
1241
+ inertiaDiagonal: computePrincipalInertiaDiagonal(joint.massKg, joint.colliderExtents),
1242
+ },
1243
+ collider: {
1244
+ geometry: { shape: jIdx },
1245
+ physicsMaterial: 0,
1246
+ collisionFilter: 0,
1247
+ },
1248
+ joint: {
1249
+ joint: jIdx,
1250
+ connectedNode: connIdx,
1251
+ enableCollision: false,
1252
+ },
1253
+ },
1254
+ };
1255
+ });
1256
+ cfg.anchors.forEach((a) => {
1257
+ const idx = nameToIndex.get(a.id);
1258
+ if (idx !== undefined && nodes[idx]) {
1259
+ nodes[idx].extras = {
1260
+ ...(nodes[idx].extras ?? {}),
1261
+ anchorType: a.id.startsWith('IK_') ? 'hand_ik_target' : 'ballistic_socket',
1262
+ };
1263
+ }
1264
+ });
1265
+ });
1266
+ const validation = validateGlbBinary(patched);
1267
+ resolve({
1268
+ buffer: patched,
1269
+ validation,
1270
+ jointCount: isStandaloneCustom ? 0 : allJoints.length,
1271
+ });
1272
+ }, (err) => {
1273
+ tempLensMats.forEach((m) => m.dispose());
1274
+ bakedScaledGeos.forEach((g) => g.dispose());
1275
+ rig.dispose();
1276
+ mats.dispose();
1277
+ reject(err);
1278
+ }, { binary: true });
1279
+ });
1280
+ }
1281
+ export async function exportWeaponKhrGlb(archetypeId, loadout, tuning, ikOffsets, partOffsets, customCadPart, forwardAxis = '+Z', partScales, triggerDownload = true) {
1282
+ const { buffer, validation, jointCount } = await buildWeaponKhrGlbBuffer(archetypeId, loadout, tuning, ikOffsets, partOffsets, customCadPart, forwardAxis, partScales);
1283
+ const axisSuffix = forwardAxis === '-Z' ? '_negZ' : '_posZ';
1284
+ const filename = customCadPart?.mode === 'standalone'
1285
+ ? `khr_armory_${customCadPart.name.toLowerCase().replace(/[^a-z0-9]+/g, '_')}${axisSuffix}.glb`
1286
+ : `khr_armory_${archetypeId}_physics${axisSuffix}.glb`;
1287
+ const downloaded = validation.valid && triggerDownload && typeof document !== 'undefined';
1288
+ if (downloaded) {
1289
+ downloadBinary(buffer, filename);
1290
+ }
1291
+ return {
1292
+ filename,
1293
+ byteSize: buffer.byteLength,
1294
+ jointCount,
1295
+ validation,
1296
+ downloaded,
1297
+ };
1298
+ }
1299
+ export async function exportCustomCadGlb(spec, forwardAxis = '+Z', triggerDownload = true) {
1300
+ const mats = createArmoryMaterials();
1301
+ const group = buildCustomCadPartGroup(spec, mats);
1302
+ if (forwardAxis === '-Z') {
1303
+ group.rotation.y = Math.PI;
1304
+ }
1305
+ const tempGeos = sanitizeExportSceneGeometries(group);
1306
+ group.updateMatrixWorld(true);
1307
+ const exporter = new GLTFExporter();
1308
+ return new Promise((resolve, reject) => {
1309
+ exporter.parse(group, (result) => {
1310
+ tempGeos.forEach((g) => g.dispose());
1311
+ group.traverse((o) => {
1312
+ if (o instanceof THREE.Mesh)
1313
+ o.geometry.dispose();
1314
+ });
1315
+ mats.dispose();
1316
+ if (!(result instanceof ArrayBuffer)) {
1317
+ reject(new Error('Expected binary GLB output'));
1318
+ return;
1319
+ }
1320
+ const patched = patchGlbJsonChunk(result, (gltf) => {
1321
+ gltf.asset = {
1322
+ ...(gltf.asset ?? {}),
1323
+ version: '2.0',
1324
+ generator: 'khr-armory (2D Extruder)',
1325
+ };
1326
+ gltf.extras = {
1327
+ customCadSketch2D: spec,
1328
+ coordinateConvention: forwardAxis === '-Z'
1329
+ ? '-Z_forward_+Y_up_+X_right_SI_meters'
1330
+ : '+Z_forward_+Y_up_+X_right_SI_meters',
1331
+ };
1332
+ });
1333
+ const validation = validateGlbBinary(patched);
1334
+ const safeName = spec.name.toLowerCase().replace(/[^a-z0-9]+/g, '_') || 'custom_cad_part';
1335
+ const filename = `khr_armory_${safeName}.glb`;
1336
+ const downloaded = validation.valid && triggerDownload && typeof document !== 'undefined';
1337
+ if (downloaded) {
1338
+ downloadBinary(patched, filename);
1339
+ }
1340
+ resolve({ filename, byteSize: patched.byteLength, validation, downloaded });
1341
+ }, (err) => {
1342
+ tempGeos.forEach((g) => g.dispose());
1343
+ group.traverse((o) => {
1344
+ if (o instanceof THREE.Mesh)
1345
+ o.geometry.dispose();
1346
+ });
1347
+ mats.dispose();
1348
+ reject(err);
1349
+ }, { binary: true });
1350
+ });
1351
+ }
1352
+ export async function buildAmmoLodsGlbBuffer(archetypeId, radialSides, ammoSpec) {
1353
+ const mats = createArmoryMaterials();
1354
+ const sides = ammoSpec?.radialSides ?? radialSides;
1355
+ const payload = ammoSpec?.payload ?? 'parabellum-9mm';
1356
+ const calScale = ammoSpec?.caliberScale ?? 1.0;
1357
+ const lenScale = ammoSpec?.lengthScale ?? 1.0;
1358
+ const chain = buildAmmoLodChain(archetypeId, sides, ammoSpec);
1359
+ const billboardRes = createAmmoBillboardResources(payload);
1360
+ const root = new THREE.Group();
1361
+ root.name = `AmmoPack_${payload}_${sides}gon`;
1362
+ const projMat = payload === 'warhead-85mm'
1363
+ ? mats.warheadOlive
1364
+ : payload === 'grenade-40mm'
1365
+ ? mats.smokeCanisterAmber
1366
+ : payload === 'hull-12ga'
1367
+ ? mats.darkGunmetal
1368
+ : mats.copperTip;
1369
+ const caseMat = payload === 'hull-12ga'
1370
+ ? mats.shotgunHullRed
1371
+ : payload === 'warhead-85mm' || payload === 'grenade-40mm'
1372
+ ? mats.darkGunmetal
1373
+ : mats.brass;
1374
+ const spacingX = Math.max(0.055, chain.maxRadiusM * 4.2);
1375
+ const halfSpan = (chain.steps.length - 1) * 0.5;
1376
+ const nodeMetaByName = new Map();
1377
+ for (let i = 0; i < chain.steps.length; i++) {
1378
+ const step = chain.steps[i];
1379
+ const xPos = Number(((i - halfSpan) * spacingX).toFixed(4));
1380
+ const cart = new THREE.Group();
1381
+ cart.name = `Cartridge_LOD${i}_${step.sides}gon`;
1382
+ cart.position.set(xPos, 0, 0);
1383
+ nodeMetaByName.set(cart.name, {
1384
+ lodIndex: step.lodIndex,
1385
+ sides: step.sides,
1386
+ isBillboard: step.isBillboard,
1387
+ });
1388
+ if (step.isBillboard && step.billboardGeo) {
1389
+ const bMesh = new THREE.Mesh(step.billboardGeo, billboardRes.material);
1390
+ bMesh.name = `Billboard_LOD${i}_2gon`;
1391
+ cart.add(bMesh);
1392
+ }
1393
+ else if (step.casingGeo && step.projectileGeo) {
1394
+ const upright = new THREE.Group();
1395
+ upright.name = `UprightAssembly_LOD${i}`;
1396
+ upright.rotation.x = -Math.PI / 2;
1397
+ const cMesh = new THREE.Mesh(step.casingGeo, caseMat);
1398
+ cMesh.name = `Case_LOD${i}`;
1399
+ cMesh.position.set(0, 0, chain.uprightCaseZ);
1400
+ const pMesh = new THREE.Mesh(step.projectileGeo, projMat);
1401
+ pMesh.name = `Projectile_LOD${i}`;
1402
+ pMesh.position.set(0, 0, chain.uprightProjZ);
1403
+ upright.add(cMesh, pMesh);
1404
+ cart.add(upright);
1405
+ }
1406
+ root.add(cart);
1407
+ }
1408
+ const tempAmmoGeos = sanitizeExportSceneGeometries(root);
1409
+ root.updateMatrixWorld(true);
1410
+ const exporter = new GLTFExporter();
1411
+ const baseMass = payload === 'warhead-85mm'
1412
+ ? 1.45
1413
+ : payload === 'grenade-40mm'
1414
+ ? 0.23
1415
+ : payload === 'hull-12ga'
1416
+ ? 0.036
1417
+ : payload === 'spire-556'
1418
+ ? 0.012
1419
+ : payload === 'acp-45'
1420
+ ? 0.021
1421
+ : 0.012;
1422
+ const massKg = Number((baseMass * calScale * calScale * lenScale).toFixed(4));
1423
+ const capRadius = Number(((payload === 'warhead-85mm'
1424
+ ? 0.032
1425
+ : payload === 'grenade-40mm'
1426
+ ? 0.02
1427
+ : payload === 'hull-12ga'
1428
+ ? 0.01
1429
+ : payload === 'acp-45'
1430
+ ? 0.0062
1431
+ : 0.005) * calScale).toFixed(4));
1432
+ const capHeight = Number(Math.max(0.012, chain.totalHeightM).toFixed(4));
1433
+ const cleanupAll = () => {
1434
+ tempAmmoGeos.forEach((g) => g.dispose());
1435
+ chain.dispose();
1436
+ billboardRes.dispose();
1437
+ mats.dispose();
1438
+ };
1439
+ return new Promise((resolve, reject) => {
1440
+ exporter.parse(root, (result) => {
1441
+ cleanupAll();
1442
+ if (!(result instanceof ArrayBuffer)) {
1443
+ reject(new Error('Expected binary GLB output'));
1444
+ return;
1445
+ }
1446
+ const patched = patchGlbJsonChunk(result, (gltf) => {
1447
+ const used = new Set(gltf.extensionsUsed ?? []);
1448
+ used.add('KHR_physics_rigid_bodies');
1449
+ used.add('KHR_implicit_shapes');
1450
+ gltf.extensionsUsed = Array.from(used);
1451
+ gltf.extensions = gltf.extensions ?? {};
1452
+ gltf.extensions.KHR_implicit_shapes = {
1453
+ shapes: [
1454
+ {
1455
+ type: 'capsule',
1456
+ capsule: {
1457
+ height: capHeight,
1458
+ radiusTop: capRadius,
1459
+ radiusBottom: capRadius,
1460
+ },
1461
+ },
1462
+ ],
1463
+ };
1464
+ gltf.extensions.KHR_physics_rigid_bodies = {
1465
+ physicsMaterials: [
1466
+ {
1467
+ name: 'CartridgeBrass_C260',
1468
+ staticFriction: 0.36,
1469
+ dynamicFriction: 0.24,
1470
+ restitution: 0.46,
1471
+ },
1472
+ ],
1473
+ collisionFilters: [
1474
+ {
1475
+ name: 'BallisticDebris',
1476
+ collisionSystems: ['ammo_lods'],
1477
+ collideWithSystems: ['world_static'],
1478
+ },
1479
+ ],
1480
+ };
1481
+ (gltf.nodes ?? []).forEach((n) => {
1482
+ const meta = n.name ? nodeMetaByName.get(n.name) : undefined;
1483
+ if (meta) {
1484
+ n.extras = {
1485
+ ...(n.extras ?? {}),
1486
+ weaponRole: 'assembled_cartridge',
1487
+ payload,
1488
+ lodLevel: meta.lodIndex,
1489
+ radialSegments: meta.sides,
1490
+ isBillboard: meta.isBillboard,
1491
+ };
1492
+ n.extensions = {
1493
+ ...(n.extensions ?? {}),
1494
+ KHR_physics_rigid_bodies: {
1495
+ motion: {
1496
+ mass: massKg,
1497
+ isKinematic: false,
1498
+ centerOfMass: [0, Number((capHeight * 0.45).toFixed(4)), 0],
1499
+ inertiaDiagonal: computePrincipalInertiaDiagonal(massKg, [
1500
+ capRadius * 2,
1501
+ capHeight,
1502
+ capRadius * 2,
1503
+ ]),
1504
+ },
1505
+ collider: { geometry: { shape: 0 }, physicsMaterial: 0, collisionFilter: 0 },
1506
+ },
1507
+ };
1508
+ }
1509
+ });
1510
+ });
1511
+ const validation = validateGlbBinary(patched);
1512
+ resolve({ buffer: patched, validation });
1513
+ }, (err) => {
1514
+ cleanupAll();
1515
+ reject(err);
1516
+ }, { binary: true });
1517
+ });
1518
+ }
1519
+ export async function exportAmmoLodsGlb(archetypeId, radialSides, ammoSpec, triggerDownload = true) {
1520
+ const sides = ammoSpec?.radialSides ?? radialSides;
1521
+ const payload = ammoSpec?.payload ?? 'parabellum-9mm';
1522
+ const { buffer, validation } = await buildAmmoLodsGlbBuffer(archetypeId, sides, ammoSpec);
1523
+ const filename = `khr_armory_${payload}_ammo_${sides}gon.glb`;
1524
+ const downloaded = validation.valid && triggerDownload && typeof document !== 'undefined';
1525
+ if (downloaded) {
1526
+ downloadBinary(buffer, filename);
1527
+ }
1528
+ return { filename, byteSize: buffer.byteLength, validation, downloaded };
1529
+ }
1530
+ function sanitizeImportedGeometryForExport(geom) {
1531
+ const g = geom.clone();
1532
+ const pos = g.attributes.position;
1533
+ if (!pos)
1534
+ return g;
1535
+ if (!g.attributes.normal || g.attributes.normal.count !== pos.count) {
1536
+ g.computeVertexNormals();
1537
+ }
1538
+ const norm = g.attributes.normal;
1539
+ if (norm) {
1540
+ for (let i = 0; i < norm.count; i++) {
1541
+ const nx = norm.getX(i);
1542
+ const ny = norm.getY(i);
1543
+ const nz = norm.getZ(i);
1544
+ const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
1545
+ if (!Number.isFinite(len) || len < 1e-6) {
1546
+ norm.setXYZ(i, 0, 1, 0);
1547
+ }
1548
+ else if (Math.abs(len - 1.0) > 0.001) {
1549
+ norm.setXYZ(i, nx / len, ny / len, nz / len);
1550
+ }
1551
+ }
1552
+ norm.needsUpdate = true;
1553
+ }
1554
+ if (!g.attributes.uv) {
1555
+ const uvs = new Float32Array(pos.count * 2);
1556
+ for (let i = 0; i < pos.count; i++) {
1557
+ uvs[i * 2] = (pos.getZ(i) * 4) % 1;
1558
+ uvs[i * 2 + 1] = 0.875;
1559
+ }
1560
+ g.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));
1561
+ }
1562
+ return g;
1563
+ }
1564
+ function buildRoleJointDefinition(role, bboxSize, tuning) {
1565
+ const [sx, sy, sz] = bboxSize;
1566
+ const kS = tuning.stiffnessScale;
1567
+ const cS = tuning.dampingScale;
1568
+ if (role === 'wheel_shapecast') {
1569
+ return {
1570
+ isLinear: false,
1571
+ activeAxis: 0,
1572
+ freeSpin: true,
1573
+ min: 0,
1574
+ max: 0,
1575
+ limitK: 0,
1576
+ limitC: 0,
1577
+ driveK: 0,
1578
+ driveC: 0,
1579
+ };
1580
+ }
1581
+ if (role === 'slide_bolt') {
1582
+ return {
1583
+ isLinear: true,
1584
+ activeAxis: 2,
1585
+ min: -Number(Math.max(0.035, Math.min(0.11, sz * 0.34)).toFixed(4)),
1586
+ max: 0,
1587
+ limitK: Number((4200 * kS).toFixed(2)),
1588
+ limitC: Number((120 * cS).toFixed(2)),
1589
+ driveK: Number((920 * kS).toFixed(2)),
1590
+ driveC: Number((32 * cS).toFixed(2)),
1591
+ };
1592
+ }
1593
+ if (role === 'pump_forend') {
1594
+ return {
1595
+ isLinear: true,
1596
+ activeAxis: 2,
1597
+ min: -Number(Math.max(0.05, Math.min(0.14, sz * 0.55)).toFixed(4)),
1598
+ max: 0,
1599
+ limitK: Number((3400 * kS).toFixed(2)),
1600
+ limitC: Number((110 * cS).toFixed(2)),
1601
+ driveK: Number((480 * kS).toFixed(2)),
1602
+ driveC: Number((34 * cS).toFixed(2)),
1603
+ };
1604
+ }
1605
+ if (role === 'magazine') {
1606
+ return {
1607
+ isLinear: true,
1608
+ activeAxis: 1,
1609
+ min: -Number(Math.max(0.09, Math.min(0.24, sy * 1.15)).toFixed(4)),
1610
+ max: 0,
1611
+ limitK: Number((2500 * kS).toFixed(2)),
1612
+ limitC: Number((75 * cS).toFixed(2)),
1613
+ driveK: Number((460 * kS).toFixed(2)),
1614
+ driveC: Number((28 * cS).toFixed(2)),
1615
+ };
1616
+ }
1617
+ if (role === 'trigger') {
1618
+ return {
1619
+ isLinear: false,
1620
+ activeAxis: 0,
1621
+ min: 0,
1622
+ max: 0.36,
1623
+ limitK: Number((500 * kS).toFixed(2)),
1624
+ limitC: Number((14 * cS).toFixed(2)),
1625
+ driveK: Number((320 * kS).toFixed(2)),
1626
+ driveC: Number((18 * cS).toFixed(2)),
1627
+ };
1628
+ }
1629
+ return {
1630
+ isLinear: false,
1631
+ activeAxis: (sz >= sx ? 2 : 0),
1632
+ min: -2.15,
1633
+ max: 0,
1634
+ limitK: Number((440 * kS).toFixed(2)),
1635
+ limitC: Number((16 * cS).toFixed(2)),
1636
+ driveK: Number((190 * kS).toFixed(2)),
1637
+ driveC: Number((15 * cS).toFixed(2)),
1638
+ };
1639
+ }
1640
+ /**
1641
+ * Re-exports an uploaded segmented .glb (e.g. `tripo_part_0..N`) with user-assigned clean node names,
1642
+ * preserved `extras.originalSourceName`, auto-fitted `KHR_implicit_shapes` box colliders,
1643
+ * and `KHR_physics_rigid_bodies` 6-DOF joints connected to the `Receiver` root!
1644
+ */
1645
+ export async function buildTaggedExternalKhrGlbBuffer(rawBuffer, originalFilename, partTags, tuning, forwardAxis = '+Z', segmentationMode = 'islands') {
1646
+ const loader = new GLTFLoader();
1647
+ const gltfLoaded = await new Promise((resolve, reject) => {
1648
+ loader.parse(rawBuffer.slice(0), '', (res) => resolve({ scene: res.scene }), (err) => reject(err));
1649
+ });
1650
+ const sceneRoot = gltfLoaded.scene;
1651
+ sceneRoot.updateMatrixWorld(true);
1652
+ const rawBox = new THREE.Box3().setFromObject(sceneRoot);
1653
+ const rawSize = new THREE.Vector3();
1654
+ const rawCenter = new THREE.Vector3();
1655
+ rawBox.getSize(rawSize);
1656
+ rawBox.getCenter(rawCenter);
1657
+ const maxDim = Math.max(rawSize.x, rawSize.y, rawSize.z, 0.0001);
1658
+ // Normalize arbitrary unit-cube Tripo/Meshy/Rodin3D exports into realistic SI weapon scale (~0.44m)
1659
+ const normScale = maxDim < 0.1 || maxDim > 1.4 ? 0.44 / maxDim : 1.0;
1660
+ const normGroup = new THREE.Group();
1661
+ sceneRoot.scale.setScalar(normScale);
1662
+ sceneRoot.position.set(-rawCenter.x * normScale, -rawCenter.y * normScale + 0.02, -rawCenter.z * normScale);
1663
+ normGroup.add(sceneRoot);
1664
+ normGroup.updateMatrixWorld(true);
1665
+ const segmented = buildSegmentedUploadedScene(normGroup, segmentationMode);
1666
+ const sharedSegTextures = collectObject3DTextures(segmented.root);
1667
+ disposeObject3DResources(normGroup, { skipTextures: sharedSegTextures });
1668
+ const wrapper = segmented.root;
1669
+ wrapper.name = 'Receiver';
1670
+ if (forwardAxis === '-Z') {
1671
+ wrapper.rotation.y = Math.PI;
1672
+ }
1673
+ wrapper.updateMatrixWorld(true);
1674
+ const segments = segmented.segments;
1675
+ const usedNames = new Set(['Receiver']);
1676
+ const ensureUniqueName = (desired) => {
1677
+ const clean = desired.trim().replace(/\s+/g, '_') || 'Part_Segment';
1678
+ if (!usedNames.has(clean)) {
1679
+ usedNames.add(clean);
1680
+ return clean;
1681
+ }
1682
+ let suffix = 2;
1683
+ while (usedNames.has(`${clean}_${suffix}`))
1684
+ suffix++;
1685
+ const unique = `${clean}_${suffix}`;
1686
+ usedNames.add(unique);
1687
+ return unique;
1688
+ };
1689
+ const taggedEntries = [];
1690
+ const clonedGeos = [];
1691
+ let renamedCount = 0;
1692
+ const segBox = new THREE.Box3();
1693
+ const segSize = new THREE.Vector3();
1694
+ segments.forEach(({ segmentId, mesh, defaultTag }) => {
1695
+ const userTag = partTags[segmentId] ?? defaultTag;
1696
+ const roleSpec = IMPORTED_ROLE_SPECS.find((r) => r.id === userTag.role);
1697
+ const importedSanitized = sanitizeImportedGeometryForExport(mesh.geometry);
1698
+ const sanitizedGeo = sanitizeGeometryForFlatGlbExport(importedSanitized);
1699
+ importedSanitized.dispose();
1700
+ mesh.geometry.dispose();
1701
+ clonedGeos.push(sanitizedGeo);
1702
+ mesh.geometry = sanitizedGeo;
1703
+ const baseDesiredName = userTag.customName.trim() && userTag.customName.trim() !== defaultTag.originalName
1704
+ ? userTag.customName.trim()
1705
+ : roleSpec
1706
+ ? roleSpec.canonicalNodeName
1707
+ : userTag.customName.trim() || defaultTag.originalName;
1708
+ const finalNodeName = ensureUniqueName(baseDesiredName);
1709
+ if (finalNodeName !== defaultTag.originalName || userTag.role !== 'untagged') {
1710
+ renamedCount++;
1711
+ }
1712
+ mesh.name = finalNodeName;
1713
+ segBox.setFromObject(mesh);
1714
+ segBox.getSize(segSize);
1715
+ const bboxSizeM = [
1716
+ Number(Math.max(0.004, segSize.x).toFixed(4)),
1717
+ Number(Math.max(0.004, segSize.y).toFixed(4)),
1718
+ Number(Math.max(0.004, segSize.z).toFixed(4)),
1719
+ ];
1720
+ taggedEntries.push({
1721
+ nodeName: finalNodeName,
1722
+ originalSourceName: defaultTag.originalName,
1723
+ role: userTag.role,
1724
+ bboxSizeM,
1725
+ massKg: roleSpec?.defaultMassKg ?? 0.08,
1726
+ isDynamicJoint: Boolean(roleSpec?.isDynamicJoint),
1727
+ });
1728
+ });
1729
+ const fullBox = new THREE.Box3().setFromObject(wrapper);
1730
+ const fullSize = new THREE.Vector3();
1731
+ fullBox.getSize(fullSize);
1732
+ const rootBbox = [
1733
+ Number(Math.max(0.02, fullSize.x).toFixed(4)),
1734
+ Number(Math.max(0.02, fullSize.y).toFixed(4)),
1735
+ Number(Math.max(0.02, fullSize.z).toFixed(4)),
1736
+ ];
1737
+ const exporter = new GLTFExporter();
1738
+ return new Promise((resolve, reject) => {
1739
+ exporter.parse(wrapper, (result) => {
1740
+ clonedGeos.forEach((g) => g.dispose());
1741
+ disposeObject3DResources(wrapper);
1742
+ if (!(result instanceof ArrayBuffer)) {
1743
+ reject(new Error('Expected binary GLB output'));
1744
+ return;
1745
+ }
1746
+ let builtJointCount = 0;
1747
+ const patched = patchGlbJsonChunk(result, (gltf) => {
1748
+ gltf.asset = {
1749
+ ...(gltf.asset ?? {}),
1750
+ version: '2.0',
1751
+ generator: 'khr-armory (Segmented Rig)',
1752
+ extras: {
1753
+ sourceFile: originalFilename,
1754
+ coordinateConvention: forwardAxis === '-Z'
1755
+ ? '-Z_forward_+Y_up_+X_right_SI_meters'
1756
+ : '+Z_forward_+Y_up_+X_right_SI_meters',
1757
+ },
1758
+ };
1759
+ const used = new Set(gltf.extensionsUsed ?? []);
1760
+ used.add('KHR_physics_rigid_bodies');
1761
+ used.add('KHR_implicit_shapes');
1762
+ gltf.extensionsUsed = Array.from(used);
1763
+ const nodes = gltf.nodes ?? [];
1764
+ const nameToIdx = new Map();
1765
+ nodes.forEach((n, idx) => {
1766
+ if (n.name)
1767
+ nameToIdx.set(n.name, idx);
1768
+ });
1769
+ // Pick explicit receiver_body node if tagged, else top-level 'Receiver' wrapper
1770
+ const explicitRecEntry = taggedEntries.find((e) => e.role === 'receiver_body');
1771
+ const receiverNodeIdx = (explicitRecEntry ? nameToIdx.get(explicitRecEntry.nodeName) : undefined) ??
1772
+ nameToIdx.get('Receiver') ??
1773
+ 0;
1774
+ const receiverExtents = explicitRecEntry ? explicitRecEntry.bboxSizeM : rootBbox;
1775
+ const shapes = [];
1776
+ const physicsJoints = [];
1777
+ // Shape 0: Kinematic Receiver / Chassis Root
1778
+ shapes.push({
1779
+ type: 'box',
1780
+ box: { size: receiverExtents },
1781
+ });
1782
+ if (nodes[receiverNodeIdx]) {
1783
+ nodes[receiverNodeIdx].extras = {
1784
+ ...(nodes[receiverNodeIdx].extras ?? {}),
1785
+ weaponRole: 'receiver_root',
1786
+ originalSourceName: explicitRecEntry?.originalSourceName ?? originalFilename,
1787
+ };
1788
+ nodes[receiverNodeIdx].extensions = {
1789
+ ...(nodes[receiverNodeIdx].extensions ?? {}),
1790
+ KHR_physics_rigid_bodies: {
1791
+ motion: {
1792
+ isKinematic: true,
1793
+ },
1794
+ collider: {
1795
+ geometry: { shape: 0 },
1796
+ physicsMaterial: 0,
1797
+ collisionFilter: 0,
1798
+ },
1799
+ },
1800
+ };
1801
+ }
1802
+ // Attach metadata + colliders + 6-DOF KHR joints for every tagged mesh node
1803
+ taggedEntries.forEach((entry) => {
1804
+ const nIdx = nameToIdx.get(entry.nodeName);
1805
+ if (nIdx === undefined || !nodes[nIdx] || nIdx === receiverNodeIdx)
1806
+ return;
1807
+ const isWheel = entry.role === 'wheel_shapecast';
1808
+ const wheelRadius = Number((Math.max(entry.bboxSizeM[1], entry.bboxSizeM[2]) * 0.5).toFixed(4));
1809
+ const wheelWidth = Number(entry.bboxSizeM[0].toFixed(4));
1810
+ const wheelTravel = Number((wheelRadius * 0.45).toFixed(4));
1811
+ nodes[nIdx].extras = {
1812
+ ...(nodes[nIdx].extras ?? {}),
1813
+ originalSourceName: entry.originalSourceName,
1814
+ weaponRole: entry.role,
1815
+ ...(isWheel
1816
+ ? {
1817
+ ecctrlWheel: {
1818
+ radius: wheelRadius,
1819
+ width: wheelWidth,
1820
+ travel: wheelTravel,
1821
+ sag: Number((wheelTravel * 0.35).toFixed(4)),
1822
+ steer: false,
1823
+ drive: true,
1824
+ brake: true,
1825
+ },
1826
+ }
1827
+ : {}),
1828
+ };
1829
+ if (isWheel)
1830
+ return;
1831
+ if (entry.isDynamicJoint) {
1832
+ const shapeIdx = shapes.length;
1833
+ shapes.push({
1834
+ type: 'box',
1835
+ box: { size: entry.bboxSizeM },
1836
+ });
1837
+ const jd = buildRoleJointDefinition(entry.role, entry.bboxSizeM, tuning);
1838
+ const jointIdx = physicsJoints.length;
1839
+ physicsJoints.push(buildKhr6DofJoint({
1840
+ isLinear: jd.isLinear,
1841
+ activeAxis: jd.activeAxis,
1842
+ freeSpin: 'freeSpin' in jd ? jd.freeSpin : false,
1843
+ min: jd.min,
1844
+ max: jd.max,
1845
+ limitStiffness: jd.limitK,
1846
+ limitDamping: jd.limitC,
1847
+ driveStiffness: jd.driveK,
1848
+ driveDamping: jd.driveC,
1849
+ extras: {
1850
+ weaponRole: entry.role,
1851
+ nodeName: entry.nodeName,
1852
+ connectedNodeName: nodes[receiverNodeIdx]?.name ?? 'Receiver',
1853
+ },
1854
+ }));
1855
+ nodes[nIdx].extensions = {
1856
+ ...(nodes[nIdx].extensions ?? {}),
1857
+ KHR_physics_rigid_bodies: {
1858
+ motion: {
1859
+ mass: entry.massKg,
1860
+ isKinematic: false,
1861
+ centerOfMass: [0, 0, 0],
1862
+ inertiaDiagonal: computePrincipalInertiaDiagonal(entry.massKg, entry.bboxSizeM),
1863
+ },
1864
+ collider: {
1865
+ geometry: { shape: shapeIdx },
1866
+ physicsMaterial: 0,
1867
+ collisionFilter: 0,
1868
+ },
1869
+ joint: {
1870
+ joint: jointIdx,
1871
+ connectedNode: receiverNodeIdx,
1872
+ enableCollision: false,
1873
+ },
1874
+ },
1875
+ };
1876
+ builtJointCount++;
1877
+ }
1878
+ else if (entry.role !== 'untagged') {
1879
+ // Static collider shape on tagged rails/barrels/grips
1880
+ const shapeIdx = shapes.length;
1881
+ shapes.push({
1882
+ type: 'box',
1883
+ box: { size: entry.bboxSizeM },
1884
+ });
1885
+ nodes[nIdx].extensions = {
1886
+ ...(nodes[nIdx].extensions ?? {}),
1887
+ KHR_physics_rigid_bodies: {
1888
+ collider: {
1889
+ geometry: { shape: shapeIdx },
1890
+ physicsMaterial: 0,
1891
+ collisionFilter: 0,
1892
+ },
1893
+ },
1894
+ };
1895
+ }
1896
+ });
1897
+ gltf.extensions = gltf.extensions ?? {};
1898
+ gltf.extensions.KHR_implicit_shapes = { shapes };
1899
+ gltf.extensions.KHR_physics_rigid_bodies = {
1900
+ physicsMaterials: [
1901
+ {
1902
+ name: 'MachinedSteel_4140',
1903
+ staticFriction: 0.42,
1904
+ dynamicFriction: 0.28,
1905
+ restitution: 0.22,
1906
+ },
1907
+ ],
1908
+ collisionFilters: [
1909
+ {
1910
+ name: 'WeaponInternalMechanism',
1911
+ collisionSystems: ['weapon_rig'],
1912
+ notCollideWithSystems: ['weapon_rig'],
1913
+ },
1914
+ ],
1915
+ physicsJoints,
1916
+ };
1917
+ const renamedFromOriginal = new Map();
1918
+ for (const entry of taggedEntries) {
1919
+ if (entry.originalSourceName && entry.originalSourceName !== entry.nodeName) {
1920
+ renamedFromOriginal.set(entry.originalSourceName, entry.nodeName);
1921
+ }
1922
+ }
1923
+ copyOmiExtensions(readGlbJson(rawBuffer), gltf, renamedFromOriginal);
1924
+ });
1925
+ const validation = validateGlbBinary(patched);
1926
+ resolve({
1927
+ buffer: patched,
1928
+ validation,
1929
+ jointCount: builtJointCount,
1930
+ renamedCount,
1931
+ });
1932
+ }, (err) => {
1933
+ clonedGeos.forEach((g) => g.dispose());
1934
+ disposeObject3DResources(wrapper);
1935
+ reject(err);
1936
+ }, { binary: true });
1937
+ });
1938
+ }
1939
+ export async function exportTaggedExternalGlb(rawBuffer, originalFilename, partTags, tuning, forwardAxis = '+Z', segmentationMode = 'islands', triggerDownload = true) {
1940
+ const { buffer, validation, jointCount, renamedCount } = await buildTaggedExternalKhrGlbBuffer(rawBuffer, originalFilename, partTags, tuning, forwardAxis, segmentationMode);
1941
+ const baseStem = originalFilename
1942
+ .replace(/\.(glb|gltf)$/i, '')
1943
+ .toLowerCase()
1944
+ .replace(/[^a-z0-9]+/g, '_');
1945
+ const axisSuffix = forwardAxis === '-Z' ? '_negZ' : '_posZ';
1946
+ const filename = `${baseStem || 'segmented_weapon'}_khr_rigged${axisSuffix}.glb`;
1947
+ const downloaded = validation.valid && triggerDownload && typeof document !== 'undefined';
1948
+ if (downloaded) {
1949
+ downloadBinary(buffer, filename);
1950
+ }
1951
+ return {
1952
+ filename,
1953
+ byteSize: buffer.byteLength,
1954
+ jointCount,
1955
+ renamedCount,
1956
+ validation,
1957
+ downloaded,
1958
+ };
1959
+ }
1960
+ //# sourceMappingURL=glbPhysicsExporter.js.map