@khr3/core 0.2.12 → 0.2.13

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.
@@ -2,6 +2,7 @@ import React, { createContext, useCallback, useEffect, useLayoutEffect, useRef }
2
2
  import { BallCollider, CapsuleCollider, CoefficientCombineRule, ConvexHullCollider, CuboidCollider, CylinderCollider, TrimeshCollider } from "@react-three/rapier";
3
3
  import { jsx } from "react/jsx-runtime";
4
4
  import * as THREE from "three";
5
+ import { ConvexGeometry } from "three/examples/jsm/geometries/ConvexGeometry.js";
5
6
  // src/types.ts
6
7
  var KhrValidationError = class extends Error {
7
8
  constructor(message) {
@@ -33,9 +34,6 @@ function assignRef(ref, value) {
33
34
  var SCALE_EPS = 1e-4;
34
35
  var _wsScratch = new THREE.Vector3();
35
36
  var _one = new THREE.Vector3(1, 1, 1);
36
- var _tmpPos = new THREE.Vector3();
37
- var _tmpQuat = new THREE.Quaternion();
38
- var _tmpQuatB = new THREE.Quaternion();
39
37
  function isUnitScalar(v) {
40
38
  return typeof v === "number" && Number.isFinite(v) && Math.abs(v - 1) <= 1e-9;
41
39
  }
@@ -138,18 +136,493 @@ function extractMeshColliderShape(targetObj, meshNodeName, convexHull) {
138
136
  meshNodeName
139
137
  };
140
138
  }
141
- function bodyPoseMatrix(body, target = new THREE.Matrix4()) {
142
- return target.compose(_tmpPos.fromArray(body.localPosition), _tmpQuat.fromArray(body.localQuaternion), _one);
139
+ /**
140
+ * Exact 3x3 symmetric Jacobi eigendecomposition returning positive principal inertia diagonal
141
+ * and right-handed `SO(3)` principal frame quaternion `[x, y, z, w]`.
142
+ */
143
+ function jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz) {
144
+ const a = [
145
+ [
146
+ ixx,
147
+ ixy,
148
+ ixz
149
+ ],
150
+ [
151
+ ixy,
152
+ iyy,
153
+ iyz
154
+ ],
155
+ [
156
+ ixz,
157
+ iyz,
158
+ izz
159
+ ]
160
+ ];
161
+ const v = [
162
+ [
163
+ 1,
164
+ 0,
165
+ 0
166
+ ],
167
+ [
168
+ 0,
169
+ 1,
170
+ 0
171
+ ],
172
+ [
173
+ 0,
174
+ 0,
175
+ 1
176
+ ]
177
+ ];
178
+ for (let iter = 0; iter < 32; iter++) {
179
+ const tr = Math.max(a[0][0] + a[1][1] + a[2][2], 0);
180
+ let p = 0, q = 1, maxOff = Math.abs(a[0][1]);
181
+ if (Math.abs(a[0][2]) > maxOff) {
182
+ p = 0;
183
+ q = 2;
184
+ maxOff = Math.abs(a[0][2]);
185
+ }
186
+ if (Math.abs(a[1][2]) > maxOff) {
187
+ p = 1;
188
+ q = 2;
189
+ maxOff = Math.abs(a[1][2]);
190
+ }
191
+ if (maxOff <= 1e-12 * tr) break;
192
+ const apq = a[p][q], app = a[p][p], aqq = a[q][q];
193
+ const tau = (aqq - app) / (2 * apq);
194
+ const t = tau >= 0 ? 1 / (tau + Math.sqrt(1 + tau * tau)) : -1 / (-tau + Math.sqrt(1 + tau * tau));
195
+ const c = 1 / Math.sqrt(1 + t * t), s = t * c;
196
+ const r = 3 - p - q;
197
+ a[p][p] = c * c * app - 2 * s * c * apq + s * s * aqq;
198
+ a[q][q] = s * s * app + 2 * s * c * apq + c * c * aqq;
199
+ a[p][q] = a[q][p] = 0;
200
+ const arp = a[r][p], arq = a[r][q];
201
+ a[r][p] = a[p][r] = c * arp - s * arq;
202
+ a[r][q] = a[q][r] = s * arp + c * arq;
203
+ for (let i = 0; i < 3; i++) {
204
+ const vip = v[i][p], viq = v[i][q];
205
+ v[i][p] = c * vip - s * viq;
206
+ v[i][q] = s * vip + c * viq;
207
+ }
208
+ }
209
+ if (v[0][0] * (v[1][1] * v[2][2] - v[1][2] * v[2][1]) - v[0][1] * (v[1][0] * v[2][2] - v[1][2] * v[2][0]) + v[0][2] * (v[1][0] * v[2][1] - v[1][1] * v[2][0]) < 0) {
210
+ v[0][2] = -v[0][2];
211
+ v[1][2] = -v[1][2];
212
+ v[2][2] = -v[2][2];
213
+ }
214
+ const mat = new THREE.Matrix4().set(v[0][0], v[0][1], v[0][2], 0, v[1][0], v[1][1], v[1][2], 0, v[2][0], v[2][1], v[2][2], 0, 0, 0, 0, 1);
215
+ const q = new THREE.Quaternion().setFromRotationMatrix(mat).normalize();
216
+ return {
217
+ inertia: [
218
+ a[0][0],
219
+ a[1][1],
220
+ a[2][2]
221
+ ],
222
+ inertiaFrame: [
223
+ q.x,
224
+ q.y,
225
+ q.z,
226
+ q.w
227
+ ]
228
+ };
229
+ }
230
+ /**
231
+ * Exact 3D signed-tetrahedron divergence integration for closed solid triangle meshes.
232
+ */
233
+ function integrateClosedMeshProps(vertices, indices) {
234
+ const triCount = indices ? Math.floor(indices.length / 3) : Math.floor(vertices.length / 9);
235
+ if (triCount < 4) return null;
236
+ let rx = 0, ry = 0, rz = 0;
237
+ const vCount = Math.floor(vertices.length / 3);
238
+ for (let i = 0; i < vCount; i++) {
239
+ rx += vertices[i * 3];
240
+ ry += vertices[i * 3 + 1];
241
+ rz += vertices[i * 3 + 2];
242
+ }
243
+ rx /= vCount;
244
+ ry /= vCount;
245
+ rz /= vCount;
246
+ let vol6 = 0;
247
+ let cx24 = 0, cy24 = 0, cz24 = 0;
248
+ let cxx120 = 0, cyy120 = 0, czz120 = 0;
249
+ let cxy120 = 0, cxz120 = 0, cyz120 = 0;
250
+ for (let t = 0; t < triCount; t++) {
251
+ const i0 = (indices ? indices[t * 3] : t * 3) * 3;
252
+ const i1 = (indices ? indices[t * 3 + 1] : t * 3 + 1) * 3;
253
+ const i2 = (indices ? indices[t * 3 + 2] : t * 3 + 2) * 3;
254
+ const ax = vertices[i0] - rx, ay = vertices[i0 + 1] - ry, az = vertices[i0 + 2] - rz;
255
+ const bx = vertices[i1] - rx, by = vertices[i1 + 1] - ry, bz = vertices[i1 + 2] - rz;
256
+ const cx = vertices[i2] - rx, cy = vertices[i2 + 1] - ry, cz = vertices[i2 + 2] - rz;
257
+ const det = ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx);
258
+ vol6 += det;
259
+ const sx = ax + bx + cx, sy = ay + by + cy, sz = az + bz + cz;
260
+ cx24 += det * sx;
261
+ cy24 += det * sy;
262
+ cz24 += det * sz;
263
+ cxx120 += det * (sx * sx + ax * ax + bx * bx + cx * cx);
264
+ cyy120 += det * (sy * sy + ay * ay + by * by + cy * cy);
265
+ czz120 += det * (sz * sz + az * az + bz * bz + cz * cz);
266
+ cxy120 += det * (sx * sy + ax * ay + bx * by + cx * cy);
267
+ cxz120 += det * (sx * sz + ax * az + bx * bz + cx * cz);
268
+ cyz120 += det * (sy * sz + ay * az + by * bz + cy * cz);
269
+ }
270
+ const sign = vol6 < 0 ? -1 : 1;
271
+ const volume = sign * vol6 / 6;
272
+ if (!(volume > 1e-9)) return null;
273
+ const invV = 1 / volume;
274
+ const comRelX = sign * cx24 / (24 * volume);
275
+ const comRelY = sign * cy24 / (24 * volume);
276
+ const comRelZ = sign * cz24 / (24 * volume);
277
+ const cxx = sign * cxx120 / 120 * invV - comRelX * comRelX;
278
+ const cyy = sign * cyy120 / 120 * invV - comRelY * comRelY;
279
+ const czz = sign * czz120 / 120 * invV - comRelZ * comRelZ;
280
+ const cxy = sign * cxy120 / 120 * invV - comRelX * comRelY;
281
+ const cxz = sign * cxz120 / 120 * invV - comRelX * comRelZ;
282
+ const cyz = sign * cyz120 / 120 * invV - comRelY * comRelZ;
283
+ const ixx = cyy + czz;
284
+ const iyy = cxx + czz;
285
+ const izz = cxx + cyy;
286
+ if (!(ixx > 0 && iyy > 0 && izz > 0)) return null;
287
+ return {
288
+ measure: volume,
289
+ isVolumetric: true,
290
+ centroid: new THREE.Vector3(rx + comRelX, ry + comRelY, rz + comRelZ),
291
+ unitTensor: [
292
+ ixx,
293
+ iyy,
294
+ izz,
295
+ -cxy,
296
+ -cxz,
297
+ -cyz
298
+ ]
299
+ };
300
+ }
301
+ /**
302
+ * Exact 2D surface-area second-moment integration over open triangle shells
303
+ * (used when an unclosed sheet-metal panel mesh has zero enclosed 3D volume).
304
+ * Throws `KhrValidationError` if all triangles are collinear/degenerate.
305
+ */
306
+ function integrateSurfaceShellProps(vertices, indices, label) {
307
+ const triCount = indices ? Math.floor(indices.length / 3) : Math.floor(vertices.length / 9);
308
+ if (triCount < 1) throw new KhrValidationError(`Collider mesh "${label}" has no triangles`);
309
+ let rx = 0, ry = 0, rz = 0;
310
+ const vCount = Math.floor(vertices.length / 3);
311
+ for (let i = 0; i < vCount; i++) {
312
+ rx += vertices[i * 3];
313
+ ry += vertices[i * 3 + 1];
314
+ rz += vertices[i * 3 + 2];
315
+ }
316
+ rx /= vCount;
317
+ ry /= vCount;
318
+ rz /= vCount;
319
+ let area2 = 0;
320
+ let cx6 = 0, cy6 = 0, cz6 = 0;
321
+ let sxx24 = 0, syy24 = 0, szz24 = 0;
322
+ let sxy24 = 0, sxz24 = 0, syz24 = 0;
323
+ for (let t = 0; t < triCount; t++) {
324
+ const i0 = (indices ? indices[t * 3] : t * 3) * 3;
325
+ const i1 = (indices ? indices[t * 3 + 1] : t * 3 + 1) * 3;
326
+ const i2 = (indices ? indices[t * 3 + 2] : t * 3 + 2) * 3;
327
+ const ax = vertices[i0] - rx, ay = vertices[i0 + 1] - ry, az = vertices[i0 + 2] - rz;
328
+ const bx = vertices[i1] - rx, by = vertices[i1 + 1] - ry, bz = vertices[i1 + 2] - rz;
329
+ const cx = vertices[i2] - rx, cy = vertices[i2 + 1] - ry, cz = vertices[i2 + 2] - rz;
330
+ const e1x = bx - ax, e1y = by - ay, e1z = bz - az;
331
+ const e2x = cx - ax, e2y = cy - ay, e2z = cz - az;
332
+ const nx = e1y * e2z - e1z * e2y;
333
+ const ny = e1z * e2x - e1x * e2z;
334
+ const nz = e1x * e2y - e1y * e2x;
335
+ const dblArea = Math.hypot(nx, ny, nz);
336
+ if (dblArea <= 1e-14) continue;
337
+ area2 += dblArea;
338
+ const sx = ax + bx + cx, sy = ay + by + cy, sz = az + bz + cz;
339
+ cx6 += dblArea * sx;
340
+ cy6 += dblArea * sy;
341
+ cz6 += dblArea * sz;
342
+ sxx24 += dblArea * (sx * sx + ax * ax + bx * bx + cx * cx);
343
+ syy24 += dblArea * (sy * sy + ay * ay + by * by + cy * cy);
344
+ szz24 += dblArea * (sz * sz + az * az + bz * bz + cz * cz);
345
+ sxy24 += dblArea * (sx * sy + ax * ay + bx * by + cx * cy);
346
+ sxz24 += dblArea * (sx * sz + ax * az + bx * bz + cx * cz);
347
+ syz24 += dblArea * (sy * sz + ay * az + by * bz + cy * cz);
348
+ }
349
+ const area = .5 * area2;
350
+ if (!(area > 1e-10)) throw new KhrValidationError(`Collider mesh "${label}" has zero surface area (collinear/degenerate vertices)`);
351
+ const comRelX = cx6 / (6 * area);
352
+ const comRelY = cy6 / (6 * area);
353
+ const comRelZ = cz6 / (6 * area);
354
+ const cxx = sxx24 / (24 * area) - comRelX * comRelX;
355
+ const cyy = syy24 / (24 * area) - comRelY * comRelY;
356
+ const czz = szz24 / (24 * area) - comRelZ * comRelZ;
357
+ const cxy = sxy24 / (24 * area) - comRelX * comRelY;
358
+ const cxz = sxz24 / (24 * area) - comRelX * comRelZ;
359
+ const cyz = syz24 / (24 * area) - comRelY * comRelZ;
360
+ const ixx = Math.max(cyy + czz, 1e-9);
361
+ const iyy = Math.max(cxx + czz, 1e-9);
362
+ const izz = Math.max(cxx + cyy, 1e-9);
363
+ return {
364
+ measure: area,
365
+ isVolumetric: false,
366
+ centroid: new THREE.Vector3(rx + comRelX, ry + comRelY, rz + comRelZ),
367
+ unitTensor: [
368
+ ixx,
369
+ iyy,
370
+ izz,
371
+ -cxy,
372
+ -cxz,
373
+ -cyz
374
+ ]
375
+ };
376
+ }
377
+ function deduplicateQuantizedPoints(vertices) {
378
+ const pts = [];
379
+ const seen = /* @__PURE__ */ new Set();
380
+ for (let i = 0; i < vertices.length; i += 3) {
381
+ const vx = vertices[i], vy = vertices[i + 1], vz = vertices[i + 2];
382
+ const key = `${Math.round(vx * 1e5)},${Math.round(vy * 1e5)},${Math.round(vz * 1e5)}`;
383
+ if (!seen.has(key)) {
384
+ seen.add(key);
385
+ pts.push(new THREE.Vector3(vx, vy, vz));
386
+ }
387
+ }
388
+ return pts;
389
+ }
390
+ function unitInertiaForShape(shape) {
391
+ if (shape.type === "box") {
392
+ const [x, y, z] = shape.size;
393
+ return {
394
+ measure: x * y * z,
395
+ isVolumetric: true,
396
+ centroid: new THREE.Vector3(),
397
+ unitTensor: [
398
+ (y * y + z * z) / 12,
399
+ (x * x + z * z) / 12,
400
+ (x * x + y * y) / 12,
401
+ 0,
402
+ 0,
403
+ 0
404
+ ]
405
+ };
406
+ }
407
+ if (shape.type === "sphere") {
408
+ const r = shape.radius;
409
+ const i = .4 * r * r;
410
+ return {
411
+ measure: 4 / 3 * Math.PI * r * r * r,
412
+ isVolumetric: true,
413
+ centroid: new THREE.Vector3(),
414
+ unitTensor: [
415
+ i,
416
+ i,
417
+ i,
418
+ 0,
419
+ 0,
420
+ 0
421
+ ]
422
+ };
423
+ }
424
+ if (shape.type === "trimesh") return integrateClosedMeshProps(shape.vertices, shape.indices) ?? integrateSurfaceShellProps(shape.vertices, shape.indices, shape.meshNodeName);
425
+ if (shape.type === "convexHull") {
426
+ const pts = deduplicateQuantizedPoints(shape.vertices);
427
+ if (pts.length >= 4) try {
428
+ const hullGeo = new ConvexGeometry(pts);
429
+ const pos = hullGeo.getAttribute("position");
430
+ const closed = pos && pos.count >= 12 ? integrateClosedMeshProps(pos.array, null) : null;
431
+ hullGeo.dispose();
432
+ if (closed) return closed;
433
+ } catch {}
434
+ if (pts.length >= 3) {
435
+ const fanVerts = new Float32Array((pts.length - 2) * 9);
436
+ let o = 0;
437
+ for (let i = 1; i + 1 < pts.length; i++) {
438
+ fanVerts[o++] = pts[0].x;
439
+ fanVerts[o++] = pts[0].y;
440
+ fanVerts[o++] = pts[0].z;
441
+ fanVerts[o++] = pts[i].x;
442
+ fanVerts[o++] = pts[i].y;
443
+ fanVerts[o++] = pts[i].z;
444
+ fanVerts[o++] = pts[i + 1].x;
445
+ fanVerts[o++] = pts[i + 1].y;
446
+ fanVerts[o++] = pts[i + 1].z;
447
+ }
448
+ return integrateSurfaceShellProps(fanVerts, null, shape.meshNodeName);
449
+ }
450
+ throw new KhrValidationError(`ConvexHull collider "${shape.meshNodeName}" has fewer than 3 distinct vertices`);
451
+ }
452
+ const r = shape.radiusTop;
453
+ const h = shape.height;
454
+ if (shape.type === "capsule") {
455
+ const cylVol = Math.PI * r * r * h;
456
+ const totVol = cylVol + 4 / 3 * Math.PI * r * r * r;
457
+ const fc = cylVol / totVol;
458
+ const fh = 1 - fc;
459
+ const iy = .5 * fc * r * r + .4 * fh * r * r;
460
+ const ix = fc * (h * h / 12 + .25 * r * r) + fh * (.4 * r * r + .25 * h * h + .375 * h * r);
461
+ return {
462
+ measure: totVol,
463
+ isVolumetric: true,
464
+ centroid: new THREE.Vector3(),
465
+ unitTensor: [
466
+ ix,
467
+ iy,
468
+ ix,
469
+ 0,
470
+ 0,
471
+ 0
472
+ ]
473
+ };
474
+ }
475
+ const ix = (3 * r * r + h * h) / 12;
476
+ return {
477
+ measure: Math.PI * r * r * h,
478
+ isVolumetric: true,
479
+ centroid: new THREE.Vector3(),
480
+ unitTensor: [
481
+ ix,
482
+ .5 * r * r,
483
+ ix,
484
+ 0,
485
+ 0,
486
+ 0
487
+ ]
488
+ };
489
+ }
490
+ /**
491
+ * Computes exact principal inertia diagonal `[I1, I2, I3]` for a single `KhrColliderShape` of `mass` kg
492
+ * about its centroid.
493
+ */
494
+ function computeShapeInertia(shape, mass) {
495
+ const [ixx, iyy, izz, ixy, ixz, iyz] = unitInertiaForShape(shape).unitTensor;
496
+ if (Math.abs(ixy) + Math.abs(ixz) + Math.abs(iyz) > 1e-12 * (ixx + iyy + izz)) {
497
+ const { inertia } = jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz);
498
+ return [
499
+ mass * inertia[0],
500
+ mass * inertia[1],
501
+ mass * inertia[2]
502
+ ];
503
+ }
504
+ return [
505
+ mass * ixx,
506
+ mass * iyy,
507
+ mass * izz
508
+ ];
509
+ }
510
+ /**
511
+ * Resolves exact center of mass, full 3x3 Steiner parallel-axis inertia tensor, and Jacobi principal frame
512
+ * for a dynamic `KhrBodySpec` from its colliders when `motion.inertiaDiagonal` is omitted in the `.glb`.
513
+ */
514
+ function resolveBodyMassFromColliders(colliders, mass, explicitCom, explicitInertiaOrientation, nodeName) {
515
+ if (colliders.length === 0) throw new KhrValidationError(`Dynamic node "${nodeName}" is missing motion.inertiaDiagonal and has no colliders`);
516
+ const shapes = colliders.map((c) => unitInertiaForShape(c.shape));
517
+ const hasVolumetric = shapes.some((s) => s.isVolumetric);
518
+ let totalWeight = 0;
519
+ for (const s of shapes) if (!hasVolumetric || s.isVolumetric) totalWeight += s.measure;
520
+ const colQuat = new THREE.Quaternion();
521
+ const worldCentroids = [];
522
+ let wx = 0, wy = 0, wz = 0;
523
+ for (let i = 0; i < colliders.length; i++) {
524
+ const col = colliders[i];
525
+ const shp = shapes[i];
526
+ const w = !hasVolumetric || shp.isVolumetric ? shp.measure : 0;
527
+ colQuat.fromArray(col.localQuaternion);
528
+ const cBody = shp.centroid.clone().applyQuaternion(colQuat).add(new THREE.Vector3().fromArray(col.localPosition));
529
+ worldCentroids.push(cBody);
530
+ wx += cBody.x * w;
531
+ wy += cBody.y * w;
532
+ wz += cBody.z * w;
533
+ }
534
+ const com = explicitCom ?? (totalWeight > 0 ? [
535
+ wx / totalWeight,
536
+ wy / totalWeight,
537
+ wz / totalWeight
538
+ ] : [
539
+ 0,
540
+ 0,
541
+ 0
542
+ ]);
543
+ const invFrame = explicitInertiaOrientation ? new THREE.Quaternion().fromArray(explicitInertiaOrientation).invert() : new THREE.Quaternion();
544
+ const relQuat = new THREE.Quaternion();
545
+ const offset = new THREE.Vector3();
546
+ const rotMat = new THREE.Matrix4();
547
+ const m = rotMat.elements;
548
+ let ixx = 0, iyy = 0, izz = 0, ixy = 0, ixz = 0, iyz = 0;
549
+ for (let i = 0; i < colliders.length; i++) {
550
+ const col = colliders[i];
551
+ const shp = shapes[i];
552
+ const w = !hasVolumetric || shp.isVolumetric ? shp.measure : 0;
553
+ const mShare = totalWeight > 0 ? mass * (w / totalWeight) : mass / colliders.length;
554
+ if (mShare <= 0) continue;
555
+ colQuat.fromArray(col.localQuaternion);
556
+ offset.copy(worldCentroids[i]).sub(new THREE.Vector3(com[0], com[1], com[2])).applyQuaternion(invFrame);
557
+ relQuat.copy(invFrame).multiply(colQuat);
558
+ rotMat.makeRotationFromQuaternion(relQuat);
559
+ const [uxx, uyy, uzz, uxy, uxz, uyz] = shp.unitTensor;
560
+ const r00 = m[0], r01 = m[4], r02 = m[8];
561
+ const r10 = m[1], r11 = m[5], r12 = m[9];
562
+ const r20 = m[2], r21 = m[6], r22 = m[10];
563
+ const a00 = uxx * r00 + uxy * r01 + uxz * r02;
564
+ const a01 = uxy * r00 + uyy * r01 + uyz * r02;
565
+ const a02 = uxz * r00 + uyz * r01 + uzz * r02;
566
+ const a10 = uxx * r10 + uxy * r11 + uxz * r12;
567
+ const a11 = uxy * r10 + uyy * r11 + uyz * r12;
568
+ const a12 = uxz * r10 + uyz * r11 + uzz * r12;
569
+ const txx = r00 * a00 + r01 * a01 + r02 * a02;
570
+ const tyy = r10 * a10 + r11 * a11 + r12 * a12;
571
+ const tzz = r20 * (uxx * r20 + uxy * r21 + uxz * r22) + r21 * (uxy * r20 + uyy * r21 + uyz * r22) + r22 * (uxz * r20 + uyz * r21 + uzz * r22);
572
+ const txy = r00 * a10 + r01 * a11 + r02 * a12;
573
+ const txz = r00 * (uxx * r20 + uxy * r21 + uxz * r22) + r01 * (uxy * r20 + uyy * r21 + uyz * r22) + r02 * (uxz * r20 + uyz * r21 + uzz * r22);
574
+ const tyz = r10 * (uxx * r20 + uxy * r21 + uxz * r22) + r11 * (uxy * r20 + uyy * r21 + uyz * r22) + r12 * (uxz * r20 + uyz * r21 + uzz * r22);
575
+ const dx = offset.x, dy = offset.y, dz = offset.z;
576
+ ixx += mShare * (txx + dy * dy + dz * dz);
577
+ iyy += mShare * (tyy + dx * dx + dz * dz);
578
+ izz += mShare * (tzz + dx * dx + dy * dy);
579
+ ixy += mShare * (txy - dx * dy);
580
+ ixz += mShare * (txz - dx * dz);
581
+ iyz += mShare * (tyz - dy * dz);
582
+ }
583
+ if (!Number.isFinite(ixx) || !Number.isFinite(iyy) || !Number.isFinite(izz) || ixx <= 0 || iyy <= 0 || izz <= 0) throw new KhrValidationError(`Dynamic node "${nodeName}" has degenerate collider geometry; cannot compute positive motion.inertiaDiagonal`);
584
+ if (explicitInertiaOrientation) return {
585
+ centerOfMass: com,
586
+ inertiaDiagonal: [
587
+ ixx,
588
+ iyy,
589
+ izz
590
+ ],
591
+ inertiaOrientation: explicitInertiaOrientation
592
+ };
593
+ const diagSum = Math.max(ixx + iyy + izz, 0);
594
+ if (Math.max(Math.abs(ixy), Math.abs(ixz), Math.abs(iyz)) <= 1e-12 * diagSum) return {
595
+ centerOfMass: com,
596
+ inertiaDiagonal: [
597
+ ixx,
598
+ iyy,
599
+ izz
600
+ ],
601
+ inertiaOrientation: [
602
+ 0,
603
+ 0,
604
+ 0,
605
+ 1
606
+ ]
607
+ };
608
+ const { inertia, inertiaFrame } = jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz);
609
+ return {
610
+ centerOfMass: com,
611
+ inertiaDiagonal: inertia,
612
+ inertiaOrientation: inertiaFrame
613
+ };
143
614
  }
144
615
  function computeAssemblyMassAndCom(bodies) {
145
616
  let totalDynamicMass = 0, mx = 0, my = 0, mz = 0;
617
+ const q = new THREE.Quaternion();
618
+ const c = new THREE.Vector3();
146
619
  for (const b of bodies) {
147
620
  if (b.isKinematic) continue;
148
621
  totalDynamicMass += b.mass;
149
- _tmpPos.fromArray(b.centerOfMass).applyQuaternion(_tmpQuat.fromArray(b.localQuaternion));
150
- mx += (b.localPosition[0] + _tmpPos.x) * b.mass;
151
- my += (b.localPosition[1] + _tmpPos.y) * b.mass;
152
- mz += (b.localPosition[2] + _tmpPos.z) * b.mass;
622
+ c.fromArray(b.centerOfMass).applyQuaternion(q.fromArray(b.localQuaternion));
623
+ mx += (b.localPosition[0] + c.x) * b.mass;
624
+ my += (b.localPosition[1] + c.y) * b.mass;
625
+ mz += (b.localPosition[2] + c.z) * b.mass;
153
626
  }
154
627
  return {
155
628
  totalDynamicMass,
@@ -164,134 +637,128 @@ function computeAssemblyMassAndCom(bodies) {
164
637
  ]
165
638
  };
166
639
  }
167
- /**
168
- * Builds a `RigidBody`-local mass specification from a `KhrBodySpec`.
169
- * When `hasExplicitInertia` is false, Rapier WASM (`parry3d`) computes exact volume, CoM,
170
- * parallel-axis tensor, and principal inertia directly from the attached colliders.
171
- */
172
- function buildBodyMassTarget(body, bodyRotInRigidBody = [
173
- 0,
174
- 0,
175
- 0,
176
- 1
177
- ], bodyOffsetInRigidBody = [
178
- 0,
179
- 0,
180
- 0
181
- ]) {
182
- if (body.isKinematic || !(body.mass > 0)) return null;
183
- _tmpQuat.set(bodyRotInRigidBody[0], bodyRotInRigidBody[1], bodyRotInRigidBody[2], bodyRotInRigidBody[3]).normalize();
184
- _tmpPos.fromArray(body.centerOfMass).applyQuaternion(_tmpQuat);
640
+ function bodyPoseMatrix(body, target = new THREE.Matrix4()) {
641
+ return target.compose(new THREE.Vector3().fromArray(body.localPosition), new THREE.Quaternion().fromArray(body.localQuaternion), _one);
642
+ }
643
+ function decomposeBodyInFrame(body, invFrame, posOut, quatOut, sclScratch, matScratch) {
644
+ if (invFrame) {
645
+ matScratch.multiplyMatrices(invFrame, bodyPoseMatrix(body, matScratch)).decompose(posOut, quatOut, sclScratch);
646
+ quatOut.normalize();
647
+ } else {
648
+ posOut.fromArray(body.localPosition);
649
+ quatOut.fromArray(body.localQuaternion).normalize();
650
+ }
651
+ }
652
+ function computeLumpedMassProps(bodies, invFrame) {
653
+ const dyn = bodies.filter((b) => !b.isKinematic && b.mass > 0);
654
+ if (dyn.length === 0) return null;
655
+ const pos = new THREE.Vector3();
656
+ const quat = new THREE.Quaternion();
657
+ const qExtra = new THREE.Quaternion();
658
+ const rCom = new THREE.Vector3();
659
+ const scl = new THREE.Vector3();
660
+ const mat = new THREE.Matrix4();
661
+ if (dyn.length === 1) {
662
+ const b = dyn[0];
663
+ decomposeBodyInFrame(b, invFrame, pos, quat, scl, mat);
664
+ rCom.fromArray(b.centerOfMass).applyQuaternion(quat);
665
+ const frameQuat = quat.clone().multiply(qExtra.fromArray(b.inertiaOrientation)).normalize();
666
+ return {
667
+ mass: b.mass,
668
+ com: [
669
+ pos.x + rCom.x,
670
+ pos.y + rCom.y,
671
+ pos.z + rCom.z
672
+ ],
673
+ inertia: [
674
+ b.inertiaDiagonal[0],
675
+ b.inertiaDiagonal[1],
676
+ b.inertiaDiagonal[2]
677
+ ],
678
+ inertiaFrame: [
679
+ frameQuat.x,
680
+ frameQuat.y,
681
+ frameQuat.z,
682
+ frameQuat.w
683
+ ]
684
+ };
685
+ }
686
+ let totalMass = 0, mx = 0, my = 0, mz = 0;
687
+ for (const b of dyn) {
688
+ decomposeBodyInFrame(b, invFrame, pos, quat, scl, mat);
689
+ rCom.fromArray(b.centerOfMass).applyQuaternion(quat);
690
+ totalMass += b.mass;
691
+ mx += (pos.x + rCom.x) * b.mass;
692
+ my += (pos.y + rCom.y) * b.mass;
693
+ mz += (pos.z + rCom.z) * b.mass;
694
+ }
695
+ if (!(totalMass > 0)) return null;
185
696
  const com = [
186
- bodyOffsetInRigidBody[0] + _tmpPos.x,
187
- bodyOffsetInRigidBody[1] + _tmpPos.y,
188
- bodyOffsetInRigidBody[2] + _tmpPos.z
697
+ mx / totalMass,
698
+ my / totalMass,
699
+ mz / totalMass
189
700
  ];
190
- _tmpQuatB.copy(_tmpQuat).multiply(new THREE.Quaternion().fromArray(body.inertiaOrientation)).normalize();
191
- return {
192
- mass: body.mass,
701
+ let ixx = 0, iyy = 0, izz = 0, ixy = 0, ixz = 0, iyz = 0;
702
+ const m = mat.elements;
703
+ for (const b of dyn) {
704
+ decomposeBodyInFrame(b, invFrame, pos, quat, scl, mat);
705
+ rCom.fromArray(b.centerOfMass).applyQuaternion(quat);
706
+ const dx = pos.x + rCom.x - com[0];
707
+ const dy = pos.y + rCom.y - com[1];
708
+ const dz = pos.z + rCom.z - com[2];
709
+ mat.makeRotationFromQuaternion(quat.multiply(qExtra.fromArray(b.inertiaOrientation)));
710
+ const [d0, d1, d2] = b.inertiaDiagonal;
711
+ ixx += m[0] * m[0] * d0 + m[4] * m[4] * d1 + m[8] * m[8] * d2 + b.mass * (dy * dy + dz * dz);
712
+ iyy += m[1] * m[1] * d0 + m[5] * m[5] * d1 + m[9] * m[9] * d2 + b.mass * (dx * dx + dz * dz);
713
+ izz += m[2] * m[2] * d0 + m[6] * m[6] * d1 + m[10] * m[10] * d2 + b.mass * (dx * dx + dy * dy);
714
+ ixy += m[0] * m[1] * d0 + m[4] * m[5] * d1 + m[8] * m[9] * d2 - b.mass * dx * dy;
715
+ ixz += m[0] * m[2] * d0 + m[4] * m[6] * d1 + m[8] * m[10] * d2 - b.mass * dx * dz;
716
+ iyz += m[1] * m[2] * d0 + m[5] * m[6] * d1 + m[9] * m[10] * d2 - b.mass * dy * dz;
717
+ }
718
+ const diagSum = Math.max(ixx + iyy + izz, 0);
719
+ if (Math.max(Math.abs(ixy), Math.abs(ixz), Math.abs(iyz)) <= 1e-12 * diagSum) return {
720
+ mass: totalMass,
193
721
  com,
194
- hasExplicitCom: Boolean(body.hasExplicitCom) || Math.abs(com[0]) > 1e-9 || Math.abs(com[1]) > 1e-9 || Math.abs(com[2]) > 1e-9,
195
- inertiaDiagonal: [
196
- body.inertiaDiagonal[0],
197
- body.inertiaDiagonal[1],
198
- body.inertiaDiagonal[2]
722
+ inertia: [
723
+ ixx,
724
+ iyy,
725
+ izz
199
726
  ],
200
727
  inertiaFrame: [
201
- _tmpQuatB.x,
202
- _tmpQuatB.y,
203
- _tmpQuatB.z,
204
- _tmpQuatB.w
205
- ],
206
- hasExplicitInertia: Boolean(body.hasExplicitInertia)
728
+ 0,
729
+ 0,
730
+ 0,
731
+ 1
732
+ ]
733
+ };
734
+ const { inertia, inertiaFrame } = jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz);
735
+ return {
736
+ mass: totalMass,
737
+ com,
738
+ inertia,
739
+ inertiaFrame
207
740
  };
208
741
  }
209
742
  /**
210
- * Applies `KHR_physics_rigid_bodies` mass properties to a live Rapier WASM `RigidBody`:
211
- * - Explicit `motion.inertiaDiagonal`: passes authored `{ mass, com, inertiaDiagonal, inertiaFrame }` directly to Rapier.
212
- * - Omitted `motion.inertiaDiagonal`: delegates volume, CoM, parallel-axis lumping, and Jacobi principal-axis inertia
213
- * to Rapier's Rust `parry3d` engine across all attached colliders, preserving explicit `motion.centerOfMass` if authored.
743
+ * Applies exact `LumpedMassProps` directly in `RigidBody` local space (`density = 0` on colliders).
214
744
  */
215
- function applyRapierBodyMass(rb, target) {
216
- if (!target || !(target.mass > 0)) return;
745
+ function applyRapierBodyMass(rb, lumped) {
746
+ if (!lumped || !(lumped.mass > 0)) return;
217
747
  const n = rb.numColliders();
218
- if (target.hasExplicitInertia) {
219
- for (let i = 0; i < n; i++) rb.collider(i).setDensity(0);
220
- rb.setAdditionalMassProperties(target.mass, {
221
- x: target.com[0],
222
- y: target.com[1],
223
- z: target.com[2]
224
- }, {
225
- x: target.inertiaDiagonal[0],
226
- y: target.inertiaDiagonal[1],
227
- z: target.inertiaDiagonal[2]
228
- }, {
229
- x: target.inertiaFrame[0],
230
- y: target.inertiaFrame[1],
231
- z: target.inertiaFrame[2],
232
- w: target.inertiaFrame[3]
233
- }, true);
234
- rb.recomputeMassPropertiesFromColliders();
235
- return;
236
- }
237
- rb.setAdditionalMassProperties(0, {
238
- x: 0,
239
- y: 0,
240
- z: 0
241
- }, {
242
- x: 0,
243
- y: 0,
244
- z: 0
245
- }, {
246
- x: 0,
247
- y: 0,
248
- z: 0,
249
- w: 1
250
- }, false);
251
- for (let i = 0; i < n; i++) rb.collider(i).setDensity(1);
252
- rb.recomputeMassPropertiesFromColliders();
253
- const unitMass = rb.mass();
254
- if (n > 0 && unitMass > 1e-9) {
255
- const rho = target.mass / unitMass;
256
- for (let i = 0; i < n; i++) rb.collider(i).setDensity(rho);
257
- rb.recomputeMassPropertiesFromColliders();
258
- if (target.hasExplicitCom) {
259
- const pi = rb.principalInertia();
260
- const pf = rb.principalInertiaLocalFrame();
261
- for (let i = 0; i < n; i++) rb.collider(i).setDensity(0);
262
- rb.setAdditionalMassProperties(target.mass, {
263
- x: target.com[0],
264
- y: target.com[1],
265
- z: target.com[2]
266
- }, {
267
- x: pi.x,
268
- y: pi.y,
269
- z: pi.z
270
- }, {
271
- x: pf.x,
272
- y: pf.y,
273
- z: pf.z,
274
- w: pf.w
275
- }, true);
276
- rb.recomputeMassPropertiesFromColliders();
277
- }
278
- return;
279
- }
280
748
  for (let i = 0; i < n; i++) rb.collider(i).setDensity(0);
281
- const diag = .04 * target.mass;
282
- rb.setAdditionalMassProperties(target.mass, {
283
- x: target.com[0],
284
- y: target.com[1],
285
- z: target.com[2]
749
+ rb.setAdditionalMassProperties(lumped.mass, {
750
+ x: lumped.com[0],
751
+ y: lumped.com[1],
752
+ z: lumped.com[2]
286
753
  }, {
287
- x: diag,
288
- y: diag,
289
- z: diag
754
+ x: lumped.inertia[0],
755
+ y: lumped.inertia[1],
756
+ z: lumped.inertia[2]
290
757
  }, {
291
- x: 0,
292
- y: 0,
293
- z: 0,
294
- w: 1
758
+ x: lumped.inertiaFrame[0],
759
+ y: lumped.inertiaFrame[1],
760
+ z: lumped.inertiaFrame[2],
761
+ w: lumped.inertiaFrame[3]
295
762
  }, true);
296
763
  rb.recomputeMassPropertiesFromColliders();
297
764
  }
@@ -442,6 +909,13 @@ function cloneKhrBundle(bundle) {
442
909
  position: [...p.position],
443
910
  ...p.quaternion ? { quaternion: [...p.quaternion] } : {}
444
911
  })),
912
+ emitters: bundle.emitters.map((e) => ({
913
+ ...e,
914
+ ...e.color ? { color: [...e.color] } : {},
915
+ position: [...e.position],
916
+ quaternion: [...e.quaternion],
917
+ object: remapNode(bundle.scene, e.object, scene)
918
+ })),
445
919
  sockets,
446
920
  totalDynamicMass: bundle.totalDynamicMass,
447
921
  centerOfMass: [...bundle.centerOfMass],
@@ -860,6 +1334,6 @@ function toggleDrivenJoint(rt) {
860
1334
  rt.applyTarget(nextTarget);
861
1335
  return true;
862
1336
  }
863
- export { computeRelativePose as A, isObj as B, applyRapierBodyMass as C, bodyPoseMatrix as D, assertUnitScale as E, JointRegistryContext as F, optFiniteNum as H, KhrValidationError as I, assignRef as L, readFiniteVec3 as M, readUnitQuat as N, buildBodyMassTarget as O, COMBINE_MODES as P, isFiniteNum as R, snapshotSceneWithMountedSubtrees as S, assertSceneIdentityWorldScale as T, isPosNum as V, cloneKhrBundle as _, configureJointDrive as a, releaseBundleMount as b, measureJointCoordinate as c, KHR_TRIMESH_FLAGS as d, KhrCollider as f, claimBundleMount as g, captureSubtreeOrigins as h, closedTargetForLimits as i, extractMeshColliderShape as j, computeAssemblyMassAndCom as k, openTargetForLimits as l, MountSubtreeSlot as m, DETACHED_PANEL_INTERACTION_GROUPS as n, createRapierImpulseJoint as o, BundleSceneHost as p, buildJointRuntime as r, isJointOpen as s, ATTACHED_PANEL_INTERACTION_GROUPS as t, toggleDrivenJoint as u, disposeKhrBundle as v, assertIdentityWorldScale as w, restoreSubtreeOrigin as x, registerMountedSubtree as y, isNonNegNum as z };
1337
+ export { computeRelativePose as A, assignRef as B, applyRapierBodyMass as C, bodyPoseMatrix as D, assertUnitScale as E, readUnitQuat as F, optFiniteNum as G, isNonNegNum as H, resolveBodyMassFromColliders as I, COMBINE_MODES as L, extractMeshColliderShape as M, jacobiPrincipalInertia as N, computeAssemblyMassAndCom as O, readFiniteVec3 as P, JointRegistryContext as R, snapshotSceneWithMountedSubtrees as S, assertSceneIdentityWorldScale as T, isObj as U, isFiniteNum as V, isPosNum as W, cloneKhrBundle as _, configureJointDrive as a, releaseBundleMount as b, measureJointCoordinate as c, KHR_TRIMESH_FLAGS as d, KhrCollider as f, claimBundleMount as g, captureSubtreeOrigins as h, closedTargetForLimits as i, computeShapeInertia as j, computeLumpedMassProps as k, openTargetForLimits as l, MountSubtreeSlot as m, DETACHED_PANEL_INTERACTION_GROUPS as n, createRapierImpulseJoint as o, BundleSceneHost as p, buildJointRuntime as r, isJointOpen as s, ATTACHED_PANEL_INTERACTION_GROUPS as t, toggleDrivenJoint as u, disposeKhrBundle as v, assertIdentityWorldScale as w, restoreSubtreeOrigin as x, registerMountedSubtree as y, KhrValidationError as z };
864
1338
 
865
- //# sourceMappingURL=joints-5IgWDD2w.js.map
1339
+ //# sourceMappingURL=joints-H3uae8pm.js.map