@threenative/physics 0.3.3 → 0.3.5

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.
@@ -1,4 +1,5 @@
1
1
  import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh } from 'three';
2
+ import { snowDiscFootprint } from '@threenative/core/world';
2
3
 
3
4
  // src/handles.ts
4
5
  function physicsHandle(raw) {
@@ -27,6 +28,7 @@ function interactionGroups(layer, mask) {
27
28
  var PHYSICS_TRANSFORM_STRIDE = 8;
28
29
  var PHYSICS_COLLISION_EVENT_STRIDE = 4;
29
30
  var PHYSICS_SLEEP_STATE_STRIDE = 2;
31
+ var PHYSICS_CONTACT_STRIDE = 8;
30
32
  var MAX_PHYSICS_QUERY_RESULTS = 1024;
31
33
  var F32_EPSILON = Math.fround(2 ** -23);
32
34
  var F32_EPSILON_SQUARED = Math.fround(F32_EPSILON * F32_EPSILON);
@@ -41,6 +43,7 @@ function f32LengthSquared(values) {
41
43
  function effectiveContinuousCollision(type, requested) {
42
44
  return type === "dynamic" && (requested ?? true);
43
45
  }
46
+ var PHYSICS_VEHICLE_WHEEL_STRIDE = 3;
44
47
  function requireFiniteVector(vector, label) {
45
48
  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))
46
49
  throw new Error(`TN_PHYSICS_NON_FINITE: ${label} must be a finite { x, y, z }.`);
@@ -80,6 +83,33 @@ function requirePhysicsJointCreateOptions(options) {
80
83
  if (options.frameB !== void 0) requireFiniteRotation(options.frameB, "joint frameB");
81
84
  return options;
82
85
  }
86
+ function requireVehicleNumber(value, label, positive3) {
87
+ if (typeof value !== "number" || !Number.isFinite(value) || (positive3 ? value <= 0 : value < 0))
88
+ throw new Error(
89
+ `TN_VEHICLE_INVALID: ${label} must be a finite ${positive3 ? "positive" : "non-negative"} number.`
90
+ );
91
+ }
92
+ function requirePhysicsVehicleCreateOptions(options) {
93
+ if (typeof options !== "object" || options === null)
94
+ throw new Error("IPhysicsSimulation vehicle options must be an object.");
95
+ if (options.forwardAxis !== 0 && options.forwardAxis !== 2)
96
+ throw new Error("TN_VEHICLE_INVALID: forwardAxis must be 0 (x) or 2 (z).");
97
+ requireFiniteVector(options.axle, "vehicle axle");
98
+ if (!Array.isArray(options.wheels) || options.wheels.length < 1)
99
+ throw new Error("TN_VEHICLE_INVALID: a vehicle needs at least one wheel.");
100
+ for (const [index, wheel] of options.wheels.entries()) {
101
+ requireFiniteVector(wheel.position, `vehicle wheel ${index} position`);
102
+ requireVehicleNumber(wheel.wheelRadius, `wheel ${index} wheelRadius`, true);
103
+ requireVehicleNumber(wheel.suspensionRestLength, `wheel ${index} suspensionRestLength`, true);
104
+ requireVehicleNumber(wheel.suspensionStiffness, `wheel ${index} suspensionStiffness`, false);
105
+ requireVehicleNumber(wheel.dampingCompression, `wheel ${index} dampingCompression`, false);
106
+ requireVehicleNumber(wheel.dampingRelaxation, `wheel ${index} dampingRelaxation`, false);
107
+ requireVehicleNumber(wheel.wheelFrictionSlip, `wheel ${index} wheelFrictionSlip`, false);
108
+ if (wheel.maxSuspensionTravel !== void 0)
109
+ requireVehicleNumber(wheel.maxSuspensionTravel, `wheel ${index} maxSuspensionTravel`, false);
110
+ }
111
+ return options;
112
+ }
83
113
  var selectedBackend;
84
114
  function installPhysicsSimulationBackend(backend) {
85
115
  selectedBackend = backend;
@@ -228,7 +258,14 @@ function requirePhysicsPointQuery(value) {
228
258
  position: queryVector(query.position, "point position")
229
259
  };
230
260
  }
261
+ var warnedDeprecatedWorldOption = false;
231
262
  function requirePhysicsSimulation(physics, world) {
263
+ if (world !== void 0 && !warnedDeprecatedWorldOption) {
264
+ warnedDeprecatedWorldOption = true;
265
+ console.warn(
266
+ "TN_DEPRECATED_PHYSICS_WORLD_OPTION: the constructor option `world` is deprecated on every physics node; pass an IPhysicsContext as `physics` instead. The node classes themselves are not deprecated."
267
+ );
268
+ }
232
269
  if (physics?.simulation !== void 0) return physics.simulation;
233
270
  const candidate = typeof world === "object" && world !== null && "simulation" in world ? world.simulation : world;
234
271
  if (typeof candidate === "object" && candidate !== null && "createBody" in candidate && typeof candidate.createBody === "function" && "step" in candidate && typeof candidate.step === "function")
@@ -260,6 +297,44 @@ function primitiveShape(shape) {
260
297
  throw new Error(`TN_NATIVE_PHYSICS_SHAPE_UNSUPPORTED: ${shape.kind} remains OPEN on native`);
261
298
  return shape;
262
299
  }
300
+ function nativeBodyShape(shape) {
301
+ if (shape.kind === "heightfield") {
302
+ const { columns, heights, rows, scale } = shape;
303
+ if (rows === void 0 || columns === void 0 || heights === void 0 || scale === void 0 || heights.length !== rows * columns)
304
+ throw new Error(
305
+ "TN_NATIVE_PHYSICS_SHAPE_INVALID: heightfield requires rows x columns heights"
306
+ );
307
+ return {
308
+ collisionLayer: shape.collisionLayer,
309
+ collisionMask: shape.collisionMask,
310
+ columns,
311
+ heights,
312
+ kind: "heightfield",
313
+ rows,
314
+ scale,
315
+ sensor: shape.sensor,
316
+ x: 0,
317
+ y: 0,
318
+ z: 0
319
+ };
320
+ }
321
+ if (shape.kind === "trimesh") {
322
+ if (shape.vertices === void 0 || shape.indices === void 0)
323
+ throw new Error("TN_NATIVE_PHYSICS_SHAPE_INVALID: trimesh requires vertices and indices");
324
+ return {
325
+ collisionLayer: shape.collisionLayer,
326
+ collisionMask: shape.collisionMask,
327
+ indices: shape.indices,
328
+ kind: shape.kind,
329
+ sensor: shape.sensor,
330
+ vertices: shape.vertices,
331
+ x: shape.x,
332
+ y: shape.y,
333
+ z: shape.z
334
+ };
335
+ }
336
+ return primitiveShape(shape);
337
+ }
263
338
  function opaqueNativeShape(shape) {
264
339
  return Object.freeze({ backend: "native", kind: shape.kind });
265
340
  }
@@ -272,6 +347,31 @@ function growUint32(buffer, minimum) {
272
347
  return length === buffer.length ? buffer : new Uint32Array(length);
273
348
  }
274
349
  var NATIVE_CHARACTER_STATE_STRIDE = 6;
350
+ var RAPIER_DEFAULT_MAX_SUSPENSION_TRAVEL = 5;
351
+ var NATIVE_VEHICLE_WHEEL_WIDTH = 12;
352
+ function flattenVehicleWheels(options) {
353
+ const wheels = new Float32Array(options.wheels.length * NATIVE_VEHICLE_WHEEL_WIDTH);
354
+ options.wheels.forEach((wheel, index) => {
355
+ wheels.set(
356
+ [
357
+ wheel.position.x,
358
+ wheel.position.y,
359
+ wheel.position.z,
360
+ wheel.wheelRadius,
361
+ wheel.suspensionRestLength,
362
+ wheel.suspensionStiffness,
363
+ wheel.dampingCompression,
364
+ wheel.dampingRelaxation,
365
+ wheel.wheelFrictionSlip,
366
+ wheel.maxSuspensionTravel ?? RAPIER_DEFAULT_MAX_SUSPENSION_TRAVEL,
367
+ wheel.useAsSteering ? 1 : 0,
368
+ wheel.useAsTraction ? 1 : 0
369
+ ],
370
+ index * NATIVE_VEHICLE_WHEEL_WIDTH
371
+ );
372
+ });
373
+ return wheels;
374
+ }
275
375
  function createNativePhysicsSimulation(raw, version) {
276
376
  const bodyIds = /* @__PURE__ */ new Set();
277
377
  const bodyHandles = /* @__PURE__ */ new Map();
@@ -279,6 +379,9 @@ function createNativePhysicsSimulation(raw, version) {
279
379
  const characterIds = /* @__PURE__ */ new Set();
280
380
  const characterState = /* @__PURE__ */ new Map();
281
381
  const characterStatePresent = /* @__PURE__ */ new Set();
382
+ const vehicles = /* @__PURE__ */ new Map();
383
+ const vehicleBodies = /* @__PURE__ */ new Map();
384
+ const dynamicBodies = /* @__PURE__ */ new Set();
282
385
  let characterStates = new Float32Array(48);
283
386
  const rayOutput = new Float32Array(8);
284
387
  let areaPairs = new Uint32Array(32);
@@ -304,6 +407,12 @@ function createNativePhysicsSimulation(raw, version) {
304
407
  throw new Error("TN_NATIVE_PHYSICS_INVALID: query returned an unknown body");
305
408
  return handle;
306
409
  };
410
+ const requireVehicle = (id, operation) => {
411
+ const record = vehicles.get(id);
412
+ if (record === void 0)
413
+ throw new Error(`TN_VEHICLE_UNKNOWN: ${operation} references an unknown vehicle ${id}.`);
414
+ return record;
415
+ };
307
416
  const finiteQueryVector = (value, label) => {
308
417
  if (!Number.isFinite(value.x) || !Number.isFinite(value.y) || !Number.isFinite(value.z))
309
418
  throw new Error(`TN_NATIVE_PHYSICS_INVALID: ${label} contains a non-finite vector`);
@@ -409,7 +518,7 @@ function createNativePhysicsSimulation(raw, version) {
409
518
  throw new Error("Physics body continuousCollision must be a boolean.");
410
519
  requireFiniteVector(options.position, "body position");
411
520
  requireFiniteRotation(options.rotation, "body rotation");
412
- const shape = primitiveShape(options.shape);
521
+ const shape = nativeBodyShape(options.shape);
413
522
  const sensor = requirePhysicsBodySensor(options);
414
523
  const id = raw.createBody({
415
524
  collisionLayer: shape.collisionLayer,
@@ -431,6 +540,7 @@ function createNativePhysicsSimulation(raw, version) {
431
540
  const bodyHandleValue = physicsBodyHandle(id, rawHandle, options.entity);
432
541
  bodyIds.add(id);
433
542
  bodyHandles.set(id, bodyHandleValue);
543
+ if (options.type === "dynamic") dynamicBodies.add(id);
434
544
  if (sensor) {
435
545
  areaIntersections.set(id, /* @__PURE__ */ new Set());
436
546
  }
@@ -471,6 +581,7 @@ function createNativePhysicsSimulation(raw, version) {
471
581
  raw.removeBody(id);
472
582
  bodyIds.delete(id);
473
583
  bodyHandles.delete(id);
584
+ dynamicBodies.delete(id);
474
585
  for (const [jointId, bodies] of jointBodies) {
475
586
  if (bodies[0] === id || bodies[1] === id) jointBodies.delete(jointId);
476
587
  }
@@ -478,6 +589,11 @@ function createNativePhysicsSimulation(raw, version) {
478
589
  characterIds.delete(id);
479
590
  characterState.delete(id);
480
591
  characterStatePresent.delete(id);
592
+ for (const [vehicleId, bodyId2] of vehicleBodies) {
593
+ if (bodyId2 !== id) continue;
594
+ vehicleBodies.delete(vehicleId);
595
+ vehicles.delete(vehicleId);
596
+ }
481
597
  invalidateObservations();
482
598
  },
483
599
  removeJoint: (id) => {
@@ -548,6 +664,38 @@ function createNativePhysicsSimulation(raw, version) {
548
664
  requirePhysicsSleepStateBuffer(buffer, bodyIds.size);
549
665
  return raw.readBodySleepStates(buffer);
550
666
  },
667
+ readContacts: (target, colliders, buffer) => {
668
+ requireLive();
669
+ if (raw.readContacts === void 0)
670
+ throw new Error("TN_NATIVE_PHYSICS_CONTACTS_MISSING: runtime ABI is too old");
671
+ if (!(buffer instanceof Float32Array) || !(colliders instanceof Uint32Array))
672
+ throw new Error(
673
+ "IPhysicsSimulation.readContacts requires Uint32Array ids and a Float32Array."
674
+ );
675
+ if (!bodyIds.has(target.id))
676
+ throw new Error(
677
+ `IPhysicsSimulation contact target ${String(target.id)} is not a live collider.`
678
+ );
679
+ const count = raw.readContacts(target.id, colliders, buffer);
680
+ if (!Number.isInteger(count) || count < 0)
681
+ throw new Error("TN_NATIVE_PHYSICS_INVALID: contact read returned an invalid count");
682
+ return count;
683
+ },
684
+ setColliderShape: (collider, shape) => {
685
+ requireLive();
686
+ if (raw.setColliderShape === void 0)
687
+ throw new Error("TN_NATIVE_PHYSICS_SHAPE_REFRESH_MISSING: runtime ABI is too old");
688
+ if (!bodyIds.has(collider.id))
689
+ throw new Error(
690
+ `IPhysicsSimulation shape target ${String(collider.id)} is not a live collider.`
691
+ );
692
+ if (shape.kind !== "heightfield")
693
+ throw new Error(
694
+ `TN_NATIVE_PHYSICS_SHAPE_UNSUPPORTED: native setColliderShape takes a heightfield, not ${shape.kind}`
695
+ );
696
+ raw.setColliderShape(collider.id, nativeBodyShape(shape));
697
+ invalidateObservations();
698
+ },
551
699
  intersectRay: (value) => {
552
700
  requireLive();
553
701
  const query = requirePhysicsRayQuery(value);
@@ -641,6 +789,73 @@ function createNativePhysicsSimulation(raw, version) {
641
789
  requirePhysicsEventBuffer(buffer);
642
790
  return raw.drainCollisionEvents(buffer);
643
791
  },
792
+ createVehicle: (options) => {
793
+ requireLive();
794
+ const requested = requirePhysicsVehicleCreateOptions(options);
795
+ if (!bodyIds.has(requested.bodyId))
796
+ throw new Error(
797
+ `TN_PHYSICS_UNKNOWN_BODY: createVehicle references an unknown body ${requested.bodyId}.`
798
+ );
799
+ if (!dynamicBodies.has(requested.bodyId))
800
+ throw new Error(
801
+ `TN_PHYSICS_NOT_DYNAMIC: createVehicle needs a dynamic body; body ${requested.bodyId} is not dynamic.`
802
+ );
803
+ if (raw.createVehicle === void 0)
804
+ throw new Error("TN_NATIVE_PHYSICS_VEHICLE_MISSING: runtime ABI is too old");
805
+ const wheelCount = requested.wheels.length;
806
+ const id = raw.createVehicle({
807
+ axle: requested.axle,
808
+ bodyId: requested.bodyId,
809
+ forwardAxis: requested.forwardAxis,
810
+ wheels: flattenVehicleWheels(requested)
811
+ });
812
+ if (!Number.isSafeInteger(id) || id < 0)
813
+ throw new Error("TN_NATIVE_PHYSICS_INVALID: runtime returned an invalid vehicle id");
814
+ const buffer = new Float32Array(1 + wheelCount * PHYSICS_VEHICLE_WHEEL_STRIDE);
815
+ vehicles.set(id, {
816
+ buffer,
817
+ state: { speed: 0, wheels: buffer.subarray(1) }
818
+ });
819
+ vehicleBodies.set(id, requested.bodyId);
820
+ return id;
821
+ },
822
+ setVehicleInput: (id, input) => {
823
+ requireLive();
824
+ if (raw.setVehicleInput === void 0)
825
+ throw new Error("TN_NATIVE_PHYSICS_VEHICLE_MISSING: runtime ABI is too old");
826
+ if (typeof input?.engineForce !== "number" || typeof input.brake !== "number" || typeof input.steering !== "number" || !Number.isFinite(input.engineForce) || !Number.isFinite(input.brake) || !Number.isFinite(input.steering))
827
+ throw new Error(
828
+ "TN_PHYSICS_NON_FINITE: vehicle input needs a finite engineForce, brake and steering."
829
+ );
830
+ requireVehicle(id, "setVehicleInput");
831
+ raw.setVehicleInput(id, input);
832
+ },
833
+ readVehicleState: (id) => {
834
+ requireLive();
835
+ if (raw.readVehicleState === void 0)
836
+ throw new Error("TN_NATIVE_PHYSICS_VEHICLE_MISSING: runtime ABI is too old");
837
+ const record = requireVehicle(id, "readVehicleState");
838
+ const count = raw.readVehicleState(id, record.buffer);
839
+ if (!Number.isSafeInteger(count) || count < 1)
840
+ throw new Error("TN_VEHICLE_UNKNOWN: the vehicle left the backend.");
841
+ if (count !== record.buffer.length)
842
+ throw new Error(
843
+ `TN_VEHICLE_STATE_SHORT: readVehicleState wrote ${count} of ${record.buffer.length} floats for vehicle ${id}.`
844
+ );
845
+ record.state.speed = record.buffer[0] ?? 0;
846
+ return record.state;
847
+ },
848
+ resetVehicle: (id, position, yaw) => {
849
+ requireLive();
850
+ if (raw.resetVehicle === void 0)
851
+ throw new Error("TN_NATIVE_PHYSICS_VEHICLE_MISSING: runtime ABI is too old");
852
+ requireVehicle(id, "resetVehicle");
853
+ requireFiniteVector(position, "vehicle position");
854
+ if (typeof yaw !== "number" || !Number.isFinite(yaw))
855
+ throw new Error("TN_PHYSICS_NON_FINITE: vehicle yaw must be a finite number of radians.");
856
+ raw.resetVehicle(id, position, yaw);
857
+ bodyTransformsDirty = true;
858
+ },
644
859
  dispose: () => {
645
860
  if (disposed) return;
646
861
  disposed = true;
@@ -649,6 +864,9 @@ function createNativePhysicsSimulation(raw, version) {
649
864
  bodyTransformRows.clear();
650
865
  bodyHandles.clear();
651
866
  jointBodies.clear();
867
+ vehicles.clear();
868
+ vehicleBodies.clear();
869
+ dynamicBodies.clear();
652
870
  characterIds.clear();
653
871
  characterState.clear();
654
872
  characterStatePresent.clear();
@@ -853,6 +1071,19 @@ var CharacterBody3D = class {
853
1071
  #beforeY = 0;
854
1072
  #desiredY = 0;
855
1073
  #disposed = false;
1074
+ #interpolate = true;
1075
+ /** Draw between solved ticks; false presents this body at its true tick pose. */
1076
+ get interpolate() {
1077
+ return this.#interpolate;
1078
+ }
1079
+ set interpolate(enabled) {
1080
+ if (this.#disposed)
1081
+ throw new Error("CharacterBody3D.interpolate cannot be used after dispose.");
1082
+ if (typeof enabled !== "boolean") throw new Error("interpolate must be a boolean.");
1083
+ if (enabled === this.#interpolate) return;
1084
+ this.#interpolate = enabled;
1085
+ this.#physics?.updateInterpolation?.(this);
1086
+ }
856
1087
  constructor(options) {
857
1088
  this.#simulation = requirePhysicsSimulation(options.physics, options.world);
858
1089
  this.#physics = options.physics;
@@ -956,6 +1187,7 @@ var CharacterBody3D = class {
956
1187
  if (this.#disposed) throw new Error("CharacterBody3D.teleport cannot be used after dispose.");
957
1188
  this.#simulation.setBodyTransform(this.body.id, position);
958
1189
  this.object.position.set(position.x, position.y, position.z);
1190
+ this.#physics?.resetInterpolation?.(this.object);
959
1191
  this.velocity.set(0, 0, 0);
960
1192
  this.#desired.x = 0;
961
1193
  this.#desired.y = 0;
@@ -1190,6 +1422,15 @@ var CollisionShape3D = class _CollisionShape3D {
1190
1422
  const width = (bounds.max.x - bounds.min.x) * Math.abs(mesh.scale.x);
1191
1423
  const height = (bounds.max.y - bounds.min.y) * Math.abs(mesh.scale.y);
1192
1424
  const depth = (bounds.max.z - bounds.min.z) * Math.abs(mesh.scale.z);
1425
+ const offset = Math.max(
1426
+ Math.abs(bounds.max.x + bounds.min.x) / 2 * Math.abs(mesh.scale.x),
1427
+ Math.abs(bounds.max.y + bounds.min.y) / 2 * Math.abs(mesh.scale.y),
1428
+ Math.abs(bounds.max.z + bounds.min.z) / 2 * Math.abs(mesh.scale.z)
1429
+ );
1430
+ if (offset > 1e-4 + 1e-3 * Math.max(width, height, depth))
1431
+ throw new Error(
1432
+ `TN_COLLISION_SHAPE_OFF_CENTRE: '${mesh.name || "mesh"}' has geometry centred ${offset.toFixed(3)} from its origin, so a ${inferred} collider would sit away from what is drawn. Call geometry.center() and move the mesh instead, pass "trimesh", or build level colliders with buildStaticColliders.`
1433
+ );
1193
1434
  if (inferred === "sphere") {
1194
1435
  geometry.computeBoundingSphere();
1195
1436
  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));
@@ -1500,6 +1741,18 @@ var RigidBody3D = class {
1500
1741
  #motion = { x: 0, y: 0, z: 0 };
1501
1742
  #zeroMotion = { x: 0, y: 0, z: 0 };
1502
1743
  #disposed = false;
1744
+ #interpolate = true;
1745
+ /** Draw between solved ticks; false presents this body at its true tick pose. */
1746
+ get interpolate() {
1747
+ return this.#interpolate;
1748
+ }
1749
+ set interpolate(enabled) {
1750
+ this.#requireLive("interpolate");
1751
+ if (typeof enabled !== "boolean") throw new Error("interpolate must be a boolean.");
1752
+ if (enabled === this.#interpolate) return;
1753
+ this.#interpolate = enabled;
1754
+ this.#physics?.updateInterpolation?.(this);
1755
+ }
1503
1756
  constructor(options) {
1504
1757
  const initial = resolveInitialTransform(options);
1505
1758
  const type = options.type ?? "dynamic";
@@ -1567,6 +1820,23 @@ var RigidBody3D = class {
1567
1820
  this.#motion.z = object.position.z - this.#lastPosition.z;
1568
1821
  return this.#motion;
1569
1822
  }
1823
+ /** Assign a world position to teleport; mutate object.position for ordinary kinematic motion. */
1824
+ get position() {
1825
+ const position = this.#object?.position ?? this.#simulation.readBodyTransform?.(this.body.id)?.position;
1826
+ if (position === void 0) throw new Error("RigidBody3D position is unavailable.");
1827
+ return position;
1828
+ }
1829
+ set position(position) {
1830
+ this.#requireLive("position");
1831
+ this.#simulation.setBodyTransform(this.body.id, position);
1832
+ this.#lastPosition.x = position.x;
1833
+ this.#lastPosition.y = position.y;
1834
+ this.#lastPosition.z = position.z;
1835
+ if (this.#object !== void 0) {
1836
+ this.#object.position.set(position.x, position.y, position.z);
1837
+ this.#physics?.resetInterpolation?.(this.#object);
1838
+ }
1839
+ }
1570
1840
  syncToPhysics() {
1571
1841
  }
1572
1842
  /**
@@ -1811,6 +2081,543 @@ var PhysicsSoftBodyCollision = class {
1811
2081
  function softBodyCollision(...bodies) {
1812
2082
  return new PhysicsSoftBodyCollision(bodies);
1813
2083
  }
2084
+ function unionBounds(current, next) {
2085
+ if (current === void 0) return next;
2086
+ const column = Math.min(current.column, next.column);
2087
+ const row = Math.min(current.row, next.row);
2088
+ return {
2089
+ column,
2090
+ columns: Math.max(current.column + current.columns, next.column + next.columns) - column,
2091
+ row,
2092
+ rows: Math.max(current.row + current.rows, next.row + next.rows) - row
2093
+ };
2094
+ }
2095
+ var ZERO_SAMPLE = {
2096
+ bank: 0,
2097
+ coverage: 0,
2098
+ disturbance: 0,
2099
+ relief: 0,
2100
+ shape: 0
2101
+ };
2102
+ function clamp(value, minimum, maximum) {
2103
+ return Math.max(minimum, Math.min(maximum, value));
2104
+ }
2105
+ function smoothstep(edge0, edge1, value) {
2106
+ const t = clamp((value - edge0) / (edge1 - edge0), 0, 1);
2107
+ return t * t * (3 - 2 * t);
2108
+ }
2109
+ function positive2(value, name) {
2110
+ if (!Number.isFinite(value) || value <= 0)
2111
+ throw new Error(`attachSnowPhysics ${name} must be a positive finite number.`);
2112
+ return value;
2113
+ }
2114
+ function capsuleFootprint(halfHeight, radius) {
2115
+ positive2(radius, "capsule radius");
2116
+ if (!Number.isFinite(halfHeight) || halfHeight < 0)
2117
+ throw new Error("attachSnowPhysics capsule halfHeight must be a non-negative finite number.");
2118
+ const softness = 0.2 * radius;
2119
+ return {
2120
+ extent: halfHeight + radius + 2 * softness,
2121
+ sample: (x, z) => {
2122
+ const along = clamp(z, -halfHeight, halfHeight);
2123
+ return edgeSample(Math.hypot(x, z - along) - radius, softness);
2124
+ }
2125
+ };
2126
+ }
2127
+ function boxFootprint(halfWidth, halfDepth) {
2128
+ positive2(halfWidth, "box halfWidth");
2129
+ positive2(halfDepth, "box halfDepth");
2130
+ const edge = 0.15 * Math.min(halfWidth, halfDepth);
2131
+ return {
2132
+ extent: Math.hypot(halfWidth + 2 * edge, halfDepth + 2 * edge),
2133
+ sample: (x, z) => edgeSample(Math.max(Math.abs(x) - halfWidth, Math.abs(z) - halfDepth), edge)
2134
+ };
2135
+ }
2136
+ function edgeSample(outside, edge) {
2137
+ if (outside >= 2 * edge) return ZERO_SAMPLE;
2138
+ if (outside >= edge) {
2139
+ const bank = 1 - (outside - edge) / edge;
2140
+ return { bank, coverage: 0, disturbance: bank * 0.5, relief: 0, shape: 1 };
2141
+ }
2142
+ const coverage = outside <= 0 ? 1 : 1 - smoothstep(0, edge, outside);
2143
+ return { bank: 0, coverage, disturbance: coverage, relief: 0, shape: 1 };
2144
+ }
2145
+ var SUPPORTED_SHAPES = ["sphere", "box", "capsule"];
2146
+ function rotateAxis(q, axis) {
2147
+ const { w, x, y, z } = q;
2148
+ if (axis === 0) return [1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)];
2149
+ if (axis === 1) return [2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)];
2150
+ return [2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)];
2151
+ }
2152
+ function orientedFootprint(watched, transform, cellSize) {
2153
+ const { position, rotation } = transform;
2154
+ if (watched.custom !== void 0) {
2155
+ const forward = rotateAxis(rotation, 2);
2156
+ return {
2157
+ footprint: watched.custom,
2158
+ rotation: Math.atan2(forward[0], forward[2]),
2159
+ x: position.x,
2160
+ z: position.z
2161
+ };
2162
+ }
2163
+ const shape = watched.shape;
2164
+ if (shape === void 0) throw new Error("attachSnowPhysics watched body lost its shape.");
2165
+ if (shape.kind === "box") return boxPrint(watched.cache, shape, transform);
2166
+ if (shape.kind === "capsule") return capsulePrint(watched.cache, shape, transform, cellSize);
2167
+ return {
2168
+ footprint: cached(watched.cache, 0, () => snowDiscFootprint(shape.x)),
2169
+ rotation: 0,
2170
+ x: position.x,
2171
+ z: position.z
2172
+ };
2173
+ }
2174
+ function cached(cache, key, create) {
2175
+ let footprint = cache.get(key);
2176
+ if (footprint === void 0) {
2177
+ footprint = create();
2178
+ cache.set(key, footprint);
2179
+ }
2180
+ return footprint;
2181
+ }
2182
+ function boxPrint(cache, shape, { position, rotation }) {
2183
+ const axes = [rotateAxis(rotation, 0), rotateAxis(rotation, 1), rotateAxis(rotation, 2)];
2184
+ const halves = [shape.x, shape.y, shape.z];
2185
+ let down = 0;
2186
+ for (let axis2 = 1; axis2 < 3; axis2 += 1)
2187
+ if (Math.abs(axes[axis2]?.[1] ?? 0) > Math.abs(axes[down]?.[1] ?? 0)) down = axis2;
2188
+ const across = down === 0 ? 1 : 0;
2189
+ const along = down === 2 ? 1 : 2;
2190
+ const normal = axes[down];
2191
+ const toFace = halves[down] * (normal[1] > 0 ? -1 : 1);
2192
+ const axis = axes[across];
2193
+ return {
2194
+ footprint: cached(
2195
+ cache,
2196
+ down,
2197
+ () => boxFootprint(halves[across], halves[along])
2198
+ ),
2199
+ rotation: Math.atan2(-axis[2], axis[0]),
2200
+ x: position.x + normal[0] * toFace,
2201
+ z: position.z + normal[2] * toFace
2202
+ };
2203
+ }
2204
+ function capsulePrint(cache, shape, { position, rotation }, cellSize) {
2205
+ const spine = rotateAxis(rotation, 1);
2206
+ const reach = shape.x * Math.hypot(spine[0], spine[2]);
2207
+ const key = Math.round(reach / (cellSize / 2));
2208
+ return {
2209
+ footprint: cached(cache, key, () => capsuleFootprint(key * cellSize / 2, shape.y)),
2210
+ rotation: Math.atan2(spine[0], spine[2]),
2211
+ x: position.x,
2212
+ z: position.z
2213
+ };
2214
+ }
2215
+ function attachSnowPhysics(options) {
2216
+ const simulation = options.physics.simulation;
2217
+ if (typeof simulation.readContacts !== "function" || typeof simulation.setColliderShape !== "function" || typeof simulation.readBodyTransform !== "function")
2218
+ throw new Error(
2219
+ "attachSnowPhysics requires a physics backend with persistent solved contacts, in-place shape refresh and body transform reads."
2220
+ );
2221
+ const readContacts = simulation.readContacts.bind(simulation);
2222
+ const setColliderShape = simulation.setColliderShape.bind(simulation);
2223
+ const readBodyTransform = simulation.readBodyTransform.bind(simulation);
2224
+ const snow = options.snow;
2225
+ const field = snow.field;
2226
+ const loadScale = finiteOr(options.loadScale, 1, "loadScale");
2227
+ const supportNormal = clamp(finiteOr(options.supportNormal, 0.35, "supportNormal"), 0, 1);
2228
+ const cellSize = Math.min(snow.cellWidth, snow.cellDepth);
2229
+ const colliderTolerance = finiteOr(options.colliderTolerance, 5e-4, "colliderTolerance");
2230
+ if (colliderTolerance < 0)
2231
+ throw new Error("attachSnowPhysics colliderTolerance must be non-negative.");
2232
+ const watched = /* @__PURE__ */ new Map();
2233
+ let colliderHeights = field.toColliderHeights();
2234
+ const changes = field.trackChanges();
2235
+ let unsynced;
2236
+ let surfaceVersion = snow.version;
2237
+ let contacts = 0;
2238
+ let supported = 0;
2239
+ let load = 0;
2240
+ let version = snow.version;
2241
+ let disposed = false;
2242
+ function surfaceDescriptor() {
2243
+ return {
2244
+ collisionLayer: options.collisionLayer ?? 1,
2245
+ collisionMask: options.collisionMask ?? 65535,
2246
+ columns: field.columns,
2247
+ heights: colliderHeights,
2248
+ kind: "heightfield",
2249
+ rows: field.rows,
2250
+ // Rapier's heightfield scale is the full extent, and its own axis order is the transposed
2251
+ // buffer `toColliderHeights` already produced.
2252
+ scale: { x: field.width, y: 1, z: field.depth },
2253
+ sensor: false,
2254
+ x: 0,
2255
+ y: 0,
2256
+ z: 0
2257
+ };
2258
+ }
2259
+ const registration = simulation.createBody({
2260
+ entity: "threenative.snow.surface",
2261
+ mass: 0,
2262
+ position: { x: field.origin.x, y: 0, z: field.origin.z },
2263
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
2264
+ sensor: false,
2265
+ shape: surfaceDescriptor(),
2266
+ type: "fixed"
2267
+ });
2268
+ const surface = registration.collider;
2269
+ const surfaceBody = registration.body;
2270
+ let contactBuffer = new Float32Array(PHYSICS_CONTACT_STRIDE * 64);
2271
+ let colliderScratch = new Uint32Array(8);
2272
+ function colliderGap(canonical) {
2273
+ let gap = 0;
2274
+ for (let index = 0; index < canonical.length; index += 1)
2275
+ gap = Math.max(
2276
+ gap,
2277
+ Math.abs(canonical[index] - colliderHeights[index])
2278
+ );
2279
+ return gap;
2280
+ }
2281
+ function windowGap(window) {
2282
+ let gap = 0;
2283
+ const rows = field.rows;
2284
+ for (let column = window.column; column < window.column + window.columns; column += 1) {
2285
+ for (let row = window.row; row < window.row + window.rows; row += 1) {
2286
+ const installed = colliderHeights[column * rows + row];
2287
+ gap = Math.max(gap, Math.abs(field.colliderHeight(row, column) - installed));
2288
+ }
2289
+ }
2290
+ return gap;
2291
+ }
2292
+ function refreshSurface() {
2293
+ const changed = changes.take();
2294
+ if (changed !== void 0) unsynced = unionBounds(unsynced, changed);
2295
+ if (unsynced !== void 0 && windowGap(unsynced) > colliderTolerance) {
2296
+ colliderHeights = field.toColliderHeights();
2297
+ setColliderShape(surface, surfaceDescriptor());
2298
+ unsynced = void 0;
2299
+ }
2300
+ surfaceVersion = snow.version;
2301
+ }
2302
+ function colliderIds() {
2303
+ if (colliderScratch.length < watched.size) colliderScratch = new Uint32Array(watched.size * 2);
2304
+ let index = 0;
2305
+ for (const id of watched.keys()) {
2306
+ colliderScratch[index] = id;
2307
+ index += 1;
2308
+ }
2309
+ return colliderScratch.subarray(0, index);
2310
+ }
2311
+ function readAll(ids) {
2312
+ let found = readContacts(surface, ids, contactBuffer);
2313
+ if (found * PHYSICS_CONTACT_STRIDE > contactBuffer.length) {
2314
+ contactBuffer = new Float32Array(found * 2 * PHYSICS_CONTACT_STRIDE);
2315
+ found = readContacts(surface, ids, contactBuffer);
2316
+ if (found * PHYSICS_CONTACT_STRIDE > contactBuffer.length)
2317
+ throw new Error("attachSnowPhysics contact count changed between two reads of one step.");
2318
+ }
2319
+ return found;
2320
+ }
2321
+ function add(body, footprint) {
2322
+ if (disposed) throw new Error("attachSnowPhysics binding is disposed.");
2323
+ const shape = "shape" in body ? body.shape.descriptor : void 0;
2324
+ if (footprint === void 0 && !SUPPORTED_SHAPES.includes(shape?.kind))
2325
+ throw new Error(
2326
+ `attachSnowPhysics cannot derive a contact profile for a '${shape?.kind ?? "unknown"}' shape; supported shapes are ${SUPPORTED_SHAPES.join(", ")}. Pass an explicit footprint instead.`
2327
+ );
2328
+ watched.set(body.collider.id, {
2329
+ body,
2330
+ cache: /* @__PURE__ */ new Map(),
2331
+ custom: footprint,
2332
+ impulse: 0,
2333
+ load: 0,
2334
+ shape
2335
+ });
2336
+ }
2337
+ for (const body of options.bodies ?? []) add(body);
2338
+ function gather() {
2339
+ const found = readAll(colliderIds());
2340
+ contacts = found;
2341
+ for (let index = 0; index < found; index += 1) {
2342
+ const offset = index * PHYSICS_CONTACT_STRIDE;
2343
+ const entry = watched.get(contactBuffer[offset]);
2344
+ if (entry === void 0 || contactBuffer[offset + 5] < supportNormal) continue;
2345
+ entry.impulse += Math.max(0, contactBuffer[offset + 7]);
2346
+ }
2347
+ }
2348
+ function press(deltaTime) {
2349
+ gather();
2350
+ for (const entry of watched.values()) {
2351
+ entry.load = 0;
2352
+ if (entry.impulse <= 0) continue;
2353
+ const transform = readBodyTransform(entry.body.body.id);
2354
+ if (transform === void 0) throw new Error("attachSnowPhysics lost a watched body.");
2355
+ const oriented = orientedFootprint(entry, transform, cellSize);
2356
+ const bodyLoad = entry.impulse / deltaTime * loadScale;
2357
+ snow.stamp({
2358
+ area: footprintArea(oriented.footprint),
2359
+ duration: deltaTime,
2360
+ footprint: oriented.footprint,
2361
+ load: bodyLoad,
2362
+ rotation: oriented.rotation,
2363
+ x: oriented.x,
2364
+ z: oriented.z
2365
+ });
2366
+ supported += 1;
2367
+ load += bodyLoad;
2368
+ entry.load = bodyLoad;
2369
+ entry.impulse = 0;
2370
+ }
2371
+ }
2372
+ const binding = {
2373
+ add,
2374
+ deposition: finiteOr(options.deposition, 0, "deposition"),
2375
+ wind: finiteOr(options.wind, 0, "wind"),
2376
+ get contacts() {
2377
+ return contacts;
2378
+ },
2379
+ get supported() {
2380
+ return supported;
2381
+ },
2382
+ get surface() {
2383
+ return surface;
2384
+ },
2385
+ get surfaceVersion() {
2386
+ return surfaceVersion;
2387
+ },
2388
+ get version() {
2389
+ return version;
2390
+ },
2391
+ observe() {
2392
+ return {
2393
+ colliderError: colliderGap(field.toColliderHeights()),
2394
+ colliderVersion: surfaceVersion,
2395
+ contacts,
2396
+ load,
2397
+ loadProvenance: "solver-impulse-per-step",
2398
+ supported,
2399
+ version: snow.version
2400
+ };
2401
+ },
2402
+ remove(body) {
2403
+ watched.delete(body.collider.id);
2404
+ },
2405
+ loadOf(body) {
2406
+ return watched.get(body.collider.id)?.load ?? 0;
2407
+ },
2408
+ step(deltaTime) {
2409
+ if (disposed) return;
2410
+ if (!Number.isFinite(deltaTime) || deltaTime <= 0)
2411
+ throw new Error("attachSnowPhysics step requires a positive finite delta time.");
2412
+ contacts = 0;
2413
+ supported = 0;
2414
+ load = 0;
2415
+ if (watched.size > 0) press(deltaTime);
2416
+ const deposition = Math.max(0, finiteOr(binding.deposition, 0, "deposition"));
2417
+ const wind = Math.max(0, finiteOr(binding.wind, 0, "wind"));
2418
+ if (deposition > 0 || wind > 0) snow.recover(deltaTime, deposition, wind);
2419
+ refreshSurface();
2420
+ version = snow.version;
2421
+ },
2422
+ dispose() {
2423
+ if (disposed) return;
2424
+ disposed = true;
2425
+ changes.dispose();
2426
+ watched.clear();
2427
+ simulation.removeBody(surfaceBody.id);
2428
+ }
2429
+ };
2430
+ return binding;
2431
+ }
2432
+ function finiteOr(value, fallback, name) {
2433
+ if (value === void 0) return fallback;
2434
+ if (!Number.isFinite(value)) throw new Error(`attachSnowPhysics ${name} must be finite.`);
2435
+ return value;
2436
+ }
2437
+ var MIN_CONTACT_AREA = 1e-4;
2438
+ var footprintAreas = /* @__PURE__ */ new WeakMap();
2439
+ function footprintArea(footprint) {
2440
+ const cached2 = footprintAreas.get(footprint);
2441
+ if (cached2 !== void 0) return cached2;
2442
+ const steps = 24;
2443
+ const step = footprint.extent * 2 / steps;
2444
+ let area = 0;
2445
+ for (let row = 0; row < steps; row += 1) {
2446
+ const z = -footprint.extent + (row + 0.5) * step;
2447
+ for (let column = 0; column < steps; column += 1) {
2448
+ const x = -footprint.extent + (column + 0.5) * step;
2449
+ area += footprint.sample(x, z).coverage * step * step;
2450
+ }
2451
+ }
2452
+ const measured = Math.max(area, MIN_CONTACT_AREA);
2453
+ footprintAreas.set(footprint, measured);
2454
+ return measured;
2455
+ }
2456
+
2457
+ // src/VehicleBody3D.ts
2458
+ var FORWARD_AXES = {
2459
+ "-x": { axle: { x: 0, y: 0, z: -1 }, index: 0 },
2460
+ "-z": { axle: { x: 1, y: 0, z: 0 }, index: 2 },
2461
+ x: { axle: { x: 0, y: 0, z: 1 }, index: 0 },
2462
+ z: { axle: { x: -1, y: 0, z: 0 }, index: 2 }
2463
+ };
2464
+ function requireFinite(value, label) {
2465
+ if (typeof value !== "number" || !Number.isFinite(value))
2466
+ throw new Error(`TN_VEHICLE_INVALID: ${label} must be a finite number.`);
2467
+ }
2468
+ var VehicleBody3D = class extends RigidBody3D {
2469
+ wheels;
2470
+ #object;
2471
+ #simulation;
2472
+ #readState;
2473
+ #setInput;
2474
+ #vehicle;
2475
+ #engineForce = 0;
2476
+ #brake = 0;
2477
+ #steering = 0;
2478
+ #disposed = false;
2479
+ constructor(options) {
2480
+ const forward = FORWARD_AXES[options.forwardAxis ?? "-z"];
2481
+ if (forward === void 0)
2482
+ throw new Error(
2483
+ `TN_VEHICLE_INVALID: forwardAxis '${String(options.forwardAxis)}' must be one of -x, -z, x, z.`
2484
+ );
2485
+ const simulation = requirePhysicsSimulation(options.physics, options.world);
2486
+ const createVehicle = simulation.createVehicle;
2487
+ const setVehicleInput = simulation.setVehicleInput;
2488
+ const readVehicleState = simulation.readVehicleState;
2489
+ if (createVehicle === void 0 || setVehicleInput === void 0 || readVehicleState === void 0)
2490
+ throw new Error(
2491
+ "TN_VEHICLE_NATIVE_UNAVAILABLE: the active physics backend has no vehicle controller. Use RigidBody3D instead."
2492
+ );
2493
+ super({
2494
+ collisionLayer: options.collisionLayer,
2495
+ collisionMask: options.collisionMask,
2496
+ entity: options.entity,
2497
+ mass: options.mass ?? 0,
2498
+ object: options.object,
2499
+ physics: options.physics,
2500
+ shape: options.shape,
2501
+ type: "dynamic",
2502
+ world: options.world
2503
+ });
2504
+ this.wheels = options.wheels;
2505
+ this.#object = options.object;
2506
+ this.#simulation = simulation;
2507
+ this.#readState = readVehicleState;
2508
+ this.#setInput = setVehicleInput;
2509
+ try {
2510
+ this.#vehicle = createVehicle.call(simulation, {
2511
+ axle: forward.axle,
2512
+ bodyId: this.body.id,
2513
+ forwardAxis: forward.index,
2514
+ wheels: options.wheels
2515
+ });
2516
+ } catch (error) {
2517
+ this.dispose();
2518
+ throw error;
2519
+ }
2520
+ }
2521
+ /**
2522
+ * Godot's `engine_force`, in newtons. Every wheel with `useAsTraction` receives the full value,
2523
+ * so two driven wheels are twice the force. Negative is reverse.
2524
+ */
2525
+ get engineForce() {
2526
+ this.#requireLive("engineForce");
2527
+ return this.#engineForce;
2528
+ }
2529
+ set engineForce(value) {
2530
+ requireFinite(value, "engineForce");
2531
+ if (value === this.#engineForce) return;
2532
+ this.#engineForce = value;
2533
+ this.#pushInput();
2534
+ }
2535
+ /** Godot's `brake`, applied to every wheel. It is a braking impulse, not a force. */
2536
+ get brake() {
2537
+ this.#requireLive("brake");
2538
+ return this.#brake;
2539
+ }
2540
+ set brake(value) {
2541
+ requireFinite(value, "brake");
2542
+ if (value === this.#brake) return;
2543
+ this.#brake = value;
2544
+ this.#pushInput();
2545
+ }
2546
+ /** Godot's `steering`, in radians, applied to every wheel with `useAsSteering`. */
2547
+ get steering() {
2548
+ this.#requireLive("steering");
2549
+ return this.#steering;
2550
+ }
2551
+ set steering(value) {
2552
+ requireFinite(value, "steering");
2553
+ if (value === this.#steering) return;
2554
+ this.#steering = value;
2555
+ this.#pushInput();
2556
+ }
2557
+ /**
2558
+ * Signed metres per second along `forwardAxis`: positive while accelerating forward. It reflects
2559
+ * the last completed step, so read it after the physics update.
2560
+ */
2561
+ get speed() {
2562
+ return this.#state().speed;
2563
+ }
2564
+ /** Whether this wheel's suspension ray found ground on the last completed step. */
2565
+ wheelContact(index) {
2566
+ return this.#wheel(index, 0) === 1;
2567
+ }
2568
+ /** How far the wheel hangs below its attachment point, in metres. Below the rest length while loaded. */
2569
+ wheelSuspensionLength(index) {
2570
+ return this.#wheel(index, 1);
2571
+ }
2572
+ /** The wheel's spin angle in radians, for animating the mesh. */
2573
+ wheelRotation(index) {
2574
+ return this.#wheel(index, 2);
2575
+ }
2576
+ /**
2577
+ * Respawn: move the chassis, face `yaw` radians, and drop both velocities. Wheels keep their
2578
+ * cached spin, so the first frame after a rescue is one frame of stale wheel animation.
2579
+ */
2580
+ teleport(position, yaw) {
2581
+ this.#requireLive("teleport");
2582
+ if (this.#simulation.resetVehicle === void 0)
2583
+ throw new Error(
2584
+ "TN_VEHICLE_NATIVE_UNAVAILABLE: the active physics backend cannot respawn a vehicle."
2585
+ );
2586
+ requireFinite(yaw, "yaw");
2587
+ this.#simulation.resetVehicle(this.#vehicle, position, yaw);
2588
+ this.#object.position.set(position.x, position.y, position.z);
2589
+ this.#object.rotation.set(0, yaw, 0);
2590
+ this.physics?.resetInterpolation?.(this.#object);
2591
+ }
2592
+ dispose() {
2593
+ super.dispose();
2594
+ this.#disposed = true;
2595
+ }
2596
+ #pushInput() {
2597
+ if (this.#disposed) throw new Error("VehicleBody3D input cannot be used after dispose.");
2598
+ this.#setInput(this.#vehicle, {
2599
+ brake: this.#brake,
2600
+ engineForce: this.#engineForce,
2601
+ steering: this.#steering
2602
+ });
2603
+ }
2604
+ #state() {
2605
+ this.#requireLive("vehicle state");
2606
+ const state = this.#readState(this.#vehicle);
2607
+ if (state === void 0) throw new Error("TN_VEHICLE_UNKNOWN: the vehicle left the backend.");
2608
+ return state;
2609
+ }
2610
+ #wheel(index, field) {
2611
+ if (!Number.isSafeInteger(index) || index < 0 || index >= this.wheels.length)
2612
+ throw new Error(
2613
+ `TN_VEHICLE_INVALID: wheel index ${String(index)} is outside 0 through ${this.wheels.length - 1}.`
2614
+ );
2615
+ return this.#state().wheels[index * PHYSICS_VEHICLE_WHEEL_STRIDE + field] ?? 0;
2616
+ }
2617
+ #requireLive(operation) {
2618
+ if (this.#disposed) throw new Error(`VehicleBody3D.${operation} cannot be used after dispose.`);
2619
+ }
2620
+ };
1814
2621
 
1815
2622
  // src/plugin.ts
1816
2623
  var PHYSICS_DEBUG_BODY_LIMIT = 100;
@@ -1856,10 +2663,22 @@ function rapier(options = {}) {
1856
2663
  let events = new Uint32Array(64);
1857
2664
  const activeContacts = /* @__PURE__ */ new Map();
1858
2665
  let debugSeries = [];
2666
+ let completedSteps = 0;
2667
+ let gameContext;
2668
+ const interpolationRemovals = /* @__PURE__ */ new Map();
2669
+ function updateInterpolation(body) {
2670
+ interpolationRemovals.get(body)?.();
2671
+ interpolationRemovals.delete(body);
2672
+ if (body.interpolate && body.object !== void 0 && gameContext?.interpolate !== void 0)
2673
+ interpolationRemovals.set(body, gameContext.interpolate(body.object));
2674
+ }
1859
2675
  let unregisterObservations;
1860
2676
  function buildContext(selected) {
1861
2677
  return {
2678
+ resetInterpolation: (object) => gameContext?.resetInterpolation?.(object),
2679
+ updateInterpolation,
1862
2680
  add: (body) => {
2681
+ updateInterpolation(body);
1863
2682
  bodies.add(body);
1864
2683
  bodiesById.set(body.body.id, body);
1865
2684
  },
@@ -1875,6 +2694,8 @@ function rapier(options = {}) {
1875
2694
  kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
1876
2695
  numBodies: () => bodies.size,
1877
2696
  remove: (body) => {
2697
+ interpolationRemovals.get(body)?.();
2698
+ interpolationRemovals.delete(body);
1878
2699
  bodies.delete(body);
1879
2700
  bodiesById.delete(body.body.id);
1880
2701
  removeContactsFor(body.body.id);
@@ -1892,6 +2713,7 @@ function rapier(options = {}) {
1892
2713
  }
1893
2714
  return {
1894
2715
  setup: async (ctx, runtime) => {
2716
+ gameContext = ctx;
1895
2717
  await backend.initialize();
1896
2718
  const selected = backend.createSimulation(options);
1897
2719
  simulation = selected;
@@ -1932,6 +2754,7 @@ function rapier(options = {}) {
1932
2754
  };
1933
2755
  for (const buoyancy of buoyancies) buoyancy.apply(dt);
1934
2756
  simulation.step(dt, input);
2757
+ completedSteps += 1;
1935
2758
  visible = growFloat(visible, bodies.size + areas.size);
1936
2759
  let visibleResizeAttempts = 0;
1937
2760
  for (; ; ) {
@@ -2053,7 +2876,8 @@ function rapier(options = {}) {
2053
2876
  };
2054
2877
  function physicsObservations(ctx, runtime, request) {
2055
2878
  if (simulation === void 0) throw new Error("Physics observations sampled before setup.");
2056
- if (request.include?.includes("physicsDebugSeries") !== true) return {};
2879
+ if (request.include?.includes("physicsDebugSeries") !== true)
2880
+ return { physicsSteps: completedSteps };
2057
2881
  if (request.label !== void 0) {
2058
2882
  if (debugSeries.some(({ label }) => label === request.label)) {
2059
2883
  throw new Error(
@@ -2071,7 +2895,10 @@ function rapier(options = {}) {
2071
2895
  tick: runtime.tick()
2072
2896
  });
2073
2897
  }
2074
- return { physicsDebugSeries: debugSeries.map((sample) => ({ ...sample })) };
2898
+ return {
2899
+ physicsDebugSeries: debugSeries.map((sample) => ({ ...sample })),
2900
+ physicsSteps: completedSteps
2901
+ };
2075
2902
  }
2076
2903
  function physicsDebugSnapshot(ctx) {
2077
2904
  if (simulation === void 0) throw new Error("Physics observations sampled before setup.");
@@ -2163,4 +2990,4 @@ function physicsEntityId(ctx, body) {
2163
2990
  return stableId;
2164
2991
  }
2165
2992
 
2166
- export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, buildStaticColliders, interactionGroups, rapier, softBodyCollision };
2993
+ export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, VehicleBody3D, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, rapier, softBodyCollision };