@threenative/physics 0.3.12 → 0.3.15

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.
@@ -301,6 +301,11 @@ interface IPhysicsSimulation {
301
301
  */
302
302
  createVehicle?(options: IPhysicsVehicleCreateOptions): number;
303
303
  setVehicleInput?(id: number, input: IPhysicsVehicleInput): void;
304
+ /**
305
+ * Godot's `VehicleWheel3D.wheel_friction_slip` for one wheel, at runtime: the grip cap that a
306
+ * handbrake drops on the rear pair. Cold path, called on a change of grip, not per frame.
307
+ */
308
+ setVehicleWheelFriction?(id: number, wheel: number, frictionSlip: number): void;
304
309
  readVehicleState?(id: number): IPhysicsVehicleState | undefined;
305
310
  /** Cold-path respawn: move the chassis, drop both velocities, and face the given yaw in radians. */
306
311
  resetVehicle?(id: number, position: IPhysicsVector3, yaw: number): void;
@@ -846,6 +851,11 @@ interface IPhysicsContext {
846
851
  readonly y: number;
847
852
  readonly z: number;
848
853
  } | undefined;
854
+ /**
855
+ * False for ground that can move with no notice: a dynamic `RigidBody3D` or another character.
856
+ * A `CharacterBody3D` standing on such ground keeps taking its gravity step, so it follows it.
857
+ */
858
+ groundHolds?(bodyId: number): boolean;
849
859
  remove(body: PhysicsBody3D): void;
850
860
  addArea(area: Area3D): void;
851
861
  removeArea(area: Area3D): void;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { I as IPhysicsContext, a as IPhysicsWorldHandle, b as IPhysicsBodyHandle, c as IPhysicsVector3, d as IPhysicsRotation, e as IPhysicsJointLimit, R as RigidBody3D, f as IPhysicsColliderHandle, P as PhysicsBody3D, C as CollisionShape3D, g as IPhysicsVehicleWheelOptions } from './Area3D-D03tyOlF.js';
2
- export { A as Area3D, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, n as ICollisionShapeHandle, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, s as IPhysicsCharacterOptions, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, X as PhysicsQueryVector3, Y as PhysicsShapeKind, Z as RigidBodyType, _ as rapier } from './Area3D-D03tyOlF.js';
1
+ import { I as IPhysicsContext, a as IPhysicsWorldHandle, b as IPhysicsBodyHandle, c as IPhysicsVector3, d as IPhysicsRotation, e as IPhysicsJointLimit, R as RigidBody3D, f as IPhysicsColliderHandle, P as PhysicsBody3D, C as CollisionShape3D, g as IPhysicsVehicleWheelOptions } from './Area3D-BI0ynKEY.js';
2
+ export { A as Area3D, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, n as ICollisionShapeHandle, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, s as IPhysicsCharacterOptions, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, X as PhysicsQueryVector3, Y as PhysicsShapeKind, Z as RigidBodyType, _ as rapier } from './Area3D-BI0ynKEY.js';
3
3
  import { Object3D, BufferGeometry, Matrix4 } from 'three';
4
4
  import { ISoftBodyCollision } from '@threenative/core';
5
5
  import { ISnowFootprint, SnowField } from '@threenative/core/world';
@@ -309,6 +309,14 @@ declare class VehicleBody3D extends RigidBody3D {
309
309
  * the last completed step, so read it after the physics update.
310
310
  */
311
311
  get speed(): number;
312
+ /**
313
+ * Godot's `VehicleWheel3D.wheel_friction_slip`, changed while the car drives: the cap on the
314
+ * tyre's combined grip impulse, as a multiple of the load on it. Dropping the rear pair is a
315
+ * handbrake slide; restoring it is the catch. Cold path: call it when the grip changes.
316
+ */
317
+ setWheelFrictionSlip(index: number, frictionSlip: number): void;
318
+ /** The wheel's current grip cap: its construction value until `setWheelFrictionSlip` moves it. */
319
+ wheelFrictionSlip(index: number): number;
312
320
  /** Whether this wheel's suspension ray found ground on the last completed step. */
313
321
  wheelContact(index: number): boolean;
314
322
  /** How far the wheel hangs below its attachment point, in metres. Below the rest length while loaded. */
package/dist/index.js CHANGED
@@ -1,9 +1,7 @@
1
- import * as rapier from '@dimforge/rapier3d-compat';
2
- import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh, Matrix3 } from 'three';
1
+ import { Matrix4, Vector3, Quaternion, Object3D, Mesh, InstancedMesh, Matrix3 } from 'three';
2
+ import { isStreamedGeometry } from '@threenative/core';
3
3
  import { snowDiscFootprint } from '@threenative/core/world';
4
4
 
5
- // src/web.ts
6
-
7
5
  // src/collision.ts
8
6
  function interactionGroups(layer, mask) {
9
7
  if (!Number.isInteger(layer) || layer < 0 || layer > 65535)
@@ -287,57 +285,57 @@ function requirePhysicsPointQuery(value) {
287
285
  position: queryVector(query.position, "point position")
288
286
  };
289
287
  }
290
- function createWebPhysicsShape(rapier3, shape, sensor = shape.sensor) {
288
+ function createWebPhysicsShape(rapier2, shape, sensor = shape.sensor) {
291
289
  let descriptor;
292
- if (shape.kind === "box") descriptor = rapier3.ColliderDesc.cuboid(shape.x, shape.y, shape.z);
293
- else if (shape.kind === "sphere") descriptor = rapier3.ColliderDesc.ball(shape.x);
294
- else if (shape.kind === "capsule") descriptor = rapier3.ColliderDesc.capsule(shape.x, shape.y);
290
+ if (shape.kind === "box") descriptor = rapier2.ColliderDesc.cuboid(shape.x, shape.y, shape.z);
291
+ else if (shape.kind === "sphere") descriptor = rapier2.ColliderDesc.ball(shape.x);
292
+ else if (shape.kind === "capsule") descriptor = rapier2.ColliderDesc.capsule(shape.x, shape.y);
295
293
  else if (shape.kind === "trimesh") {
296
294
  if (shape.vertices === void 0 || shape.indices === void 0)
297
295
  throw new Error("CollisionShape3D.trimesh is missing mesh data.");
298
- descriptor = rapier3.ColliderDesc.trimesh(
296
+ descriptor = rapier2.ColliderDesc.trimesh(
299
297
  shape.vertices,
300
298
  shape.indices,
301
- rapier3.TriMeshFlags.FIX_INTERNAL_EDGES
299
+ rapier2.TriMeshFlags.FIX_INTERNAL_EDGES
302
300
  );
303
301
  } else if (shape.kind === "convexHull") {
304
302
  if (shape.vertices === void 0)
305
303
  throw new Error("CollisionShape3D.convexHull is missing vertices.");
306
- descriptor = rapier3.ColliderDesc.convexHull(shape.vertices);
304
+ descriptor = rapier2.ColliderDesc.convexHull(shape.vertices);
307
305
  if (descriptor === null) throw new Error("CollisionShape3D could not build a convex hull.");
308
306
  } else {
309
307
  if (shape.rows === void 0 || shape.columns === void 0 || shape.heights === void 0 || shape.scale === void 0)
310
308
  throw new Error("CollisionShape3D.heightfield is missing height data.");
311
- descriptor = rapier3.ColliderDesc.heightfield(
309
+ descriptor = rapier2.ColliderDesc.heightfield(
312
310
  shape.rows - 1,
313
311
  shape.columns - 1,
314
312
  shape.heights,
315
313
  shape.scale,
316
- rapier3.HeightFieldFlags.FIX_INTERNAL_EDGES
314
+ rapier2.HeightFieldFlags.FIX_INTERNAL_EDGES
317
315
  );
318
316
  }
319
317
  descriptor.setCollisionGroups(interactionGroups(shape.collisionLayer, shape.collisionMask));
320
318
  descriptor.setSensor(sensor);
321
- descriptor.setActiveEvents(rapier3.ActiveEvents.COLLISION_EVENTS);
319
+ descriptor.setActiveEvents(rapier2.ActiveEvents.COLLISION_EVENTS);
322
320
  return descriptor;
323
321
  }
324
- function bodyDescription(rapier3, type, position, rotation, continuousCollision) {
325
- const description = type === "fixed" ? rapier3.RigidBodyDesc.fixed() : type === "kinematic" || type === "character" ? rapier3.RigidBodyDesc.kinematicPositionBased() : rapier3.RigidBodyDesc.dynamic();
322
+ function bodyDescription(rapier2, type, position, rotation, continuousCollision) {
323
+ const description = type === "fixed" ? rapier2.RigidBodyDesc.fixed() : type === "kinematic" || type === "character" ? rapier2.RigidBodyDesc.kinematicPositionBased() : rapier2.RigidBodyDesc.dynamic();
326
324
  description.setTranslation(position.x, position.y, position.z).setRotation({ x: rotation.x, y: rotation.y, z: rotation.z, w: rotation.w });
327
325
  if (type === "dynamic") description.setCcdEnabled(continuousCollision);
328
326
  return description;
329
327
  }
330
- function jointDescription(rapier3, jointOptions) {
328
+ function jointDescription(rapier2, jointOptions) {
331
329
  if (jointOptions.type === "pin")
332
- return rapier3.JointData.spherical(jointOptions.anchorA, jointOptions.anchorB);
330
+ return rapier2.JointData.spherical(jointOptions.anchorA, jointOptions.anchorB);
333
331
  if (jointOptions.type === "hinge") {
334
- return rapier3.JointData.revolute(
332
+ return rapier2.JointData.revolute(
335
333
  jointOptions.anchorA,
336
334
  jointOptions.anchorB,
337
335
  jointOptions.axis
338
336
  );
339
337
  }
340
- return rapier3.JointData.fixed(
338
+ return rapier2.JointData.fixed(
341
339
  jointOptions.anchorA,
342
340
  jointOptions.frameA ?? { x: 0, y: 0, z: 0, w: 1 },
343
341
  jointOptions.anchorB,
@@ -1068,6 +1066,12 @@ function createWebPhysicsSimulation(options) {
1068
1066
  for (let wheel = 0; wheel < controller.numWheels(); wheel += 1)
1069
1067
  controller.setWheelBrake(wheel, input.brake);
1070
1068
  },
1069
+ setVehicleWheelFriction: (id, wheel, frictionSlip) => {
1070
+ requireLive();
1071
+ const { controller } = requireVehicle(id, "setVehicleWheelFriction");
1072
+ requireWheelFriction(wheel, frictionSlip, controller.numWheels());
1073
+ controller.setWheelFrictionSlip(wheel, frictionSlip);
1074
+ },
1071
1075
  readVehicleState: (id) => {
1072
1076
  requireLive();
1073
1077
  const record = requireVehicle(id, "readVehicleState");
@@ -1145,6 +1149,10 @@ function requirePhysicsSimulation(physics, world) {
1145
1149
  );
1146
1150
  }
1147
1151
  if (physics?.simulation !== void 0) return physics.simulation;
1152
+ if (physics === void 0 && world === void 0)
1153
+ throw new Error(
1154
+ "TN_PHYSICS_NOT_READY: `physics` is undefined. ctx.physics is set before Scene.enter(), not during load(), because Rapier initializes while the scene loads: create physics nodes in enter() or later."
1155
+ );
1148
1156
  const candidate = typeof world === "object" && world !== null && "simulation" in world ? world.simulation : world;
1149
1157
  if (typeof candidate === "object" && candidate !== null && "createBody" in candidate && typeof candidate.createBody === "function" && "step" in candidate && typeof candidate.step === "function")
1150
1158
  return candidate;
@@ -1155,19 +1163,38 @@ function requirePhysicsSimulation(physics, world) {
1155
1163
  "Physics nodes require an IPhysicsContext. Passing a raw backend world is deprecated and backend-specific."
1156
1164
  );
1157
1165
  }
1166
+ function requireWheelFriction(wheel, frictionSlip, wheels) {
1167
+ if (!Number.isSafeInteger(wheel) || wheel < 0 || wheel >= wheels)
1168
+ throw new Error(
1169
+ `TN_VEHICLE_INVALID: wheel index ${String(wheel)} is outside 0 through ${wheels - 1}.`
1170
+ );
1171
+ if (typeof frictionSlip !== "number" || !Number.isFinite(frictionSlip) || frictionSlip < 0)
1172
+ throw new Error("TN_PHYSICS_NON_FINITE: wheel friction slip must be a finite number >= 0.");
1173
+ }
1158
1174
 
1159
1175
  // src/web.ts
1176
+ var loaded;
1177
+ var rapierModule = import('@dimforge/rapier3d-compat').then((module) => {
1178
+ loaded = module;
1179
+ return module;
1180
+ });
1181
+ rapierModule.catch(() => void 0);
1182
+ var rapierReady = () => {
1183
+ if (loaded === void 0) throw new Error("Rapier used before the physics backend initialized.");
1184
+ return loaded;
1185
+ };
1160
1186
  var initialized;
1161
1187
  var simulations = /* @__PURE__ */ new WeakMap();
1162
1188
  var RAPIER_INIT_WARNING = "using deprecated parameters for the initialization function; pass a single object instead";
1163
- function initializeRapier() {
1189
+ async function initializeRapier() {
1190
+ const rapier2 = await rapierModule;
1164
1191
  const previousWarn = console.warn;
1165
1192
  console.warn = (...args) => {
1166
1193
  if (args[0] === RAPIER_INIT_WARNING) return;
1167
1194
  previousWarn(...args);
1168
1195
  };
1169
1196
  try {
1170
- return rapier.init().finally(() => {
1197
+ await rapier2.init().finally(() => {
1171
1198
  console.warn = previousWarn;
1172
1199
  });
1173
1200
  } catch (error) {
@@ -1181,11 +1208,12 @@ installPhysicsSimulationBackend({
1181
1208
  return initialized;
1182
1209
  },
1183
1210
  createSimulation: (options = {}) => {
1184
- const world = new rapier.World(options.gravity ?? { x: 0, y: -9.81, z: 0 });
1211
+ const rapier2 = rapierReady();
1212
+ const world = new rapier2.World(options.gravity ?? { x: 0, y: -9.81, z: 0 });
1185
1213
  const simulation = createWebPhysicsSimulation({
1186
- eventQueue: new rapier.EventQueue(true),
1187
- rapier,
1188
- version: rapier.version(),
1214
+ eventQueue: new rapier2.EventQueue(true),
1215
+ rapier: rapier2,
1216
+ version: rapier2.version(),
1189
1217
  world
1190
1218
  });
1191
1219
  simulations.set(world, simulation);
@@ -1196,16 +1224,17 @@ installPhysicsSimulationBackend({
1196
1224
  throw new Error("Physics nodes expected a Rapier World.");
1197
1225
  const simulation = simulations.get(world);
1198
1226
  if (simulation !== void 0) return simulation;
1227
+ const rapier2 = rapierReady();
1199
1228
  const created = createWebPhysicsSimulation({
1200
- eventQueue: new rapier.EventQueue(true),
1201
- rapier,
1202
- version: rapier.version(),
1229
+ eventQueue: new rapier2.EventQueue(true),
1230
+ rapier: rapier2,
1231
+ version: rapier2.version(),
1203
1232
  world
1204
1233
  });
1205
1234
  simulations.set(world, created);
1206
1235
  return created;
1207
1236
  },
1208
- createShape: (shape) => createWebPhysicsShape(rapier, shape)
1237
+ createShape: (shape) => createWebPhysicsShape(rapierReady(), shape)
1209
1238
  });
1210
1239
 
1211
1240
  // src/transformRecord.ts
@@ -1357,6 +1386,11 @@ var Area3D = class {
1357
1386
  this.#listeners.bodyExited.clear();
1358
1387
  }
1359
1388
  };
1389
+ var SEAT_LIFT = 1e-3;
1390
+ var SEAT_BAND = 2e-4;
1391
+ var SEAT_STOPPED = 5e-5;
1392
+ var SEAT_LIFTS = 16;
1393
+ var SEAT_GROUND_Y = Math.cos(Math.PI / 4 - Math.PI / 18);
1360
1394
  function halfHeightOf(shape) {
1361
1395
  const { kind, x, y } = shape.descriptor;
1362
1396
  return kind === "capsule" ? x + y : kind === "box" ? y : kind === "sphere" ? x : void 0;
@@ -1405,6 +1439,13 @@ var CharacterBody3D = class {
1405
1439
  #groundCollider;
1406
1440
  #beforeY = 0;
1407
1441
  #desiredY = 0;
1442
+ #still = false;
1443
+ #seat = 0 /* Step */;
1444
+ #lifts = 0;
1445
+ /** Where the last step started, and the solver's pose after it with the pose the object was given. */
1446
+ #from = { x: 0, y: 0, z: 0 };
1447
+ #solved = { x: 0, y: 0, z: 0 };
1448
+ #shown = { x: 0, y: 0, z: 0 };
1408
1449
  #disposed = false;
1409
1450
  #interpolate = true;
1410
1451
  /** Draw between solved ticks; false presents this body at its true tick pose. */
@@ -1526,21 +1567,43 @@ var CharacterBody3D = class {
1526
1567
  /** Called by the shared plugin before a bulk step. */
1527
1568
  writeKinematic(buffer, offset) {
1528
1569
  if (this.#disposed) return;
1529
- this.#beforeY = this.object.position.y;
1530
1570
  this.#desiredY = this.#desired.y;
1531
1571
  const carry = this.#sliding && this.grounded && this.velocity.y <= 0 && this.#groundCollider !== void 0 ? this.#physics?.kinematicMotion?.(this.#groundCollider) : void 0;
1532
1572
  const carryX = carry?.x ?? 0;
1533
1573
  const carryY = carry?.y ?? 0;
1534
1574
  const carryZ = carry?.z ?? 0;
1575
+ this.#still = this.#sliding && this.grounded && this.#desired.x === 0 && this.#desired.z === 0 && // Seating lets the gravity step land a lifted body: with no gravity step there is nothing to
1576
+ // seat, and a lift would never come back down.
1577
+ this.#desired.y < 0 && carryX === 0 && carryY === 0 && carryZ === 0 && (this.groundBody === void 0 || this.#physics?.groundHolds?.(this.groundBody.id) !== false);
1578
+ const from = this.#startPose();
1579
+ this.#from.x = from.x;
1580
+ this.#from.y = from.y;
1581
+ this.#from.z = from.z;
1582
+ this.#beforeY = from.y;
1583
+ if (!this.#still) this.#seat = 0 /* Step */;
1584
+ const travelY = this.#seat === 3 /* Rest */ ? 0 : this.#seat === 1 /* Lift */ ? Math.min(SEAT_LIFT, -this.#desired.y) : this.#desired.y;
1535
1585
  buffer[offset] = this.body.id;
1536
- buffer[offset + 1] = this.object.position.x + this.#desired.x + carryX;
1537
- buffer[offset + 2] = this.object.position.y + this.#desired.y + carryY;
1538
- buffer[offset + 3] = this.object.position.z + this.#desired.z + carryZ;
1586
+ buffer[offset + 1] = from.x + this.#desired.x + carryX;
1587
+ buffer[offset + 2] = from.y + travelY + carryY;
1588
+ buffer[offset + 3] = from.z + this.#desired.z + carryZ;
1539
1589
  buffer[offset + 4] = this.object.quaternion.x;
1540
1590
  buffer[offset + 5] = this.object.quaternion.y;
1541
1591
  buffer[offset + 6] = this.object.quaternion.z;
1542
1592
  buffer[offset + 7] = this.object.quaternion.w;
1543
1593
  }
1594
+ /**
1595
+ * Where this step starts. A lift is not shown, so the object can trail the body by one step and
1596
+ * the step then starts from the solver's pose. A body that moves from the middle of a seating
1597
+ * cycle leaves the unshown lift behind and starts from the pose the player sees, so a jump rises
1598
+ * the same height on every step of the cycle. An object the game moved itself starts from where
1599
+ * the game put it.
1600
+ */
1601
+ #startPose() {
1602
+ const at = this.object.position;
1603
+ const shown = this.#shown;
1604
+ const trailing = at.x === shown.x && at.y === shown.y && at.z === shown.z;
1605
+ return trailing && (this.#still || this.#seat !== 2 /* Check */) ? this.#solved : at;
1606
+ }
1544
1607
  syncToPhysics() {
1545
1608
  }
1546
1609
  step() {
@@ -1576,7 +1639,15 @@ var CharacterBody3D = class {
1576
1639
  this.#clearGroundState();
1577
1640
  }
1578
1641
  if (this.#sliding && this.grounded && this.velocity.y < 0) this.velocity.y = 0;
1579
- this.object.position.set(x, y, z);
1642
+ const lifted = this.#seat === 1 /* Lift */;
1643
+ this.#seated(x - this.#from.x, y - this.#from.y, z - this.#from.z);
1644
+ this.#solved.x = x;
1645
+ this.#solved.y = y;
1646
+ this.#solved.z = z;
1647
+ if (!lifted) this.object.position.set(x, y, z);
1648
+ this.#shown.x = this.object.position.x;
1649
+ this.#shown.y = this.object.position.y;
1650
+ this.#shown.z = this.object.position.z;
1580
1651
  setRotationIfChanged(this.object.quaternion, qx, qy, qz, qw);
1581
1652
  this.#desired.x = 0;
1582
1653
  this.#desired.y = 0;
@@ -1637,6 +1708,24 @@ var CharacterBody3D = class {
1637
1708
  this.swimming = this.immersionDepth > 0.5;
1638
1709
  return this.immersionDepth;
1639
1710
  }
1711
+ /** Advances the seat from the solver's answer to the step that just ran. */
1712
+ #seated(dx, dy, dz) {
1713
+ if (this.#seat === 3 /* Rest */ && this.#still && this.grounded) return;
1714
+ const band = Math.max(SEAT_BAND, -0.25 * this.#desiredY);
1715
+ if (!this.#still || !this.grounded || this.groundNormal.y < SEAT_GROUND_Y || Math.abs(dx) >= band || Math.abs(dz) >= band) {
1716
+ this.#seat = 0 /* Step */;
1717
+ this.#lifts = 0;
1718
+ } else if (this.#seat === 0 /* Step */) {
1719
+ if (Math.abs(dy) < band) this.#seat = 1 /* Lift */;
1720
+ } else if (this.#seat === 1 /* Lift */) {
1721
+ this.#seat = 2 /* Check */;
1722
+ } else if (dy >= 0) {
1723
+ this.#lifts += 1;
1724
+ this.#seat = this.#lifts < SEAT_LIFTS ? 1 /* Lift */ : 3 /* Rest */;
1725
+ } else if (dy > this.#desiredY + SEAT_STOPPED) {
1726
+ this.#seat = 3 /* Rest */;
1727
+ }
1728
+ }
1640
1729
  #clearGroundState() {
1641
1730
  this.grounded = false;
1642
1731
  this.#groundCollider = void 0;
@@ -1645,24 +1734,39 @@ var CharacterBody3D = class {
1645
1734
  this.slopeAngle = 0;
1646
1735
  }
1647
1736
  };
1648
-
1649
- // src/CollisionShape3D.ts
1737
+ function attributeStorage(attribute, itemSize) {
1738
+ if (attribute.isInterleavedBufferAttribute === true) return void 0;
1739
+ if (attribute.normalized || attribute.itemSize !== itemSize) return void 0;
1740
+ return attribute.array.length === attribute.count * itemSize ? attribute.array : void 0;
1741
+ }
1650
1742
  function geometryVertices(mesh) {
1651
1743
  const position = mesh.geometry.getAttribute("position");
1652
1744
  if (position === void 0)
1653
1745
  throw new Error("CollisionShape3D.fromMesh requires vertex positions.");
1654
1746
  const vertices = new Float32Array(position.count * 3);
1655
- for (let index = 0; index < position.count; index++) {
1656
- vertices[index * 3] = position.getX(index) * mesh.scale.x;
1657
- vertices[index * 3 + 1] = position.getY(index) * mesh.scale.y;
1658
- vertices[index * 3 + 2] = position.getZ(index) * mesh.scale.z;
1747
+ const storage = attributeStorage(position, 3);
1748
+ if (storage === void 0)
1749
+ for (let index = 0; index < position.count; index++) {
1750
+ vertices[index * 3] = position.getX(index);
1751
+ vertices[index * 3 + 1] = position.getY(index);
1752
+ vertices[index * 3 + 2] = position.getZ(index);
1753
+ }
1754
+ else vertices.set(storage);
1755
+ const { x, y, z } = mesh.scale;
1756
+ if (x === 1 && y === 1 && z === 1) return vertices;
1757
+ for (let index = 0; index < vertices.length; index += 3) {
1758
+ vertices[index] = vertices[index] * x;
1759
+ vertices[index + 1] = vertices[index + 1] * y;
1760
+ vertices[index + 2] = vertices[index + 2] * z;
1659
1761
  }
1660
1762
  return vertices;
1661
1763
  }
1662
1764
  function geometryIndices(mesh) {
1663
1765
  const index = mesh.geometry.getIndex();
1664
- if (index !== null)
1665
- return Uint32Array.from({ length: index.count }, (_, offset) => index.getX(offset));
1766
+ if (index !== null) {
1767
+ const storage = attributeStorage(index, 1);
1768
+ return storage === void 0 ? Uint32Array.from({ length: index.count }, (_, offset) => index.getX(offset)) : Uint32Array.from(storage);
1769
+ }
1666
1770
  const count = mesh.geometry.getAttribute("position")?.count ?? 0;
1667
1771
  if (count === 0 || count % 3 !== 0)
1668
1772
  throw new Error("CollisionShape3D.fromMesh requires triangle indices.");
@@ -1800,6 +1904,10 @@ var CollisionShape3D = class _CollisionShape3D {
1800
1904
  }
1801
1905
  static fromMesh(mesh, kind) {
1802
1906
  const geometry = mesh.geometry;
1907
+ if ((kind === "trimesh" || kind === "convexHull") && isStreamedGeometry(geometry))
1908
+ console.warn(
1909
+ `TN_COLLIDER_COARSE: CollisionShape3D.fromMesh(${JSON.stringify(mesh.name)}, "${kind}") copies the streamed coarse model's vertices; load it with ctx.assets.model(path, { whole: true }) to collide with the full one.`
1910
+ );
1803
1911
  const inferred = kind ?? (geometry.type.toLowerCase().includes("sphere") ? "sphere" : geometry.type.toLowerCase().includes("capsule") ? "capsule" : "box");
1804
1912
  if (inferred === "trimesh")
1805
1913
  return new _CollisionShape3D({
@@ -2337,7 +2445,6 @@ var scratchWorld = new Matrix4();
2337
2445
  var scratchPosition = new Vector3();
2338
2446
  var scratchScale = new Vector3();
2339
2447
  var scratchRotation = new Quaternion();
2340
- var scratchBounds = new Box3();
2341
2448
  function optionsFor(filter) {
2342
2449
  return typeof filter === "function" ? { predicate: filter } : filter ?? {};
2343
2450
  }
@@ -2365,8 +2472,14 @@ function configureCarrier(carrier, transform, scale) {
2365
2472
  carrier.updateMatrixWorld(true);
2366
2473
  }
2367
2474
  function isReachable(carrier, ceiling) {
2368
- scratchBounds.setFromObject(carrier, true);
2369
- return !scratchBounds.isEmpty() && scratchBounds.min.y < ceiling;
2475
+ const position = carrier.geometry.getAttribute("position");
2476
+ if (position === void 0 || position.count === 0) return false;
2477
+ const e = carrier.matrixWorld.elements;
2478
+ const [m1, m5, m9, m13] = [e[1] ?? 0, e[5] ?? 0, e[9] ?? 0, e[13] ?? 0];
2479
+ for (let i = 0; i < position.count; i++)
2480
+ if (m1 * position.getX(i) + m5 * position.getY(i) + m9 * position.getZ(i) + m13 < ceiling)
2481
+ return true;
2482
+ return false;
2370
2483
  }
2371
2484
  function addCollider(context, source, transform, options) {
2372
2485
  const carrier = new Mesh(source.geometry);
@@ -2876,7 +2989,7 @@ function attachSnowPhysics(options) {
2876
2989
  let contacts = 0;
2877
2990
  let supported = 0;
2878
2991
  let load = 0;
2879
- let version2 = snow.version;
2992
+ let version = snow.version;
2880
2993
  let disposed = false;
2881
2994
  function surfaceDescriptor() {
2882
2995
  return {
@@ -3025,7 +3138,7 @@ function attachSnowPhysics(options) {
3025
3138
  return surfaceVersion;
3026
3139
  },
3027
3140
  get version() {
3028
- return version2;
3141
+ return version;
3029
3142
  },
3030
3143
  observe() {
3031
3144
  return {
@@ -3056,7 +3169,7 @@ function attachSnowPhysics(options) {
3056
3169
  const wind = Math.max(0, finiteOr(binding.wind, 0, "wind"));
3057
3170
  if (deposition > 0 || wind > 0) snow.recover(deltaTime, deposition, wind);
3058
3171
  refreshSurface();
3059
- version2 = snow.version;
3172
+ version = snow.version;
3060
3173
  },
3061
3174
  dispose() {
3062
3175
  if (disposed) return;
@@ -3118,7 +3231,8 @@ function visibleId(buffer, offset) {
3118
3231
  throw new Error("IPhysicsSimulation returned an invalid visible body id.");
3119
3232
  return value;
3120
3233
  }
3121
- function rapier2(options = {}) {
3234
+ var PHYSICS_READY = /* @__PURE__ */ Symbol.for("threenative.physics.ready");
3235
+ function rapier(options = {}) {
3122
3236
  const backend = physicsSimulationBackend();
3123
3237
  let simulation;
3124
3238
  let context;
@@ -3139,6 +3253,7 @@ function rapier2(options = {}) {
3139
3253
  let debugSeries = [];
3140
3254
  let completedSteps = 0;
3141
3255
  let gameContext;
3256
+ let generations = 0;
3142
3257
  const interpolationRemovals = /* @__PURE__ */ new Map();
3143
3258
  function updateInterpolation(body) {
3144
3259
  interpolationRemovals.get(body)?.();
@@ -3166,6 +3281,10 @@ function rapier2(options = {}) {
3166
3281
  addBuoyancy: (buoyancy) => buoyancies.add(buoyancy),
3167
3282
  eventQueue: physicsHandle(selected.rawEventQueue),
3168
3283
  kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
3284
+ groundHolds: (bodyId2) => {
3285
+ const ground = bodiesById.get(bodyId2);
3286
+ return ground === void 0 || ground instanceof RigidBody3D && ground.type !== "dynamic";
3287
+ },
3169
3288
  numBodies: () => bodies.size,
3170
3289
  remove: (body) => {
3171
3290
  interpolationRemovals.get(body)?.();
@@ -3186,19 +3305,36 @@ function rapier2(options = {}) {
3186
3305
  };
3187
3306
  }
3188
3307
  return {
3189
- setup: async (ctx, runtime) => {
3308
+ // Rapier's Wasm initializes while the scene loads: a game builds bodies in `enter()`, and the
3309
+ // start gate holds `enter()` until `ctx.physics` is set, so a first visit does not wait for
3310
+ // Rapier before loading its textures and world (PRD-860). With no gate, setup awaits it.
3311
+ setup: (ctx, runtime) => {
3190
3312
  gameContext = ctx;
3191
- await backend.initialize();
3192
- const selected = backend.createSimulation(options);
3193
- simulation = selected;
3194
- if (runtime !== void 0) runtime.rapier = selected.version;
3195
- context = buildContext(selected);
3196
- ctx.physics = context;
3197
- unregisterObservations = runtime?.observations?.contribute({
3198
- capabilities: ["runtime.physics"],
3199
- sample: (request) => physicsObservations(ctx, runtime, request)
3313
+ const generation = ++generations;
3314
+ const ready = backend.initialize().then(() => {
3315
+ if (generation !== generations) {
3316
+ console.warn(
3317
+ "TN_PHYSICS_SETUP_SUPERSEDED: rapier initialized after its game was disposed; nothing was installed."
3318
+ );
3319
+ return void 0;
3320
+ }
3321
+ const selected = backend.createSimulation(options);
3322
+ simulation = selected;
3323
+ if (runtime !== void 0) runtime.rapier = selected.version;
3324
+ const built = buildContext(selected);
3325
+ context = built;
3326
+ ctx.physics = built;
3327
+ unregisterObservations = runtime?.observations?.contribute({
3328
+ capabilities: ["runtime.physics"],
3329
+ sample: (request) => physicsObservations(ctx, runtime, request)
3330
+ });
3331
+ return built;
3200
3332
  });
3201
- return unregisterObservations;
3333
+ Object.defineProperty(ctx, PHYSICS_READY, { configurable: true, value: ready });
3334
+ const cleanup = () => unregisterObservations?.();
3335
+ if (runtime?.holdStart === void 0) return ready.then(() => cleanup);
3336
+ void runtime.holdStart(ready.then(() => void 0)).catch(() => void 0);
3337
+ return cleanup;
3202
3338
  },
3203
3339
  update: (_ctx, dt) => {
3204
3340
  if (simulation === void 0) throw new Error("Physics plugin updated before setup.");
@@ -3330,6 +3466,7 @@ function rapier2(options = {}) {
3330
3466
  ctx.physics = context;
3331
3467
  },
3332
3468
  dispose: () => {
3469
+ generations += 1;
3333
3470
  unregisterObservations?.();
3334
3471
  unregisterObservations = void 0;
3335
3472
  for (const buoyancy of [...buoyancies]) buoyancy.dispose();
@@ -3486,6 +3623,7 @@ var VehicleBody3D = class extends RigidBody3D {
3486
3623
  #brake = 0;
3487
3624
  #steering = 0;
3488
3625
  #disposed = false;
3626
+ #friction;
3489
3627
  constructor(options) {
3490
3628
  const forward = FORWARD_AXES[options.forwardAxis ?? "-z"];
3491
3629
  if (forward === void 0)
@@ -3512,6 +3650,7 @@ var VehicleBody3D = class extends RigidBody3D {
3512
3650
  world: options.world
3513
3651
  });
3514
3652
  this.wheels = options.wheels;
3653
+ this.#friction = options.wheels.map((wheel) => wheel.wheelFrictionSlip);
3515
3654
  this.#object = options.object;
3516
3655
  this.#simulation = simulation;
3517
3656
  this.#readState = readVehicleState;
@@ -3571,6 +3710,26 @@ var VehicleBody3D = class extends RigidBody3D {
3571
3710
  get speed() {
3572
3711
  return this.#state().speed;
3573
3712
  }
3713
+ /**
3714
+ * Godot's `VehicleWheel3D.wheel_friction_slip`, changed while the car drives: the cap on the
3715
+ * tyre's combined grip impulse, as a multiple of the load on it. Dropping the rear pair is a
3716
+ * handbrake slide; restoring it is the catch. Cold path: call it when the grip changes.
3717
+ */
3718
+ setWheelFrictionSlip(index, frictionSlip) {
3719
+ this.#requireLive("setWheelFrictionSlip");
3720
+ const set = this.#simulation.setVehicleWheelFriction;
3721
+ if (set === void 0)
3722
+ throw new Error(
3723
+ "TN_VEHICLE_NATIVE_UNAVAILABLE: the active physics backend cannot change wheel grip."
3724
+ );
3725
+ set.call(this.#simulation, this.#vehicle, index, frictionSlip);
3726
+ this.#friction[index] = frictionSlip;
3727
+ }
3728
+ /** The wheel's current grip cap: its construction value until `setWheelFrictionSlip` moves it. */
3729
+ wheelFrictionSlip(index) {
3730
+ this.#wheel(index, 0);
3731
+ return this.#friction[index];
3732
+ }
3574
3733
  /** Whether this wheel's suspension ray found ground on the last completed step. */
3575
3734
  wheelContact(index) {
3576
3735
  return this.#wheel(index, 0) === 1;
@@ -3629,4 +3788,4 @@ var VehicleBody3D = class extends RigidBody3D {
3629
3788
  }
3630
3789
  };
3631
3790
 
3632
- export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, ScatterColliders, VehicleBody3D, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, rapier2 as rapier, softBodyCollision };
3791
+ export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, ScatterColliders, VehicleBody3D, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, rapier, softBodyCollision };
@@ -1,4 +1,4 @@
1
- export { A as Area3D, $ as AreaEvent, a0 as AreaHandler, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, C as CollisionShape3D, a1 as CollisionShapeKind, a2 as IArea3DOptions, a3 as IAreaContact, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, a4 as ICharacterBody3DOptions, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, b as IPhysicsBodyHandle, s as IPhysicsCharacterOptions, f as IPhysicsColliderHandle, I as IPhysicsContext, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, e as IPhysicsJointLimit, a5 as IPhysicsOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, d as IPhysicsRotation, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, c as IPhysicsVector3, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, a as IPhysicsWorldHandle, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, P as PhysicsBody3D, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, a6 as PhysicsPlugin, X as PhysicsQueryVector3, Y as PhysicsShapeKind, R as RigidBody3D, Z as RigidBodyType, _ as rapier } from '../Area3D-D03tyOlF.js';
1
+ export { A as Area3D, $ as AreaEvent, a0 as AreaHandler, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, C as CollisionShape3D, a1 as CollisionShapeKind, a2 as IArea3DOptions, a3 as IAreaContact, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, a4 as ICharacterBody3DOptions, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, b as IPhysicsBodyHandle, s as IPhysicsCharacterOptions, f as IPhysicsColliderHandle, I as IPhysicsContext, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, e as IPhysicsJointLimit, a5 as IPhysicsOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, d as IPhysicsRotation, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, c as IPhysicsVector3, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, a as IPhysicsWorldHandle, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, P as PhysicsBody3D, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, a6 as PhysicsPlugin, X as PhysicsQueryVector3, Y as PhysicsShapeKind, R as RigidBody3D, Z as RigidBodyType, _ as rapier } from '../Area3D-BI0ynKEY.js';
2
2
  export { IBuildStaticCollidersOptions, IFixedJoint3DOptions, IHingeJoint3DOptions, IJoint3DOptions, IPinJoint3DOptions, IScatterColliderInstance, IScatterCollidersOptions, IScatterCollidersStats, ISnowPhysicsBinding, ISnowPhysicsObservation, ISnowPhysicsOptions, IStaticColliderContext, IVehicleBody3DOptions, IVehicleWheel3D, Joint3D, PhysicsJointBody, ScatterColliders, ScatterCollision, StaticColliderPredicate, VehicleBody3D, VehicleForwardAxis, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, softBodyCollision } from '../index.js';
3
3
  import 'three';
4
4
  import '@threenative/core';
@@ -1,4 +1,5 @@
1
- import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh, Matrix3 } from 'three';
1
+ import { Matrix4, Vector3, Quaternion, Object3D, Mesh, InstancedMesh, Matrix3 } from 'three';
2
+ import { isStreamedGeometry } from '@threenative/core';
2
3
  import { snowDiscFootprint } from '@threenative/core/world';
3
4
 
4
5
  // src/handles.ts
@@ -270,6 +271,10 @@ function requirePhysicsSimulation(physics, world) {
270
271
  );
271
272
  }
272
273
  if (physics?.simulation !== void 0) return physics.simulation;
274
+ if (physics === void 0 && world === void 0)
275
+ throw new Error(
276
+ "TN_PHYSICS_NOT_READY: `physics` is undefined. ctx.physics is set before Scene.enter(), not during load(), because Rapier initializes while the scene loads: create physics nodes in enter() or later."
277
+ );
273
278
  const candidate = typeof world === "object" && world !== null && "simulation" in world ? world.simulation : world;
274
279
  if (typeof candidate === "object" && candidate !== null && "createBody" in candidate && typeof candidate.createBody === "function" && "step" in candidate && typeof candidate.step === "function")
275
280
  return candidate;
@@ -280,6 +285,14 @@ function requirePhysicsSimulation(physics, world) {
280
285
  "Physics nodes require an IPhysicsContext. Passing a raw backend world is deprecated and backend-specific."
281
286
  );
282
287
  }
288
+ function requireWheelFriction(wheel, frictionSlip, wheels) {
289
+ if (!Number.isSafeInteger(wheel) || wheel < 0 || wheel >= wheels)
290
+ throw new Error(
291
+ `TN_VEHICLE_INVALID: wheel index ${String(wheel)} is outside 0 through ${wheels - 1}.`
292
+ );
293
+ if (typeof frictionSlip !== "number" || !Number.isFinite(frictionSlip) || frictionSlip < 0)
294
+ throw new Error("TN_PHYSICS_NON_FINITE: wheel friction slip must be a finite number >= 0.");
295
+ }
283
296
 
284
297
  // src/native/host.ts
285
298
  function nativePhysicsHost() {
@@ -833,6 +846,18 @@ function createNativePhysicsSimulation(raw, version) {
833
846
  requireVehicle(id, "setVehicleInput");
834
847
  raw.setVehicleInput(id, input);
835
848
  },
849
+ setVehicleWheelFriction: (id, wheel, frictionSlip) => {
850
+ requireLive();
851
+ if (raw.setVehicleWheelFriction === void 0)
852
+ throw new Error("TN_NATIVE_PHYSICS_VEHICLE_MISSING: runtime ABI is too old");
853
+ const record = requireVehicle(id, "setVehicleWheelFriction");
854
+ requireWheelFriction(
855
+ wheel,
856
+ frictionSlip,
857
+ (record.buffer.length - 1) / PHYSICS_VEHICLE_WHEEL_STRIDE
858
+ );
859
+ raw.setVehicleWheelFriction(id, wheel, frictionSlip);
860
+ },
836
861
  readVehicleState: (id) => {
837
862
  requireLive();
838
863
  if (raw.readVehicleState === void 0)
@@ -1054,6 +1079,11 @@ var Area3D = class {
1054
1079
  this.#listeners.bodyExited.clear();
1055
1080
  }
1056
1081
  };
1082
+ var SEAT_LIFT = 1e-3;
1083
+ var SEAT_BAND = 2e-4;
1084
+ var SEAT_STOPPED = 5e-5;
1085
+ var SEAT_LIFTS = 16;
1086
+ var SEAT_GROUND_Y = Math.cos(Math.PI / 4 - Math.PI / 18);
1057
1087
  function halfHeightOf(shape) {
1058
1088
  const { kind, x, y } = shape.descriptor;
1059
1089
  return kind === "capsule" ? x + y : kind === "box" ? y : kind === "sphere" ? x : void 0;
@@ -1102,6 +1132,13 @@ var CharacterBody3D = class {
1102
1132
  #groundCollider;
1103
1133
  #beforeY = 0;
1104
1134
  #desiredY = 0;
1135
+ #still = false;
1136
+ #seat = 0 /* Step */;
1137
+ #lifts = 0;
1138
+ /** Where the last step started, and the solver's pose after it with the pose the object was given. */
1139
+ #from = { x: 0, y: 0, z: 0 };
1140
+ #solved = { x: 0, y: 0, z: 0 };
1141
+ #shown = { x: 0, y: 0, z: 0 };
1105
1142
  #disposed = false;
1106
1143
  #interpolate = true;
1107
1144
  /** Draw between solved ticks; false presents this body at its true tick pose. */
@@ -1223,21 +1260,43 @@ var CharacterBody3D = class {
1223
1260
  /** Called by the shared plugin before a bulk step. */
1224
1261
  writeKinematic(buffer, offset) {
1225
1262
  if (this.#disposed) return;
1226
- this.#beforeY = this.object.position.y;
1227
1263
  this.#desiredY = this.#desired.y;
1228
1264
  const carry = this.#sliding && this.grounded && this.velocity.y <= 0 && this.#groundCollider !== void 0 ? this.#physics?.kinematicMotion?.(this.#groundCollider) : void 0;
1229
1265
  const carryX = carry?.x ?? 0;
1230
1266
  const carryY = carry?.y ?? 0;
1231
1267
  const carryZ = carry?.z ?? 0;
1268
+ this.#still = this.#sliding && this.grounded && this.#desired.x === 0 && this.#desired.z === 0 && // Seating lets the gravity step land a lifted body: with no gravity step there is nothing to
1269
+ // seat, and a lift would never come back down.
1270
+ this.#desired.y < 0 && carryX === 0 && carryY === 0 && carryZ === 0 && (this.groundBody === void 0 || this.#physics?.groundHolds?.(this.groundBody.id) !== false);
1271
+ const from = this.#startPose();
1272
+ this.#from.x = from.x;
1273
+ this.#from.y = from.y;
1274
+ this.#from.z = from.z;
1275
+ this.#beforeY = from.y;
1276
+ if (!this.#still) this.#seat = 0 /* Step */;
1277
+ const travelY = this.#seat === 3 /* Rest */ ? 0 : this.#seat === 1 /* Lift */ ? Math.min(SEAT_LIFT, -this.#desired.y) : this.#desired.y;
1232
1278
  buffer[offset] = this.body.id;
1233
- buffer[offset + 1] = this.object.position.x + this.#desired.x + carryX;
1234
- buffer[offset + 2] = this.object.position.y + this.#desired.y + carryY;
1235
- buffer[offset + 3] = this.object.position.z + this.#desired.z + carryZ;
1279
+ buffer[offset + 1] = from.x + this.#desired.x + carryX;
1280
+ buffer[offset + 2] = from.y + travelY + carryY;
1281
+ buffer[offset + 3] = from.z + this.#desired.z + carryZ;
1236
1282
  buffer[offset + 4] = this.object.quaternion.x;
1237
1283
  buffer[offset + 5] = this.object.quaternion.y;
1238
1284
  buffer[offset + 6] = this.object.quaternion.z;
1239
1285
  buffer[offset + 7] = this.object.quaternion.w;
1240
1286
  }
1287
+ /**
1288
+ * Where this step starts. A lift is not shown, so the object can trail the body by one step and
1289
+ * the step then starts from the solver's pose. A body that moves from the middle of a seating
1290
+ * cycle leaves the unshown lift behind and starts from the pose the player sees, so a jump rises
1291
+ * the same height on every step of the cycle. An object the game moved itself starts from where
1292
+ * the game put it.
1293
+ */
1294
+ #startPose() {
1295
+ const at = this.object.position;
1296
+ const shown = this.#shown;
1297
+ const trailing = at.x === shown.x && at.y === shown.y && at.z === shown.z;
1298
+ return trailing && (this.#still || this.#seat !== 2 /* Check */) ? this.#solved : at;
1299
+ }
1241
1300
  syncToPhysics() {
1242
1301
  }
1243
1302
  step() {
@@ -1273,7 +1332,15 @@ var CharacterBody3D = class {
1273
1332
  this.#clearGroundState();
1274
1333
  }
1275
1334
  if (this.#sliding && this.grounded && this.velocity.y < 0) this.velocity.y = 0;
1276
- this.object.position.set(x, y, z);
1335
+ const lifted = this.#seat === 1 /* Lift */;
1336
+ this.#seated(x - this.#from.x, y - this.#from.y, z - this.#from.z);
1337
+ this.#solved.x = x;
1338
+ this.#solved.y = y;
1339
+ this.#solved.z = z;
1340
+ if (!lifted) this.object.position.set(x, y, z);
1341
+ this.#shown.x = this.object.position.x;
1342
+ this.#shown.y = this.object.position.y;
1343
+ this.#shown.z = this.object.position.z;
1277
1344
  setRotationIfChanged(this.object.quaternion, qx, qy, qz, qw);
1278
1345
  this.#desired.x = 0;
1279
1346
  this.#desired.y = 0;
@@ -1334,6 +1401,24 @@ var CharacterBody3D = class {
1334
1401
  this.swimming = this.immersionDepth > 0.5;
1335
1402
  return this.immersionDepth;
1336
1403
  }
1404
+ /** Advances the seat from the solver's answer to the step that just ran. */
1405
+ #seated(dx, dy, dz) {
1406
+ if (this.#seat === 3 /* Rest */ && this.#still && this.grounded) return;
1407
+ const band = Math.max(SEAT_BAND, -0.25 * this.#desiredY);
1408
+ if (!this.#still || !this.grounded || this.groundNormal.y < SEAT_GROUND_Y || Math.abs(dx) >= band || Math.abs(dz) >= band) {
1409
+ this.#seat = 0 /* Step */;
1410
+ this.#lifts = 0;
1411
+ } else if (this.#seat === 0 /* Step */) {
1412
+ if (Math.abs(dy) < band) this.#seat = 1 /* Lift */;
1413
+ } else if (this.#seat === 1 /* Lift */) {
1414
+ this.#seat = 2 /* Check */;
1415
+ } else if (dy >= 0) {
1416
+ this.#lifts += 1;
1417
+ this.#seat = this.#lifts < SEAT_LIFTS ? 1 /* Lift */ : 3 /* Rest */;
1418
+ } else if (dy > this.#desiredY + SEAT_STOPPED) {
1419
+ this.#seat = 3 /* Rest */;
1420
+ }
1421
+ }
1337
1422
  #clearGroundState() {
1338
1423
  this.grounded = false;
1339
1424
  this.#groundCollider = void 0;
@@ -1342,24 +1427,39 @@ var CharacterBody3D = class {
1342
1427
  this.slopeAngle = 0;
1343
1428
  }
1344
1429
  };
1345
-
1346
- // src/CollisionShape3D.ts
1430
+ function attributeStorage(attribute, itemSize) {
1431
+ if (attribute.isInterleavedBufferAttribute === true) return void 0;
1432
+ if (attribute.normalized || attribute.itemSize !== itemSize) return void 0;
1433
+ return attribute.array.length === attribute.count * itemSize ? attribute.array : void 0;
1434
+ }
1347
1435
  function geometryVertices(mesh) {
1348
1436
  const position = mesh.geometry.getAttribute("position");
1349
1437
  if (position === void 0)
1350
1438
  throw new Error("CollisionShape3D.fromMesh requires vertex positions.");
1351
1439
  const vertices = new Float32Array(position.count * 3);
1352
- for (let index = 0; index < position.count; index++) {
1353
- vertices[index * 3] = position.getX(index) * mesh.scale.x;
1354
- vertices[index * 3 + 1] = position.getY(index) * mesh.scale.y;
1355
- vertices[index * 3 + 2] = position.getZ(index) * mesh.scale.z;
1440
+ const storage = attributeStorage(position, 3);
1441
+ if (storage === void 0)
1442
+ for (let index = 0; index < position.count; index++) {
1443
+ vertices[index * 3] = position.getX(index);
1444
+ vertices[index * 3 + 1] = position.getY(index);
1445
+ vertices[index * 3 + 2] = position.getZ(index);
1446
+ }
1447
+ else vertices.set(storage);
1448
+ const { x, y, z } = mesh.scale;
1449
+ if (x === 1 && y === 1 && z === 1) return vertices;
1450
+ for (let index = 0; index < vertices.length; index += 3) {
1451
+ vertices[index] = vertices[index] * x;
1452
+ vertices[index + 1] = vertices[index + 1] * y;
1453
+ vertices[index + 2] = vertices[index + 2] * z;
1356
1454
  }
1357
1455
  return vertices;
1358
1456
  }
1359
1457
  function geometryIndices(mesh) {
1360
1458
  const index = mesh.geometry.getIndex();
1361
- if (index !== null)
1362
- return Uint32Array.from({ length: index.count }, (_, offset) => index.getX(offset));
1459
+ if (index !== null) {
1460
+ const storage = attributeStorage(index, 1);
1461
+ return storage === void 0 ? Uint32Array.from({ length: index.count }, (_, offset) => index.getX(offset)) : Uint32Array.from(storage);
1462
+ }
1363
1463
  const count = mesh.geometry.getAttribute("position")?.count ?? 0;
1364
1464
  if (count === 0 || count % 3 !== 0)
1365
1465
  throw new Error("CollisionShape3D.fromMesh requires triangle indices.");
@@ -1497,6 +1597,10 @@ var CollisionShape3D = class _CollisionShape3D {
1497
1597
  }
1498
1598
  static fromMesh(mesh, kind) {
1499
1599
  const geometry = mesh.geometry;
1600
+ if ((kind === "trimesh" || kind === "convexHull") && isStreamedGeometry(geometry))
1601
+ console.warn(
1602
+ `TN_COLLIDER_COARSE: CollisionShape3D.fromMesh(${JSON.stringify(mesh.name)}, "${kind}") copies the streamed coarse model's vertices; load it with ctx.assets.model(path, { whole: true }) to collide with the full one.`
1603
+ );
1500
1604
  const inferred = kind ?? (geometry.type.toLowerCase().includes("sphere") ? "sphere" : geometry.type.toLowerCase().includes("capsule") ? "capsule" : "box");
1501
1605
  if (inferred === "trimesh")
1502
1606
  return new _CollisionShape3D({
@@ -2034,7 +2138,6 @@ var scratchWorld = new Matrix4();
2034
2138
  var scratchPosition = new Vector3();
2035
2139
  var scratchScale = new Vector3();
2036
2140
  var scratchRotation = new Quaternion();
2037
- var scratchBounds = new Box3();
2038
2141
  function optionsFor(filter) {
2039
2142
  return typeof filter === "function" ? { predicate: filter } : filter ?? {};
2040
2143
  }
@@ -2062,8 +2165,14 @@ function configureCarrier(carrier, transform, scale) {
2062
2165
  carrier.updateMatrixWorld(true);
2063
2166
  }
2064
2167
  function isReachable(carrier, ceiling) {
2065
- scratchBounds.setFromObject(carrier, true);
2066
- return !scratchBounds.isEmpty() && scratchBounds.min.y < ceiling;
2168
+ const position = carrier.geometry.getAttribute("position");
2169
+ if (position === void 0 || position.count === 0) return false;
2170
+ const e = carrier.matrixWorld.elements;
2171
+ const [m1, m5, m9, m13] = [e[1] ?? 0, e[5] ?? 0, e[9] ?? 0, e[13] ?? 0];
2172
+ for (let i = 0; i < position.count; i++)
2173
+ if (m1 * position.getX(i) + m5 * position.getY(i) + m9 * position.getZ(i) + m13 < ceiling)
2174
+ return true;
2175
+ return false;
2067
2176
  }
2068
2177
  function addCollider(context, source, transform, options) {
2069
2178
  const carrier = new Mesh(source.geometry);
@@ -2812,6 +2921,7 @@ var VehicleBody3D = class extends RigidBody3D {
2812
2921
  #brake = 0;
2813
2922
  #steering = 0;
2814
2923
  #disposed = false;
2924
+ #friction;
2815
2925
  constructor(options) {
2816
2926
  const forward = FORWARD_AXES[options.forwardAxis ?? "-z"];
2817
2927
  if (forward === void 0)
@@ -2838,6 +2948,7 @@ var VehicleBody3D = class extends RigidBody3D {
2838
2948
  world: options.world
2839
2949
  });
2840
2950
  this.wheels = options.wheels;
2951
+ this.#friction = options.wheels.map((wheel) => wheel.wheelFrictionSlip);
2841
2952
  this.#object = options.object;
2842
2953
  this.#simulation = simulation;
2843
2954
  this.#readState = readVehicleState;
@@ -2897,6 +3008,26 @@ var VehicleBody3D = class extends RigidBody3D {
2897
3008
  get speed() {
2898
3009
  return this.#state().speed;
2899
3010
  }
3011
+ /**
3012
+ * Godot's `VehicleWheel3D.wheel_friction_slip`, changed while the car drives: the cap on the
3013
+ * tyre's combined grip impulse, as a multiple of the load on it. Dropping the rear pair is a
3014
+ * handbrake slide; restoring it is the catch. Cold path: call it when the grip changes.
3015
+ */
3016
+ setWheelFrictionSlip(index, frictionSlip) {
3017
+ this.#requireLive("setWheelFrictionSlip");
3018
+ const set = this.#simulation.setVehicleWheelFriction;
3019
+ if (set === void 0)
3020
+ throw new Error(
3021
+ "TN_VEHICLE_NATIVE_UNAVAILABLE: the active physics backend cannot change wheel grip."
3022
+ );
3023
+ set.call(this.#simulation, this.#vehicle, index, frictionSlip);
3024
+ this.#friction[index] = frictionSlip;
3025
+ }
3026
+ /** The wheel's current grip cap: its construction value until `setWheelFrictionSlip` moves it. */
3027
+ wheelFrictionSlip(index) {
3028
+ this.#wheel(index, 0);
3029
+ return this.#friction[index];
3030
+ }
2900
3031
  /** Whether this wheel's suspension ray found ground on the last completed step. */
2901
3032
  wheelContact(index) {
2902
3033
  return this.#wheel(index, 0) === 1;
@@ -2980,6 +3111,7 @@ function visibleId(buffer, offset) {
2980
3111
  throw new Error("IPhysicsSimulation returned an invalid visible body id.");
2981
3112
  return value;
2982
3113
  }
3114
+ var PHYSICS_READY = /* @__PURE__ */ Symbol.for("threenative.physics.ready");
2983
3115
  function rapier(options = {}) {
2984
3116
  const backend = physicsSimulationBackend();
2985
3117
  let simulation;
@@ -3001,6 +3133,7 @@ function rapier(options = {}) {
3001
3133
  let debugSeries = [];
3002
3134
  let completedSteps = 0;
3003
3135
  let gameContext;
3136
+ let generations = 0;
3004
3137
  const interpolationRemovals = /* @__PURE__ */ new Map();
3005
3138
  function updateInterpolation(body) {
3006
3139
  interpolationRemovals.get(body)?.();
@@ -3028,6 +3161,10 @@ function rapier(options = {}) {
3028
3161
  addBuoyancy: (buoyancy) => buoyancies.add(buoyancy),
3029
3162
  eventQueue: physicsHandle(selected.rawEventQueue),
3030
3163
  kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
3164
+ groundHolds: (bodyId2) => {
3165
+ const ground = bodiesById.get(bodyId2);
3166
+ return ground === void 0 || ground instanceof RigidBody3D && ground.type !== "dynamic";
3167
+ },
3031
3168
  numBodies: () => bodies.size,
3032
3169
  remove: (body) => {
3033
3170
  interpolationRemovals.get(body)?.();
@@ -3048,19 +3185,36 @@ function rapier(options = {}) {
3048
3185
  };
3049
3186
  }
3050
3187
  return {
3051
- setup: async (ctx, runtime) => {
3188
+ // Rapier's Wasm initializes while the scene loads: a game builds bodies in `enter()`, and the
3189
+ // start gate holds `enter()` until `ctx.physics` is set, so a first visit does not wait for
3190
+ // Rapier before loading its textures and world (PRD-860). With no gate, setup awaits it.
3191
+ setup: (ctx, runtime) => {
3052
3192
  gameContext = ctx;
3053
- await backend.initialize();
3054
- const selected = backend.createSimulation(options);
3055
- simulation = selected;
3056
- if (runtime !== void 0) runtime.rapier = selected.version;
3057
- context = buildContext(selected);
3058
- ctx.physics = context;
3059
- unregisterObservations = runtime?.observations?.contribute({
3060
- capabilities: ["runtime.physics"],
3061
- sample: (request) => physicsObservations(ctx, runtime, request)
3193
+ const generation = ++generations;
3194
+ const ready = backend.initialize().then(() => {
3195
+ if (generation !== generations) {
3196
+ console.warn(
3197
+ "TN_PHYSICS_SETUP_SUPERSEDED: rapier initialized after its game was disposed; nothing was installed."
3198
+ );
3199
+ return void 0;
3200
+ }
3201
+ const selected = backend.createSimulation(options);
3202
+ simulation = selected;
3203
+ if (runtime !== void 0) runtime.rapier = selected.version;
3204
+ const built = buildContext(selected);
3205
+ context = built;
3206
+ ctx.physics = built;
3207
+ unregisterObservations = runtime?.observations?.contribute({
3208
+ capabilities: ["runtime.physics"],
3209
+ sample: (request) => physicsObservations(ctx, runtime, request)
3210
+ });
3211
+ return built;
3062
3212
  });
3063
- return unregisterObservations;
3213
+ Object.defineProperty(ctx, PHYSICS_READY, { configurable: true, value: ready });
3214
+ const cleanup = () => unregisterObservations?.();
3215
+ if (runtime?.holdStart === void 0) return ready.then(() => cleanup);
3216
+ void runtime.holdStart(ready.then(() => void 0)).catch(() => void 0);
3217
+ return cleanup;
3064
3218
  },
3065
3219
  update: (_ctx, dt) => {
3066
3220
  if (simulation === void 0) throw new Error("Physics plugin updated before setup.");
@@ -3192,6 +3346,7 @@ function rapier(options = {}) {
3192
3346
  ctx.physics = context;
3193
3347
  },
3194
3348
  dispose: () => {
3349
+ generations += 1;
3195
3350
  unregisterObservations?.();
3196
3351
  unregisterObservations = void 0;
3197
3352
  for (const buoyancy of [...buoyancies]) buoyancy.dispose();
@@ -1,4 +1,4 @@
1
1
  import '@threenative/core';
2
2
  import 'recast-navigation';
3
- export { a7 as INavigationAgent3DOptions, a8 as INavigationContext, a9 as INavigationObstacle3DOptions, aa as INavigationRegion3DOptions, ab as NavigationAgent3D, ac as NavigationAgentEvent, ad as NavigationAgentHandler, ae as NavigationObstacle3D, af as NavigationPlugin, ag as NavigationRegion3D, ah as recast } from '../Area3D-D03tyOlF.js';
3
+ export { a7 as INavigationAgent3DOptions, a8 as INavigationContext, a9 as INavigationObstacle3DOptions, aa as INavigationRegion3DOptions, ab as NavigationAgent3D, ac as NavigationAgentEvent, ad as NavigationAgentHandler, ae as NavigationObstacle3D, af as NavigationPlugin, ag as NavigationRegion3D, ah as recast } from '../Area3D-BI0ynKEY.js';
4
4
  import 'three';
@@ -620,19 +620,28 @@ function disposeNavigation(navigation) {
620
620
  function recast() {
621
621
  let navigation;
622
622
  return {
623
- setup: async (ctx) => {
624
- await initialize();
625
- if (ctx.physics === void 0)
623
+ // Like rapier(), Recast initializes while the scene loads and holds `enter()` until it is up.
624
+ setup: (ctx, runtime) => {
625
+ const physics = Reflect.get(
626
+ ctx,
627
+ /* @__PURE__ */ Symbol.for("threenative.physics.ready")
628
+ );
629
+ if (physics === void 0)
626
630
  throw new Error("recast() requires rapier() earlier in the plugins array.");
627
- const empty = emptyNavigation();
628
- navigation = {
629
- agents: /* @__PURE__ */ new Set(),
630
- navMesh: empty.navMesh,
631
- obstacles: /* @__PURE__ */ new Set(),
632
- query: empty.query,
633
- regions: /* @__PURE__ */ new Set()
634
- };
635
- ctx.physics.navigation = navigation;
631
+ const ready = Promise.all([physics, initialize()]).then(([context]) => {
632
+ if (context === void 0) return;
633
+ const empty = emptyNavigation();
634
+ navigation = {
635
+ agents: /* @__PURE__ */ new Set(),
636
+ navMesh: empty.navMesh,
637
+ obstacles: /* @__PURE__ */ new Set(),
638
+ query: empty.query,
639
+ regions: /* @__PURE__ */ new Set()
640
+ };
641
+ context.navigation = navigation;
642
+ });
643
+ if (runtime?.holdStart === void 0) return ready.then(() => void 0);
644
+ void runtime.holdStart(ready).catch(() => void 0);
636
645
  return void 0;
637
646
  },
638
647
  update: (ctx, dt) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/physics",
3
- "version": "0.3.12",
3
+ "version": "0.3.15",
4
4
  "license": "MIT",
5
5
  "description": "Thin Rapier physics bindings for ThreeNative games.",
6
6
  "keywords": [
@@ -55,7 +55,7 @@
55
55
  "recast-navigation": "0.43.1"
56
56
  },
57
57
  "peerDependencies": {
58
- "@threenative/core": ">=0.3.12 <0.4.0",
58
+ "@threenative/core": ">=0.3.15 <0.4.0",
59
59
  "three": ">=0.187.0 <0.188.0"
60
60
  },
61
61
  "devDependencies": {
@@ -65,7 +65,7 @@
65
65
  "tsup": "8.5.1",
66
66
  "typescript": "npm:@typescript/typescript6@6.0.2",
67
67
  "@typescript/native": "npm:typescript@7.0.2",
68
- "@threenative/core": "0.3.12"
68
+ "@threenative/core": "0.3.15"
69
69
  },
70
70
  "scripts": {
71
71
  "build": "tsup --config tsup.config.ts && publint",