@threenative/physics 0.1.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.
- package/README.md +17 -0
- package/dist/Area3D-B8LJ2C4S.d.ts +403 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +1122 -0
- package/dist/native/index.d.ts +5 -0
- package/dist/native/index.js +986 -0
- package/dist/navigation/index.d.ts +4 -0
- package/dist/navigation/index.js +5133 -0
- package/package.json +53 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1122 @@
|
|
|
1
|
+
import * as RAPIER from '@dimforge/rapier3d-compat';
|
|
2
|
+
|
|
3
|
+
// src/web.ts
|
|
4
|
+
|
|
5
|
+
// src/collision.ts
|
|
6
|
+
function interactionGroups(layer, mask) {
|
|
7
|
+
if (!Number.isInteger(layer) || layer < 0 || layer > 65535)
|
|
8
|
+
throw new Error("interactionGroups: layer must be an integer in 0..0xffff.");
|
|
9
|
+
if (!Number.isInteger(mask) || mask < 0 || mask > 65535)
|
|
10
|
+
throw new Error("interactionGroups: mask must be an integer in 0..0xffff.");
|
|
11
|
+
return (layer << 16 | mask) >>> 0;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// src/handles.ts
|
|
15
|
+
function physicsHandle(raw) {
|
|
16
|
+
return { raw };
|
|
17
|
+
}
|
|
18
|
+
function physicsWorldHandle(raw, simulation) {
|
|
19
|
+
return { raw, simulation };
|
|
20
|
+
}
|
|
21
|
+
function physicsBodyHandle(id, raw) {
|
|
22
|
+
return { id, raw };
|
|
23
|
+
}
|
|
24
|
+
function physicsColliderHandle(id, raw) {
|
|
25
|
+
return { id, raw };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// src/simulation.ts
|
|
29
|
+
var PHYSICS_TRANSFORM_STRIDE = 8;
|
|
30
|
+
var PHYSICS_COLLISION_EVENT_STRIDE = 4;
|
|
31
|
+
var selectedBackend;
|
|
32
|
+
function installPhysicsSimulationBackend(backend) {
|
|
33
|
+
selectedBackend = backend;
|
|
34
|
+
}
|
|
35
|
+
function physicsSimulationBackend() {
|
|
36
|
+
if (selectedBackend === void 0)
|
|
37
|
+
throw new Error("TN_PHYSICS_BACKEND_MISSING: no PhysicsSimulation backend was selected");
|
|
38
|
+
return selectedBackend;
|
|
39
|
+
}
|
|
40
|
+
function requirePhysicsStepInput(deltaTime, inputSnapshot, bodyExists) {
|
|
41
|
+
if (!Number.isFinite(deltaTime) || deltaTime <= 0)
|
|
42
|
+
throw new Error("PhysicsSimulation.step requires a positive finite deltaTime.");
|
|
43
|
+
if (inputSnapshot === void 0) return;
|
|
44
|
+
if (!(inputSnapshot.kinematicTransforms instanceof Float32Array))
|
|
45
|
+
throw new Error("PhysicsSimulation input must use a Float32Array.");
|
|
46
|
+
if (!Number.isSafeInteger(inputSnapshot.kinematicCount) || inputSnapshot.kinematicCount < 0 || inputSnapshot.kinematicCount > Math.floor(inputSnapshot.kinematicTransforms.length / PHYSICS_TRANSFORM_STRIDE)) {
|
|
47
|
+
throw new Error("PhysicsSimulation input has an invalid kinematic record count.");
|
|
48
|
+
}
|
|
49
|
+
for (let index = 0; index < inputSnapshot.kinematicCount; index += 1) {
|
|
50
|
+
const offset = index * PHYSICS_TRANSFORM_STRIDE;
|
|
51
|
+
for (let scalar = 0; scalar < PHYSICS_TRANSFORM_STRIDE; scalar += 1) {
|
|
52
|
+
if (!Number.isFinite(inputSnapshot.kinematicTransforms[offset + scalar]))
|
|
53
|
+
throw new Error("PhysicsSimulation input contains a non-finite transform.");
|
|
54
|
+
}
|
|
55
|
+
const id = inputSnapshot.kinematicTransforms[offset];
|
|
56
|
+
if (!Number.isInteger(id) || id < 0)
|
|
57
|
+
throw new Error("PhysicsSimulation input contains an invalid body id.");
|
|
58
|
+
if (!bodyExists(id)) throw new Error("PhysicsSimulation input contains an unknown body id.");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function requirePhysicsRenderBuffer(renderBuffer, bodyCount) {
|
|
62
|
+
if (!(renderBuffer instanceof Float32Array))
|
|
63
|
+
throw new Error("PhysicsSimulation output must use a Float32Array.");
|
|
64
|
+
if (renderBuffer.length < bodyCount * PHYSICS_TRANSFORM_STRIDE)
|
|
65
|
+
throw new Error("PhysicsSimulation output buffer is too small for visible transforms.");
|
|
66
|
+
}
|
|
67
|
+
function requirePhysicsEventBuffer(buffer) {
|
|
68
|
+
if (!(buffer instanceof Uint32Array))
|
|
69
|
+
throw new Error("PhysicsSimulation events must use a Uint32Array.");
|
|
70
|
+
}
|
|
71
|
+
function createWebPhysicsShape(rapier2, shape) {
|
|
72
|
+
let descriptor;
|
|
73
|
+
if (shape.kind === "box") descriptor = rapier2.ColliderDesc.cuboid(shape.x, shape.y, shape.z);
|
|
74
|
+
else if (shape.kind === "sphere") descriptor = rapier2.ColliderDesc.ball(shape.x);
|
|
75
|
+
else if (shape.kind === "capsule") descriptor = rapier2.ColliderDesc.capsule(shape.x, shape.y);
|
|
76
|
+
else if (shape.kind === "trimesh") {
|
|
77
|
+
if (shape.vertices === void 0 || shape.indices === void 0)
|
|
78
|
+
throw new Error("CollisionShape3D.trimesh is missing mesh data.");
|
|
79
|
+
descriptor = rapier2.ColliderDesc.trimesh(shape.vertices, shape.indices);
|
|
80
|
+
} else if (shape.kind === "convexHull") {
|
|
81
|
+
if (shape.vertices === void 0)
|
|
82
|
+
throw new Error("CollisionShape3D.convexHull is missing vertices.");
|
|
83
|
+
descriptor = rapier2.ColliderDesc.convexHull(shape.vertices);
|
|
84
|
+
if (descriptor === null) throw new Error("CollisionShape3D could not build a convex hull.");
|
|
85
|
+
} else {
|
|
86
|
+
if (shape.rows === void 0 || shape.columns === void 0 || shape.heights === void 0 || shape.scale === void 0)
|
|
87
|
+
throw new Error("CollisionShape3D.heightfield is missing height data.");
|
|
88
|
+
descriptor = rapier2.ColliderDesc.heightfield(
|
|
89
|
+
shape.rows - 1,
|
|
90
|
+
shape.columns - 1,
|
|
91
|
+
shape.heights,
|
|
92
|
+
shape.scale
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
descriptor.setCollisionGroups(interactionGroups(shape.collisionLayer, shape.collisionMask));
|
|
96
|
+
descriptor.setSensor(shape.sensor);
|
|
97
|
+
descriptor.setActiveEvents(rapier2.ActiveEvents.COLLISION_EVENTS);
|
|
98
|
+
return descriptor;
|
|
99
|
+
}
|
|
100
|
+
function bodyDescription(rapier2, type, position, rotation, mass) {
|
|
101
|
+
const description = type === "fixed" ? rapier2.RigidBodyDesc.fixed() : type === "kinematic" || type === "character" ? rapier2.RigidBodyDesc.kinematicPositionBased() : rapier2.RigidBodyDesc.dynamic();
|
|
102
|
+
description.setTranslation(position.x, position.y, position.z).setRotation({ x: rotation.x, y: rotation.y, z: rotation.z, w: rotation.w });
|
|
103
|
+
if (mass !== 0) description.setAdditionalMass(mass);
|
|
104
|
+
return description;
|
|
105
|
+
}
|
|
106
|
+
function characterState(simulationBody, byCollider) {
|
|
107
|
+
const controller = simulationBody.controller;
|
|
108
|
+
if (controller === void 0) return { grounded: false };
|
|
109
|
+
let groundCollider;
|
|
110
|
+
for (let index = 0; index < controller.numComputedCollisions(); index += 1) {
|
|
111
|
+
const collision = controller.computedCollision(index);
|
|
112
|
+
if (collision?.collider === null || collision?.collider === void 0) continue;
|
|
113
|
+
if ((collision.normal1.y ?? Number.NEGATIVE_INFINITY) >= 0.5) {
|
|
114
|
+
groundCollider = byCollider.get(collision.collider.handle)?.id;
|
|
115
|
+
if (groundCollider !== void 0) break;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const grounded = controller.computedGrounded();
|
|
119
|
+
if (groundCollider !== void 0) simulationBody.groundCollider = groundCollider;
|
|
120
|
+
else if (!grounded) simulationBody.groundCollider = void 0;
|
|
121
|
+
return { grounded, groundCollider: simulationBody.groundCollider };
|
|
122
|
+
}
|
|
123
|
+
function createWebPhysicsSimulation(options) {
|
|
124
|
+
const bodies = /* @__PURE__ */ new Map();
|
|
125
|
+
const byCollider = /* @__PURE__ */ new Map();
|
|
126
|
+
const pendingCollisionEvents = [];
|
|
127
|
+
let nextId = 0;
|
|
128
|
+
let disposed = false;
|
|
129
|
+
const requireLive = () => {
|
|
130
|
+
if (disposed) throw new Error("Physics simulation is disposed.");
|
|
131
|
+
};
|
|
132
|
+
const simulation = {
|
|
133
|
+
version: options.version,
|
|
134
|
+
rawWorld: options.world,
|
|
135
|
+
rawEventQueue: options.eventQueue,
|
|
136
|
+
createBody: (bodyOptions) => {
|
|
137
|
+
requireLive();
|
|
138
|
+
if (!Number.isFinite(bodyOptions.mass) || bodyOptions.mass < 0)
|
|
139
|
+
throw new Error("Physics body mass must be a finite non-negative number.");
|
|
140
|
+
const id = nextId;
|
|
141
|
+
nextId += 1;
|
|
142
|
+
const rawShape = createWebPhysicsShape(options.rapier, bodyOptions.shape);
|
|
143
|
+
const rawBody = options.world.createRigidBody(
|
|
144
|
+
bodyDescription(
|
|
145
|
+
options.rapier,
|
|
146
|
+
bodyOptions.type,
|
|
147
|
+
bodyOptions.position,
|
|
148
|
+
bodyOptions.rotation,
|
|
149
|
+
bodyOptions.mass
|
|
150
|
+
)
|
|
151
|
+
);
|
|
152
|
+
const rawCollider = options.world.createCollider(rawShape, rawBody);
|
|
153
|
+
const entry = {
|
|
154
|
+
body: rawBody,
|
|
155
|
+
collider: rawCollider,
|
|
156
|
+
id,
|
|
157
|
+
type: bodyOptions.type
|
|
158
|
+
};
|
|
159
|
+
if (bodyOptions.type === "character") {
|
|
160
|
+
entry.controller = options.world.createCharacterController(0.01);
|
|
161
|
+
entry.controllerHandle = physicsHandle(entry.controller);
|
|
162
|
+
}
|
|
163
|
+
bodies.set(id, entry);
|
|
164
|
+
byCollider.set(rawCollider.handle, entry);
|
|
165
|
+
return {
|
|
166
|
+
body: physicsBodyHandle(id, rawBody),
|
|
167
|
+
collider: physicsColliderHandle(id, rawCollider),
|
|
168
|
+
controller: entry.controllerHandle,
|
|
169
|
+
rawShape
|
|
170
|
+
};
|
|
171
|
+
},
|
|
172
|
+
configureCharacter: (id, characterOptions) => {
|
|
173
|
+
requireLive();
|
|
174
|
+
const entry = bodies.get(id);
|
|
175
|
+
if (entry?.controller === void 0)
|
|
176
|
+
throw new Error("Physics character configuration references a non-character body.");
|
|
177
|
+
if (characterOptions.offset !== 0.01) {
|
|
178
|
+
options.world.removeCharacterController(entry.controller);
|
|
179
|
+
entry.controller = options.world.createCharacterController(characterOptions.offset);
|
|
180
|
+
if (entry.controllerHandle !== void 0)
|
|
181
|
+
entry.controllerHandle.raw = entry.controller;
|
|
182
|
+
}
|
|
183
|
+
entry.character = characterOptions;
|
|
184
|
+
entry.controller.setMaxSlopeClimbAngle(characterOptions.maxSlopeClimbAngle);
|
|
185
|
+
if (characterOptions.autostep !== void 0) {
|
|
186
|
+
entry.controller.enableAutostep(
|
|
187
|
+
characterOptions.autostep.maxHeight,
|
|
188
|
+
characterOptions.autostep.minWidth,
|
|
189
|
+
characterOptions.autostep.includeDynamicBodies
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
if (characterOptions.snapToGround !== void 0)
|
|
193
|
+
entry.controller.enableSnapToGround(characterOptions.snapToGround);
|
|
194
|
+
},
|
|
195
|
+
removeBody: (id) => {
|
|
196
|
+
requireLive();
|
|
197
|
+
const entry = bodies.get(id);
|
|
198
|
+
if (entry === void 0) return;
|
|
199
|
+
bodies.delete(id);
|
|
200
|
+
byCollider.delete(entry.collider.handle);
|
|
201
|
+
if (entry.controller !== void 0) options.world.removeCharacterController(entry.controller);
|
|
202
|
+
if (entry.body.isValid()) options.world.removeRigidBody(entry.body);
|
|
203
|
+
},
|
|
204
|
+
setBodyTransform: (id, position) => {
|
|
205
|
+
requireLive();
|
|
206
|
+
const entry = bodies.get(id);
|
|
207
|
+
if (entry === void 0)
|
|
208
|
+
throw new Error("Physics body transform references an unknown body.");
|
|
209
|
+
entry.body.setTranslation(position, true);
|
|
210
|
+
},
|
|
211
|
+
step: (deltaTime, inputSnapshot) => {
|
|
212
|
+
requireLive();
|
|
213
|
+
requirePhysicsStepInput(deltaTime, inputSnapshot, (id) => bodies.has(id));
|
|
214
|
+
if (inputSnapshot !== void 0) {
|
|
215
|
+
for (let index = 0; index < inputSnapshot.kinematicCount; index += 1) {
|
|
216
|
+
const offset = index * PHYSICS_TRANSFORM_STRIDE;
|
|
217
|
+
const id = inputSnapshot.kinematicTransforms[offset];
|
|
218
|
+
const entry = bodies.get(id);
|
|
219
|
+
if (entry === void 0) throw new Error("PhysicsSimulation input body disappeared.");
|
|
220
|
+
const target = {
|
|
221
|
+
x: inputSnapshot.kinematicTransforms[offset + 1],
|
|
222
|
+
y: inputSnapshot.kinematicTransforms[offset + 2],
|
|
223
|
+
z: inputSnapshot.kinematicTransforms[offset + 3]
|
|
224
|
+
};
|
|
225
|
+
const rotation = {
|
|
226
|
+
x: inputSnapshot.kinematicTransforms[offset + 4],
|
|
227
|
+
y: inputSnapshot.kinematicTransforms[offset + 5],
|
|
228
|
+
z: inputSnapshot.kinematicTransforms[offset + 6],
|
|
229
|
+
w: inputSnapshot.kinematicTransforms[offset + 7]
|
|
230
|
+
};
|
|
231
|
+
if (entry.type === "character") {
|
|
232
|
+
const controller = entry.controller;
|
|
233
|
+
const config = entry.character;
|
|
234
|
+
if (controller === void 0 || config === void 0)
|
|
235
|
+
throw new Error("Physics character was not configured before stepping.");
|
|
236
|
+
const current = entry.body.translation();
|
|
237
|
+
const desired = {
|
|
238
|
+
x: target.x - current.x,
|
|
239
|
+
y: target.y - current.y,
|
|
240
|
+
z: target.z - current.z
|
|
241
|
+
};
|
|
242
|
+
const filterGroups = config.oneWayLayers !== 0 && desired.y > 0 ? interactionGroups(65535, 65535 ^ config.oneWayLayers) : void 0;
|
|
243
|
+
const filterPredicate = config.oneWayLayers !== 0 && desired.y > 0 ? (collider) => (collider.collisionGroups() >>> 16 & config.oneWayLayers) === 0 : void 0;
|
|
244
|
+
controller.computeColliderMovement(
|
|
245
|
+
entry.collider,
|
|
246
|
+
desired,
|
|
247
|
+
options.rapier.QueryFilterFlags.EXCLUDE_SENSORS,
|
|
248
|
+
filterGroups,
|
|
249
|
+
filterPredicate
|
|
250
|
+
);
|
|
251
|
+
const movement = controller.computedMovement();
|
|
252
|
+
entry.body.setNextKinematicTranslation({
|
|
253
|
+
x: current.x + movement.x,
|
|
254
|
+
y: current.y + movement.y,
|
|
255
|
+
z: current.z + movement.z
|
|
256
|
+
});
|
|
257
|
+
} else {
|
|
258
|
+
if (!entry.body.isKinematic())
|
|
259
|
+
throw new Error("PhysicsSimulation received kinematic input for a dynamic body.");
|
|
260
|
+
entry.body.setNextKinematicTranslation(target);
|
|
261
|
+
}
|
|
262
|
+
entry.body.setNextKinematicRotation(rotation);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
options.world.timestep = deltaTime;
|
|
266
|
+
options.world.step(options.eventQueue);
|
|
267
|
+
},
|
|
268
|
+
readVisibleTransforms: (renderBuffer) => {
|
|
269
|
+
requireLive();
|
|
270
|
+
requirePhysicsRenderBuffer(renderBuffer, bodies.size);
|
|
271
|
+
let index = 0;
|
|
272
|
+
for (const entry of bodies.values()) {
|
|
273
|
+
if (!entry.body.isValid()) continue;
|
|
274
|
+
const offset = index * PHYSICS_TRANSFORM_STRIDE;
|
|
275
|
+
const translation = entry.body.translation();
|
|
276
|
+
const rotation = entry.body.rotation();
|
|
277
|
+
renderBuffer[offset] = entry.id;
|
|
278
|
+
renderBuffer[offset + 1] = translation.x;
|
|
279
|
+
renderBuffer[offset + 2] = translation.y;
|
|
280
|
+
renderBuffer[offset + 3] = translation.z;
|
|
281
|
+
renderBuffer[offset + 4] = rotation.x;
|
|
282
|
+
renderBuffer[offset + 5] = rotation.y;
|
|
283
|
+
renderBuffer[offset + 6] = rotation.z;
|
|
284
|
+
renderBuffer[offset + 7] = rotation.w;
|
|
285
|
+
index += 1;
|
|
286
|
+
}
|
|
287
|
+
return index;
|
|
288
|
+
},
|
|
289
|
+
readBodyTransform: (id) => {
|
|
290
|
+
requireLive();
|
|
291
|
+
const entry = bodies.get(id);
|
|
292
|
+
if (entry === void 0 || !entry.body.isValid()) return void 0;
|
|
293
|
+
const position = entry.body.translation();
|
|
294
|
+
const rotation = entry.body.rotation();
|
|
295
|
+
return { position, rotation };
|
|
296
|
+
},
|
|
297
|
+
readCharacterState: (id) => {
|
|
298
|
+
requireLive();
|
|
299
|
+
const entry = bodies.get(id);
|
|
300
|
+
return entry === void 0 ? void 0 : characterState(entry, byCollider);
|
|
301
|
+
},
|
|
302
|
+
areaIntersections: (id) => {
|
|
303
|
+
requireLive();
|
|
304
|
+
const area = bodies.get(id);
|
|
305
|
+
if (area === void 0) return /* @__PURE__ */ new Set();
|
|
306
|
+
const current = /* @__PURE__ */ new Set();
|
|
307
|
+
const areaMask = area.collider.collisionGroups() & 65535;
|
|
308
|
+
options.world.intersectionsWithShape(
|
|
309
|
+
area.collider.translation(),
|
|
310
|
+
area.collider.rotation(),
|
|
311
|
+
area.collider.shape,
|
|
312
|
+
(collider) => {
|
|
313
|
+
const body = byCollider.get(collider.handle);
|
|
314
|
+
if (body !== void 0 && body.id !== id && !collider.isSensor() && (collider.collisionGroups() >>> 16 & areaMask) !== 0)
|
|
315
|
+
current.add(body.id);
|
|
316
|
+
return true;
|
|
317
|
+
},
|
|
318
|
+
options.rapier.QueryFilterFlags.EXCLUDE_SENSORS,
|
|
319
|
+
void 0,
|
|
320
|
+
area.collider
|
|
321
|
+
);
|
|
322
|
+
return current;
|
|
323
|
+
},
|
|
324
|
+
drainCollisionEvents: (buffer) => {
|
|
325
|
+
requireLive();
|
|
326
|
+
requirePhysicsEventBuffer(buffer);
|
|
327
|
+
options.eventQueue.drainCollisionEvents((first, second, started) => {
|
|
328
|
+
const left = byCollider.get(first)?.id;
|
|
329
|
+
const right = byCollider.get(second)?.id;
|
|
330
|
+
if (left !== void 0 && right !== void 0)
|
|
331
|
+
pendingCollisionEvents.push([left, right, Number(started), 1]);
|
|
332
|
+
});
|
|
333
|
+
if (buffer.length < pendingCollisionEvents.length * PHYSICS_COLLISION_EVENT_STRIDE)
|
|
334
|
+
throw new Error("PhysicsSimulation collision event buffer is too small.");
|
|
335
|
+
pendingCollisionEvents.forEach(
|
|
336
|
+
(event, index) => buffer.set(event, index * PHYSICS_COLLISION_EVENT_STRIDE)
|
|
337
|
+
);
|
|
338
|
+
const count = pendingCollisionEvents.length;
|
|
339
|
+
pendingCollisionEvents.length = 0;
|
|
340
|
+
return count;
|
|
341
|
+
},
|
|
342
|
+
dispose: () => {
|
|
343
|
+
if (disposed) return;
|
|
344
|
+
disposed = true;
|
|
345
|
+
for (const entry of bodies.values()) {
|
|
346
|
+
if (entry.controller !== void 0)
|
|
347
|
+
options.world.removeCharacterController(entry.controller);
|
|
348
|
+
if (entry.body.isValid()) options.world.removeRigidBody(entry.body);
|
|
349
|
+
}
|
|
350
|
+
bodies.clear();
|
|
351
|
+
byCollider.clear();
|
|
352
|
+
pendingCollisionEvents.length = 0;
|
|
353
|
+
options.eventQueue.free();
|
|
354
|
+
options.world.free();
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
return simulation;
|
|
358
|
+
}
|
|
359
|
+
function requirePhysicsSimulation(physics, world) {
|
|
360
|
+
if (physics?.simulation !== void 0) return physics.simulation;
|
|
361
|
+
const candidate = typeof world === "object" && world !== null && "simulation" in world ? world.simulation : world;
|
|
362
|
+
if (typeof candidate === "object" && candidate !== null && "createBody" in candidate && typeof candidate.createBody === "function" && "step" in candidate && typeof candidate.step === "function")
|
|
363
|
+
return candidate;
|
|
364
|
+
const backend = selectedBackend;
|
|
365
|
+
if (world !== void 0 && backend?.simulationForWorld !== void 0)
|
|
366
|
+
return backend.simulationForWorld(candidate);
|
|
367
|
+
throw new Error(
|
|
368
|
+
"Physics nodes require a PhysicsContext. Passing a raw backend world is deprecated and backend-specific."
|
|
369
|
+
);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// src/web.ts
|
|
373
|
+
var initialized;
|
|
374
|
+
var simulations = /* @__PURE__ */ new WeakMap();
|
|
375
|
+
installPhysicsSimulationBackend({
|
|
376
|
+
initialize: () => {
|
|
377
|
+
initialized ??= RAPIER.init();
|
|
378
|
+
return initialized;
|
|
379
|
+
},
|
|
380
|
+
createSimulation: (options = {}) => {
|
|
381
|
+
const world = new RAPIER.World(options.gravity ?? { x: 0, y: -9.81, z: 0 });
|
|
382
|
+
const simulation = createWebPhysicsSimulation({
|
|
383
|
+
eventQueue: new RAPIER.EventQueue(true),
|
|
384
|
+
rapier: RAPIER,
|
|
385
|
+
version: RAPIER.version(),
|
|
386
|
+
world
|
|
387
|
+
});
|
|
388
|
+
simulations.set(world, simulation);
|
|
389
|
+
return simulation;
|
|
390
|
+
},
|
|
391
|
+
simulationForWorld: (world) => {
|
|
392
|
+
if (typeof world !== "object" || world === null)
|
|
393
|
+
throw new Error("Physics nodes expected a Rapier World.");
|
|
394
|
+
const simulation = simulations.get(world);
|
|
395
|
+
if (simulation !== void 0) return simulation;
|
|
396
|
+
const created = createWebPhysicsSimulation({
|
|
397
|
+
eventQueue: new RAPIER.EventQueue(true),
|
|
398
|
+
rapier: RAPIER,
|
|
399
|
+
version: RAPIER.version(),
|
|
400
|
+
world
|
|
401
|
+
});
|
|
402
|
+
simulations.set(world, created);
|
|
403
|
+
return created;
|
|
404
|
+
},
|
|
405
|
+
createShape: (shape) => createWebPhysicsShape(RAPIER, shape)
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
// src/Area3D.ts
|
|
409
|
+
var MAX_CONTACT_LOG = 1e3;
|
|
410
|
+
function finiteTransform(values, offset) {
|
|
411
|
+
const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
|
|
412
|
+
if (result.some((value) => value === void 0 || !Number.isFinite(value)))
|
|
413
|
+
throw new Error("PhysicsSimulation returned a malformed transform.");
|
|
414
|
+
return result;
|
|
415
|
+
}
|
|
416
|
+
var Area3D = class {
|
|
417
|
+
entity;
|
|
418
|
+
body;
|
|
419
|
+
collider;
|
|
420
|
+
#simulation;
|
|
421
|
+
#physics;
|
|
422
|
+
#position = { x: 0, y: 0, z: 0 };
|
|
423
|
+
#entered = /* @__PURE__ */ new Map();
|
|
424
|
+
#contacts = [];
|
|
425
|
+
#monitoring = true;
|
|
426
|
+
#listeners = {
|
|
427
|
+
bodyEntered: /* @__PURE__ */ new Set(),
|
|
428
|
+
bodyExited: /* @__PURE__ */ new Set()
|
|
429
|
+
};
|
|
430
|
+
#disposed = false;
|
|
431
|
+
constructor(options) {
|
|
432
|
+
this.#simulation = requirePhysicsSimulation(options.physics, options.world);
|
|
433
|
+
this.#physics = options.physics;
|
|
434
|
+
this.entity = options.entity;
|
|
435
|
+
Object.assign(this.#position, options.position ?? { x: 0, y: 0, z: 0 });
|
|
436
|
+
const shape = options.shape.setSensor(true).descriptor;
|
|
437
|
+
if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
|
|
438
|
+
const layer = options.collisionLayer ?? shape.collisionLayer;
|
|
439
|
+
const mask = options.collisionMask ?? shape.collisionMask;
|
|
440
|
+
options.shape.setCollisionGroups(interactionGroups(layer, mask));
|
|
441
|
+
}
|
|
442
|
+
const registration = this.#simulation.createBody({
|
|
443
|
+
mass: 0,
|
|
444
|
+
position: this.#position,
|
|
445
|
+
rotation: { w: 1, x: 0, y: 0, z: 0 },
|
|
446
|
+
sensor: true,
|
|
447
|
+
shape,
|
|
448
|
+
type: "kinematic"
|
|
449
|
+
});
|
|
450
|
+
options.shape.bindRaw(registration.rawShape);
|
|
451
|
+
this.body = registration.body;
|
|
452
|
+
this.collider = registration.collider;
|
|
453
|
+
this.#physics?.addArea(this);
|
|
454
|
+
}
|
|
455
|
+
on(event, handler) {
|
|
456
|
+
this.#listeners[event].add(handler);
|
|
457
|
+
return () => this.#listeners[event].delete(handler);
|
|
458
|
+
}
|
|
459
|
+
/** Mirrors Godot's Area3D.monitoring. When false the area reports no contacts. */
|
|
460
|
+
get monitoring() {
|
|
461
|
+
return this.#monitoring;
|
|
462
|
+
}
|
|
463
|
+
set monitoring(value) {
|
|
464
|
+
if (this.#monitoring === value) return;
|
|
465
|
+
this.#monitoring = value;
|
|
466
|
+
if (!value) this.#entered.clear();
|
|
467
|
+
}
|
|
468
|
+
setPosition(position) {
|
|
469
|
+
if (!this.#disposed) {
|
|
470
|
+
Object.assign(this.#position, position);
|
|
471
|
+
this.#simulation.setBodyTransform(this.body.id, position);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
/** Called by the shared plugin before a bulk step. */
|
|
475
|
+
writeKinematic(buffer, offset) {
|
|
476
|
+
if (this.#disposed) return;
|
|
477
|
+
buffer.set(
|
|
478
|
+
[this.body.id, this.#position.x, this.#position.y, this.#position.z, 0, 0, 0, 1],
|
|
479
|
+
offset
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
applyTransform(values, offset) {
|
|
483
|
+
const [, x, y, z] = finiteTransform(values, offset);
|
|
484
|
+
Object.assign(this.#position, { x, y, z });
|
|
485
|
+
}
|
|
486
|
+
handleCollision(body, started) {
|
|
487
|
+
if (this.#disposed || !this.#monitoring) return;
|
|
488
|
+
const handle = body.body.id;
|
|
489
|
+
if (started) {
|
|
490
|
+
if (this.#entered.has(handle)) return;
|
|
491
|
+
this.#entered.set(handle, body);
|
|
492
|
+
this.#contacts.push({ area: this, body, entity: this.entity, started: true });
|
|
493
|
+
if (this.#contacts.length > MAX_CONTACT_LOG) this.#contacts.shift();
|
|
494
|
+
for (const handler of this.#listeners.bodyEntered) handler(body);
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
const entered = this.#entered.get(handle);
|
|
498
|
+
if (entered === void 0) return;
|
|
499
|
+
this.#entered.delete(handle);
|
|
500
|
+
this.#contacts.push({ area: this, body: entered, entity: this.entity, started: false });
|
|
501
|
+
if (this.#contacts.length > MAX_CONTACT_LOG) this.#contacts.shift();
|
|
502
|
+
for (const handler of this.#listeners.bodyExited) handler(entered);
|
|
503
|
+
}
|
|
504
|
+
drainContacts() {
|
|
505
|
+
const contacts = this.#contacts;
|
|
506
|
+
this.#contacts = [];
|
|
507
|
+
return contacts;
|
|
508
|
+
}
|
|
509
|
+
reconcileIntersections(current) {
|
|
510
|
+
for (const body of current.values()) this.handleCollision(body, true);
|
|
511
|
+
for (const [handle, body] of this.#entered) {
|
|
512
|
+
if (!current.has(handle)) this.handleCollision(body, false);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
dispose() {
|
|
516
|
+
if (this.#disposed) return;
|
|
517
|
+
this.#disposed = true;
|
|
518
|
+
this.#physics?.removeArea(this);
|
|
519
|
+
this.#simulation.removeBody(this.body.id);
|
|
520
|
+
this.#entered.clear();
|
|
521
|
+
this.#listeners.bodyEntered.clear();
|
|
522
|
+
this.#listeners.bodyExited.clear();
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
// src/CharacterBody3D.ts
|
|
527
|
+
function finiteTransform2(values, offset) {
|
|
528
|
+
const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
|
|
529
|
+
if (result.some((value) => value === void 0 || !Number.isFinite(value)))
|
|
530
|
+
throw new Error("PhysicsSimulation returned a malformed transform.");
|
|
531
|
+
return result;
|
|
532
|
+
}
|
|
533
|
+
var CharacterBody3D = class {
|
|
534
|
+
body;
|
|
535
|
+
collider;
|
|
536
|
+
controller;
|
|
537
|
+
object;
|
|
538
|
+
velocity;
|
|
539
|
+
gravity;
|
|
540
|
+
maxFallSpeed;
|
|
541
|
+
oneWayLayers;
|
|
542
|
+
grounded = false;
|
|
543
|
+
#simulation;
|
|
544
|
+
#physics;
|
|
545
|
+
#desired = { x: 0, y: 0, z: 0 };
|
|
546
|
+
#sliding = false;
|
|
547
|
+
#groundCollider;
|
|
548
|
+
#beforeY = 0;
|
|
549
|
+
#desiredY = 0;
|
|
550
|
+
#disposed = false;
|
|
551
|
+
constructor(options) {
|
|
552
|
+
this.#simulation = requirePhysicsSimulation(options.physics, options.world);
|
|
553
|
+
this.#physics = options.physics;
|
|
554
|
+
this.object = options.object;
|
|
555
|
+
this.velocity = this.object.position.clone().set(0, 0, 0);
|
|
556
|
+
this.gravity = options.gravity ?? -9.81;
|
|
557
|
+
this.maxFallSpeed = options.maxFallSpeed ?? 50;
|
|
558
|
+
this.oneWayLayers = options.oneWayLayers ?? 0;
|
|
559
|
+
const shape = options.shape.descriptor;
|
|
560
|
+
if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
|
|
561
|
+
const layer = options.collisionLayer ?? shape.collisionLayer;
|
|
562
|
+
const mask = options.collisionMask ?? shape.collisionMask;
|
|
563
|
+
options.shape.setCollisionGroups(interactionGroups(layer, mask));
|
|
564
|
+
}
|
|
565
|
+
const registration = this.#simulation.createBody({
|
|
566
|
+
mass: 0,
|
|
567
|
+
position: this.object.position,
|
|
568
|
+
rotation: this.object.quaternion,
|
|
569
|
+
sensor: false,
|
|
570
|
+
shape,
|
|
571
|
+
type: "character"
|
|
572
|
+
});
|
|
573
|
+
if (registration.controller === void 0) {
|
|
574
|
+
this.#simulation.removeBody(registration.body.id);
|
|
575
|
+
throw new Error("Physics character backend did not provide a controller handle.");
|
|
576
|
+
}
|
|
577
|
+
options.shape.bindRaw(registration.rawShape);
|
|
578
|
+
this.body = registration.body;
|
|
579
|
+
this.collider = registration.collider;
|
|
580
|
+
this.controller = registration.controller;
|
|
581
|
+
const characterOptions = {
|
|
582
|
+
autostep: options.autostep === void 0 ? void 0 : {
|
|
583
|
+
includeDynamicBodies: options.autostep.includeDynamicBodies ?? false,
|
|
584
|
+
maxHeight: options.autostep.maxHeight,
|
|
585
|
+
minWidth: options.autostep.minWidth
|
|
586
|
+
},
|
|
587
|
+
maxSlopeClimbAngle: options.maxSlopeClimbAngle ?? Math.PI / 4,
|
|
588
|
+
offset: options.offset ?? 0.01,
|
|
589
|
+
oneWayLayers: this.oneWayLayers,
|
|
590
|
+
snapToGround: options.snapToGround
|
|
591
|
+
};
|
|
592
|
+
try {
|
|
593
|
+
this.#simulation.configureCharacter(this.body.id, characterOptions);
|
|
594
|
+
} catch (error) {
|
|
595
|
+
this.#simulation.removeBody(this.body.id);
|
|
596
|
+
throw error;
|
|
597
|
+
}
|
|
598
|
+
this.#physics?.add(this);
|
|
599
|
+
}
|
|
600
|
+
move(desiredTranslation) {
|
|
601
|
+
this.#desired = { x: desiredTranslation.x, y: desiredTranslation.y, z: desiredTranslation.z };
|
|
602
|
+
this.#sliding = false;
|
|
603
|
+
}
|
|
604
|
+
moveAndSlide(dt) {
|
|
605
|
+
if (!Number.isFinite(dt) || dt < 0)
|
|
606
|
+
throw new Error("CharacterBody3D.moveAndSlide requires a finite non-negative dt.");
|
|
607
|
+
this.velocity.y = Math.max(this.velocity.y + this.gravity * dt, -this.maxFallSpeed);
|
|
608
|
+
this.#desired = {
|
|
609
|
+
x: this.velocity.x * dt,
|
|
610
|
+
y: this.velocity.y * dt,
|
|
611
|
+
z: this.velocity.z * dt
|
|
612
|
+
};
|
|
613
|
+
this.#sliding = true;
|
|
614
|
+
}
|
|
615
|
+
/** Called by the shared plugin before a bulk step. */
|
|
616
|
+
writeKinematic(buffer, offset) {
|
|
617
|
+
if (this.#disposed) return;
|
|
618
|
+
this.#beforeY = this.object.position.y;
|
|
619
|
+
this.#desiredY = this.#desired.y;
|
|
620
|
+
const carry = this.#sliding && this.grounded && this.velocity.y <= 0 && this.#groundCollider !== void 0 ? this.#physics?.kinematicMotion?.(this.#groundCollider) : void 0;
|
|
621
|
+
buffer.set(
|
|
622
|
+
[
|
|
623
|
+
this.body.id,
|
|
624
|
+
this.object.position.x + this.#desired.x + (carry?.x ?? 0),
|
|
625
|
+
this.object.position.y + this.#desired.y + (carry?.y ?? 0),
|
|
626
|
+
this.object.position.z + this.#desired.z + (carry?.z ?? 0),
|
|
627
|
+
this.object.quaternion.x,
|
|
628
|
+
this.object.quaternion.y,
|
|
629
|
+
this.object.quaternion.z,
|
|
630
|
+
this.object.quaternion.w
|
|
631
|
+
],
|
|
632
|
+
offset
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
syncToPhysics() {
|
|
636
|
+
}
|
|
637
|
+
step() {
|
|
638
|
+
}
|
|
639
|
+
teleport(position) {
|
|
640
|
+
if (this.#disposed) throw new Error("CharacterBody3D.teleport cannot be used after dispose.");
|
|
641
|
+
this.#simulation.setBodyTransform(this.body.id, position);
|
|
642
|
+
this.object.position.set(position.x, position.y, position.z);
|
|
643
|
+
this.velocity.set(0, 0, 0);
|
|
644
|
+
this.#desired = { x: 0, y: 0, z: 0 };
|
|
645
|
+
this.#sliding = false;
|
|
646
|
+
this.#groundCollider = void 0;
|
|
647
|
+
this.grounded = false;
|
|
648
|
+
}
|
|
649
|
+
applyTransform(values, offset) {
|
|
650
|
+
const [, x, y, z, qx, qy, qz, qw] = finiteTransform2(values, offset);
|
|
651
|
+
const state = this.#simulation.readCharacterState?.(this.body.id);
|
|
652
|
+
this.grounded = state?.grounded ?? (this.#sliding && this.#desiredY < 0 && y - this.#beforeY > this.#desiredY + 1e-4);
|
|
653
|
+
this.#groundCollider = state?.groundCollider;
|
|
654
|
+
if (this.#sliding && this.grounded && this.velocity.y < 0) this.velocity.y = 0;
|
|
655
|
+
this.object.position.set(x, y, z);
|
|
656
|
+
this.object.quaternion.set(qx, qy, qz, qw);
|
|
657
|
+
this.#desired = { x: 0, y: 0, z: 0 };
|
|
658
|
+
this.#sliding = false;
|
|
659
|
+
}
|
|
660
|
+
syncFromPhysics() {
|
|
661
|
+
const transform = this.#simulation.readBodyTransform?.(this.body.id);
|
|
662
|
+
if (transform === void 0) return;
|
|
663
|
+
this.object.position.set(transform.position.x, transform.position.y, transform.position.z);
|
|
664
|
+
this.object.quaternion.set(
|
|
665
|
+
transform.rotation.x,
|
|
666
|
+
transform.rotation.y,
|
|
667
|
+
transform.rotation.z,
|
|
668
|
+
transform.rotation.w
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
dispose() {
|
|
672
|
+
if (this.#disposed) return;
|
|
673
|
+
this.#disposed = true;
|
|
674
|
+
this.#physics?.remove(this);
|
|
675
|
+
this.#simulation.removeBody(this.body.id);
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
|
|
679
|
+
// src/CollisionShape3D.ts
|
|
680
|
+
function geometryVertices(mesh) {
|
|
681
|
+
const position = mesh.geometry.getAttribute("position");
|
|
682
|
+
if (position === void 0)
|
|
683
|
+
throw new Error("CollisionShape3D.fromMesh requires vertex positions.");
|
|
684
|
+
const vertices = new Float32Array(position.count * 3);
|
|
685
|
+
for (let index = 0; index < position.count; index++) {
|
|
686
|
+
vertices[index * 3] = position.getX(index) * mesh.scale.x;
|
|
687
|
+
vertices[index * 3 + 1] = position.getY(index) * mesh.scale.y;
|
|
688
|
+
vertices[index * 3 + 2] = position.getZ(index) * mesh.scale.z;
|
|
689
|
+
}
|
|
690
|
+
return vertices;
|
|
691
|
+
}
|
|
692
|
+
function geometryIndices(mesh) {
|
|
693
|
+
const index = mesh.geometry.getIndex();
|
|
694
|
+
if (index !== null)
|
|
695
|
+
return Uint32Array.from({ length: index.count }, (_, offset) => index.getX(offset));
|
|
696
|
+
const count = mesh.geometry.getAttribute("position")?.count ?? 0;
|
|
697
|
+
if (count === 0 || count % 3 !== 0)
|
|
698
|
+
throw new Error("CollisionShape3D.fromMesh requires triangle indices.");
|
|
699
|
+
return Uint32Array.from({ length: count }, (_, offset) => offset);
|
|
700
|
+
}
|
|
701
|
+
function finitePositive(value, label) {
|
|
702
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
703
|
+
throw new Error(`CollisionShape3D.${label} requires a positive finite value.`);
|
|
704
|
+
return value;
|
|
705
|
+
}
|
|
706
|
+
function applyRaw(raw, method, ...args) {
|
|
707
|
+
if (typeof raw !== "object" || raw === null || !(method in raw)) return;
|
|
708
|
+
const operation = raw[method];
|
|
709
|
+
if (typeof operation === "function") operation.apply(raw, args);
|
|
710
|
+
}
|
|
711
|
+
var CollisionShape3D = class _CollisionShape3D {
|
|
712
|
+
#descriptor;
|
|
713
|
+
#backendRaw;
|
|
714
|
+
constructor(descriptor) {
|
|
715
|
+
this.#descriptor = descriptor;
|
|
716
|
+
}
|
|
717
|
+
/** Backend-neutral data consumed by the selected PhysicsSimulation adapter. */
|
|
718
|
+
get descriptor() {
|
|
719
|
+
return this.#descriptor;
|
|
720
|
+
}
|
|
721
|
+
/** Rapier's descriptor on web, or an opaque native descriptor after registration. */
|
|
722
|
+
get raw() {
|
|
723
|
+
if (this.#backendRaw === void 0) {
|
|
724
|
+
try {
|
|
725
|
+
const createShape = physicsSimulationBackend().createShape;
|
|
726
|
+
if (createShape !== void 0) this.#backendRaw = createShape(this.#descriptor);
|
|
727
|
+
} catch {
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return this.#backendRaw ?? this.#descriptor;
|
|
731
|
+
}
|
|
732
|
+
/** Internal seam: the backend binds its own descriptor when the body is created. */
|
|
733
|
+
bindRaw(raw) {
|
|
734
|
+
this.#backendRaw = raw;
|
|
735
|
+
applyRaw(
|
|
736
|
+
raw,
|
|
737
|
+
"setCollisionGroups",
|
|
738
|
+
interactionGroups(this.#descriptor.collisionLayer, this.#descriptor.collisionMask)
|
|
739
|
+
);
|
|
740
|
+
applyRaw(raw, "setSensor", this.#descriptor.sensor);
|
|
741
|
+
}
|
|
742
|
+
static box(width, height, depth) {
|
|
743
|
+
return new _CollisionShape3D({
|
|
744
|
+
collisionLayer: 1,
|
|
745
|
+
collisionMask: 65535,
|
|
746
|
+
kind: "box",
|
|
747
|
+
sensor: false,
|
|
748
|
+
x: finitePositive(width, "box") / 2,
|
|
749
|
+
y: finitePositive(height, "box") / 2,
|
|
750
|
+
z: finitePositive(depth, "box") / 2
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
static sphere(radius) {
|
|
754
|
+
return new _CollisionShape3D({
|
|
755
|
+
collisionLayer: 1,
|
|
756
|
+
collisionMask: 65535,
|
|
757
|
+
kind: "sphere",
|
|
758
|
+
sensor: false,
|
|
759
|
+
x: finitePositive(radius, "sphere"),
|
|
760
|
+
y: 0,
|
|
761
|
+
z: 0
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
static capsule(halfHeight, radius) {
|
|
765
|
+
if (!Number.isFinite(halfHeight) || halfHeight < 0)
|
|
766
|
+
throw new Error("CollisionShape3D.capsule requires a finite non-negative halfHeight.");
|
|
767
|
+
return new _CollisionShape3D({
|
|
768
|
+
collisionLayer: 1,
|
|
769
|
+
collisionMask: 65535,
|
|
770
|
+
kind: "capsule",
|
|
771
|
+
sensor: false,
|
|
772
|
+
x: halfHeight,
|
|
773
|
+
y: finitePositive(radius, "capsule"),
|
|
774
|
+
z: 0
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
static heightfield(rows, columns, heights, scale) {
|
|
778
|
+
if (!Number.isInteger(rows) || rows < 2)
|
|
779
|
+
throw new Error("CollisionShape3D.heightfield requires at least 2 rows.");
|
|
780
|
+
if (!Number.isInteger(columns) || columns < 2)
|
|
781
|
+
throw new Error("CollisionShape3D.heightfield requires at least 2 columns.");
|
|
782
|
+
if (heights.length !== rows * columns)
|
|
783
|
+
throw new Error(
|
|
784
|
+
`CollisionShape3D.heightfield expected ${rows * columns} heights, received ${heights.length}.`
|
|
785
|
+
);
|
|
786
|
+
return new _CollisionShape3D({
|
|
787
|
+
collisionLayer: 1,
|
|
788
|
+
collisionMask: 65535,
|
|
789
|
+
kind: "heightfield",
|
|
790
|
+
sensor: false,
|
|
791
|
+
x: 0,
|
|
792
|
+
y: 0,
|
|
793
|
+
z: 0,
|
|
794
|
+
rows,
|
|
795
|
+
columns,
|
|
796
|
+
heights,
|
|
797
|
+
shape: { ncols: columns - 1, nrows: rows - 1, scale },
|
|
798
|
+
scale
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
static fromMesh(mesh, kind) {
|
|
802
|
+
const geometry = mesh.geometry;
|
|
803
|
+
const inferred = kind ?? (geometry.type.toLowerCase().includes("sphere") ? "sphere" : geometry.type.toLowerCase().includes("capsule") ? "capsule" : "box");
|
|
804
|
+
if (inferred === "trimesh")
|
|
805
|
+
return new _CollisionShape3D({
|
|
806
|
+
collisionLayer: 1,
|
|
807
|
+
collisionMask: 65535,
|
|
808
|
+
kind: inferred,
|
|
809
|
+
sensor: false,
|
|
810
|
+
x: 0,
|
|
811
|
+
y: 0,
|
|
812
|
+
z: 0,
|
|
813
|
+
vertices: geometryVertices(mesh),
|
|
814
|
+
indices: geometryIndices(mesh)
|
|
815
|
+
});
|
|
816
|
+
if (inferred === "convexHull")
|
|
817
|
+
return new _CollisionShape3D({
|
|
818
|
+
collisionLayer: 1,
|
|
819
|
+
collisionMask: 65535,
|
|
820
|
+
kind: inferred,
|
|
821
|
+
sensor: false,
|
|
822
|
+
x: 0,
|
|
823
|
+
y: 0,
|
|
824
|
+
z: 0,
|
|
825
|
+
vertices: geometryVertices(mesh)
|
|
826
|
+
});
|
|
827
|
+
if (inferred === "heightfield")
|
|
828
|
+
throw new Error("CollisionShape3D.fromMesh cannot infer a heightfield.");
|
|
829
|
+
geometry.computeBoundingBox();
|
|
830
|
+
const bounds = geometry.boundingBox;
|
|
831
|
+
if (bounds === null) throw new Error("CollisionShape3D.fromMesh requires a bounding box.");
|
|
832
|
+
const width = (bounds.max.x - bounds.min.x) * Math.abs(mesh.scale.x);
|
|
833
|
+
const height = (bounds.max.y - bounds.min.y) * Math.abs(mesh.scale.y);
|
|
834
|
+
const depth = (bounds.max.z - bounds.min.z) * Math.abs(mesh.scale.z);
|
|
835
|
+
if (inferred === "sphere") {
|
|
836
|
+
geometry.computeBoundingSphere();
|
|
837
|
+
const radius = (geometry.boundingSphere?.radius ?? Math.max(width, height, depth) / 2) * Math.max(Math.abs(mesh.scale.x), Math.abs(mesh.scale.y), Math.abs(mesh.scale.z));
|
|
838
|
+
return _CollisionShape3D.sphere(radius);
|
|
839
|
+
}
|
|
840
|
+
if (inferred === "capsule") {
|
|
841
|
+
const radius = Math.min(width, depth) / 2;
|
|
842
|
+
return _CollisionShape3D.capsule(Math.max(0, height / 2 - radius), radius);
|
|
843
|
+
}
|
|
844
|
+
return _CollisionShape3D.box(width, height, depth);
|
|
845
|
+
}
|
|
846
|
+
setCollisionGroups(groups) {
|
|
847
|
+
const layer = groups >>> 16;
|
|
848
|
+
const mask = groups & 65535;
|
|
849
|
+
interactionGroups(layer, mask);
|
|
850
|
+
this.#descriptor.collisionLayer = layer;
|
|
851
|
+
this.#descriptor.collisionMask = mask;
|
|
852
|
+
applyRaw(this.#backendRaw, "setCollisionGroups", groups);
|
|
853
|
+
return this;
|
|
854
|
+
}
|
|
855
|
+
setSensor(sensor) {
|
|
856
|
+
this.#descriptor.sensor = sensor;
|
|
857
|
+
applyRaw(this.#backendRaw, "setSensor", sensor);
|
|
858
|
+
return this;
|
|
859
|
+
}
|
|
860
|
+
};
|
|
861
|
+
|
|
862
|
+
// src/RigidBody3D.ts
|
|
863
|
+
function finiteTransform3(values, offset) {
|
|
864
|
+
const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
|
|
865
|
+
if (result.some((value) => value === void 0 || !Number.isFinite(value)))
|
|
866
|
+
throw new Error("PhysicsSimulation returned a malformed transform.");
|
|
867
|
+
return result;
|
|
868
|
+
}
|
|
869
|
+
var RigidBody3D = class {
|
|
870
|
+
body;
|
|
871
|
+
collider;
|
|
872
|
+
object;
|
|
873
|
+
type;
|
|
874
|
+
#simulation;
|
|
875
|
+
#physics;
|
|
876
|
+
#lastPosition;
|
|
877
|
+
#disposed = false;
|
|
878
|
+
constructor(options) {
|
|
879
|
+
this.#simulation = requirePhysicsSimulation(options.physics, options.world);
|
|
880
|
+
this.#physics = options.physics;
|
|
881
|
+
this.object = options.object;
|
|
882
|
+
this.type = options.type ?? "dynamic";
|
|
883
|
+
const shape = options.shape.descriptor;
|
|
884
|
+
if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
|
|
885
|
+
const layer = options.collisionLayer ?? shape.collisionLayer;
|
|
886
|
+
const mask = options.collisionMask ?? shape.collisionMask;
|
|
887
|
+
options.shape.setCollisionGroups(interactionGroups(layer, mask));
|
|
888
|
+
}
|
|
889
|
+
const registration = this.#simulation.createBody({
|
|
890
|
+
mass: options.mass ?? 0,
|
|
891
|
+
position: this.object.position,
|
|
892
|
+
rotation: this.object.quaternion,
|
|
893
|
+
sensor: false,
|
|
894
|
+
shape,
|
|
895
|
+
type: this.type
|
|
896
|
+
});
|
|
897
|
+
options.shape.bindRaw(registration.rawShape);
|
|
898
|
+
this.body = registration.body;
|
|
899
|
+
this.collider = registration.collider;
|
|
900
|
+
this.#lastPosition = {
|
|
901
|
+
x: this.object.position.x,
|
|
902
|
+
y: this.object.position.y,
|
|
903
|
+
z: this.object.position.z
|
|
904
|
+
};
|
|
905
|
+
this.#physics?.add(this);
|
|
906
|
+
}
|
|
907
|
+
/** Called by the shared plugin before a bulk step. */
|
|
908
|
+
writeKinematic(buffer, offset) {
|
|
909
|
+
if (this.#disposed) return;
|
|
910
|
+
buffer.set(
|
|
911
|
+
[
|
|
912
|
+
this.body.id,
|
|
913
|
+
this.object.position.x,
|
|
914
|
+
this.object.position.y,
|
|
915
|
+
this.object.position.z,
|
|
916
|
+
this.object.quaternion.x,
|
|
917
|
+
this.object.quaternion.y,
|
|
918
|
+
this.object.quaternion.z,
|
|
919
|
+
this.object.quaternion.w
|
|
920
|
+
],
|
|
921
|
+
offset
|
|
922
|
+
);
|
|
923
|
+
}
|
|
924
|
+
/** Displacement since the last backend transform, used for moving-platform carry. */
|
|
925
|
+
kinematicMotion() {
|
|
926
|
+
return {
|
|
927
|
+
x: this.object.position.x - this.#lastPosition.x,
|
|
928
|
+
y: this.object.position.y - this.#lastPosition.y,
|
|
929
|
+
z: this.object.position.z - this.#lastPosition.z
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
syncToPhysics() {
|
|
933
|
+
}
|
|
934
|
+
syncFromPhysics() {
|
|
935
|
+
const transform = this.#simulation.readBodyTransform?.(this.body.id);
|
|
936
|
+
if (transform === void 0) return;
|
|
937
|
+
this.object.position.set(transform.position.x, transform.position.y, transform.position.z);
|
|
938
|
+
this.object.quaternion.set(
|
|
939
|
+
transform.rotation.x,
|
|
940
|
+
transform.rotation.y,
|
|
941
|
+
transform.rotation.z,
|
|
942
|
+
transform.rotation.w
|
|
943
|
+
);
|
|
944
|
+
this.#lastPosition = { ...transform.position };
|
|
945
|
+
}
|
|
946
|
+
applyTransform(values, offset) {
|
|
947
|
+
const [, x, y, z, qx, qy, qz, qw] = finiteTransform3(values, offset);
|
|
948
|
+
this.object.position.set(x, y, z);
|
|
949
|
+
this.object.quaternion.set(qx, qy, qz, qw);
|
|
950
|
+
this.#lastPosition = { x, y, z };
|
|
951
|
+
}
|
|
952
|
+
dispose() {
|
|
953
|
+
if (this.#disposed) return;
|
|
954
|
+
this.#disposed = true;
|
|
955
|
+
this.#physics?.remove(this);
|
|
956
|
+
this.#simulation.removeBody(this.body.id);
|
|
957
|
+
}
|
|
958
|
+
};
|
|
959
|
+
|
|
960
|
+
// src/plugin.ts
|
|
961
|
+
function growFloat(buffer, records) {
|
|
962
|
+
if (buffer.length >= records * PHYSICS_TRANSFORM_STRIDE) return buffer;
|
|
963
|
+
return new Float32Array(
|
|
964
|
+
Math.max(records, Math.max(1, buffer.length / PHYSICS_TRANSFORM_STRIDE) * 2) * PHYSICS_TRANSFORM_STRIDE
|
|
965
|
+
);
|
|
966
|
+
}
|
|
967
|
+
function growEvents(buffer, bodyCount) {
|
|
968
|
+
const required = Math.max(64, bodyCount * 2 * PHYSICS_COLLISION_EVENT_STRIDE);
|
|
969
|
+
let length = buffer.length;
|
|
970
|
+
while (length < required) length *= 2;
|
|
971
|
+
return length === buffer.length ? buffer : new Uint32Array(length);
|
|
972
|
+
}
|
|
973
|
+
function isSmallBufferError(error) {
|
|
974
|
+
return error instanceof Error && /buffer is too small/i.test(error.message);
|
|
975
|
+
}
|
|
976
|
+
function visibleId(buffer, offset) {
|
|
977
|
+
const value = buffer[offset];
|
|
978
|
+
if (value === void 0 || !Number.isInteger(value) || value < 0)
|
|
979
|
+
throw new Error("PhysicsSimulation returned an invalid visible body id.");
|
|
980
|
+
return value;
|
|
981
|
+
}
|
|
982
|
+
function rapier(options = {}) {
|
|
983
|
+
const backend = physicsSimulationBackend();
|
|
984
|
+
let simulation;
|
|
985
|
+
let context;
|
|
986
|
+
const bodies = /* @__PURE__ */ new Set();
|
|
987
|
+
const bodiesById = /* @__PURE__ */ new Map();
|
|
988
|
+
const areas = /* @__PURE__ */ new Map();
|
|
989
|
+
const kinematicMotions = /* @__PURE__ */ new Map();
|
|
990
|
+
let kinematic = new Float32Array(PHYSICS_TRANSFORM_STRIDE * 16);
|
|
991
|
+
let visible = new Float32Array(PHYSICS_TRANSFORM_STRIDE * 16);
|
|
992
|
+
let events = new Uint32Array(64);
|
|
993
|
+
return {
|
|
994
|
+
setup: async (ctx, runtime) => {
|
|
995
|
+
await backend.initialize();
|
|
996
|
+
const selected = backend.createSimulation(options);
|
|
997
|
+
simulation = selected;
|
|
998
|
+
if (runtime !== void 0) runtime.rapier = selected.version;
|
|
999
|
+
context = {
|
|
1000
|
+
add: (body) => {
|
|
1001
|
+
bodies.add(body);
|
|
1002
|
+
bodiesById.set(body.body.id, body);
|
|
1003
|
+
},
|
|
1004
|
+
addArea: (area) => areas.set(area.body.id, area),
|
|
1005
|
+
eventQueue: physicsHandle(selected.rawEventQueue),
|
|
1006
|
+
kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
|
|
1007
|
+
numBodies: () => bodies.size,
|
|
1008
|
+
remove: (body) => {
|
|
1009
|
+
bodies.delete(body);
|
|
1010
|
+
bodiesById.delete(body.body.id);
|
|
1011
|
+
},
|
|
1012
|
+
removeArea: (area) => areas.delete(area.body.id),
|
|
1013
|
+
simulation: selected,
|
|
1014
|
+
world: physicsWorldHandle(selected.rawWorld, selected)
|
|
1015
|
+
};
|
|
1016
|
+
ctx.physics = context;
|
|
1017
|
+
return void 0;
|
|
1018
|
+
},
|
|
1019
|
+
update: (_ctx, dt) => {
|
|
1020
|
+
if (simulation === void 0) throw new Error("Physics plugin updated before setup.");
|
|
1021
|
+
kinematicMotions.clear();
|
|
1022
|
+
let count = 0;
|
|
1023
|
+
kinematic = growFloat(kinematic, bodies.size + areas.size);
|
|
1024
|
+
for (const body of bodies) {
|
|
1025
|
+
if (body instanceof RigidBody3D && body.type === "kinematic") {
|
|
1026
|
+
kinematicMotions.set(body.collider.id, body.kinematicMotion());
|
|
1027
|
+
body.writeKinematic(kinematic, count * PHYSICS_TRANSFORM_STRIDE);
|
|
1028
|
+
count += 1;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
for (const body of bodies) {
|
|
1032
|
+
if (body instanceof CharacterBody3D) {
|
|
1033
|
+
body.writeKinematic(kinematic, count * PHYSICS_TRANSFORM_STRIDE);
|
|
1034
|
+
count += 1;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
for (const area of areas.values()) {
|
|
1038
|
+
area.writeKinematic(kinematic, count * PHYSICS_TRANSFORM_STRIDE);
|
|
1039
|
+
count += 1;
|
|
1040
|
+
}
|
|
1041
|
+
const input = {
|
|
1042
|
+
kinematicCount: count,
|
|
1043
|
+
kinematicTransforms: kinematic
|
|
1044
|
+
};
|
|
1045
|
+
simulation.step(dt, input);
|
|
1046
|
+
visible = growFloat(visible, bodies.size + areas.size);
|
|
1047
|
+
const visibleCount = simulation.readVisibleTransforms(visible);
|
|
1048
|
+
for (let index = 0; index < visibleCount; index += 1) {
|
|
1049
|
+
const offset = index * PHYSICS_TRANSFORM_STRIDE;
|
|
1050
|
+
const id = visibleId(visible, offset);
|
|
1051
|
+
const body = bodiesById.get(id);
|
|
1052
|
+
if (body !== void 0) body.applyTransform(visible, offset);
|
|
1053
|
+
else {
|
|
1054
|
+
const area = areas.get(id);
|
|
1055
|
+
if (area === void 0)
|
|
1056
|
+
throw new Error("PhysicsSimulation returned an unknown visible body id.");
|
|
1057
|
+
area.applyTransform(visible, offset);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
events = growEvents(events, bodies.size + areas.size);
|
|
1061
|
+
const maximumEventValues = Math.max(
|
|
1062
|
+
64,
|
|
1063
|
+
(bodies.size + areas.size) ** 2 * PHYSICS_COLLISION_EVENT_STRIDE
|
|
1064
|
+
);
|
|
1065
|
+
let eventCount;
|
|
1066
|
+
for (; ; ) {
|
|
1067
|
+
try {
|
|
1068
|
+
eventCount = simulation.drainCollisionEvents(events);
|
|
1069
|
+
break;
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
if (!isSmallBufferError(error) || events.length >= maximumEventValues) throw error;
|
|
1072
|
+
events = new Uint32Array(Math.min(maximumEventValues, events.length * 2));
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
for (let index = 0; index < eventCount; index += 1) {
|
|
1076
|
+
const offset = index * PHYSICS_COLLISION_EVENT_STRIDE;
|
|
1077
|
+
const left = events[offset];
|
|
1078
|
+
const right = events[offset + 1];
|
|
1079
|
+
const started = events[offset + 2] === 1;
|
|
1080
|
+
if (left === void 0 || right === void 0)
|
|
1081
|
+
throw new Error("PhysicsSimulation returned a malformed collision event.");
|
|
1082
|
+
const leftArea = areas.get(left);
|
|
1083
|
+
const rightArea = areas.get(right);
|
|
1084
|
+
const leftBody = bodiesById.get(left);
|
|
1085
|
+
const rightBody = bodiesById.get(right);
|
|
1086
|
+
if (leftArea !== void 0 && rightBody !== void 0)
|
|
1087
|
+
leftArea.handleCollision(rightBody, started);
|
|
1088
|
+
if (rightArea !== void 0 && leftBody !== void 0)
|
|
1089
|
+
rightArea.handleCollision(leftBody, started);
|
|
1090
|
+
}
|
|
1091
|
+
if (simulation.areaIntersections !== void 0) {
|
|
1092
|
+
for (const area of areas.values()) {
|
|
1093
|
+
const current = /* @__PURE__ */ new Map();
|
|
1094
|
+
for (const bodyId of simulation.areaIntersections(area.body.id)) {
|
|
1095
|
+
const body = bodiesById.get(bodyId);
|
|
1096
|
+
if (body !== void 0) current.set(bodyId, body);
|
|
1097
|
+
}
|
|
1098
|
+
area.reconcileIntersections(current);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
kinematicMotions.clear();
|
|
1102
|
+
},
|
|
1103
|
+
sceneExit: () => {
|
|
1104
|
+
for (const area of [...areas.values()]) area.dispose();
|
|
1105
|
+
for (const body of [...bodies]) body.dispose();
|
|
1106
|
+
kinematicMotions.clear();
|
|
1107
|
+
},
|
|
1108
|
+
dispose: () => {
|
|
1109
|
+
for (const area of [...areas.values()]) area.dispose();
|
|
1110
|
+
for (const body of [...bodies]) body.dispose();
|
|
1111
|
+
simulation?.dispose();
|
|
1112
|
+
simulation = void 0;
|
|
1113
|
+
context = void 0;
|
|
1114
|
+
areas.clear();
|
|
1115
|
+
bodies.clear();
|
|
1116
|
+
bodiesById.clear();
|
|
1117
|
+
kinematicMotions.clear();
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
export { Area3D, CharacterBody3D, CollisionShape3D, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, RigidBody3D, interactionGroups, rapier };
|