@khr3/core 0.2.10 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +8 -0
  2. package/dist/{physicsEcs-Bi0ikONC.js → KhrAssembly-CKW8I_2z.js} +1136 -625
  3. package/dist/KhrAssembly-CKW8I_2z.js.map +1 -0
  4. package/dist/KhrAssembly.d.ts +46 -8
  5. package/dist/KhrCollider.d.ts +21 -7
  6. package/dist/clone.d.ts +40 -0
  7. package/dist/{khrExporter.d.ts → exporter.d.ts} +2 -2
  8. package/dist/{khrGlb.d.ts → glb.d.ts} +4 -3
  9. package/dist/index.d.ts +10 -9
  10. package/dist/index.js +734 -1083
  11. package/dist/index.js.map +1 -1
  12. package/dist/{khrInertia.d.ts → inertia.d.ts} +22 -8
  13. package/dist/{jointDynamics.d.ts → joints.d.ts} +8 -7
  14. package/dist/loader.d.ts +9 -0
  15. package/dist/types.d.ts +282 -0
  16. package/dist/useKhrGlb.d.ts +6 -1
  17. package/dist/vehicle.d.ts +35 -2
  18. package/dist/vehicle.js +435 -526
  19. package/dist/vehicle.js.map +1 -1
  20. package/dist/wheelLoads.d.ts +5 -4
  21. package/package.json +4 -16
  22. package/dist/AssemblyRootBody.d.ts +0 -16
  23. package/dist/BundleSceneHost.d.ts +0 -23
  24. package/dist/KhrVehicle.d.ts +0 -20
  25. package/dist/assemblyPlan.d.ts +0 -61
  26. package/dist/curves.d.ts +0 -378
  27. package/dist/curves.js +0 -542
  28. package/dist/curves.js.map +0 -1
  29. package/dist/khrBundleFinalize.d.ts +0 -15
  30. package/dist/khrClone.d.ts +0 -14
  31. package/dist/khrConfigTypes.d.ts +0 -62
  32. package/dist/khrExportEncoders.d.ts +0 -8
  33. package/dist/khrExtras.d.ts +0 -22
  34. package/dist/khrJointParser.d.ts +0 -3
  35. package/dist/khrLoader.d.ts +0 -7
  36. package/dist/khrMassProps.d.ts +0 -16
  37. package/dist/khrParsers.d.ts +0 -10
  38. package/dist/khrPlugin.d.ts +0 -8
  39. package/dist/khrPluginHelpers.d.ts +0 -26
  40. package/dist/khrRotorDecoders.d.ts +0 -4
  41. package/dist/khrShapeParser.d.ts +0 -8
  42. package/dist/khrTypes.d.ts +0 -141
  43. package/dist/khrVehicleChassis.d.ts +0 -20
  44. package/dist/khrVehicleJointHelpers.d.ts +0 -37
  45. package/dist/khrVehicleJoints.d.ts +0 -30
  46. package/dist/khrVehicleRotors.d.ts +0 -22
  47. package/dist/khrVehicleSlots.d.ts +0 -41
  48. package/dist/khrVehicleTypes.d.ts +0 -52
  49. package/dist/pacejka.d.ts +0 -22
  50. package/dist/physicsEcs-Bi0ikONC.js.map +0 -1
  51. package/dist/physicsEcs.d.ts +0 -25
package/dist/vehicle.js CHANGED
@@ -1,16 +1,106 @@
1
1
  import { useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
2
- import { RigidBody, useRapier } from "@react-three/rapier";
3
- import { EcctrlVehicle, ShapeCastWheel, ThrustPropeller } from "@pinkaphant/ecctrl/vehicle";
4
- import { D as KhrValidationError, a as MountSubtreeSlot, b as assertUnitScale, d as computeLumpedMassProps, f as KhrCollider, g as registerMountedSubtree, i as BundleSceneHost, l as toColliderMass, n as buildJointRuntime, o as captureSubtreeOrigins, r as createRapierImpulseJoint, s as restoreSubtreeOrigin, t as JointRegistryContext, u as bodyPoseMatrix, y as assertSceneIdentityWorldScale } from "./physicsEcs-Bi0ikONC.js";
5
2
  import * as THREE from "three";
6
3
  import { useFrame } from "@react-three/fiber";
4
+ import { RigidBody, useRapier } from "@react-three/rapier";
7
5
  import { useCustomGravity } from "@pinkaphant/ecctrl/gravity";
6
+ import { EcctrlVehicle, ShapeCastWheel, ThrustPropeller } from "@pinkaphant/ecctrl/vehicle";
7
+ import { C as assertSceneIdentityWorldScale, F as JointRegistryContext, I as KhrValidationError, L as assignRef, O as computeLumpedMassProps, T as bodyPoseMatrix, c as createRapierImpulseJoint, d as openTargetForLimits, f as KhrCollider, h as captureSubtreeOrigins, i as ATTACHED_PANEL_INTERACTION_GROUPS, l as isJointOpen, m as MountSubtreeSlot, o as buildJointRuntime, p as BundleSceneHost, r as toColliderMass, w as assertUnitScale, x as restoreSubtreeOrigin, y as registerMountedSubtree } from "./KhrAssembly-CKW8I_2z.js";
8
8
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
- // src/khrVehicleChassis.ts
10
- function assertVehicleProps(scale, colliders) {
11
- if (colliders !== void 0) throw new KhrValidationError("KhrVehicle: colliders prop cannot be overridden; edit colliders in the .glb asset");
12
- assertUnitScale(scale, "KhrVehicle");
9
+ // src/wheelLoads.ts
10
+ var STANDARD_GRAVITY = 9.81;
11
+ function projectToLowerBoundedSimplex(values, lowerBound, totalSum) {
12
+ const n = values.length;
13
+ const shifted = values.map((v) => v - lowerBound);
14
+ const rem = Math.max(0, totalSum - n * lowerBound);
15
+ const sorted = [...shifted].sort((a, b) => b - a);
16
+ let prefix = 0;
17
+ let k = 0;
18
+ let theta = 0;
19
+ for (let i = 0; i < n; i++) {
20
+ prefix += sorted[i];
21
+ const candidate = (prefix - rem) / (i + 1);
22
+ if (sorted[i] - candidate > 0) {
23
+ k = i + 1;
24
+ theta = candidate;
25
+ }
26
+ }
27
+ if (k === 0) theta = (prefix - rem) / n;
28
+ return shifted.map((v) => lowerBound + Math.max(v - theta, 0));
13
29
  }
30
+ function solveCornerMasses(wheels, totalMassKg, com) {
31
+ const n = wheels.length;
32
+ if (n === 0) return [];
33
+ if (n === 1) return [totalMassKg];
34
+ const mBase = totalMassKg / n;
35
+ const xs = wheels.map((w) => w.position[0] - com[0]);
36
+ const zs = wheels.map((w) => w.position[2] - com[2]);
37
+ const meanX = xs.reduce((s, v) => s + v, 0) / n;
38
+ const meanZ = zs.reduce((s, v) => s + v, 0) / n;
39
+ const cx = xs.map((v) => v - meanX);
40
+ const cz = zs.map((v) => v - meanZ);
41
+ let sxx = 0, szz = 0, sxz = 0;
42
+ for (let i = 0; i < n; i++) {
43
+ sxx += cx[i] * cx[i];
44
+ szz += cz[i] * cz[i];
45
+ sxz += cx[i] * cz[i];
46
+ }
47
+ const bx = -totalMassKg * meanX;
48
+ const bz = -totalMassKg * meanZ;
49
+ const det = sxx * szz - sxz * sxz;
50
+ const trace = sxx + szz;
51
+ let lx = 0, lz = 0;
52
+ if (det > 1e-10 * trace * trace && det > 1e-12) {
53
+ lx = (szz * bx - sxz * bz) / det;
54
+ lz = (sxx * bz - sxz * bx) / det;
55
+ } else if (trace > 1e-10) {
56
+ const angle = .5 * Math.atan2(2 * sxz, sxx - szz);
57
+ const ux = Math.cos(angle);
58
+ const uz = Math.sin(angle);
59
+ const normSq = ux * ux * sxx + 2 * ux * uz * sxz + uz * uz * szz;
60
+ if (normSq > 1e-10) {
61
+ const proj = (ux * bx + uz * bz) / normSq;
62
+ lx = proj * ux;
63
+ lz = proj * uz;
64
+ }
65
+ }
66
+ const raw = wheels.map((_, i) => mBase + lx * cx[i] + lz * cz[i]);
67
+ const mMin = Math.min(.05 * totalMassKg, totalMassKg / n);
68
+ if (raw.every((m) => m >= mMin - 1e-9)) return raw;
69
+ return projectToLowerBoundedSimplex(raw, mMin, totalMassKg);
70
+ }
71
+ /**
72
+ * Distributes `totalMassKg` across N >= 1 wheels around `com`, resolves fallback
73
+ * `springK` / `dampingC` using reference surface gravity `refGravity` (defaulting to `9.81 m/s^2`),
74
+ * and computes natural scene-space `mountPos` (`tag.position + lift`).
75
+ */
76
+ function solveWheelLoads(wheels, totalMassKg, com, dampingRatio = .7, refGravity = STANDARD_GRAVITY) {
77
+ if (wheels.length === 0) return [];
78
+ const effG = refGravity > 1e-4 ? refGravity : STANDARD_GRAVITY;
79
+ const cornerMasses = solveCornerMasses(wheels, totalMassKg, com);
80
+ return wheels.map((tag, i) => {
81
+ const cornerMassKg = cornerMasses[i];
82
+ const springK = tag.springK ?? cornerMassKg * effG / Math.max(tag.sag, 1e-4);
83
+ const dampingC = tag.dampingC ?? 2 * dampingRatio * Math.sqrt(springK * cornerMassKg);
84
+ const lift = Math.max(0, tag.travel - tag.sag);
85
+ const mountOffset = new THREE.Vector3(0, lift, 0);
86
+ if (tag.quaternion) mountOffset.applyQuaternion(new THREE.Quaternion(tag.quaternion[0], tag.quaternion[1], tag.quaternion[2], tag.quaternion[3]).normalize());
87
+ return {
88
+ tag,
89
+ cornerMassKg,
90
+ springK,
91
+ dampingC,
92
+ mountPos: [
93
+ tag.position[0] + mountOffset.x,
94
+ tag.position[1] + mountOffset.y,
95
+ tag.position[2] + mountOffset.z
96
+ ]
97
+ };
98
+ });
99
+ }
100
+ // src/vehicle.tsx
101
+ var UNSPRUNG_CORNER_RATIO = .035;
102
+ var ATTACHED_PANEL_USER_DATA = { ecctrl: { excludeVehicleRay: true } };
103
+ var _samplePos = new THREE.Vector3();
14
104
  function readPosTuple(pos) {
15
105
  if (typeof pos === "number") return [
16
106
  pos,
@@ -32,7 +122,7 @@ function readPosTuple(pos) {
32
122
  }
33
123
  return [
34
124
  0,
35
- .5,
125
+ 0,
36
126
  0
37
127
  ];
38
128
  }
@@ -82,7 +172,7 @@ function readSpawnQuat(rotation, quaternion) {
82
172
  ];
83
173
  }
84
174
  function computeChassisMassProps(bodies) {
85
- const dyn = bodies.filter((b) => !b.isKinematic).filter((b) => b.joint === null);
175
+ const dyn = bodies.filter((b) => !b.isKinematic && b.joint === null);
86
176
  if (dyn.length === 0) throw new KhrValidationError("KhrVehicle: bundle has no dynamic rigid body for the chassis");
87
177
  const lumped = computeLumpedMassProps(dyn);
88
178
  if (!lumped || !(lumped.mass > 0)) throw new KhrValidationError("KhrVehicle: chassis dynamic mass must be positive");
@@ -95,9 +185,7 @@ function computeChassisMassProps(bodies) {
95
185
  }
96
186
  let linearVelocity;
97
187
  if (dyn.some((b) => b.linearVelocity !== void 0)) {
98
- let vx = 0;
99
- let vy = 0;
100
- let vz = 0;
188
+ let vx = 0, vy = 0, vz = 0;
101
189
  for (const b of dyn) {
102
190
  const lv = b.linearVelocity ?? [
103
191
  0,
@@ -114,7 +202,7 @@ function computeChassisMassProps(bodies) {
114
202
  vz / lumped.mass
115
203
  ];
116
204
  }
117
- const rootDyn = dyn.find((b) => !b.joint && b.angularVelocity !== void 0) ?? dyn.find((b) => b.angularVelocity !== void 0);
205
+ const rootDyn = dyn.find((b) => b.angularVelocity !== void 0);
118
206
  const angularVelocity = rootDyn?.angularVelocity ? [
119
207
  rootDyn.angularVelocity[0],
120
208
  rootDyn.angularVelocity[1],
@@ -137,7 +225,7 @@ function buildChassisColliders(bodies, chassis) {
137
225
  const quat = new THREE.Quaternion();
138
226
  const scl = new THREE.Vector3();
139
227
  for (const b of bodies) {
140
- if (b.isKinematic || b.joint !== null) continue;
228
+ if (b.joint !== null || b.isKinematic && b.hasExplicitMotion) continue;
141
229
  const bodyMat = bodyPoseMatrix(b);
142
230
  for (let idx = 0; idx < b.colliders.length; idx++) {
143
231
  const c = b.colliders[idx];
@@ -181,22 +269,111 @@ function computeRotorLocalMatrix(node, scene, center, quaternion) {
181
269
  if (cur !== scene && node !== scene) throw new KhrValidationError(`Rotor node "${node.name}" is not under bundle.scene`);
182
270
  return new THREE.Matrix4().compose(new THREE.Vector3(center[0], center[1], center[2]), quaternion ? new THREE.Quaternion(quaternion[0], quaternion[1], quaternion[2], quaternion[3]).normalize() : new THREE.Quaternion(), new THREE.Vector3(1, 1, 1)).invert().multiply(nodeToScene);
183
271
  }
184
- // src/khrVehicleJointHelpers.ts
185
- /** Membership group 1 (0x0002), filter ~0x0002 (0xfffd): collides with world/actors, never with sibling attached vehicle panels. */
186
- var ATTACHED_PANEL_COLLISION_GROUPS = 196605;
187
- var DETACHED_PANEL_COLLISION_GROUPS = 0xffffffff;
272
+ function clearSingleWheelInfo(w) {
273
+ w.rayHit = null;
274
+ w.rayHitBody = null;
275
+ w.floatImp.set(0, 0, 0);
276
+ w.lngFricImp.set(0, 0, 0);
277
+ w.latFricImp.set(0, 0, 0);
278
+ w.lngSlipRatio = 0;
279
+ w.latSlipRatio = 0;
280
+ w.slipStrength = 0;
281
+ w.isOnPlatform = false;
282
+ w.effInertia = 0;
283
+ }
284
+ function resetWheelHits(handle, filter) {
285
+ if (!handle) return;
286
+ for (const wheelRef of handle.wheelsInfo.values()) {
287
+ const w = wheelRef.current;
288
+ if (w && (!filter || filter(w.name))) clearSingleWheelInfo(w);
289
+ }
290
+ }
291
+ function resetPropellerOutputs(handle) {
292
+ if (!handle) return;
293
+ for (const propRef of handle.propellersInfo.values()) {
294
+ const p = propRef.current;
295
+ if (!p) continue;
296
+ p.lx = 0;
297
+ p.ly = 0;
298
+ p.lz = 0;
299
+ p.ax = 0;
300
+ p.ay = 0;
301
+ p.az = 0;
302
+ p.thrustDir.set(0, 0, 0);
303
+ p.torqueDir.set(0, 0, 0);
304
+ p.thrustImpulse.set(0, 0, 0);
305
+ p.torqueImpulse.set(0, 0, 0);
306
+ p.finalThrottle = 0;
307
+ p.throttle = 0;
308
+ p.setThrottle?.(0);
309
+ }
310
+ }
311
+ function resetDisabledRotors(handle, opts) {
312
+ if (opts.wheelsAllOff) resetWheelHits(handle);
313
+ else if (opts.frontOff || opts.rearOff) resetWheelHits(handle, (name) => name && opts.frontWheelNames.has(name) ? opts.frontOff : opts.rearOff);
314
+ if (opts.propsOff) resetPropellerOutputs(handle);
315
+ }
316
+ function RotorVisualSlot({ object, center, quaternion, scene, origin }) {
317
+ const slotRef = useRef(null);
318
+ useLayoutEffect(() => {
319
+ const slot = slotRef.current;
320
+ if (!slot?.parent) return;
321
+ const snap = origin ?? captureSubtreeOrigins([object], scene).get(object);
322
+ scene.updateMatrixWorld(true);
323
+ const localMat = computeRotorLocalMatrix(object, scene, center, quaternion);
324
+ if (snap.origParent) snap.origParent.remove(object);
325
+ const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
326
+ localMat.decompose(pos, quat, scl);
327
+ object.position.copy(pos);
328
+ object.quaternion.copy(quat.normalize());
329
+ object.scale.copy(scl);
330
+ slot.add(object);
331
+ const untrack = registerMountedSubtree(snap.ownerScene, () => {
332
+ const p = object.position.clone(), q = object.quaternion.clone(), s = object.scale.clone();
333
+ if (object.parent === slot) slot.remove(object);
334
+ restoreSubtreeOrigin(object, snap);
335
+ return () => {
336
+ if (snap.origParent) snap.origParent.remove(object);
337
+ object.position.copy(p);
338
+ object.quaternion.copy(q);
339
+ object.scale.copy(s);
340
+ slot.add(object);
341
+ };
342
+ });
343
+ return () => {
344
+ untrack();
345
+ if (object.parent === slot) slot.remove(object);
346
+ restoreSubtreeOrigin(object, snap);
347
+ };
348
+ }, [
349
+ object,
350
+ center,
351
+ quaternion,
352
+ scene,
353
+ origin
354
+ ]);
355
+ return /* @__PURE__ */ jsx("group", { ref: slotRef });
356
+ }
188
357
  function planVehicleJointParts(bodies) {
189
358
  const dyn = bodies.filter((b) => !b.isKinematic);
190
359
  const byName = new Map(dyn.map((b) => [b.nodeName, b]));
191
360
  const jointed = dyn.filter((b) => b.joint !== null);
192
361
  if (jointed.length === 0) return [];
362
+ const depthMemo = /* @__PURE__ */ new Map();
193
363
  const depthOf = (b, seen = /* @__PURE__ */ new Set()) => {
194
- if (!b.joint) return 0;
364
+ const hit = depthMemo.get(b.nodeName);
365
+ if (hit !== void 0) return hit;
366
+ if (!b.joint) {
367
+ depthMemo.set(b.nodeName, 0);
368
+ return 0;
369
+ }
195
370
  if (seen.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
196
371
  seen.add(b.nodeName);
197
372
  const parent = byName.get(b.joint.connectedNodeName);
198
373
  if (!parent) throw new KhrValidationError(`Vehicle joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a dynamic KHR body`);
199
- return 1 + depthOf(parent, seen);
374
+ const d = 1 + depthOf(parent, seen);
375
+ depthMemo.set(b.nodeName, d);
376
+ return d;
200
377
  };
201
378
  jointed.sort((a, b) => depthOf(a) - depthOf(b));
202
379
  const one = new THREE.Vector3(1, 1, 1);
@@ -208,7 +385,6 @@ function planVehicleJointParts(bodies) {
208
385
  const parent = partByName.get(joint.connectedNodeName) ?? null;
209
386
  const bodyMat = bodyPoseMatrix(b);
210
387
  (parent ? bodyPoseMatrix(parent.spec) : new THREE.Matrix4()).clone().invert().multiply(bodyMat).decompose(rpPos, rpQuat, scl);
211
- rpQuat.normalize();
212
388
  bodyMat.decompose(rcPos, rcQuat, scl);
213
389
  rcQuat.normalize();
214
390
  const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
@@ -234,9 +410,8 @@ function planVehicleJointParts(bodies) {
234
410
  const planned = {
235
411
  spec: spec.collisionGroups === void 0 ? {
236
412
  ...spec,
237
- collisionGroups: ATTACHED_PANEL_COLLISION_GROUPS
413
+ collisionGroups: ATTACHED_PANEL_INTERACTION_GROUPS
238
414
  } : spec,
239
- local,
240
415
  position: [
241
416
  cPos.x,
242
417
  cPos.y,
@@ -291,80 +466,11 @@ function planVehicleJointParts(bodies) {
291
466
  return plan;
292
467
  });
293
468
  }
294
- function openTargetForLimits(limits) {
295
- return Math.abs(limits[0]) > Math.abs(limits[1]) ? limits[0] : limits[1];
296
- }
297
- function isVehicleJointOpen(rt) {
298
- if (!rt.limits) return false;
299
- const openTgt = openTargetForLimits(rt.limits);
300
- return Math.abs(openTgt) > 1e-6 && Math.abs((rt.positionTarget ?? rt.getCoordinate()) - openTgt) < Math.abs(openTgt) * .5;
301
- }
302
- var _pPos = new THREE.Vector3();
303
- var _pQuat = new THREE.Quaternion();
304
- var _rQuat = new THREE.Quaternion();
305
- var _cQuat = new THREE.Quaternion();
306
- var _anchor = new THREE.Vector3();
307
- function shiftAttachedPanels(parts, bodyMap, runtimeMap, dx, dy, dz) {
308
- for (const part of parts) {
309
- const rb = bodyMap.get(part.spec.nodeName);
310
- const rt = runtimeMap.get(part.spec.nodeName);
311
- if (!rb || rt?.detached) continue;
312
- const t = rb.translation();
313
- rb.setTranslation({
314
- x: t.x + dx,
315
- y: t.y + dy,
316
- z: t.z + dz
317
- }, true);
318
- }
319
- }
320
- function syncAttachedPanelsToParent(parts, bodyMap, runtimeMap, parentBody) {
321
- if (!parentBody) return;
322
- const pt = parentBody.translation(), pr = parentBody.rotation(), lv = parentBody.linvel(), av = parentBody.angvel();
323
- _pPos.set(pt.x, pt.y, pt.z);
324
- _pQuat.set(pr.x, pr.y, pr.z, pr.w);
325
- for (const part of parts) {
326
- const rb = bodyMap.get(part.spec.nodeName), rt = runtimeMap.get(part.spec.nodeName);
327
- if (!rb || rt?.detached) continue;
328
- _anchor.fromArray(part.restRelChassisPos).applyQuaternion(_pQuat).add(_pPos);
329
- _cQuat.copy(_pQuat).multiply(_rQuat.fromArray(part.restRelChassisQuat)).normalize();
330
- rb.setTranslation({
331
- x: _anchor.x,
332
- y: _anchor.y,
333
- z: _anchor.z
334
- }, true);
335
- rb.setRotation({
336
- x: _cQuat.x,
337
- y: _cQuat.y,
338
- z: _cQuat.z,
339
- w: _cQuat.w
340
- }, true);
341
- rb.setLinvel(lv, true);
342
- rb.setAngvel(av, true);
343
- }
344
- }
345
- function stepVehicleArticulatedPanels(params) {
346
- const { parts, bodyMap, runtimeMap, detachedCleared, enableCustomGravity, timestep, applyGravityField } = params;
347
- for (const part of parts) {
348
- const rb = bodyMap.get(part.spec.nodeName);
349
- if (!rb) continue;
350
- if (runtimeMap.get(part.spec.nodeName)?.detached && !detachedCleared.has(rb)) {
351
- detachedCleared.add(rb);
352
- rb.userData = {};
353
- const n = rb.numColliders();
354
- for (let i = 0; i < n; i++) if (part.spec.colliders[i]?.collisionGroups === void 0) rb.collider(i).setCollisionGroups(DETACHED_PANEL_COLLISION_GROUPS);
355
- }
356
- if (enableCustomGravity && timestep > 0 && applyGravityField && rb.isDynamic()) applyGravityField(rb, timestep);
357
- }
358
- }
359
- // src/khrVehicleJoints.tsx
360
- var ATTACHED_PANEL_USER_DATA = { ecctrl: { excludeVehicleRay: true } };
361
- function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, angularVelocity, gravityScale, parentBodyGetter, origin, onBody, onJointReady }) {
469
+ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, angularVelocity, gravityScale, parentBody, origin, onBody, onJointReady }) {
362
470
  const { rapier, world } = useRapier();
363
471
  const registry = useContext(JointRegistryContext);
364
- const childRef = useRef(null);
365
472
  const rtRef = useRef(null);
366
- const parentBodyGetterRef = useRef(parentBodyGetter);
367
- parentBodyGetterRef.current = parentBodyGetter;
473
+ const [childBody, setChildBody] = useState(null);
368
474
  const worldPose = useMemo(() => {
369
475
  const sq = new THREE.Quaternion(spawnQuat[0], spawnQuat[1], spawnQuat[2], spawnQuat[3]).normalize();
370
476
  const pos = new THREE.Vector3().fromArray(part.restRelChassisPos).applyQuaternion(sq).add(new THREE.Vector3(spawnPos[0], spawnPos[1], spawnPos[2]));
@@ -386,12 +492,19 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, an
386
492
  spawnPos,
387
493
  spawnQuat
388
494
  ]);
389
- useEffect(() => {
390
- onBody(part.spec.nodeName, childRef.current);
391
- return () => onBody(part.spec.nodeName, null);
495
+ const assignChildRef = useCallback((rb) => {
496
+ setChildBody(rb);
497
+ onBody(part.spec.nodeName, rb);
392
498
  }, [part.spec.nodeName, onBody]);
499
+ useEffect(() => () => onBody(part.spec.nodeName, null), [part.spec.nodeName, onBody]);
500
+ useEffect(() => {
501
+ const pm = part.partMass;
502
+ if (childBody && pm) {
503
+ childBody.setAdditionalMassProperties(pm.mass, pm.centerOfMass, pm.principalAngularInertia, pm.angularInertiaLocalFrame, true);
504
+ childBody.recomputeMassPropertiesFromColliders();
505
+ }
506
+ }, [childBody, part.partMass]);
393
507
  useEffect(() => {
394
- const parentBody = parentBodyGetterRef.current(), childBody = childRef.current;
395
508
  if (!parentBody || !childBody) return;
396
509
  const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
397
510
  0,
@@ -407,12 +520,6 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, an
407
520
  object: part.spec.object,
408
521
  axisParent: part.axisParent,
409
522
  anchorParent: part.restRelParentPos,
410
- restRelQuat: [
411
- 0,
412
- 0,
413
- 0,
414
- 1
415
- ],
416
523
  limits: part.joint.limits,
417
524
  drive: part.joint.drive,
418
525
  breakaway: part.spec.breakaway,
@@ -433,17 +540,19 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, an
433
540
  rapier,
434
541
  world,
435
542
  part,
543
+ parentBody,
544
+ childBody,
436
545
  registry,
437
546
  onJointReady
438
547
  ]);
439
- const onForce = part.spec.breakaway ? (p) => {
440
- rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * Math.max(world.timestep, 1 / 240));
441
- } : void 0;
548
+ const onForce = useMemo(() => part.spec.breakaway ? (p) => {
549
+ if (world.timestep > 0) rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * world.timestep);
550
+ } : void 0, [part.spec.breakaway, world]);
442
551
  const linVel = part.spec.linearVelocity ?? linearVelocity;
443
552
  const angVel = part.spec.angularVelocity ?? angularVelocity;
444
553
  const gravScale = part.spec.gravityFactor ?? gravityScale;
445
554
  return /* @__PURE__ */ jsxs(RigidBody, {
446
- ref: childRef,
555
+ ref: assignChildRef,
447
556
  type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
448
557
  position: worldPose.pos,
449
558
  quaternion: worldPose.quat,
@@ -470,30 +579,34 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, an
470
579
  }, `vj_${part.spec.nodeName}:${cIdx}`))]
471
580
  });
472
581
  }
473
- function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, enableCustomGravity = false, linearVelocity, angularVelocity, gravityScale, jointsRef }) {
582
+ var _pPos = new THREE.Vector3();
583
+ var _pQuat = new THREE.Quaternion();
584
+ var _rQuat = new THREE.Quaternion();
585
+ var _cQuat = new THREE.Quaternion();
586
+ var _anchor = new THREE.Vector3();
587
+ function KhrVehicleJoints({ bundleScene, bodies, vehicleRef, chassisBody, spawnPos, spawnQuat, enableCustomGravity = false, linearVelocity, angularVelocity, gravityScale, jointsRef }) {
474
588
  const { world } = useRapier();
475
589
  const applyGravityField = useCustomGravity((state) => state.applyGravityField);
476
590
  const parts = useMemo(() => planVehicleJointParts(bodies), [bodies]);
477
- const origins = useMemo(() => parts.length > 0 ? captureSubtreeOrigins(parts.map((p) => p.spec.object)) : null, [parts]);
591
+ const origins = useMemo(() => parts.length > 0 ? captureSubtreeOrigins(parts.map((p) => p.spec.object), bundleScene) : null, [parts, bundleScene]);
478
592
  const bodyMapRef = useRef(/* @__PURE__ */ new Map());
593
+ const [partBodies, setPartBodies] = useState(() => /* @__PURE__ */ new Map());
479
594
  const runtimeMapRef = useRef(/* @__PURE__ */ new Map());
480
595
  const byObjectRef = useRef(/* @__PURE__ */ new Map());
481
- const detachedClearedRef = useRef(/* @__PURE__ */ new WeakSet());
482
596
  useFrame(() => {
483
- if (parts.length === 0) return;
484
- stepVehicleArticulatedPanels({
485
- parts,
486
- bodyMap: bodyMapRef.current,
487
- runtimeMap: runtimeMapRef.current,
488
- detachedCleared: detachedClearedRef.current,
489
- enableCustomGravity,
490
- timestep: world.timestep,
491
- applyGravityField: enableCustomGravity ? applyGravityField : void 0
492
- });
597
+ if (!enableCustomGravity || parts.length === 0 || world.timestep <= 0) return;
598
+ for (const rb of bodyMapRef.current.values()) if (rb.isDynamic()) applyGravityField(rb, world.timestep);
493
599
  });
494
600
  const handleBody = useCallback((nodeName, rb) => {
495
601
  if (rb) bodyMapRef.current.set(nodeName, rb);
496
602
  else bodyMapRef.current.delete(nodeName);
603
+ setPartBodies((prev) => {
604
+ if ((prev.get(nodeName) ?? null) === rb) return prev;
605
+ const next = new Map(prev);
606
+ if (rb) next.set(nodeName, rb);
607
+ else next.delete(nodeName);
608
+ return next;
609
+ });
497
610
  }, []);
498
611
  const handleJointReady = useCallback((nodeName, obj, rt) => {
499
612
  if (rt) {
@@ -524,7 +637,7 @@ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, enableCusto
524
637
  for (let cur = hit; cur; cur = cur.parent) {
525
638
  const rt = byObjectRef.current.get(cur);
526
639
  if (rt && rt.limits && rt.drive?.stiffness !== void 0) {
527
- rt.applyTarget(isVehicleJointOpen(rt) ? 0 : openTargetForLimits(rt.limits));
640
+ rt.applyTarget(isJointOpen(rt) ? 0 : openTargetForLimits(rt.limits));
528
641
  return true;
529
642
  }
530
643
  }
@@ -534,11 +647,49 @@ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, enableCusto
534
647
  const low = prefix.toLowerCase();
535
648
  const matches = [...runtimeMapRef.current.values()].filter((rt) => rt.limits !== null && rt.drive?.stiffness !== void 0 && ((rt.role ?? "").toLowerCase().startsWith(low) || rt.nodeName.toLowerCase().startsWith(low)));
536
649
  if (matches.length === 0) return;
537
- const anyOpen = matches.some((rt) => isVehicleJointOpen(rt));
650
+ const anyOpen = matches.some((rt) => isJointOpen(rt));
538
651
  for (const rt of matches) rt.applyTarget(anyOpen ? 0 : openTargetForLimits(rt.limits));
539
652
  },
540
- shiftBodies: (dx, dy, dz) => shiftAttachedPanels(parts, bodyMapRef.current, runtimeMapRef.current, dx, dy, dz),
541
- syncBodiesToParent: () => syncAttachedPanelsToParent(parts, bodyMapRef.current, runtimeMapRef.current, vehicleRef.current?.body ?? null)
653
+ shiftBodies: (dx, dy, dz) => {
654
+ for (const part of parts) {
655
+ const rb = bodyMapRef.current.get(part.spec.nodeName);
656
+ const rt = runtimeMapRef.current.get(part.spec.nodeName);
657
+ if (!rb || rt?.detached) continue;
658
+ const t = rb.translation();
659
+ rb.setTranslation({
660
+ x: t.x + dx,
661
+ y: t.y + dy,
662
+ z: t.z + dz
663
+ }, true);
664
+ }
665
+ },
666
+ syncBodiesToParent: () => {
667
+ const parent = vehicleRef.current?.body;
668
+ if (!parent) return;
669
+ const pt = parent.translation(), pr = parent.rotation(), lv = parent.linvel(), av = parent.angvel();
670
+ _pPos.set(pt.x, pt.y, pt.z);
671
+ _pQuat.set(pr.x, pr.y, pr.z, pr.w);
672
+ for (const part of parts) {
673
+ const rb = bodyMapRef.current.get(part.spec.nodeName);
674
+ const rt = runtimeMapRef.current.get(part.spec.nodeName);
675
+ if (!rb || rt?.detached) continue;
676
+ _anchor.fromArray(part.restRelChassisPos).applyQuaternion(_pQuat).add(_pPos);
677
+ _cQuat.copy(_pQuat).multiply(_rQuat.fromArray(part.restRelChassisQuat)).normalize();
678
+ rb.setTranslation({
679
+ x: _anchor.x,
680
+ y: _anchor.y,
681
+ z: _anchor.z
682
+ }, true);
683
+ rb.setRotation({
684
+ x: _cQuat.x,
685
+ y: _cQuat.y,
686
+ z: _cQuat.z,
687
+ w: _cQuat.w
688
+ }, true);
689
+ rb.setLinvel(lv, true);
690
+ rb.setAngvel(av, true);
691
+ }
692
+ }
542
693
  }), [parts, vehicleRef]);
543
694
  if (parts.length === 0) return null;
544
695
  return /* @__PURE__ */ jsx(Fragment, { children: parts.map((part) => /* @__PURE__ */ jsx(VehicleArticulatedPanel, {
@@ -548,391 +699,50 @@ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, enableCusto
548
699
  linearVelocity,
549
700
  angularVelocity,
550
701
  gravityScale,
551
- parentBodyGetter: () => part.parent ? bodyMapRef.current.get(part.parent.spec.nodeName) ?? null : vehicleRef.current?.body ?? null,
702
+ parentBody: part.parent ? partBodies.get(part.parent.spec.nodeName) ?? null : chassisBody ?? vehicleRef.current?.body ?? null,
552
703
  origin: origins?.get(part.spec.object),
553
704
  onBody: handleBody,
554
705
  onJointReady: handleJointReady
555
706
  }, part.spec.nodeName)) });
556
707
  }
557
- // src/khrVehicleSlots.tsx
558
- var captureRotorOrigins = captureSubtreeOrigins;
559
- var _samplePos = new THREE.Vector3();
560
- function resetAllWheelHits(handle) {
561
- if (!handle) return;
562
- for (const wheelRef of handle.wheelsInfo.values()) {
563
- const w = wheelRef.current;
564
- if (!w) continue;
565
- w.rayHit = null;
566
- w.rayHitBody = null;
567
- w.floatImp.set(0, 0, 0);
568
- w.lngFricImp.set(0, 0, 0);
569
- w.latFricImp.set(0, 0, 0);
570
- w.lngSlipRatio = 0;
571
- w.latSlipRatio = 0;
572
- w.slipStrength = 0;
573
- w.isOnPlatform = false;
574
- w.effInertia = 0;
575
- }
576
- }
577
- function resetDisabledWheelHits(handle, isDisabled) {
578
- if (!handle) return;
579
- for (const wheelRef of handle.wheelsInfo.values()) {
580
- const w = wheelRef.current;
581
- if (!w || !isDisabled(w.name)) continue;
582
- w.rayHit = null;
583
- w.rayHitBody = null;
584
- w.floatImp.set(0, 0, 0);
585
- w.lngFricImp.set(0, 0, 0);
586
- w.latFricImp.set(0, 0, 0);
587
- w.lngSlipRatio = 0;
588
- w.latSlipRatio = 0;
589
- w.slipStrength = 0;
590
- w.isOnPlatform = false;
591
- w.effInertia = 0;
592
- }
593
- }
594
- function resetAllPropellerOutputs(handle) {
595
- if (!handle) return;
596
- for (const propRef of handle.propellersInfo.values()) {
597
- const p = propRef.current;
598
- if (!p) continue;
599
- p.lx = 0;
600
- p.ly = 0;
601
- p.lz = 0;
602
- p.ax = 0;
603
- p.ay = 0;
604
- p.az = 0;
605
- p.thrustDir.set(0, 0, 0);
606
- p.torqueDir.set(0, 0, 0);
607
- p.thrustImpulse.set(0, 0, 0);
608
- p.torqueImpulse.set(0, 0, 0);
609
- p.finalThrottle = 0;
610
- p.throttle = 0;
611
- p.setThrottle?.(0);
612
- }
613
- }
614
- function resetDisabledRotors(handle, opts) {
615
- if (opts.wheelsAllOff) resetAllWheelHits(handle);
616
- else if (opts.frontOff || opts.rearOff) resetDisabledWheelHits(handle, (name) => name && opts.frontWheelNames.has(name) ? opts.frontOff : opts.rearOff);
617
- if (opts.propsOff) resetAllPropellerOutputs(handle);
618
- }
619
- /**
620
- * Enables `<ShapeCastWheel>` exclusively under positive gravity (`gravityMag > 1e-6`), keeping
621
- * `ShapeCastWheel` internal `smoothedLngImpulse` state finite during 0G flight.
622
- */
623
- function ZeroGWheelGate({ vehicleRef, enable, enableCustomGravity, spawnPos, zeroGRef, onZeroGChange }) {
624
- const { world } = useRapier();
625
- useFrame(() => {
626
- if (!enable) return;
627
- const handle = vehicleRef.current;
628
- let gSq;
629
- if (enableCustomGravity) {
630
- if (handle?.body && !handle.body.isSleeping()) gSq = handle.gravityMag * handle.gravityMag;
631
- else {
632
- const t = handle?.body?.translation();
633
- if (t) _samplePos.set(t.x, t.y, t.z);
634
- else _samplePos.set(spawnPos[0], spawnPos[1], spawnPos[2]);
635
- gSq = useCustomGravity.getState().gravityField(_samplePos).lengthSq();
636
- }
637
- } else {
638
- const g = world.gravity;
639
- gSq = g.x * g.x + g.y * g.y + g.z * g.z;
640
- }
641
- const isZeroG = gSq <= 1e-12;
642
- if (isZeroG !== zeroGRef.current) {
643
- zeroGRef.current = isZeroG;
644
- onZeroGChange(isZeroG);
645
- }
646
- if (isZeroG) resetAllWheelHits(handle);
647
- });
648
- return null;
649
- }
650
- function ZeroGWheelPostClear({ vehicleRef, zeroGRef, disabledRotorsRef }) {
651
- useFrame(() => {
652
- if (zeroGRef.current) {
653
- resetAllWheelHits(vehicleRef.current);
654
- return;
655
- }
656
- const flags = disabledRotorsRef?.current;
657
- if (flags && (flags.wheelsAllOff || flags.frontOff || flags.rearOff || flags.propsOff)) resetDisabledRotors(vehicleRef.current, flags);
658
- });
659
- return null;
660
- }
661
- function RotorVisualSlot({ object, center, quaternion, scene, origin }) {
662
- const slotRef = useRef(null);
663
- useLayoutEffect(() => {
664
- const slot = slotRef.current;
665
- const parent = slot?.parent ?? null;
666
- if (!slot || !parent) return;
667
- const snap = origin ?? captureSubtreeOrigins([object]).get(object);
668
- scene.updateMatrixWorld(true);
669
- const localMat = computeRotorLocalMatrix(object, scene, center, quaternion);
670
- if (snap.origParent) snap.origParent.remove(object);
671
- const pos = new THREE.Vector3();
672
- const quat = new THREE.Quaternion();
673
- const scl = new THREE.Vector3();
674
- localMat.decompose(pos, quat, scl);
675
- object.position.copy(pos);
676
- object.quaternion.copy(quat.normalize());
677
- object.scale.copy(scl);
678
- slot.add(object);
679
- const untrack = registerMountedSubtree(() => {
680
- const p = object.position.clone(), q = object.quaternion.clone(), s = object.scale.clone();
681
- if (object.parent === slot) slot.remove(object);
682
- restoreSubtreeOrigin(object, snap);
683
- return () => {
684
- if (snap.origParent) snap.origParent.remove(object);
685
- object.position.copy(p);
686
- object.quaternion.copy(q);
687
- object.scale.copy(s);
688
- slot.add(object);
689
- };
690
- });
691
- return () => {
692
- untrack();
693
- if (object.parent === slot) slot.remove(object);
694
- restoreSubtreeOrigin(object, snap);
695
- };
696
- }, [
697
- object,
698
- center,
699
- quaternion,
700
- scene,
701
- origin
702
- ]);
703
- return /* @__PURE__ */ jsx("group", { ref: slotRef });
704
- }
705
- // src/khrVehicleRotors.tsx
706
- var G_SI$1 = 9.81;
707
- var UNSPRUNG_CORNER_RATIO = .035;
708
- function KhrVehicleRotors({ solvedWheels, propellers, scene, comZ, rotorOrigins, enable, wheelEnable, wheelEpoch = 0, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig }) {
709
- return /* @__PURE__ */ jsxs(Fragment, { children: [solvedWheels.map(({ tag, cornerMassKg, springK, dampingC, mountPos }) => {
710
- const axleCfg = mountPos[2] >= comZ ? frontWheelConfig : rearWheelConfig;
711
- const wheelVol = Math.max(Math.PI * tag.radius * tag.radius * tag.width, 1e-6);
712
- const wheelModelDensity = tag.wheelDensity ?? UNSPRUNG_CORNER_RATIO * cornerMassKg / wheelVol;
713
- const tagWheelProps = {
714
- rayLength: tag.travel,
715
- rayShapeR: tag.radius,
716
- rayShapeH: tag.width * .5,
717
- wheelModelRadius: tag.radius,
718
- wheelModelDensity,
719
- springK,
720
- dampingC,
721
- steerWheel: tag.steer,
722
- driveWheel: tag.drive,
723
- brakeWheel: tag.brake,
724
- maxBrakeTorque: tag.maxBrakeTorque ?? cornerMassKg * G_SI$1 * tag.radius,
725
- ...tag.steerInvert !== void 0 ? { steerInvert: tag.steerInvert } : {},
726
- ...tag.driveInvert !== void 0 ? { driveInvert: tag.driveInvert } : {},
727
- ...tag.driveTorqueWeight !== void 0 ? { driveTorqueWeight: tag.driveTorqueWeight } : {},
728
- ...tag.rollingResistanceCoef !== void 0 ? { rollingResistanceCoef: tag.rollingResistanceCoef } : {},
729
- ...tag.tireGripFactor !== void 0 ? { tireGripFactor: tag.tireGripFactor } : {},
730
- ...tag.latFrictionEllipseScale !== void 0 ? { latFrictionEllipseScale: tag.latFrictionEllipseScale } : {},
731
- ...tag.relaxLngRate !== void 0 ? { relaxLngRate: tag.relaxLngRate } : {},
732
- ...tag.relaxLatRate !== void 0 ? { relaxLatRate: tag.relaxLatRate } : {},
733
- ...tag.lngSlipRatioCurveData !== void 0 ? { lngSlipRatioCurveData: tag.lngSlipRatioCurveData } : {},
734
- ...tag.latSlipRatioCurveData !== void 0 ? { latSlipRatioCurveData: tag.latSlipRatioCurveData } : {}
735
- };
736
- return /* @__PURE__ */ jsx(ShapeCastWheel, {
737
- name: tag.nodeName,
738
- position: mountPos,
739
- quaternion: tag.quaternion ?? [
740
- 0,
741
- 0,
742
- 0,
743
- 1
744
- ],
745
- ...tagWheelProps,
746
- ...wheelConfig,
747
- ...axleCfg,
748
- enable: wheelEnable && (axleCfg?.enable ?? wheelConfig?.enable ?? true),
749
- children: /* @__PURE__ */ jsx(RotorVisualSlot, {
750
- object: tag.object,
751
- center: tag.position,
752
- quaternion: tag.quaternion,
753
- scene,
754
- origin: rotorOrigins.get(tag.object)
755
- })
756
- }, `${tag.nodeName}:${wheelEpoch}`);
757
- }), propellers.map((tag) => {
758
- const propEnabled = enable && (propellerConfig?.enable ?? true);
759
- const visual = /* @__PURE__ */ jsx(RotorVisualSlot, {
760
- object: tag.object,
761
- center: tag.position,
762
- quaternion: tag.quaternion,
763
- scene,
764
- origin: rotorOrigins.get(tag.object)
765
- });
766
- if (!propEnabled) return /* @__PURE__ */ jsx("group", {
767
- name: tag.nodeName,
768
- position: [
769
- tag.position[0],
770
- tag.position[1],
771
- tag.position[2]
772
- ],
773
- quaternion: tag.quaternion ?? [
774
- 0,
775
- 0,
776
- 0,
777
- 1
778
- ],
779
- children: visual
780
- }, `${tag.nodeName}:off`);
781
- return /* @__PURE__ */ jsx(ThrustPropeller, {
782
- name: tag.nodeName,
783
- position: [
784
- tag.position[0],
785
- tag.position[1],
786
- tag.position[2]
787
- ],
788
- quaternion: tag.quaternion ?? [
789
- 0,
790
- 0,
791
- 0,
792
- 1
793
- ],
794
- debug: false,
795
- maxThrust: tag.maxThrust,
796
- ...tag.torqueRatio !== void 0 ? { torqueRatio: tag.torqueRatio } : {},
797
- ...tag.invertThrust !== void 0 ? { invertThrust: tag.invertThrust } : {},
798
- ...tag.invertTorque !== void 0 ? { invertTorque: tag.invertTorque } : {},
799
- ...propellerConfig,
800
- enable: true,
801
- children: visual
802
- }, tag.nodeName);
803
- })] });
804
- }
805
- // src/wheelLoads.ts
806
- var G_SI = 9.81;
807
- function projectToLowerBoundedSimplex(values, lowerBound, totalSum) {
808
- const n = values.length;
809
- const shifted = values.map((v) => v - lowerBound);
810
- const rem = Math.max(0, totalSum - n * lowerBound);
811
- const sorted = [...shifted].sort((a, b) => b - a);
812
- let prefix = 0;
813
- let k = 0;
814
- let theta = 0;
815
- for (let i = 0; i < n; i++) {
816
- prefix += sorted[i];
817
- const candidate = (prefix - rem) / (i + 1);
818
- if (sorted[i] - candidate > 0) {
819
- k = i + 1;
820
- theta = candidate;
821
- }
822
- }
823
- if (k === 0) theta = (prefix - rem) / n;
824
- return shifted.map((v) => lowerBound + Math.max(v - theta, 0));
825
- }
826
- function solveCornerMasses(wheels, totalMassKg, com) {
827
- const n = wheels.length;
828
- if (n === 0) return [];
829
- if (n === 1) return [totalMassKg];
830
- const mBase = totalMassKg / n;
831
- const xs = wheels.map((w) => w.position[0] - com[0]);
832
- const zs = wheels.map((w) => w.position[2] - com[2]);
833
- const meanX = xs.reduce((s, v) => s + v, 0) / n;
834
- const meanZ = zs.reduce((s, v) => s + v, 0) / n;
835
- const cx = xs.map((v) => v - meanX);
836
- const cz = zs.map((v) => v - meanZ);
837
- let sxx = 0;
838
- let szz = 0;
839
- let sxz = 0;
840
- for (let i = 0; i < n; i++) {
841
- sxx += cx[i] * cx[i];
842
- szz += cz[i] * cz[i];
843
- sxz += cx[i] * cz[i];
844
- }
845
- const bx = -totalMassKg * meanX;
846
- const bz = -totalMassKg * meanZ;
847
- const det = sxx * szz - sxz * sxz;
848
- const trace = sxx + szz;
849
- let lx = 0;
850
- let lz = 0;
851
- if (det > 1e-10 * trace * trace && det > 1e-12) {
852
- lx = (szz * bx - sxz * bz) / det;
853
- lz = (sxx * bz - sxz * bx) / det;
854
- } else if (trace > 1e-10) {
855
- const angle = .5 * Math.atan2(2 * sxz, sxx - szz);
856
- const ux = Math.cos(angle);
857
- const uz = Math.sin(angle);
858
- const normSq = ux * ux * sxx + 2 * ux * uz * sxz + uz * uz * szz;
859
- if (normSq > 1e-10) {
860
- const proj = (ux * bx + uz * bz) / normSq;
861
- lx = proj * ux;
862
- lz = proj * uz;
863
- }
864
- }
865
- const raw = wheels.map((_, i) => mBase + lx * cx[i] + lz * cz[i]);
866
- const mMin = Math.min(.05 * totalMassKg, totalMassKg / n);
867
- if (raw.every((m) => m >= mMin - 1e-9)) return raw;
868
- return projectToLowerBoundedSimplex(raw, mMin, totalMassKg);
869
- }
870
- /**
871
- * Distributes `totalMassKg` across N >= 1 wheels around `com`, resolves fallback
872
- * `springK` / `dampingC` when omitted on the `.glb` wheel descriptor, and returns
873
- * natural scene-space `mountPos` (`tag.position + lift`).
874
- */
875
- function solveWheelLoads(wheels, totalMassKg, com, dampingRatio = .7) {
876
- if (wheels.length === 0) return [];
877
- const cornerMasses = solveCornerMasses(wheels, totalMassKg, com);
878
- return wheels.map((tag, i) => {
879
- const cornerMassKg = cornerMasses[i];
880
- const springK = tag.springK ?? cornerMassKg * G_SI / Math.max(tag.sag, 1e-4);
881
- const dampingC = tag.dampingC ?? 2 * dampingRatio * Math.sqrt(springK * cornerMassKg);
882
- const lift = Math.max(0, tag.travel - tag.sag);
883
- const mountOffset = new THREE.Vector3(0, lift, 0);
884
- if (tag.quaternion) mountOffset.applyQuaternion(new THREE.Quaternion(tag.quaternion[0], tag.quaternion[1], tag.quaternion[2], tag.quaternion[3]).normalize());
885
- return {
886
- tag,
887
- cornerMassKg,
888
- springK,
889
- dampingC,
890
- mountPos: [
891
- tag.position[0] + mountOffset.x,
892
- tag.position[1] + mountOffset.y,
893
- tag.position[2] + mountOffset.z
894
- ]
895
- };
896
- });
897
- }
898
- // src/KhrVehicle.tsx
899
- var patchedHandles = /* @__PURE__ */ new WeakSet();
900
708
  function hasActiveMovement(m) {
901
709
  return Boolean(m.forward || m.backward || m.steerLeft || m.steerRight || m.brake || m.throttleUp || m.throttleDown || m.yawLeft || m.yawRight || m.pitchForward || m.pitchBackward || m.rollLeft || m.rollRight || m.joystickL && (Math.abs(m.joystickL.x) > 1e-4 || Math.abs(m.joystickL.y) > 1e-4) || m.joystickR && (Math.abs(m.joystickR.x) > 1e-4 || Math.abs(m.joystickR.y) > 1e-4));
902
710
  }
711
+ var patchedHandles = /* @__PURE__ */ new WeakSet();
903
712
  function KhrVehicle({ scale, colliders, bundle, ...rest }) {
904
- assertVehicleProps(scale, colliders);
905
- bundle.scene.updateMatrixWorld(true);
906
- assertSceneIdentityWorldScale(bundle.scene);
713
+ if (colliders !== void 0) throw new KhrValidationError("KhrVehicle: colliders prop cannot be overridden; edit colliders in the .glb asset");
714
+ assertUnitScale(scale, "KhrVehicle");
715
+ useMemo(() => assertSceneIdentityWorldScale(bundle.scene), [bundle]);
907
716
  const { ref, vehicleRef, jointsRef, position, rotation, quaternion, enable = true, enableCustomGravity = false, carConfig, droneConfig, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig, linearVelocity, angularVelocity, gravityScale, children, ...ecctrlRest } = rest;
908
717
  const { world } = useRapier();
909
- const [isZeroG, setIsZeroG] = useState(() => {
910
- if (enableCustomGravity) return true;
911
- const g = world.gravity;
912
- return g.x * g.x + g.y * g.y + g.z * g.z <= 1e-12;
913
- });
914
- const [wheelEpoch, setWheelEpoch] = useState(0);
718
+ const worldGravMag = Math.hypot(world.gravity.x, world.gravity.y, world.gravity.z);
719
+ const refGrav = worldGravMag > 1e-4 ? worldGravMag : STANDARD_GRAVITY;
720
+ const [isZeroG, setIsZeroG] = useState(() => enableCustomGravity ? true : worldGravMag <= 1e-6);
915
721
  const zeroGRef = useRef(isZeroG);
916
- const poisonedRef = useRef(false);
917
- const handleZeroGChange = useCallback((nextZeroG) => {
918
- if (nextZeroG) {
919
- poisonedRef.current = true;
920
- resetAllWheelHits(innerRef.current);
921
- } else if (poisonedRef.current) {
922
- poisonedRef.current = false;
923
- setWheelEpoch((e) => e + 1);
924
- }
925
- setIsZeroG(nextZeroG);
926
- }, []);
722
+ const [chassisBody, setChassisBody] = useState(null);
927
723
  const chassis = useMemo(() => computeChassisMassProps(bundle.bodies), [bundle]);
928
724
  const collidersList = useMemo(() => buildChassisColliders(bundle.bodies, chassis), [bundle.bodies, chassis]);
929
- const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, bundle.totalDynamicMass, bundle.centerOfMass, .7), [
725
+ const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, bundle.totalDynamicMass, bundle.centerOfMass, .7, refGrav), [
930
726
  bundle.wheels,
931
727
  bundle.totalDynamicMass,
932
- bundle.centerOfMass
728
+ bundle.centerOfMass,
729
+ refGrav
730
+ ]);
731
+ const rotorOrigins = useMemo(() => captureSubtreeOrigins([...bundle.wheels.map((w) => w.object), ...bundle.propellers.map((p) => p.object)], bundle.scene), [
732
+ bundle.wheels,
733
+ bundle.propellers,
734
+ bundle.scene
735
+ ]);
736
+ const forwardSign = useMemo(() => {
737
+ const steered = solvedWheels.filter((w) => w.tag.steer && !w.tag.steerInvert);
738
+ if (steered.length === 0) return 1;
739
+ return steered.reduce((s, w) => s + w.mountPos[2], 0) / steered.length < chassis.com[2] - .001 ? -1 : 1;
740
+ }, [solvedWheels, chassis.com]);
741
+ const frontWheelNames = useMemo(() => new Set(solvedWheels.filter((w) => (w.mountPos[2] - chassis.com[2]) * forwardSign >= 0).map((w) => w.tag.nodeName)), [
742
+ solvedWheels,
743
+ chassis.com,
744
+ forwardSign
933
745
  ]);
934
- const rotorOrigins = useMemo(() => captureRotorOrigins([...bundle.wheels.map((w) => w.object), ...bundle.propellers.map((p) => p.object)]), [bundle.wheels, bundle.propellers]);
935
- const frontWheelNames = useMemo(() => new Set(solvedWheels.filter((w) => w.mountPos[2] >= chassis.com[2]).map((w) => w.tag.nodeName)), [solvedWheels, chassis.com]);
936
746
  const wheelsAllOff = !enable || isZeroG || wheelConfig?.enable === false && frontWheelConfig?.enable !== true && rearWheelConfig?.enable !== true;
937
747
  const frontOff = frontWheelConfig?.enable === false || frontWheelConfig?.enable === void 0 && wheelConfig?.enable === false;
938
748
  const rearOff = rearWheelConfig?.enable === false || rearWheelConfig?.enable === void 0 && wheelConfig?.enable === false;
@@ -951,6 +761,7 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
951
761
  propsOff,
952
762
  frontWheelNames
953
763
  };
764
+ const innerRef = useRef(null);
954
765
  useLayoutEffect(() => {
955
766
  resetDisabledRotors(innerRef.current, disabledRotorsRef.current);
956
767
  }, [
@@ -960,6 +771,34 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
960
771
  propsOff,
961
772
  frontWheelNames
962
773
  ]);
774
+ useFrame(() => {
775
+ const handle = innerRef.current;
776
+ if (handle?.body && handle.body !== chassisBody) setChassisBody(handle.body);
777
+ if (!enable) return;
778
+ let gSq;
779
+ if (enableCustomGravity) {
780
+ if (handle?.body && !handle.body.isSleeping()) gSq = handle.gravityMag * handle.gravityMag;
781
+ else {
782
+ const t = handle?.body?.translation();
783
+ if (t) _samplePos.set(t.x, t.y, t.z);
784
+ else _samplePos.set(bodyPos[0], bodyPos[1], bodyPos[2]);
785
+ gSq = useCustomGravity.getState().gravityField(_samplePos).lengthSq();
786
+ }
787
+ } else {
788
+ const g = world.gravity;
789
+ gSq = g.x * g.x + g.y * g.y + g.z * g.z;
790
+ }
791
+ const nextZeroG = gSq <= 1e-12;
792
+ if (nextZeroG !== zeroGRef.current) {
793
+ zeroGRef.current = nextZeroG;
794
+ setIsZeroG(nextZeroG);
795
+ }
796
+ if (nextZeroG) resetWheelHits(handle);
797
+ else {
798
+ const flags = disabledRotorsRef.current;
799
+ if (flags.wheelsAllOff || flags.frontOff || flags.rearOff || flags.propsOff) resetDisabledRotors(handle, flags);
800
+ }
801
+ });
963
802
  const [px, py, pz] = readPosTuple(position);
964
803
  const [qx, qy, qz, qw] = readSpawnQuat(rotation, quaternion);
965
804
  const bodyPos = useMemo(() => [
@@ -982,8 +821,7 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
982
821
  qz,
983
822
  qw
984
823
  ]);
985
- const innerRef = useRef(null);
986
- const assignRef = useCallback((handle) => {
824
+ const assignVehicleRef = useCallback((handle) => {
987
825
  if (handle && !patchedHandles.has(handle)) {
988
826
  patchedHandles.add(handle);
989
827
  const origSetMovement = handle.setMovement;
@@ -993,10 +831,9 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
993
831
  };
994
832
  }
995
833
  innerRef.current = handle;
996
- if (typeof vehicleRef === "function") vehicleRef(handle);
997
- else if (vehicleRef && typeof vehicleRef === "object") vehicleRef.current = handle;
998
- if (typeof ref === "function") ref(handle);
999
- else if (ref && typeof ref === "object") ref.current = handle;
834
+ setChassisBody(handle?.body ?? null);
835
+ assignRef(vehicleRef, handle);
836
+ assignRef(ref, handle);
1000
837
  }, [ref, vehicleRef]);
1001
838
  const omiSteerAngle = useMemo(() => bundle.wheels.find((w) => w.steer && w.maxSteeringAngle !== void 0 && w.maxSteeringAngle > 0)?.maxSteeringAngle, [bundle.wheels]);
1002
839
  const mergedCarConfig = useMemo(() => bundle.tune || carConfig || omiSteerAngle !== void 0 ? {
@@ -1015,8 +852,9 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
1015
852
  const effLinVel = linearVelocity ?? chassis.linearVelocity;
1016
853
  const effAngVel = angularVelocity ?? chassis.angularVelocity;
1017
854
  const effGravScale = gravityScale ?? chassis.gravityFactor;
855
+ const wheelEnable = enable && !isZeroG;
1018
856
  return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(EcctrlVehicle, {
1019
- ref: assignRef,
857
+ ref: assignVehicleRef,
1020
858
  enable,
1021
859
  enableCustomGravity,
1022
860
  position: bodyPos,
@@ -1037,37 +875,108 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
1037
875
  c: spec,
1038
876
  massProperties
1039
877
  }, key)),
1040
- /* @__PURE__ */ jsx(ZeroGWheelGate, {
1041
- vehicleRef: innerRef,
1042
- enable,
1043
- enableCustomGravity,
1044
- spawnPos: bodyPos,
1045
- zeroGRef,
1046
- onZeroGChange: handleZeroGChange
1047
- }),
1048
- /* @__PURE__ */ jsx(KhrVehicleRotors, {
1049
- solvedWheels,
1050
- propellers: bundle.propellers,
1051
- scene: bundle.scene,
1052
- comZ: chassis.com[2],
1053
- rotorOrigins,
1054
- enable,
1055
- wheelEnable: enable && !isZeroG,
1056
- wheelEpoch,
1057
- wheelConfig,
1058
- frontWheelConfig,
1059
- rearWheelConfig,
1060
- propellerConfig
878
+ solvedWheels.map(({ tag, cornerMassKg, springK, dampingC, mountPos }) => {
879
+ const axleCfg = frontWheelNames.has(tag.nodeName) ? frontWheelConfig : rearWheelConfig;
880
+ const wheelVol = Math.max(Math.PI * tag.radius * tag.radius * tag.width, 1e-6);
881
+ const wheelModelDensity = tag.wheelDensity ?? UNSPRUNG_CORNER_RATIO * cornerMassKg / wheelVol;
882
+ const tagWheelProps = {
883
+ rayLength: tag.travel,
884
+ rayShapeR: tag.radius,
885
+ rayShapeH: tag.width * .5,
886
+ wheelModelRadius: tag.radius,
887
+ wheelModelDensity,
888
+ springK,
889
+ dampingC,
890
+ steerWheel: tag.steer,
891
+ driveWheel: tag.drive,
892
+ brakeWheel: tag.brake,
893
+ maxBrakeTorque: tag.maxBrakeTorque ?? cornerMassKg * refGrav * tag.radius,
894
+ ...tag.steerInvert !== void 0 ? { steerInvert: tag.steerInvert } : {},
895
+ ...tag.driveInvert !== void 0 ? { driveInvert: tag.driveInvert } : {},
896
+ ...tag.driveTorqueWeight !== void 0 ? { driveTorqueWeight: tag.driveTorqueWeight } : {},
897
+ ...tag.rollingResistanceCoef !== void 0 ? { rollingResistanceCoef: tag.rollingResistanceCoef } : {},
898
+ ...tag.tireGripFactor !== void 0 ? { tireGripFactor: tag.tireGripFactor } : {},
899
+ ...tag.latFrictionEllipseScale !== void 0 ? { latFrictionEllipseScale: tag.latFrictionEllipseScale } : {},
900
+ ...tag.relaxLngRate !== void 0 ? { relaxLngRate: tag.relaxLngRate } : {},
901
+ ...tag.relaxLatRate !== void 0 ? { relaxLatRate: tag.relaxLatRate } : {},
902
+ ...tag.lngSlipRatioCurveData !== void 0 ? { lngSlipRatioCurveData: tag.lngSlipRatioCurveData } : {},
903
+ ...tag.latSlipRatioCurveData !== void 0 ? { latSlipRatioCurveData: tag.latSlipRatioCurveData } : {}
904
+ };
905
+ return /* @__PURE__ */ jsx(ShapeCastWheel, {
906
+ name: tag.nodeName,
907
+ position: mountPos,
908
+ quaternion: tag.quaternion ?? [
909
+ 0,
910
+ 0,
911
+ 0,
912
+ 1
913
+ ],
914
+ ...tagWheelProps,
915
+ ...wheelConfig,
916
+ ...axleCfg,
917
+ enable: wheelEnable && (axleCfg?.enable ?? wheelConfig?.enable ?? true),
918
+ children: /* @__PURE__ */ jsx(RotorVisualSlot, {
919
+ object: tag.object,
920
+ center: tag.position,
921
+ quaternion: tag.quaternion,
922
+ scene: bundle.scene,
923
+ origin: rotorOrigins.get(tag.object)
924
+ })
925
+ }, tag.nodeName);
1061
926
  }),
1062
- /* @__PURE__ */ jsx(ZeroGWheelPostClear, {
1063
- vehicleRef: innerRef,
1064
- zeroGRef,
1065
- disabledRotorsRef
1066
- }, `post:${wheelEpoch}`)
927
+ bundle.propellers.map((tag) => {
928
+ const propEnabled = enable && (propellerConfig?.enable ?? true);
929
+ const visual = /* @__PURE__ */ jsx(RotorVisualSlot, {
930
+ object: tag.object,
931
+ center: tag.position,
932
+ quaternion: tag.quaternion,
933
+ scene: bundle.scene,
934
+ origin: rotorOrigins.get(tag.object)
935
+ });
936
+ if (!propEnabled) return /* @__PURE__ */ jsx("group", {
937
+ name: tag.nodeName,
938
+ position: [
939
+ tag.position[0],
940
+ tag.position[1],
941
+ tag.position[2]
942
+ ],
943
+ quaternion: tag.quaternion ?? [
944
+ 0,
945
+ 0,
946
+ 0,
947
+ 1
948
+ ],
949
+ children: visual
950
+ }, `${tag.nodeName}:off`);
951
+ return /* @__PURE__ */ jsx(ThrustPropeller, {
952
+ name: tag.nodeName,
953
+ position: [
954
+ tag.position[0],
955
+ tag.position[1],
956
+ tag.position[2]
957
+ ],
958
+ quaternion: tag.quaternion ?? [
959
+ 0,
960
+ 0,
961
+ 0,
962
+ 1
963
+ ],
964
+ debug: false,
965
+ maxThrust: tag.maxThrust,
966
+ ...tag.torqueRatio !== void 0 ? { torqueRatio: tag.torqueRatio } : {},
967
+ ...tag.invertThrust !== void 0 ? { invertThrust: tag.invertThrust } : {},
968
+ ...tag.invertTorque !== void 0 ? { invertTorque: tag.invertTorque } : {},
969
+ ...propellerConfig,
970
+ enable: true,
971
+ children: visual
972
+ }, tag.nodeName);
973
+ })
1067
974
  ]
1068
975
  }), /* @__PURE__ */ jsx(KhrVehicleJoints, {
976
+ bundleScene: bundle.scene,
1069
977
  bodies: bundle.bodies,
1070
978
  vehicleRef: innerRef,
979
+ chassisBody,
1071
980
  spawnPos: bodyPos,
1072
981
  spawnQuat: bodyQuat,
1073
982
  enableCustomGravity,