@khr3/core 0.2.12 → 0.2.14
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/README.md +54 -3
- package/dist/KhrAssembly-BOY_g5we.js +1968 -0
- package/dist/KhrAssembly-BOY_g5we.js.map +1 -0
- package/dist/KhrAssembly.d.ts +31 -4
- package/dist/decoders.d.ts +5 -2
- package/dist/heightfield.d.ts +45 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +255 -496
- package/dist/index.js.map +1 -1
- package/dist/inertia.d.ts +29 -17
- package/dist/types.d.ts +12 -0
- package/dist/vehicle.js +37 -198
- package/dist/vehicle.js.map +1 -1
- package/dist/vehicleJoints.d.ts +4 -2
- package/docs/api-reference.md +160 -0
- package/package.json +4 -3
- package/dist/joints-5IgWDD2w.js +0 -865
- package/dist/joints-5IgWDD2w.js.map +0 -1
|
@@ -0,0 +1,1968 @@
|
|
|
1
|
+
import React, { createContext, useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef } from "react";
|
|
2
|
+
import * as THREE from "three";
|
|
3
|
+
import { useFrame } from "@react-three/fiber";
|
|
4
|
+
import { BallCollider, CapsuleCollider, CoefficientCombineRule, ConvexHullCollider, CuboidCollider, CylinderCollider, RigidBody, TrimeshCollider, useRapier } from "@react-three/rapier";
|
|
5
|
+
import { useCustomGravity } from "@pinkaphant/ecctrl/gravity";
|
|
6
|
+
import { ConvexGeometry } from "three/examples/jsm/geometries/ConvexGeometry.js";
|
|
7
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
8
|
+
// src/types.ts
|
|
9
|
+
var KhrValidationError = class extends Error {
|
|
10
|
+
constructor(message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "KhrValidationError";
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var JointRegistryContext = createContext(null);
|
|
16
|
+
var COMBINE_MODES = /* @__PURE__ */ new Set([
|
|
17
|
+
"average",
|
|
18
|
+
"minimum",
|
|
19
|
+
"maximum",
|
|
20
|
+
"multiply"
|
|
21
|
+
]);
|
|
22
|
+
var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
23
|
+
var isFiniteNum = (v) => typeof v === "number" && Number.isFinite(v);
|
|
24
|
+
var isPosNum = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
25
|
+
var isNonNegNum = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
|
|
26
|
+
function optFiniteNum(v, label, nonNeg = false) {
|
|
27
|
+
if (v === void 0) return void 0;
|
|
28
|
+
if (!isFiniteNum(v) || nonNeg && v < 0) throw new KhrValidationError(`Invalid ${label}: expected finite number${nonNeg ? " >= 0" : ""}`);
|
|
29
|
+
return v;
|
|
30
|
+
}
|
|
31
|
+
function assignRef(ref, value) {
|
|
32
|
+
if (typeof ref === "function") ref(value);
|
|
33
|
+
else if (ref && typeof ref === "object") ref.current = value;
|
|
34
|
+
}
|
|
35
|
+
// src/inertia.ts
|
|
36
|
+
var SCALE_EPS = 1e-4;
|
|
37
|
+
var _wsScratch = new THREE.Vector3();
|
|
38
|
+
var _one = new THREE.Vector3(1, 1, 1);
|
|
39
|
+
function isUnitScalar(v) {
|
|
40
|
+
return typeof v === "number" && Number.isFinite(v) && Math.abs(v - 1) <= 1e-9;
|
|
41
|
+
}
|
|
42
|
+
function assertUnitScale(scale, owner) {
|
|
43
|
+
if (scale === void 0) return;
|
|
44
|
+
let ok = false;
|
|
45
|
+
if (typeof scale === "number") ok = isUnitScalar(scale);
|
|
46
|
+
else if (Array.isArray(scale)) ok = scale.length === 3 && scale.every(isUnitScalar);
|
|
47
|
+
else if (typeof scale === "object" && scale && "x" in scale && "y" in scale && "z" in scale) {
|
|
48
|
+
const v = scale;
|
|
49
|
+
ok = isUnitScalar(v.x) && isUnitScalar(v.y) && isUnitScalar(v.z);
|
|
50
|
+
}
|
|
51
|
+
if (!ok) throw new KhrValidationError(`${owner}: scale must be 1 (got ${typeof scale === "number" && !Number.isFinite(scale) ? String(scale) : JSON.stringify(scale)}); bake scale into the .glb at import`);
|
|
52
|
+
}
|
|
53
|
+
function readFiniteVec3(val, fieldLabel) {
|
|
54
|
+
if (!Array.isArray(val) || val.length !== 3 || !val.every((n) => typeof n === "number" && Number.isFinite(n))) throw new KhrValidationError(`Invalid ${fieldLabel}: expected finite 3-tuple`);
|
|
55
|
+
return [
|
|
56
|
+
val[0],
|
|
57
|
+
val[1],
|
|
58
|
+
val[2]
|
|
59
|
+
];
|
|
60
|
+
}
|
|
61
|
+
function readUnitQuat(val, fieldLabel) {
|
|
62
|
+
if (!Array.isArray(val) || val.length !== 4 || !val.every((n) => typeof n === "number" && Number.isFinite(n))) throw new KhrValidationError(`Invalid ${fieldLabel}: expected finite 4-tuple`);
|
|
63
|
+
const norm = Math.hypot(val[0], val[1], val[2], val[3]);
|
|
64
|
+
if (!(norm > 1e-6)) throw new KhrValidationError(`Invalid ${fieldLabel}: zero-norm quaternion`);
|
|
65
|
+
return [
|
|
66
|
+
val[0] / norm,
|
|
67
|
+
val[1] / norm,
|
|
68
|
+
val[2] / norm,
|
|
69
|
+
val[3] / norm
|
|
70
|
+
];
|
|
71
|
+
}
|
|
72
|
+
function assertIdentityWorldScale(obj, nodeName) {
|
|
73
|
+
obj.getWorldScale(_wsScratch);
|
|
74
|
+
if (!Number.isFinite(_wsScratch.x) || !Number.isFinite(_wsScratch.y) || !Number.isFinite(_wsScratch.z) || Math.abs(_wsScratch.x - 1) > SCALE_EPS || Math.abs(_wsScratch.y - 1) > SCALE_EPS || Math.abs(_wsScratch.z - 1) > SCALE_EPS) throw new KhrValidationError(`Non-identity world scale [${_wsScratch.x.toFixed(4)}, ${_wsScratch.y.toFixed(4)}, ${_wsScratch.z.toFixed(4)}] on "${nodeName}"; bake scale=[1,1,1]`);
|
|
75
|
+
const ls = obj.scale;
|
|
76
|
+
if (!Number.isFinite(ls.x) || !Number.isFinite(ls.y) || !Number.isFinite(ls.z) || Math.abs(ls.x - 1) > SCALE_EPS || Math.abs(ls.y - 1) > SCALE_EPS || Math.abs(ls.z - 1) > SCALE_EPS) throw new KhrValidationError(`Non-identity local scale [${ls.x.toFixed(4)}, ${ls.y.toFixed(4)}, ${ls.z.toFixed(4)}] on "${nodeName}"; bake scale=[1,1,1]`);
|
|
77
|
+
}
|
|
78
|
+
function assertSceneIdentityWorldScale(root) {
|
|
79
|
+
root.updateMatrixWorld(true);
|
|
80
|
+
root.traverse((child) => {
|
|
81
|
+
assertIdentityWorldScale(child, child.name || (child === root ? "gltf.scene" : "unnamed_node"));
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
function computeRelativePose(ownerObj, childObj) {
|
|
85
|
+
const ownerPos = ownerObj.getWorldPosition(new THREE.Vector3());
|
|
86
|
+
const ownerInvQuat = ownerObj.getWorldQuaternion(new THREE.Quaternion()).invert();
|
|
87
|
+
const pos = childObj.getWorldPosition(new THREE.Vector3()).sub(ownerPos).applyQuaternion(ownerInvQuat);
|
|
88
|
+
const quat = ownerInvQuat.multiply(childObj.getWorldQuaternion(new THREE.Quaternion()));
|
|
89
|
+
return {
|
|
90
|
+
localPosition: [
|
|
91
|
+
pos.x,
|
|
92
|
+
pos.y,
|
|
93
|
+
pos.z
|
|
94
|
+
],
|
|
95
|
+
localQuaternion: [
|
|
96
|
+
quat.x,
|
|
97
|
+
quat.y,
|
|
98
|
+
quat.z,
|
|
99
|
+
quat.w
|
|
100
|
+
]
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function extractMeshColliderShape(targetObj, meshNodeName, convexHull) {
|
|
104
|
+
assertIdentityWorldScale(targetObj, meshNodeName);
|
|
105
|
+
const invOwner = targetObj.matrixWorld.clone().invert();
|
|
106
|
+
const rel = new THREE.Matrix4();
|
|
107
|
+
const v = new THREE.Vector3();
|
|
108
|
+
const verts = [];
|
|
109
|
+
const indices = [];
|
|
110
|
+
targetObj.traverse((child) => {
|
|
111
|
+
const mesh = child;
|
|
112
|
+
if (!mesh.isMesh || !mesh.geometry) return;
|
|
113
|
+
assertIdentityWorldScale(mesh, mesh.name || meshNodeName);
|
|
114
|
+
const posAttr = mesh.geometry.getAttribute("position");
|
|
115
|
+
if (!posAttr || posAttr.count === 0) return;
|
|
116
|
+
rel.multiplyMatrices(invOwner, mesh.matrixWorld);
|
|
117
|
+
const base = verts.length / 3;
|
|
118
|
+
for (let i = 0; i < posAttr.count; i++) {
|
|
119
|
+
v.fromBufferAttribute(posAttr, i).applyMatrix4(rel);
|
|
120
|
+
if (!Number.isFinite(v.x) || !Number.isFinite(v.y) || !Number.isFinite(v.z)) throw new KhrValidationError(`Non-finite vertex in collider mesh "${meshNodeName}"`);
|
|
121
|
+
verts.push(v.x, v.y, v.z);
|
|
122
|
+
}
|
|
123
|
+
const idx = mesh.geometry.getIndex();
|
|
124
|
+
if (idx) for (let i = 0; i < idx.count; i++) indices.push(base + idx.getX(i));
|
|
125
|
+
else for (let i = 0; i < posAttr.count; i++) indices.push(base + i);
|
|
126
|
+
});
|
|
127
|
+
if (verts.length < 9) throw new KhrValidationError(`Collider node "${meshNodeName}" has fewer than 3 vertices`);
|
|
128
|
+
if (convexHull) return {
|
|
129
|
+
type: "convexHull",
|
|
130
|
+
vertices: new Float32Array(verts),
|
|
131
|
+
meshNodeName
|
|
132
|
+
};
|
|
133
|
+
if (indices.length < 3) throw new KhrValidationError(`Trimesh node "${meshNodeName}" has fewer than 3 indices`);
|
|
134
|
+
return {
|
|
135
|
+
type: "trimesh",
|
|
136
|
+
vertices: new Float32Array(verts),
|
|
137
|
+
indices: new Uint32Array(indices),
|
|
138
|
+
meshNodeName
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Exact 3x3 symmetric Jacobi eigendecomposition returning positive principal inertia diagonal
|
|
143
|
+
* and right-handed `SO(3)` principal frame quaternion `[x, y, z, w]`.
|
|
144
|
+
*/
|
|
145
|
+
function jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz) {
|
|
146
|
+
const a = [
|
|
147
|
+
[
|
|
148
|
+
ixx,
|
|
149
|
+
ixy,
|
|
150
|
+
ixz
|
|
151
|
+
],
|
|
152
|
+
[
|
|
153
|
+
ixy,
|
|
154
|
+
iyy,
|
|
155
|
+
iyz
|
|
156
|
+
],
|
|
157
|
+
[
|
|
158
|
+
ixz,
|
|
159
|
+
iyz,
|
|
160
|
+
izz
|
|
161
|
+
]
|
|
162
|
+
];
|
|
163
|
+
const v = [
|
|
164
|
+
[
|
|
165
|
+
1,
|
|
166
|
+
0,
|
|
167
|
+
0
|
|
168
|
+
],
|
|
169
|
+
[
|
|
170
|
+
0,
|
|
171
|
+
1,
|
|
172
|
+
0
|
|
173
|
+
],
|
|
174
|
+
[
|
|
175
|
+
0,
|
|
176
|
+
0,
|
|
177
|
+
1
|
|
178
|
+
]
|
|
179
|
+
];
|
|
180
|
+
for (let iter = 0; iter < 32; iter++) {
|
|
181
|
+
const tr = Math.max(a[0][0] + a[1][1] + a[2][2], 0);
|
|
182
|
+
let p = 0, q = 1, maxOff = Math.abs(a[0][1]);
|
|
183
|
+
if (Math.abs(a[0][2]) > maxOff) {
|
|
184
|
+
p = 0;
|
|
185
|
+
q = 2;
|
|
186
|
+
maxOff = Math.abs(a[0][2]);
|
|
187
|
+
}
|
|
188
|
+
if (Math.abs(a[1][2]) > maxOff) {
|
|
189
|
+
p = 1;
|
|
190
|
+
q = 2;
|
|
191
|
+
maxOff = Math.abs(a[1][2]);
|
|
192
|
+
}
|
|
193
|
+
if (maxOff <= 1e-12 * tr) break;
|
|
194
|
+
const apq = a[p][q], app = a[p][p], aqq = a[q][q];
|
|
195
|
+
const tau = (aqq - app) / (2 * apq);
|
|
196
|
+
const t = tau >= 0 ? 1 / (tau + Math.sqrt(1 + tau * tau)) : -1 / (-tau + Math.sqrt(1 + tau * tau));
|
|
197
|
+
const c = 1 / Math.sqrt(1 + t * t), s = t * c;
|
|
198
|
+
const r = 3 - p - q;
|
|
199
|
+
a[p][p] = c * c * app - 2 * s * c * apq + s * s * aqq;
|
|
200
|
+
a[q][q] = s * s * app + 2 * s * c * apq + c * c * aqq;
|
|
201
|
+
a[p][q] = a[q][p] = 0;
|
|
202
|
+
const arp = a[r][p], arq = a[r][q];
|
|
203
|
+
a[r][p] = a[p][r] = c * arp - s * arq;
|
|
204
|
+
a[r][q] = a[q][r] = s * arp + c * arq;
|
|
205
|
+
for (let i = 0; i < 3; i++) {
|
|
206
|
+
const vip = v[i][p], viq = v[i][q];
|
|
207
|
+
v[i][p] = c * vip - s * viq;
|
|
208
|
+
v[i][q] = s * vip + c * viq;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (v[0][0] * (v[1][1] * v[2][2] - v[1][2] * v[2][1]) - v[0][1] * (v[1][0] * v[2][2] - v[1][2] * v[2][0]) + v[0][2] * (v[1][0] * v[2][1] - v[1][1] * v[2][0]) < 0) {
|
|
212
|
+
v[0][2] = -v[0][2];
|
|
213
|
+
v[1][2] = -v[1][2];
|
|
214
|
+
v[2][2] = -v[2][2];
|
|
215
|
+
}
|
|
216
|
+
const mat = new THREE.Matrix4().set(v[0][0], v[0][1], v[0][2], 0, v[1][0], v[1][1], v[1][2], 0, v[2][0], v[2][1], v[2][2], 0, 0, 0, 0, 1);
|
|
217
|
+
const q = new THREE.Quaternion().setFromRotationMatrix(mat).normalize();
|
|
218
|
+
return {
|
|
219
|
+
inertia: [
|
|
220
|
+
a[0][0],
|
|
221
|
+
a[1][1],
|
|
222
|
+
a[2][2]
|
|
223
|
+
],
|
|
224
|
+
inertiaFrame: [
|
|
225
|
+
q.x,
|
|
226
|
+
q.y,
|
|
227
|
+
q.z,
|
|
228
|
+
q.w
|
|
229
|
+
]
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Exact 3D signed-tetrahedron divergence integration for closed solid triangle meshes.
|
|
234
|
+
*/
|
|
235
|
+
function integrateClosedMeshProps(vertices, indices) {
|
|
236
|
+
const triCount = indices ? Math.floor(indices.length / 3) : Math.floor(vertices.length / 9);
|
|
237
|
+
if (triCount < 4) return null;
|
|
238
|
+
let rx = 0, ry = 0, rz = 0;
|
|
239
|
+
const vCount = Math.floor(vertices.length / 3);
|
|
240
|
+
for (let i = 0; i < vCount; i++) {
|
|
241
|
+
rx += vertices[i * 3];
|
|
242
|
+
ry += vertices[i * 3 + 1];
|
|
243
|
+
rz += vertices[i * 3 + 2];
|
|
244
|
+
}
|
|
245
|
+
rx /= vCount;
|
|
246
|
+
ry /= vCount;
|
|
247
|
+
rz /= vCount;
|
|
248
|
+
let vol6 = 0;
|
|
249
|
+
let cx24 = 0, cy24 = 0, cz24 = 0;
|
|
250
|
+
let cxx120 = 0, cyy120 = 0, czz120 = 0;
|
|
251
|
+
let cxy120 = 0, cxz120 = 0, cyz120 = 0;
|
|
252
|
+
for (let t = 0; t < triCount; t++) {
|
|
253
|
+
const i0 = (indices ? indices[t * 3] : t * 3) * 3;
|
|
254
|
+
const i1 = (indices ? indices[t * 3 + 1] : t * 3 + 1) * 3;
|
|
255
|
+
const i2 = (indices ? indices[t * 3 + 2] : t * 3 + 2) * 3;
|
|
256
|
+
const ax = vertices[i0] - rx, ay = vertices[i0 + 1] - ry, az = vertices[i0 + 2] - rz;
|
|
257
|
+
const bx = vertices[i1] - rx, by = vertices[i1 + 1] - ry, bz = vertices[i1 + 2] - rz;
|
|
258
|
+
const cx = vertices[i2] - rx, cy = vertices[i2 + 1] - ry, cz = vertices[i2 + 2] - rz;
|
|
259
|
+
const det = ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx);
|
|
260
|
+
vol6 += det;
|
|
261
|
+
const sx = ax + bx + cx, sy = ay + by + cy, sz = az + bz + cz;
|
|
262
|
+
cx24 += det * sx;
|
|
263
|
+
cy24 += det * sy;
|
|
264
|
+
cz24 += det * sz;
|
|
265
|
+
cxx120 += det * (sx * sx + ax * ax + bx * bx + cx * cx);
|
|
266
|
+
cyy120 += det * (sy * sy + ay * ay + by * by + cy * cy);
|
|
267
|
+
czz120 += det * (sz * sz + az * az + bz * bz + cz * cz);
|
|
268
|
+
cxy120 += det * (sx * sy + ax * ay + bx * by + cx * cy);
|
|
269
|
+
cxz120 += det * (sx * sz + ax * az + bx * bz + cx * cz);
|
|
270
|
+
cyz120 += det * (sy * sz + ay * az + by * bz + cy * cz);
|
|
271
|
+
}
|
|
272
|
+
const sign = vol6 < 0 ? -1 : 1;
|
|
273
|
+
const volume = sign * vol6 / 6;
|
|
274
|
+
if (!(volume > 1e-9)) return null;
|
|
275
|
+
const invV = 1 / volume;
|
|
276
|
+
const comRelX = sign * cx24 / (24 * volume);
|
|
277
|
+
const comRelY = sign * cy24 / (24 * volume);
|
|
278
|
+
const comRelZ = sign * cz24 / (24 * volume);
|
|
279
|
+
const cxx = sign * cxx120 / 120 * invV - comRelX * comRelX;
|
|
280
|
+
const cyy = sign * cyy120 / 120 * invV - comRelY * comRelY;
|
|
281
|
+
const czz = sign * czz120 / 120 * invV - comRelZ * comRelZ;
|
|
282
|
+
const cxy = sign * cxy120 / 120 * invV - comRelX * comRelY;
|
|
283
|
+
const cxz = sign * cxz120 / 120 * invV - comRelX * comRelZ;
|
|
284
|
+
const cyz = sign * cyz120 / 120 * invV - comRelY * comRelZ;
|
|
285
|
+
const ixx = cyy + czz;
|
|
286
|
+
const iyy = cxx + czz;
|
|
287
|
+
const izz = cxx + cyy;
|
|
288
|
+
if (!(ixx > 0 && iyy > 0 && izz > 0)) return null;
|
|
289
|
+
return {
|
|
290
|
+
measure: volume,
|
|
291
|
+
isVolumetric: true,
|
|
292
|
+
centroid: new THREE.Vector3(rx + comRelX, ry + comRelY, rz + comRelZ),
|
|
293
|
+
unitTensor: [
|
|
294
|
+
ixx,
|
|
295
|
+
iyy,
|
|
296
|
+
izz,
|
|
297
|
+
-cxy,
|
|
298
|
+
-cxz,
|
|
299
|
+
-cyz
|
|
300
|
+
]
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Exact 2D surface-area second-moment integration over open triangle shells
|
|
305
|
+
* (used when an unclosed sheet-metal panel mesh has zero enclosed 3D volume).
|
|
306
|
+
* Throws `KhrValidationError` if all triangles are collinear/degenerate.
|
|
307
|
+
*/
|
|
308
|
+
function integrateSurfaceShellProps(vertices, indices, label) {
|
|
309
|
+
const triCount = indices ? Math.floor(indices.length / 3) : Math.floor(vertices.length / 9);
|
|
310
|
+
if (triCount < 1) throw new KhrValidationError(`Collider mesh "${label}" has no triangles`);
|
|
311
|
+
let rx = 0, ry = 0, rz = 0;
|
|
312
|
+
const vCount = Math.floor(vertices.length / 3);
|
|
313
|
+
for (let i = 0; i < vCount; i++) {
|
|
314
|
+
rx += vertices[i * 3];
|
|
315
|
+
ry += vertices[i * 3 + 1];
|
|
316
|
+
rz += vertices[i * 3 + 2];
|
|
317
|
+
}
|
|
318
|
+
rx /= vCount;
|
|
319
|
+
ry /= vCount;
|
|
320
|
+
rz /= vCount;
|
|
321
|
+
let area2 = 0;
|
|
322
|
+
let cx6 = 0, cy6 = 0, cz6 = 0;
|
|
323
|
+
let sxx24 = 0, syy24 = 0, szz24 = 0;
|
|
324
|
+
let sxy24 = 0, sxz24 = 0, syz24 = 0;
|
|
325
|
+
for (let t = 0; t < triCount; t++) {
|
|
326
|
+
const i0 = (indices ? indices[t * 3] : t * 3) * 3;
|
|
327
|
+
const i1 = (indices ? indices[t * 3 + 1] : t * 3 + 1) * 3;
|
|
328
|
+
const i2 = (indices ? indices[t * 3 + 2] : t * 3 + 2) * 3;
|
|
329
|
+
const ax = vertices[i0] - rx, ay = vertices[i0 + 1] - ry, az = vertices[i0 + 2] - rz;
|
|
330
|
+
const bx = vertices[i1] - rx, by = vertices[i1 + 1] - ry, bz = vertices[i1 + 2] - rz;
|
|
331
|
+
const cx = vertices[i2] - rx, cy = vertices[i2 + 1] - ry, cz = vertices[i2 + 2] - rz;
|
|
332
|
+
const e1x = bx - ax, e1y = by - ay, e1z = bz - az;
|
|
333
|
+
const e2x = cx - ax, e2y = cy - ay, e2z = cz - az;
|
|
334
|
+
const nx = e1y * e2z - e1z * e2y;
|
|
335
|
+
const ny = e1z * e2x - e1x * e2z;
|
|
336
|
+
const nz = e1x * e2y - e1y * e2x;
|
|
337
|
+
const dblArea = Math.hypot(nx, ny, nz);
|
|
338
|
+
if (dblArea <= 1e-14) continue;
|
|
339
|
+
area2 += dblArea;
|
|
340
|
+
const sx = ax + bx + cx, sy = ay + by + cy, sz = az + bz + cz;
|
|
341
|
+
cx6 += dblArea * sx;
|
|
342
|
+
cy6 += dblArea * sy;
|
|
343
|
+
cz6 += dblArea * sz;
|
|
344
|
+
sxx24 += dblArea * (sx * sx + ax * ax + bx * bx + cx * cx);
|
|
345
|
+
syy24 += dblArea * (sy * sy + ay * ay + by * by + cy * cy);
|
|
346
|
+
szz24 += dblArea * (sz * sz + az * az + bz * bz + cz * cz);
|
|
347
|
+
sxy24 += dblArea * (sx * sy + ax * ay + bx * by + cx * cy);
|
|
348
|
+
sxz24 += dblArea * (sx * sz + ax * az + bx * bz + cx * cz);
|
|
349
|
+
syz24 += dblArea * (sy * sz + ay * az + by * bz + cy * cz);
|
|
350
|
+
}
|
|
351
|
+
const area = .5 * area2;
|
|
352
|
+
if (!(area > 1e-10)) throw new KhrValidationError(`Collider mesh "${label}" has zero surface area (collinear/degenerate vertices)`);
|
|
353
|
+
const comRelX = cx6 / (6 * area);
|
|
354
|
+
const comRelY = cy6 / (6 * area);
|
|
355
|
+
const comRelZ = cz6 / (6 * area);
|
|
356
|
+
const cxx = sxx24 / (24 * area) - comRelX * comRelX;
|
|
357
|
+
const cyy = syy24 / (24 * area) - comRelY * comRelY;
|
|
358
|
+
const czz = szz24 / (24 * area) - comRelZ * comRelZ;
|
|
359
|
+
const cxy = sxy24 / (24 * area) - comRelX * comRelY;
|
|
360
|
+
const cxz = sxz24 / (24 * area) - comRelX * comRelZ;
|
|
361
|
+
const cyz = syz24 / (24 * area) - comRelY * comRelZ;
|
|
362
|
+
const ixx = cyy + czz;
|
|
363
|
+
const iyy = cxx + czz;
|
|
364
|
+
const izz = cxx + cyy;
|
|
365
|
+
if (!(ixx > 1e-12 && iyy > 1e-12 && izz > 1e-12)) throw new KhrValidationError(`Collider mesh "${label}" is degenerate (1D collinear strip); cannot compute positive 3D inertia`);
|
|
366
|
+
return {
|
|
367
|
+
measure: area,
|
|
368
|
+
isVolumetric: false,
|
|
369
|
+
centroid: new THREE.Vector3(rx + comRelX, ry + comRelY, rz + comRelZ),
|
|
370
|
+
unitTensor: [
|
|
371
|
+
ixx,
|
|
372
|
+
iyy,
|
|
373
|
+
izz,
|
|
374
|
+
-cxy,
|
|
375
|
+
-cxz,
|
|
376
|
+
-cyz
|
|
377
|
+
]
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
function deduplicateQuantizedPoints(vertices) {
|
|
381
|
+
const pts = [];
|
|
382
|
+
const seen = /* @__PURE__ */ new Set();
|
|
383
|
+
for (let i = 0; i < vertices.length; i += 3) {
|
|
384
|
+
const vx = vertices[i], vy = vertices[i + 1], vz = vertices[i + 2];
|
|
385
|
+
const key = `${Math.round(vx * 1e5)},${Math.round(vy * 1e5)},${Math.round(vz * 1e5)}`;
|
|
386
|
+
if (!seen.has(key)) {
|
|
387
|
+
seen.add(key);
|
|
388
|
+
pts.push(new THREE.Vector3(vx, vy, vz));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return pts;
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Exact 2D Andrew Monotone Chain convex hull in the best-fit plane of coplanar 3D points `pts`,
|
|
395
|
+
* returning CCW-ordered perimeter vertices so triangle fan integration never self-intersects.
|
|
396
|
+
*/
|
|
397
|
+
function buildCoplanarConvexPolygon(pts, label) {
|
|
398
|
+
const p0 = pts[0];
|
|
399
|
+
let bestNormal = new THREE.Vector3();
|
|
400
|
+
let bestNormSq = 0;
|
|
401
|
+
const e1 = new THREE.Vector3();
|
|
402
|
+
const e2 = new THREE.Vector3();
|
|
403
|
+
const nCand = new THREE.Vector3();
|
|
404
|
+
for (let i = 1; i < pts.length; i++) {
|
|
405
|
+
e1.subVectors(pts[i], p0);
|
|
406
|
+
for (let j = i + 1; j < pts.length; j++) {
|
|
407
|
+
e2.subVectors(pts[j], p0);
|
|
408
|
+
nCand.crossVectors(e1, e2);
|
|
409
|
+
const sq = nCand.lengthSq();
|
|
410
|
+
if (sq > bestNormSq) {
|
|
411
|
+
bestNormSq = sq;
|
|
412
|
+
bestNormal.copy(nCand);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
if (!(bestNormSq > 1e-20)) throw new KhrValidationError(`ConvexHull collider "${label}" has collinear vertices (zero 2D hull area)`);
|
|
417
|
+
bestNormal.normalize();
|
|
418
|
+
const axisU = new THREE.Vector3();
|
|
419
|
+
if (Math.abs(bestNormal.x) < .9) axisU.set(1, 0, 0).cross(bestNormal).normalize();
|
|
420
|
+
else axisU.set(0, 1, 0).cross(bestNormal).normalize();
|
|
421
|
+
const axisV = new THREE.Vector3().crossVectors(bestNormal, axisU).normalize();
|
|
422
|
+
const projected = pts.map((p) => {
|
|
423
|
+
const d = e1.subVectors(p, p0);
|
|
424
|
+
return {
|
|
425
|
+
u: d.dot(axisU),
|
|
426
|
+
v: d.dot(axisV),
|
|
427
|
+
p
|
|
428
|
+
};
|
|
429
|
+
});
|
|
430
|
+
projected.sort((a, b) => a.u !== b.u ? a.u - b.u : a.v - b.v);
|
|
431
|
+
const cross2 = (o, a, b) => (a.u - o.u) * (b.v - o.v) - (a.v - o.v) * (b.u - o.u);
|
|
432
|
+
const lower = [];
|
|
433
|
+
for (const pt of projected) {
|
|
434
|
+
while (lower.length >= 2 && cross2(lower[lower.length - 2], lower[lower.length - 1], pt) <= 1e-12) lower.pop();
|
|
435
|
+
lower.push(pt);
|
|
436
|
+
}
|
|
437
|
+
const upper = [];
|
|
438
|
+
for (let i = projected.length - 1; i >= 0; i--) {
|
|
439
|
+
const pt = projected[i];
|
|
440
|
+
while (upper.length >= 2 && cross2(upper[upper.length - 2], upper[upper.length - 1], pt) <= 1e-12) upper.pop();
|
|
441
|
+
upper.push(pt);
|
|
442
|
+
}
|
|
443
|
+
lower.pop();
|
|
444
|
+
upper.pop();
|
|
445
|
+
const hull = [...lower, ...upper];
|
|
446
|
+
if (hull.length < 3) throw new KhrValidationError(`ConvexHull collider "${label}" has fewer than 3 non-collinear hull vertices`);
|
|
447
|
+
const fanVerts = new Float32Array((hull.length - 2) * 9);
|
|
448
|
+
let o = 0;
|
|
449
|
+
for (let i = 1; i + 1 < hull.length; i++) {
|
|
450
|
+
fanVerts[o++] = hull[0].p.x;
|
|
451
|
+
fanVerts[o++] = hull[0].p.y;
|
|
452
|
+
fanVerts[o++] = hull[0].p.z;
|
|
453
|
+
fanVerts[o++] = hull[i].p.x;
|
|
454
|
+
fanVerts[o++] = hull[i].p.y;
|
|
455
|
+
fanVerts[o++] = hull[i].p.z;
|
|
456
|
+
fanVerts[o++] = hull[i + 1].p.x;
|
|
457
|
+
fanVerts[o++] = hull[i + 1].p.y;
|
|
458
|
+
fanVerts[o++] = hull[i + 1].p.z;
|
|
459
|
+
}
|
|
460
|
+
return fanVerts;
|
|
461
|
+
}
|
|
462
|
+
function unitInertiaForShape(shape) {
|
|
463
|
+
if (shape.type === "box") {
|
|
464
|
+
const [x, y, z] = shape.size;
|
|
465
|
+
return {
|
|
466
|
+
measure: x * y * z,
|
|
467
|
+
isVolumetric: true,
|
|
468
|
+
centroid: new THREE.Vector3(),
|
|
469
|
+
unitTensor: [
|
|
470
|
+
(y * y + z * z) / 12,
|
|
471
|
+
(x * x + z * z) / 12,
|
|
472
|
+
(x * x + y * y) / 12,
|
|
473
|
+
0,
|
|
474
|
+
0,
|
|
475
|
+
0
|
|
476
|
+
]
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
if (shape.type === "sphere") {
|
|
480
|
+
const r = shape.radius;
|
|
481
|
+
const i = .4 * r * r;
|
|
482
|
+
return {
|
|
483
|
+
measure: 4 / 3 * Math.PI * r * r * r,
|
|
484
|
+
isVolumetric: true,
|
|
485
|
+
centroid: new THREE.Vector3(),
|
|
486
|
+
unitTensor: [
|
|
487
|
+
i,
|
|
488
|
+
i,
|
|
489
|
+
i,
|
|
490
|
+
0,
|
|
491
|
+
0,
|
|
492
|
+
0
|
|
493
|
+
]
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
if (shape.type === "trimesh") return integrateClosedMeshProps(shape.vertices, shape.indices) ?? integrateSurfaceShellProps(shape.vertices, shape.indices, shape.meshNodeName);
|
|
497
|
+
if (shape.type === "convexHull") {
|
|
498
|
+
const pts = deduplicateQuantizedPoints(shape.vertices);
|
|
499
|
+
if (pts.length >= 4) try {
|
|
500
|
+
const hullGeo = new ConvexGeometry(pts);
|
|
501
|
+
const pos = hullGeo.getAttribute("position");
|
|
502
|
+
const closed = pos && pos.count >= 12 ? integrateClosedMeshProps(pos.array, null) : null;
|
|
503
|
+
hullGeo.dispose();
|
|
504
|
+
if (closed) return closed;
|
|
505
|
+
} catch {}
|
|
506
|
+
if (pts.length >= 3) return integrateSurfaceShellProps(buildCoplanarConvexPolygon(pts, shape.meshNodeName), null, shape.meshNodeName);
|
|
507
|
+
throw new KhrValidationError(`ConvexHull collider "${shape.meshNodeName}" has fewer than 3 distinct vertices`);
|
|
508
|
+
}
|
|
509
|
+
const r = shape.radiusTop;
|
|
510
|
+
const h = shape.height;
|
|
511
|
+
if (shape.type === "capsule") {
|
|
512
|
+
const cylVol = Math.PI * r * r * h;
|
|
513
|
+
const totVol = cylVol + 4 / 3 * Math.PI * r * r * r;
|
|
514
|
+
const fc = cylVol / totVol;
|
|
515
|
+
const fh = 1 - fc;
|
|
516
|
+
const iy = .5 * fc * r * r + .4 * fh * r * r;
|
|
517
|
+
const ix = fc * (h * h / 12 + .25 * r * r) + fh * (.4 * r * r + .25 * h * h + .375 * h * r);
|
|
518
|
+
return {
|
|
519
|
+
measure: totVol,
|
|
520
|
+
isVolumetric: true,
|
|
521
|
+
centroid: new THREE.Vector3(),
|
|
522
|
+
unitTensor: [
|
|
523
|
+
ix,
|
|
524
|
+
iy,
|
|
525
|
+
ix,
|
|
526
|
+
0,
|
|
527
|
+
0,
|
|
528
|
+
0
|
|
529
|
+
]
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
const ix = (3 * r * r + h * h) / 12;
|
|
533
|
+
return {
|
|
534
|
+
measure: Math.PI * r * r * h,
|
|
535
|
+
isVolumetric: true,
|
|
536
|
+
centroid: new THREE.Vector3(),
|
|
537
|
+
unitTensor: [
|
|
538
|
+
ix,
|
|
539
|
+
.5 * r * r,
|
|
540
|
+
ix,
|
|
541
|
+
0,
|
|
542
|
+
0,
|
|
543
|
+
0
|
|
544
|
+
]
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Computes exact principal inertia diagonal `[I1, I2, I3]` for a single `KhrColliderShape` of `mass` kg
|
|
549
|
+
* about its centroid.
|
|
550
|
+
*/
|
|
551
|
+
function computeShapeInertia(shape, mass) {
|
|
552
|
+
const [ixx, iyy, izz, ixy, ixz, iyz] = unitInertiaForShape(shape).unitTensor;
|
|
553
|
+
if (Math.abs(ixy) + Math.abs(ixz) + Math.abs(iyz) > 1e-12 * (ixx + iyy + izz)) {
|
|
554
|
+
const { inertia } = jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz);
|
|
555
|
+
return [
|
|
556
|
+
mass * inertia[0],
|
|
557
|
+
mass * inertia[1],
|
|
558
|
+
mass * inertia[2]
|
|
559
|
+
];
|
|
560
|
+
}
|
|
561
|
+
return [
|
|
562
|
+
mass * ixx,
|
|
563
|
+
mass * iyy,
|
|
564
|
+
mass * izz
|
|
565
|
+
];
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Resolves exact center of mass, full 3x3 Steiner parallel-axis inertia tensor, and Jacobi principal frame
|
|
569
|
+
* for a dynamic `KhrBodySpec` from its colliders when `motion.inertiaDiagonal` is omitted in the `.glb`.
|
|
570
|
+
*/
|
|
571
|
+
function resolveBodyMassFromColliders(colliders, mass, explicitCom, explicitInertiaOrientation, nodeName) {
|
|
572
|
+
if (colliders.length === 0) throw new KhrValidationError(`Dynamic node "${nodeName}" is missing motion.inertiaDiagonal and has no colliders`);
|
|
573
|
+
const shapes = colliders.map((c) => unitInertiaForShape(c.shape));
|
|
574
|
+
const hasVolumetric = shapes.some((s) => s.isVolumetric);
|
|
575
|
+
let totalWeight = 0;
|
|
576
|
+
for (const s of shapes) if (!hasVolumetric || s.isVolumetric) totalWeight += s.measure;
|
|
577
|
+
const colQuat = new THREE.Quaternion();
|
|
578
|
+
const worldCentroids = [];
|
|
579
|
+
let wx = 0, wy = 0, wz = 0;
|
|
580
|
+
for (let i = 0; i < colliders.length; i++) {
|
|
581
|
+
const col = colliders[i];
|
|
582
|
+
const shp = shapes[i];
|
|
583
|
+
const w = !hasVolumetric || shp.isVolumetric ? shp.measure : 0;
|
|
584
|
+
colQuat.fromArray(col.localQuaternion);
|
|
585
|
+
const cBody = shp.centroid.clone().applyQuaternion(colQuat).add(new THREE.Vector3().fromArray(col.localPosition));
|
|
586
|
+
worldCentroids.push(cBody);
|
|
587
|
+
wx += cBody.x * w;
|
|
588
|
+
wy += cBody.y * w;
|
|
589
|
+
wz += cBody.z * w;
|
|
590
|
+
}
|
|
591
|
+
const com = explicitCom ?? (totalWeight > 0 ? [
|
|
592
|
+
wx / totalWeight,
|
|
593
|
+
wy / totalWeight,
|
|
594
|
+
wz / totalWeight
|
|
595
|
+
] : [
|
|
596
|
+
0,
|
|
597
|
+
0,
|
|
598
|
+
0
|
|
599
|
+
]);
|
|
600
|
+
const invFrame = explicitInertiaOrientation ? new THREE.Quaternion().fromArray(explicitInertiaOrientation).invert() : new THREE.Quaternion();
|
|
601
|
+
const relQuat = new THREE.Quaternion();
|
|
602
|
+
const offset = new THREE.Vector3();
|
|
603
|
+
const rotMat = new THREE.Matrix4();
|
|
604
|
+
const m = rotMat.elements;
|
|
605
|
+
let ixx = 0, iyy = 0, izz = 0, ixy = 0, ixz = 0, iyz = 0;
|
|
606
|
+
for (let i = 0; i < colliders.length; i++) {
|
|
607
|
+
const col = colliders[i];
|
|
608
|
+
const shp = shapes[i];
|
|
609
|
+
const w = !hasVolumetric || shp.isVolumetric ? shp.measure : 0;
|
|
610
|
+
const mShare = totalWeight > 0 ? mass * (w / totalWeight) : mass / colliders.length;
|
|
611
|
+
if (mShare <= 0) continue;
|
|
612
|
+
colQuat.fromArray(col.localQuaternion);
|
|
613
|
+
offset.copy(worldCentroids[i]).sub(new THREE.Vector3(com[0], com[1], com[2])).applyQuaternion(invFrame);
|
|
614
|
+
relQuat.copy(invFrame).multiply(colQuat);
|
|
615
|
+
rotMat.makeRotationFromQuaternion(relQuat);
|
|
616
|
+
const [uxx, uyy, uzz, uxy, uxz, uyz] = shp.unitTensor;
|
|
617
|
+
const r00 = m[0], r01 = m[4], r02 = m[8];
|
|
618
|
+
const r10 = m[1], r11 = m[5], r12 = m[9];
|
|
619
|
+
const r20 = m[2], r21 = m[6], r22 = m[10];
|
|
620
|
+
const a00 = uxx * r00 + uxy * r01 + uxz * r02;
|
|
621
|
+
const a01 = uxy * r00 + uyy * r01 + uyz * r02;
|
|
622
|
+
const a02 = uxz * r00 + uyz * r01 + uzz * r02;
|
|
623
|
+
const a10 = uxx * r10 + uxy * r11 + uxz * r12;
|
|
624
|
+
const a11 = uxy * r10 + uyy * r11 + uyz * r12;
|
|
625
|
+
const a12 = uxz * r10 + uyz * r11 + uzz * r12;
|
|
626
|
+
const txx = r00 * a00 + r01 * a01 + r02 * a02;
|
|
627
|
+
const tyy = r10 * a10 + r11 * a11 + r12 * a12;
|
|
628
|
+
const tzz = r20 * (uxx * r20 + uxy * r21 + uxz * r22) + r21 * (uxy * r20 + uyy * r21 + uyz * r22) + r22 * (uxz * r20 + uyz * r21 + uzz * r22);
|
|
629
|
+
const txy = r00 * a10 + r01 * a11 + r02 * a12;
|
|
630
|
+
const txz = r00 * (uxx * r20 + uxy * r21 + uxz * r22) + r01 * (uxy * r20 + uyy * r21 + uyz * r22) + r02 * (uxz * r20 + uyz * r21 + uzz * r22);
|
|
631
|
+
const tyz = r10 * (uxx * r20 + uxy * r21 + uxz * r22) + r11 * (uxy * r20 + uyy * r21 + uyz * r22) + r12 * (uxz * r20 + uyz * r21 + uzz * r22);
|
|
632
|
+
const dx = offset.x, dy = offset.y, dz = offset.z;
|
|
633
|
+
ixx += mShare * (txx + dy * dy + dz * dz);
|
|
634
|
+
iyy += mShare * (tyy + dx * dx + dz * dz);
|
|
635
|
+
izz += mShare * (tzz + dx * dx + dy * dy);
|
|
636
|
+
ixy += mShare * (txy - dx * dy);
|
|
637
|
+
ixz += mShare * (txz - dx * dz);
|
|
638
|
+
iyz += mShare * (tyz - dy * dz);
|
|
639
|
+
}
|
|
640
|
+
if (!Number.isFinite(ixx) || !Number.isFinite(iyy) || !Number.isFinite(izz) || ixx <= 0 || iyy <= 0 || izz <= 0) throw new KhrValidationError(`Dynamic node "${nodeName}" has degenerate collider geometry; cannot compute positive motion.inertiaDiagonal`);
|
|
641
|
+
if (explicitInertiaOrientation) return {
|
|
642
|
+
centerOfMass: com,
|
|
643
|
+
inertiaDiagonal: [
|
|
644
|
+
ixx,
|
|
645
|
+
iyy,
|
|
646
|
+
izz
|
|
647
|
+
],
|
|
648
|
+
inertiaOrientation: explicitInertiaOrientation
|
|
649
|
+
};
|
|
650
|
+
const diagSum = Math.max(ixx + iyy + izz, 0);
|
|
651
|
+
if (Math.max(Math.abs(ixy), Math.abs(ixz), Math.abs(iyz)) <= 1e-12 * diagSum) return {
|
|
652
|
+
centerOfMass: com,
|
|
653
|
+
inertiaDiagonal: [
|
|
654
|
+
ixx,
|
|
655
|
+
iyy,
|
|
656
|
+
izz
|
|
657
|
+
],
|
|
658
|
+
inertiaOrientation: [
|
|
659
|
+
0,
|
|
660
|
+
0,
|
|
661
|
+
0,
|
|
662
|
+
1
|
|
663
|
+
]
|
|
664
|
+
};
|
|
665
|
+
const { inertia, inertiaFrame } = jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz);
|
|
666
|
+
return {
|
|
667
|
+
centerOfMass: com,
|
|
668
|
+
inertiaDiagonal: inertia,
|
|
669
|
+
inertiaOrientation: inertiaFrame
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
function computeAssemblyMassAndCom(bodies) {
|
|
673
|
+
let totalDynamicMass = 0, mx = 0, my = 0, mz = 0;
|
|
674
|
+
const q = new THREE.Quaternion();
|
|
675
|
+
const c = new THREE.Vector3();
|
|
676
|
+
for (const b of bodies) {
|
|
677
|
+
if (b.isKinematic) continue;
|
|
678
|
+
totalDynamicMass += b.mass;
|
|
679
|
+
c.fromArray(b.centerOfMass).applyQuaternion(q.fromArray(b.localQuaternion));
|
|
680
|
+
mx += (b.localPosition[0] + c.x) * b.mass;
|
|
681
|
+
my += (b.localPosition[1] + c.y) * b.mass;
|
|
682
|
+
mz += (b.localPosition[2] + c.z) * b.mass;
|
|
683
|
+
}
|
|
684
|
+
return {
|
|
685
|
+
totalDynamicMass,
|
|
686
|
+
centerOfMass: totalDynamicMass > 0 ? [
|
|
687
|
+
mx / totalDynamicMass,
|
|
688
|
+
my / totalDynamicMass,
|
|
689
|
+
mz / totalDynamicMass
|
|
690
|
+
] : [
|
|
691
|
+
0,
|
|
692
|
+
0,
|
|
693
|
+
0
|
|
694
|
+
]
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
function bodyPoseMatrix(body, target = new THREE.Matrix4()) {
|
|
698
|
+
return target.compose(new THREE.Vector3().fromArray(body.localPosition), new THREE.Quaternion().fromArray(body.localQuaternion), _one);
|
|
699
|
+
}
|
|
700
|
+
function decomposeBodyInFrame(body, invFrame, posOut, quatOut, sclScratch, matScratch) {
|
|
701
|
+
if (invFrame) {
|
|
702
|
+
matScratch.multiplyMatrices(invFrame, bodyPoseMatrix(body, matScratch)).decompose(posOut, quatOut, sclScratch);
|
|
703
|
+
quatOut.normalize();
|
|
704
|
+
} else {
|
|
705
|
+
posOut.fromArray(body.localPosition);
|
|
706
|
+
quatOut.fromArray(body.localQuaternion).normalize();
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
function computeLumpedMassProps(bodies, invFrame) {
|
|
710
|
+
const dyn = bodies.filter((b) => !b.isKinematic && b.mass > 0);
|
|
711
|
+
if (dyn.length === 0) return null;
|
|
712
|
+
const pos = new THREE.Vector3();
|
|
713
|
+
const quat = new THREE.Quaternion();
|
|
714
|
+
const qExtra = new THREE.Quaternion();
|
|
715
|
+
const rCom = new THREE.Vector3();
|
|
716
|
+
const scl = new THREE.Vector3();
|
|
717
|
+
const mat = new THREE.Matrix4();
|
|
718
|
+
if (dyn.length === 1) {
|
|
719
|
+
const b = dyn[0];
|
|
720
|
+
decomposeBodyInFrame(b, invFrame, pos, quat, scl, mat);
|
|
721
|
+
rCom.fromArray(b.centerOfMass).applyQuaternion(quat);
|
|
722
|
+
const frameQuat = quat.clone().multiply(qExtra.fromArray(b.inertiaOrientation)).normalize();
|
|
723
|
+
return {
|
|
724
|
+
mass: b.mass,
|
|
725
|
+
com: [
|
|
726
|
+
pos.x + rCom.x,
|
|
727
|
+
pos.y + rCom.y,
|
|
728
|
+
pos.z + rCom.z
|
|
729
|
+
],
|
|
730
|
+
inertia: [
|
|
731
|
+
b.inertiaDiagonal[0],
|
|
732
|
+
b.inertiaDiagonal[1],
|
|
733
|
+
b.inertiaDiagonal[2]
|
|
734
|
+
],
|
|
735
|
+
inertiaFrame: [
|
|
736
|
+
frameQuat.x,
|
|
737
|
+
frameQuat.y,
|
|
738
|
+
frameQuat.z,
|
|
739
|
+
frameQuat.w
|
|
740
|
+
]
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
let totalMass = 0, mx = 0, my = 0, mz = 0;
|
|
744
|
+
for (const b of dyn) {
|
|
745
|
+
decomposeBodyInFrame(b, invFrame, pos, quat, scl, mat);
|
|
746
|
+
rCom.fromArray(b.centerOfMass).applyQuaternion(quat);
|
|
747
|
+
totalMass += b.mass;
|
|
748
|
+
mx += (pos.x + rCom.x) * b.mass;
|
|
749
|
+
my += (pos.y + rCom.y) * b.mass;
|
|
750
|
+
mz += (pos.z + rCom.z) * b.mass;
|
|
751
|
+
}
|
|
752
|
+
if (!(totalMass > 0)) return null;
|
|
753
|
+
const com = [
|
|
754
|
+
mx / totalMass,
|
|
755
|
+
my / totalMass,
|
|
756
|
+
mz / totalMass
|
|
757
|
+
];
|
|
758
|
+
let ixx = 0, iyy = 0, izz = 0, ixy = 0, ixz = 0, iyz = 0;
|
|
759
|
+
const m = mat.elements;
|
|
760
|
+
for (const b of dyn) {
|
|
761
|
+
decomposeBodyInFrame(b, invFrame, pos, quat, scl, mat);
|
|
762
|
+
rCom.fromArray(b.centerOfMass).applyQuaternion(quat);
|
|
763
|
+
const dx = pos.x + rCom.x - com[0];
|
|
764
|
+
const dy = pos.y + rCom.y - com[1];
|
|
765
|
+
const dz = pos.z + rCom.z - com[2];
|
|
766
|
+
mat.makeRotationFromQuaternion(quat.multiply(qExtra.fromArray(b.inertiaOrientation)));
|
|
767
|
+
const [d0, d1, d2] = b.inertiaDiagonal;
|
|
768
|
+
ixx += m[0] * m[0] * d0 + m[4] * m[4] * d1 + m[8] * m[8] * d2 + b.mass * (dy * dy + dz * dz);
|
|
769
|
+
iyy += m[1] * m[1] * d0 + m[5] * m[5] * d1 + m[9] * m[9] * d2 + b.mass * (dx * dx + dz * dz);
|
|
770
|
+
izz += m[2] * m[2] * d0 + m[6] * m[6] * d1 + m[10] * m[10] * d2 + b.mass * (dx * dx + dy * dy);
|
|
771
|
+
ixy += m[0] * m[1] * d0 + m[4] * m[5] * d1 + m[8] * m[9] * d2 - b.mass * dx * dy;
|
|
772
|
+
ixz += m[0] * m[2] * d0 + m[4] * m[6] * d1 + m[8] * m[10] * d2 - b.mass * dx * dz;
|
|
773
|
+
iyz += m[1] * m[2] * d0 + m[5] * m[6] * d1 + m[9] * m[10] * d2 - b.mass * dy * dz;
|
|
774
|
+
}
|
|
775
|
+
const diagSum = Math.max(ixx + iyy + izz, 0);
|
|
776
|
+
if (Math.max(Math.abs(ixy), Math.abs(ixz), Math.abs(iyz)) <= 1e-12 * diagSum) return {
|
|
777
|
+
mass: totalMass,
|
|
778
|
+
com,
|
|
779
|
+
inertia: [
|
|
780
|
+
ixx,
|
|
781
|
+
iyy,
|
|
782
|
+
izz
|
|
783
|
+
],
|
|
784
|
+
inertiaFrame: [
|
|
785
|
+
0,
|
|
786
|
+
0,
|
|
787
|
+
0,
|
|
788
|
+
1
|
|
789
|
+
]
|
|
790
|
+
};
|
|
791
|
+
const { inertia, inertiaFrame } = jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz);
|
|
792
|
+
return {
|
|
793
|
+
mass: totalMass,
|
|
794
|
+
com,
|
|
795
|
+
inertia,
|
|
796
|
+
inertiaFrame
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Applies exact `LumpedMassProps` directly in `RigidBody` local space (`density = 0` on colliders).
|
|
801
|
+
*/
|
|
802
|
+
function applyRapierBodyMass(rb, lumped) {
|
|
803
|
+
if (!lumped || !(lumped.mass > 0)) return;
|
|
804
|
+
const n = rb.numColliders();
|
|
805
|
+
for (let i = 0; i < n; i++) rb.collider(i).setDensity(0);
|
|
806
|
+
rb.setAdditionalMassProperties(lumped.mass, {
|
|
807
|
+
x: lumped.com[0],
|
|
808
|
+
y: lumped.com[1],
|
|
809
|
+
z: lumped.com[2]
|
|
810
|
+
}, {
|
|
811
|
+
x: lumped.inertia[0],
|
|
812
|
+
y: lumped.inertia[1],
|
|
813
|
+
z: lumped.inertia[2]
|
|
814
|
+
}, {
|
|
815
|
+
x: lumped.inertiaFrame[0],
|
|
816
|
+
y: lumped.inertiaFrame[1],
|
|
817
|
+
z: lumped.inertiaFrame[2],
|
|
818
|
+
w: lumped.inertiaFrame[3]
|
|
819
|
+
}, true);
|
|
820
|
+
rb.recomputeMassPropertiesFromColliders();
|
|
821
|
+
}
|
|
822
|
+
// src/clone.ts
|
|
823
|
+
var mountedScenes = /* @__PURE__ */ new WeakSet();
|
|
824
|
+
var clonedScenes = /* @__PURE__ */ new WeakSet();
|
|
825
|
+
var disposedScenes = /* @__PURE__ */ new WeakSet();
|
|
826
|
+
var templateByClone = /* @__PURE__ */ new WeakMap();
|
|
827
|
+
var subtreeRestorersByScene = /* @__PURE__ */ new WeakMap();
|
|
828
|
+
function findSceneRoot(obj) {
|
|
829
|
+
let cur = obj;
|
|
830
|
+
while (cur.parent) cur = cur.parent;
|
|
831
|
+
return cur;
|
|
832
|
+
}
|
|
833
|
+
function registerMountedSubtree(ownerScene, restoreForClone) {
|
|
834
|
+
let set = subtreeRestorersByScene.get(ownerScene);
|
|
835
|
+
if (!set) {
|
|
836
|
+
set = /* @__PURE__ */ new Set();
|
|
837
|
+
subtreeRestorersByScene.set(ownerScene, set);
|
|
838
|
+
}
|
|
839
|
+
set.add(restoreForClone);
|
|
840
|
+
return () => {
|
|
841
|
+
set?.delete(restoreForClone);
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
function claimBundleMount(bundle, ownerComponent) {
|
|
845
|
+
if (disposedScenes.has(bundle.scene)) throw new KhrValidationError(`${ownerComponent}: KhrAssetBundle "${bundle.scene.name || bundle.scene.uuid}" has already been disposed`);
|
|
846
|
+
if (mountedScenes.has(bundle.scene)) throw new KhrValidationError(`${ownerComponent}: KhrAssetBundle "${bundle.scene.name || bundle.scene.uuid}" is already mounted; call cloneKhrBundle(template) per concurrent instance`);
|
|
847
|
+
mountedScenes.add(bundle.scene);
|
|
848
|
+
}
|
|
849
|
+
function releaseBundleMount(bundle) {
|
|
850
|
+
mountedScenes.delete(bundle.scene);
|
|
851
|
+
}
|
|
852
|
+
function remapNode(srcRoot, node, dstRoot) {
|
|
853
|
+
if (node === srcRoot) return dstRoot;
|
|
854
|
+
const path = [];
|
|
855
|
+
let cur = node;
|
|
856
|
+
while (cur && cur !== srcRoot) {
|
|
857
|
+
const parent = cur.parent;
|
|
858
|
+
if (!parent) throw new KhrValidationError(`cloneKhrBundle: body node "${node.name}" is detached from bundle.scene`);
|
|
859
|
+
const idx = parent.children.indexOf(cur);
|
|
860
|
+
if (idx < 0) throw new KhrValidationError(`cloneKhrBundle: child index missing for "${node.name}"`);
|
|
861
|
+
path.push(idx);
|
|
862
|
+
cur = parent;
|
|
863
|
+
}
|
|
864
|
+
let out = dstRoot;
|
|
865
|
+
for (let i = path.length - 1; i >= 0; i--) out = out.children[path[i]];
|
|
866
|
+
return out;
|
|
867
|
+
}
|
|
868
|
+
function cloneCurve(curve) {
|
|
869
|
+
if (!curve) return void 0;
|
|
870
|
+
return {
|
|
871
|
+
...curve,
|
|
872
|
+
points: curve.points.map((pt) => ({ ...pt }))
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
function cloneCarTune(tune) {
|
|
876
|
+
if (!tune) return void 0;
|
|
877
|
+
return {
|
|
878
|
+
...tune,
|
|
879
|
+
...tune.gearRatios ? { gearRatios: [...tune.gearRatios] } : {},
|
|
880
|
+
...tune.engineTorqueCurveData ? { engineTorqueCurveData: cloneCurve(tune.engineTorqueCurveData) } : {},
|
|
881
|
+
...tune.steerAngleCurveData ? { steerAngleCurveData: cloneCurve(tune.steerAngleCurveData) } : {}
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Returns a structural `Object3D` clone with any mounted `RotorVisualSlot` / `MountSubtreeSlot`
|
|
886
|
+
* subtrees restored synchronously when `root` is currently mounted, or `root` itself otherwise.
|
|
887
|
+
*/
|
|
888
|
+
function snapshotSceneWithMountedSubtrees(root) {
|
|
889
|
+
const scopedSet = subtreeRestorersByScene.get(root);
|
|
890
|
+
if (!scopedSet || scopedSet.size === 0) return root;
|
|
891
|
+
const restorers = [...scopedSet];
|
|
892
|
+
const reattach = [];
|
|
893
|
+
for (let i = restorers.length - 1; i >= 0; i--) reattach.push(restorers[i]());
|
|
894
|
+
try {
|
|
895
|
+
return root.clone(true);
|
|
896
|
+
} finally {
|
|
897
|
+
for (let i = reattach.length - 1; i >= 0; i--) reattach[i]();
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* Clones a parsed `KhrAssetBundle` in O(nodes) while sharing GPU `BufferGeometry` / `Material` buffers
|
|
902
|
+
* and Rapier `Float32Array` collider vertices. Only restores subtrees belonging to `bundle.scene`.
|
|
903
|
+
*/
|
|
904
|
+
function cloneKhrBundle(bundle) {
|
|
905
|
+
if (disposedScenes.has(bundle.scene)) throw new KhrValidationError(`cloneKhrBundle: cannot clone disposed KhrAssetBundle "${bundle.scene.name || bundle.scene.uuid}"`);
|
|
906
|
+
const scopedSet = subtreeRestorersByScene.get(bundle.scene);
|
|
907
|
+
const restorers = scopedSet ? [...scopedSet] : [];
|
|
908
|
+
const reattach = [];
|
|
909
|
+
for (let i = restorers.length - 1; i >= 0; i--) reattach.push(restorers[i]());
|
|
910
|
+
try {
|
|
911
|
+
const scene = bundle.scene.clone(true);
|
|
912
|
+
clonedScenes.add(scene);
|
|
913
|
+
templateByClone.set(scene, templateByClone.get(bundle.scene) ?? bundle.scene);
|
|
914
|
+
const sockets = Object.create(null);
|
|
915
|
+
for (const [k, v] of Object.entries(bundle.sockets)) sockets[k] = [
|
|
916
|
+
v[0],
|
|
917
|
+
v[1],
|
|
918
|
+
v[2]
|
|
919
|
+
];
|
|
920
|
+
return {
|
|
921
|
+
scene,
|
|
922
|
+
bodies: bundle.bodies.map((b) => {
|
|
923
|
+
const drives = b.joint ? b.joint.drives.map((d) => ({ ...d })) : [];
|
|
924
|
+
return {
|
|
925
|
+
...b,
|
|
926
|
+
centerOfMass: [...b.centerOfMass],
|
|
927
|
+
inertiaDiagonal: [...b.inertiaDiagonal],
|
|
928
|
+
inertiaOrientation: [...b.inertiaOrientation],
|
|
929
|
+
...b.linearVelocity ? { linearVelocity: [...b.linearVelocity] } : {},
|
|
930
|
+
...b.angularVelocity ? { angularVelocity: [...b.angularVelocity] } : {},
|
|
931
|
+
localPosition: [...b.localPosition],
|
|
932
|
+
localQuaternion: [...b.localQuaternion],
|
|
933
|
+
colliders: b.colliders.map((c) => ({
|
|
934
|
+
...c,
|
|
935
|
+
shape: c.shape.type === "box" ? {
|
|
936
|
+
...c.shape,
|
|
937
|
+
size: [...c.shape.size]
|
|
938
|
+
} : { ...c.shape },
|
|
939
|
+
localPosition: [...c.localPosition],
|
|
940
|
+
localQuaternion: [...c.localQuaternion]
|
|
941
|
+
})),
|
|
942
|
+
joint: b.joint ? {
|
|
943
|
+
...b.joint,
|
|
944
|
+
axis: [...b.joint.axis],
|
|
945
|
+
limits: b.joint.limits ? [...b.joint.limits] : null,
|
|
946
|
+
drive: drives[0] ?? (b.joint.drive ? { ...b.joint.drive } : null),
|
|
947
|
+
drives,
|
|
948
|
+
anchor1: [...b.joint.anchor1],
|
|
949
|
+
anchor2: [...b.joint.anchor2]
|
|
950
|
+
} : null,
|
|
951
|
+
...b.breakaway ? { breakaway: { ...b.breakaway } } : {},
|
|
952
|
+
object: remapNode(bundle.scene, b.object, scene)
|
|
953
|
+
};
|
|
954
|
+
}),
|
|
955
|
+
wheels: bundle.wheels.map((w) => ({
|
|
956
|
+
...w,
|
|
957
|
+
object: remapNode(bundle.scene, w.object, scene),
|
|
958
|
+
position: [...w.position],
|
|
959
|
+
...w.quaternion ? { quaternion: [...w.quaternion] } : {},
|
|
960
|
+
...w.lngSlipRatioCurveData ? { lngSlipRatioCurveData: cloneCurve(w.lngSlipRatioCurveData) } : {},
|
|
961
|
+
...w.latSlipRatioCurveData ? { latSlipRatioCurveData: cloneCurve(w.latSlipRatioCurveData) } : {}
|
|
962
|
+
})),
|
|
963
|
+
propellers: bundle.propellers.map((p) => ({
|
|
964
|
+
...p,
|
|
965
|
+
object: remapNode(bundle.scene, p.object, scene),
|
|
966
|
+
position: [...p.position],
|
|
967
|
+
...p.quaternion ? { quaternion: [...p.quaternion] } : {}
|
|
968
|
+
})),
|
|
969
|
+
emitters: bundle.emitters.map((e) => ({
|
|
970
|
+
...e,
|
|
971
|
+
...e.color ? { color: [...e.color] } : {},
|
|
972
|
+
position: [...e.position],
|
|
973
|
+
quaternion: [...e.quaternion],
|
|
974
|
+
object: remapNode(bundle.scene, e.object, scene)
|
|
975
|
+
})),
|
|
976
|
+
sockets,
|
|
977
|
+
totalDynamicMass: bundle.totalDynamicMass,
|
|
978
|
+
centerOfMass: [...bundle.centerOfMass],
|
|
979
|
+
...bundle.tune ? { tune: cloneCarTune(bundle.tune) } : {},
|
|
980
|
+
...bundle.droneTune ? { droneTune: { ...bundle.droneTune } } : {}
|
|
981
|
+
};
|
|
982
|
+
} finally {
|
|
983
|
+
for (let i = reattach.length - 1; i >= 0; i--) reattach[i]();
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
function disposeSceneGpuResources(roots) {
|
|
987
|
+
const geos = /* @__PURE__ */ new Set();
|
|
988
|
+
const mats = /* @__PURE__ */ new Set();
|
|
989
|
+
const texs = /* @__PURE__ */ new Set();
|
|
990
|
+
for (const root of roots) root.traverse((child) => {
|
|
991
|
+
const mesh = child;
|
|
992
|
+
if (mesh.geometry && !geos.has(mesh.geometry)) {
|
|
993
|
+
geos.add(mesh.geometry);
|
|
994
|
+
mesh.geometry.dispose();
|
|
995
|
+
}
|
|
996
|
+
const matList = Array.isArray(mesh.material) ? mesh.material : mesh.material ? [mesh.material] : [];
|
|
997
|
+
for (const mat of matList) if (!mats.has(mat)) {
|
|
998
|
+
mats.add(mat);
|
|
999
|
+
for (const val of Object.values(mat)) if (val && typeof val === "object" && "isTexture" in val && val.isTexture) {
|
|
1000
|
+
const tex = val;
|
|
1001
|
+
if (!texs.has(tex)) {
|
|
1002
|
+
texs.add(tex);
|
|
1003
|
+
tex.dispose();
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
mat.dispose();
|
|
1007
|
+
}
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Releases mount ownership. On root templates (or when `{ disposeTemplate: true }` is passed on a clone),
|
|
1012
|
+
* disposes unique GPU geometries, materials, and textures once.
|
|
1013
|
+
*/
|
|
1014
|
+
function disposeKhrBundle(bundle, options) {
|
|
1015
|
+
mountedScenes.delete(bundle.scene);
|
|
1016
|
+
if (disposedScenes.has(bundle.scene)) return;
|
|
1017
|
+
disposedScenes.add(bundle.scene);
|
|
1018
|
+
const isClone = clonedScenes.has(bundle.scene);
|
|
1019
|
+
if (isClone && !options?.disposeTemplate) return;
|
|
1020
|
+
const targetRoot = isClone ? templateByClone.get(bundle.scene) ?? bundle.scene : bundle.scene;
|
|
1021
|
+
disposedScenes.add(targetRoot);
|
|
1022
|
+
disposeSceneGpuResources([
|
|
1023
|
+
targetRoot,
|
|
1024
|
+
...bundle.wheels.map((w) => w.object),
|
|
1025
|
+
...bundle.propellers.map((p) => p.object)
|
|
1026
|
+
]);
|
|
1027
|
+
}
|
|
1028
|
+
function captureSubtreeOrigins(objects, explicitScene) {
|
|
1029
|
+
const parentOrders = /* @__PURE__ */ new Map();
|
|
1030
|
+
const origins = /* @__PURE__ */ new Map();
|
|
1031
|
+
for (const obj of objects) {
|
|
1032
|
+
const ownerScene = explicitScene ?? findSceneRoot(obj);
|
|
1033
|
+
const origParent = obj.parent;
|
|
1034
|
+
let origOrder = null;
|
|
1035
|
+
let origIndex = -1;
|
|
1036
|
+
if (origParent) {
|
|
1037
|
+
let order = parentOrders.get(origParent);
|
|
1038
|
+
if (!order) {
|
|
1039
|
+
order = /* @__PURE__ */ new Map();
|
|
1040
|
+
origParent.children.forEach((child, idx) => order.set(child, idx));
|
|
1041
|
+
parentOrders.set(origParent, order);
|
|
1042
|
+
}
|
|
1043
|
+
origOrder = order;
|
|
1044
|
+
origIndex = order.get(obj) ?? origParent.children.indexOf(obj);
|
|
1045
|
+
}
|
|
1046
|
+
origins.set(obj, {
|
|
1047
|
+
ownerScene,
|
|
1048
|
+
origParent,
|
|
1049
|
+
origIndex,
|
|
1050
|
+
origOrder,
|
|
1051
|
+
origPos: obj.position.clone(),
|
|
1052
|
+
origQuat: obj.quaternion.clone(),
|
|
1053
|
+
origScale: obj.scale.clone()
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
return origins;
|
|
1057
|
+
}
|
|
1058
|
+
function restoreSubtreeOrigin(object, snap) {
|
|
1059
|
+
object.position.copy(snap.origPos);
|
|
1060
|
+
object.quaternion.copy(snap.origQuat);
|
|
1061
|
+
object.scale.copy(snap.origScale);
|
|
1062
|
+
const { origParent, origIndex, origOrder } = snap;
|
|
1063
|
+
if (!origParent) return;
|
|
1064
|
+
if (object.parent && object.parent !== origParent) object.parent.remove(object);
|
|
1065
|
+
const existingIdx = origParent.children.indexOf(object);
|
|
1066
|
+
if (existingIdx >= 0) origParent.children.splice(existingIdx, 1);
|
|
1067
|
+
let insertAt = origParent.children.length;
|
|
1068
|
+
if (origOrder && origOrder.size > 0) {
|
|
1069
|
+
for (let i = 0; i < origParent.children.length; i++) if ((origOrder.get(origParent.children[i]) ?? 1e400) > origIndex) {
|
|
1070
|
+
insertAt = i;
|
|
1071
|
+
break;
|
|
1072
|
+
}
|
|
1073
|
+
} else if (origIndex >= 0) insertAt = Math.min(origIndex, origParent.children.length);
|
|
1074
|
+
object.parent = origParent;
|
|
1075
|
+
origParent.children.splice(insertAt, 0, object);
|
|
1076
|
+
}
|
|
1077
|
+
function BundleSceneHost({ bundle, owner }) {
|
|
1078
|
+
const hostRef = useRef(null);
|
|
1079
|
+
useLayoutEffect(() => {
|
|
1080
|
+
const host = hostRef.current;
|
|
1081
|
+
if (!host) return;
|
|
1082
|
+
claimBundleMount(bundle, owner);
|
|
1083
|
+
host.add(bundle.scene);
|
|
1084
|
+
return () => {
|
|
1085
|
+
if (bundle.scene.parent === host) host.remove(bundle.scene);
|
|
1086
|
+
releaseBundleMount(bundle);
|
|
1087
|
+
};
|
|
1088
|
+
}, [bundle, owner]);
|
|
1089
|
+
return React.createElement("group", { ref: hostRef });
|
|
1090
|
+
}
|
|
1091
|
+
function MountSubtreeSlot({ object, position, quaternion, origin }) {
|
|
1092
|
+
const slotRef = useRef(null);
|
|
1093
|
+
useLayoutEffect(() => {
|
|
1094
|
+
const slot = slotRef.current;
|
|
1095
|
+
if (!slot) return;
|
|
1096
|
+
const snap = origin ?? captureSubtreeOrigins([object]).get(object);
|
|
1097
|
+
if (snap.origParent) snap.origParent.remove(object);
|
|
1098
|
+
object.position.set(0, 0, 0);
|
|
1099
|
+
object.quaternion.set(0, 0, 0, 1);
|
|
1100
|
+
object.scale.set(1, 1, 1);
|
|
1101
|
+
slot.add(object);
|
|
1102
|
+
const untrack = registerMountedSubtree(snap.ownerScene, () => {
|
|
1103
|
+
const p = object.position.clone(), q = object.quaternion.clone(), s = object.scale.clone();
|
|
1104
|
+
if (object.parent === slot) slot.remove(object);
|
|
1105
|
+
restoreSubtreeOrigin(object, snap);
|
|
1106
|
+
return () => {
|
|
1107
|
+
if (snap.origParent) snap.origParent.remove(object);
|
|
1108
|
+
object.position.copy(p);
|
|
1109
|
+
object.quaternion.copy(q);
|
|
1110
|
+
object.scale.copy(s);
|
|
1111
|
+
slot.add(object);
|
|
1112
|
+
};
|
|
1113
|
+
});
|
|
1114
|
+
return () => {
|
|
1115
|
+
untrack();
|
|
1116
|
+
if (object.parent === slot) slot.remove(object);
|
|
1117
|
+
restoreSubtreeOrigin(object, snap);
|
|
1118
|
+
};
|
|
1119
|
+
}, [object, origin]);
|
|
1120
|
+
return React.createElement("group", {
|
|
1121
|
+
ref: slotRef,
|
|
1122
|
+
position,
|
|
1123
|
+
quaternion
|
|
1124
|
+
});
|
|
1125
|
+
}
|
|
1126
|
+
// src/KhrCollider.tsx
|
|
1127
|
+
var COMBINE_RULES = {
|
|
1128
|
+
average: CoefficientCombineRule.Average,
|
|
1129
|
+
minimum: CoefficientCombineRule.Min,
|
|
1130
|
+
maximum: CoefficientCombineRule.Max,
|
|
1131
|
+
multiply: CoefficientCombineRule.Multiply
|
|
1132
|
+
};
|
|
1133
|
+
/** `RAPIER.TriMeshFlags.FIX_INTERNAL_EDGES` (144) — merges duplicate vertices and suppresses internal seam ghost normals. */
|
|
1134
|
+
var KHR_TRIMESH_FLAGS = 144;
|
|
1135
|
+
function KhrCollider({ c, position, quaternion, density, mass, massProperties, collisionGroups, solverGroups, ref }) {
|
|
1136
|
+
const innerRef = useRef(null);
|
|
1137
|
+
const setRef = useCallback((node) => {
|
|
1138
|
+
innerRef.current = node;
|
|
1139
|
+
assignRef(ref, node);
|
|
1140
|
+
}, [ref]);
|
|
1141
|
+
useEffect(() => {
|
|
1142
|
+
innerRef.current?.parent()?.recomputeMassPropertiesFromColliders();
|
|
1143
|
+
}, [
|
|
1144
|
+
c,
|
|
1145
|
+
density,
|
|
1146
|
+
mass,
|
|
1147
|
+
massProperties
|
|
1148
|
+
]);
|
|
1149
|
+
const effCollisionGroups = c.collisionGroups ?? collisionGroups;
|
|
1150
|
+
const effSolverGroups = solverGroups ?? effCollisionGroups;
|
|
1151
|
+
const massOption = massProperties ? { massProperties } : mass !== void 0 ? { mass } : { density: density ?? 0 };
|
|
1152
|
+
const common = {
|
|
1153
|
+
ref: setRef,
|
|
1154
|
+
position: position ?? c.localPosition,
|
|
1155
|
+
quaternion: quaternion ?? c.localQuaternion,
|
|
1156
|
+
...massOption,
|
|
1157
|
+
...c.friction === void 0 ? {} : { friction: c.friction },
|
|
1158
|
+
...c.restitution === void 0 ? {} : { restitution: c.restitution },
|
|
1159
|
+
...c.frictionCombine === void 0 ? {} : { frictionCombineRule: COMBINE_RULES[c.frictionCombine] },
|
|
1160
|
+
...c.restitutionCombine === void 0 ? {} : { restitutionCombineRule: COMBINE_RULES[c.restitutionCombine] },
|
|
1161
|
+
...effCollisionGroups === void 0 ? {} : { collisionGroups: effCollisionGroups },
|
|
1162
|
+
...effSolverGroups === void 0 ? {} : { solverGroups: effSolverGroups }
|
|
1163
|
+
};
|
|
1164
|
+
const { shape } = c;
|
|
1165
|
+
if (shape.type === "box") {
|
|
1166
|
+
const [sx, sy, sz] = shape.size;
|
|
1167
|
+
return /* @__PURE__ */ jsx(CuboidCollider, {
|
|
1168
|
+
args: [
|
|
1169
|
+
sx * .5,
|
|
1170
|
+
sy * .5,
|
|
1171
|
+
sz * .5
|
|
1172
|
+
],
|
|
1173
|
+
...common
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
if (shape.type === "sphere") return /* @__PURE__ */ jsx(BallCollider, {
|
|
1177
|
+
args: [shape.radius],
|
|
1178
|
+
...common
|
|
1179
|
+
});
|
|
1180
|
+
if (shape.type === "cylinder") return /* @__PURE__ */ jsx(CylinderCollider, {
|
|
1181
|
+
args: [shape.height * .5, shape.radiusTop],
|
|
1182
|
+
...common
|
|
1183
|
+
});
|
|
1184
|
+
if (shape.type === "capsule") return /* @__PURE__ */ jsx(CapsuleCollider, {
|
|
1185
|
+
args: [shape.height * .5, shape.radiusTop],
|
|
1186
|
+
...common
|
|
1187
|
+
});
|
|
1188
|
+
if (shape.type === "convexHull") return /* @__PURE__ */ jsx(ConvexHullCollider, {
|
|
1189
|
+
args: [shape.vertices],
|
|
1190
|
+
...common
|
|
1191
|
+
});
|
|
1192
|
+
return /* @__PURE__ */ jsx(TrimeshCollider, {
|
|
1193
|
+
args: [
|
|
1194
|
+
shape.vertices,
|
|
1195
|
+
shape.indices,
|
|
1196
|
+
144
|
|
1197
|
+
],
|
|
1198
|
+
...common
|
|
1199
|
+
});
|
|
1200
|
+
}
|
|
1201
|
+
// src/joints.ts
|
|
1202
|
+
/**
|
|
1203
|
+
* Rapier interaction group bitmask for attached vehicle articulated panels:
|
|
1204
|
+
* member of group 1 (`0x0002`), collides with all groups except group 1 (`0xfffd`),
|
|
1205
|
+
* preventing sibling hinged panels (e.g. `door_fl` <-> `door_rl` / `hood`) from
|
|
1206
|
+
* fighting across joints while colliding normally with world geometry and projectiles.
|
|
1207
|
+
*/
|
|
1208
|
+
var ATTACHED_PANEL_INTERACTION_GROUPS = 196605;
|
|
1209
|
+
var DETACHED_PANEL_INTERACTION_GROUPS = 0xffffffff;
|
|
1210
|
+
var _q1 = new THREE.Quaternion();
|
|
1211
|
+
var _q2 = new THREE.Quaternion();
|
|
1212
|
+
var _qRel = new THREE.Quaternion();
|
|
1213
|
+
var _deltaPos = new THREE.Vector3();
|
|
1214
|
+
var _axWorld = new THREE.Vector3();
|
|
1215
|
+
function createRapierImpulseJoint(rapier, world, parentBody, childBody, joint, anchorParent, anchorChild, axisParent, axisChild, restFrameRelQuat) {
|
|
1216
|
+
const a1 = {
|
|
1217
|
+
x: anchorParent[0],
|
|
1218
|
+
y: anchorParent[1],
|
|
1219
|
+
z: anchorParent[2]
|
|
1220
|
+
};
|
|
1221
|
+
const a2 = {
|
|
1222
|
+
x: anchorChild[0],
|
|
1223
|
+
y: anchorChild[1],
|
|
1224
|
+
z: anchorChild[2]
|
|
1225
|
+
};
|
|
1226
|
+
const qRel = _qRel.set(restFrameRelQuat[0], restFrameRelQuat[1], restFrameRelQuat[2], restFrameRelQuat[3]).normalize();
|
|
1227
|
+
const axFromChild = _axWorld.set(axisChild[0], axisChild[1], axisChild[2]).applyQuaternion(qRel);
|
|
1228
|
+
const ax = (axFromChild.lengthSq() > 1e-12 ? axFromChild : _axWorld.set(axisParent[0], axisParent[1], axisParent[2])).normalize();
|
|
1229
|
+
let data;
|
|
1230
|
+
if (joint.kind === "fixed") {
|
|
1231
|
+
const pr = parentBody.rotation();
|
|
1232
|
+
const cr = childBody.rotation();
|
|
1233
|
+
const bodyRel = _q1.set(pr.x, pr.y, pr.z, pr.w).invert().multiply(_q2.set(cr.x, cr.y, cr.z, cr.w)).normalize();
|
|
1234
|
+
data = rapier.JointData.fixed(a1, {
|
|
1235
|
+
x: bodyRel.x,
|
|
1236
|
+
y: bodyRel.y,
|
|
1237
|
+
z: bodyRel.z,
|
|
1238
|
+
w: bodyRel.w
|
|
1239
|
+
}, a2, {
|
|
1240
|
+
x: 0,
|
|
1241
|
+
y: 0,
|
|
1242
|
+
z: 0,
|
|
1243
|
+
w: 1
|
|
1244
|
+
});
|
|
1245
|
+
} else if (joint.kind === "revolute") {
|
|
1246
|
+
data = rapier.JointData.revolute(a1, a2, {
|
|
1247
|
+
x: ax.x,
|
|
1248
|
+
y: ax.y,
|
|
1249
|
+
z: ax.z
|
|
1250
|
+
});
|
|
1251
|
+
if (joint.limits) {
|
|
1252
|
+
data.limitsEnabled = true;
|
|
1253
|
+
data.limits = [joint.limits[0], joint.limits[1]];
|
|
1254
|
+
}
|
|
1255
|
+
} else {
|
|
1256
|
+
data = rapier.JointData.prismatic(a1, a2, {
|
|
1257
|
+
x: ax.x,
|
|
1258
|
+
y: ax.y,
|
|
1259
|
+
z: ax.z
|
|
1260
|
+
});
|
|
1261
|
+
if (joint.limits) {
|
|
1262
|
+
data.limitsEnabled = true;
|
|
1263
|
+
data.limits = [joint.limits[0], joint.limits[1]];
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
const imp = world.createImpulseJoint(data, parentBody, childBody, true);
|
|
1267
|
+
imp.setContactsEnabled(Boolean(joint.enableCollision));
|
|
1268
|
+
const activeDrive = selectMatchingDrive(joint);
|
|
1269
|
+
configureJointDrive(rapier, imp, joint.kind, activeDrive, activeDrive?.positionTarget ?? null);
|
|
1270
|
+
return imp;
|
|
1271
|
+
}
|
|
1272
|
+
function selectMatchingDrive(joint) {
|
|
1273
|
+
if (joint.kind === "fixed") return null;
|
|
1274
|
+
const expectedType = joint.kind === "revolute" ? "angular" : "linear";
|
|
1275
|
+
for (const d of joint.drives) if (d.type === void 0 || d.type === expectedType) return d;
|
|
1276
|
+
return joint.drive;
|
|
1277
|
+
}
|
|
1278
|
+
function configureJointDrive(rapier, imp, kind, drive, targetPos) {
|
|
1279
|
+
if (kind === "fixed" || !drive) return;
|
|
1280
|
+
const unit = imp;
|
|
1281
|
+
unit.configureMotorModel(drive.mode === "force" ? rapier.MotorModel.ForceBased : rapier.MotorModel.AccelerationBased);
|
|
1282
|
+
const effTargetPos = targetPos ?? drive.positionTarget ?? (drive.stiffness !== void 0 && drive.stiffness > 0 ? 0 : null);
|
|
1283
|
+
if (effTargetPos !== null && drive.stiffness !== void 0) {
|
|
1284
|
+
if (drive.velocityTarget !== void 0) unit.configureMotor(effTargetPos, drive.velocityTarget, drive.stiffness, drive.damping ?? 0);
|
|
1285
|
+
else unit.configureMotorPosition(effTargetPos, drive.stiffness, drive.damping ?? 0);
|
|
1286
|
+
} else if (drive.velocityTarget !== void 0) unit.configureMotorVelocity(drive.velocityTarget, drive.damping ?? 0);
|
|
1287
|
+
if (drive.maxForce !== void 0) unit.setMotorMaxForce?.(drive.maxForce);
|
|
1288
|
+
}
|
|
1289
|
+
function measureJointCoordinate(parentBody, childBody, kind, axisParent, anchorParent) {
|
|
1290
|
+
if (!parentBody || !childBody || kind === "fixed") return 0;
|
|
1291
|
+
const pr = parentBody.rotation();
|
|
1292
|
+
const cr = childBody.rotation();
|
|
1293
|
+
_q1.set(pr.x, pr.y, pr.z, pr.w);
|
|
1294
|
+
_q2.set(cr.x, cr.y, cr.z, cr.w);
|
|
1295
|
+
if (kind === "prismatic") {
|
|
1296
|
+
const pt = parentBody.translation();
|
|
1297
|
+
const ct = childBody.translation();
|
|
1298
|
+
_deltaPos.set(anchorParent[0], anchorParent[1], anchorParent[2]).applyQuaternion(_q1);
|
|
1299
|
+
_deltaPos.set(ct.x - (pt.x + _deltaPos.x), ct.y - (pt.y + _deltaPos.y), ct.z - (pt.z + _deltaPos.z));
|
|
1300
|
+
_axWorld.set(axisParent[0], axisParent[1], axisParent[2]).applyQuaternion(_q1).normalize();
|
|
1301
|
+
return _deltaPos.dot(_axWorld);
|
|
1302
|
+
}
|
|
1303
|
+
_qRel.copy(_q1).invert().multiply(_q2).normalize();
|
|
1304
|
+
if (_qRel.w < 0) _qRel.set(-_qRel.x, -_qRel.y, -_qRel.z, -_qRel.w);
|
|
1305
|
+
const sinHalf = _qRel.x * axisParent[0] + _qRel.y * axisParent[1] + _qRel.z * axisParent[2];
|
|
1306
|
+
return 2 * Math.atan2(sinHalf, _qRel.w);
|
|
1307
|
+
}
|
|
1308
|
+
function buildJointRuntime(params) {
|
|
1309
|
+
const { rapier, world, nodeName, role, kind, object, axisParent, anchorParent, limits, drive, breakaway, rapierJoint, parentBody, childBody } = params;
|
|
1310
|
+
const rt = {
|
|
1311
|
+
nodeName,
|
|
1312
|
+
role,
|
|
1313
|
+
kind,
|
|
1314
|
+
object,
|
|
1315
|
+
axis: new THREE.Vector3(axisParent[0], axisParent[1], axisParent[2]).normalize(),
|
|
1316
|
+
limits,
|
|
1317
|
+
drive,
|
|
1318
|
+
positionTarget: drive?.positionTarget ?? null,
|
|
1319
|
+
velocityTarget: drive?.velocityTarget ?? 0,
|
|
1320
|
+
rapierJoint,
|
|
1321
|
+
parentBody,
|
|
1322
|
+
childBody,
|
|
1323
|
+
unlatched: false,
|
|
1324
|
+
detached: false,
|
|
1325
|
+
getCoordinate: () => measureJointCoordinate(rt.parentBody, rt.childBody, kind, axisParent, anchorParent),
|
|
1326
|
+
applyTarget: (target) => {
|
|
1327
|
+
if (rt.detached || !rt.rapierJoint) return;
|
|
1328
|
+
if (!drive || drive.stiffness === void 0) throw new KhrValidationError(`Joint "${nodeName}" has no authored drive stiffness; cannot set a position target`);
|
|
1329
|
+
rt.unlatched = false;
|
|
1330
|
+
rt.positionTarget = target;
|
|
1331
|
+
configureJointDrive(rapier, rt.rapierJoint, kind, drive, target);
|
|
1332
|
+
if (parentBody.isDynamic()) parentBody.wakeUp();
|
|
1333
|
+
if (childBody.isDynamic()) childBody.wakeUp();
|
|
1334
|
+
},
|
|
1335
|
+
applyImpactImpulse: (impulseNs) => {
|
|
1336
|
+
if (rt.detached || !breakaway || !(impulseNs > 0)) return rt.detached ? "detached" : rt.unlatched ? "unlatched" : "intact";
|
|
1337
|
+
if (impulseNs >= breakaway.breakImpulseNs) {
|
|
1338
|
+
if (world && rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
|
|
1339
|
+
rt.rapierJoint = null;
|
|
1340
|
+
rt.detached = true;
|
|
1341
|
+
rt.unlatched = true;
|
|
1342
|
+
rt.positionTarget = null;
|
|
1343
|
+
const ud = childBody.userData;
|
|
1344
|
+
if (ud?.ecctrl) childBody.userData = {
|
|
1345
|
+
...ud,
|
|
1346
|
+
ecctrl: {
|
|
1347
|
+
...ud.ecctrl,
|
|
1348
|
+
excludeVehicleRay: false
|
|
1349
|
+
}
|
|
1350
|
+
};
|
|
1351
|
+
for (let i = 0; i < childBody.numColliders(); i++) {
|
|
1352
|
+
const col = childBody.collider(i);
|
|
1353
|
+
if (col.collisionGroups() === 196605) {
|
|
1354
|
+
col.setCollisionGroups(DETACHED_PANEL_INTERACTION_GROUPS);
|
|
1355
|
+
col.setSolverGroups(DETACHED_PANEL_INTERACTION_GROUPS);
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
if (childBody.isDynamic()) childBody.wakeUp();
|
|
1359
|
+
return "detached";
|
|
1360
|
+
}
|
|
1361
|
+
if (breakaway.latchImpulseNs !== void 0 && impulseNs >= breakaway.latchImpulseNs && !rt.unlatched) {
|
|
1362
|
+
rt.unlatched = true;
|
|
1363
|
+
rt.positionTarget = null;
|
|
1364
|
+
if (kind !== "fixed" && rt.rapierJoint) rt.rapierJoint.configureMotorPosition(0, 0, Math.min(drive?.damping ?? 1, 1.5));
|
|
1365
|
+
if (childBody.isDynamic()) childBody.wakeUp();
|
|
1366
|
+
return "unlatched";
|
|
1367
|
+
}
|
|
1368
|
+
return rt.unlatched ? "unlatched" : "intact";
|
|
1369
|
+
}
|
|
1370
|
+
};
|
|
1371
|
+
return rt;
|
|
1372
|
+
}
|
|
1373
|
+
function openTargetForLimits(limits) {
|
|
1374
|
+
return Math.abs(limits[0]) > Math.abs(limits[1]) ? limits[0] : limits[1];
|
|
1375
|
+
}
|
|
1376
|
+
function closedTargetForLimits(limits) {
|
|
1377
|
+
return Math.min(limits[1], Math.max(limits[0], 0));
|
|
1378
|
+
}
|
|
1379
|
+
function isJointOpen(rt) {
|
|
1380
|
+
if (!rt.limits) return false;
|
|
1381
|
+
const openTgt = openTargetForLimits(rt.limits);
|
|
1382
|
+
const closedTgt = closedTargetForLimits(rt.limits);
|
|
1383
|
+
if (Math.abs(openTgt - closedTgt) <= 1e-6) return false;
|
|
1384
|
+
const cur = rt.positionTarget ?? rt.getCoordinate();
|
|
1385
|
+
return Math.abs(cur - openTgt) < Math.abs(cur - closedTgt);
|
|
1386
|
+
}
|
|
1387
|
+
function toggleDrivenJoint(rt) {
|
|
1388
|
+
if (rt.detached || rt.drive?.stiffness === void 0) return false;
|
|
1389
|
+
const limits = rt.limits ?? [0, Math.PI / 2];
|
|
1390
|
+
const nextTarget = isJointOpen(rt) ? closedTargetForLimits(limits) : openTargetForLimits(limits);
|
|
1391
|
+
rt.applyTarget(nextTarget);
|
|
1392
|
+
return true;
|
|
1393
|
+
}
|
|
1394
|
+
// src/KhrAssembly.tsx
|
|
1395
|
+
function matrixToRoot(node, sceneRoot) {
|
|
1396
|
+
const out = new THREE.Matrix4();
|
|
1397
|
+
for (let cur = node; cur && cur !== sceneRoot; cur = cur.parent) {
|
|
1398
|
+
if (!cur.parent) throw new KhrValidationError(`Node "${node.name}" is detached from bundle.scene`);
|
|
1399
|
+
cur.updateMatrix();
|
|
1400
|
+
out.premultiply(cur.matrix);
|
|
1401
|
+
}
|
|
1402
|
+
return out;
|
|
1403
|
+
}
|
|
1404
|
+
function isSceneDescendant(node, ancestor) {
|
|
1405
|
+
for (let cur = node; cur; cur = cur.parent) if (cur === ancestor) return true;
|
|
1406
|
+
return false;
|
|
1407
|
+
}
|
|
1408
|
+
function lowestCommonAncestor(nodes, sceneRoot) {
|
|
1409
|
+
let candidate = nodes[0];
|
|
1410
|
+
while (candidate && candidate !== sceneRoot) {
|
|
1411
|
+
if (nodes.every((n) => isSceneDescendant(n, candidate))) return candidate;
|
|
1412
|
+
candidate = candidate.parent ?? sceneRoot;
|
|
1413
|
+
}
|
|
1414
|
+
return sceneRoot;
|
|
1415
|
+
}
|
|
1416
|
+
function planOwnColliders(body, frameQuat) {
|
|
1417
|
+
const one = new THREE.Vector3(1, 1, 1);
|
|
1418
|
+
const frameMat = frameQuat ? new THREE.Matrix4().makeRotationFromQuaternion(frameQuat) : null;
|
|
1419
|
+
const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
|
|
1420
|
+
return body.colliders.map((spec) => {
|
|
1421
|
+
const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
|
|
1422
|
+
const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one);
|
|
1423
|
+
if (frameMat) local.premultiply(frameMat);
|
|
1424
|
+
local.decompose(pos, quat, scl);
|
|
1425
|
+
quat.normalize();
|
|
1426
|
+
return {
|
|
1427
|
+
spec,
|
|
1428
|
+
position: [
|
|
1429
|
+
pos.x,
|
|
1430
|
+
pos.y,
|
|
1431
|
+
pos.z
|
|
1432
|
+
],
|
|
1433
|
+
quaternion: [
|
|
1434
|
+
quat.x,
|
|
1435
|
+
quat.y,
|
|
1436
|
+
quat.z,
|
|
1437
|
+
quat.w
|
|
1438
|
+
]
|
|
1439
|
+
};
|
|
1440
|
+
});
|
|
1441
|
+
}
|
|
1442
|
+
function planAssembly(bundle) {
|
|
1443
|
+
const byName = new Map(bundle.bodies.map((b) => [b.nodeName, b]));
|
|
1444
|
+
const rootMemo = /* @__PURE__ */ new Map();
|
|
1445
|
+
const depthMemo = /* @__PURE__ */ new Map();
|
|
1446
|
+
const resolveRootAndDepth = (b, visiting = /* @__PURE__ */ new Set()) => {
|
|
1447
|
+
const cachedRoot = rootMemo.get(b.nodeName);
|
|
1448
|
+
const cachedDepth = depthMemo.get(b.nodeName);
|
|
1449
|
+
if (cachedRoot && cachedDepth !== void 0) return {
|
|
1450
|
+
root: cachedRoot,
|
|
1451
|
+
depth: cachedDepth
|
|
1452
|
+
};
|
|
1453
|
+
if (!b.joint) {
|
|
1454
|
+
rootMemo.set(b.nodeName, b);
|
|
1455
|
+
depthMemo.set(b.nodeName, 0);
|
|
1456
|
+
return {
|
|
1457
|
+
root: b,
|
|
1458
|
+
depth: 0
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
if (visiting.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
|
|
1462
|
+
visiting.add(b.nodeName);
|
|
1463
|
+
const parent = byName.get(b.joint.connectedNodeName);
|
|
1464
|
+
if (!parent) throw new KhrValidationError(`Joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a KHR body`);
|
|
1465
|
+
const up = resolveRootAndDepth(parent, visiting);
|
|
1466
|
+
rootMemo.set(b.nodeName, up.root);
|
|
1467
|
+
depthMemo.set(b.nodeName, up.depth + 1);
|
|
1468
|
+
return {
|
|
1469
|
+
root: up.root,
|
|
1470
|
+
depth: up.depth + 1
|
|
1471
|
+
};
|
|
1472
|
+
};
|
|
1473
|
+
for (const b of bundle.bodies) resolveRootAndDepth(b);
|
|
1474
|
+
const plans = bundle.bodies.filter((b) => !b.joint).map((root) => {
|
|
1475
|
+
const invRoot = bodyPoseMatrix(root).clone().invert();
|
|
1476
|
+
const descendants = bundle.bodies.filter((b) => b.joint && rootMemo.get(b.nodeName) === root).sort((a, b) => (depthMemo.get(a.nodeName) ?? 0) - (depthMemo.get(b.nodeName) ?? 0));
|
|
1477
|
+
const partByName = /* @__PURE__ */ new Map();
|
|
1478
|
+
const parts = descendants.map((b) => {
|
|
1479
|
+
const joint = b.joint;
|
|
1480
|
+
const parent = partByName.get(joint.connectedNodeName) ?? null;
|
|
1481
|
+
if (parent && !isSceneDescendant(b.object, parent.spec.object)) throw new KhrValidationError(`Jointed node "${b.nodeName}" must be a scene-graph descendant of its jointed parent "${joint.connectedNodeName}"`);
|
|
1482
|
+
const relParentMat = bodyPoseMatrix(parent ? parent.spec : root).clone().invert().multiply(bodyPoseMatrix(b));
|
|
1483
|
+
const relRootMat = invRoot.clone().multiply(bodyPoseMatrix(b));
|
|
1484
|
+
const rpPos = new THREE.Vector3(), tmpQ = new THREE.Quaternion(), rpScl = new THREE.Vector3();
|
|
1485
|
+
relParentMat.decompose(rpPos, tmpQ, rpScl);
|
|
1486
|
+
const rrPos = new THREE.Vector3(), rrQuat = new THREE.Quaternion();
|
|
1487
|
+
relRootMat.decompose(rrPos, rrQuat, rpScl);
|
|
1488
|
+
rrQuat.normalize();
|
|
1489
|
+
const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
|
|
1490
|
+
const axParentVec = axChildVec.clone().applyQuaternion(rrQuat).normalize();
|
|
1491
|
+
const anchorParent = parent ? [
|
|
1492
|
+
rrPos.x - parent.restRelRootPos[0],
|
|
1493
|
+
rrPos.y - parent.restRelRootPos[1],
|
|
1494
|
+
rrPos.z - parent.restRelRootPos[2]
|
|
1495
|
+
] : [
|
|
1496
|
+
rpPos.x,
|
|
1497
|
+
rpPos.y,
|
|
1498
|
+
rpPos.z
|
|
1499
|
+
];
|
|
1500
|
+
const rrQuatTuple = [
|
|
1501
|
+
rrQuat.x,
|
|
1502
|
+
rrQuat.y,
|
|
1503
|
+
rrQuat.z,
|
|
1504
|
+
rrQuat.w
|
|
1505
|
+
];
|
|
1506
|
+
const invPartFrame = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(b.localPosition), new THREE.Quaternion().fromArray(root.localQuaternion), new THREE.Vector3(1, 1, 1)).invert();
|
|
1507
|
+
const lumpedMass = computeLumpedMassProps([b], invPartFrame);
|
|
1508
|
+
const colliders = planOwnColliders(b, rrQuat);
|
|
1509
|
+
const plan = {
|
|
1510
|
+
spec: b,
|
|
1511
|
+
joint,
|
|
1512
|
+
parent,
|
|
1513
|
+
restRelParentPos: anchorParent,
|
|
1514
|
+
restRelParentQuat: rrQuatTuple,
|
|
1515
|
+
restRelRootPos: [
|
|
1516
|
+
rrPos.x,
|
|
1517
|
+
rrPos.y,
|
|
1518
|
+
rrPos.z
|
|
1519
|
+
],
|
|
1520
|
+
restRelRootQuat: rrQuatTuple,
|
|
1521
|
+
axisParent: [
|
|
1522
|
+
axParentVec.x,
|
|
1523
|
+
axParentVec.y,
|
|
1524
|
+
axParentVec.z
|
|
1525
|
+
],
|
|
1526
|
+
axisChild: [
|
|
1527
|
+
axChildVec.x,
|
|
1528
|
+
axChildVec.y,
|
|
1529
|
+
axChildVec.z
|
|
1530
|
+
],
|
|
1531
|
+
lumpedMass,
|
|
1532
|
+
colliders
|
|
1533
|
+
};
|
|
1534
|
+
partByName.set(b.nodeName, plan);
|
|
1535
|
+
return plan;
|
|
1536
|
+
});
|
|
1537
|
+
const lumpedMass = computeLumpedMassProps([root], invRoot);
|
|
1538
|
+
const colliders = planOwnColliders(root);
|
|
1539
|
+
const mountNode = lowestCommonAncestor([root.object, ...descendants.map((d) => d.object)], bundle.scene);
|
|
1540
|
+
const mountInRoot = invRoot.clone().multiply(matrixToRoot(mountNode, bundle.scene));
|
|
1541
|
+
const scenePos = new THREE.Vector3(), sceneQuat = new THREE.Quaternion(), sceneScl = new THREE.Vector3();
|
|
1542
|
+
invRoot.decompose(scenePos, sceneQuat, sceneScl);
|
|
1543
|
+
sceneQuat.normalize();
|
|
1544
|
+
const mountPos = new THREE.Vector3(), mountQuat = new THREE.Quaternion();
|
|
1545
|
+
mountInRoot.decompose(mountPos, mountQuat, sceneScl);
|
|
1546
|
+
mountQuat.normalize();
|
|
1547
|
+
return {
|
|
1548
|
+
spec: root,
|
|
1549
|
+
sceneInRootPos: [
|
|
1550
|
+
scenePos.x,
|
|
1551
|
+
scenePos.y,
|
|
1552
|
+
scenePos.z
|
|
1553
|
+
],
|
|
1554
|
+
sceneInRootQuat: [
|
|
1555
|
+
sceneQuat.x,
|
|
1556
|
+
sceneQuat.y,
|
|
1557
|
+
sceneQuat.z,
|
|
1558
|
+
sceneQuat.w
|
|
1559
|
+
],
|
|
1560
|
+
mountNode,
|
|
1561
|
+
mountPosition: [
|
|
1562
|
+
mountPos.x,
|
|
1563
|
+
mountPos.y,
|
|
1564
|
+
mountPos.z
|
|
1565
|
+
],
|
|
1566
|
+
mountQuaternion: [
|
|
1567
|
+
mountQuat.x,
|
|
1568
|
+
mountQuat.y,
|
|
1569
|
+
mountQuat.z,
|
|
1570
|
+
mountQuat.w
|
|
1571
|
+
],
|
|
1572
|
+
lumpedMass,
|
|
1573
|
+
colliders,
|
|
1574
|
+
parts
|
|
1575
|
+
};
|
|
1576
|
+
});
|
|
1577
|
+
for (const a of plans) for (const b of plans) if (a !== b && isSceneDescendant(b.mountNode, a.mountNode)) throw new KhrValidationError(`Root bodies "${a.spec.nodeName}" and "${b.spec.nodeName}" share scene subtree "${a.mountNode.name}"; split them into separate glTF branches`);
|
|
1578
|
+
return plans;
|
|
1579
|
+
}
|
|
1580
|
+
function ArticulatedPartBody({ part, rootPos, rootQuat, linearVelocity, angularVelocity, gravityScale, parentBody, userData, origin, onBody, onJointReady }) {
|
|
1581
|
+
const { rapier, world } = useRapier();
|
|
1582
|
+
const registry = useContext(JointRegistryContext);
|
|
1583
|
+
const rtRef = useRef(null);
|
|
1584
|
+
const [childBody, setChildBody] = React.useState(null);
|
|
1585
|
+
const worldPose = useMemo(() => {
|
|
1586
|
+
const rq = new THREE.Quaternion(rootQuat[0], rootQuat[1], rootQuat[2], rootQuat[3]).normalize();
|
|
1587
|
+
const pos = new THREE.Vector3().fromArray(part.restRelRootPos).applyQuaternion(rq).add(new THREE.Vector3(rootPos[0], rootPos[1], rootPos[2]));
|
|
1588
|
+
return {
|
|
1589
|
+
pos: [
|
|
1590
|
+
pos.x,
|
|
1591
|
+
pos.y,
|
|
1592
|
+
pos.z
|
|
1593
|
+
],
|
|
1594
|
+
quat: [
|
|
1595
|
+
rq.x,
|
|
1596
|
+
rq.y,
|
|
1597
|
+
rq.z,
|
|
1598
|
+
rq.w
|
|
1599
|
+
]
|
|
1600
|
+
};
|
|
1601
|
+
}, [
|
|
1602
|
+
part.restRelRootPos,
|
|
1603
|
+
rootPos,
|
|
1604
|
+
rootQuat
|
|
1605
|
+
]);
|
|
1606
|
+
const assignChildRef = useCallback((rb) => {
|
|
1607
|
+
setChildBody(rb);
|
|
1608
|
+
onBody(part.spec.nodeName, rb);
|
|
1609
|
+
}, [part.spec.nodeName, onBody]);
|
|
1610
|
+
useEffect(() => () => onBody(part.spec.nodeName, null), [part.spec.nodeName, onBody]);
|
|
1611
|
+
useEffect(() => {
|
|
1612
|
+
if (childBody && part.lumpedMass) applyRapierBodyMass(childBody, part.lumpedMass);
|
|
1613
|
+
}, [childBody, part.lumpedMass]);
|
|
1614
|
+
useEffect(() => {
|
|
1615
|
+
if (!parentBody || !childBody) return;
|
|
1616
|
+
const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
|
|
1617
|
+
0,
|
|
1618
|
+
0,
|
|
1619
|
+
0
|
|
1620
|
+
], part.axisParent, part.axisChild, part.restRelParentQuat);
|
|
1621
|
+
const rt = buildJointRuntime({
|
|
1622
|
+
rapier,
|
|
1623
|
+
world,
|
|
1624
|
+
nodeName: part.spec.nodeName,
|
|
1625
|
+
role: part.joint.role,
|
|
1626
|
+
kind: part.joint.kind,
|
|
1627
|
+
object: part.spec.object,
|
|
1628
|
+
axisParent: part.axisParent,
|
|
1629
|
+
anchorParent: part.restRelParentPos,
|
|
1630
|
+
limits: part.joint.limits,
|
|
1631
|
+
drive: part.joint.drive,
|
|
1632
|
+
breakaway: part.spec.breakaway,
|
|
1633
|
+
rapierJoint: imp,
|
|
1634
|
+
parentBody,
|
|
1635
|
+
childBody
|
|
1636
|
+
});
|
|
1637
|
+
rtRef.current = rt;
|
|
1638
|
+
registry?.add(rt);
|
|
1639
|
+
onJointReady(rt.nodeName, part.spec.object, rt);
|
|
1640
|
+
return () => {
|
|
1641
|
+
rtRef.current = null;
|
|
1642
|
+
registry?.delete(rt);
|
|
1643
|
+
onJointReady(rt.nodeName, part.spec.object, null);
|
|
1644
|
+
if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
|
|
1645
|
+
};
|
|
1646
|
+
}, [
|
|
1647
|
+
rapier,
|
|
1648
|
+
world,
|
|
1649
|
+
part,
|
|
1650
|
+
parentBody,
|
|
1651
|
+
childBody,
|
|
1652
|
+
registry,
|
|
1653
|
+
onJointReady
|
|
1654
|
+
]);
|
|
1655
|
+
const onForce = useMemo(() => part.spec.breakaway ? (p) => {
|
|
1656
|
+
if (world.timestep > 0) rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * world.timestep);
|
|
1657
|
+
} : void 0, [part.spec.breakaway, world]);
|
|
1658
|
+
const linVel = part.spec.linearVelocity ?? linearVelocity;
|
|
1659
|
+
const angVel = part.spec.angularVelocity ?? angularVelocity;
|
|
1660
|
+
const gravScale = part.spec.gravityFactor ?? gravityScale;
|
|
1661
|
+
return /* @__PURE__ */ jsxs(RigidBody, {
|
|
1662
|
+
ref: assignChildRef,
|
|
1663
|
+
type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
|
|
1664
|
+
position: worldPose.pos,
|
|
1665
|
+
quaternion: worldPose.quat,
|
|
1666
|
+
colliders: false,
|
|
1667
|
+
onContactForce: onForce,
|
|
1668
|
+
...userData === void 0 ? {} : { userData },
|
|
1669
|
+
...linVel ? { linearVelocity: linVel } : {},
|
|
1670
|
+
...angVel ? { angularVelocity: angVel } : {},
|
|
1671
|
+
...gravScale === void 0 ? {} : { gravityScale: gravScale },
|
|
1672
|
+
children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
|
|
1673
|
+
object: part.spec.object,
|
|
1674
|
+
position: [
|
|
1675
|
+
0,
|
|
1676
|
+
0,
|
|
1677
|
+
0
|
|
1678
|
+
],
|
|
1679
|
+
quaternion: part.restRelRootQuat,
|
|
1680
|
+
origin
|
|
1681
|
+
}), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
|
|
1682
|
+
c: col.spec,
|
|
1683
|
+
position: col.position,
|
|
1684
|
+
quaternion: col.quaternion
|
|
1685
|
+
}, `${part.spec.nodeName}:${cIdx}`))]
|
|
1686
|
+
});
|
|
1687
|
+
}
|
|
1688
|
+
function AssemblyRootBody({ plan, bundleScene, position, quaternion, fixedRoot, rigidBodyProps, onBody, onJointReady, children }) {
|
|
1689
|
+
const [rootBody, setRootBody] = React.useState(null);
|
|
1690
|
+
const [partBodies, setPartBodies] = React.useState(() => /* @__PURE__ */ new Map());
|
|
1691
|
+
const partOrigins = useMemo(() => plan.parts.length > 0 ? captureSubtreeOrigins(plan.parts.map((p) => p.spec.object), bundleScene) : null, [plan.parts, bundleScene]);
|
|
1692
|
+
const rootSpec = plan.spec;
|
|
1693
|
+
const assignRootRef = useCallback((rb) => {
|
|
1694
|
+
setRootBody(rb);
|
|
1695
|
+
onBody(rootSpec.nodeName, rb);
|
|
1696
|
+
}, [rootSpec.nodeName, onBody]);
|
|
1697
|
+
useEffect(() => () => onBody(rootSpec.nodeName, null), [rootSpec.nodeName, onBody]);
|
|
1698
|
+
useEffect(() => {
|
|
1699
|
+
if (rootBody && plan.lumpedMass) applyRapierBodyMass(rootBody, plan.lumpedMass);
|
|
1700
|
+
}, [rootBody, plan.lumpedMass]);
|
|
1701
|
+
const handlePartBody = useCallback((nodeName, rb) => {
|
|
1702
|
+
setPartBodies((prev) => {
|
|
1703
|
+
if ((prev.get(nodeName) ?? null) === rb) return prev;
|
|
1704
|
+
const next = new Map(prev);
|
|
1705
|
+
if (rb) next.set(nodeName, rb);
|
|
1706
|
+
else next.delete(nodeName);
|
|
1707
|
+
return next;
|
|
1708
|
+
});
|
|
1709
|
+
onBody(nodeName, rb);
|
|
1710
|
+
}, [onBody]);
|
|
1711
|
+
const bodyType = rootSpec.isKinematic ? fixedRoot ? "fixed" : "kinematicPosition" : "dynamic";
|
|
1712
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(RigidBody, {
|
|
1713
|
+
...rigidBodyProps,
|
|
1714
|
+
ref: assignRootRef,
|
|
1715
|
+
type: bodyType,
|
|
1716
|
+
position,
|
|
1717
|
+
quaternion,
|
|
1718
|
+
colliders: false,
|
|
1719
|
+
...rootSpec.linearVelocity ? { linearVelocity: rootSpec.linearVelocity } : {},
|
|
1720
|
+
...rootSpec.angularVelocity ? { angularVelocity: rootSpec.angularVelocity } : {},
|
|
1721
|
+
...rootSpec.gravityFactor === void 0 ? {} : { gravityScale: rootSpec.gravityFactor },
|
|
1722
|
+
children: [children, plan.colliders.map((col, idx) => /* @__PURE__ */ jsx(KhrCollider, {
|
|
1723
|
+
c: col.spec,
|
|
1724
|
+
position: col.position,
|
|
1725
|
+
quaternion: col.quaternion
|
|
1726
|
+
}, `r${idx}`))]
|
|
1727
|
+
}), plan.parts.map((part) => /* @__PURE__ */ jsx(ArticulatedPartBody, {
|
|
1728
|
+
part,
|
|
1729
|
+
rootPos: position,
|
|
1730
|
+
rootQuat: quaternion,
|
|
1731
|
+
linearVelocity: rootSpec.linearVelocity,
|
|
1732
|
+
angularVelocity: rootSpec.angularVelocity,
|
|
1733
|
+
gravityScale: rootSpec.gravityFactor,
|
|
1734
|
+
parentBody: part.parent ? partBodies.get(part.parent.spec.nodeName) ?? null : rootBody,
|
|
1735
|
+
userData: rigidBodyProps?.userData,
|
|
1736
|
+
origin: partOrigins?.get(part.spec.object),
|
|
1737
|
+
onBody: handlePartBody,
|
|
1738
|
+
onJointReady
|
|
1739
|
+
}, part.spec.nodeName))] });
|
|
1740
|
+
}
|
|
1741
|
+
function KhrAssembly({ ref, bundle, position = [
|
|
1742
|
+
0,
|
|
1743
|
+
0,
|
|
1744
|
+
0
|
|
1745
|
+
], rotation, quaternion, scale, fixedRoot = false, enableCustomGravity = false, rigidBodyProps, children, ...groupProps }) {
|
|
1746
|
+
assertUnitScale(scale, "KhrAssembly");
|
|
1747
|
+
useMemo(() => assertSceneIdentityWorldScale(bundle.scene), [bundle]);
|
|
1748
|
+
const { world } = useRapier();
|
|
1749
|
+
const applyGravityField = useCustomGravity((s) => s.applyGravityField);
|
|
1750
|
+
const plans = useMemo(() => planAssembly(bundle), [bundle]);
|
|
1751
|
+
const isStaticMultiRootCompound = useMemo(() => fixedRoot && plans.length > 1 && plans.every((p) => p.spec.isKinematic && p.parts.length === 0), [fixedRoot, plans]);
|
|
1752
|
+
const compoundColliders = useMemo(() => {
|
|
1753
|
+
if (!isStaticMultiRootCompound) return null;
|
|
1754
|
+
const one = new THREE.Vector3(1, 1, 1);
|
|
1755
|
+
const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
|
|
1756
|
+
const out = [];
|
|
1757
|
+
for (const p of plans) {
|
|
1758
|
+
const bMat = bodyPoseMatrix(p.spec);
|
|
1759
|
+
for (let idx = 0; idx < p.spec.colliders.length; idx++) {
|
|
1760
|
+
const c = p.spec.colliders[idx];
|
|
1761
|
+
const cMat = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(c.localPosition), new THREE.Quaternion().fromArray(c.localQuaternion), one);
|
|
1762
|
+
bMat.clone().multiply(cMat).decompose(pos, quat, scl);
|
|
1763
|
+
quat.normalize();
|
|
1764
|
+
out.push({
|
|
1765
|
+
key: `${p.spec.nodeName}:${idx}`,
|
|
1766
|
+
spec: c,
|
|
1767
|
+
position: [
|
|
1768
|
+
pos.x,
|
|
1769
|
+
pos.y,
|
|
1770
|
+
pos.z
|
|
1771
|
+
],
|
|
1772
|
+
quaternion: [
|
|
1773
|
+
quat.x,
|
|
1774
|
+
quat.y,
|
|
1775
|
+
quat.z,
|
|
1776
|
+
quat.w
|
|
1777
|
+
]
|
|
1778
|
+
});
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
return out;
|
|
1782
|
+
}, [isStaticMultiRootCompound, plans]);
|
|
1783
|
+
const origins = useMemo(() => !isStaticMultiRootCompound && plans.length > 1 ? captureSubtreeOrigins(plans.map((p) => p.mountNode), bundle.scene) : null, [
|
|
1784
|
+
isStaticMultiRootCompound,
|
|
1785
|
+
plans,
|
|
1786
|
+
bundle.scene
|
|
1787
|
+
]);
|
|
1788
|
+
const [px, py, pz] = position;
|
|
1789
|
+
const [rx, ry, rz] = rotation ?? [
|
|
1790
|
+
0,
|
|
1791
|
+
0,
|
|
1792
|
+
0
|
|
1793
|
+
];
|
|
1794
|
+
const hasQuat = quaternion !== void 0;
|
|
1795
|
+
const qx = quaternion?.[0] ?? 0;
|
|
1796
|
+
const qy = quaternion?.[1] ?? 0;
|
|
1797
|
+
const qz = quaternion?.[2] ?? 0;
|
|
1798
|
+
const qw = quaternion?.[3] ?? 1;
|
|
1799
|
+
const spawnQuat = useMemo(() => hasQuat ? new THREE.Quaternion(qx, qy, qz, qw).normalize() : new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), [
|
|
1800
|
+
hasQuat,
|
|
1801
|
+
qx,
|
|
1802
|
+
qy,
|
|
1803
|
+
qz,
|
|
1804
|
+
qw,
|
|
1805
|
+
rx,
|
|
1806
|
+
ry,
|
|
1807
|
+
rz
|
|
1808
|
+
]);
|
|
1809
|
+
const rootPoses = useMemo(() => plans.map((p) => {
|
|
1810
|
+
const pos = new THREE.Vector3().fromArray(p.spec.localPosition).applyQuaternion(spawnQuat).add(new THREE.Vector3(px, py, pz));
|
|
1811
|
+
const quat = spawnQuat.clone().multiply(new THREE.Quaternion().fromArray(p.spec.localQuaternion));
|
|
1812
|
+
return {
|
|
1813
|
+
position: [
|
|
1814
|
+
pos.x,
|
|
1815
|
+
pos.y,
|
|
1816
|
+
pos.z
|
|
1817
|
+
],
|
|
1818
|
+
quaternion: [
|
|
1819
|
+
quat.x,
|
|
1820
|
+
quat.y,
|
|
1821
|
+
quat.z,
|
|
1822
|
+
quat.w
|
|
1823
|
+
]
|
|
1824
|
+
};
|
|
1825
|
+
}), [
|
|
1826
|
+
plans,
|
|
1827
|
+
spawnQuat,
|
|
1828
|
+
px,
|
|
1829
|
+
py,
|
|
1830
|
+
pz
|
|
1831
|
+
]);
|
|
1832
|
+
const bodiesRef = useRef(/* @__PURE__ */ new Map());
|
|
1833
|
+
const jointsRef = useRef(/* @__PURE__ */ new Map());
|
|
1834
|
+
const byObjectRef = useRef(/* @__PURE__ */ new Map());
|
|
1835
|
+
const handleBody = useCallback((nodeName, rb) => {
|
|
1836
|
+
if (rb) bodiesRef.current.set(nodeName, rb);
|
|
1837
|
+
else bodiesRef.current.delete(nodeName);
|
|
1838
|
+
}, []);
|
|
1839
|
+
const handleJointReady = useCallback((nodeName, obj, rt) => {
|
|
1840
|
+
if (rt) {
|
|
1841
|
+
jointsRef.current.set(nodeName, rt);
|
|
1842
|
+
byObjectRef.current.set(obj, rt);
|
|
1843
|
+
} else {
|
|
1844
|
+
jointsRef.current.delete(nodeName);
|
|
1845
|
+
byObjectRef.current.delete(obj);
|
|
1846
|
+
}
|
|
1847
|
+
}, []);
|
|
1848
|
+
useFrame(() => {
|
|
1849
|
+
if (!enableCustomGravity || world.timestep <= 0) return;
|
|
1850
|
+
for (const rb of bodiesRef.current.values()) if (rb.isDynamic()) applyGravityField(rb, world.timestep);
|
|
1851
|
+
});
|
|
1852
|
+
useImperativeHandle(ref, () => ({
|
|
1853
|
+
get jointNames() {
|
|
1854
|
+
return [...jointsRef.current.keys()];
|
|
1855
|
+
},
|
|
1856
|
+
getBody: (nodeName) => bodiesRef.current.get(nodeName) ?? null,
|
|
1857
|
+
getJointRuntime: (nodeName) => jointsRef.current.get(nodeName) ?? null,
|
|
1858
|
+
setJointTarget: (nodeName, target) => {
|
|
1859
|
+
jointsRef.current.get(nodeName)?.applyTarget(target);
|
|
1860
|
+
},
|
|
1861
|
+
setRoleTarget: (role, target) => {
|
|
1862
|
+
for (const rt of jointsRef.current.values()) if (rt.role === role) rt.applyTarget(target);
|
|
1863
|
+
},
|
|
1864
|
+
toggleHitObject: (hit) => {
|
|
1865
|
+
for (let cur = hit; cur; cur = cur.parent) {
|
|
1866
|
+
const rt = byObjectRef.current.get(cur);
|
|
1867
|
+
if (rt && toggleDrivenJoint(rt)) return true;
|
|
1868
|
+
}
|
|
1869
|
+
return false;
|
|
1870
|
+
}
|
|
1871
|
+
}), []);
|
|
1872
|
+
const assignCompoundRef = useCallback((rb) => {
|
|
1873
|
+
for (const p of plans) if (rb) bodiesRef.current.set(p.spec.nodeName, rb);
|
|
1874
|
+
else bodiesRef.current.delete(p.spec.nodeName);
|
|
1875
|
+
}, [plans]);
|
|
1876
|
+
useEffect(() => {
|
|
1877
|
+
if (!isStaticMultiRootCompound) return;
|
|
1878
|
+
return () => {
|
|
1879
|
+
for (const p of plans) bodiesRef.current.delete(p.spec.nodeName);
|
|
1880
|
+
};
|
|
1881
|
+
}, [isStaticMultiRootCompound, plans]);
|
|
1882
|
+
if (isStaticMultiRootCompound && compoundColliders) return /* @__PURE__ */ jsx("group", {
|
|
1883
|
+
...groupProps,
|
|
1884
|
+
children: /* @__PURE__ */ jsxs(RigidBody, {
|
|
1885
|
+
...rigidBodyProps,
|
|
1886
|
+
ref: assignCompoundRef,
|
|
1887
|
+
type: "fixed",
|
|
1888
|
+
position,
|
|
1889
|
+
quaternion: [
|
|
1890
|
+
spawnQuat.x,
|
|
1891
|
+
spawnQuat.y,
|
|
1892
|
+
spawnQuat.z,
|
|
1893
|
+
spawnQuat.w
|
|
1894
|
+
],
|
|
1895
|
+
colliders: false,
|
|
1896
|
+
children: [
|
|
1897
|
+
/* @__PURE__ */ jsx(BundleSceneHost, {
|
|
1898
|
+
bundle,
|
|
1899
|
+
owner: "KhrAssembly"
|
|
1900
|
+
}),
|
|
1901
|
+
children,
|
|
1902
|
+
compoundColliders.map((col) => /* @__PURE__ */ jsx(KhrCollider, {
|
|
1903
|
+
c: col.spec,
|
|
1904
|
+
position: col.position,
|
|
1905
|
+
quaternion: col.quaternion
|
|
1906
|
+
}, col.key))
|
|
1907
|
+
]
|
|
1908
|
+
})
|
|
1909
|
+
});
|
|
1910
|
+
if (plans.length === 1) {
|
|
1911
|
+
const plan = plans[0];
|
|
1912
|
+
return /* @__PURE__ */ jsx("group", {
|
|
1913
|
+
...groupProps,
|
|
1914
|
+
children: /* @__PURE__ */ jsx(AssemblyRootBody, {
|
|
1915
|
+
plan,
|
|
1916
|
+
bundleScene: bundle.scene,
|
|
1917
|
+
position: rootPoses[0].position,
|
|
1918
|
+
quaternion: rootPoses[0].quaternion,
|
|
1919
|
+
fixedRoot,
|
|
1920
|
+
rigidBodyProps,
|
|
1921
|
+
onBody: handleBody,
|
|
1922
|
+
onJointReady: handleJointReady,
|
|
1923
|
+
children: /* @__PURE__ */ jsxs("group", {
|
|
1924
|
+
position: plan.sceneInRootPos,
|
|
1925
|
+
quaternion: plan.sceneInRootQuat,
|
|
1926
|
+
children: [/* @__PURE__ */ jsx(BundleSceneHost, {
|
|
1927
|
+
bundle,
|
|
1928
|
+
owner: "KhrAssembly"
|
|
1929
|
+
}), children]
|
|
1930
|
+
})
|
|
1931
|
+
}, `${bundle.scene.uuid}:${plan.spec.nodeName}`)
|
|
1932
|
+
});
|
|
1933
|
+
}
|
|
1934
|
+
return /* @__PURE__ */ jsxs("group", {
|
|
1935
|
+
...groupProps,
|
|
1936
|
+
children: [/* @__PURE__ */ jsxs("group", {
|
|
1937
|
+
position,
|
|
1938
|
+
quaternion: [
|
|
1939
|
+
spawnQuat.x,
|
|
1940
|
+
spawnQuat.y,
|
|
1941
|
+
spawnQuat.z,
|
|
1942
|
+
spawnQuat.w
|
|
1943
|
+
],
|
|
1944
|
+
children: [/* @__PURE__ */ jsx(BundleSceneHost, {
|
|
1945
|
+
bundle,
|
|
1946
|
+
owner: "KhrAssembly"
|
|
1947
|
+
}), children]
|
|
1948
|
+
}), plans.map((plan, idx) => /* @__PURE__ */ jsx(AssemblyRootBody, {
|
|
1949
|
+
plan,
|
|
1950
|
+
bundleScene: bundle.scene,
|
|
1951
|
+
position: rootPoses[idx].position,
|
|
1952
|
+
quaternion: rootPoses[idx].quaternion,
|
|
1953
|
+
fixedRoot,
|
|
1954
|
+
rigidBodyProps,
|
|
1955
|
+
onBody: handleBody,
|
|
1956
|
+
onJointReady: handleJointReady,
|
|
1957
|
+
children: /* @__PURE__ */ jsx(MountSubtreeSlot, {
|
|
1958
|
+
object: plan.mountNode,
|
|
1959
|
+
position: plan.mountPosition,
|
|
1960
|
+
quaternion: plan.mountQuaternion,
|
|
1961
|
+
origin: origins?.get(plan.mountNode)
|
|
1962
|
+
})
|
|
1963
|
+
}, `${bundle.scene.uuid}:${plan.spec.nodeName}`))]
|
|
1964
|
+
});
|
|
1965
|
+
}
|
|
1966
|
+
export { computeAssemblyMassAndCom as A, JointRegistryContext as B, restoreSubtreeOrigin as C, assertSceneIdentityWorldScale as D, assertIdentityWorldScale as E, jacobiPrincipalInertia as F, isObj as G, assignRef as H, readFiniteVec3 as I, isPosNum as K, readUnitQuat as L, computeRelativePose as M, computeShapeInertia as N, assertUnitScale as O, extractMeshColliderShape as P, resolveBodyMassFromColliders as R, releaseBundleMount as S, applyRapierBodyMass as T, isFiniteNum as U, KhrValidationError as V, isNonNegNum as W, captureSubtreeOrigins as _, DETACHED_PANEL_INTERACTION_GROUPS as a, disposeKhrBundle as b, configureJointDrive as c, measureJointCoordinate as d, openTargetForLimits as f, BundleSceneHost as g, KhrCollider as h, ATTACHED_PANEL_INTERACTION_GROUPS as i, computeLumpedMassProps as j, bodyPoseMatrix as k, createRapierImpulseJoint as l, KHR_TRIMESH_FLAGS as m, KhrAssembly as n, buildJointRuntime as o, toggleDrivenJoint as p, optFiniteNum as q, planAssembly as r, closedTargetForLimits as s, ArticulatedPartBody as t, isJointOpen as u, claimBundleMount as v, snapshotSceneWithMountedSubtrees as w, registerMountedSubtree as x, cloneKhrBundle as y, COMBINE_MODES as z };
|
|
1967
|
+
|
|
1968
|
+
//# sourceMappingURL=KhrAssembly-BOY_g5we.js.map
|