@khr3/core 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vehicle.js CHANGED
@@ -4,8 +4,353 @@ import { useFrame } from "@react-three/fiber";
4
4
  import { RigidBody, useRapier } from "@react-three/rapier";
5
5
  import { useCustomGravity } from "@pinkaphant/ecctrl/gravity";
6
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";
7
+ import { B as assignRef, C as applyRapierBodyMass, D as bodyPoseMatrix, E as assertUnitScale, R as JointRegistryContext, T as assertSceneIdentityWorldScale, f as KhrCollider, h as captureSubtreeOrigins, i as closedTargetForLimits, k as computeLumpedMassProps, l as openTargetForLimits, m as MountSubtreeSlot, o as createRapierImpulseJoint, p as BundleSceneHost, r as buildJointRuntime, s as isJointOpen, t as ATTACHED_PANEL_INTERACTION_GROUPS, u as toggleDrivenJoint, x as restoreSubtreeOrigin, y as registerMountedSubtree, z as KhrValidationError } from "./joints-H3uae8pm.js";
8
8
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
+ // src/vehicleJoints.tsx
10
+ function mergeVehiclePanelUserData(userData) {
11
+ const base = userData && typeof userData === "object" ? userData : {};
12
+ const ecctrl = base.ecctrl && typeof base.ecctrl === "object" ? base.ecctrl : {};
13
+ return {
14
+ ...base,
15
+ ecctrl: {
16
+ ...ecctrl,
17
+ excludeVehicleRay: true
18
+ }
19
+ };
20
+ }
21
+ function planVehicleJointParts(bodies) {
22
+ const dyn = bodies.filter((b) => !b.isKinematic);
23
+ const byName = new Map(dyn.map((b) => [b.nodeName, b]));
24
+ const jointed = dyn.filter((b) => b.joint !== null);
25
+ if (jointed.length === 0) return [];
26
+ const depthMemo = /* @__PURE__ */ new Map();
27
+ const depthOf = (b, seen = /* @__PURE__ */ new Set()) => {
28
+ const hit = depthMemo.get(b.nodeName);
29
+ if (hit !== void 0) return hit;
30
+ if (!b.joint) {
31
+ depthMemo.set(b.nodeName, 0);
32
+ return 0;
33
+ }
34
+ if (seen.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
35
+ seen.add(b.nodeName);
36
+ const parent = byName.get(b.joint.connectedNodeName);
37
+ if (!parent) throw new KhrValidationError(`Vehicle joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a dynamic KHR body`);
38
+ const d = 1 + depthOf(parent, seen);
39
+ depthMemo.set(b.nodeName, d);
40
+ return d;
41
+ };
42
+ jointed.sort((a, b) => depthOf(a) - depthOf(b));
43
+ const one = new THREE.Vector3(1, 1, 1);
44
+ const rpPos = new THREE.Vector3(), rpQuat = new THREE.Quaternion();
45
+ const rcPos = new THREE.Vector3(), rcQuat = new THREE.Quaternion(), scl = new THREE.Vector3();
46
+ const partByName = /* @__PURE__ */ new Map();
47
+ return jointed.map((b) => {
48
+ const joint = b.joint;
49
+ const parent = partByName.get(joint.connectedNodeName) ?? null;
50
+ const bodyMat = bodyPoseMatrix(b);
51
+ (parent ? bodyPoseMatrix(parent.spec) : new THREE.Matrix4()).clone().invert().multiply(bodyMat).decompose(rpPos, rpQuat, scl);
52
+ bodyMat.decompose(rcPos, rcQuat, scl);
53
+ rcQuat.normalize();
54
+ const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
55
+ const axParentVec = axChildVec.clone().applyQuaternion(rcQuat).normalize();
56
+ const anchorParent = parent ? [
57
+ rcPos.x - parent.restRelChassisPos[0],
58
+ rcPos.y - parent.restRelChassisPos[1],
59
+ rcPos.z - parent.restRelChassisPos[2]
60
+ ] : [
61
+ rpPos.x,
62
+ rpPos.y,
63
+ rpPos.z
64
+ ];
65
+ const rcQuatTuple = [
66
+ rcQuat.x,
67
+ rcQuat.y,
68
+ rcQuat.z,
69
+ rcQuat.w
70
+ ];
71
+ const invPartFrame = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(b.localPosition), new THREE.Quaternion(), one).invert();
72
+ const lumpedMass = computeLumpedMassProps([b], invPartFrame);
73
+ const frameMat = new THREE.Matrix4().makeRotationFromQuaternion(rcQuat);
74
+ const cPos = new THREE.Vector3(), cQuat = new THREE.Quaternion();
75
+ const colliders = b.colliders.map((spec) => {
76
+ const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
77
+ new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one).premultiply(frameMat).decompose(cPos, cQuat, scl);
78
+ cQuat.normalize();
79
+ return {
80
+ spec: spec.collisionGroups === void 0 ? {
81
+ ...spec,
82
+ collisionGroups: ATTACHED_PANEL_INTERACTION_GROUPS
83
+ } : spec,
84
+ position: [
85
+ cPos.x,
86
+ cPos.y,
87
+ cPos.z
88
+ ],
89
+ quaternion: [
90
+ cQuat.x,
91
+ cQuat.y,
92
+ cQuat.z,
93
+ cQuat.w
94
+ ]
95
+ };
96
+ });
97
+ const plan = {
98
+ spec: b,
99
+ joint,
100
+ parent,
101
+ restRelParentPos: anchorParent,
102
+ restRelParentQuat: rcQuatTuple,
103
+ restRelChassisPos: [
104
+ rcPos.x,
105
+ rcPos.y,
106
+ rcPos.z
107
+ ],
108
+ restRelChassisQuat: rcQuatTuple,
109
+ axisParent: [
110
+ axParentVec.x,
111
+ axParentVec.y,
112
+ axParentVec.z
113
+ ],
114
+ axisChild: [
115
+ axChildVec.x,
116
+ axChildVec.y,
117
+ axChildVec.z
118
+ ],
119
+ lumpedMass,
120
+ colliders
121
+ };
122
+ partByName.set(b.nodeName, plan);
123
+ return plan;
124
+ });
125
+ }
126
+ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, angularVelocity, gravityScale, panelUserData, parentBody, origin, onBody, onJointReady }) {
127
+ const { rapier, world } = useRapier();
128
+ const registry = useContext(JointRegistryContext);
129
+ const rtRef = useRef(null);
130
+ const [childBody, setChildBody] = useState(null);
131
+ const worldPose = useMemo(() => {
132
+ const sq = new THREE.Quaternion(spawnQuat[0], spawnQuat[1], spawnQuat[2], spawnQuat[3]).normalize();
133
+ const pos = new THREE.Vector3().fromArray(part.restRelChassisPos).applyQuaternion(sq).add(new THREE.Vector3(spawnPos[0], spawnPos[1], spawnPos[2]));
134
+ return {
135
+ pos: [
136
+ pos.x,
137
+ pos.y,
138
+ pos.z
139
+ ],
140
+ quat: [
141
+ sq.x,
142
+ sq.y,
143
+ sq.z,
144
+ sq.w
145
+ ]
146
+ };
147
+ }, [
148
+ part.restRelChassisPos,
149
+ spawnPos,
150
+ spawnQuat
151
+ ]);
152
+ const assignChildRef = useCallback((rb) => {
153
+ setChildBody(rb);
154
+ onBody(part.spec.nodeName, rb);
155
+ }, [part.spec.nodeName, onBody]);
156
+ useEffect(() => () => onBody(part.spec.nodeName, null), [part.spec.nodeName, onBody]);
157
+ useEffect(() => {
158
+ if (childBody && part.lumpedMass) applyRapierBodyMass(childBody, part.lumpedMass);
159
+ }, [childBody, part.lumpedMass]);
160
+ useEffect(() => {
161
+ if (!parentBody || !childBody) return;
162
+ const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
163
+ 0,
164
+ 0,
165
+ 0
166
+ ], part.axisParent, part.axisChild, part.restRelParentQuat);
167
+ const rt = buildJointRuntime({
168
+ rapier,
169
+ world,
170
+ nodeName: part.spec.nodeName,
171
+ role: part.joint.role,
172
+ kind: part.joint.kind,
173
+ object: part.spec.object,
174
+ axisParent: part.axisParent,
175
+ anchorParent: part.restRelParentPos,
176
+ limits: part.joint.limits,
177
+ drive: part.joint.drive,
178
+ breakaway: part.spec.breakaway,
179
+ rapierJoint: imp,
180
+ parentBody,
181
+ childBody
182
+ });
183
+ rtRef.current = rt;
184
+ registry?.add(rt);
185
+ onJointReady(rt.nodeName, part.spec.object, rt);
186
+ return () => {
187
+ rtRef.current = null;
188
+ registry?.delete(rt);
189
+ onJointReady(rt.nodeName, part.spec.object, null);
190
+ if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
191
+ };
192
+ }, [
193
+ rapier,
194
+ world,
195
+ part,
196
+ parentBody,
197
+ childBody,
198
+ registry,
199
+ onJointReady
200
+ ]);
201
+ const onForce = useMemo(() => part.spec.breakaway ? (p) => {
202
+ if (world.timestep > 0) rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * world.timestep);
203
+ } : void 0, [part.spec.breakaway, world]);
204
+ const linVel = part.spec.linearVelocity ?? linearVelocity;
205
+ const angVel = part.spec.angularVelocity ?? angularVelocity;
206
+ const gravScale = part.spec.gravityFactor ?? gravityScale;
207
+ return /* @__PURE__ */ jsxs(RigidBody, {
208
+ ref: assignChildRef,
209
+ type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
210
+ position: worldPose.pos,
211
+ quaternion: worldPose.quat,
212
+ colliders: false,
213
+ userData: panelUserData,
214
+ onContactForce: onForce,
215
+ ...linVel ? { linearVelocity: linVel } : {},
216
+ ...angVel ? { angularVelocity: angVel } : {},
217
+ ...gravScale === void 0 ? {} : { gravityScale: gravScale },
218
+ children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
219
+ object: part.spec.object,
220
+ position: [
221
+ 0,
222
+ 0,
223
+ 0
224
+ ],
225
+ quaternion: part.restRelChassisQuat,
226
+ origin
227
+ }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
228
+ c: col.spec,
229
+ position: col.position,
230
+ quaternion: col.quaternion
231
+ }, `vj_${part.spec.nodeName}:${cIdx}`))]
232
+ });
233
+ }
234
+ var _pPos = new THREE.Vector3();
235
+ var _pQuat = new THREE.Quaternion();
236
+ var _anchor = new THREE.Vector3();
237
+ function KhrVehicleJoints({ bundleScene, bodies, vehicleRef, chassisBody, spawnPos, spawnQuat, enableCustomGravity = false, linearVelocity, angularVelocity, gravityScale, userData, jointsRef }) {
238
+ const { world } = useRapier();
239
+ const applyGravityField = useCustomGravity((state) => state.applyGravityField);
240
+ const parts = useMemo(() => planVehicleJointParts(bodies), [bodies]);
241
+ const origins = useMemo(() => parts.length > 0 ? captureSubtreeOrigins(parts.map((p) => p.spec.object), bundleScene) : null, [parts, bundleScene]);
242
+ const panelUserData = useMemo(() => mergeVehiclePanelUserData(userData), [userData]);
243
+ const bodyMapRef = useRef(/* @__PURE__ */ new Map());
244
+ const [partBodies, setPartBodies] = useState(() => /* @__PURE__ */ new Map());
245
+ const runtimeMapRef = useRef(/* @__PURE__ */ new Map());
246
+ const byObjectRef = useRef(/* @__PURE__ */ new Map());
247
+ useFrame(() => {
248
+ if (!enableCustomGravity || parts.length === 0 || world.timestep <= 0) return;
249
+ for (const rb of bodyMapRef.current.values()) if (rb.isDynamic()) applyGravityField(rb, world.timestep);
250
+ });
251
+ const handleBody = useCallback((nodeName, rb) => {
252
+ if (rb) bodyMapRef.current.set(nodeName, rb);
253
+ else bodyMapRef.current.delete(nodeName);
254
+ setPartBodies((prev) => {
255
+ if ((prev.get(nodeName) ?? null) === rb) return prev;
256
+ const next = new Map(prev);
257
+ if (rb) next.set(nodeName, rb);
258
+ else next.delete(nodeName);
259
+ return next;
260
+ });
261
+ }, []);
262
+ const handleJointReady = useCallback((nodeName, obj, rt) => {
263
+ if (rt) {
264
+ runtimeMapRef.current.set(nodeName, rt);
265
+ byObjectRef.current.set(obj, rt);
266
+ } else {
267
+ runtimeMapRef.current.delete(nodeName);
268
+ byObjectRef.current.delete(obj);
269
+ }
270
+ }, []);
271
+ useImperativeHandle(jointsRef, () => ({
272
+ get hasJoints() {
273
+ return parts.length > 0;
274
+ },
275
+ get jointNames() {
276
+ return parts.map((p) => p.spec.nodeName);
277
+ },
278
+ getBody: (nodeName) => bodyMapRef.current.get(nodeName) ?? null,
279
+ getJointRuntime: (nodeName) => runtimeMapRef.current.get(nodeName) ?? null,
280
+ getJointAngle: (nodeName) => runtimeMapRef.current.get(nodeName)?.getCoordinate() ?? null,
281
+ setJointTarget: (nodeName, target) => {
282
+ runtimeMapRef.current.get(nodeName)?.applyTarget(target);
283
+ },
284
+ setRoleTarget: (role, target) => {
285
+ for (const rt of runtimeMapRef.current.values()) if (rt.role === role) rt.applyTarget(target);
286
+ },
287
+ toggleHitObject: (hit) => {
288
+ for (let cur = hit; cur; cur = cur.parent) {
289
+ const rt = byObjectRef.current.get(cur);
290
+ if (rt && toggleDrivenJoint(rt)) return true;
291
+ }
292
+ return false;
293
+ },
294
+ toggleRolePrefix: (prefix) => {
295
+ const low = prefix.toLowerCase();
296
+ const matches = [...runtimeMapRef.current.values()].filter((rt) => !rt.detached && rt.drive?.stiffness !== void 0 && ((rt.role ?? "").toLowerCase().startsWith(low) || rt.nodeName.toLowerCase().startsWith(low)));
297
+ if (matches.length === 0) return;
298
+ const anyOpen = matches.some((rt) => isJointOpen(rt));
299
+ for (const rt of matches) {
300
+ const limits = rt.limits ?? [0, Math.PI / 2];
301
+ rt.applyTarget(anyOpen ? closedTargetForLimits(limits) : openTargetForLimits(limits));
302
+ }
303
+ },
304
+ shiftBodies: (dx, dy, dz) => {
305
+ for (const part of parts) {
306
+ const rb = bodyMapRef.current.get(part.spec.nodeName);
307
+ const rt = runtimeMapRef.current.get(part.spec.nodeName);
308
+ if (!rb || rt?.detached) continue;
309
+ const t = rb.translation();
310
+ rb.setTranslation({
311
+ x: t.x + dx,
312
+ y: t.y + dy,
313
+ z: t.z + dz
314
+ }, true);
315
+ }
316
+ },
317
+ syncBodiesToParent: () => {
318
+ const parent = vehicleRef.current?.body;
319
+ if (!parent) return;
320
+ const pt = parent.translation(), pr = parent.rotation(), lv = parent.linvel(), av = parent.angvel();
321
+ _pPos.set(pt.x, pt.y, pt.z);
322
+ _pQuat.set(pr.x, pr.y, pr.z, pr.w);
323
+ for (const part of parts) {
324
+ const rb = bodyMapRef.current.get(part.spec.nodeName);
325
+ const rt = runtimeMapRef.current.get(part.spec.nodeName);
326
+ if (!rb || rt?.detached) continue;
327
+ _anchor.fromArray(part.restRelChassisPos).applyQuaternion(_pQuat).add(_pPos);
328
+ rb.setTranslation({
329
+ x: _anchor.x,
330
+ y: _anchor.y,
331
+ z: _anchor.z
332
+ }, true);
333
+ rb.setRotation(pr, true);
334
+ rb.setLinvel(lv, true);
335
+ rb.setAngvel(av, true);
336
+ }
337
+ }
338
+ }), [parts, vehicleRef]);
339
+ if (parts.length === 0) return null;
340
+ return /* @__PURE__ */ jsx(Fragment, { children: parts.map((part) => /* @__PURE__ */ jsx(VehicleArticulatedPanel, {
341
+ part,
342
+ spawnPos,
343
+ spawnQuat,
344
+ linearVelocity,
345
+ angularVelocity,
346
+ gravityScale,
347
+ panelUserData,
348
+ parentBody: part.parent ? partBodies.get(part.parent.spec.nodeName) ?? null : chassisBody ?? vehicleRef.current?.body ?? null,
349
+ origin: origins?.get(part.spec.object),
350
+ onBody: handleBody,
351
+ onJointReady: handleJointReady
352
+ }, part.spec.nodeName)) });
353
+ }
9
354
  // src/wheelLoads.ts
10
355
  var STANDARD_GRAVITY = 9.81;
11
356
  function projectToLowerBoundedSimplex(values, lowerBound, totalSum) {
@@ -99,7 +444,6 @@ function solveWheelLoads(wheels, totalMassKg, com, dampingRatio = .7, refGravity
99
444
  }
100
445
  // src/vehicle.tsx
101
446
  var UNSPRUNG_CORNER_RATIO = .035;
102
- var ATTACHED_PANEL_USER_DATA = { ecctrl: { excludeVehicleRay: true } };
103
447
  var _samplePos = new THREE.Vector3();
104
448
  function readPosTuple(pos) {
105
449
  if (typeof pos === "number") return [
@@ -174,9 +518,8 @@ function readSpawnQuat(rotation, quaternion) {
174
518
  function computeChassisMassProps(bodies) {
175
519
  const dyn = bodies.filter((b) => !b.isKinematic && b.joint === null);
176
520
  if (dyn.length === 0) throw new KhrValidationError("KhrVehicle: bundle has no dynamic rigid body for the chassis");
177
- const lumped = computeLumpedMassProps(dyn);
178
- if (!lumped || !(lumped.mass > 0)) throw new KhrValidationError("KhrVehicle: chassis dynamic mass must be positive");
179
- if (!lumped.inertia.every((v) => Number.isFinite(v) && v > 0)) throw new KhrValidationError("KhrVehicle: chassis principal inertia must be positive and finite");
521
+ const lumpedMass = computeLumpedMassProps(dyn);
522
+ if (!lumpedMass) throw new KhrValidationError("KhrVehicle: chassis dynamic mass must be positive");
180
523
  let gravityFactor;
181
524
  if (dyn.some((b) => b.gravityFactor !== void 0)) {
182
525
  const g0 = dyn[0].gravityFactor ?? 1;
@@ -197,9 +540,9 @@ function computeChassisMassProps(bodies) {
197
540
  vz += lv[2] * b.mass;
198
541
  }
199
542
  linearVelocity = [
200
- vx / lumped.mass,
201
- vy / lumped.mass,
202
- vz / lumped.mass
543
+ vx / lumpedMass.mass,
544
+ vy / lumpedMass.mass,
545
+ vz / lumpedMass.mass
203
546
  ];
204
547
  }
205
548
  const rootDyn = dyn.find((b) => b.angularVelocity !== void 0);
@@ -209,16 +552,13 @@ function computeChassisMassProps(bodies) {
209
552
  rootDyn.angularVelocity[2]
210
553
  ] : void 0;
211
554
  return {
212
- mass: lumped.mass,
213
- com: lumped.com,
214
- inertia: lumped.inertia,
215
- inertiaFrame: lumped.inertiaFrame,
555
+ lumpedMass,
216
556
  ...linearVelocity ? { linearVelocity } : {},
217
557
  ...angularVelocity ? { angularVelocity } : {},
218
558
  ...gravityFactor !== void 0 ? { gravityFactor } : {}
219
559
  };
220
560
  }
221
- function buildChassisColliders(bodies, chassis) {
561
+ function buildChassisColliders(bodies) {
222
562
  const out = [];
223
563
  const one = new THREE.Vector3(1, 1, 1);
224
564
  const pos = new THREE.Vector3();
@@ -232,8 +572,6 @@ function buildChassisColliders(bodies, chassis) {
232
572
  const colMat = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(c.localPosition), new THREE.Quaternion().fromArray(c.localQuaternion), one);
233
573
  bodyMat.clone().multiply(colMat).decompose(pos, quat, scl);
234
574
  quat.normalize();
235
- const isFirst = out.length === 0;
236
- const rigidColMat = isFirst ? new THREE.Matrix4().compose(pos, quat, one) : void 0;
237
575
  out.push({
238
576
  key: `${b.nodeName}:${idx}`,
239
577
  spec: {
@@ -249,8 +587,7 @@ function buildChassisColliders(bodies, chassis) {
249
587
  quat.z,
250
588
  quat.w
251
589
  ]
252
- },
253
- ...isFirst ? { massProperties: toColliderMass(chassis, rigidColMat, quat.clone()) } : {}
590
+ }
254
591
  });
255
592
  }
256
593
  }
@@ -303,407 +640,56 @@ function resetPropellerOutputs(handle) {
303
640
  p.torqueDir.set(0, 0, 0);
304
641
  p.thrustImpulse.set(0, 0, 0);
305
642
  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
- }
357
- function planVehicleJointParts(bodies) {
358
- const dyn = bodies.filter((b) => !b.isKinematic);
359
- const byName = new Map(dyn.map((b) => [b.nodeName, b]));
360
- const jointed = dyn.filter((b) => b.joint !== null);
361
- if (jointed.length === 0) return [];
362
- const depthMemo = /* @__PURE__ */ new Map();
363
- const depthOf = (b, seen = /* @__PURE__ */ new Set()) => {
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
- }
370
- if (seen.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
371
- seen.add(b.nodeName);
372
- const parent = byName.get(b.joint.connectedNodeName);
373
- if (!parent) throw new KhrValidationError(`Vehicle joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a dynamic KHR body`);
374
- const d = 1 + depthOf(parent, seen);
375
- depthMemo.set(b.nodeName, d);
376
- return d;
377
- };
378
- jointed.sort((a, b) => depthOf(a) - depthOf(b));
379
- const one = new THREE.Vector3(1, 1, 1);
380
- const rpPos = new THREE.Vector3(), rpQuat = new THREE.Quaternion();
381
- const rcPos = new THREE.Vector3(), rcQuat = new THREE.Quaternion(), scl = new THREE.Vector3();
382
- const partByName = /* @__PURE__ */ new Map();
383
- return jointed.map((b) => {
384
- const joint = b.joint;
385
- const parent = partByName.get(joint.connectedNodeName) ?? null;
386
- const bodyMat = bodyPoseMatrix(b);
387
- (parent ? bodyPoseMatrix(parent.spec) : new THREE.Matrix4()).clone().invert().multiply(bodyMat).decompose(rpPos, rpQuat, scl);
388
- bodyMat.decompose(rcPos, rcQuat, scl);
389
- rcQuat.normalize();
390
- const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
391
- const axParentVec = axChildVec.clone().applyQuaternion(rcQuat).normalize();
392
- const anchorParent = parent ? [
393
- rcPos.x - parent.restRelChassisPos[0],
394
- rcPos.y - parent.restRelChassisPos[1],
395
- rcPos.z - parent.restRelChassisPos[2]
396
- ] : [
397
- rpPos.x,
398
- rpPos.y,
399
- rpPos.z
400
- ];
401
- const bodyAlignInv = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(b.localPosition), new THREE.Quaternion(), one).invert();
402
- const ownLumped = computeLumpedMassProps([b], bodyAlignInv);
403
- const frameMat = new THREE.Matrix4().makeRotationFromQuaternion(rcQuat);
404
- const cPos = new THREE.Vector3(), cQuat = new THREE.Quaternion();
405
- const colliders = b.colliders.map((spec, idx) => {
406
- const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
407
- const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one).premultiply(frameMat);
408
- local.decompose(cPos, cQuat, scl);
409
- cQuat.normalize();
410
- const planned = {
411
- spec: spec.collisionGroups === void 0 ? {
412
- ...spec,
413
- collisionGroups: ATTACHED_PANEL_INTERACTION_GROUPS
414
- } : spec,
415
- position: [
416
- cPos.x,
417
- cPos.y,
418
- cPos.z
419
- ],
420
- quaternion: [
421
- cQuat.x,
422
- cQuat.y,
423
- cQuat.z,
424
- cQuat.w
425
- ]
426
- };
427
- if (idx === 0 && ownLumped) planned.massProperties = toColliderMass(ownLumped, local, cQuat);
428
- return planned;
429
- });
430
- const plan = {
431
- spec: b,
432
- joint,
433
- parent,
434
- restRelParentPos: anchorParent,
435
- restRelParentQuat: [
436
- rcQuat.x,
437
- rcQuat.y,
438
- rcQuat.z,
439
- rcQuat.w
440
- ],
441
- restRelChassisPos: [
442
- rcPos.x,
443
- rcPos.y,
444
- rcPos.z
445
- ],
446
- restRelChassisQuat: [
447
- rcQuat.x,
448
- rcQuat.y,
449
- rcQuat.z,
450
- rcQuat.w
451
- ],
452
- axisParent: [
453
- axParentVec.x,
454
- axParentVec.y,
455
- axParentVec.z
456
- ],
457
- axisChild: [
458
- axChildVec.x,
459
- axChildVec.y,
460
- axChildVec.z
461
- ],
462
- ...ownLumped && colliders.length === 0 ? { partMass: toColliderMass(ownLumped) } : {},
463
- colliders
464
- };
465
- partByName.set(b.nodeName, plan);
466
- return plan;
467
- });
643
+ p.finalThrottle = 0;
644
+ p.throttle = 0;
645
+ p.setThrottle?.(0);
646
+ }
468
647
  }
469
- function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, angularVelocity, gravityScale, parentBody, origin, onBody, onJointReady }) {
470
- const { rapier, world } = useRapier();
471
- const registry = useContext(JointRegistryContext);
472
- const rtRef = useRef(null);
473
- const [childBody, setChildBody] = useState(null);
474
- const worldPose = useMemo(() => {
475
- const sq = new THREE.Quaternion(spawnQuat[0], spawnQuat[1], spawnQuat[2], spawnQuat[3]).normalize();
476
- const pos = new THREE.Vector3().fromArray(part.restRelChassisPos).applyQuaternion(sq).add(new THREE.Vector3(spawnPos[0], spawnPos[1], spawnPos[2]));
477
- return {
478
- pos: [
479
- pos.x,
480
- pos.y,
481
- pos.z
482
- ],
483
- quat: [
484
- sq.x,
485
- sq.y,
486
- sq.z,
487
- sq.w
488
- ]
489
- };
490
- }, [
491
- part.restRelChassisPos,
492
- spawnPos,
493
- spawnQuat
494
- ]);
495
- const assignChildRef = useCallback((rb) => {
496
- setChildBody(rb);
497
- onBody(part.spec.nodeName, rb);
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]);
507
- useEffect(() => {
508
- if (!parentBody || !childBody) return;
509
- const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
510
- 0,
511
- 0,
512
- 0
513
- ], part.axisParent, part.axisChild, part.restRelParentQuat);
514
- const rt = buildJointRuntime({
515
- rapier,
516
- world,
517
- nodeName: part.spec.nodeName,
518
- role: part.joint.role,
519
- kind: part.joint.kind,
520
- object: part.spec.object,
521
- axisParent: part.axisParent,
522
- anchorParent: part.restRelParentPos,
523
- limits: part.joint.limits,
524
- drive: part.joint.drive,
525
- breakaway: part.spec.breakaway,
526
- rapierJoint: imp,
527
- parentBody,
528
- childBody
648
+ function resetDisabledRotors(handle, opts) {
649
+ if (opts.wheelsAllOff) resetWheelHits(handle);
650
+ else if (opts.frontOff || opts.rearOff) resetWheelHits(handle, (name) => name && opts.frontWheelNames.has(name) ? opts.frontOff : opts.rearOff);
651
+ if (opts.propsOff) resetPropellerOutputs(handle);
652
+ }
653
+ function RotorVisualSlot({ object, center, quaternion, scene, origin }) {
654
+ const slotRef = useRef(null);
655
+ useLayoutEffect(() => {
656
+ const slot = slotRef.current;
657
+ if (!slot?.parent) return;
658
+ const snap = origin ?? captureSubtreeOrigins([object], scene).get(object);
659
+ scene.updateMatrixWorld(true);
660
+ const localMat = computeRotorLocalMatrix(object, scene, center, quaternion);
661
+ if (snap.origParent) snap.origParent.remove(object);
662
+ const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
663
+ localMat.decompose(pos, quat, scl);
664
+ object.position.copy(pos);
665
+ object.quaternion.copy(quat.normalize());
666
+ object.scale.copy(scl);
667
+ slot.add(object);
668
+ const untrack = registerMountedSubtree(snap.ownerScene, () => {
669
+ const p = object.position.clone(), q = object.quaternion.clone(), s = object.scale.clone();
670
+ if (object.parent === slot) slot.remove(object);
671
+ restoreSubtreeOrigin(object, snap);
672
+ return () => {
673
+ if (snap.origParent) snap.origParent.remove(object);
674
+ object.position.copy(p);
675
+ object.quaternion.copy(q);
676
+ object.scale.copy(s);
677
+ slot.add(object);
678
+ };
529
679
  });
530
- rtRef.current = rt;
531
- registry?.add(rt);
532
- onJointReady(rt.nodeName, part.spec.object, rt);
533
680
  return () => {
534
- rtRef.current = null;
535
- registry?.delete(rt);
536
- onJointReady(rt.nodeName, part.spec.object, null);
537
- if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
681
+ untrack();
682
+ if (object.parent === slot) slot.remove(object);
683
+ restoreSubtreeOrigin(object, snap);
538
684
  };
539
685
  }, [
540
- rapier,
541
- world,
542
- part,
543
- parentBody,
544
- childBody,
545
- registry,
546
- onJointReady
686
+ object,
687
+ center,
688
+ quaternion,
689
+ scene,
690
+ origin
547
691
  ]);
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]);
551
- const linVel = part.spec.linearVelocity ?? linearVelocity;
552
- const angVel = part.spec.angularVelocity ?? angularVelocity;
553
- const gravScale = part.spec.gravityFactor ?? gravityScale;
554
- return /* @__PURE__ */ jsxs(RigidBody, {
555
- ref: assignChildRef,
556
- type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
557
- position: worldPose.pos,
558
- quaternion: worldPose.quat,
559
- colliders: false,
560
- userData: ATTACHED_PANEL_USER_DATA,
561
- onContactForce: onForce,
562
- ...linVel ? { linearVelocity: linVel } : {},
563
- ...angVel ? { angularVelocity: angVel } : {},
564
- ...gravScale === void 0 ? {} : { gravityScale: gravScale },
565
- children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
566
- object: part.spec.object,
567
- position: [
568
- 0,
569
- 0,
570
- 0
571
- ],
572
- quaternion: part.restRelChassisQuat,
573
- origin
574
- }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
575
- c: col.spec,
576
- position: col.position,
577
- quaternion: col.quaternion,
578
- massProperties: col.massProperties
579
- }, `vj_${part.spec.nodeName}:${cIdx}`))]
580
- });
581
- }
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 }) {
588
- const { world } = useRapier();
589
- const applyGravityField = useCustomGravity((state) => state.applyGravityField);
590
- const parts = useMemo(() => planVehicleJointParts(bodies), [bodies]);
591
- const origins = useMemo(() => parts.length > 0 ? captureSubtreeOrigins(parts.map((p) => p.spec.object), bundleScene) : null, [parts, bundleScene]);
592
- const bodyMapRef = useRef(/* @__PURE__ */ new Map());
593
- const [partBodies, setPartBodies] = useState(() => /* @__PURE__ */ new Map());
594
- const runtimeMapRef = useRef(/* @__PURE__ */ new Map());
595
- const byObjectRef = useRef(/* @__PURE__ */ new Map());
596
- useFrame(() => {
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);
599
- });
600
- const handleBody = useCallback((nodeName, rb) => {
601
- if (rb) bodyMapRef.current.set(nodeName, rb);
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
- });
610
- }, []);
611
- const handleJointReady = useCallback((nodeName, obj, rt) => {
612
- if (rt) {
613
- runtimeMapRef.current.set(nodeName, rt);
614
- byObjectRef.current.set(obj, rt);
615
- } else {
616
- runtimeMapRef.current.delete(nodeName);
617
- byObjectRef.current.delete(obj);
618
- }
619
- }, []);
620
- useImperativeHandle(jointsRef, () => ({
621
- get hasJoints() {
622
- return parts.length > 0;
623
- },
624
- get jointNames() {
625
- return parts.map((p) => p.spec.nodeName);
626
- },
627
- getBody: (nodeName) => bodyMapRef.current.get(nodeName) ?? null,
628
- getJointRuntime: (nodeName) => runtimeMapRef.current.get(nodeName) ?? null,
629
- getJointAngle: (nodeName) => runtimeMapRef.current.get(nodeName)?.getCoordinate() ?? null,
630
- setJointTarget: (nodeName, target) => {
631
- runtimeMapRef.current.get(nodeName)?.applyTarget(target);
632
- },
633
- setRoleTarget: (role, target) => {
634
- for (const rt of runtimeMapRef.current.values()) if (rt.role === role) rt.applyTarget(target);
635
- },
636
- toggleHitObject: (hit) => {
637
- for (let cur = hit; cur; cur = cur.parent) {
638
- const rt = byObjectRef.current.get(cur);
639
- if (rt && rt.limits && rt.drive?.stiffness !== void 0) {
640
- rt.applyTarget(isJointOpen(rt) ? 0 : openTargetForLimits(rt.limits));
641
- return true;
642
- }
643
- }
644
- return false;
645
- },
646
- toggleRolePrefix: (prefix) => {
647
- const low = prefix.toLowerCase();
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)));
649
- if (matches.length === 0) return;
650
- const anyOpen = matches.some((rt) => isJointOpen(rt));
651
- for (const rt of matches) rt.applyTarget(anyOpen ? 0 : openTargetForLimits(rt.limits));
652
- },
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
- }
693
- }), [parts, vehicleRef]);
694
- if (parts.length === 0) return null;
695
- return /* @__PURE__ */ jsx(Fragment, { children: parts.map((part) => /* @__PURE__ */ jsx(VehicleArticulatedPanel, {
696
- part,
697
- spawnPos,
698
- spawnQuat,
699
- linearVelocity,
700
- angularVelocity,
701
- gravityScale,
702
- parentBody: part.parent ? partBodies.get(part.parent.spec.nodeName) ?? null : chassisBody ?? vehicleRef.current?.body ?? null,
703
- origin: origins?.get(part.spec.object),
704
- onBody: handleBody,
705
- onJointReady: handleJointReady
706
- }, part.spec.nodeName)) });
692
+ return /* @__PURE__ */ jsx("group", { ref: slotRef });
707
693
  }
708
694
  function hasActiveMovement(m) {
709
695
  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));
@@ -721,7 +707,10 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
721
707
  const zeroGRef = useRef(isZeroG);
722
708
  const [chassisBody, setChassisBody] = useState(null);
723
709
  const chassis = useMemo(() => computeChassisMassProps(bundle.bodies), [bundle]);
724
- const collidersList = useMemo(() => buildChassisColliders(bundle.bodies, chassis), [bundle.bodies, chassis]);
710
+ const collidersList = useMemo(() => buildChassisColliders(bundle.bodies), [bundle.bodies]);
711
+ useEffect(() => {
712
+ if (chassisBody) applyRapierBodyMass(chassisBody, chassis.lumpedMass);
713
+ }, [chassisBody, chassis.lumpedMass]);
725
714
  const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, bundle.totalDynamicMass, bundle.centerOfMass, .7, refGrav), [
726
715
  bundle.wheels,
727
716
  bundle.totalDynamicMass,
@@ -736,11 +725,11 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
736
725
  const forwardSign = useMemo(() => {
737
726
  const steered = solvedWheels.filter((w) => w.tag.steer && !w.tag.steerInvert);
738
727
  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)), [
728
+ return steered.reduce((s, w) => s + w.mountPos[2], 0) / steered.length < bundle.centerOfMass[2] - .001 ? -1 : 1;
729
+ }, [solvedWheels, bundle.centerOfMass]);
730
+ const frontWheelNames = useMemo(() => new Set(solvedWheels.filter((w) => (w.mountPos[2] - bundle.centerOfMass[2]) * forwardSign >= 0).map((w) => w.tag.nodeName)), [
742
731
  solvedWheels,
743
- chassis.com,
732
+ bundle.centerOfMass,
744
733
  forwardSign
745
734
  ]);
746
735
  const wheelsAllOff = !enable || isZeroG || wheelConfig?.enable === false && frontWheelConfig?.enable !== true && rearWheelConfig?.enable !== true;
@@ -871,10 +860,7 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
871
860
  owner: "KhrVehicle"
872
861
  }),
873
862
  children,
874
- collidersList.map(({ key, spec, massProperties }) => /* @__PURE__ */ jsx(KhrCollider, {
875
- c: spec,
876
- massProperties
877
- }, key)),
863
+ collidersList.map(({ key, spec }) => /* @__PURE__ */ jsx(KhrCollider, { c: spec }, key)),
878
864
  solvedWheels.map(({ tag, cornerMassKg, springK, dampingC, mountPos }) => {
879
865
  const axleCfg = frontWheelNames.has(tag.nodeName) ? frontWheelConfig : rearWheelConfig;
880
866
  const wheelVol = Math.max(Math.PI * tag.radius * tag.radius * tag.width, 1e-6);
@@ -983,9 +969,10 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
983
969
  linearVelocity: effLinVel,
984
970
  angularVelocity: effAngVel,
985
971
  gravityScale: effGravScale,
972
+ userData: ecctrlRest.userData,
986
973
  jointsRef
987
974
  })] });
988
975
  }
989
- export { KhrVehicle, solveWheelLoads };
976
+ export { KhrVehicle, mergeVehiclePanelUserData, solveWheelLoads };
990
977
 
991
978
  //# sourceMappingURL=vehicle.js.map