@khr3/core 0.2.13 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,10 @@
1
- import React, { createContext, useCallback, useEffect, useLayoutEffect, useRef } from "react";
2
- import { BallCollider, CapsuleCollider, CoefficientCombineRule, ConvexHullCollider, CuboidCollider, CylinderCollider, TrimeshCollider } from "@react-three/rapier";
3
- import { jsx } from "react/jsx-runtime";
1
+ import React, { createContext, useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef } from "react";
4
2
  import * as THREE from "three";
3
+ import { useFrame } from "@react-three/fiber";
4
+ import { BallCollider, CapsuleCollider, CoefficientCombineRule, ConvexHullCollider, CuboidCollider, CylinderCollider, RigidBody, TrimeshCollider, useRapier } from "@react-three/rapier";
5
+ import { useCustomGravity } from "@pinkaphant/ecctrl/gravity";
5
6
  import { ConvexGeometry } from "three/examples/jsm/geometries/ConvexGeometry.js";
7
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
8
  // src/types.ts
7
9
  var KhrValidationError = class extends Error {
8
10
  constructor(message) {
@@ -357,9 +359,10 @@ function integrateSurfaceShellProps(vertices, indices, label) {
357
359
  const cxy = sxy24 / (24 * area) - comRelX * comRelY;
358
360
  const cxz = sxz24 / (24 * area) - comRelX * comRelZ;
359
361
  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);
362
+ const ixx = cyy + czz;
363
+ const iyy = cxx + czz;
364
+ const izz = cxx + cyy;
365
+ if (!(ixx > 1e-12 && iyy > 1e-12 && izz > 1e-12)) throw new KhrValidationError(`Collider mesh "${label}" is degenerate (1D collinear strip); cannot compute positive 3D inertia`);
363
366
  return {
364
367
  measure: area,
365
368
  isVolumetric: false,
@@ -387,6 +390,75 @@ function deduplicateQuantizedPoints(vertices) {
387
390
  }
388
391
  return pts;
389
392
  }
393
+ /**
394
+ * Exact 2D Andrew Monotone Chain convex hull in the best-fit plane of coplanar 3D points `pts`,
395
+ * returning CCW-ordered perimeter vertices so triangle fan integration never self-intersects.
396
+ */
397
+ function buildCoplanarConvexPolygon(pts, label) {
398
+ const p0 = pts[0];
399
+ let bestNormal = new THREE.Vector3();
400
+ let bestNormSq = 0;
401
+ const e1 = new THREE.Vector3();
402
+ const e2 = new THREE.Vector3();
403
+ const nCand = new THREE.Vector3();
404
+ for (let i = 1; i < pts.length; i++) {
405
+ e1.subVectors(pts[i], p0);
406
+ for (let j = i + 1; j < pts.length; j++) {
407
+ e2.subVectors(pts[j], p0);
408
+ nCand.crossVectors(e1, e2);
409
+ const sq = nCand.lengthSq();
410
+ if (sq > bestNormSq) {
411
+ bestNormSq = sq;
412
+ bestNormal.copy(nCand);
413
+ }
414
+ }
415
+ }
416
+ if (!(bestNormSq > 1e-20)) throw new KhrValidationError(`ConvexHull collider "${label}" has collinear vertices (zero 2D hull area)`);
417
+ bestNormal.normalize();
418
+ const axisU = new THREE.Vector3();
419
+ if (Math.abs(bestNormal.x) < .9) axisU.set(1, 0, 0).cross(bestNormal).normalize();
420
+ else axisU.set(0, 1, 0).cross(bestNormal).normalize();
421
+ const axisV = new THREE.Vector3().crossVectors(bestNormal, axisU).normalize();
422
+ const projected = pts.map((p) => {
423
+ const d = e1.subVectors(p, p0);
424
+ return {
425
+ u: d.dot(axisU),
426
+ v: d.dot(axisV),
427
+ p
428
+ };
429
+ });
430
+ projected.sort((a, b) => a.u !== b.u ? a.u - b.u : a.v - b.v);
431
+ const cross2 = (o, a, b) => (a.u - o.u) * (b.v - o.v) - (a.v - o.v) * (b.u - o.u);
432
+ const lower = [];
433
+ for (const pt of projected) {
434
+ while (lower.length >= 2 && cross2(lower[lower.length - 2], lower[lower.length - 1], pt) <= 1e-12) lower.pop();
435
+ lower.push(pt);
436
+ }
437
+ const upper = [];
438
+ for (let i = projected.length - 1; i >= 0; i--) {
439
+ const pt = projected[i];
440
+ while (upper.length >= 2 && cross2(upper[upper.length - 2], upper[upper.length - 1], pt) <= 1e-12) upper.pop();
441
+ upper.push(pt);
442
+ }
443
+ lower.pop();
444
+ upper.pop();
445
+ const hull = [...lower, ...upper];
446
+ if (hull.length < 3) throw new KhrValidationError(`ConvexHull collider "${label}" has fewer than 3 non-collinear hull vertices`);
447
+ const fanVerts = new Float32Array((hull.length - 2) * 9);
448
+ let o = 0;
449
+ for (let i = 1; i + 1 < hull.length; i++) {
450
+ fanVerts[o++] = hull[0].p.x;
451
+ fanVerts[o++] = hull[0].p.y;
452
+ fanVerts[o++] = hull[0].p.z;
453
+ fanVerts[o++] = hull[i].p.x;
454
+ fanVerts[o++] = hull[i].p.y;
455
+ fanVerts[o++] = hull[i].p.z;
456
+ fanVerts[o++] = hull[i + 1].p.x;
457
+ fanVerts[o++] = hull[i + 1].p.y;
458
+ fanVerts[o++] = hull[i + 1].p.z;
459
+ }
460
+ return fanVerts;
461
+ }
390
462
  function unitInertiaForShape(shape) {
391
463
  if (shape.type === "box") {
392
464
  const [x, y, z] = shape.size;
@@ -431,22 +503,7 @@ function unitInertiaForShape(shape) {
431
503
  hullGeo.dispose();
432
504
  if (closed) return closed;
433
505
  } 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
- }
506
+ if (pts.length >= 3) return integrateSurfaceShellProps(buildCoplanarConvexPolygon(pts, shape.meshNodeName), null, shape.meshNodeName);
450
507
  throw new KhrValidationError(`ConvexHull collider "${shape.meshNodeName}" has fewer than 3 distinct vertices`);
451
508
  }
452
509
  const r = shape.radiusTop;
@@ -740,10 +797,26 @@ function computeLumpedMassProps(bodies, invFrame) {
740
797
  };
741
798
  }
742
799
  /**
800
+ * Verifies that `rb` is still live in `world` (`world.getRigidBody(rb.handle) === rb`),
801
+ * preventing React 19 `<StrictMode>` pass-1 freed WASM handle panics (`RuntimeError: unreachable`).
802
+ */
803
+ function isLiveRapierBody(world, rb) {
804
+ if (!rb) return false;
805
+ return world.getRigidBody(rb.handle) === rb;
806
+ }
807
+ /**
808
+ * Verifies that `col` is still live in `world` (`world.getCollider(col.handle) === col`).
809
+ */
810
+ function isLiveRapierCollider(world, col) {
811
+ if (!col) return false;
812
+ return world.getCollider(col.handle) === col;
813
+ }
814
+ /**
743
815
  * Applies exact `LumpedMassProps` directly in `RigidBody` local space (`density = 0` on colliders).
744
816
  */
745
- function applyRapierBodyMass(rb, lumped) {
817
+ function applyRapierBodyMass(rb, lumped, world) {
746
818
  if (!lumped || !(lumped.mass > 0)) return;
819
+ if (world && !isLiveRapierBody(world, rb)) return;
747
820
  const n = rb.numColliders();
748
821
  for (let i = 0; i < n; i++) rb.collider(i).setDensity(0);
749
822
  rb.setAdditionalMassProperties(lumped.mass, {
@@ -1076,14 +1149,19 @@ var COMBINE_RULES = {
1076
1149
  /** `RAPIER.TriMeshFlags.FIX_INTERNAL_EDGES` (144) — merges duplicate vertices and suppresses internal seam ghost normals. */
1077
1150
  var KHR_TRIMESH_FLAGS = 144;
1078
1151
  function KhrCollider({ c, position, quaternion, density, mass, massProperties, collisionGroups, solverGroups, ref }) {
1152
+ const { world } = useRapier();
1079
1153
  const innerRef = useRef(null);
1080
1154
  const setRef = useCallback((node) => {
1081
1155
  innerRef.current = node;
1082
1156
  assignRef(ref, node);
1083
1157
  }, [ref]);
1084
1158
  useEffect(() => {
1085
- innerRef.current?.parent()?.recomputeMassPropertiesFromColliders();
1159
+ const col = innerRef.current;
1160
+ if (!col || !isLiveRapierCollider(world, col)) return;
1161
+ const parent = col.parent();
1162
+ if (parent && isLiveRapierBody(world, parent)) parent.recomputeMassPropertiesFromColliders();
1086
1163
  }, [
1164
+ world,
1087
1165
  c,
1088
1166
  density,
1089
1167
  mass,
@@ -1334,6 +1412,587 @@ function toggleDrivenJoint(rt) {
1334
1412
  rt.applyTarget(nextTarget);
1335
1413
  return true;
1336
1414
  }
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 };
1415
+ // src/KhrAssembly.tsx
1416
+ function matrixToRoot(node, sceneRoot) {
1417
+ const out = new THREE.Matrix4();
1418
+ for (let cur = node; cur && cur !== sceneRoot; cur = cur.parent) {
1419
+ if (!cur.parent) throw new KhrValidationError(`Node "${node.name}" is detached from bundle.scene`);
1420
+ cur.updateMatrix();
1421
+ out.premultiply(cur.matrix);
1422
+ }
1423
+ return out;
1424
+ }
1425
+ function isSceneDescendant(node, ancestor) {
1426
+ for (let cur = node; cur; cur = cur.parent) if (cur === ancestor) return true;
1427
+ return false;
1428
+ }
1429
+ function lowestCommonAncestor(nodes, sceneRoot) {
1430
+ let candidate = nodes[0];
1431
+ while (candidate && candidate !== sceneRoot) {
1432
+ if (nodes.every((n) => isSceneDescendant(n, candidate))) return candidate;
1433
+ candidate = candidate.parent ?? sceneRoot;
1434
+ }
1435
+ return sceneRoot;
1436
+ }
1437
+ function planOwnColliders(body, frameQuat) {
1438
+ const one = new THREE.Vector3(1, 1, 1);
1439
+ const frameMat = frameQuat ? new THREE.Matrix4().makeRotationFromQuaternion(frameQuat) : null;
1440
+ const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
1441
+ return body.colliders.map((spec) => {
1442
+ const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
1443
+ const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one);
1444
+ if (frameMat) local.premultiply(frameMat);
1445
+ local.decompose(pos, quat, scl);
1446
+ quat.normalize();
1447
+ return {
1448
+ spec,
1449
+ position: [
1450
+ pos.x,
1451
+ pos.y,
1452
+ pos.z
1453
+ ],
1454
+ quaternion: [
1455
+ quat.x,
1456
+ quat.y,
1457
+ quat.z,
1458
+ quat.w
1459
+ ]
1460
+ };
1461
+ });
1462
+ }
1463
+ function planAssembly(bundle) {
1464
+ const byName = new Map(bundle.bodies.map((b) => [b.nodeName, b]));
1465
+ const rootMemo = /* @__PURE__ */ new Map();
1466
+ const depthMemo = /* @__PURE__ */ new Map();
1467
+ const resolveRootAndDepth = (b, visiting = /* @__PURE__ */ new Set()) => {
1468
+ const cachedRoot = rootMemo.get(b.nodeName);
1469
+ const cachedDepth = depthMemo.get(b.nodeName);
1470
+ if (cachedRoot && cachedDepth !== void 0) return {
1471
+ root: cachedRoot,
1472
+ depth: cachedDepth
1473
+ };
1474
+ if (!b.joint) {
1475
+ rootMemo.set(b.nodeName, b);
1476
+ depthMemo.set(b.nodeName, 0);
1477
+ return {
1478
+ root: b,
1479
+ depth: 0
1480
+ };
1481
+ }
1482
+ if (visiting.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
1483
+ visiting.add(b.nodeName);
1484
+ const parent = byName.get(b.joint.connectedNodeName);
1485
+ if (!parent) throw new KhrValidationError(`Joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a KHR body`);
1486
+ const up = resolveRootAndDepth(parent, visiting);
1487
+ rootMemo.set(b.nodeName, up.root);
1488
+ depthMemo.set(b.nodeName, up.depth + 1);
1489
+ return {
1490
+ root: up.root,
1491
+ depth: up.depth + 1
1492
+ };
1493
+ };
1494
+ for (const b of bundle.bodies) resolveRootAndDepth(b);
1495
+ const plans = bundle.bodies.filter((b) => !b.joint).map((root) => {
1496
+ const invRoot = bodyPoseMatrix(root).clone().invert();
1497
+ const descendants = bundle.bodies.filter((b) => b.joint && rootMemo.get(b.nodeName) === root).sort((a, b) => (depthMemo.get(a.nodeName) ?? 0) - (depthMemo.get(b.nodeName) ?? 0));
1498
+ const partByName = /* @__PURE__ */ new Map();
1499
+ const parts = descendants.map((b) => {
1500
+ const joint = b.joint;
1501
+ const parent = partByName.get(joint.connectedNodeName) ?? null;
1502
+ if (parent && !isSceneDescendant(b.object, parent.spec.object)) throw new KhrValidationError(`Jointed node "${b.nodeName}" must be a scene-graph descendant of its jointed parent "${joint.connectedNodeName}"`);
1503
+ const relParentMat = bodyPoseMatrix(parent ? parent.spec : root).clone().invert().multiply(bodyPoseMatrix(b));
1504
+ const relRootMat = invRoot.clone().multiply(bodyPoseMatrix(b));
1505
+ const rpPos = new THREE.Vector3(), tmpQ = new THREE.Quaternion(), rpScl = new THREE.Vector3();
1506
+ relParentMat.decompose(rpPos, tmpQ, rpScl);
1507
+ const rrPos = new THREE.Vector3(), rrQuat = new THREE.Quaternion();
1508
+ relRootMat.decompose(rrPos, rrQuat, rpScl);
1509
+ rrQuat.normalize();
1510
+ const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
1511
+ const axParentVec = axChildVec.clone().applyQuaternion(rrQuat).normalize();
1512
+ const anchorParent = parent ? [
1513
+ rrPos.x - parent.restRelRootPos[0],
1514
+ rrPos.y - parent.restRelRootPos[1],
1515
+ rrPos.z - parent.restRelRootPos[2]
1516
+ ] : [
1517
+ rpPos.x,
1518
+ rpPos.y,
1519
+ rpPos.z
1520
+ ];
1521
+ const rrQuatTuple = [
1522
+ rrQuat.x,
1523
+ rrQuat.y,
1524
+ rrQuat.z,
1525
+ rrQuat.w
1526
+ ];
1527
+ const invPartFrame = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(b.localPosition), new THREE.Quaternion().fromArray(root.localQuaternion), new THREE.Vector3(1, 1, 1)).invert();
1528
+ const lumpedMass = computeLumpedMassProps([b], invPartFrame);
1529
+ const colliders = planOwnColliders(b, rrQuat);
1530
+ const plan = {
1531
+ spec: b,
1532
+ joint,
1533
+ parent,
1534
+ restRelParentPos: anchorParent,
1535
+ restRelParentQuat: rrQuatTuple,
1536
+ restRelRootPos: [
1537
+ rrPos.x,
1538
+ rrPos.y,
1539
+ rrPos.z
1540
+ ],
1541
+ restRelRootQuat: rrQuatTuple,
1542
+ axisParent: [
1543
+ axParentVec.x,
1544
+ axParentVec.y,
1545
+ axParentVec.z
1546
+ ],
1547
+ axisChild: [
1548
+ axChildVec.x,
1549
+ axChildVec.y,
1550
+ axChildVec.z
1551
+ ],
1552
+ lumpedMass,
1553
+ colliders
1554
+ };
1555
+ partByName.set(b.nodeName, plan);
1556
+ return plan;
1557
+ });
1558
+ const lumpedMass = computeLumpedMassProps([root], invRoot);
1559
+ const colliders = planOwnColliders(root);
1560
+ const mountNode = lowestCommonAncestor([root.object, ...descendants.map((d) => d.object)], bundle.scene);
1561
+ const mountInRoot = invRoot.clone().multiply(matrixToRoot(mountNode, bundle.scene));
1562
+ const scenePos = new THREE.Vector3(), sceneQuat = new THREE.Quaternion(), sceneScl = new THREE.Vector3();
1563
+ invRoot.decompose(scenePos, sceneQuat, sceneScl);
1564
+ sceneQuat.normalize();
1565
+ const mountPos = new THREE.Vector3(), mountQuat = new THREE.Quaternion();
1566
+ mountInRoot.decompose(mountPos, mountQuat, sceneScl);
1567
+ mountQuat.normalize();
1568
+ return {
1569
+ spec: root,
1570
+ sceneInRootPos: [
1571
+ scenePos.x,
1572
+ scenePos.y,
1573
+ scenePos.z
1574
+ ],
1575
+ sceneInRootQuat: [
1576
+ sceneQuat.x,
1577
+ sceneQuat.y,
1578
+ sceneQuat.z,
1579
+ sceneQuat.w
1580
+ ],
1581
+ mountNode,
1582
+ mountPosition: [
1583
+ mountPos.x,
1584
+ mountPos.y,
1585
+ mountPos.z
1586
+ ],
1587
+ mountQuaternion: [
1588
+ mountQuat.x,
1589
+ mountQuat.y,
1590
+ mountQuat.z,
1591
+ mountQuat.w
1592
+ ],
1593
+ lumpedMass,
1594
+ colliders,
1595
+ parts
1596
+ };
1597
+ });
1598
+ for (const a of plans) for (const b of plans) if (a !== b && isSceneDescendant(b.mountNode, a.mountNode)) throw new KhrValidationError(`Root bodies "${a.spec.nodeName}" and "${b.spec.nodeName}" share scene subtree "${a.mountNode.name}"; split them into separate glTF branches`);
1599
+ return plans;
1600
+ }
1601
+ function ArticulatedPartBody({ part, rootPos, rootQuat, linearVelocity, angularVelocity, gravityScale, parentBody, userData, origin, onBody, onJointReady }) {
1602
+ const { rapier, world } = useRapier();
1603
+ const registry = useContext(JointRegistryContext);
1604
+ const rtRef = useRef(null);
1605
+ const [childBody, setChildBody] = React.useState(null);
1606
+ const worldPose = useMemo(() => {
1607
+ const rq = new THREE.Quaternion(rootQuat[0], rootQuat[1], rootQuat[2], rootQuat[3]).normalize();
1608
+ const pos = new THREE.Vector3().fromArray(part.restRelRootPos).applyQuaternion(rq).add(new THREE.Vector3(rootPos[0], rootPos[1], rootPos[2]));
1609
+ return {
1610
+ pos: [
1611
+ pos.x,
1612
+ pos.y,
1613
+ pos.z
1614
+ ],
1615
+ quat: [
1616
+ rq.x,
1617
+ rq.y,
1618
+ rq.z,
1619
+ rq.w
1620
+ ]
1621
+ };
1622
+ }, [
1623
+ part.restRelRootPos,
1624
+ rootPos,
1625
+ rootQuat
1626
+ ]);
1627
+ const assignChildRef = useCallback((rb) => {
1628
+ setChildBody(rb);
1629
+ onBody(part.spec.nodeName, rb);
1630
+ }, [part.spec.nodeName, onBody]);
1631
+ useEffect(() => () => onBody(part.spec.nodeName, null), [part.spec.nodeName, onBody]);
1632
+ useEffect(() => {
1633
+ if (childBody && part.lumpedMass && isLiveRapierBody(world, childBody)) applyRapierBodyMass(childBody, part.lumpedMass, world);
1634
+ }, [
1635
+ world,
1636
+ childBody,
1637
+ part.lumpedMass
1638
+ ]);
1639
+ useEffect(() => {
1640
+ if (!parentBody || !childBody || !isLiveRapierBody(world, parentBody) || !isLiveRapierBody(world, childBody)) return;
1641
+ const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
1642
+ 0,
1643
+ 0,
1644
+ 0
1645
+ ], part.axisParent, part.axisChild, part.restRelParentQuat);
1646
+ const rt = buildJointRuntime({
1647
+ rapier,
1648
+ world,
1649
+ nodeName: part.spec.nodeName,
1650
+ role: part.joint.role,
1651
+ kind: part.joint.kind,
1652
+ object: part.spec.object,
1653
+ axisParent: part.axisParent,
1654
+ anchorParent: part.restRelParentPos,
1655
+ limits: part.joint.limits,
1656
+ drive: part.joint.drive,
1657
+ breakaway: part.spec.breakaway,
1658
+ rapierJoint: imp,
1659
+ parentBody,
1660
+ childBody
1661
+ });
1662
+ rtRef.current = rt;
1663
+ registry?.add(rt);
1664
+ onJointReady(rt.nodeName, part.spec.object, rt);
1665
+ return () => {
1666
+ rtRef.current = null;
1667
+ registry?.delete(rt);
1668
+ onJointReady(rt.nodeName, part.spec.object, null);
1669
+ if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle) === rt.rapierJoint) world.removeImpulseJoint(rt.rapierJoint, true);
1670
+ };
1671
+ }, [
1672
+ rapier,
1673
+ world,
1674
+ part,
1675
+ parentBody,
1676
+ childBody,
1677
+ registry,
1678
+ onJointReady
1679
+ ]);
1680
+ const onForce = useMemo(() => part.spec.breakaway ? (p) => {
1681
+ if (world.timestep > 0) rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * world.timestep);
1682
+ } : void 0, [part.spec.breakaway, world]);
1683
+ const linVel = part.spec.linearVelocity ?? linearVelocity;
1684
+ const angVel = part.spec.angularVelocity ?? angularVelocity;
1685
+ const gravScale = part.spec.gravityFactor ?? gravityScale;
1686
+ return /* @__PURE__ */ jsxs(RigidBody, {
1687
+ ref: assignChildRef,
1688
+ type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
1689
+ position: worldPose.pos,
1690
+ quaternion: worldPose.quat,
1691
+ colliders: false,
1692
+ onContactForce: onForce,
1693
+ ...userData === void 0 ? {} : { userData },
1694
+ ...linVel ? { linearVelocity: linVel } : {},
1695
+ ...angVel ? { angularVelocity: angVel } : {},
1696
+ ...gravScale === void 0 ? {} : { gravityScale: gravScale },
1697
+ children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
1698
+ object: part.spec.object,
1699
+ position: [
1700
+ 0,
1701
+ 0,
1702
+ 0
1703
+ ],
1704
+ quaternion: part.restRelRootQuat,
1705
+ origin
1706
+ }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
1707
+ c: col.spec,
1708
+ position: col.position,
1709
+ quaternion: col.quaternion
1710
+ }, `${part.spec.nodeName}:${cIdx}`))]
1711
+ });
1712
+ }
1713
+ function AssemblyRootBody({ plan, bundleScene, position, quaternion, fixedRoot, rigidBodyProps, onBody, onJointReady, children }) {
1714
+ const { world } = useRapier();
1715
+ const [rootBody, setRootBody] = React.useState(null);
1716
+ const [partBodies, setPartBodies] = React.useState(() => /* @__PURE__ */ new Map());
1717
+ const partOrigins = useMemo(() => plan.parts.length > 0 ? captureSubtreeOrigins(plan.parts.map((p) => p.spec.object), bundleScene) : null, [plan.parts, bundleScene]);
1718
+ const rootSpec = plan.spec;
1719
+ const assignRootRef = useCallback((rb) => {
1720
+ setRootBody(rb);
1721
+ onBody(rootSpec.nodeName, rb);
1722
+ }, [rootSpec.nodeName, onBody]);
1723
+ useEffect(() => () => onBody(rootSpec.nodeName, null), [rootSpec.nodeName, onBody]);
1724
+ useEffect(() => {
1725
+ if (rootBody && plan.lumpedMass && isLiveRapierBody(world, rootBody)) applyRapierBodyMass(rootBody, plan.lumpedMass, world);
1726
+ }, [
1727
+ world,
1728
+ rootBody,
1729
+ plan.lumpedMass
1730
+ ]);
1731
+ const handlePartBody = useCallback((nodeName, rb) => {
1732
+ setPartBodies((prev) => {
1733
+ if ((prev.get(nodeName) ?? null) === rb) return prev;
1734
+ const next = new Map(prev);
1735
+ if (rb) next.set(nodeName, rb);
1736
+ else next.delete(nodeName);
1737
+ return next;
1738
+ });
1739
+ onBody(nodeName, rb);
1740
+ }, [onBody]);
1741
+ const bodyType = rootSpec.isKinematic ? fixedRoot ? "fixed" : "kinematicPosition" : "dynamic";
1742
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(RigidBody, {
1743
+ ...rigidBodyProps,
1744
+ ref: assignRootRef,
1745
+ type: bodyType,
1746
+ position,
1747
+ quaternion,
1748
+ colliders: false,
1749
+ ...rootSpec.linearVelocity ? { linearVelocity: rootSpec.linearVelocity } : {},
1750
+ ...rootSpec.angularVelocity ? { angularVelocity: rootSpec.angularVelocity } : {},
1751
+ ...rootSpec.gravityFactor === void 0 ? {} : { gravityScale: rootSpec.gravityFactor },
1752
+ children: [children, plan.colliders.map((col, idx) => /* @__PURE__ */ jsx(KhrCollider, {
1753
+ c: col.spec,
1754
+ position: col.position,
1755
+ quaternion: col.quaternion
1756
+ }, `r${idx}`))]
1757
+ }), plan.parts.map((part) => /* @__PURE__ */ jsx(ArticulatedPartBody, {
1758
+ part,
1759
+ rootPos: position,
1760
+ rootQuat: quaternion,
1761
+ linearVelocity: rootSpec.linearVelocity,
1762
+ angularVelocity: rootSpec.angularVelocity,
1763
+ gravityScale: rootSpec.gravityFactor,
1764
+ parentBody: part.parent ? partBodies.get(part.parent.spec.nodeName) ?? null : rootBody,
1765
+ userData: rigidBodyProps?.userData,
1766
+ origin: partOrigins?.get(part.spec.object),
1767
+ onBody: handlePartBody,
1768
+ onJointReady
1769
+ }, part.spec.nodeName))] });
1770
+ }
1771
+ function KhrAssembly({ ref, bundle, position = [
1772
+ 0,
1773
+ 0,
1774
+ 0
1775
+ ], rotation, quaternion, scale, fixedRoot = false, enableCustomGravity = false, rigidBodyProps, children, ...groupProps }) {
1776
+ assertUnitScale(scale, "KhrAssembly");
1777
+ useMemo(() => assertSceneIdentityWorldScale(bundle.scene), [bundle]);
1778
+ const { world } = useRapier();
1779
+ const applyGravityField = useCustomGravity((s) => s.applyGravityField);
1780
+ const plans = useMemo(() => planAssembly(bundle), [bundle]);
1781
+ const isStaticMultiRootCompound = useMemo(() => fixedRoot && plans.length > 1 && plans.every((p) => p.spec.isKinematic && p.parts.length === 0), [fixedRoot, plans]);
1782
+ const compoundColliders = useMemo(() => {
1783
+ if (!isStaticMultiRootCompound) return null;
1784
+ const one = new THREE.Vector3(1, 1, 1);
1785
+ const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
1786
+ const out = [];
1787
+ for (const p of plans) {
1788
+ const bMat = bodyPoseMatrix(p.spec);
1789
+ for (let idx = 0; idx < p.spec.colliders.length; idx++) {
1790
+ const c = p.spec.colliders[idx];
1791
+ const cMat = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(c.localPosition), new THREE.Quaternion().fromArray(c.localQuaternion), one);
1792
+ bMat.clone().multiply(cMat).decompose(pos, quat, scl);
1793
+ quat.normalize();
1794
+ out.push({
1795
+ key: `${p.spec.nodeName}:${idx}`,
1796
+ spec: c,
1797
+ position: [
1798
+ pos.x,
1799
+ pos.y,
1800
+ pos.z
1801
+ ],
1802
+ quaternion: [
1803
+ quat.x,
1804
+ quat.y,
1805
+ quat.z,
1806
+ quat.w
1807
+ ]
1808
+ });
1809
+ }
1810
+ }
1811
+ return out;
1812
+ }, [isStaticMultiRootCompound, plans]);
1813
+ const origins = useMemo(() => !isStaticMultiRootCompound && plans.length > 1 ? captureSubtreeOrigins(plans.map((p) => p.mountNode), bundle.scene) : null, [
1814
+ isStaticMultiRootCompound,
1815
+ plans,
1816
+ bundle.scene
1817
+ ]);
1818
+ const [px, py, pz] = position;
1819
+ const [rx, ry, rz] = rotation ?? [
1820
+ 0,
1821
+ 0,
1822
+ 0
1823
+ ];
1824
+ const hasQuat = quaternion !== void 0;
1825
+ const qx = quaternion?.[0] ?? 0;
1826
+ const qy = quaternion?.[1] ?? 0;
1827
+ const qz = quaternion?.[2] ?? 0;
1828
+ const qw = quaternion?.[3] ?? 1;
1829
+ const spawnQuat = useMemo(() => hasQuat ? new THREE.Quaternion(qx, qy, qz, qw).normalize() : new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), [
1830
+ hasQuat,
1831
+ qx,
1832
+ qy,
1833
+ qz,
1834
+ qw,
1835
+ rx,
1836
+ ry,
1837
+ rz
1838
+ ]);
1839
+ const rootPoses = useMemo(() => plans.map((p) => {
1840
+ const pos = new THREE.Vector3().fromArray(p.spec.localPosition).applyQuaternion(spawnQuat).add(new THREE.Vector3(px, py, pz));
1841
+ const quat = spawnQuat.clone().multiply(new THREE.Quaternion().fromArray(p.spec.localQuaternion));
1842
+ return {
1843
+ position: [
1844
+ pos.x,
1845
+ pos.y,
1846
+ pos.z
1847
+ ],
1848
+ quaternion: [
1849
+ quat.x,
1850
+ quat.y,
1851
+ quat.z,
1852
+ quat.w
1853
+ ]
1854
+ };
1855
+ }), [
1856
+ plans,
1857
+ spawnQuat,
1858
+ px,
1859
+ py,
1860
+ pz
1861
+ ]);
1862
+ const bodiesRef = useRef(/* @__PURE__ */ new Map());
1863
+ const jointsRef = useRef(/* @__PURE__ */ new Map());
1864
+ const byObjectRef = useRef(/* @__PURE__ */ new Map());
1865
+ const handleBody = useCallback((nodeName, rb) => {
1866
+ if (rb) bodiesRef.current.set(nodeName, rb);
1867
+ else bodiesRef.current.delete(nodeName);
1868
+ }, []);
1869
+ const handleJointReady = useCallback((nodeName, obj, rt) => {
1870
+ if (rt) {
1871
+ jointsRef.current.set(nodeName, rt);
1872
+ byObjectRef.current.set(obj, rt);
1873
+ } else {
1874
+ jointsRef.current.delete(nodeName);
1875
+ byObjectRef.current.delete(obj);
1876
+ }
1877
+ }, []);
1878
+ useFrame(() => {
1879
+ if (!enableCustomGravity || world.timestep <= 0) return;
1880
+ for (const rb of bodiesRef.current.values()) if (isLiveRapierBody(world, rb) && rb.isDynamic()) applyGravityField(rb, world.timestep);
1881
+ });
1882
+ useImperativeHandle(ref, () => ({
1883
+ get jointNames() {
1884
+ return [...jointsRef.current.keys()];
1885
+ },
1886
+ getBody: (nodeName) => bodiesRef.current.get(nodeName) ?? null,
1887
+ getJointRuntime: (nodeName) => jointsRef.current.get(nodeName) ?? null,
1888
+ setJointTarget: (nodeName, target) => {
1889
+ jointsRef.current.get(nodeName)?.applyTarget(target);
1890
+ },
1891
+ setRoleTarget: (role, target) => {
1892
+ for (const rt of jointsRef.current.values()) if (rt.role === role) rt.applyTarget(target);
1893
+ },
1894
+ toggleHitObject: (hit) => {
1895
+ for (let cur = hit; cur; cur = cur.parent) {
1896
+ const rt = byObjectRef.current.get(cur);
1897
+ if (rt && toggleDrivenJoint(rt)) return true;
1898
+ }
1899
+ return false;
1900
+ }
1901
+ }), []);
1902
+ const assignCompoundRef = useCallback((rb) => {
1903
+ for (const p of plans) if (rb) bodiesRef.current.set(p.spec.nodeName, rb);
1904
+ else bodiesRef.current.delete(p.spec.nodeName);
1905
+ }, [plans]);
1906
+ useEffect(() => {
1907
+ if (!isStaticMultiRootCompound) return;
1908
+ return () => {
1909
+ for (const p of plans) bodiesRef.current.delete(p.spec.nodeName);
1910
+ };
1911
+ }, [isStaticMultiRootCompound, plans]);
1912
+ if (isStaticMultiRootCompound && compoundColliders) return /* @__PURE__ */ jsx("group", {
1913
+ ...groupProps,
1914
+ children: /* @__PURE__ */ jsxs(RigidBody, {
1915
+ ...rigidBodyProps,
1916
+ ref: assignCompoundRef,
1917
+ type: "fixed",
1918
+ position,
1919
+ quaternion: [
1920
+ spawnQuat.x,
1921
+ spawnQuat.y,
1922
+ spawnQuat.z,
1923
+ spawnQuat.w
1924
+ ],
1925
+ colliders: false,
1926
+ children: [
1927
+ /* @__PURE__ */ jsx(BundleSceneHost, {
1928
+ bundle,
1929
+ owner: "KhrAssembly"
1930
+ }),
1931
+ children,
1932
+ compoundColliders.map((col) => /* @__PURE__ */ jsx(KhrCollider, {
1933
+ c: col.spec,
1934
+ position: col.position,
1935
+ quaternion: col.quaternion
1936
+ }, col.key))
1937
+ ]
1938
+ })
1939
+ });
1940
+ if (plans.length === 1) {
1941
+ const plan = plans[0];
1942
+ return /* @__PURE__ */ jsx("group", {
1943
+ ...groupProps,
1944
+ children: /* @__PURE__ */ jsx(AssemblyRootBody, {
1945
+ plan,
1946
+ bundleScene: bundle.scene,
1947
+ position: rootPoses[0].position,
1948
+ quaternion: rootPoses[0].quaternion,
1949
+ fixedRoot,
1950
+ rigidBodyProps,
1951
+ onBody: handleBody,
1952
+ onJointReady: handleJointReady,
1953
+ children: /* @__PURE__ */ jsxs("group", {
1954
+ position: plan.sceneInRootPos,
1955
+ quaternion: plan.sceneInRootQuat,
1956
+ children: [/* @__PURE__ */ jsx(BundleSceneHost, {
1957
+ bundle,
1958
+ owner: "KhrAssembly"
1959
+ }), children]
1960
+ })
1961
+ }, `${bundle.scene.uuid}:${plan.spec.nodeName}`)
1962
+ });
1963
+ }
1964
+ return /* @__PURE__ */ jsxs("group", {
1965
+ ...groupProps,
1966
+ children: [/* @__PURE__ */ jsxs("group", {
1967
+ position,
1968
+ quaternion: [
1969
+ spawnQuat.x,
1970
+ spawnQuat.y,
1971
+ spawnQuat.z,
1972
+ spawnQuat.w
1973
+ ],
1974
+ children: [/* @__PURE__ */ jsx(BundleSceneHost, {
1975
+ bundle,
1976
+ owner: "KhrAssembly"
1977
+ }), children]
1978
+ }), plans.map((plan, idx) => /* @__PURE__ */ jsx(AssemblyRootBody, {
1979
+ plan,
1980
+ bundleScene: bundle.scene,
1981
+ position: rootPoses[idx].position,
1982
+ quaternion: rootPoses[idx].quaternion,
1983
+ fixedRoot,
1984
+ rigidBodyProps,
1985
+ onBody: handleBody,
1986
+ onJointReady: handleJointReady,
1987
+ children: /* @__PURE__ */ jsx(MountSubtreeSlot, {
1988
+ object: plan.mountNode,
1989
+ position: plan.mountPosition,
1990
+ quaternion: plan.mountQuaternion,
1991
+ origin: origins?.get(plan.mountNode)
1992
+ })
1993
+ }, `${bundle.scene.uuid}:${plan.spec.nodeName}`))]
1994
+ });
1995
+ }
1996
+ export { computeAssemblyMassAndCom as A, resolveBodyMassFromColliders as B, restoreSubtreeOrigin as C, assertSceneIdentityWorldScale as D, assertIdentityWorldScale as E, isLiveRapierBody as F, isFiniteNum as G, JointRegistryContext as H, isLiveRapierCollider as I, isPosNum as J, isNonNegNum as K, jacobiPrincipalInertia as L, computeRelativePose as M, computeShapeInertia as N, assertUnitScale as O, extractMeshColliderShape as P, readFiniteVec3 as R, releaseBundleMount as S, applyRapierBodyMass as T, KhrValidationError as U, COMBINE_MODES as V, assignRef as W, optFiniteNum as Y, captureSubtreeOrigins as _, DETACHED_PANEL_INTERACTION_GROUPS as a, disposeKhrBundle as b, configureJointDrive as c, measureJointCoordinate as d, openTargetForLimits as f, BundleSceneHost as g, KhrCollider as h, ATTACHED_PANEL_INTERACTION_GROUPS as i, computeLumpedMassProps as j, bodyPoseMatrix as k, createRapierImpulseJoint as l, KHR_TRIMESH_FLAGS as m, KhrAssembly as n, buildJointRuntime as o, toggleDrivenJoint as p, isObj as q, planAssembly as r, closedTargetForLimits as s, ArticulatedPartBody as t, isJointOpen as u, claimBundleMount as v, snapshotSceneWithMountedSubtrees as w, registerMountedSubtree as x, cloneKhrBundle as y, readUnitQuat as z };
1338
1997
 
1339
- //# sourceMappingURL=joints-H3uae8pm.js.map
1998
+ //# sourceMappingURL=KhrAssembly-DAVP2HJe.js.map