@khr3/core 0.1.5 → 0.2.0

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 (44) hide show
  1. package/README.md +3 -114
  2. package/dist/BundleSceneHost-DUqqPtJF.js +1036 -0
  3. package/dist/BundleSceneHost-DUqqPtJF.js.map +1 -0
  4. package/dist/KhrCollider.d.ts +1 -1
  5. package/dist/KhrVehicle.d.ts +5 -7
  6. package/dist/PhysicsWorld.d.ts +2 -2
  7. package/dist/assemblyPlan.d.ts +2 -0
  8. package/dist/curves.d.ts +11 -32
  9. package/dist/curves.js +141 -139
  10. package/dist/curves.js.map +1 -0
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.js +1639 -1240
  13. package/dist/index.js.map +1 -0
  14. package/dist/jointDynamics.d.ts +1 -1
  15. package/dist/khrBundleFinalize.d.ts +14 -0
  16. package/dist/khrConfigTypes.d.ts +62 -0
  17. package/dist/khrExportEncoders.d.ts +8 -0
  18. package/dist/khrExporter.d.ts +2 -1
  19. package/dist/khrExtras.d.ts +3 -3
  20. package/dist/khrGlb.d.ts +23 -0
  21. package/dist/khrJointParser.d.ts +3 -0
  22. package/dist/khrLoader.d.ts +2 -1
  23. package/dist/khrParsers.d.ts +5 -9
  24. package/dist/khrPlugin.d.ts +2 -3
  25. package/dist/khrPluginHelpers.d.ts +4 -0
  26. package/dist/khrRotorDecoders.d.ts +4 -0
  27. package/dist/khrShapeParser.d.ts +8 -0
  28. package/dist/khrTypes.d.ts +11 -103
  29. package/dist/khrVehicleChassis.d.ts +9 -17
  30. package/dist/khrVehicleJointHelpers.d.ts +24 -0
  31. package/dist/khrVehicleJoints.d.ts +18 -0
  32. package/dist/khrVehicleRotors.d.ts +22 -0
  33. package/dist/khrVehicleSlots.d.ts +19 -15
  34. package/dist/khrVehicleTypes.d.ts +52 -0
  35. package/dist/pacejka.d.ts +1 -1
  36. package/dist/physicsEcs.d.ts +2 -7
  37. package/dist/useKhrGlb.d.ts +2 -2
  38. package/dist/vehicle.d.ts +2 -2
  39. package/dist/vehicle.js +757 -451
  40. package/dist/vehicle.js.map +1 -0
  41. package/dist/wheelLoads.d.ts +4 -7
  42. package/docs/api-reference.md +209 -0
  43. package/package.json +8 -7
  44. package/dist/BundleSceneHost-CE3HPB8a.js +0 -556
package/dist/vehicle.js CHANGED
@@ -1,34 +1,33 @@
1
- import { C as e, S as t, T as n, a as r, b as i, d as a, f as o, i as s, r as c, t as l, x as u } from "./BundleSceneHost-CE3HPB8a.js";
2
- import { useCallback as d, useContext as f, useEffect as p, useLayoutEffect as m, useMemo as h, useRef as g, useState as _ } from "react";
3
- import { useFrame as v } from "@react-three/fiber";
4
- import { useAfterPhysicsStep as y, useRapier as b } from "@react-three/rapier";
5
- import * as x from "three";
6
- import { jsx as S, jsxs as C } from "react/jsx-runtime";
7
- import { useCustomGravity as w } from "@pinkaphant/ecctrl/gravity";
8
- import { EcctrlVehicle as T, ShapeCastWheel as ee, ThrustPropeller as te } from "@pinkaphant/ecctrl/vehicle";
1
+ import { C as effectiveJointInertia, D as bodyPoseMatrix, E as KhrValidationError, O as computeLumpedMassProps, S as WorldGravityContext, i as restoreSubtreeOrigin, m as assertUnitScale, o as toColliderMass, p as assertSceneIdentityWorldScale, r as captureSubtreeOrigins, s as KhrCollider, t as BundleSceneHost, x as JointRegistryContext } from "./BundleSceneHost-DUqqPtJF.js";
2
+ import React, { useCallback, useContext, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { useFrame } from "@react-three/fiber";
4
+ import { useRapier } from "@react-three/rapier";
5
+ import * as THREE from "three";
6
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
+ import { EcctrlVehicle, ShapeCastWheel, ThrustPropeller } from "@pinkaphant/ecctrl/vehicle";
8
+ import { useCustomGravity } from "@pinkaphant/ecctrl/gravity";
9
9
  // src/khrVehicleChassis.ts
10
- var E = new x.Euler(), D = new x.Quaternion(), O = new x.Matrix4(), k = new x.Vector3(), A = new x.Vector3(1, 1, 1);
11
- function j(t, n) {
12
- if (n !== void 0) throw new e(`KhrVehicle: colliders prop cannot be overridden (got ${JSON.stringify(n)}); colliders are authored in the .glb`);
13
- o(t, "KhrVehicle");
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");
14
13
  }
15
- function M(e) {
16
- if (typeof e == "number") return [
17
- e,
18
- e,
19
- e
14
+ function readPosTuple(pos) {
15
+ if (typeof pos === "number") return [
16
+ pos,
17
+ pos,
18
+ pos
20
19
  ];
21
- if (Array.isArray(e)) return [
22
- e[0] ?? 0,
23
- e[1] ?? 0,
24
- e[2] ?? 0
20
+ if (Array.isArray(pos)) return [
21
+ Number(pos[0] ?? 0),
22
+ Number(pos[1] ?? 0),
23
+ Number(pos[2] ?? 0)
25
24
  ];
26
- if (e && typeof e == "object" && "x" in e) {
27
- let t = e;
25
+ if (pos && typeof pos === "object" && "x" in pos) {
26
+ const v = pos;
28
27
  return [
29
- t.x,
30
- t.y,
31
- t.z
28
+ Number(v.x ?? 0),
29
+ Number(v.y ?? 0),
30
+ Number(v.z ?? 0)
32
31
  ];
33
32
  }
34
33
  return [
@@ -37,474 +36,781 @@ function M(e) {
37
36
  0
38
37
  ];
39
38
  }
40
- function N(e, t) {
41
- return t === void 0 ? e === void 0 ? [
39
+ function readSpawnQuat(rotation, quaternion) {
40
+ if (quaternion) {
41
+ if (Array.isArray(quaternion)) {
42
+ const q = new THREE.Quaternion(Number(quaternion[0] ?? 0), Number(quaternion[1] ?? 0), Number(quaternion[2] ?? 0), Number(quaternion[3] ?? 1)).normalize();
43
+ return [
44
+ q.x,
45
+ q.y,
46
+ q.z,
47
+ q.w
48
+ ];
49
+ }
50
+ if (typeof quaternion === "object" && "x" in quaternion) {
51
+ const qObj = quaternion;
52
+ const q = new THREE.Quaternion(qObj.x, qObj.y, qObj.z, qObj.w).normalize();
53
+ return [
54
+ q.x,
55
+ q.y,
56
+ q.z,
57
+ q.w
58
+ ];
59
+ }
60
+ }
61
+ if (rotation) {
62
+ const euler = new THREE.Euler();
63
+ if (rotation instanceof THREE.Euler) euler.copy(rotation);
64
+ else if (Array.isArray(rotation)) euler.set(Number(rotation[0] ?? 0), Number(rotation[1] ?? 0), Number(rotation[2] ?? 0), typeof rotation[3] === "string" ? rotation[3] : "XYZ");
65
+ else if (typeof rotation === "object" && "x" in rotation) {
66
+ const rObj = rotation;
67
+ euler.set(Number(rObj.x ?? 0), Number(rObj.y ?? 0), Number(rObj.z ?? 0), rObj.order ?? "XYZ");
68
+ }
69
+ const q = new THREE.Quaternion().setFromEuler(euler).normalize();
70
+ return [
71
+ q.x,
72
+ q.y,
73
+ q.z,
74
+ q.w
75
+ ];
76
+ }
77
+ return [
42
78
  0,
43
79
  0,
44
80
  0,
45
81
  1
46
- ] : (typeof e == "number" ? E.set(e, e, e, "XYZ") : Array.isArray(e) ? E.set(e[0], e[1], e[2], e[3] ?? "XYZ") : typeof e == "object" && "x" in e ? E.copy(e) : E.set(0, 0, 0, "XYZ"), D.setFromEuler(E), [
47
- D.x,
48
- D.y,
49
- D.z,
50
- D.w
51
- ]) : (Array.isArray(t) ? D.set(t[0], t[1], t[2], t[3]) : typeof t == "object" && "x" in t ? D.copy(t) : D.identity(), D.lengthSq() > 0 && D.normalize(), [
52
- D.x,
53
- D.y,
54
- D.z,
55
- D.w
56
- ]);
82
+ ];
57
83
  }
58
- function ne(t) {
59
- let r = t.filter((e) => !e.isKinematic), i = n(r);
60
- if (!i) throw new e("KhrVehicle: bundle has no dynamic KHR motion.mass; author a dynamic chassis node with mass");
61
- let { mass: a, com: o, inertia: s, inertiaFrame: c } = i;
62
- if (!(s[0] > 0 && s[1] > 0 && s[2] > 0)) throw new e(`KhrVehicle: authored inertia is non-positive [${s.join(", ")}]`);
63
- let l = r.find((e) => e.joint === null) ?? r[0], u = r.filter((e) => e.gravityFactor !== void 0).map((e) => e.gravityFactor), d;
64
- if (u.length > 0) {
65
- if (u.some((e) => Math.abs(e - u[0]) > 1e-6)) throw new e("KhrVehicle: dynamic chassis bodies have conflicting motion.gravityFactor values");
66
- d = u[0];
84
+ function computeChassisMassProps(bodies) {
85
+ const dyn = bodies.filter((b) => !b.isKinematic);
86
+ if (dyn.length === 0) throw new KhrValidationError("KhrVehicle: bundle has no dynamic rigid body for the chassis");
87
+ const lumped = computeLumpedMassProps(dyn);
88
+ if (!lumped || !(lumped.mass > 0)) throw new KhrValidationError("KhrVehicle: chassis dynamic mass must be positive");
89
+ if (!lumped.inertia.every((v) => Number.isFinite(v) && v > 0)) throw new KhrValidationError("KhrVehicle: chassis principal inertia must be positive and finite");
90
+ let gravityFactor;
91
+ if (dyn.some((b) => b.gravityFactor !== void 0)) {
92
+ const g0 = dyn[0].gravityFactor ?? 1;
93
+ for (const b of dyn) if (Math.abs((b.gravityFactor ?? 1) - g0) > 1e-6) throw new KhrValidationError(`KhrVehicle: all dynamic chassis bodies must share gravityFactor (got ${g0} vs ${b.gravityFactor ?? 1} on "${b.nodeName}")`);
94
+ gravityFactor = g0;
67
95
  }
68
- let f = r.filter((e) => e.linearVelocity !== void 0), p;
69
- if (f.length === 1) p = f[0].linearVelocity;
70
- else if (f.length > 1) {
71
- let e = f.reduce((e, t) => e + t.mass, 0);
72
- p = [
73
- f.reduce((e, t) => e + t.linearVelocity[0] * t.mass, 0) / e,
74
- f.reduce((e, t) => e + t.linearVelocity[1] * t.mass, 0) / e,
75
- f.reduce((e, t) => e + t.linearVelocity[2] * t.mass, 0) / e
96
+ let linearVelocity;
97
+ if (dyn.some((b) => b.linearVelocity !== void 0)) {
98
+ let vx = 0;
99
+ let vy = 0;
100
+ let vz = 0;
101
+ for (const b of dyn) {
102
+ const lv = b.linearVelocity ?? [
103
+ 0,
104
+ 0,
105
+ 0
106
+ ];
107
+ vx += lv[0] * b.mass;
108
+ vy += lv[1] * b.mass;
109
+ vz += lv[2] * b.mass;
110
+ }
111
+ linearVelocity = [
112
+ vx / lumped.mass,
113
+ vy / lumped.mass,
114
+ vz / lumped.mass
76
115
  ];
77
116
  }
78
- let m = r.filter((e) => e.angularVelocity !== void 0), h = m.length === 1 ? m[0].angularVelocity : l.angularVelocity ?? m[0]?.angularVelocity;
117
+ const rootDyn = dyn.find((b) => !b.joint && b.angularVelocity !== void 0) ?? dyn.find((b) => b.angularVelocity !== void 0);
118
+ const angularVelocity = rootDyn?.angularVelocity ? [
119
+ rootDyn.angularVelocity[0],
120
+ rootDyn.angularVelocity[1],
121
+ rootDyn.angularVelocity[2]
122
+ ] : void 0;
79
123
  return {
80
- mass: a,
81
- com: o,
82
- inertia: s,
83
- inertiaFrame: c,
84
- ...p ? { linearVelocity: p } : {},
85
- ...h ? { angularVelocity: h } : {},
86
- ...d === void 0 ? {} : { gravityFactor: d }
124
+ mass: lumped.mass,
125
+ com: lumped.com,
126
+ inertia: lumped.inertia,
127
+ inertiaFrame: lumped.inertiaFrame,
128
+ ...linearVelocity ? { linearVelocity } : {},
129
+ ...angularVelocity ? { angularVelocity } : {},
130
+ ...gravityFactor !== void 0 ? { gravityFactor } : {}
87
131
  };
88
132
  }
89
- function re(e, t) {
90
- let n = new x.Vector3(), r = new x.Quaternion(), i = new x.Vector3(), a = new x.Quaternion(), o = new x.Quaternion();
91
- return e.flatMap((e) => (n.fromArray(e.localPosition), r.fromArray(e.localQuaternion), e.colliders.map((s, c) => (i.fromArray(s.localPosition).applyQuaternion(r).add(n), a.copy(r).multiply(o.fromArray(s.localQuaternion)), {
92
- key: `${e.nodeName}-${c}`,
93
- spec: {
94
- shape: s.shape,
95
- localPosition: [
96
- i.x - t[0],
97
- i.y - t[1],
98
- i.z - t[2]
99
- ],
100
- localQuaternion: [
101
- a.x,
102
- a.y,
103
- a.z,
104
- a.w
105
- ],
106
- ...s.friction === void 0 ? {} : { friction: s.friction },
107
- ...s.restitution === void 0 ? {} : { restitution: s.restitution },
108
- ...s.collisionGroups === void 0 ? {} : { collisionGroups: s.collisionGroups }
133
+ function buildChassisColliders(bodies, chassis) {
134
+ const out = [];
135
+ const one = new THREE.Vector3(1, 1, 1);
136
+ const pos = new THREE.Vector3();
137
+ const quat = new THREE.Quaternion();
138
+ const scl = new THREE.Vector3();
139
+ for (const b of bodies) {
140
+ if (b.isKinematic || b.joint !== null) continue;
141
+ const bodyMat = bodyPoseMatrix(b);
142
+ for (let idx = 0; idx < b.colliders.length; idx++) {
143
+ const c = b.colliders[idx];
144
+ const colMat = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(c.localPosition), new THREE.Quaternion().fromArray(c.localQuaternion), one);
145
+ bodyMat.clone().multiply(colMat).decompose(pos, quat, scl);
146
+ quat.normalize();
147
+ const isFirst = out.length === 0;
148
+ const rigidColMat = isFirst ? new THREE.Matrix4().compose(pos, quat, one) : void 0;
149
+ out.push({
150
+ key: `${b.nodeName}:${idx}`,
151
+ spec: {
152
+ ...c,
153
+ localPosition: [
154
+ pos.x,
155
+ pos.y,
156
+ pos.z
157
+ ],
158
+ localQuaternion: [
159
+ quat.x,
160
+ quat.y,
161
+ quat.z,
162
+ quat.w
163
+ ]
164
+ },
165
+ ...isFirst ? { massProperties: toColliderMass(chassis, rigidColMat, quat.clone()) } : {}
166
+ });
109
167
  }
110
- }))));
111
- }
112
- function ie(t, n, r, i) {
113
- let a = new x.Matrix4();
114
- for (let r = t; r && r !== n; r = r.parent) {
115
- if (!r.parent) throw new e(`KhrVehicle: rotor node "${t.name}" is detached from bundle.scene`);
116
- r.updateMatrix(), a.premultiply(r.matrix);
117
168
  }
118
- return k.set(r[0], r[1], r[2]), i ? D.set(i[0], i[1], i[2], i[3]).normalize() : D.identity(), O.compose(k, D, A).invert().clone().multiply(a);
169
+ if (out.length === 0) throw new KhrValidationError("KhrVehicle: chassis has no colliders");
170
+ return out;
119
171
  }
120
- function ae(e, t, n, r, i, a) {
121
- let o = e[t], s;
122
- if (r || i) {
123
- let t = !1, n = !1, a = 0;
124
- for (let r of e) r.steer ? t = !0 : n = !0, a += r.position[2];
125
- if (t && n) s = o.steer ? r : i;
126
- else {
127
- let t = o.position[2] - a / e.length;
128
- t > 1e-4 ? s = r : t < -1e-4 && (s = i);
129
- }
172
+ function computeRotorLocalMatrix(node, scene, center, quaternion) {
173
+ const nodeToScene = new THREE.Matrix4();
174
+ let cur = node;
175
+ while (cur && cur !== scene) {
176
+ if (!cur.parent) throw new KhrValidationError(`Rotor node "${node.name}" is detached from bundle.scene`);
177
+ cur.updateMatrix();
178
+ nodeToScene.premultiply(cur.matrix);
179
+ cur = cur.parent;
130
180
  }
131
- let c = typeof a == "function" ? a(o, t) : a?.[o.nodeName];
132
- if (n || s || c) return {
133
- ...n,
134
- ...s,
135
- ...c
136
- };
181
+ if (cur !== scene && node !== scene) throw new KhrValidationError(`Rotor node "${node.name}" is not under bundle.scene`);
182
+ 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
+ }
184
+ // src/khrVehicleJointHelpers.ts
185
+ function isJointDescendant(body, ancestorName, byName) {
186
+ for (let cur = body.joint ? byName.get(body.joint.connectedNodeName) : void 0; cur; cur = cur.joint ? byName.get(cur.joint.connectedNodeName) : void 0) if (cur.nodeName === ancestorName) return true;
187
+ return false;
137
188
  }
138
- function oe(e, t, n, r) {
139
- let i = typeof r == "function" ? r(e, t) : r?.[e.nodeName];
140
- if (n || i) return {
141
- ...n,
142
- ...i
189
+ function planVehicleJointParts(bodies) {
190
+ const dyn = bodies.filter((b) => !b.isKinematic);
191
+ const byName = new Map(dyn.map((b) => [b.nodeName, b]));
192
+ const jointed = dyn.filter((b) => b.joint !== null);
193
+ if (jointed.length === 0) return [];
194
+ const depthOf = (b, seen = /* @__PURE__ */ new Set()) => {
195
+ if (!b.joint) return 0;
196
+ if (seen.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
197
+ seen.add(b.nodeName);
198
+ const parent = byName.get(b.joint.connectedNodeName);
199
+ if (!parent) throw new KhrValidationError(`Vehicle joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a dynamic KHR body`);
200
+ return 1 + depthOf(parent, seen);
143
201
  };
202
+ jointed.sort((a, b) => depthOf(a) - depthOf(b));
203
+ const one = new THREE.Vector3(1, 1, 1);
204
+ const pos = new THREE.Vector3();
205
+ const quat = new THREE.Quaternion();
206
+ const scl = new THREE.Vector3();
207
+ const partByName = /* @__PURE__ */ new Map();
208
+ return jointed.map((b) => {
209
+ const joint = b.joint;
210
+ const parent = partByName.get(joint.connectedNodeName) ?? null;
211
+ const bodyMat = bodyPoseMatrix(b);
212
+ const restRelParent = parent ? bodyPoseMatrix(parent.spec).clone().invert().multiply(bodyMat) : bodyMat;
213
+ const descendants = jointed.filter((d) => d !== b && isJointDescendant(d, b.nodeName, byName));
214
+ const colliders = b.colliders.map((spec) => {
215
+ const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
216
+ const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one);
217
+ bodyMat.clone().multiply(local).decompose(pos, quat, scl);
218
+ quat.normalize();
219
+ return {
220
+ spec,
221
+ local,
222
+ position: [
223
+ pos.x,
224
+ pos.y,
225
+ pos.z
226
+ ],
227
+ quaternion: [
228
+ quat.x,
229
+ quat.y,
230
+ quat.z,
231
+ quat.w
232
+ ]
233
+ };
234
+ });
235
+ const plan = {
236
+ spec: b,
237
+ joint,
238
+ parent,
239
+ restRelParent,
240
+ inertia: effectiveJointInertia(b, joint, descendants),
241
+ colliders
242
+ };
243
+ partByName.set(b.nodeName, plan);
244
+ return plan;
245
+ });
144
246
  }
145
- // src/khrVehicleSlots.tsx
146
- var P = new x.Vector3();
147
- function F(e) {
148
- e.rayHit !== null && (e.rayHit = null, e.floatImp.set(0, 0, 0), e.lngFricImp.set(0, 0, 0), e.latFricImp.set(0, 0, 0));
247
+ function openTargetForLimits(limits) {
248
+ return Math.abs(limits[0]) > Math.abs(limits[1]) ? limits[0] : limits[1];
249
+ }
250
+ function isVehicleJointOpen(rt) {
251
+ if (!rt.limits) return false;
252
+ const openTgt = openTargetForLimits(rt.limits);
253
+ return Math.abs(openTgt) > 1e-6 && Math.abs((rt.positionTarget ?? rt.q) - openTgt) < Math.abs(openTgt) * .5;
149
254
  }
150
- var se = c;
151
- function ce({ object: e, center: t, quaternion: n, scene: r, origin: i }) {
152
- let a = g(null);
153
- return m(() => {
154
- let o = a.current?.parent;
155
- if (!o) return;
156
- let l = i ?? c([e]).get(e), u = ie(e, r, t, n);
157
- return l.origParent && l.origParent.remove(e), u.decompose(e.position, e.quaternion, e.scale), o.add(e), () => {
158
- e.parent === o && o.remove(e), s(e, l);
255
+ function createVehicleJointRuntime(part, assemblyId, parent, colliderRefs) {
256
+ const drive = part.joint.drive;
257
+ return {
258
+ assemblyId,
259
+ nodeName: part.spec.nodeName,
260
+ role: part.joint.role,
261
+ kind: part.joint.kind,
262
+ object: part.spec.object,
263
+ axis: new THREE.Vector3().fromArray(part.joint.axis).normalize(),
264
+ restPosition: part.spec.object.position.clone(),
265
+ restQuaternion: part.spec.object.quaternion.clone(),
266
+ q: 0,
267
+ v: 0,
268
+ positionTarget: drive?.positionTarget ?? null,
269
+ velocityTarget: drive?.velocityTarget ?? 0,
270
+ drive,
271
+ limits: part.joint.limits,
272
+ limitStiffness: part.joint.limitStiffness ?? null,
273
+ limitDamping: part.joint.limitDamping ?? 0,
274
+ inertia: part.inertia,
275
+ parent,
276
+ restRelParent: part.restRelParent,
277
+ current: part.restRelParent.clone(),
278
+ stamp: -1,
279
+ colliders: part.colliders.map((c, idx) => ({
280
+ ref: colliderRefs[idx],
281
+ local: c.local
282
+ }))
283
+ };
284
+ }
285
+ // src/khrVehicleJoints.tsx
286
+ var nextVehicleJointAssemblyId = 1e5;
287
+ function KhrVehicleJoints({ bodies, vehicleRef, jointsRef }) {
288
+ const registry = useContext(JointRegistryContext);
289
+ const assemblyId = useMemo(() => nextVehicleJointAssemblyId++, []);
290
+ const parts = useMemo(() => planVehicleJointParts(bodies), [bodies]);
291
+ const colliderRefs = useMemo(() => parts.map((p) => p.colliders.map(() => ({ current: null }))), [parts]);
292
+ const runtimeMapRef = React.useRef(/* @__PURE__ */ new Map());
293
+ const byObjectRef = React.useRef(/* @__PURE__ */ new Map());
294
+ useLayoutEffect(() => {
295
+ const map = /* @__PURE__ */ new Map();
296
+ const byObj = /* @__PURE__ */ new Map();
297
+ for (let i = 0; i < parts.length; i++) {
298
+ const part = parts[i];
299
+ const parent = part.parent ? map.get(part.parent.spec.nodeName) ?? null : null;
300
+ const rt = createVehicleJointRuntime(part, assemblyId, parent, colliderRefs[i]);
301
+ map.set(rt.nodeName, rt);
302
+ byObj.set(rt.object, rt);
303
+ registry?.add(rt);
304
+ }
305
+ runtimeMapRef.current = map;
306
+ byObjectRef.current = byObj;
307
+ return () => {
308
+ runtimeMapRef.current = /* @__PURE__ */ new Map();
309
+ byObjectRef.current = /* @__PURE__ */ new Map();
310
+ for (const rt of map.values()) {
311
+ registry?.delete(rt);
312
+ rt.object.position.copy(rt.restPosition);
313
+ rt.object.quaternion.copy(rt.restQuaternion);
314
+ }
159
315
  };
160
316
  }, [
161
- e,
162
- t,
163
- n,
164
- r,
165
- i
166
- ]), /* @__PURE__ */ S("group", { ref: a });
317
+ parts,
318
+ colliderRefs,
319
+ assemblyId,
320
+ registry
321
+ ]);
322
+ useImperativeHandle(jointsRef, () => {
323
+ const applyTarget = (rt, target) => {
324
+ if (!rt.drive || rt.drive.stiffness === void 0) throw new KhrValidationError(`Joint "${rt.nodeName}" has no authored drive stiffness; cannot set a position target`);
325
+ rt.positionTarget = target;
326
+ vehicleRef.current?.body?.wakeUp();
327
+ };
328
+ return {
329
+ get hasJoints() {
330
+ return parts.length > 0;
331
+ },
332
+ get jointNames() {
333
+ return parts.map((p) => p.spec.nodeName);
334
+ },
335
+ getJointAngle: (nodeName) => runtimeMapRef.current.get(nodeName)?.q ?? null,
336
+ setJointTarget: (nodeName, target) => {
337
+ const rt = runtimeMapRef.current.get(nodeName);
338
+ if (rt) applyTarget(rt, target);
339
+ },
340
+ setRoleTarget: (role, target) => {
341
+ for (const rt of runtimeMapRef.current.values()) if (rt.role === role) applyTarget(rt, target);
342
+ },
343
+ toggleHitObject: (hit) => {
344
+ for (let cur = hit; cur; cur = cur.parent) {
345
+ const rt = byObjectRef.current.get(cur);
346
+ if (rt && rt.limits && rt.drive?.stiffness !== void 0) {
347
+ const openTgt = openTargetForLimits(rt.limits);
348
+ applyTarget(rt, isVehicleJointOpen(rt) ? 0 : openTgt);
349
+ return true;
350
+ }
351
+ }
352
+ return false;
353
+ },
354
+ toggleRolePrefix: (prefix) => {
355
+ const low = prefix.toLowerCase();
356
+ 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)));
357
+ if (matches.length === 0) return;
358
+ const anyOpen = matches.some((rt) => isVehicleJointOpen(rt));
359
+ for (const rt of matches) applyTarget(rt, anyOpen ? 0 : openTargetForLimits(rt.limits));
360
+ }
361
+ };
362
+ }, [parts, vehicleRef]);
363
+ if (parts.length === 0) return null;
364
+ return /* @__PURE__ */ jsx(Fragment, { children: parts.map((part, pIdx) => part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
365
+ ref: colliderRefs[pIdx][cIdx],
366
+ c: col.spec,
367
+ position: col.position,
368
+ quaternion: col.quaternion
369
+ }, `vj_${part.spec.nodeName}:${cIdx}`))) });
167
370
  }
168
- function I(e, t) {
169
- let n = 0;
170
- for (let r of e.wheelsInfo.values()) {
171
- let i = r.current;
172
- if (!t.has(i.name ?? "") || !i.rayHit) continue;
173
- let a = Math.min(1, Math.max(-1, i.rayHitNormal.dot(e.upAxis))), o = Math.sqrt(Math.max(0, 1 - a * a));
174
- o > n && (n = o);
371
+ // src/khrVehicleSlots.tsx
372
+ var captureRotorOrigins = captureSubtreeOrigins;
373
+ var _samplePos = new THREE.Vector3();
374
+ function isZeroGravityVec(x, y, z) {
375
+ return x * x + y * y + z * z <= 1e-12;
376
+ }
377
+ function resetAllWheelHits(handle) {
378
+ if (!handle) return;
379
+ for (const wheelRef of handle.wheelsInfo.values()) {
380
+ const w = wheelRef.current;
381
+ if (!w) continue;
382
+ w.rayHit = null;
383
+ w.rayHitBody = null;
384
+ w.floatImp.set(0, 0, 0);
385
+ w.lngFricImp.set(0, 0, 0);
386
+ w.latFricImp.set(0, 0, 0);
387
+ w.lngSlipRatio = 0;
388
+ w.latSlipRatio = 0;
389
+ w.slipStrength = 0;
390
+ w.isOnPlatform = false;
391
+ w.effInertia = 0;
175
392
  }
176
- return n;
177
393
  }
178
- function le({ vehicleRef: e, active: n, hasRenderGravity: r, enableCustomGravity: i, activeWheelNames: a, gravityPrimedRef: o, setGravityPrimed: s, spatialZeroGRef: c, setSpatialZeroG: l }) {
179
- let u = f(t), d = g(0);
180
- return y(() => {
181
- let t = e.current, n = t?.body;
182
- if (!t || !n) return;
183
- let r = !1;
184
- if (i) {
185
- let e = n.translation();
186
- if (P.set(e.x, e.y, e.z), r = w.getState().gravityField(P).lengthSq() <= 1e-12, r) for (let e of t.wheelsInfo.values()) F(e.current);
187
- r !== c.current && (c.current = r, l(r));
394
+ function ZeroGWheelPreGuard({ vehicleRef, enable, enableCustomGravity, spawnPos, wheelActiveRef, zeroGRef, customPrimedRef, needsEpochBumpRef, onZeroGChange, onCustomPrimed, onBumpWheelEpoch }) {
395
+ const { world } = useRapier();
396
+ useFrame(() => {
397
+ if (!enable) return;
398
+ const handle = vehicleRef.current;
399
+ let isZeroG;
400
+ if (enableCustomGravity) {
401
+ if (handle?.body && !handle.body.isSleeping()) isZeroG = handle.gravityMag <= 1e-6;
402
+ else {
403
+ const body = handle?.body;
404
+ if (body) {
405
+ const t = body.translation();
406
+ _samplePos.set(t.x, t.y, t.z);
407
+ } else _samplePos.set(spawnPos[0], spawnPos[1], spawnPos[2]);
408
+ const g = useCustomGravity.getState().gravityField(_samplePos);
409
+ isZeroG = isZeroGravityVec(g.x, g.y, g.z);
410
+ }
411
+ if (!customPrimedRef.current) {
412
+ customPrimedRef.current = true;
413
+ onCustomPrimed();
414
+ }
415
+ } else {
416
+ const g = world.gravity;
417
+ isZeroG = isZeroGravityVec(g.x, g.y, g.z);
188
418
  }
189
- let a = !r && t.gravityMag > 1e-6;
190
- a !== o.current && (o.current = a, s(a));
191
- }), v(() => {
192
- let t = e.current, i = t?.body;
193
- if (!t || !i) return;
194
- for (let e of t.wheelsInfo.values()) {
195
- let t = e.current;
196
- a.has(t.name ?? "") || F(t);
419
+ if (isZeroG !== zeroGRef.current) {
420
+ const wasActive = wheelActiveRef.current;
421
+ zeroGRef.current = isZeroG;
422
+ if (isZeroG && wasActive) needsEpochBumpRef.current = true;
423
+ else if (!isZeroG && needsEpochBumpRef.current) {
424
+ needsEpochBumpRef.current = false;
425
+ onBumpWheelEpoch();
426
+ }
427
+ onZeroGChange(isZeroG);
197
428
  }
198
- if (!n || u !== null && !(u.current > 0)) return;
199
- (r && !c.current && !o.current || (!r || c.current) && t.gravityMag > 1e-6) && i.isSleeping() && i.wakeUp();
200
- let s = t.input, l = Math.abs(s.joystickL?.x ?? 0) > .001, f = Math.abs(s.joystickL?.y ?? 0) > .001, p = Math.abs(s.joystickR?.x ?? 0) > .001 || Math.abs(s.joystickR?.y ?? 0) > .001, m = !!(s.forward || s.backward), h = !!(s.steerLeft || s.steerRight || l), g = !!s.brake, _ = !!(f || p || s.throttleUp || s.throttleDown || s.yawLeft || s.yawRight || s.pitchForward || s.pitchBackward || s.rollLeft || s.rollRight), v = !!m | (h ? 2 : 0) | (g ? 4 : 0) | (_ ? 8 : 0), y = d.current;
201
- d.current = v, i.isSleeping() ? (v & 11 & ~(y & 11) || y & 4 && !g) && i.wakeUp() : (!g && h || g && I(t, a) >= .025) && i.wakeUp();
202
- }), null;
429
+ if (isZeroG) resetAllWheelHits(handle);
430
+ });
431
+ return null;
203
432
  }
204
- // src/wheelLoads.ts
205
- var L = 9.80665;
206
- function R(e) {
207
- let t = e.travel - e.sag, n = e.quaternion;
208
- if (!n) return [
209
- e.position[0],
210
- e.position[1] + t,
211
- e.position[2]
212
- ];
213
- let [r, i, a, o] = n, s = 2 * (r * i - o * a), c = 1 - 2 * (r * r + a * a), l = 2 * (i * a + o * r);
214
- return [
215
- e.position[0] + s * t,
216
- e.position[1] + c * t,
217
- e.position[2] + l * t
218
- ];
433
+ function ZeroGWheelPostGuard({ vehicleRef, zeroGRef }) {
434
+ useFrame(() => {
435
+ if (zeroGRef.current) resetAllWheelHits(vehicleRef.current);
436
+ });
437
+ return null;
219
438
  }
220
- var z = new x.Quaternion(), B = new x.Matrix4();
221
- function ue(t, n, r, i = .7, a, o) {
222
- let s = t.length;
223
- if (s === 0) return [];
224
- if (!Number.isFinite(n) || n <= 0) throw new e(`solveWheelLoads: totalMassKg must be positive finite (got ${n})`);
225
- for (let n of t) if (!Number.isFinite(n.sag) || n.sag < 0 || n.springK === void 0 && n.sag <= 0) throw new e(`solveWheelLoads: wheel "${n.nodeName}" requires positive sag (got ${n.sag})`);
226
- let c = n * L;
227
- if (s === 1) {
228
- let e = t[0], r = e.springK ?? c / e.sag;
229
- return [{
230
- tag: e,
231
- cornerMassKg: n,
232
- springK: r,
233
- dampingC: e.dampingC ?? 2 * i * Math.sqrt(r * n),
234
- mountPos: R(e)
235
- }];
439
+ function RotorVisualSlot({ object, center, quaternion, scene, origin }) {
440
+ const slotRef = useRef(null);
441
+ useLayoutEffect(() => {
442
+ const slot = slotRef.current;
443
+ const parent = slot?.parent ?? null;
444
+ if (!slot || !parent) return;
445
+ const snap = origin ?? captureSubtreeOrigins([object]).get(object);
446
+ scene.updateMatrixWorld(true);
447
+ const localMat = computeRotorLocalMatrix(object, scene, center, quaternion);
448
+ if (snap.origParent) snap.origParent.remove(object);
449
+ const pos = new THREE.Vector3();
450
+ const quat = new THREE.Quaternion();
451
+ const scl = new THREE.Vector3();
452
+ localMat.decompose(pos, quat, scl);
453
+ object.position.copy(pos);
454
+ object.quaternion.copy(quat.normalize());
455
+ object.scale.copy(scl);
456
+ slot.add(object);
457
+ return () => {
458
+ if (object.parent === slot) slot.remove(object);
459
+ restoreSubtreeOrigin(object, snap);
460
+ };
461
+ }, [
462
+ object,
463
+ center,
464
+ quaternion,
465
+ scene,
466
+ origin
467
+ ]);
468
+ return /* @__PURE__ */ jsx("group", { ref: slotRef });
469
+ }
470
+ // src/khrVehicleRotors.tsx
471
+ var G_SI$1 = 9.81;
472
+ var UNSPRUNG_CORNER_RATIO = .035;
473
+ function KhrVehicleRotors({ solvedWheels, propellers, scene, comZ, rotorOrigins, enable, wheelEnable, wheelEpoch = 0, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig }) {
474
+ return /* @__PURE__ */ jsxs(Fragment, { children: [solvedWheels.map(({ tag, cornerMassKg, springK, dampingC, mountPos }) => {
475
+ const axleCfg = mountPos[2] >= comZ ? frontWheelConfig : rearWheelConfig;
476
+ const wheelVol = Math.max(Math.PI * tag.radius * tag.radius * tag.width, 1e-6);
477
+ const wheelModelDensity = tag.wheelDensity ?? UNSPRUNG_CORNER_RATIO * cornerMassKg / wheelVol;
478
+ const tagWheelProps = {
479
+ rayLength: tag.travel,
480
+ rayShapeR: tag.radius,
481
+ rayShapeH: tag.width * .5,
482
+ wheelModelRadius: tag.radius,
483
+ wheelModelDensity,
484
+ springK,
485
+ dampingC,
486
+ steerWheel: tag.steer,
487
+ driveWheel: tag.drive,
488
+ brakeWheel: tag.brake,
489
+ maxBrakeTorque: tag.maxBrakeTorque ?? cornerMassKg * G_SI$1 * tag.radius,
490
+ ...tag.steerInvert !== void 0 ? { steerInvert: tag.steerInvert } : {},
491
+ ...tag.driveInvert !== void 0 ? { driveInvert: tag.driveInvert } : {},
492
+ ...tag.driveTorqueWeight !== void 0 ? { driveTorqueWeight: tag.driveTorqueWeight } : {},
493
+ ...tag.rollingResistanceCoef !== void 0 ? { rollingResistanceCoef: tag.rollingResistanceCoef } : {},
494
+ ...tag.tireGripFactor !== void 0 ? { tireGripFactor: tag.tireGripFactor } : {},
495
+ ...tag.latFrictionEllipseScale !== void 0 ? { latFrictionEllipseScale: tag.latFrictionEllipseScale } : {},
496
+ ...tag.relaxLngRate !== void 0 ? { relaxLngRate: tag.relaxLngRate } : {},
497
+ ...tag.relaxLatRate !== void 0 ? { relaxLatRate: tag.relaxLatRate } : {},
498
+ ...tag.lngSlipRatioCurveData !== void 0 ? { lngSlipRatioCurveData: tag.lngSlipRatioCurveData } : {},
499
+ ...tag.latSlipRatioCurveData !== void 0 ? { latSlipRatioCurveData: tag.latSlipRatioCurveData } : {}
500
+ };
501
+ return /* @__PURE__ */ jsx(ShapeCastWheel, {
502
+ name: tag.nodeName,
503
+ position: mountPos,
504
+ quaternion: tag.quaternion ?? [
505
+ 0,
506
+ 0,
507
+ 0,
508
+ 1
509
+ ],
510
+ enable: wheelEnable,
511
+ ...tagWheelProps,
512
+ ...wheelConfig,
513
+ ...axleCfg,
514
+ children: /* @__PURE__ */ jsx(RotorVisualSlot, {
515
+ object: tag.object,
516
+ center: tag.position,
517
+ quaternion: tag.quaternion,
518
+ scene,
519
+ origin: rotorOrigins.get(tag.object)
520
+ })
521
+ }, `${tag.nodeName}:${wheelEpoch}`);
522
+ }), propellers.map((tag) => /* @__PURE__ */ jsx(ThrustPropeller, {
523
+ name: tag.nodeName,
524
+ position: [
525
+ tag.position[0],
526
+ tag.position[1],
527
+ tag.position[2]
528
+ ],
529
+ quaternion: tag.quaternion ?? [
530
+ 0,
531
+ 0,
532
+ 0,
533
+ 1
534
+ ],
535
+ debug: false,
536
+ enable,
537
+ maxThrust: tag.maxThrust,
538
+ ...tag.torqueRatio !== void 0 ? { torqueRatio: tag.torqueRatio } : {},
539
+ ...tag.invertThrust !== void 0 ? { invertThrust: tag.invertThrust } : {},
540
+ ...tag.invertTorque !== void 0 ? { invertTorque: tag.invertTorque } : {},
541
+ ...propellerConfig,
542
+ children: /* @__PURE__ */ jsx(RotorVisualSlot, {
543
+ object: tag.object,
544
+ center: tag.position,
545
+ quaternion: tag.quaternion,
546
+ scene,
547
+ origin: rotorOrigins.get(tag.object)
548
+ })
549
+ }, tag.nodeName))] });
550
+ }
551
+ // src/wheelLoads.ts
552
+ var G_SI = 9.81;
553
+ function projectToLowerBoundedSimplex(values, lowerBound, totalSum) {
554
+ const n = values.length;
555
+ const shifted = values.map((v) => v - lowerBound);
556
+ const rem = Math.max(0, totalSum - n * lowerBound);
557
+ const sorted = [...shifted].sort((a, b) => b - a);
558
+ let prefix = 0;
559
+ let k = 0;
560
+ let theta = 0;
561
+ for (let i = 0; i < n; i++) {
562
+ prefix += sorted[i];
563
+ const candidate = (prefix - rem) / (i + 1);
564
+ if (sorted[i] - candidate > 0) {
565
+ k = i + 1;
566
+ theta = candidate;
567
+ }
236
568
  }
237
- let l = 0, u = 0;
238
- for (let e of t) l += e.position[0], u += e.position[2];
239
- l /= s, u /= s;
240
- let d = 0, f = 0, p = 0, m = t.map((e) => {
241
- let t = e.position[0] - l, n = e.position[2] - u;
242
- return d += t * t, f += t * n, p += n * n, [t, n];
243
- }), h = (r[0] - l) * c, g = (r[2] - u) * c, _ = d + p, v = d * p - f * f, y = 0, b = 0;
244
- if (v > 1e-6 * _ * _) y = (p * h - f * g) / v, b = (-f * h + d * g) / v;
245
- else if (_ > 1e-12) {
246
- let e = 1 / (_ * _);
247
- y = (d * h + f * g) * e, b = (f * h + p * g) * e;
569
+ if (k === 0) theta = (prefix - rem) / n;
570
+ return shifted.map((v) => lowerBound + Math.max(v - theta, 0));
571
+ }
572
+ function solveCornerMasses(wheels, totalMassKg, com) {
573
+ const n = wheels.length;
574
+ if (n === 0) return [];
575
+ if (n === 1) return [totalMassKg];
576
+ const mBase = totalMassKg / n;
577
+ const xs = wheels.map((w) => w.position[0] - com[0]);
578
+ const zs = wheels.map((w) => w.position[2] - com[2]);
579
+ const meanX = xs.reduce((s, v) => s + v, 0) / n;
580
+ const meanZ = zs.reduce((s, v) => s + v, 0) / n;
581
+ const cx = xs.map((v) => v - meanX);
582
+ const cz = zs.map((v) => v - meanZ);
583
+ let sxx = 0;
584
+ let szz = 0;
585
+ let sxz = 0;
586
+ for (let i = 0; i < n; i++) {
587
+ sxx += cx[i] * cx[i];
588
+ szz += cz[i] * cz[i];
589
+ sxz += cx[i] * cz[i];
248
590
  }
249
- let x = c / s, S = Math.min(c * .05, x), C = m.map(([e, t]) => x + e * y + t * b);
250
- if (C.some((e) => e < S)) {
251
- let e = new Uint8Array(s);
252
- for (let t = 0; t < s; t++) {
253
- let t = 0, n = 0, r = 0;
254
- for (let i = 0; i < s; i++) e[i] || C[i] <= S ? (e[i] = 1, C[i] = S, t += S) : (n += C[i], r++);
255
- if (r === 0) break;
256
- let i = c - t, a = n > 1e-12 ? i / n : 0, o = !1;
257
- for (let t = 0; t < s; t++) e[t] || (C[t] = n > 1e-12 ? C[t] * a : i / r, C[t] < S - 1e-9 && (o = !0));
258
- if (!o) break;
591
+ const bx = -totalMassKg * meanX;
592
+ const bz = -totalMassKg * meanZ;
593
+ const det = sxx * szz - sxz * sxz;
594
+ const trace = sxx + szz;
595
+ let lx = 0;
596
+ let lz = 0;
597
+ if (det > 1e-10 * trace * trace && det > 1e-12) {
598
+ lx = (szz * bx - sxz * bz) / det;
599
+ lz = (sxx * bz - sxz * bx) / det;
600
+ } else if (trace > 1e-10) {
601
+ const angle = .5 * Math.atan2(2 * sxz, sxx - szz);
602
+ const ux = Math.cos(angle);
603
+ const uz = Math.sin(angle);
604
+ const normSq = ux * ux * sxx + 2 * ux * uz * sxz + uz * uz * szz;
605
+ if (normSq > 1e-10) {
606
+ const proj = (ux * bx + uz * bz) / normSq;
607
+ lx = proj * ux;
608
+ lz = proj * uz;
259
609
  }
260
610
  }
261
- let w = t.map((e, t) => {
262
- let n = C[t], r = n / L, a = e.springK ?? n / e.sag;
611
+ const raw = wheels.map((_, i) => mBase + lx * cx[i] + lz * cz[i]);
612
+ const mMin = Math.min(.05 * totalMassKg, totalMassKg / n);
613
+ if (raw.every((m) => m >= mMin - 1e-9)) return raw;
614
+ return projectToLowerBoundedSimplex(raw, mMin, totalMassKg);
615
+ }
616
+ /**
617
+ * Distributes `totalMassKg` across N >= 1 wheels around `com`, resolves fallback
618
+ * `springK` / `dampingC` when omitted on the `.glb` wheel descriptor, and returns
619
+ * natural scene-space `mountPos` (`tag.position + lift`).
620
+ */
621
+ function solveWheelLoads(wheels, totalMassKg, com, dampingRatio = .7) {
622
+ if (wheels.length === 0) return [];
623
+ const cornerMasses = solveCornerMasses(wheels, totalMassKg, com);
624
+ return wheels.map((tag, i) => {
625
+ const cornerMassKg = cornerMasses[i];
626
+ const springK = tag.springK ?? cornerMassKg * G_SI / Math.max(tag.sag, 1e-4);
627
+ const dampingC = tag.dampingC ?? 2 * dampingRatio * Math.sqrt(springK * cornerMassKg);
628
+ const lift = Math.max(0, tag.travel - tag.sag);
629
+ const mountOffset = new THREE.Vector3(0, lift, 0);
630
+ if (tag.quaternion) mountOffset.applyQuaternion(new THREE.Quaternion(tag.quaternion[0], tag.quaternion[1], tag.quaternion[2], tag.quaternion[3]).normalize());
263
631
  return {
264
- tag: e,
265
- cornerMassKg: r,
266
- springK: a,
267
- dampingC: e.dampingC ?? 2 * i * Math.sqrt(a * r),
268
- mountPos: R(e)
632
+ tag,
633
+ cornerMassKg,
634
+ springK,
635
+ dampingC,
636
+ mountPos: [
637
+ tag.position[0] + mountOffset.x,
638
+ tag.position[1] + mountOffset.y,
639
+ tag.position[2] + mountOffset.z
640
+ ]
269
641
  };
270
642
  });
271
- if (!a || !o) return w;
272
- z.set(o[0], o[1], o[2], o[3]).normalize(), B.makeRotationFromQuaternion(z);
273
- let T = B.elements, ee = T[0] * T[0] * a[0] + T[4] * T[4] * a[1] + T[8] * T[8] * a[2], te = T[2] * T[2] * a[0] + T[6] * T[6] * a[1] + T[10] * T[10] * a[2], E = 0, D = 0, O = 0, k = 0, A = 0, j = 0;
274
- for (let e of w) {
275
- let t = e.mountPos[0] - r[0], n = e.mountPos[2] - r[2];
276
- E += e.dampingC, D += e.dampingC * t * t, O += e.dampingC * n * n, k += e.springK, A += e.springK * t * t, j += e.springK * n * n;
277
- }
278
- let M = (e, t, n) => {
279
- if (!(n > 1e-6) || !(e > 0)) return 1;
280
- let r = t > 0 ? Math.min(1, 2 * i * Math.sqrt(t * n) / e) : 1, a = e * r * .03333333333333333 / n, o = Math.max(.35, 1 - t * .0011111111111111111 / n);
281
- return r * (a > o ? o / a : 1);
282
- }, N = Math.min(M(E, k, n), M(O, j, ee), M(D, A, te));
283
- return N < 1 ? w.map((e) => e.tag.dampingC === void 0 ? {
284
- ...e,
285
- dampingC: e.dampingC * N
286
- } : e) : w;
287
643
  }
288
644
  // src/KhrVehicle.tsx
289
- var de = 220, fe = new x.Quaternion(), V = new x.Vector3();
290
- function pe({ ref: t, bundle: n, position: a = [
291
- 0,
292
- .5,
293
- 0
294
- ], enable: o = !0, carConfig: s, droneConfig: c, wheelConfig: m, frontWheelConfig: v, rearWheelConfig: y, wheelConfigs: x, propellerConfig: E, propellerConfigs: D, vehicleRef: O, children: k, ...A }) {
295
- let { world: j } = b(), ie = f(u), P = f(i), F = w((e) => e.gravityField), I = g(null), [L, R] = _(!1), [z, B] = _(!1), de = g(!1), [pe, H] = _(!1), U = g(!1), me = d((e) => {
296
- I.current = e, O && (O.current = e), typeof t == "function" ? t(e) : t && (t.current = e);
297
- }, [t, O]), { mass: W, com: G, inertia: K, inertiaFrame: q, linearVelocity: he, angularVelocity: ge, gravityFactor: _e } = h(() => ne(n.bodies), [n.bodies]), ve = h(() => se([...n.wheels.map((e) => e.object), ...n.propellers.map((e) => e.object)]), [n]), [ye, be, xe] = M(a), [Se, Ce, we, Te] = N(A.rotation, A.quaternion), J = h(() => (fe.set(Se, Ce, we, Te), V.set(G[0], G[1], G[2]).applyQuaternion(fe), [
298
- ye + V.x,
299
- be + V.y,
300
- xe + V.z
301
- ]), [
302
- ye,
303
- be,
304
- xe,
305
- Se,
306
- Ce,
307
- we,
308
- Te,
309
- G
310
- ]), Ee = h(() => [
311
- -G[0],
312
- -G[1],
313
- -G[2]
314
- ], [G]), De = h(() => re(n.bodies, G), [n.bodies, G]), Oe = h(() => {
315
- let t = {
316
- ...n.tune,
317
- ...s
318
- };
319
- if (n.wheels.some((e) => e.drive) && !(typeof t.engineHorsepower == "number" && t.engineHorsepower > 0)) throw new e("KhrVehicle: drive wheels need carConfig.engineHorsepower (author scene.extras.tune or pass the carConfig prop)");
320
- return t;
321
- }, [
322
- n.tune,
323
- n.wheels,
324
- s
325
- ]), Y = h(() => ue(n.wheels, W, G, .7, K, q).map((e) => ({
326
- sw: e,
327
- localPos: [
328
- e.mountPos[0] - G[0],
329
- e.mountPos[1] - G[1],
330
- e.mountPos[2] - G[2]
331
- ]
332
- })), [
333
- n.wheels,
334
- W,
335
- G,
336
- K,
337
- q
338
- ]), X = h(() => n.propellers.map((e) => ({
339
- p: e,
340
- localPos: [
341
- e.position[0] - G[0],
342
- e.position[1] - G[1],
343
- e.position[2] - G[2]
344
- ]
345
- })), [n.propellers, G]), ke = h(() => n.droneTune || c ? {
346
- ...n.droneTune,
347
- ...c
348
- } : void 0, [n.droneTune, c]);
349
- p(() => {
350
- let e = I.current?.body;
351
- e && (e.setAdditionalMassProperties(W, {
352
- x: 0,
353
- y: 0,
354
- z: 0
355
- }, {
356
- x: K[0],
357
- y: K[1],
358
- z: K[2]
359
- }, {
360
- x: q[0],
361
- y: q[1],
362
- z: q[2],
363
- w: q[3]
364
- }, !0), e.recomputeMassPropertiesFromColliders(), X.length > 0 && R(!0));
645
+ var patchedHandles = /* @__PURE__ */ new WeakSet();
646
+ function hasActiveMovement(m) {
647
+ 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));
648
+ }
649
+ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
650
+ assertVehicleProps(scale, colliders);
651
+ bundle.scene.updateMatrixWorld(true);
652
+ assertSceneIdentityWorldScale(bundle.scene);
653
+ const { ref, vehicleRef, jointsRef, position, rotation, quaternion, enable = true, enableCustomGravity = false, carConfig, droneConfig, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig, linearVelocity, angularVelocity, gravityScale, children, ...ecctrlRest } = rest;
654
+ const { world } = useRapier();
655
+ const worldGravity = useContext(WorldGravityContext);
656
+ const propZeroG = worldGravity ? isZeroGravityVec(worldGravity[0], worldGravity[1], worldGravity[2]) : false;
657
+ const [rotorsPrimed, setRotorsPrimed] = useState(false);
658
+ const [customPrimed, setCustomPrimed] = useState(() => !enableCustomGravity);
659
+ const [runtimeZeroG, setRuntimeZeroG] = useState(() => !enableCustomGravity && (propZeroG || isZeroGravityVec(world.gravity.x, world.gravity.y, world.gravity.z)));
660
+ const [wheelEpoch, setWheelEpoch] = useState(0);
661
+ const customPrimedRef = useRef(!enableCustomGravity);
662
+ const zeroGRef = useRef(runtimeZeroG);
663
+ const needsEpochBumpRef = useRef(false);
664
+ const wheelEnable = enable && customPrimed && !(!enableCustomGravity && propZeroG) && !runtimeZeroG;
665
+ const wheelActiveRef = useRef(wheelEnable);
666
+ wheelActiveRef.current = wheelEnable;
667
+ const bumpWheelEpoch = useCallback(() => setWheelEpoch((e) => e + 1), []);
668
+ const markCustomPrimed = useCallback(() => setCustomPrimed(true), []);
669
+ useLayoutEffect(() => {
670
+ setRotorsPrimed(true);
671
+ }, []);
672
+ useLayoutEffect(() => {
673
+ if (enableCustomGravity) {
674
+ customPrimedRef.current = false;
675
+ setCustomPrimed(false);
676
+ } else {
677
+ customPrimedRef.current = true;
678
+ setCustomPrimed(true);
679
+ const isZeroG = propZeroG || isZeroGravityVec(world.gravity.x, world.gravity.y, world.gravity.z);
680
+ zeroGRef.current = isZeroG;
681
+ setRuntimeZeroG(isZeroG);
682
+ if (isZeroG) resetAllWheelHits(innerRef.current);
683
+ }
365
684
  }, [
366
- W,
367
- K,
368
- q,
369
- X.length
685
+ enableCustomGravity,
686
+ propZeroG,
687
+ world
370
688
  ]);
371
- let Ae = !!A.enableCustomGravity, Z;
372
- if (Ae) I.current?.body ? V.copy(I.current.body.translation()) : V.set(J[0], J[1], J[2]), Z = F(V).lengthSq() > 1e-12;
373
- else {
374
- let [e, t, n] = ie ?? [
375
- j.gravity.x,
376
- j.gravity.y,
377
- j.gravity.z
378
- ];
379
- Z = e * e + t * t + n * n > 1e-12;
380
- }
381
- let Q = o && P, je = Q && Z && !pe && z;
382
- p(() => {
383
- Z && U.current && (U.current = !1, H(!1));
384
- }, [Z]);
385
- let $ = h(() => Y.map((e, t) => ae(n.wheels, t, m, v, y, x)), [
386
- Y,
387
- n.wheels,
388
- m,
389
- v,
390
- y,
391
- x
392
- ]), Me = h(() => {
393
- let e = /* @__PURE__ */ new Set();
394
- if (!je) return e;
395
- for (let t = 0; t < Y.length; t++) ($[t]?.enable ?? o) && e.add(Y[t].sw.tag.nodeName);
396
- return e;
397
- }, [
398
- Y,
399
- $,
400
- je,
401
- o
689
+ const chassis = useMemo(() => computeChassisMassProps(bundle.bodies), [bundle]);
690
+ const collidersList = useMemo(() => buildChassisColliders(bundle.bodies, chassis), [bundle.bodies, chassis]);
691
+ const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, chassis.mass, chassis.com), [
692
+ bundle.wheels,
693
+ chassis.mass,
694
+ chassis.com
695
+ ]);
696
+ const rotorOrigins = useMemo(() => captureRotorOrigins([...bundle.wheels.map((w) => w.object), ...bundle.propellers.map((p) => p.object)]), [bundle.wheels, bundle.propellers]);
697
+ const [px, py, pz] = readPosTuple(position);
698
+ const [qx, qy, qz, qw] = readSpawnQuat(rotation, quaternion);
699
+ const bodyPos = useMemo(() => [
700
+ px,
701
+ py,
702
+ pz
703
+ ], [
704
+ px,
705
+ py,
706
+ pz
707
+ ]);
708
+ const bodyQuat = useMemo(() => [
709
+ qx,
710
+ qy,
711
+ qz,
712
+ qw
713
+ ], [
714
+ qx,
715
+ qy,
716
+ qz,
717
+ qw
718
+ ]);
719
+ const innerRef = useRef(null);
720
+ const assignRef = useCallback((handle) => {
721
+ if (handle && !patchedHandles.has(handle)) {
722
+ patchedHandles.add(handle);
723
+ const origSetMovement = handle.setMovement;
724
+ handle.setMovement = (state) => {
725
+ origSetMovement(state);
726
+ if (hasActiveMovement(state) && handle.body?.isSleeping()) handle.body.wakeUp();
727
+ };
728
+ }
729
+ innerRef.current = handle;
730
+ if (vehicleRef) vehicleRef.current = handle;
731
+ if (typeof ref === "function") ref(handle);
732
+ else if (ref && typeof ref === "object") ref.current = handle;
733
+ }, [ref, vehicleRef]);
734
+ const omiSteerAngle = useMemo(() => bundle.wheels.find((w) => w.steer && w.maxSteeringAngle !== void 0 && w.maxSteeringAngle > 0)?.maxSteeringAngle, [bundle.wheels]);
735
+ const mergedCarConfig = useMemo(() => bundle.tune || carConfig || omiSteerAngle !== void 0 ? {
736
+ ...omiSteerAngle !== void 0 ? { maxSteerAngle: omiSteerAngle } : {},
737
+ ...bundle.tune,
738
+ ...carConfig
739
+ } : void 0, [
740
+ omiSteerAngle,
741
+ bundle.tune,
742
+ carConfig
402
743
  ]);
403
- return /* @__PURE__ */ C(T, {
404
- ref: me,
405
- position: J,
406
- enable: Q,
407
- carConfig: Oe,
408
- droneConfig: ke,
409
- ...he ? { linearVelocity: he } : {},
410
- ...ge ? { angularVelocity: ge } : {},
411
- ..._e === void 0 ? {} : { gravityScale: _e },
412
- ...A,
744
+ const mergedDroneConfig = useMemo(() => bundle.droneTune || droneConfig ? {
745
+ ...bundle.droneTune,
746
+ ...droneConfig
747
+ } : void 0, [bundle.droneTune, droneConfig]);
748
+ const effLinVel = linearVelocity ?? chassis.linearVelocity;
749
+ const effAngVel = angularVelocity ?? chassis.angularVelocity;
750
+ const effGravScale = gravityScale ?? chassis.gravityFactor;
751
+ return /* @__PURE__ */ jsxs(EcctrlVehicle, {
752
+ ref: assignRef,
753
+ enable,
754
+ enableCustomGravity,
755
+ position: bodyPos,
756
+ quaternion: bodyQuat,
757
+ ...effLinVel !== void 0 ? { linearVelocity: effLinVel } : {},
758
+ ...effAngVel !== void 0 ? { angularVelocity: effAngVel } : {},
759
+ ...effGravScale !== void 0 ? { gravityScale: effGravScale } : {},
760
+ carConfig: mergedCarConfig,
761
+ droneConfig: mergedDroneConfig,
762
+ ...ecctrlRest,
413
763
  children: [
414
- /* @__PURE__ */ C("group", {
415
- position: Ee,
416
- children: [/* @__PURE__ */ S(l, {
417
- bundle: n,
418
- owner: "KhrVehicle"
419
- }), k]
420
- }),
421
- De.map(({ key: e, spec: t }) => /* @__PURE__ */ S(r, { c: t }, e)),
422
- /* @__PURE__ */ S(le, {
423
- vehicleRef: I,
424
- active: Q,
425
- hasRenderGravity: Z,
426
- enableCustomGravity: Ae,
427
- activeWheelNames: Me,
428
- gravityPrimedRef: de,
429
- setGravityPrimed: B,
430
- spatialZeroGRef: U,
431
- setSpatialZeroG: H
764
+ /* @__PURE__ */ jsx(BundleSceneHost, {
765
+ bundle,
766
+ owner: "KhrVehicle"
432
767
  }),
433
- Y.map(({ sw: e, localPos: t }, r) => {
434
- let i = e.tag.nodeName;
435
- return /* @__PURE__ */ S(ee, {
436
- quaternion: e.tag.quaternion,
437
- wheelModelDensity: e.tag.wheelDensity ?? 220,
438
- wheelModelRadius: e.tag.radius,
439
- rayShapeR: e.tag.radius,
440
- rayShapeH: e.tag.width * .5,
441
- rayLength: e.tag.travel,
442
- springK: e.tag.springK ?? e.springK,
443
- dampingC: e.tag.dampingC ?? e.dampingC,
444
- steerWheel: e.tag.steer,
445
- driveWheel: e.tag.drive,
446
- brakeWheel: e.tag.brake,
447
- steerInvert: e.tag.steerInvert,
448
- driveInvert: e.tag.driveInvert,
449
- driveTorqueWeight: e.tag.driveTorqueWeight,
450
- tireGripFactor: e.tag.tireGripFactor,
451
- lngFrictionEllipseScale: e.tag.lngFrictionEllipseScale,
452
- latFrictionEllipseScale: e.tag.latFrictionEllipseScale,
453
- relaxLngRate: e.tag.relaxLngRate,
454
- relaxLatRate: e.tag.relaxLatRate,
455
- minLngRelaxCoeff: e.tag.minLngRelaxCoeff,
456
- minLatRelaxCoeff: e.tag.minLatRelaxCoeff,
457
- rollingResistanceCoef: e.tag.rollingResistanceCoef,
458
- lngSlipRatioCurveData: e.tag.lngSlipRatioCurveData,
459
- latSlipRatioCurveData: e.tag.latSlipRatioCurveData,
460
- maxBrakeTorque: e.tag.maxBrakeTorque ?? e.cornerMassKg * 9.80665 * e.tag.radius,
461
- groundDetection: e.tag.groundDetection ?? "shapeCast",
462
- ...$[r],
463
- name: i,
464
- position: t,
465
- enable: Me.has(i),
466
- children: /* @__PURE__ */ S(ce, {
467
- object: e.tag.object,
468
- center: e.tag.position,
469
- quaternion: e.tag.quaternion,
470
- scene: n.scene,
471
- origin: ve.get(e.tag.object)
472
- })
473
- }, i);
768
+ children,
769
+ collidersList.map(({ key, spec, massProperties }) => /* @__PURE__ */ jsx(KhrCollider, {
770
+ c: spec,
771
+ massProperties
772
+ }, key)),
773
+ /* @__PURE__ */ jsx(KhrVehicleJoints, {
774
+ bodies: bundle.bodies,
775
+ vehicleRef: innerRef,
776
+ jointsRef
474
777
  }),
475
- X.map(({ p: e, localPos: t }, r) => {
476
- let i = oe(e, r, E, D), a = !!((i?.enable ?? o) && Q), s = /* @__PURE__ */ S(ce, {
477
- object: e.object,
478
- center: e.position,
479
- quaternion: e.quaternion,
480
- scene: n.scene,
481
- origin: ve.get(e.object)
482
- });
483
- return a ? /* @__PURE__ */ S(te, {
484
- debug: !1,
485
- maxThrust: e.maxThrust,
486
- torqueRatio: e.torqueRatio,
487
- invertThrust: e.invertThrust,
488
- invertTorque: e.invertTorque,
489
- ...i,
490
- name: e.nodeName,
491
- position: t,
492
- quaternion: e.quaternion,
493
- enable: L,
494
- children: s
495
- }, e.nodeName) : /* @__PURE__ */ S("group", {
496
- position: t,
497
- quaternion: e.quaternion,
498
- children: s
499
- }, `${e.nodeName}-idle`);
500
- })
778
+ rotorsPrimed && /* @__PURE__ */ jsxs(Fragment, { children: [
779
+ /* @__PURE__ */ jsx(ZeroGWheelPreGuard, {
780
+ vehicleRef: innerRef,
781
+ enable,
782
+ enableCustomGravity,
783
+ spawnPos: bodyPos,
784
+ wheelActiveRef,
785
+ zeroGRef,
786
+ customPrimedRef,
787
+ needsEpochBumpRef,
788
+ onZeroGChange: setRuntimeZeroG,
789
+ onCustomPrimed: markCustomPrimed,
790
+ onBumpWheelEpoch: bumpWheelEpoch
791
+ }),
792
+ /* @__PURE__ */ jsx(KhrVehicleRotors, {
793
+ solvedWheels,
794
+ propellers: bundle.propellers,
795
+ scene: bundle.scene,
796
+ comZ: chassis.com[2],
797
+ rotorOrigins,
798
+ enable,
799
+ wheelEnable,
800
+ wheelEpoch,
801
+ wheelConfig,
802
+ frontWheelConfig,
803
+ rearWheelConfig,
804
+ propellerConfig
805
+ }),
806
+ /* @__PURE__ */ jsx(ZeroGWheelPostGuard, {
807
+ vehicleRef: innerRef,
808
+ zeroGRef
809
+ })
810
+ ] })
501
811
  ]
502
812
  });
503
813
  }
504
- function H({ scale: e, colliders: t, bundle: n, ...r }) {
505
- return j(e, t), n.scene.updateMatrixWorld(!0), a(n.scene), /* @__PURE__ */ S(pe, {
506
- bundle: n,
507
- ...r
508
- }, n.scene.uuid);
509
- }
510
- export { L as BENCH_GRAVITY, H as KhrVehicle, de as WHEEL_ASSEMBLY_DENSITY_KG_M3, ue as solveWheelLoads };
814
+ export { KhrVehicle, solveWheelLoads };
815
+
816
+ //# sourceMappingURL=vehicle.js.map