@threenative/physics 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import * as RAPIER from '@dimforge/rapier3d-compat';
1
+ import * as rapier from '@dimforge/rapier3d-compat';
2
2
 
3
3
  // src/web.ts
4
4
 
@@ -18,8 +18,8 @@ function physicsHandle(raw) {
18
18
  function physicsWorldHandle(raw, simulation) {
19
19
  return { raw, simulation };
20
20
  }
21
- function physicsBodyHandle(id, raw) {
22
- return { id, raw };
21
+ function physicsBodyHandle(id, raw, entity) {
22
+ return { entity, id, raw };
23
23
  }
24
24
  function physicsColliderHandle(id, raw) {
25
25
  return { id, raw };
@@ -28,64 +28,178 @@ function physicsColliderHandle(id, raw) {
28
28
  // src/simulation.ts
29
29
  var PHYSICS_TRANSFORM_STRIDE = 8;
30
30
  var PHYSICS_COLLISION_EVENT_STRIDE = 4;
31
+ var PHYSICS_SLEEP_STATE_STRIDE = 2;
32
+ var MAX_PHYSICS_QUERY_RESULTS = 1024;
33
+ function requireFiniteVector(vector, label) {
34
+ if (typeof vector?.x !== "number" || typeof vector.y !== "number" || typeof vector.z !== "number" || !Number.isFinite(vector.x) || !Number.isFinite(vector.y) || !Number.isFinite(vector.z))
35
+ throw new Error(`TN_PHYSICS_NON_FINITE: ${label} must be a finite { x, y, z }.`);
36
+ }
31
37
  var selectedBackend;
32
38
  function installPhysicsSimulationBackend(backend) {
33
39
  selectedBackend = backend;
34
40
  }
35
41
  function physicsSimulationBackend() {
36
42
  if (selectedBackend === void 0)
37
- throw new Error("TN_PHYSICS_BACKEND_MISSING: no PhysicsSimulation backend was selected");
43
+ throw new Error("TN_PHYSICS_BACKEND_MISSING: no IPhysicsSimulation backend was selected");
38
44
  return selectedBackend;
39
45
  }
40
46
  function requirePhysicsStepInput(deltaTime, inputSnapshot, bodyExists) {
41
47
  if (!Number.isFinite(deltaTime) || deltaTime <= 0)
42
- throw new Error("PhysicsSimulation.step requires a positive finite deltaTime.");
48
+ throw new Error("IPhysicsSimulation.step requires a positive finite deltaTime.");
43
49
  if (inputSnapshot === void 0) return;
44
50
  if (!(inputSnapshot.kinematicTransforms instanceof Float32Array))
45
- throw new Error("PhysicsSimulation input must use a Float32Array.");
51
+ throw new Error("IPhysicsSimulation input must use a Float32Array.");
46
52
  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.");
53
+ throw new Error("IPhysicsSimulation input has an invalid kinematic record count.");
48
54
  }
49
55
  for (let index = 0; index < inputSnapshot.kinematicCount; index += 1) {
50
56
  const offset = index * PHYSICS_TRANSFORM_STRIDE;
51
57
  for (let scalar = 0; scalar < PHYSICS_TRANSFORM_STRIDE; scalar += 1) {
52
58
  if (!Number.isFinite(inputSnapshot.kinematicTransforms[offset + scalar]))
53
- throw new Error("PhysicsSimulation input contains a non-finite transform.");
59
+ throw new Error("IPhysicsSimulation input contains a non-finite transform.");
54
60
  }
55
61
  const id = inputSnapshot.kinematicTransforms[offset];
56
62
  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.");
63
+ throw new Error("IPhysicsSimulation input contains an invalid body id.");
64
+ if (!bodyExists(id)) throw new Error("IPhysicsSimulation input contains an unknown body id.");
59
65
  }
60
66
  }
61
67
  function requirePhysicsRenderBuffer(renderBuffer, bodyCount) {
62
68
  if (!(renderBuffer instanceof Float32Array))
63
- throw new Error("PhysicsSimulation output must use a Float32Array.");
69
+ throw new Error("IPhysicsSimulation output must use a Float32Array.");
64
70
  if (renderBuffer.length < bodyCount * PHYSICS_TRANSFORM_STRIDE)
65
- throw new Error("PhysicsSimulation output buffer is too small for visible transforms.");
71
+ throw new Error("IPhysicsSimulation output buffer is too small for visible transforms.");
72
+ }
73
+ function requirePhysicsSleepStateBuffer(buffer, bodyCount) {
74
+ if (!(buffer instanceof Float32Array))
75
+ throw new Error("IPhysicsSimulation sleep states must use a Float32Array.");
76
+ if (buffer.length < bodyCount * PHYSICS_SLEEP_STATE_STRIDE)
77
+ throw new Error("IPhysicsSimulation sleep state buffer is too small.");
66
78
  }
67
79
  function requirePhysicsEventBuffer(buffer) {
68
80
  if (!(buffer instanceof Uint32Array))
69
- throw new Error("PhysicsSimulation events must use a Uint32Array.");
81
+ throw new Error("IPhysicsSimulation events must use a Uint32Array.");
82
+ }
83
+ function requirePhysicsBodySensor(options) {
84
+ if (options.sensor !== options.shape.sensor)
85
+ throw new Error(
86
+ `TN_PHYSICS_SENSOR_CONFLICT: options.sensor (${options.sensor}) must match shape.sensor (${options.shape.sensor}).`
87
+ );
88
+ return options.sensor;
70
89
  }
71
- function createWebPhysicsShape(rapier2, shape) {
90
+ var QUERY_SHAPE_KINDS = /* @__PURE__ */ new Set([
91
+ "box",
92
+ "sphere",
93
+ "capsule",
94
+ "trimesh",
95
+ "convexHull",
96
+ "heightfield"
97
+ ]);
98
+ function queryObject(value, label) {
99
+ if (typeof value !== "object" || value === null)
100
+ throw new Error(`IPhysicsSimulation ${label} must be an object.`);
101
+ return value;
102
+ }
103
+ function queryVector(value, label) {
104
+ const object = queryObject(value, `${label} vector`);
105
+ const x = object.x;
106
+ const y = object.y;
107
+ const z = object.z;
108
+ if (typeof x !== "number" || typeof y !== "number" || typeof z !== "number" || !Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z))
109
+ throw new Error(`IPhysicsSimulation ${label} vector must contain finite x, y, and z values.`);
110
+ return { x, y, z };
111
+ }
112
+ function queryRotation(value) {
113
+ const object = queryObject(value, "shape rotation");
114
+ const x = object.x;
115
+ const y = object.y;
116
+ const z = object.z;
117
+ const w = object.w;
118
+ if (typeof x !== "number" || typeof y !== "number" || typeof z !== "number" || typeof w !== "number" || !Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z) || !Number.isFinite(w))
119
+ throw new Error("IPhysicsSimulation shape rotation must contain finite x, y, z, and w values.");
120
+ const lengthSquared = x * x + y * y + z * z + w * w;
121
+ if (lengthSquared <= Number.EPSILON)
122
+ throw new Error("IPhysicsSimulation shape rotation must not have zero length.");
123
+ return { w, x, y, z };
124
+ }
125
+ function requirePhysicsCollisionMask(value) {
126
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value > 65535)
127
+ throw new Error("IPhysicsSimulation collisionMask must be an integer from 0 through 65535.");
128
+ return value;
129
+ }
130
+ function requirePhysicsMaxResults(value) {
131
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1 || value > MAX_PHYSICS_QUERY_RESULTS)
132
+ throw new Error(
133
+ `IPhysicsSimulation maxResults must be an integer from 1 through ${MAX_PHYSICS_QUERY_RESULTS}.`
134
+ );
135
+ return value;
136
+ }
137
+ function queryShape(value) {
138
+ const shape = queryObject(value, "query shape");
139
+ const kind = shape.kind;
140
+ if (typeof kind !== "string" || !QUERY_SHAPE_KINDS.has(kind))
141
+ throw new Error("IPhysicsSimulation query shape has an unknown kind.");
142
+ const x = shape.x;
143
+ const y = shape.y;
144
+ const z = shape.z;
145
+ if (typeof x !== "number" || typeof y !== "number" || typeof z !== "number" || !Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z))
146
+ throw new Error("IPhysicsSimulation query shape dimensions must be finite.");
147
+ if (kind === "box" && (x <= 0 || y <= 0 || z <= 0))
148
+ throw new Error("IPhysicsSimulation query box dimensions must be positive.");
149
+ if (kind === "sphere" && x <= 0)
150
+ throw new Error("IPhysicsSimulation query sphere radius must be positive.");
151
+ if (kind === "capsule" && (x < 0 || y <= 0))
152
+ throw new Error("IPhysicsSimulation query capsule dimensions are invalid.");
153
+ return shape;
154
+ }
155
+ function requirePhysicsRayQuery(value) {
156
+ const query = queryObject(value, "ray query");
157
+ const from = queryVector(query.from, "ray from");
158
+ const to = queryVector(query.to, "ray to");
159
+ if (from.x === to.x && from.y === to.y && from.z === to.z)
160
+ throw new Error("IPhysicsSimulation ray must have non-zero length.");
161
+ return {
162
+ collisionMask: requirePhysicsCollisionMask(query.collisionMask),
163
+ from,
164
+ to
165
+ };
166
+ }
167
+ function requirePhysicsShapeQuery(value) {
168
+ const query = queryObject(value, "shape query");
169
+ return {
170
+ collisionMask: requirePhysicsCollisionMask(query.collisionMask),
171
+ maxResults: requirePhysicsMaxResults(query.maxResults),
172
+ position: queryVector(query.position, "shape position"),
173
+ rotation: queryRotation(query.rotation),
174
+ shape: queryShape(query.shape)
175
+ };
176
+ }
177
+ function requirePhysicsPointQuery(value) {
178
+ const query = queryObject(value, "point query");
179
+ return {
180
+ collisionMask: requirePhysicsCollisionMask(query.collisionMask),
181
+ maxResults: requirePhysicsMaxResults(query.maxResults),
182
+ position: queryVector(query.position, "point position")
183
+ };
184
+ }
185
+ function createWebPhysicsShape(rapier3, shape, sensor = shape.sensor) {
72
186
  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);
187
+ if (shape.kind === "box") descriptor = rapier3.ColliderDesc.cuboid(shape.x, shape.y, shape.z);
188
+ else if (shape.kind === "sphere") descriptor = rapier3.ColliderDesc.ball(shape.x);
189
+ else if (shape.kind === "capsule") descriptor = rapier3.ColliderDesc.capsule(shape.x, shape.y);
76
190
  else if (shape.kind === "trimesh") {
77
191
  if (shape.vertices === void 0 || shape.indices === void 0)
78
192
  throw new Error("CollisionShape3D.trimesh is missing mesh data.");
79
- descriptor = rapier2.ColliderDesc.trimesh(shape.vertices, shape.indices);
193
+ descriptor = rapier3.ColliderDesc.trimesh(shape.vertices, shape.indices);
80
194
  } else if (shape.kind === "convexHull") {
81
195
  if (shape.vertices === void 0)
82
196
  throw new Error("CollisionShape3D.convexHull is missing vertices.");
83
- descriptor = rapier2.ColliderDesc.convexHull(shape.vertices);
197
+ descriptor = rapier3.ColliderDesc.convexHull(shape.vertices);
84
198
  if (descriptor === null) throw new Error("CollisionShape3D could not build a convex hull.");
85
199
  } else {
86
200
  if (shape.rows === void 0 || shape.columns === void 0 || shape.heights === void 0 || shape.scale === void 0)
87
201
  throw new Error("CollisionShape3D.heightfield is missing height data.");
88
- descriptor = rapier2.ColliderDesc.heightfield(
202
+ descriptor = rapier3.ColliderDesc.heightfield(
89
203
  shape.rows - 1,
90
204
  shape.columns - 1,
91
205
  shape.heights,
@@ -93,12 +207,12 @@ function createWebPhysicsShape(rapier2, shape) {
93
207
  );
94
208
  }
95
209
  descriptor.setCollisionGroups(interactionGroups(shape.collisionLayer, shape.collisionMask));
96
- descriptor.setSensor(shape.sensor);
97
- descriptor.setActiveEvents(rapier2.ActiveEvents.COLLISION_EVENTS);
210
+ descriptor.setSensor(sensor);
211
+ descriptor.setActiveEvents(rapier3.ActiveEvents.COLLISION_EVENTS);
98
212
  return descriptor;
99
213
  }
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();
214
+ function bodyDescription(rapier3, type, position, rotation, mass) {
215
+ const description = type === "fixed" ? rapier3.RigidBodyDesc.fixed() : type === "kinematic" || type === "character" ? rapier3.RigidBodyDesc.kinematicPositionBased() : rapier3.RigidBodyDesc.dynamic();
102
216
  description.setTranslation(position.x, position.y, position.z).setRotation({ x: rotation.x, y: rotation.y, z: rotation.z, w: rotation.w });
103
217
  if (mass !== 0) description.setAdditionalMass(mass);
104
218
  return description;
@@ -123,23 +237,50 @@ function characterState(simulationBody, byCollider) {
123
237
  function createWebPhysicsSimulation(options) {
124
238
  const bodies = /* @__PURE__ */ new Map();
125
239
  const byCollider = /* @__PURE__ */ new Map();
240
+ const dirtyBodies = /* @__PURE__ */ new Set();
126
241
  const pendingCollisionEvents = [];
127
242
  let nextId = 0;
128
243
  let disposed = false;
129
244
  const requireLive = () => {
130
245
  if (disposed) throw new Error("Physics simulation is disposed.");
131
246
  };
247
+ const requireDynamic = (entry, id, operation) => {
248
+ if (entry === void 0)
249
+ throw new Error(`TN_PHYSICS_UNKNOWN_BODY: ${operation} references an unknown body ${id}.`);
250
+ if (entry.type !== "dynamic")
251
+ throw new Error(
252
+ `TN_PHYSICS_NOT_DYNAMIC: ${operation} needs a dynamic body; body ${id} is '${entry.type}'.`
253
+ );
254
+ return entry;
255
+ };
256
+ const queryPredicate = (collisionMask) => (collider) => {
257
+ const body = byCollider.get(collider.handle);
258
+ return body !== void 0 && !dirtyBodies.has(body) && !collider.isSensor() && (collider.collisionGroups() >>> 16 & collisionMask) !== 0;
259
+ };
260
+ const queryMatches = (collisionMask, collider) => {
261
+ const body = byCollider.get(collider.handle);
262
+ return body !== void 0 && !collider.isSensor() && (collider.collisionGroups() >>> 16 & collisionMask) !== 0;
263
+ };
264
+ const queryHit = (entry) => {
265
+ const position = entry.body.translation();
266
+ return {
267
+ body: physicsBodyHandle(entry.id, entry.body, entry.entity),
268
+ entity: entry.entity,
269
+ position: { x: position.x, y: position.y, z: position.z }
270
+ };
271
+ };
132
272
  const simulation = {
133
273
  version: options.version,
134
274
  rawWorld: options.world,
135
275
  rawEventQueue: options.eventQueue,
136
276
  createBody: (bodyOptions) => {
137
277
  requireLive();
278
+ const sensor = requirePhysicsBodySensor(bodyOptions);
138
279
  if (!Number.isFinite(bodyOptions.mass) || bodyOptions.mass < 0)
139
280
  throw new Error("Physics body mass must be a finite non-negative number.");
140
281
  const id = nextId;
141
282
  nextId += 1;
142
- const rawShape = createWebPhysicsShape(options.rapier, bodyOptions.shape);
283
+ const rawShape = createWebPhysicsShape(options.rapier, bodyOptions.shape, sensor);
143
284
  const rawBody = options.world.createRigidBody(
144
285
  bodyDescription(
145
286
  options.rapier,
@@ -153,6 +294,7 @@ function createWebPhysicsSimulation(options) {
153
294
  const entry = {
154
295
  body: rawBody,
155
296
  collider: rawCollider,
297
+ entity: bodyOptions.entity,
156
298
  id,
157
299
  type: bodyOptions.type
158
300
  };
@@ -162,8 +304,9 @@ function createWebPhysicsSimulation(options) {
162
304
  }
163
305
  bodies.set(id, entry);
164
306
  byCollider.set(rawCollider.handle, entry);
307
+ dirtyBodies.add(entry);
165
308
  return {
166
- body: physicsBodyHandle(id, rawBody),
309
+ body: physicsBodyHandle(id, rawBody, bodyOptions.entity),
167
310
  collider: physicsColliderHandle(id, rawCollider),
168
311
  controller: entry.controllerHandle,
169
312
  rawShape
@@ -191,6 +334,9 @@ function createWebPhysicsSimulation(options) {
191
334
  }
192
335
  if (characterOptions.snapToGround !== void 0)
193
336
  entry.controller.enableSnapToGround(characterOptions.snapToGround);
337
+ entry.controller.setApplyImpulsesToDynamicBodies(
338
+ characterOptions.pushesDynamicBodies === true
339
+ );
194
340
  },
195
341
  removeBody: (id) => {
196
342
  requireLive();
@@ -198,6 +344,7 @@ function createWebPhysicsSimulation(options) {
198
344
  if (entry === void 0) return;
199
345
  bodies.delete(id);
200
346
  byCollider.delete(entry.collider.handle);
347
+ dirtyBodies.delete(entry);
201
348
  if (entry.controller !== void 0) options.world.removeCharacterController(entry.controller);
202
349
  if (entry.body.isValid()) options.world.removeRigidBody(entry.body);
203
350
  },
@@ -207,6 +354,28 @@ function createWebPhysicsSimulation(options) {
207
354
  if (entry === void 0)
208
355
  throw new Error("Physics body transform references an unknown body.");
209
356
  entry.body.setTranslation(position, true);
357
+ options.world.propagateModifiedBodyPositionsToColliders();
358
+ dirtyBodies.add(entry);
359
+ },
360
+ applyBodyImpulse: (id, impulse) => {
361
+ requireLive();
362
+ requireFiniteVector(impulse, "impulse");
363
+ requireDynamic(bodies.get(id), id, "applyImpulse").body.applyImpulse(impulse, true);
364
+ },
365
+ applyBodyForce: (id, force) => {
366
+ requireLive();
367
+ requireFiniteVector(force, "force");
368
+ requireDynamic(bodies.get(id), id, "applyForce").body.addForce(force, true);
369
+ },
370
+ setBodyLinearVelocity: (id, velocity) => {
371
+ requireLive();
372
+ requireFiniteVector(velocity, "velocity");
373
+ requireDynamic(bodies.get(id), id, "linearVelocity").body.setLinvel(velocity, true);
374
+ },
375
+ readBodyLinearVelocity: (id) => {
376
+ requireLive();
377
+ const { x, y, z } = requireDynamic(bodies.get(id), id, "linearVelocity").body.linvel();
378
+ return { x, y, z };
210
379
  },
211
380
  step: (deltaTime, inputSnapshot) => {
212
381
  requireLive();
@@ -216,7 +385,7 @@ function createWebPhysicsSimulation(options) {
216
385
  const offset = index * PHYSICS_TRANSFORM_STRIDE;
217
386
  const id = inputSnapshot.kinematicTransforms[offset];
218
387
  const entry = bodies.get(id);
219
- if (entry === void 0) throw new Error("PhysicsSimulation input body disappeared.");
388
+ if (entry === void 0) throw new Error("IPhysicsSimulation input body disappeared.");
220
389
  const target = {
221
390
  x: inputSnapshot.kinematicTransforms[offset + 1],
222
391
  y: inputSnapshot.kinematicTransforms[offset + 2],
@@ -239,7 +408,11 @@ function createWebPhysicsSimulation(options) {
239
408
  y: target.y - current.y,
240
409
  z: target.z - current.z
241
410
  };
242
- const filterGroups = config.oneWayLayers !== 0 && desired.y > 0 ? interactionGroups(65535, 65535 ^ config.oneWayLayers) : void 0;
411
+ const characterGroups = entry.collider.collisionGroups();
412
+ const filterGroups = config.oneWayLayers !== 0 && desired.y > 0 ? interactionGroups(
413
+ characterGroups >>> 16,
414
+ characterGroups & 65535 & (65535 ^ config.oneWayLayers)
415
+ ) : characterGroups;
243
416
  const filterPredicate = config.oneWayLayers !== 0 && desired.y > 0 ? (collider) => (collider.collisionGroups() >>> 16 & config.oneWayLayers) === 0 : void 0;
244
417
  controller.computeColliderMovement(
245
418
  entry.collider,
@@ -256,7 +429,7 @@ function createWebPhysicsSimulation(options) {
256
429
  });
257
430
  } else {
258
431
  if (!entry.body.isKinematic())
259
- throw new Error("PhysicsSimulation received kinematic input for a dynamic body.");
432
+ throw new Error("IPhysicsSimulation received kinematic input for a dynamic body.");
260
433
  entry.body.setNextKinematicTranslation(target);
261
434
  }
262
435
  entry.body.setNextKinematicRotation(rotation);
@@ -264,6 +437,7 @@ function createWebPhysicsSimulation(options) {
264
437
  }
265
438
  options.world.timestep = deltaTime;
266
439
  options.world.step(options.eventQueue);
440
+ dirtyBodies.clear();
267
441
  },
268
442
  readVisibleTransforms: (renderBuffer) => {
269
443
  requireLive();
@@ -286,6 +460,117 @@ function createWebPhysicsSimulation(options) {
286
460
  }
287
461
  return index;
288
462
  },
463
+ readBodySleepStates: (buffer) => {
464
+ requireLive();
465
+ requirePhysicsSleepStateBuffer(buffer, bodies.size);
466
+ let index = 0;
467
+ for (const entry of bodies.values()) {
468
+ if (!entry.body.isValid()) continue;
469
+ const offset = index * PHYSICS_SLEEP_STATE_STRIDE;
470
+ buffer[offset] = entry.id;
471
+ buffer[offset + 1] = entry.body.isSleeping() ? 1 : 0;
472
+ index += 1;
473
+ }
474
+ return index;
475
+ },
476
+ intersectRay: (value) => {
477
+ requireLive();
478
+ const query = requirePhysicsRayQuery(value);
479
+ const dx = query.to.x - query.from.x;
480
+ const dy = query.to.y - query.from.y;
481
+ const dz = query.to.z - query.from.z;
482
+ const distance = Math.hypot(dx, dy, dz);
483
+ const ray = new options.rapier.Ray(query.from, {
484
+ x: dx / distance,
485
+ y: dy / distance,
486
+ z: dz / distance
487
+ });
488
+ const hit = options.world.castRayAndGetNormal(
489
+ ray,
490
+ distance,
491
+ true,
492
+ options.rapier.QueryFilterFlags.EXCLUDE_SENSORS,
493
+ void 0,
494
+ void 0,
495
+ void 0,
496
+ queryPredicate(query.collisionMask)
497
+ );
498
+ let closestCollider = hit?.collider;
499
+ let closestTime = hit?.timeOfImpact;
500
+ let closestNormal = hit?.normal;
501
+ for (const dirtyBody of dirtyBodies) {
502
+ if (!queryMatches(query.collisionMask, dirtyBody.collider)) continue;
503
+ const dirtyHit = dirtyBody.collider.castRayAndGetNormal(ray, distance, true);
504
+ if (dirtyHit === null || closestTime !== void 0 && dirtyHit.timeOfImpact >= closestTime)
505
+ continue;
506
+ closestCollider = dirtyBody.collider;
507
+ closestTime = dirtyHit.timeOfImpact;
508
+ closestNormal = dirtyHit.normal;
509
+ }
510
+ if (closestCollider === void 0 || closestTime === void 0 || closestNormal === void 0)
511
+ return void 0;
512
+ const entry = byCollider.get(closestCollider.handle);
513
+ if (entry === void 0)
514
+ throw new Error("IPhysicsSimulation query returned an unknown body.");
515
+ const position = ray.pointAt(closestTime);
516
+ return {
517
+ ...queryHit(entry),
518
+ distance: closestTime,
519
+ normal: { x: closestNormal.x, y: closestNormal.y, z: closestNormal.z },
520
+ position: { x: position.x, y: position.y, z: position.z }
521
+ };
522
+ },
523
+ intersectShape: (value) => {
524
+ requireLive();
525
+ const query = requirePhysicsShapeQuery(value);
526
+ const rawShape = createWebPhysicsShape(options.rapier, query.shape, false).shape;
527
+ const hits = [];
528
+ options.world.intersectionsWithShape(
529
+ query.position,
530
+ query.rotation,
531
+ rawShape,
532
+ (collider) => {
533
+ const entry = byCollider.get(collider.handle);
534
+ if (entry !== void 0 && queryPredicate(query.collisionMask)(collider))
535
+ hits.push(queryHit(entry));
536
+ return hits.length < query.maxResults;
537
+ },
538
+ options.rapier.QueryFilterFlags.EXCLUDE_SENSORS,
539
+ void 0,
540
+ void 0,
541
+ void 0,
542
+ queryPredicate(query.collisionMask)
543
+ );
544
+ for (const dirtyBody of dirtyBodies) {
545
+ if (hits.length < query.maxResults && queryMatches(query.collisionMask, dirtyBody.collider) && dirtyBody.collider.intersectsShape(rawShape, query.position, query.rotation))
546
+ hits.push(queryHit(dirtyBody));
547
+ }
548
+ return hits;
549
+ },
550
+ intersectPoint: (value) => {
551
+ requireLive();
552
+ const query = requirePhysicsPointQuery(value);
553
+ const hits = [];
554
+ options.world.intersectionsWithPoint(
555
+ query.position,
556
+ (collider) => {
557
+ const entry = byCollider.get(collider.handle);
558
+ if (entry !== void 0 && queryPredicate(query.collisionMask)(collider))
559
+ hits.push(queryHit(entry));
560
+ return hits.length < query.maxResults;
561
+ },
562
+ options.rapier.QueryFilterFlags.EXCLUDE_SENSORS,
563
+ void 0,
564
+ void 0,
565
+ void 0,
566
+ queryPredicate(query.collisionMask)
567
+ );
568
+ for (const dirtyBody of dirtyBodies) {
569
+ if (hits.length < query.maxResults && queryMatches(query.collisionMask, dirtyBody.collider) && dirtyBody.collider.containsPoint(query.position))
570
+ hits.push(queryHit(dirtyBody));
571
+ }
572
+ return hits;
573
+ },
289
574
  readBodyTransform: (id) => {
290
575
  requireLive();
291
576
  const entry = bodies.get(id);
@@ -331,7 +616,7 @@ function createWebPhysicsSimulation(options) {
331
616
  pendingCollisionEvents.push([left, right, Number(started), 1]);
332
617
  });
333
618
  if (buffer.length < pendingCollisionEvents.length * PHYSICS_COLLISION_EVENT_STRIDE)
334
- throw new Error("PhysicsSimulation collision event buffer is too small.");
619
+ throw new Error("IPhysicsSimulation collision event buffer is too small.");
335
620
  pendingCollisionEvents.forEach(
336
621
  (event, index) => buffer.set(event, index * PHYSICS_COLLISION_EVENT_STRIDE)
337
622
  );
@@ -349,6 +634,7 @@ function createWebPhysicsSimulation(options) {
349
634
  }
350
635
  bodies.clear();
351
636
  byCollider.clear();
637
+ dirtyBodies.clear();
352
638
  pendingCollisionEvents.length = 0;
353
639
  options.eventQueue.free();
354
640
  options.world.free();
@@ -365,24 +651,40 @@ function requirePhysicsSimulation(physics, world) {
365
651
  if (world !== void 0 && backend?.simulationForWorld !== void 0)
366
652
  return backend.simulationForWorld(candidate);
367
653
  throw new Error(
368
- "Physics nodes require a PhysicsContext. Passing a raw backend world is deprecated and backend-specific."
654
+ "Physics nodes require an IPhysicsContext. Passing a raw backend world is deprecated and backend-specific."
369
655
  );
370
656
  }
371
657
 
372
658
  // src/web.ts
373
659
  var initialized;
374
660
  var simulations = /* @__PURE__ */ new WeakMap();
661
+ var RAPIER_INIT_WARNING = "using deprecated parameters for the initialization function; pass a single object instead";
662
+ function initializeRapier() {
663
+ const previousWarn = console.warn;
664
+ console.warn = (...args) => {
665
+ if (args[0] === RAPIER_INIT_WARNING) return;
666
+ previousWarn(...args);
667
+ };
668
+ try {
669
+ return rapier.init().finally(() => {
670
+ console.warn = previousWarn;
671
+ });
672
+ } catch (error) {
673
+ console.warn = previousWarn;
674
+ throw error;
675
+ }
676
+ }
375
677
  installPhysicsSimulationBackend({
376
678
  initialize: () => {
377
- initialized ??= RAPIER.init();
679
+ initialized ??= initializeRapier();
378
680
  return initialized;
379
681
  },
380
682
  createSimulation: (options = {}) => {
381
- const world = new RAPIER.World(options.gravity ?? { x: 0, y: -9.81, z: 0 });
683
+ const world = new rapier.World(options.gravity ?? { x: 0, y: -9.81, z: 0 });
382
684
  const simulation = createWebPhysicsSimulation({
383
- eventQueue: new RAPIER.EventQueue(true),
384
- rapier: RAPIER,
385
- version: RAPIER.version(),
685
+ eventQueue: new rapier.EventQueue(true),
686
+ rapier,
687
+ version: rapier.version(),
386
688
  world
387
689
  });
388
690
  simulations.set(world, simulation);
@@ -394,15 +696,15 @@ installPhysicsSimulationBackend({
394
696
  const simulation = simulations.get(world);
395
697
  if (simulation !== void 0) return simulation;
396
698
  const created = createWebPhysicsSimulation({
397
- eventQueue: new RAPIER.EventQueue(true),
398
- rapier: RAPIER,
399
- version: RAPIER.version(),
699
+ eventQueue: new rapier.EventQueue(true),
700
+ rapier,
701
+ version: rapier.version(),
400
702
  world
401
703
  });
402
704
  simulations.set(world, created);
403
705
  return created;
404
706
  },
405
- createShape: (shape) => createWebPhysicsShape(RAPIER, shape)
707
+ createShape: (shape) => createWebPhysicsShape(rapier, shape)
406
708
  });
407
709
 
408
710
  // src/Area3D.ts
@@ -410,7 +712,7 @@ var MAX_CONTACT_LOG = 1e3;
410
712
  function finiteTransform(values, offset) {
411
713
  const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
412
714
  if (result.some((value) => value === void 0 || !Number.isFinite(value)))
413
- throw new Error("PhysicsSimulation returned a malformed transform.");
715
+ throw new Error("IPhysicsSimulation returned a malformed transform.");
414
716
  return result;
415
717
  }
416
718
  var Area3D = class {
@@ -441,6 +743,7 @@ var Area3D = class {
441
743
  }
442
744
  const registration = this.#simulation.createBody({
443
745
  mass: 0,
746
+ entity: this.entity,
444
747
  position: this.#position,
445
748
  rotation: { w: 1, x: 0, y: 0, z: 0 },
446
749
  sensor: true,
@@ -527,7 +830,7 @@ var Area3D = class {
527
830
  function finiteTransform2(values, offset) {
528
831
  const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
529
832
  if (result.some((value) => value === void 0 || !Number.isFinite(value)))
530
- throw new Error("PhysicsSimulation returned a malformed transform.");
833
+ throw new Error("IPhysicsSimulation returned a malformed transform.");
531
834
  return result;
532
835
  }
533
836
  var CharacterBody3D = class {
@@ -536,6 +839,7 @@ var CharacterBody3D = class {
536
839
  controller;
537
840
  object;
538
841
  velocity;
842
+ /** Signed vertical acceleration; see `ICharacterBody3DOptions.gravity`. Down is negative. */
539
843
  gravity;
540
844
  maxFallSpeed;
541
845
  oneWayLayers;
@@ -563,10 +867,11 @@ var CharacterBody3D = class {
563
867
  options.shape.setCollisionGroups(interactionGroups(layer, mask));
564
868
  }
565
869
  const registration = this.#simulation.createBody({
870
+ entity: options.entity,
566
871
  mass: 0,
567
872
  position: this.object.position,
568
873
  rotation: this.object.quaternion,
569
- sensor: false,
874
+ sensor: shape.sensor,
570
875
  shape,
571
876
  type: "character"
572
877
  });
@@ -587,6 +892,7 @@ var CharacterBody3D = class {
587
892
  maxSlopeClimbAngle: options.maxSlopeClimbAngle ?? Math.PI / 4,
588
893
  offset: options.offset ?? 0.01,
589
894
  oneWayLayers: this.oneWayLayers,
895
+ pushesDynamicBodies: options.pushesDynamicBodies ?? false,
590
896
  snapToGround: options.snapToGround
591
897
  };
592
898
  try {
@@ -714,11 +1020,11 @@ var CollisionShape3D = class _CollisionShape3D {
714
1020
  constructor(descriptor) {
715
1021
  this.#descriptor = descriptor;
716
1022
  }
717
- /** Backend-neutral data consumed by the selected PhysicsSimulation adapter. */
1023
+ /** Backend-neutral data consumed by the selected IPhysicsSimulation adapter. */
718
1024
  get descriptor() {
719
1025
  return this.#descriptor;
720
1026
  }
721
- /** Rapier's descriptor on web, or an opaque native descriptor after registration. */
1027
+ /** Backend-specific escape hatch: Rapier's descriptor on web, or an opaque native handle. */
722
1028
  get raw() {
723
1029
  if (this.#backendRaw === void 0) {
724
1030
  try {
@@ -761,6 +1067,20 @@ var CollisionShape3D = class _CollisionShape3D {
761
1067
  z: 0
762
1068
  });
763
1069
  }
1070
+ /**
1071
+ * A capsule of total height `2 * (halfHeight + radius)`, **centred on the body's origin** like
1072
+ * every other shape here — `halfHeight` is the straight section's half-length, measured from
1073
+ * that centre, and the hemispherical cap adds `radius` beyond it.
1074
+ *
1075
+ * So the body origin sits at the character's waist, not at its feet. A visual rig modelled
1076
+ * standing on its own origin, parented straight onto the body object, therefore floats exactly
1077
+ * `halfHeight + radius` above every surface it lands on. Offset the rig down by that amount:
1078
+ *
1079
+ * ```ts
1080
+ * const shape = CollisionShape3D.capsule(0.26, 0.28);
1081
+ * rig.position.y = -(0.26 + 0.28); // feet reach the capsule's bottom cap
1082
+ * ```
1083
+ */
764
1084
  static capsule(halfHeight, radius) {
765
1085
  if (!Number.isFinite(halfHeight) || halfHeight < 0)
766
1086
  throw new Error("CollisionShape3D.capsule requires a finite non-negative halfHeight.");
@@ -859,11 +1179,53 @@ var CollisionShape3D = class _CollisionShape3D {
859
1179
  }
860
1180
  };
861
1181
 
1182
+ // src/PhysicsDirectSpaceState3D.ts
1183
+ function rayQuery(options) {
1184
+ return requirePhysicsRayQuery({
1185
+ collisionMask: options.collisionMask === void 0 ? 65535 : options.collisionMask,
1186
+ from: options.from,
1187
+ to: options.to
1188
+ });
1189
+ }
1190
+ function shapeQuery(options) {
1191
+ if (!(options.shape instanceof CollisionShape3D))
1192
+ throw new Error("PhysicsDirectSpaceState3D.intersectShape requires a CollisionShape3D.");
1193
+ return requirePhysicsShapeQuery({
1194
+ collisionMask: options.collisionMask === void 0 ? 65535 : options.collisionMask,
1195
+ maxResults: options.maxResults === void 0 ? 16 : options.maxResults,
1196
+ position: options.position,
1197
+ rotation: options.rotation === void 0 ? { w: 1, x: 0, y: 0, z: 0 } : options.rotation,
1198
+ shape: options.shape.descriptor
1199
+ });
1200
+ }
1201
+ function pointQuery(options) {
1202
+ return requirePhysicsPointQuery({
1203
+ collisionMask: options.collisionMask === void 0 ? 65535 : options.collisionMask,
1204
+ maxResults: options.maxResults === void 0 ? 16 : options.maxResults,
1205
+ position: options.position
1206
+ });
1207
+ }
1208
+ var PhysicsDirectSpaceState3D = class {
1209
+ #simulation;
1210
+ constructor(simulation) {
1211
+ this.#simulation = simulation;
1212
+ }
1213
+ intersectRay(options) {
1214
+ return this.#simulation.intersectRay(rayQuery(options));
1215
+ }
1216
+ intersectShape(options) {
1217
+ return this.#simulation.intersectShape(shapeQuery(options));
1218
+ }
1219
+ intersectPoint(options) {
1220
+ return this.#simulation.intersectPoint(pointQuery(options));
1221
+ }
1222
+ };
1223
+
862
1224
  // src/RigidBody3D.ts
863
1225
  function finiteTransform3(values, offset) {
864
1226
  const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
865
1227
  if (result.some((value) => value === void 0 || !Number.isFinite(value)))
866
- throw new Error("PhysicsSimulation returned a malformed transform.");
1228
+ throw new Error("IPhysicsSimulation returned a malformed transform.");
867
1229
  return result;
868
1230
  }
869
1231
  var RigidBody3D = class {
@@ -887,10 +1249,11 @@ var RigidBody3D = class {
887
1249
  options.shape.setCollisionGroups(interactionGroups(layer, mask));
888
1250
  }
889
1251
  const registration = this.#simulation.createBody({
1252
+ entity: options.entity,
890
1253
  mass: options.mass ?? 0,
891
1254
  position: this.object.position,
892
1255
  rotation: this.object.quaternion,
893
- sensor: false,
1256
+ sensor: shape.sensor,
894
1257
  shape,
895
1258
  type: this.type
896
1259
  });
@@ -931,6 +1294,34 @@ var RigidBody3D = class {
931
1294
  }
932
1295
  syncToPhysics() {
933
1296
  }
1297
+ /**
1298
+ * Godot's `apply_impulse`. The one-shot shove: a thrown crate, a jump pad, a hit reaction.
1299
+ *
1300
+ * These four members exist because there is otherwise no portable way to move a dynamic body
1301
+ * at all. `body.raw` is a Rapier object on web and opaque on native, so reaching through it
1302
+ * forks the game by platform, and a transform write is discarded by the next step.
1303
+ */
1304
+ applyImpulse(impulse) {
1305
+ this.#requireLive("applyImpulse");
1306
+ this.#simulation.applyBodyImpulse(this.body.id, impulse);
1307
+ }
1308
+ /** Godot's `apply_force`. Continuous push; cleared by the backend each step. */
1309
+ applyForce(force) {
1310
+ this.#requireLive("applyForce");
1311
+ this.#simulation.applyBodyForce(this.body.id, force);
1312
+ }
1313
+ /** Godot's `linear_velocity`. */
1314
+ get linearVelocity() {
1315
+ this.#requireLive("linearVelocity");
1316
+ return this.#simulation.readBodyLinearVelocity(this.body.id);
1317
+ }
1318
+ set linearVelocity(velocity) {
1319
+ this.#requireLive("linearVelocity");
1320
+ this.#simulation.setBodyLinearVelocity(this.body.id, velocity);
1321
+ }
1322
+ #requireLive(operation) {
1323
+ if (this.#disposed) throw new Error(`RigidBody3D.${operation} cannot be used after dispose.`);
1324
+ }
934
1325
  syncFromPhysics() {
935
1326
  const transform = this.#simulation.readBodyTransform?.(this.body.id);
936
1327
  if (transform === void 0) return;
@@ -958,6 +1349,8 @@ var RigidBody3D = class {
958
1349
  };
959
1350
 
960
1351
  // src/plugin.ts
1352
+ var PHYSICS_DEBUG_BODY_LIMIT = 100;
1353
+ var PHYSICS_DEBUG_SAMPLE_LIMIT = 100;
961
1354
  function growFloat(buffer, records) {
962
1355
  if (buffer.length >= records * PHYSICS_TRANSFORM_STRIDE) return buffer;
963
1356
  return new Float32Array(
@@ -976,10 +1369,10 @@ function isSmallBufferError(error) {
976
1369
  function visibleId(buffer, offset) {
977
1370
  const value = buffer[offset];
978
1371
  if (value === void 0 || !Number.isInteger(value) || value < 0)
979
- throw new Error("PhysicsSimulation returned an invalid visible body id.");
1372
+ throw new Error("IPhysicsSimulation returned an invalid visible body id.");
980
1373
  return value;
981
1374
  }
982
- function rapier(options = {}) {
1375
+ function rapier2(options = {}) {
983
1376
  const backend = physicsSimulationBackend();
984
1377
  let simulation;
985
1378
  let context;
@@ -989,32 +1382,51 @@ function rapier(options = {}) {
989
1382
  const kinematicMotions = /* @__PURE__ */ new Map();
990
1383
  let kinematic = new Float32Array(PHYSICS_TRANSFORM_STRIDE * 16);
991
1384
  let visible = new Float32Array(PHYSICS_TRANSFORM_STRIDE * 16);
1385
+ let visibleCount = 0;
1386
+ let sleepStates = new Float32Array(
1387
+ PHYSICS_SLEEP_STATE_STRIDE * 16
1388
+ );
992
1389
  let events = new Uint32Array(64);
1390
+ const activeContacts = /* @__PURE__ */ new Map();
1391
+ let debugSeries = [];
1392
+ let unregisterObservations;
1393
+ function buildContext(selected) {
1394
+ return {
1395
+ add: (body) => {
1396
+ bodies.add(body);
1397
+ bodiesById.set(body.body.id, body);
1398
+ },
1399
+ addArea: (area) => areas.set(area.body.id, area),
1400
+ eventQueue: physicsHandle(selected.rawEventQueue),
1401
+ kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
1402
+ numBodies: () => bodies.size,
1403
+ remove: (body) => {
1404
+ bodies.delete(body);
1405
+ bodiesById.delete(body.body.id);
1406
+ removeContactsFor(body.body.id);
1407
+ },
1408
+ removeArea: (area) => {
1409
+ areas.delete(area.body.id);
1410
+ removeContactsFor(area.body.id);
1411
+ },
1412
+ directSpaceState: new PhysicsDirectSpaceState3D(selected),
1413
+ simulation: selected,
1414
+ world: physicsWorldHandle(selected.rawWorld, selected)
1415
+ };
1416
+ }
993
1417
  return {
994
1418
  setup: async (ctx, runtime) => {
995
1419
  await backend.initialize();
996
1420
  const selected = backend.createSimulation(options);
997
1421
  simulation = selected;
998
1422
  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
- };
1423
+ context = buildContext(selected);
1016
1424
  ctx.physics = context;
1017
- return void 0;
1425
+ unregisterObservations = runtime?.observations?.contribute({
1426
+ capabilities: ["runtime.physics"],
1427
+ sample: (request) => physicsObservations(ctx, runtime, request)
1428
+ });
1429
+ return unregisterObservations;
1018
1430
  },
1019
1431
  update: (_ctx, dt) => {
1020
1432
  if (simulation === void 0) throw new Error("Physics plugin updated before setup.");
@@ -1044,7 +1456,7 @@ function rapier(options = {}) {
1044
1456
  };
1045
1457
  simulation.step(dt, input);
1046
1458
  visible = growFloat(visible, bodies.size + areas.size);
1047
- const visibleCount = simulation.readVisibleTransforms(visible);
1459
+ visibleCount = simulation.readVisibleTransforms(visible);
1048
1460
  for (let index = 0; index < visibleCount; index += 1) {
1049
1461
  const offset = index * PHYSICS_TRANSFORM_STRIDE;
1050
1462
  const id = visibleId(visible, offset);
@@ -1053,7 +1465,7 @@ function rapier(options = {}) {
1053
1465
  else {
1054
1466
  const area = areas.get(id);
1055
1467
  if (area === void 0)
1056
- throw new Error("PhysicsSimulation returned an unknown visible body id.");
1468
+ throw new Error("IPhysicsSimulation returned an unknown visible body id.");
1057
1469
  area.applyTransform(visible, offset);
1058
1470
  }
1059
1471
  }
@@ -1078,11 +1490,14 @@ function rapier(options = {}) {
1078
1490
  const right = events[offset + 1];
1079
1491
  const started = events[offset + 2] === 1;
1080
1492
  if (left === void 0 || right === void 0)
1081
- throw new Error("PhysicsSimulation returned a malformed collision event.");
1493
+ throw new Error("IPhysicsSimulation returned a malformed collision event.");
1082
1494
  const leftArea = areas.get(left);
1083
1495
  const rightArea = areas.get(right);
1084
1496
  const leftBody = bodiesById.get(left);
1085
1497
  const rightBody = bodiesById.get(right);
1498
+ const contactKey = left < right ? `${left}:${right}` : `${right}:${left}`;
1499
+ if (started) activeContacts.set(contactKey, left < right ? [left, right] : [right, left]);
1500
+ else activeContacts.delete(contactKey);
1086
1501
  if (leftArea !== void 0 && rightBody !== void 0)
1087
1502
  leftArea.handleCollision(rightBody, started);
1088
1503
  if (rightArea !== void 0 && leftBody !== void 0)
@@ -1100,12 +1515,31 @@ function rapier(options = {}) {
1100
1515
  }
1101
1516
  kinematicMotions.clear();
1102
1517
  },
1103
- sceneExit: () => {
1518
+ // Disposing the bodies is not enough to make a restarted scene reproducible. The solver,
1519
+ // island manager and broad phase carry state from everything that has already happened, so
1520
+ // replaying an identical authored layout in a reused world settles differently -- measured
1521
+ // in a sandbox build as settle hashes a2f87bad vs 658eb6f8 at 240 vs 266 ticks, diverging
1522
+ // before any input. A scene therefore gets a pristine simulation, which makes restart
1523
+ // deterministic without a game having to discover an API for it.
1524
+ sceneExit: (ctx) => {
1104
1525
  for (const area of [...areas.values()]) area.dispose();
1105
1526
  for (const body of [...bodies]) body.dispose();
1106
1527
  kinematicMotions.clear();
1528
+ activeContacts.clear();
1529
+ debugSeries = [];
1530
+ if (options.deterministicRestart !== true) return;
1531
+ areas.clear();
1532
+ bodies.clear();
1533
+ bodiesById.clear();
1534
+ simulation?.dispose();
1535
+ const replacement = backend.createSimulation(options);
1536
+ simulation = replacement;
1537
+ context = buildContext(replacement);
1538
+ ctx.physics = context;
1107
1539
  },
1108
1540
  dispose: () => {
1541
+ unregisterObservations?.();
1542
+ unregisterObservations = void 0;
1109
1543
  for (const area of [...areas.values()]) area.dispose();
1110
1544
  for (const body of [...bodies]) body.dispose();
1111
1545
  simulation?.dispose();
@@ -1115,8 +1549,116 @@ function rapier(options = {}) {
1115
1549
  bodies.clear();
1116
1550
  bodiesById.clear();
1117
1551
  kinematicMotions.clear();
1552
+ activeContacts.clear();
1553
+ debugSeries = [];
1118
1554
  }
1119
1555
  };
1556
+ function physicsObservations(ctx, runtime, request) {
1557
+ if (simulation === void 0) throw new Error("Physics observations sampled before setup.");
1558
+ if (request.include?.includes("physicsDebugSeries") !== true) return {};
1559
+ if (request.label !== void 0) {
1560
+ if (debugSeries.some(({ label }) => label === request.label)) {
1561
+ throw new Error(
1562
+ `TN_PHYSICS_DEBUG_LABEL_DUPLICATE: '${request.label}' was already sampled.`
1563
+ );
1564
+ }
1565
+ if (debugSeries.length >= PHYSICS_DEBUG_SAMPLE_LIMIT) {
1566
+ throw new Error(
1567
+ `TN_PHYSICS_DEBUG_SAMPLE_LIMIT: at most ${PHYSICS_DEBUG_SAMPLE_LIMIT} labelled samples are retained.`
1568
+ );
1569
+ }
1570
+ debugSeries.push({
1571
+ label: request.label,
1572
+ snapshot: physicsDebugSnapshot(ctx),
1573
+ tick: runtime.tick()
1574
+ });
1575
+ }
1576
+ return { physicsDebugSeries: debugSeries.map((sample) => ({ ...sample })) };
1577
+ }
1578
+ function physicsDebugSnapshot(ctx) {
1579
+ if (simulation === void 0) throw new Error("Physics observations sampled before setup.");
1580
+ const ordered = [...bodies].sort((left, right) => left.body.id - right.body.id);
1581
+ const retained = ordered.slice(0, PHYSICS_DEBUG_BODY_LIMIT);
1582
+ const retainedIds = new Set(retained.map(({ body }) => body.id));
1583
+ const entityById = new Map(
1584
+ retained.map((body) => [body.body.id, physicsEntityId(ctx, body)])
1585
+ );
1586
+ sleepStates = growSleepStates(sleepStates, bodies.size + areas.size);
1587
+ const sleepCount = simulation.readBodySleepStates(sleepStates);
1588
+ const sleepingById = /* @__PURE__ */ new Map();
1589
+ for (let index = 0; index < sleepCount; index += 1) {
1590
+ const offset = index * PHYSICS_SLEEP_STATE_STRIDE;
1591
+ const id = sleepStates[offset];
1592
+ const sleeping = sleepStates[offset + 1];
1593
+ if (id === void 0 || !Number.isInteger(id) || sleeping !== 0 && sleeping !== 1) {
1594
+ throw new Error("IPhysicsSimulation returned a malformed sleep-state record.");
1595
+ }
1596
+ sleepingById.set(id, sleeping === 1);
1597
+ }
1598
+ const positionById = /* @__PURE__ */ new Map();
1599
+ for (let index = 0; index < visibleCount; index += 1) {
1600
+ const offset = index * PHYSICS_TRANSFORM_STRIDE;
1601
+ const id = visibleId(visible, offset);
1602
+ const position = [visible[offset + 1], visible[offset + 2], visible[offset + 3]];
1603
+ if (position.some((value) => value === void 0 || !Number.isFinite(value))) {
1604
+ throw new Error("IPhysicsSimulation returned a malformed debug position.");
1605
+ }
1606
+ positionById.set(id, position);
1607
+ }
1608
+ const primitives = [];
1609
+ for (const body of retained) {
1610
+ const entity = entityById.get(body.body.id);
1611
+ if (entity === void 0) throw new Error("A retained physics body lost its entity id.");
1612
+ const sleeping = sleepingById.get(body.body.id) ?? false;
1613
+ primitives.push({
1614
+ category: "sleep",
1615
+ entity,
1616
+ id: `sleep:${entity}`,
1617
+ value: sleeping ? 1 : 0
1618
+ });
1619
+ const position = positionById.get(body.body.id);
1620
+ if (position !== void 0) {
1621
+ primitives.push({ category: "center-of-mass", entity, position });
1622
+ }
1623
+ }
1624
+ for (const [left, right] of activeContacts.values()) {
1625
+ if (!retainedIds.has(left) || !retainedIds.has(right)) continue;
1626
+ primitives.push({
1627
+ category: "contact",
1628
+ id: `${entityById.get(left)}:${entityById.get(right)}`
1629
+ });
1630
+ }
1631
+ return {
1632
+ artifact: {
1633
+ overflow: {
1634
+ bodyLimit: PHYSICS_DEBUG_BODY_LIMIT,
1635
+ omittedBodies: Math.max(0, ordered.length - retained.length),
1636
+ totalBodies: ordered.length
1637
+ },
1638
+ primitives
1639
+ }
1640
+ };
1641
+ }
1642
+ function removeContactsFor(bodyId) {
1643
+ for (const [key, pair] of activeContacts) {
1644
+ if (pair.includes(bodyId)) activeContacts.delete(key);
1645
+ }
1646
+ }
1647
+ }
1648
+ function growSleepStates(buffer, bodyCount) {
1649
+ const required = bodyCount * PHYSICS_SLEEP_STATE_STRIDE;
1650
+ if (buffer.length >= required) return buffer;
1651
+ return new Float32Array(Math.max(required, buffer.length * 2));
1652
+ }
1653
+ function physicsEntityId(ctx, body) {
1654
+ for (const id of Object.keys(ctx.entities.snapshot())) {
1655
+ const entity = ctx.entities.get(id);
1656
+ if (entity === body || entity === body.object) return id;
1657
+ if (entity !== void 0 && Object.values(entity).some((value) => value === body || value === body.object)) {
1658
+ return id;
1659
+ }
1660
+ }
1661
+ return `physics.body.${body.body.id}`;
1120
1662
  }
1121
1663
 
1122
- export { Area3D, CharacterBody3D, CollisionShape3D, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, RigidBody3D, interactionGroups, rapier };
1664
+ export { Area3D, CharacterBody3D, CollisionShape3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, interactionGroups, rapier2 as rapier };