@khr3/core 0.2.2 → 0.2.5

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.
package/dist/vehicle.js CHANGED
@@ -1,4 +1,4 @@
1
- import { E as KhrValidationError, a as MountSubtreeSlot, d as computeLumpedMassProps, f as KhrCollider, i as BundleSceneHost, l as toColliderMass, n as buildJointRuntime, o as captureSubtreeOrigins, r as createRapierImpulseJoint, s as restoreSubtreeOrigin, t as JointRegistryContext, u as bodyPoseMatrix, v as assertSceneIdentityWorldScale, y as assertUnitScale } from "./physicsEcs-B9XGoZtl.js";
1
+ 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-dBq4psbC.js";
2
2
  import { useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
3
3
  import { useFrame } from "@react-three/fiber";
4
4
  import { RigidBody, useRapier } from "@react-three/rapier";
@@ -212,43 +212,53 @@ function planVehicleJointParts(bodies) {
212
212
  bodyMat.decompose(rcPos, rcQuat, scl);
213
213
  rcQuat.normalize();
214
214
  const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
215
- const axParentVec = axChildVec.clone().applyQuaternion(rpQuat).normalize();
216
- const ownLumped = computeLumpedMassProps([b], bodyMat.clone().invert());
215
+ const axParentVec = axChildVec.clone().applyQuaternion(rcQuat).normalize();
216
+ const anchorParent = parent ? [
217
+ rcPos.x - parent.restRelChassisPos[0],
218
+ rcPos.y - parent.restRelChassisPos[1],
219
+ rcPos.z - parent.restRelChassisPos[2]
220
+ ] : [
221
+ rpPos.x,
222
+ rpPos.y,
223
+ rpPos.z
224
+ ];
225
+ const bodyAlignInv = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(b.localPosition), new THREE.Quaternion(), one).invert();
226
+ const ownLumped = computeLumpedMassProps([b], bodyAlignInv);
227
+ const frameMat = new THREE.Matrix4().makeRotationFromQuaternion(rcQuat);
228
+ const cPos = new THREE.Vector3(), cQuat = new THREE.Quaternion();
217
229
  const colliders = b.colliders.map((spec, idx) => {
218
230
  const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
219
- const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one);
231
+ const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one).premultiply(frameMat);
232
+ local.decompose(cPos, cQuat, scl);
233
+ cQuat.normalize();
220
234
  const planned = {
221
235
  spec,
222
236
  local,
223
237
  position: [
224
- spec.localPosition[0],
225
- spec.localPosition[1],
226
- spec.localPosition[2]
238
+ cPos.x,
239
+ cPos.y,
240
+ cPos.z
227
241
  ],
228
242
  quaternion: [
229
- colQuat.x,
230
- colQuat.y,
231
- colQuat.z,
232
- colQuat.w
243
+ cQuat.x,
244
+ cQuat.y,
245
+ cQuat.z,
246
+ cQuat.w
233
247
  ]
234
248
  };
235
- if (idx === 0 && ownLumped) planned.massProperties = toColliderMass(ownLumped, local, colQuat);
249
+ if (idx === 0 && ownLumped) planned.massProperties = toColliderMass(ownLumped, local, cQuat);
236
250
  return planned;
237
251
  });
238
252
  const plan = {
239
253
  spec: b,
240
254
  joint,
241
255
  parent,
242
- restRelParentPos: [
243
- rpPos.x,
244
- rpPos.y,
245
- rpPos.z
246
- ],
256
+ restRelParentPos: anchorParent,
247
257
  restRelParentQuat: [
248
- rpQuat.x,
249
- rpQuat.y,
250
- rpQuat.z,
251
- rpQuat.w
258
+ rcQuat.x,
259
+ rcQuat.y,
260
+ rcQuat.z,
261
+ rcQuat.w
252
262
  ],
253
263
  restRelChassisPos: [
254
264
  rcPos.x,
@@ -287,15 +297,16 @@ function isVehicleJointOpen(rt) {
287
297
  return Math.abs(openTgt) > 1e-6 && Math.abs((rt.positionTarget ?? rt.getCoordinate()) - openTgt) < Math.abs(openTgt) * .5;
288
298
  }
289
299
  // src/khrVehicleJoints.tsx
290
- function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, parentBodyGetter, origin, onBody, onJointReady }) {
300
+ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, angularVelocity, gravityScale, parentBodyGetter, origin, onBody, onJointReady }) {
291
301
  const { rapier, world } = useRapier();
292
302
  const registry = useContext(JointRegistryContext);
293
303
  const childRef = useRef(null);
294
304
  const rtRef = useRef(null);
305
+ const parentBodyGetterRef = useRef(parentBodyGetter);
306
+ parentBodyGetterRef.current = parentBodyGetter;
295
307
  const worldPose = useMemo(() => {
296
- const sq = new THREE.Quaternion(spawnQuat[0], spawnQuat[1], spawnQuat[2], spawnQuat[3]);
308
+ const sq = new THREE.Quaternion(spawnQuat[0], spawnQuat[1], spawnQuat[2], spawnQuat[3]).normalize();
297
309
  const pos = new THREE.Vector3().fromArray(part.restRelChassisPos).applyQuaternion(sq).add(new THREE.Vector3(spawnPos[0], spawnPos[1], spawnPos[2]));
298
- const quat = sq.clone().multiply(new THREE.Quaternion().fromArray(part.restRelChassisQuat)).normalize();
299
310
  return {
300
311
  pos: [
301
312
  pos.x,
@@ -303,15 +314,14 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, parentBodyGetter,
303
314
  pos.z
304
315
  ],
305
316
  quat: [
306
- quat.x,
307
- quat.y,
308
- quat.z,
309
- quat.w
317
+ sq.x,
318
+ sq.y,
319
+ sq.z,
320
+ sq.w
310
321
  ]
311
322
  };
312
323
  }, [
313
324
  part.restRelChassisPos,
314
- part.restRelChassisQuat,
315
325
  spawnPos,
316
326
  spawnQuat
317
327
  ]);
@@ -328,7 +338,7 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, parentBodyGetter,
328
338
  }
329
339
  }, [part.partMass]);
330
340
  useEffect(() => {
331
- const parentBody = parentBodyGetter();
341
+ const parentBody = parentBodyGetterRef.current();
332
342
  const childBody = childRef.current;
333
343
  if (!parentBody || !childBody) return;
334
344
  const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
@@ -345,7 +355,12 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, parentBodyGetter,
345
355
  object: part.spec.object,
346
356
  axisParent: part.axisParent,
347
357
  anchorParent: part.restRelParentPos,
348
- restRelQuat: part.restRelParentQuat,
358
+ restRelQuat: [
359
+ 0,
360
+ 0,
361
+ 0,
362
+ 1
363
+ ],
349
364
  limits: part.joint.limits,
350
365
  drive: part.joint.drive,
351
366
  breakaway: part.spec.breakaway,
@@ -366,20 +381,25 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, parentBodyGetter,
366
381
  rapier,
367
382
  world,
368
383
  part,
369
- parentBodyGetter,
370
384
  registry,
371
385
  onJointReady
372
386
  ]);
373
387
  const onForce = part.spec.breakaway ? (p) => {
374
388
  rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * Math.max(world.timestep, 1 / 240));
375
389
  } : void 0;
390
+ const linVel = part.spec.linearVelocity ?? linearVelocity;
391
+ const angVel = part.spec.angularVelocity ?? angularVelocity;
392
+ const gravScale = part.spec.gravityFactor ?? gravityScale;
376
393
  return /* @__PURE__ */ jsxs(RigidBody, {
377
394
  ref: childRef,
378
- type: "dynamic",
395
+ type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
379
396
  position: worldPose.pos,
380
397
  quaternion: worldPose.quat,
381
398
  colliders: false,
382
399
  onContactForce: onForce,
400
+ ...linVel ? { linearVelocity: linVel } : {},
401
+ ...angVel ? { angularVelocity: angVel } : {},
402
+ ...gravScale === void 0 ? {} : { gravityScale: gravScale },
383
403
  children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
384
404
  object: part.spec.object,
385
405
  position: [
@@ -387,12 +407,7 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, parentBodyGetter,
387
407
  0,
388
408
  0
389
409
  ],
390
- quaternion: [
391
- 0,
392
- 0,
393
- 0,
394
- 1
395
- ],
410
+ quaternion: part.restRelChassisQuat,
396
411
  origin
397
412
  }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
398
413
  c: col.spec,
@@ -402,7 +417,7 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, parentBodyGetter,
402
417
  }, `vj_${part.spec.nodeName}:${cIdx}`))]
403
418
  });
404
419
  }
405
- function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, jointsRef }) {
420
+ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, linearVelocity, angularVelocity, gravityScale, jointsRef }) {
406
421
  const parts = useMemo(() => planVehicleJointParts(bodies), [bodies]);
407
422
  const origins = useMemo(() => parts.length > 0 ? captureSubtreeOrigins(parts.map((p) => p.spec.object)) : null, [parts]);
408
423
  const bodyMapRef = useRef(/* @__PURE__ */ new Map());
@@ -460,6 +475,9 @@ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, jointsRef }
460
475
  part,
461
476
  spawnPos,
462
477
  spawnQuat,
478
+ linearVelocity,
479
+ angularVelocity,
480
+ gravityScale,
463
481
  parentBodyGetter: () => part.parent ? bodyMapRef.current.get(part.parent.spec.nodeName) ?? null : vehicleRef.current?.body ?? null,
464
482
  origin: origins?.get(part.spec.object),
465
483
  onBody: handleBody,
@@ -486,6 +504,48 @@ function resetAllWheelHits(handle) {
486
504
  w.effInertia = 0;
487
505
  }
488
506
  }
507
+ function resetDisabledWheelHits(handle, isDisabled) {
508
+ if (!handle) return;
509
+ for (const wheelRef of handle.wheelsInfo.values()) {
510
+ const w = wheelRef.current;
511
+ if (!w || !isDisabled(w.name)) continue;
512
+ w.rayHit = null;
513
+ w.rayHitBody = null;
514
+ w.floatImp.set(0, 0, 0);
515
+ w.lngFricImp.set(0, 0, 0);
516
+ w.latFricImp.set(0, 0, 0);
517
+ w.lngSlipRatio = 0;
518
+ w.latSlipRatio = 0;
519
+ w.slipStrength = 0;
520
+ w.isOnPlatform = false;
521
+ w.effInertia = 0;
522
+ }
523
+ }
524
+ function resetAllPropellerOutputs(handle) {
525
+ if (!handle) return;
526
+ for (const propRef of handle.propellersInfo.values()) {
527
+ const p = propRef.current;
528
+ if (!p) continue;
529
+ p.lx = 0;
530
+ p.ly = 0;
531
+ p.lz = 0;
532
+ p.ax = 0;
533
+ p.ay = 0;
534
+ p.az = 0;
535
+ p.thrustDir.set(0, 0, 0);
536
+ p.torqueDir.set(0, 0, 0);
537
+ p.thrustImpulse.set(0, 0, 0);
538
+ p.torqueImpulse.set(0, 0, 0);
539
+ p.finalThrottle = 0;
540
+ p.throttle = 0;
541
+ p.setThrottle?.(0);
542
+ }
543
+ }
544
+ function resetDisabledRotors(handle, opts) {
545
+ if (opts.wheelsAllOff) resetAllWheelHits(handle);
546
+ else if (opts.frontOff || opts.rearOff) resetDisabledWheelHits(handle, (name) => name && opts.frontWheelNames.has(name) ? opts.frontOff : opts.rearOff);
547
+ if (opts.propsOff) resetAllPropellerOutputs(handle);
548
+ }
489
549
  /**
490
550
  * Gates `<ShapeCastWheel>` only when gravity is non-zero (`gravityMag > 1e-6`), preventing
491
551
  * `ShapeCastWheel`'s internal `smoothedLngImpulse += Infinity` closure poisoning in 0G.
@@ -517,9 +577,14 @@ function ZeroGWheelGate({ vehicleRef, enable, enableCustomGravity, spawnPos, zer
517
577
  });
518
578
  return null;
519
579
  }
520
- function ZeroGWheelPostClear({ vehicleRef, zeroGRef }) {
580
+ function ZeroGWheelPostClear({ vehicleRef, zeroGRef, disabledRotorsRef }) {
521
581
  useFrame(() => {
522
- if (zeroGRef.current) resetAllWheelHits(vehicleRef.current);
582
+ if (zeroGRef.current) {
583
+ resetAllWheelHits(vehicleRef.current);
584
+ return;
585
+ }
586
+ const flags = disabledRotorsRef?.current;
587
+ if (flags && (flags.wheelsAllOff || flags.frontOff || flags.rearOff || flags.propsOff)) resetDisabledRotors(vehicleRef.current, flags);
523
588
  });
524
589
  return null;
525
590
  }
@@ -541,7 +606,20 @@ function RotorVisualSlot({ object, center, quaternion, scene, origin }) {
541
606
  object.quaternion.copy(quat.normalize());
542
607
  object.scale.copy(scl);
543
608
  slot.add(object);
609
+ const untrack = registerMountedSubtree(() => {
610
+ const p = object.position.clone(), q = object.quaternion.clone(), s = object.scale.clone();
611
+ if (object.parent === slot) slot.remove(object);
612
+ restoreSubtreeOrigin(object, snap);
613
+ return () => {
614
+ if (snap.origParent) snap.origParent.remove(object);
615
+ object.position.copy(p);
616
+ object.quaternion.copy(q);
617
+ object.scale.copy(s);
618
+ slot.add(object);
619
+ };
620
+ });
544
621
  return () => {
622
+ untrack();
545
623
  if (object.parent === slot) slot.remove(object);
546
624
  restoreSubtreeOrigin(object, snap);
547
625
  };
@@ -594,10 +672,10 @@ function KhrVehicleRotors({ solvedWheels, propellers, scene, comZ, rotorOrigins,
594
672
  0,
595
673
  1
596
674
  ],
597
- enable: wheelEnable,
598
675
  ...tagWheelProps,
599
676
  ...wheelConfig,
600
677
  ...axleCfg,
678
+ enable: wheelEnable && (axleCfg?.enable ?? wheelConfig?.enable ?? true),
601
679
  children: /* @__PURE__ */ jsx(RotorVisualSlot, {
602
680
  object: tag.object,
603
681
  center: tag.position,
@@ -606,34 +684,53 @@ function KhrVehicleRotors({ solvedWheels, propellers, scene, comZ, rotorOrigins,
606
684
  origin: rotorOrigins.get(tag.object)
607
685
  })
608
686
  }, `${tag.nodeName}:${wheelEpoch}`);
609
- }), propellers.map((tag) => /* @__PURE__ */ jsx(ThrustPropeller, {
610
- name: tag.nodeName,
611
- position: [
612
- tag.position[0],
613
- tag.position[1],
614
- tag.position[2]
615
- ],
616
- quaternion: tag.quaternion ?? [
617
- 0,
618
- 0,
619
- 0,
620
- 1
621
- ],
622
- debug: false,
623
- enable,
624
- maxThrust: tag.maxThrust,
625
- ...tag.torqueRatio !== void 0 ? { torqueRatio: tag.torqueRatio } : {},
626
- ...tag.invertThrust !== void 0 ? { invertThrust: tag.invertThrust } : {},
627
- ...tag.invertTorque !== void 0 ? { invertTorque: tag.invertTorque } : {},
628
- ...propellerConfig,
629
- children: /* @__PURE__ */ jsx(RotorVisualSlot, {
687
+ }), propellers.map((tag) => {
688
+ const propEnabled = enable && (propellerConfig?.enable ?? true);
689
+ const visual = /* @__PURE__ */ jsx(RotorVisualSlot, {
630
690
  object: tag.object,
631
691
  center: tag.position,
632
692
  quaternion: tag.quaternion,
633
693
  scene,
634
694
  origin: rotorOrigins.get(tag.object)
635
- })
636
- }, tag.nodeName))] });
695
+ });
696
+ if (!propEnabled) return /* @__PURE__ */ jsx("group", {
697
+ name: tag.nodeName,
698
+ position: [
699
+ tag.position[0],
700
+ tag.position[1],
701
+ tag.position[2]
702
+ ],
703
+ quaternion: tag.quaternion ?? [
704
+ 0,
705
+ 0,
706
+ 0,
707
+ 1
708
+ ],
709
+ children: visual
710
+ }, `${tag.nodeName}:off`);
711
+ return /* @__PURE__ */ jsx(ThrustPropeller, {
712
+ name: tag.nodeName,
713
+ position: [
714
+ tag.position[0],
715
+ tag.position[1],
716
+ tag.position[2]
717
+ ],
718
+ quaternion: tag.quaternion ?? [
719
+ 0,
720
+ 0,
721
+ 0,
722
+ 1
723
+ ],
724
+ debug: false,
725
+ maxThrust: tag.maxThrust,
726
+ ...tag.torqueRatio !== void 0 ? { torqueRatio: tag.torqueRatio } : {},
727
+ ...tag.invertThrust !== void 0 ? { invertThrust: tag.invertThrust } : {},
728
+ ...tag.invertTorque !== void 0 ? { invertTorque: tag.invertTorque } : {},
729
+ ...propellerConfig,
730
+ enable: true,
731
+ children: visual
732
+ }, tag.nodeName);
733
+ })] });
637
734
  }
638
735
  // src/wheelLoads.ts
639
736
  var G_SI = 9.81;
@@ -769,6 +866,34 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
769
866
  bundle.centerOfMass
770
867
  ]);
771
868
  const rotorOrigins = useMemo(() => captureRotorOrigins([...bundle.wheels.map((w) => w.object), ...bundle.propellers.map((p) => p.object)]), [bundle.wheels, bundle.propellers]);
869
+ const frontWheelNames = useMemo(() => new Set(solvedWheels.filter((w) => w.mountPos[2] >= chassis.com[2]).map((w) => w.tag.nodeName)), [solvedWheels, chassis.com]);
870
+ const wheelsAllOff = !enable || isZeroG || wheelConfig?.enable === false && frontWheelConfig?.enable !== true && rearWheelConfig?.enable !== true;
871
+ const frontOff = frontWheelConfig?.enable === false || frontWheelConfig?.enable === void 0 && wheelConfig?.enable === false;
872
+ const rearOff = rearWheelConfig?.enable === false || rearWheelConfig?.enable === void 0 && wheelConfig?.enable === false;
873
+ const propsOff = !enable || propellerConfig?.enable === false;
874
+ const disabledRotorsRef = useRef({
875
+ wheelsAllOff,
876
+ frontOff,
877
+ rearOff,
878
+ propsOff,
879
+ frontWheelNames
880
+ });
881
+ disabledRotorsRef.current = {
882
+ wheelsAllOff,
883
+ frontOff,
884
+ rearOff,
885
+ propsOff,
886
+ frontWheelNames
887
+ };
888
+ useLayoutEffect(() => {
889
+ resetDisabledRotors(innerRef.current, disabledRotorsRef.current);
890
+ }, [
891
+ wheelsAllOff,
892
+ frontOff,
893
+ rearOff,
894
+ propsOff,
895
+ frontWheelNames
896
+ ]);
772
897
  const [px, py, pz] = readPosTuple(position);
773
898
  const [qx, qy, qz, qw] = readSpawnQuat(rotation, quaternion);
774
899
  const bodyPos = useMemo(() => [
@@ -870,7 +995,8 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
870
995
  }),
871
996
  /* @__PURE__ */ jsx(ZeroGWheelPostClear, {
872
997
  vehicleRef: innerRef,
873
- zeroGRef
998
+ zeroGRef,
999
+ disabledRotorsRef
874
1000
  }, `post:${wheelEpoch}`)
875
1001
  ] })
876
1002
  ]
@@ -879,6 +1005,9 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
879
1005
  vehicleRef: innerRef,
880
1006
  spawnPos: bodyPos,
881
1007
  spawnQuat: bodyQuat,
1008
+ linearVelocity: effLinVel,
1009
+ angularVelocity: effAngVel,
1010
+ gravityScale: effGravScale,
882
1011
  jointsRef
883
1012
  })] });
884
1013
  }