@zaisma/physics 2.4.1 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/simulation.js CHANGED
@@ -13,8 +13,9 @@
13
13
  // a world step. So a character kind steps just after the first of each fixed step's engine steps (or, if it asks,
14
14
  // just before the first), when the index is where everything stood: the same in every game and on the game server,
15
15
  // whatever was written in since.
16
- import { MOTION_KINDS, RIDING_LAYER_NAME, refuse } from "./declare.js";
16
+ import { MOTION_KINDS, RIDING_LAYER_NAME, refuse, timetablePlaceInto, triangleGroupBitNumberOf, triangleGroupMaskIndexOf } from "./declare.js";
17
17
  import { dataOf } from "./data.js";
18
+ import { ANSWER_FLOAT_COUNT, ANSWER_NUMBER_COUNT, BODY_FLOAT_COUNT, BODY_TAG_NUMBER, CHARACTER_TAG_NUMBER, CONTACT_FLOAT_COUNT, CONTACT_NUMBER_COUNT, EACH_TRIANGLE_FLAG_NUMBER, EXCLUDES_BODY_FLAG_NUMBER, NO_TRIANGLE_INDEX, ONE_SIDED_FLAG_NUMBER, SKIPS_CHARACTERS_FLAG_NUMBER, SMALL_TAG_NUMBER, TAG_KIND_MASK_NUMBER, WRITE_MOVING_NUMBER, WRITE_PLACE_ONLY_NUMBER, WRITE_RESTING_NUMBER, createBatch, heldMeshParts, isBigMesh } from "./batch.js";
18
19
 
19
20
  /** A hit slower than this isn't told. */
20
21
  const MINIMUM_TOLD_HIT_SPEED_M_PER_SEC = 1.2;
@@ -24,8 +25,12 @@ const TOUCH_MEMORY_STEP_COUNT = 15;
24
25
  const GROUND_TILE_CELL_COUNT = 32;
25
26
  /** How long laid ground nothing came near is kept before it's taken up, in steps. */
26
27
  const GROUND_KEPT_STEP_COUNT = 90;
28
+ /** How often the ground under a body that hasn't moved is kept again, in steps. */
29
+ const GROUND_KEPT_AGAIN_STEP_COUNT = 30;
27
30
  /** The gap a character's controller keeps from what it touches. */
28
31
  const CHARACTER_SKIN_M = 0.02;
32
+ /** How far under a character a body on a timetable still carries it, in metres: its controller's gap and a little more. */
33
+ const RIDE_REACH_M = CHARACTER_SKIN_M + 0.04;
29
34
  const NO_TURN = Object.freeze({ x: 0, y: 0, z: 0, w: 1 });
30
35
 
31
36
  /** An angle in radians, wrapped into -PI up to PI. */
@@ -69,21 +74,57 @@ const SUSPENSION_FORCE_HEADROOM_NUMBER = 2.5;
69
74
  * characterKind is how characters move (characters.js); tuning is the world's numbers (gravity, how surfaces grip and
70
75
  * bounce, how motion dies away); readDataFile reads a data file where the world opens on a game server. Bodies and
71
76
  * characters are known by an index from 0, which is what the wire carries; ids are for the game.
77
+ *
78
+ * bodyGrain is the wire's grain for a body's place, speed, spin and rotation ({ place, speed, spin: { minimumNumber,
79
+ * maximumNumber, stepSizeNumber, maximumStepCount }, rotationMaximumStepCount }): with it, the engine leaves every
80
+ * awake body on those steps as a step ends, so every side steps on from the numbers the wire carries.
72
81
  */
73
- export function createSimulation(engine, world, { tickDurationSec, characterKind, tuning, readDataFile = null, tracksTouches = false, isEachCharacterAlone = false }) {
82
+ export function createSimulation(engine, world, { tickDurationSec, characterKind, tuning, readDataFile = null, tracksTouches = false, isEachCharacterAlone = false, bodyGrain = null }) {
74
83
  let currentTuning = tuning;
75
84
  let stepCount = 0;
76
85
  const substepDurationSec = tickDurationSec / world.substepCount;
77
86
  const rapierWorld = new engine.World({ x: 0, y: -currentTuning.gravityMPerSecPerSec, z: 0 });
78
87
  rapierWorld.timestep = substepDurationSec;
79
- const eventQueue = new engine.EventQueue(true);
88
+ // The engine's batch calls: a step, a read, a write and a query each cross into the engine once, with plain numbers.
89
+ const batch = createBatch(engine, rapierWorld);
90
+ const { raw } = batch;
91
+ if (bodyGrain) {
92
+ const { place, speed, spin } = bodyGrain;
93
+ raw.setGrain(place.minimumNumber, place.maximumNumber, place.stepSizeNumber, place.maximumStepCount, speed.minimumNumber, speed.maximumNumber, speed.stepSizeNumber, speed.maximumStepCount, spin.minimumNumber, spin.maximumNumber, spin.stepSizeNumber, spin.maximumStepCount, bodyGrain.rotationMaximumStepCount);
94
+ }
95
+ const bodyTagOf = (index, isSmall = false) => ((index << 8) | (isSmall ? SMALL_TAG_NUMBER : 0) | BODY_TAG_NUMBER) >>> 0;
96
+ const characterTagOf = (index) => ((index << 8) | CHARACTER_TAG_NUMBER) >>> 0;
97
+ /** The engine's own step, whatever started touching in it left untold. */
98
+ const stepEngine = () => raw.substep(batch.pipeline, rapierWorld.gravity.x, rapierWorld.gravity.y, rapierWorld.gravity.z, batch.integrationParameters, batch.islands, batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, batch.impulseJoints, batch.multibodyJoints, batch.ccdSolver);
99
+ /** How many bodies the last step left awake and on the wire's steps, and which step that was. */
100
+ let settledCount = 0;
101
+ let settledStepCount = -1;
102
+ /** How many written bodies already were as written, and how many weren't: what a test reads. */
103
+ let sameWriteCount = 0;
104
+ let changedWriteCount = 0;
105
+ let movableBodyCount = 0;
106
+ /** The bodies that aren't fixed for good, by index: what a step goes through, however many pieces the level is made of. */
107
+ const unfixedBodies = [];
108
+ let lowestFreeBodyIndex = 0;
80
109
  const bodies = [];
81
110
  const bodyIndexById = new Map();
111
+ /** The bodies on a timetable, and the step their places were last worked out for. */
112
+ const timetableBodies = [];
113
+ let timetableTickIndex = null;
114
+ const blankPlace = () => ({ x: 0, y: 0, z: 0, rotationX: 0, rotationY: 0, rotationZ: 0, rotationW: 1 });
115
+ const copyPlace = (from, to) => {
116
+ to.x = from.x;
117
+ to.y = from.y;
118
+ to.z = from.z;
119
+ to.rotationX = from.rotationX;
120
+ to.rotationY = from.rotationY;
121
+ to.rotationZ = from.rotationZ;
122
+ to.rotationW = from.rotationW;
123
+ };
82
124
  const characters = [];
83
125
  const characterIndexById = new Map();
84
126
  /** Who a collider belongs to: { isCharacter, index }, or { isGround } for laid ground. */
85
127
  const ownerByColliderHandle = new Map();
86
- const movingBodyByHandle = new Map();
87
128
  const joints = new Map();
88
129
  let hits = [];
89
130
  /** Whether bodies were put somewhere since their colliders last followed. */
@@ -105,19 +146,47 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
105
146
  const characterLayerIndex = layerIndexByName.get("character");
106
147
  const groupsOf = (layerIndex) => groupsOfLayer[layerIndex] >>> 0;
107
148
 
149
+ // ---- What a hit says of the collider it met: which triangle of its whole mesh, and its surface ----
150
+ const handleFloats = new Float64Array(1);
151
+ const handleNumbers = new Uint32Array(handleFloats.buffer);
152
+ /** A collider's number, as the engine's calls answer it: the low half of its handle. */
153
+ const colliderNumberOf = (handle) => {
154
+ handleFloats[0] = handle;
155
+ return handleNumbers[0];
156
+ };
157
+ const surfaceIndexByName = new Map(world.surfaceNames.map((surfaceName, surfaceIndex) => [surfaceName, surfaceIndex]));
158
+ /** By collider number: { isMesh, triangleIndexes, surfaceIndices, surfaceName }, for a mesh's colliders and any with a surface. */
159
+ const hitInfoByColliderNumber = new Map();
160
+ /** Notes whose a collider is and, from its shape, what a hit on it says. mesh is one of heldMeshParts' parts for a mesh's collider. */
161
+ function ownCollider(collider, owner, shape = null, mesh = null) {
162
+ ownerByColliderHandle.set(collider.handle, owner);
163
+ const surfaceName = shape?.surfaceName ?? null;
164
+ if (mesh || surfaceName !== null) hitInfoByColliderNumber.set(colliderNumberOf(collider.handle), { isMesh: Boolean(mesh), triangleIndexes: mesh?.triangleIndexes ?? null, surfaceIndices: shape?.triangleSurfaceIndices ?? null, surfaceName: surfaceIndexByName.has(surfaceName) ? surfaceName : null });
165
+ }
166
+ function disownCollider(collider) {
167
+ ownerByColliderHandle.delete(collider.handle);
168
+ hitInfoByColliderNumber.delete(colliderNumberOf(collider.handle));
169
+ }
170
+ /** Colliders on a collision layer of their own (a mesh's group that stops only shots): they stay there when their body changes layer. */
171
+ const ownLayerColliders = new WeakSet();
172
+
108
173
  const gripNumberOf = (declaration) => (declaration.gripPct ?? currentTuning.gripPct) / 100;
109
174
  const bounceNumberOf = (declaration) => (declaration.bouncePct ?? currentTuning.bouncePct) / 100;
110
175
 
176
+ /** The mesh colliderDescriptionOf last described a collider from, or null when it wasn't a mesh. */
177
+ let describedMesh = null;
111
178
  function colliderDescriptionOf(shape) {
112
179
  let description;
180
+ describedMesh = null;
113
181
  if (shape.shapeKind === "box") description = engine.ColliderDesc.cuboid(shape.sizeM.x / 2, shape.sizeM.y / 2, shape.sizeM.z / 2);
114
182
  else if (shape.shapeKind === "ball") description = engine.ColliderDesc.ball(shape.radiusM);
115
183
  else if (shape.shapeKind === "capsule") description = engine.ColliderDesc.capsule(shape.heightM / 2 - shape.radiusM, shape.radiusM);
116
184
  else if (shape.shapeKind === "cylinder") description = engine.ColliderDesc.cylinder(shape.heightM / 2, shape.radiusM);
117
185
  else if (shape.shapeKind === "hull") description = engine.ColliderDesc.convexHull(new Float32Array(shape.pointsM));
118
186
  else {
119
- const mesh = dataOf(shape, readDataFile);
120
- description = engine.ColliderDesc.trimesh(mesh.pointsM, mesh.triangleIndices);
187
+ const meshData = dataOf(shape, readDataFile);
188
+ describedMesh = heldMeshParts(engine, meshData.pointsM, meshData.triangleIndices)[0] ?? null;
189
+ description = describedMesh ? new engine.ColliderDesc(describedMesh.shape) : null;
121
190
  }
122
191
  // A hull of points all in one plane has no inside: a small ball stands in, so the body is still there.
123
192
  if (!description) description = engine.ColliderDesc.ball(0.05);
@@ -132,7 +201,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
132
201
  function addGround(body, shape) {
133
202
  const { heightsM } = dataOf(shape, readDataFile);
134
203
  // The heightfield's first height is at the shape's place; rows run along +z, columns along +x, as the body turns them.
135
- grounds.push({ body, shape, heightsM, tiles: new Map(), rowTileCount: Math.ceil((shape.rowCount - 1) / GROUND_TILE_CELL_COUNT), columnTileCount: Math.ceil((shape.columnCount - 1) / GROUND_TILE_CELL_COUNT) });
204
+ grounds.push({ body, shape, heightsM, tiles: new Map(), rowTileCount: Math.ceil((shape.rowCount - 1) / GROUND_TILE_CELL_COUNT), columnTileCount: Math.ceil((shape.columnCount - 1) / GROUND_TILE_CELL_COUNT), isPlaced: false, x: 0, y: 0, z: 0, rotationX: 0, rotationY: 0, rotationZ: 0, rotationW: 1 });
136
205
  }
137
206
 
138
207
  function layTile(ground, rowTileIndex, columnTileIndex) {
@@ -156,39 +225,94 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
156
225
  .setRestitution(bounceNumberOf(body.declaration))
157
226
  .setCollisionGroups(groupsOf(body.layerIndex));
158
227
  const collider = rapierWorld.createCollider(description, body.rigidBody);
159
- ownerByColliderHandle.set(collider.handle, { isCharacter: false, index: body.index, isGround: true });
228
+ ownCollider(collider, { isCharacter: false, index: body.index, isGround: true }, shape);
229
+ raw.setColliderTag(collider.handle, bodyTagOf(body.index));
160
230
  isSceneOwed = true;
161
231
  return { collider, keptUntilStepCount: 0 };
162
232
  }
163
233
 
234
+ /** Where a ground's body is and how it's turned: read once for one that never moves, each step for one that may. */
235
+ function placeGround(ground) {
236
+ raw.readBody(batch.bodies, ground.body.rigidBody.handle);
237
+ const floats = batch.floats();
238
+ ground.x = floats[0];
239
+ ground.y = floats[1];
240
+ ground.z = floats[2];
241
+ ground.rotationX = floats[3];
242
+ ground.rotationY = floats[4];
243
+ ground.rotationZ = floats[5];
244
+ ground.rotationW = floats[6];
245
+ ground.isPlaced = true;
246
+ }
247
+
164
248
  /** Lays the ground near a point (in the world), keeping it a while: every tile within reach of it. */
165
- function keepGroundAround(point, reachM, untilStepCount) {
249
+ function keepGroundAround(pointX, pointY, pointZ, reachM, untilStepCount) {
166
250
  for (const ground of grounds) {
167
- const bodyM = ground.body.rigidBody.translation();
168
- const local = turnedBack({ x: point.x - bodyM.x, y: point.y - bodyM.y, z: point.z - bodyM.z }, ground.body.rigidBody.rotation());
251
+ if (!ground.isPlaced) placeGround(ground);
252
+ // The point in the ground's own space: turned back by its body's rotation.
253
+ const x = pointX - ground.x;
254
+ const y = pointY - ground.y;
255
+ const z = pointZ - ground.z;
256
+ const crossX = -ground.rotationY * z + ground.rotationZ * y;
257
+ const crossZ = -ground.rotationX * y + ground.rotationY * x;
258
+ const crossY = -ground.rotationZ * x + ground.rotationX * z;
259
+ const localX = x + 2 * (ground.rotationW * crossX - ground.rotationY * crossZ + ground.rotationZ * crossY);
260
+ const localZ = z + 2 * (ground.rotationW * crossZ - ground.rotationX * crossY + ground.rotationY * crossX);
169
261
  const tileSizeM = GROUND_TILE_CELL_COUNT * ground.shape.cellSizeM;
170
- const firstColumnTileIndex = Math.max(Math.floor((local.x - ground.shape.positionM.x - reachM) / tileSizeM), 0);
171
- const lastColumnTileIndex = Math.min(Math.floor((local.x - ground.shape.positionM.x + reachM) / tileSizeM), ground.columnTileCount - 1);
172
- const firstRowTileIndex = Math.max(Math.floor((local.z - ground.shape.positionM.z - reachM) / tileSizeM), 0);
173
- const lastRowTileIndex = Math.min(Math.floor((local.z - ground.shape.positionM.z + reachM) / tileSizeM), ground.rowTileCount - 1);
262
+ const firstColumnTileIndex = Math.max(Math.floor((localX - ground.shape.positionM.x - reachM) / tileSizeM), 0);
263
+ const lastColumnTileIndex = Math.min(Math.floor((localX - ground.shape.positionM.x + reachM) / tileSizeM), ground.columnTileCount - 1);
264
+ const firstRowTileIndex = Math.max(Math.floor((localZ - ground.shape.positionM.z - reachM) / tileSizeM), 0);
265
+ const lastRowTileIndex = Math.min(Math.floor((localZ - ground.shape.positionM.z + reachM) / tileSizeM), ground.rowTileCount - 1);
174
266
  for (let rowTileIndex = firstRowTileIndex; rowTileIndex <= lastRowTileIndex; rowTileIndex += 1) {
175
267
  for (let columnTileIndex = firstColumnTileIndex; columnTileIndex <= lastColumnTileIndex; columnTileIndex += 1) {
176
268
  const tileNumber = rowTileIndex * 65536 + columnTileIndex;
177
269
  let tile = ground.tiles.get(tileNumber);
178
270
  if (!tile) ground.tiles.set(tileNumber, (tile = layTile(ground, rowTileIndex, columnTileIndex)));
179
- tile.keptUntilStepCount = Math.max(tile.keptUntilStepCount, untilStepCount);
271
+ if (tile.keptUntilStepCount < untilStepCount) tile.keptUntilStepCount = untilStepCount;
180
272
  }
181
273
  }
182
274
  }
183
275
  }
184
276
 
185
- /** Before each step: ground under everything that moves (asleep too, so it never wakes over a hole), and where the game asked. */
277
+ /**
278
+ * Before each step: ground under everything that moves (asleep too, so it never wakes over a hole), and where the
279
+ * game asked. What the last step left awake is kept from where it left it; what's asleep hasn't moved, so its
280
+ * ground is kept again only now and then, well before it would be taken up.
281
+ */
186
282
  function layGround() {
187
283
  if (!grounds.length) return;
188
284
  const untilStepCount = stepCount + GROUND_KEPT_STEP_COUNT;
189
- for (const body of bodies) if (body && body.motionIndex !== 2) keepGroundAround(body.rigidBody.translation(), world.groundReachM, untilStepCount);
190
- for (const character of characters) if (character && !character.isWaiting) keepGroundAround(character.rigidBody.translation(), world.groundReachM, untilStepCount);
191
- for (const point of keptPoints) keepGroundAround(point, world.groundReachM, untilStepCount);
285
+ for (const ground of grounds) if (ground.body.motionIndex !== 2) ground.isPlaced = false;
286
+ const isSettled = settledStepCount === stepCount;
287
+ for (const body of unfixedBodies) {
288
+ if (body.motionIndex === 2) continue;
289
+ if (isSettled && body.settledStepCount === stepCount) {
290
+ const floats = batch.floats();
291
+ const firstIndex = ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT;
292
+ const x = floats[firstIndex];
293
+ const y = floats[firstIndex + 1];
294
+ const z = floats[firstIndex + 2];
295
+ keepGroundAround(x, y, z, world.groundReachM, untilStepCount);
296
+ } else if (stepCount - body.groundKeptStepCount >= GROUND_KEPT_AGAIN_STEP_COUNT) {
297
+ raw.readBody(batch.bodies, body.rigidBody.handle);
298
+ const floats = batch.floats();
299
+ const x = floats[0];
300
+ const y = floats[1];
301
+ const z = floats[2];
302
+ keepGroundAround(x, y, z, world.groundReachM, untilStepCount);
303
+ } else continue;
304
+ body.groundKeptStepCount = stepCount;
305
+ }
306
+ for (const character of characters) {
307
+ if (!character || character.isWaiting) continue;
308
+ raw.readBody(batch.bodies, character.rigidBody.handle);
309
+ const floats = batch.floats();
310
+ const x = floats[0];
311
+ const y = floats[1];
312
+ const z = floats[2];
313
+ keepGroundAround(x, y, z, world.groundReachM, untilStepCount);
314
+ }
315
+ for (const point of keptPoints) keepGroundAround(point.x, point.y, point.z, world.groundReachM, untilStepCount);
192
316
  keptPoints = [];
193
317
  pruneGround();
194
318
  }
@@ -199,7 +323,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
199
323
  for (const ground of grounds) {
200
324
  for (const [tileNumber, tile] of ground.tiles) {
201
325
  if (tile.keptUntilStepCount >= stepCount) continue;
202
- ownerByColliderHandle.delete(tile.collider.handle);
326
+ disownCollider(tile.collider);
203
327
  rapierWorld.removeCollider(tile.collider, false);
204
328
  ground.tiles.delete(tileNumber);
205
329
  }
@@ -211,12 +335,16 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
211
335
  const bodyTypeOf = (motionIndex) => (motionIndex === 0 ? engine.RigidBodyType.Dynamic : motionIndex === 1 ? engine.RigidBodyType.KinematicVelocityBased : engine.RigidBodyType.Fixed);
212
336
 
213
337
  /** Adds a body (checkBody's answer) at an index: the next free one, or the one given. Answers the index. */
338
+ /** The lowest index no body has. */
339
+ function freeBodyIndex() {
340
+ while (lowestFreeBodyIndex < bodies.length && bodies[lowestFreeBodyIndex] !== null) lowestFreeBodyIndex += 1;
341
+ return lowestFreeBodyIndex;
342
+ }
343
+
344
+ /** How many times what never moves has changed: a fixed body gone or set moving, a triangle group switched. What rests on it is judged again. */
345
+ let levelChangeCount = 0;
214
346
  function addBody(declaration, givenIndex = null) {
215
- let index = givenIndex;
216
- if (index === null) {
217
- index = bodies.findIndex((held) => held === null);
218
- if (index === -1) index = bodies.length;
219
- }
347
+ const index = givenIndex ?? freeBodyIndex();
220
348
  while (bodies.length <= index) bodies.push(null);
221
349
  const motionIndex = MOTION_KINDS.indexOf(declaration.motionKind);
222
350
  const description = (motionIndex === 0 ? engine.RigidBodyDesc.dynamic() : motionIndex === 1 ? engine.RigidBodyDesc.kinematicVelocityBased() : engine.RigidBodyDesc.fixed())
@@ -226,21 +354,34 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
226
354
  .setAngularDamping(declaration.angularDampingNumber ?? currentTuning.angularDampingNumber);
227
355
  const rigidBody = rapierWorld.createRigidBody(description);
228
356
  const layerIndex = layerIndexByName.get(declaration.collisionLayerName);
229
- const body = { index, declaration, rigidBody, colliders: [], motionIndex, declaredMotionIndex: motionIndex, layerIndex, velocityBefore: { x: 0, y: 0, z: 0 }, vehicle: null };
357
+ const body = { index, declaration, rigidBody, colliders: [], motionIndex, declaredMotionIndex: motionIndex, layerIndex, vehicle: null, settledIndex: 0, settledStepCount: -1, groundKeptStepCount: -Infinity, steppedFields: null };
230
358
  bodies[index] = body;
359
+ if (motionIndex !== 2) {
360
+ // Kept in the order of their indexes, so every side goes through them alike.
361
+ let placeIndex = unfixedBodies.length;
362
+ while (placeIndex > 0 && unfixedBodies[placeIndex - 1].index > index) placeIndex -= 1;
363
+ unfixedBodies.splice(placeIndex, 0, body);
364
+ }
231
365
  for (const shape of declaration.shapes) {
232
366
  if (shape.shapeKind === "heightfield") {
233
367
  addGround(body, shape);
234
368
  continue;
235
369
  }
236
- if (shape.shapeKind === "mesh" && shape.triangleGroupNumbers) {
370
+ if (shape.shapeKind === "mesh" && (shape.triangleGroupNumbers || isBigMesh(dataOf(shape, readDataFile).triangleIndices))) {
237
371
  addGroupedMesh(body, shape);
238
372
  continue;
239
373
  }
240
374
  const collider = rapierWorld.createCollider(colliderDescriptionOf(shape).setDensity(1).setFriction(gripNumberOf(declaration)).setRestitution(bounceNumberOf(declaration)).setCollisionGroups(groupsOf(layerIndex)).setActiveEvents(motionIndex === 0 ? engine.ActiveEvents.COLLISION_EVENTS : engine.ActiveEvents.NONE), rigidBody);
241
- ownerByColliderHandle.set(collider.handle, { isCharacter: false, index });
375
+ ownCollider(collider, { isCharacter: false, index }, shape, describedMesh);
376
+ raw.setColliderTag(collider.handle, bodyTagOf(index));
242
377
  body.colliders.push(collider);
243
378
  }
379
+ // A body fixed for good is a piece of the level: the engine never pairs two of them, however many touch.
380
+ if (motionIndex === 2) for (const collider of body.colliders) engine.RawBatch.markLevelCollider(batch.colliders, collider.handle);
381
+ if (motionIndex !== 2) {
382
+ movableBodyCount += 1;
383
+ batch.reserveAwake(movableBodyCount);
384
+ }
244
385
  if (motionIndex === 0) {
245
386
  // The shapes share the body's mass by how much room each takes.
246
387
  body.massAtUnitDensityKg = rigidBody.mass();
@@ -248,8 +389,9 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
248
389
  // A small thing thrown hard would pass through a wall between two steps.
249
390
  body.isSmall = declaration.massKg < SMALL_BODY_MASS_KG;
250
391
  rigidBody.enableCcd(body.isSmall);
251
- movingBodyByHandle.set(rigidBody.handle, index);
252
392
  }
393
+ raw.setBodyTag(rigidBody.handle, bodyTagOf(index, body.isSmall === true));
394
+ if (declaration.timetable) addTimetableBody(body);
253
395
  if (declaration.wheels.length) body.vehicle = addVehicle(body);
254
396
  bodyIndexById.set(declaration.id, index);
255
397
  return index;
@@ -257,51 +399,61 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
257
399
 
258
400
  /** Triangle groups by number: the colliders of each, switched on and off together. */
259
401
  const groupColliders = new Map();
260
- let offTriangleGroupMaskNumber = 0;
261
- /** A mesh whose triangles come in groups: a collider for each group, so a door or a bridge can come and go. */
402
+ const offTriangleGroupMaskNumbers = [0, 0, 0];
403
+ const isTriangleGroupOff = (groupNumber) => Boolean(offTriangleGroupMaskNumbers[triangleGroupMaskIndexOf(groupNumber)] & triangleGroupBitNumberOf(groupNumber));
404
+ /**
405
+ * A mesh of several colliders: one for each group its triangles come in, so a door or a bridge can come and go,
406
+ * and a big mesh's in tiles.
407
+ */
262
408
  function addGroupedMesh(body, shape) {
263
409
  const { pointsM, triangleIndices } = dataOf(shape, readDataFile);
264
410
  const groupNumbers = shape.triangleGroupNumbers;
265
- if (groupNumbers.length !== triangleIndices.length / 3) refuse("bad_body", `${body.declaration.id}'s mesh has ${triangleIndices.length / 3} triangles and ${groupNumbers.length} triangleGroupNumbers.`, "triangleGroupNumbers", "Give one group number for each of the mesh's triangles.");
266
- const countByGroup = new Map();
267
- for (const groupNumber of groupNumbers) countByGroup.set(groupNumber, (countByGroup.get(groupNumber) ?? 0) + 1);
268
- for (const [groupNumber, triangleCount] of countByGroup) {
269
- const groupIndices = new Uint32Array(triangleCount * 3);
270
- let writtenCount = 0;
271
- for (let triangleIndex = 0; triangleIndex < groupNumbers.length; triangleIndex += 1) {
272
- if (groupNumbers[triangleIndex] !== groupNumber) continue;
273
- groupIndices.set(triangleIndices.subarray(triangleIndex * 3, triangleIndex * 3 + 3), writtenCount);
274
- writtenCount += 3;
275
- }
276
- const description = engine.ColliderDesc.trimesh(pointsM, groupIndices).setTranslation(shape.positionM.x, shape.positionM.y, shape.positionM.z).setRotation(shape.rotation);
277
- const collider = rapierWorld.createCollider(description.setFriction(gripNumberOf(body.declaration)).setRestitution(bounceNumberOf(body.declaration)).setCollisionGroups(groupsOf(body.layerIndex)), body.rigidBody);
278
- ownerByColliderHandle.set(collider.handle, { isCharacter: false, index: body.index });
411
+ if (groupNumbers && groupNumbers.length !== triangleIndices.length / 3) refuse("bad_body", `${body.declaration.id}'s mesh has ${triangleIndices.length / 3} triangles and ${groupNumbers.length} triangleGroupNumbers.`, "triangleGroupNumbers", "Give one group number for each of the mesh's triangles.");
412
+ if (shape.triangleSurfaceIndices && shape.triangleSurfaceIndices.length !== triangleIndices.length / 3) refuse("bad_body", `${body.declaration.id}'s mesh has ${triangleIndices.length / 3} triangles and ${shape.triangleSurfaceIndices.length} triangleSurfaceIndices.`, "triangleSurfaceIndices", "Give one surface for each of the mesh's triangles.");
413
+ for (const mesh of heldMeshParts(engine, pointsM, triangleIndices, groupNumbers)) {
414
+ const { groupNumber } = mesh;
415
+ // A group may be on a layer of its own: glass that stops players and not shots, a rail only vehicles meet.
416
+ const ownLayerName = shape.triangleGroups?.find((group) => group.groupNumber === groupNumber)?.collisionLayerName;
417
+ const description = new engine.ColliderDesc(mesh.shape).setTranslation(shape.positionM.x, shape.positionM.y, shape.positionM.z).setRotation(shape.rotation);
418
+ const collider = rapierWorld.createCollider(description.setFriction(gripNumberOf(body.declaration)).setRestitution(bounceNumberOf(body.declaration)).setCollisionGroups(groupsOf(ownLayerName === undefined ? body.layerIndex : layerIndexByName.get(ownLayerName))), body.rigidBody);
419
+ if (ownLayerName !== undefined) ownLayerColliders.add(collider);
420
+ ownCollider(collider, { isCharacter: false, index: body.index }, shape, mesh);
421
+ raw.setColliderTag(collider.handle, bodyTagOf(body.index));
279
422
  body.colliders.push(collider);
280
423
  if (groupNumber === 0) continue;
281
424
  if (!groupColliders.has(groupNumber)) groupColliders.set(groupNumber, []);
282
425
  groupColliders.get(groupNumber).push(collider);
283
- collider.setEnabled(!(offTriangleGroupMaskNumber & (1 << (groupNumber - 1))));
426
+ collider.setEnabled(!isTriangleGroupOff(groupNumber));
284
427
  }
285
428
  }
286
- /** Which triangle groups are off: a bit for each, group 1 the lowest. */
287
- function setOffTriangleGroups(maskNumber) {
288
- if (maskNumber === offTriangleGroupMaskNumber) return;
289
- offTriangleGroupMaskNumber = maskNumber;
290
- for (const [groupNumber, colliders] of groupColliders) for (const collider of colliders) collider.setEnabled(!(maskNumber & (1 << (groupNumber - 1))));
429
+ /** Which triangle groups are off: three whole numbers with a bit for each group (triangleGroupMaskIndexOf, triangleGroupBitNumberOf). */
430
+ function setOffTriangleGroups(firstMaskNumber, secondMaskNumber = 0, thirdMaskNumber = 0) {
431
+ if (firstMaskNumber === offTriangleGroupMaskNumbers[0] && secondMaskNumber === offTriangleGroupMaskNumbers[1] && thirdMaskNumber === offTriangleGroupMaskNumbers[2]) return;
432
+ offTriangleGroupMaskNumbers[0] = firstMaskNumber;
433
+ offTriangleGroupMaskNumbers[1] = secondMaskNumber;
434
+ offTriangleGroupMaskNumbers[2] = thirdMaskNumber;
435
+ levelChangeCount += 1;
436
+ for (const [groupNumber, colliders] of groupColliders) for (const collider of colliders) collider.setEnabled(!isTriangleGroupOff(groupNumber));
291
437
  isSceneOwed = true;
292
438
  }
293
439
 
294
440
  function removeBody(index) {
295
441
  const body = bodies[index];
296
442
  if (!body) return false;
443
+ levelChangeCount += 1;
297
444
  characterKind.onBodyRemoved?.(index, stepTools);
298
445
  for (const [jointId, joint] of joints) if (joint.bodyIndexes.includes(index)) removeJoint(jointId);
299
446
  for (const character of characters) if (character?.rideBodyIndex === index) unseat(character);
300
447
  if (body.vehicle) rapierWorld.removeVehicleController(body.vehicle.controller);
301
- for (const collider of body.colliders) ownerByColliderHandle.delete(collider.handle);
302
- for (const ground of grounds.filter((each) => each.body === body)) for (const tile of ground.tiles.values()) ownerByColliderHandle.delete(tile.collider.handle);
448
+ for (const collider of body.colliders) disownCollider(collider);
449
+ for (const ground of grounds.filter((each) => each.body === body)) for (const tile of ground.tiles.values()) disownCollider(tile.collider);
303
450
  for (let groundIndex = grounds.length - 1; groundIndex >= 0; groundIndex -= 1) if (grounds[groundIndex].body === body) grounds.splice(groundIndex, 1);
304
- movingBodyByHandle.delete(body.rigidBody.handle);
451
+ if (body.declaredMotionIndex !== 2) {
452
+ movableBodyCount -= 1;
453
+ unfixedBodies.splice(unfixedBodies.indexOf(body), 1);
454
+ }
455
+ lowestFreeBodyIndex = Math.min(lowestFreeBodyIndex, index);
456
+ if (body.timetable) timetableBodies.splice(timetableBodies.indexOf(body), 1);
305
457
  rapierWorld.removeRigidBody(body.rigidBody);
306
458
  bodyIndexById.delete(body.declaration.id);
307
459
  bodies[index] = null;
@@ -318,17 +470,17 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
318
470
 
319
471
  /** Changes how a body moves while playing: a parked cart made fixed, a lift made kinematic, and back. */
320
472
  function setBodyMotion(body, motionIndex) {
321
- if (body.motionIndex === motionIndex || body.declaredMotionIndex === 2) return;
473
+ levelChangeCount += 1;
474
+ if (body.motionIndex === motionIndex || body.declaredMotionIndex === 2 || body.timetable) return;
322
475
  body.motionIndex = motionIndex;
323
476
  body.rigidBody.setBodyType(bodyTypeOf(motionIndex), true);
324
- if (motionIndex === 0) movingBodyByHandle.set(body.rigidBody.handle, body.index);
325
- else movingBodyByHandle.delete(body.rigidBody.handle);
477
+ body.settledStepCount = -1;
326
478
  }
327
479
 
328
480
  function setBodyLayer(body, layerIndex) {
329
481
  if (body.layerIndex === layerIndex) return;
330
482
  body.layerIndex = layerIndex;
331
- for (const collider of body.colliders) collider.setCollisionGroups(groupsOf(layerIndex));
483
+ for (const collider of body.colliders) if (!ownLayerColliders.has(collider)) collider.setCollisionGroups(groupsOf(layerIndex));
332
484
  }
333
485
 
334
486
  // ---- Vehicles: a body on wheels, driven by whoever sits in its first seat ----
@@ -362,8 +514,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
362
514
  /** Sets each vehicle's controls from its driver's input, or lets it roll with none. */
363
515
  function driveVehicles(worldStepContext) {
364
516
  const { inputOf } = worldStepContext;
365
- for (const body of bodies) {
366
- if (!body?.vehicle) continue;
517
+ for (const body of unfixedBodies) {
518
+ if (!body.vehicle) continue;
367
519
  const driver = characters.find((character) => character && character.rideBodyIndex === body.index && character.seatIndex === 0);
368
520
  const controls = driver ? characterKind.vehicleControls(inputOf(driver.id) ?? characterKind.idleInput, { bodyId: body.declaration.id, ...stepTools.bodyState(body.declaration.id) }, worldStepContext) : { engineNumber: 0, steerNumber: 0, brakeNumber: 0 };
369
521
  const { vehicle } = body.declaration;
@@ -384,12 +536,10 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
384
536
  }
385
537
 
386
538
  function updateVehicles() {
387
- for (const body of bodies) {
388
- if (!body?.vehicle || body.motionIndex !== 0 || body.rigidBody.isSleeping()) continue;
389
- body.vehicle.controller.updateVehicle(substepDurationSec, engine.QueryFilterFlags.EXCLUDE_SENSORS, body.vehicle.wheelGroupsNumber, (collider) => {
390
- const owner = ownerByColliderHandle.get(collider.handle);
391
- return !owner?.isCharacter && owner?.index !== body.index;
392
- });
539
+ for (const body of unfixedBodies) {
540
+ if (!body.vehicle || body.motionIndex !== 0 || body.rigidBody.isSleeping()) continue;
541
+ // Its wheels stand on what its layers say, never on a character and never on the vehicle itself.
542
+ raw.updateVehicle(body.vehicle.controller.raw, batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, substepDurationSec, body.vehicle.wheelGroupsNumber);
393
543
  }
394
544
  }
395
545
 
@@ -448,25 +598,44 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
448
598
 
449
599
  // ---- Characters ----
450
600
 
451
- const characterHalfSegmentM = world.character.heightM / 2 - world.character.radiusM;
452
601
  const isKinematicKind = characterKind.bodyKind === "kinematic";
453
- const controller = isKinematicKind ? rapierWorld.createCharacterController(CHARACTER_SKIN_M) : null;
454
- if (controller) {
455
- controller.setUp({ x: 0, y: 1, z: 0 });
456
- controller.setSlideEnabled(true);
457
- if (world.character.stepHeightM > 0) controller.enableAutostep(world.character.stepHeightM, world.character.radiusM * 0.5, false);
458
- controller.setMaxSlopeClimbAngle((world.character.maximumSlopeDeg * Math.PI) / 180);
459
- controller.setMinSlopeSlideAngle?.(((world.character.maximumSlopeDeg + 5) * Math.PI) / 180);
460
- controller.enableSnapToGround(world.character.stepHeightM > 0 ? world.character.stepHeightM : 0.1);
461
- controller.setApplyImpulsesToDynamicBodies(characterKind.canPushBodies !== false);
462
- controller.setCharacterMass(currentTuning.characterMassKg ?? 70);
463
- }
602
+ /**
603
+ * The sizes a character takes: the world's own first, then the ones it names. A character's body sits where its
604
+ * feet are and half the world's own height more, whatever its size, so a place on the wire means the same for all;
605
+ * its capsule is raised or lowered on it to stand on the same feet.
606
+ */
607
+ const characterSizes = [{ name: null, ...world.character }, ...world.characterSizes].map((size) => {
608
+ const controller = isKinematicKind ? rapierWorld.createCharacterController(CHARACTER_SKIN_M) : null;
609
+ if (controller) {
610
+ controller.setUp({ x: 0, y: 1, z: 0 });
611
+ controller.setSlideEnabled(true);
612
+ if (size.stepHeightM > 0) controller.enableAutostep(size.stepHeightM, size.radiusM * 0.5, false);
613
+ controller.setMaxSlopeClimbAngle((size.maximumSlopeDeg * Math.PI) / 180);
614
+ controller.setMinSlopeSlideAngle?.(((size.maximumSlopeDeg + 5) * Math.PI) / 180);
615
+ controller.enableSnapToGround(size.stepHeightM > 0 ? size.stepHeightM : 0.1);
616
+ controller.setApplyImpulsesToDynamicBodies(characterKind.canPushBodies !== false);
617
+ controller.setCharacterMass(currentTuning.characterMassKg ?? 70);
618
+ }
619
+ return {
620
+ ...size,
621
+ halfSegmentM: size.heightM / 2 - size.radiusM,
622
+ /** How far above the body's place the capsule's middle is. */
623
+ riseM: (size.heightM - world.character.heightM) / 2,
624
+ controller,
625
+ /** How far up a surface under the character faces, at least, for it to stand there: the steepest slope it climbs. */
626
+ minimumStandNormalNumber: Math.cos((size.maximumSlopeDeg * Math.PI) / 180),
627
+ };
628
+ });
629
+ const characterHalfSegmentM = characterSizes[0].halfSegmentM;
630
+ const tallestCharacterHeightM = Math.max(...characterSizes.map((size) => size.heightM));
631
+ const characterSizeIndexByName = new Map(characterSizes.map((size, sizeIndex) => [size.name, sizeIndex]));
464
632
 
465
633
  /**
466
634
  * Adds a character with its feet at a place, at an index: the next free one, or the one given. Answers the index.
467
635
  * With isWaiting it's in the world's lists but not in the world, touching nothing, until writeCharacter says where
468
636
  * it is: for a game that knows a character has joined before it knows where.
469
637
  */
638
+ const colliderRiseM = isKinematicKind ? CHARACTER_SKIN_M : 0;
470
639
  function addCharacter(characterId, feetPositionM, givenIndex = null, isWaiting = false) {
471
640
  let index = givenIndex;
472
641
  if (index === null) {
@@ -479,10 +648,12 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
479
648
  // No grip of its own, so a character never sticks to a wall it walks along: its feet's hold is in how it's moved.
480
649
  // A kinematic character's capsule sits its controller's gap above the body's place: the controller keeps that gap
481
650
  // from the ground, so the body stands exactly on it (and one placed exactly on the ground isn't already too close).
482
- const colliderDescription = engine.ColliderDesc.capsule(characterHalfSegmentM, world.character.radiusM).setTranslation(0, isKinematicKind ? CHARACTER_SKIN_M : 0, 0).setFriction(0).setFrictionCombineRule(engine.CoefficientCombineRule.Min).setRestitution(0).setCollisionGroups(groupsOf(characterLayerIndex)).setActiveEvents(engine.ActiveEvents.COLLISION_EVENTS);
651
+ const colliderDescription = engine.ColliderDesc.capsule(characterHalfSegmentM, world.character.radiusM).setTranslation(0, colliderRiseM, 0).setFriction(0).setFrictionCombineRule(engine.CoefficientCombineRule.Min).setRestitution(0).setCollisionGroups(groupsOf(characterLayerIndex)).setActiveEvents(engine.ActiveEvents.COLLISION_EVENTS);
483
652
  if (!isKinematicKind) colliderDescription.setMass(currentTuning.characterMassKg ?? 70);
484
653
  const collider = rapierWorld.createCollider(colliderDescription, rigidBody);
485
654
  ownerByColliderHandle.set(collider.handle, { isCharacter: true, index });
655
+ raw.setColliderTag(collider.handle, characterTagOf(index));
656
+ raw.setBodyTag(rigidBody.handle, characterTagOf(index));
486
657
  if (isWaiting) rigidBody.setEnabled(false);
487
658
  const character = {
488
659
  index,
@@ -490,6 +661,10 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
490
661
  isWaiting,
491
662
  rigidBody,
492
663
  collider,
664
+ size: characterSizes[0],
665
+ sizeIndex: 0,
666
+ /** Which of the world's characterSizes it is now, or null for the world's own character's. */
667
+ characterSizeName: null,
493
668
  /** A kinematic character's speed: the engine doesn't keep one for it. */
494
669
  velocity: { x: 0, y: 0, z: 0 },
495
670
  facingYawRad: 0,
@@ -513,13 +688,80 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
513
688
  if (!character) return false;
514
689
  characterKind.onCharacterRemoved?.(character, stepTools);
515
690
  for (const [jointId, joint] of joints) if (joint.characterIndexes.includes(index)) removeJoint(jointId);
516
- ownerByColliderHandle.delete(character.collider.handle);
691
+ disownCollider(character.collider);
517
692
  rapierWorld.removeRigidBody(character.rigidBody);
518
693
  characterIndexById.delete(character.id);
519
694
  characters[index] = null;
520
695
  return true;
521
696
  }
522
697
 
698
+ /** How near a character's capsule the ground it rests on is, at most: its controller's gap and a little more. */
699
+ const REST_REACH_M = CHARACTER_SKIN_M + 0.03;
700
+ /**
701
+ * Whether a character stands on what never moves and touches nothing else: then, with nothing asked of it and no
702
+ * speed, a step would leave it exactly where it is, and its kind may skip the move. Judged once where it stands,
703
+ * and again only when it has moved, changed size or layer, or the level under it has changed.
704
+ */
705
+ function isRestingOnLevel(character) {
706
+ if (character.rideBodyIndex >= 0) return false;
707
+ raw.readBody(batch.bodies, character.rigidBody.handle);
708
+ let floats = batch.floats();
709
+ const x = floats[0];
710
+ const y = floats[1];
711
+ const z = floats[2];
712
+ const rest = (character.rest ??= { x: NaN, y: NaN, z: NaN, sizeIndex: -1, layerIndex: -1, levelChangeCount: -1, isResting: false });
713
+ if (rest.x === x && rest.y === y && rest.z === z && rest.sizeIndex === character.sizeIndex && rest.layerIndex === character.layerIndex && rest.levelChangeCount === levelChangeCount) return rest.isResting;
714
+ rest.x = x;
715
+ rest.y = y;
716
+ rest.z = z;
717
+ rest.sizeIndex = character.sizeIndex;
718
+ rest.layerIndex = character.layerIndex;
719
+ rest.levelChangeCount = levelChangeCount;
720
+ rest.isResting = false;
721
+ const contactCount = characterContactsOf(character, x, y, z, REST_REACH_M);
722
+ floats = batch.floats();
723
+ const numbers = batch.numbers();
724
+ let isStanding = false;
725
+ for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
726
+ const tagNumber = numbers[contactIndex * CONTACT_NUMBER_COUNT];
727
+ const body = (tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? bodies[tagNumber >>> 8] : null;
728
+ if (!body || body.motionIndex !== 2) return false;
729
+ if (floats[contactIndex * CONTACT_FLOAT_COUNT + 4] >= character.size.minimumStandNormalNumber) isStanding = true;
730
+ }
731
+ rest.isResting = isStanding;
732
+ return isStanding;
733
+ }
734
+
735
+ /** How deep something may reach into a size a character asks to take before the size doesn't fit. */
736
+ const SIZE_FIT_DEPTH_M = 0.02;
737
+ /**
738
+ * Gives a character another of the world's sizes, its feet where they are. With isFitChecked, only where the size
739
+ * has room: answers false, and changes nothing, when something other than the ground it stands on is in its way.
740
+ */
741
+ function setCharacterSize(character, sizeIndex, isFitChecked = false) {
742
+ if (character.sizeIndex === sizeIndex) return true;
743
+ const size = characterSizes[sizeIndex];
744
+ if (!size) return false;
745
+ if (isFitChecked && !character.isWaiting) {
746
+ raw.readBody(batch.bodies, character.rigidBody.handle);
747
+ let floats = batch.floats();
748
+ const contactCount = raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, floats[0], floats[1] + CHARACTER_SKIN_M + size.riseM, floats[2], 0, 0, 0, 1, size.radiusM, size.halfSegmentM, 0, groupsOf(character.layerIndex), character.rigidBody.handle, (isEachCharacterAlone ? SKIPS_CHARACTERS_FLAG_NUMBER : 0) | EXCLUDES_BODY_FLAG_NUMBER | EACH_TRIANGLE_FLAG_NUMBER);
749
+ floats = batch.floats();
750
+ for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
751
+ const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
752
+ if (floats[firstIndex + 6] > SIZE_FIT_DEPTH_M && floats[firstIndex + 4] < size.minimumStandNormalNumber) return false;
753
+ }
754
+ }
755
+ character.size = size;
756
+ character.sizeIndex = sizeIndex;
757
+ character.characterSizeName = size.name;
758
+ character.collider.setShape(new engine.Capsule(size.halfSegmentM, size.radiusM));
759
+ character.collider.setTranslationWrtParent({ x: 0, y: colliderRiseM + size.riseM, z: 0 });
760
+ isPropagationOwed = true;
761
+ isSceneOwed = true;
762
+ return true;
763
+ }
764
+
523
765
  function setCharacterLayer(character, layerIndex) {
524
766
  if (character.layerIndex === layerIndex) return;
525
767
  character.layerIndex = layerIndex;
@@ -566,12 +808,6 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
566
808
 
567
809
  // ---- Queries, as a character kind and a game ask them ----
568
810
 
569
- /** Who a collider is: { bodyId, characterId }, or null for something not the world's own. */
570
- const whoOf = (collider) => {
571
- const owner = ownerByColliderHandle.get(collider.handle);
572
- if (!owner) return null;
573
- return owner.isCharacter ? { bodyId: null, characterId: characters[owner.index]?.id ?? null } : { bodyId: bodies[owner.index]?.declaration.id ?? null, characterId: null };
574
- };
575
811
  /** The groups a query searches with: the layers named (all, when none), as a layer that touches them. */
576
812
  const queryGroupsOf = (layerNames) => {
577
813
  if (!layerNames) return 0xffffffff;
@@ -585,16 +821,37 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
585
821
  if (bodyIndexById.has(exclude)) return bodies[bodyIndexById.get(exclude)].rigidBody;
586
822
  return null;
587
823
  };
824
+ // Over a level, where each character moves alone, the level's searches see the level: a character's place there is no one's to find.
825
+ const queryFlagsOf = (excluded) => (isEachCharacterAlone ? SKIPS_CHARACTERS_FLAG_NUMBER : 0) | (excluded ? EXCLUDES_BODY_FLAG_NUMBER : 0);
826
+ /** A tagNumber's body id, or null when it isn't a body's. */
827
+ const bodyIdOfTag = (tagNumber) => ((tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? (bodies[tagNumber >>> 8]?.declaration.id ?? null) : null);
828
+ const characterIdOfTag = (tagNumber) => ((tagNumber & TAG_KIND_MASK_NUMBER) === CHARACTER_TAG_NUMBER ? (characters[tagNumber >>> 8]?.id ?? null) : null);
588
829
 
830
+ /**
831
+ * Which of a mesh's triangles a hit or a contact is on (as the mesh was declared, whatever groups it's in), and
832
+ * what surface that is: null where the collider isn't a mesh, or names no surface.
833
+ */
834
+ function noteSurface(hit, colliderNumber, triangleNumber) {
835
+ const colliderInfo = hitInfoByColliderNumber.get(colliderNumber);
836
+ if (!colliderInfo) {
837
+ hit.triangleIndex = null;
838
+ hit.surfaceName = null;
839
+ return;
840
+ }
841
+ const triangleIndex = !colliderInfo.isMesh || triangleNumber === NO_TRIANGLE_INDEX ? null : colliderInfo.triangleIndexes ? colliderInfo.triangleIndexes[triangleNumber] : triangleNumber;
842
+ hit.triangleIndex = triangleIndex ?? null;
843
+ hit.surfaceName = colliderInfo.surfaceIndices && hit.triangleIndex !== null ? (world.surfaceNames[colliderInfo.surfaceIndices[hit.triangleIndex]] ?? null) : colliderInfo.surfaceName;
844
+ }
589
845
  /**
590
846
  * A hit as a query answers it, written into the caller's own object when it gives one (a game casting thousands of
591
847
  * rays a second keeps one), else a new one.
592
848
  */
593
- function hitInto(into, collider, pointX, pointY, pointZ, normalX, normalY, normalZ, distanceM) {
594
- const hit = into ?? { bodyId: null, characterId: null, pointM: { x: 0, y: 0, z: 0 }, normal: { x: 0, y: 0, z: 0 }, distanceM: 0 };
595
- const who = whoOf(collider);
596
- hit.bodyId = who?.bodyId ?? null;
597
- hit.characterId = who?.characterId ?? null;
849
+ function hitInto(into, numbers, pointX, pointY, pointZ, normalX, normalY, normalZ, distanceM) {
850
+ const hit = into ?? { bodyId: null, characterId: null, pointM: { x: 0, y: 0, z: 0 }, normal: { x: 0, y: 0, z: 0 }, distanceM: 0, triangleIndex: null, surfaceName: null };
851
+ const tagNumber = numbers[0];
852
+ hit.bodyId = bodyIdOfTag(tagNumber);
853
+ hit.characterId = characterIdOfTag(tagNumber);
854
+ noteSurface(hit, numbers[2], numbers[1]);
598
855
  hit.pointM ??= { x: 0, y: 0, z: 0 };
599
856
  hit.normal ??= { x: 0, y: 0, z: 0 };
600
857
  hit.pointM.x = pointX;
@@ -606,86 +863,122 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
606
863
  hit.distanceM = distanceM;
607
864
  return hit;
608
865
  }
609
- /** A shape moved along a direction: the first thing it meets, or null. Its own space is turned by rotation. */
610
- function castShapeQuery(shape, rotation, { fromM, directionM, maximumDistanceM, collisionLayerNames = null, excludedId = null, isStoppedAtPenetration = true }, into) {
866
+ /** A ball (shapeKindNumber 0) or a capsule (1) moved along a direction: the first thing it meets, or null. Its own space is turned by rotation. */
867
+ function castShapeQuery(shapeKindNumber, radiusM, halfSegmentM, rotation, { fromM, directionM, maximumDistanceM, collisionLayerNames = null, excludedId = null, isStoppedAtPenetration = true }, into) {
611
868
  const lengthNumber = Math.hypot(directionM.x, directionM.y, directionM.z) || 1;
612
- const direction = { x: directionM.x / lengthNumber, y: directionM.y / lengthNumber, z: directionM.z / lengthNumber };
613
- const hit = rapierWorld.castShape(fromM, rotation, direction, shape, 0, maximumDistanceM, isStoppedAtPenetration, engine.QueryFilterFlags.EXCLUDE_SENSORS, queryGroupsOf(collisionLayerNames), undefined, excludedOf(excludedId) ?? undefined, queryPredicate);
614
- if (!hit) return null;
615
- const distanceM = hit.time_of_impact;
616
- // The point and the normal are the hit collider's own (its surface there, facing out toward the shape): put into the world by its place and turn.
617
- const colliderAtM = hit.collider.translation();
618
- const colliderRotation = hit.collider.rotation();
619
- const witness = turned(hit.witness1, colliderRotation);
620
- const normal = turned(hit.normal1, colliderRotation);
621
- return hitInto(into, hit.collider, colliderAtM.x + witness.x, colliderAtM.y + witness.y, colliderAtM.z + witness.z, normal.x, normal.y, normal.z, distanceM);
622
- }
623
- /** A capsule standing up (or turned by rotation), as the engine takes it: its height is the whole, round ends included. */
624
- const capsuleOf = (radiusM, heightM) => new engine.Capsule(Math.max(heightM / 2 - radiusM, 0), radiusM);
869
+ const excluded = excludedOf(excludedId);
870
+ const isHit = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, shapeKindNumber, radiusM, halfSegmentM, rotation.x, rotation.y, rotation.z, rotation.w, fromM.x, fromM.y, fromM.z, directionM.x / lengthNumber, directionM.y / lengthNumber, directionM.z / lengthNumber, maximumDistanceM, isStoppedAtPenetration, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded));
871
+ if (!isHit) return null;
872
+ const floats = batch.floats();
873
+ return hitInto(into, batch.numbers(), floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[0]);
874
+ }
875
+ /** Contacts' objects a caller's own list held and no longer shows, kept for the next longer answer. */
876
+ const spareContacts = [];
877
+ /** A capsule's half segment, as the engine takes it: its height is the whole, round ends included. */
878
+ const halfSegmentOf = (radiusM, heightM) => Math.max(heightM / 2 - radiusM, 0);
625
879
 
626
- // Over a level, where each character moves alone, the level's searches see the level: a character's place there is no one's to find.
627
- const queryPredicate = isEachCharacterAlone ? (collider) => !ownerByColliderHandle.get(collider.handle)?.isCharacter : undefined;
628
880
  const queries = {
629
- /** The first thing a ray meets: { bodyId, characterId, pointM, normal, distanceM }, or null. With into, written there. */
881
+ /** The first thing a ray meets: { bodyId, characterId, pointM, normal, distanceM, triangleIndex, surfaceName }, or null. With into, written there. */
630
882
  castRay({ fromM, directionM, maximumDistanceM, collisionLayerNames = null, excludedId = null }, into = null) {
631
883
  const lengthNumber = Math.hypot(directionM.x, directionM.y, directionM.z) || 1;
632
- const direction = { x: directionM.x / lengthNumber, y: directionM.y / lengthNumber, z: directionM.z / lengthNumber };
633
- const hit = rapierWorld.castRayAndGetNormal(new engine.Ray(fromM, direction), maximumDistanceM, true, engine.QueryFilterFlags.EXCLUDE_SENSORS, queryGroupsOf(collisionLayerNames), undefined, excludedOf(excludedId) ?? undefined, queryPredicate);
634
- if (!hit) return null;
635
- const distanceM = hit.timeOfImpact;
636
- return hitInto(into, hit.collider, fromM.x + direction.x * distanceM, fromM.y + direction.y * distanceM, fromM.z + direction.z * distanceM, hit.normal.x, hit.normal.y, hit.normal.z, distanceM);
884
+ const directionX = directionM.x / lengthNumber;
885
+ const directionY = directionM.y / lengthNumber;
886
+ const directionZ = directionM.z / lengthNumber;
887
+ const excluded = excludedOf(excludedId);
888
+ const isHit = raw.castRay(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, fromM.x, fromM.y, fromM.z, directionX, directionY, directionZ, maximumDistanceM, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded));
889
+ if (!isHit) return null;
890
+ const floats = batch.floats();
891
+ const distanceM = floats[0];
892
+ return hitInto(into, batch.numbers(), fromM.x + directionX * distanceM, fromM.y + directionY * distanceM, fromM.z + directionZ * distanceM, floats[1], floats[2], floats[3], distanceM);
637
893
  },
638
894
  /** The first thing a ball meets moving along a direction: { bodyId, characterId, pointM, normal, distanceM }, or null. With into, written there. */
639
895
  castBall(query, into = null) {
640
- return castShapeQuery(new engine.Ball(query.radiusM), NO_TURN, query, into);
896
+ return castShapeQuery(0, query.radiusM, 0, NO_TURN, query, into);
641
897
  },
642
898
  /** The first thing a capsule (standing up, or turned by rotation) meets moving along a direction, or null. With into, written there. */
643
899
  castCapsule(query, into = null) {
644
- return castShapeQuery(capsuleOf(query.radiusM, query.heightM), query.rotation ?? NO_TURN, query, into);
900
+ return castShapeQuery(1, query.radiusM, halfSegmentOf(query.radiusM, query.heightM), query.rotation ?? NO_TURN, query, into);
645
901
  },
646
902
  /**
647
903
  * Where a capsule (standing up, or turned by rotation) touches the world: each contact's body or character, its
648
- * point, the surface's normal there (pointing out of it, toward the capsule) and how deep the capsule is in it
649
- * (depthM, above 0 when it overlaps). The way a game's own movement pushes out of walls and stands on slopes.
904
+ * point, the surface's normal there (pointing out of it, toward the capsule), how deep the capsule is in it
905
+ * (depthM, above 0 when it overlaps), the flat normal of the triangle or face it's on (faceNormal), which of a
906
+ * mesh's triangles that is (triangleIndex) and its surface (surfaceName). The way a game's own movement pushes
907
+ * out of walls and stands on slopes. A mesh answers its deepest triangle, or with isEachTriangle every triangle
908
+ * it touches; isOneSided leaves out triangles facing away. With into (a list of the caller's own, kept and given
909
+ * again), written there instead of a new list.
650
910
  */
651
- overlapCapsule({ centerM, radiusM, heightM, rotation = NO_TURN, collisionLayerNames = null, excludedId = null, marginM = 0 }) {
652
- const shape = capsuleOf(radiusM, heightM);
653
- const contacts = [];
654
- rapierWorld.intersectionsWithShape(centerM, rotation, marginM > 0 ? capsuleOf(radiusM + marginM, heightM + marginM * 2) : shape, (collider) => {
655
- const contact = collider.contactShape(shape, centerM, rotation, marginM);
656
- if (!contact) return true;
657
- const who = whoOf(collider);
658
- contacts.push({ bodyId: who?.bodyId ?? null, characterId: who?.characterId ?? null, pointM: { x: contact.point1.x, y: contact.point1.y, z: contact.point1.z }, normal: { x: contact.normal1.x, y: contact.normal1.y, z: contact.normal1.z }, depthM: -contact.distance });
659
- return true;
660
- }, engine.QueryFilterFlags.EXCLUDE_SENSORS, queryGroupsOf(collisionLayerNames), undefined, excludedOf(excludedId) ?? undefined, queryPredicate);
911
+ overlapCapsule({ centerM, radiusM, heightM, rotation = NO_TURN, collisionLayerNames = null, excludedId = null, marginM = 0, isEachTriangle = false, isOneSided = false }, into = null) {
912
+ const excluded = excludedOf(excludedId);
913
+ const contactCount = raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, centerM.x, centerM.y, centerM.z, rotation.x, rotation.y, rotation.z, rotation.w, radiusM, halfSegmentOf(radiusM, heightM), marginM, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded) | (isEachTriangle ? EACH_TRIANGLE_FLAG_NUMBER : 0) | (isOneSided ? ONE_SIDED_FLAG_NUMBER : 0));
914
+ const contacts = into ?? [];
915
+ const floats = batch.floats();
916
+ const numbers = batch.numbers();
917
+ // A list given again keeps its contacts' objects: the ones past this answer wait for a longer one.
918
+ while (contacts.length > contactCount) spareContacts.push(contacts.pop());
919
+ for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
920
+ const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
921
+ const firstNumberIndex = contactIndex * CONTACT_NUMBER_COUNT;
922
+ const tagNumber = numbers[firstNumberIndex];
923
+ const contact = (contacts[contactIndex] ??= (into && spareContacts.pop()) || { bodyId: null, characterId: null, pointM: { x: 0, y: 0, z: 0 }, normal: { x: 0, y: 0, z: 0 }, depthM: 0, faceNormal: { x: 0, y: 0, z: 0 }, triangleIndex: null, surfaceName: null });
924
+ contact.bodyId = bodyIdOfTag(tagNumber);
925
+ contact.characterId = characterIdOfTag(tagNumber);
926
+ contact.pointM.x = floats[firstIndex];
927
+ contact.pointM.y = floats[firstIndex + 1];
928
+ contact.pointM.z = floats[firstIndex + 2];
929
+ contact.normal.x = floats[firstIndex + 3];
930
+ contact.normal.y = floats[firstIndex + 4];
931
+ contact.normal.z = floats[firstIndex + 5];
932
+ contact.depthM = floats[firstIndex + 6];
933
+ contact.faceNormal.x = floats[firstIndex + 7];
934
+ contact.faceNormal.y = floats[firstIndex + 8];
935
+ contact.faceNormal.z = floats[firstIndex + 9];
936
+ noteSurface(contact, numbers[firstNumberIndex + 2], numbers[firstNumberIndex + 1]);
937
+ }
661
938
  return contacts;
662
939
  },
663
940
  /** Everything a ball overlaps: [{ bodyId, characterId }]. */
664
941
  overlapBall({ centerM, radiusM, collisionLayerNames = null, excludedId = null }) {
942
+ const excluded = excludedOf(excludedId);
943
+ const foundCount = raw.overlapBall(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, centerM.x, centerM.y, centerM.z, radiusM, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded));
665
944
  const found = [];
666
- rapierWorld.intersectionsWithShape(centerM, NO_TURN, new engine.Ball(radiusM), (collider) => {
667
- const who = whoOf(collider);
668
- if (who && !found.some((each) => each.bodyId === who.bodyId && each.characterId === who.characterId)) found.push(who);
669
- return true;
670
- }, engine.QueryFilterFlags.EXCLUDE_SENSORS, queryGroupsOf(collisionLayerNames), undefined, excludedOf(excludedId) ?? undefined, queryPredicate);
945
+ const numbers = batch.numbers();
946
+ for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) {
947
+ const tagNumber = numbers[foundIndex];
948
+ if ((tagNumber & TAG_KIND_MASK_NUMBER) === 0) continue;
949
+ const bodyId = bodyIdOfTag(tagNumber);
950
+ const characterId = characterIdOfTag(tagNumber);
951
+ if (!found.some((each) => each.bodyId === bodyId && each.characterId === characterId)) found.push({ bodyId, characterId });
952
+ }
671
953
  return found;
672
954
  },
673
955
  };
674
956
 
675
957
  /**
676
958
  * Moves a kinematic character by as much of desiredM as the world lets it: sliding along walls, up steps and
677
- * slopes it can climb, snapped down to the ground under it. Answers { movedM, isGrounded }.
959
+ * slopes it can climb, snapped down to the ground under it. Answers { movedM, isGrounded }: a new one, or into
960
+ * (an object of the step's own with a movedM, kept and given again) filled.
678
961
  */
679
- function moveAndSlide(character, desiredM) {
680
- if (!controller) return { movedM: { x: 0, y: 0, z: 0 }, isGrounded: false };
681
- // Characters that each move alone (each player predicts only their own) walk through each other: where another is stands differently in every game.
682
- controller.computeColliderMovement(character.collider, desiredM, engine.QueryFilterFlags.EXCLUDE_SENSORS, groupsOf(character.layerIndex), isEachCharacterAlone ? (collider) => !ownerByColliderHandle.get(collider.handle)?.isCharacter : (collider) => collider.handle !== character.collider.handle);
683
- const moved = controller.computedMovement();
684
- const atM = character.rigidBody.translation();
685
- character.rigidBody.setTranslation({ x: atM.x + moved.x, y: atM.y + moved.y, z: atM.z + moved.z }, true);
686
- // Its collider goes with it at once: the next character's move (and its own next) sees where it is.
687
- rapierWorld.propagateModifiedBodyPositionsToColliders();
688
- return { movedM: { x: moved.x, y: moved.y, z: moved.z }, isGrounded: controller.computedGrounded() };
962
+ function moveAndSlide(character, desiredM, into = null) {
963
+ const moved = into ?? { movedM: { x: 0, y: 0, z: 0 }, isGrounded: false };
964
+ const { controller } = character.size;
965
+ if (!controller) {
966
+ moved.movedM.x = 0;
967
+ moved.movedM.y = 0;
968
+ moved.movedM.z = 0;
969
+ moved.isGrounded = false;
970
+ return moved;
971
+ }
972
+ // Characters that each move alone (each player predicts only their own) walk through each other: where another is
973
+ // stands differently in every game. The move puts the character's body there, its collider with it at once: the
974
+ // next character's move (and its own next) sees where it is.
975
+ const isGrounded = raw.moveCharacter(controller.raw, batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, character.collider.handle, desiredM.x, desiredM.y, desiredM.z, substepDurationSec, characterKind.canPushBodies !== false ? (currentTuning.characterMassKg ?? 70) : -1, groupsOf(character.layerIndex), isEachCharacterAlone ? SKIPS_CHARACTERS_FLAG_NUMBER : 0);
976
+ const floats = batch.floats();
977
+ moved.movedM.x = floats[0];
978
+ moved.movedM.y = floats[1];
979
+ moved.movedM.z = floats[2];
980
+ moved.isGrounded = isGrounded;
981
+ return moved;
689
982
  }
690
983
 
691
984
  /** What a character kind's step reaches: the world's queries, the move, the bodies and characters by id. */
@@ -699,6 +992,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
699
992
  },
700
993
  ...queries,
701
994
  moveAndSlide,
995
+ isRestingOnLevel,
702
996
  bodies,
703
997
  characters,
704
998
  bodyIndexById,
@@ -721,9 +1015,10 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
721
1015
  characterState(characterId) {
722
1016
  const character = characters[characterIndexById.get(characterId)];
723
1017
  if (!character) return null;
724
- const centerM = character.rigidBody.translation();
725
- const velocity = isKinematicKind ? character.velocity : character.rigidBody.linvel();
726
- return { positionM: { x: centerM.x, y: centerM.y - world.character.heightM / 2, z: centerM.z }, velocityMPerSec: { x: velocity.x, y: velocity.y, z: velocity.z }, facingYawRad: character.facingYawRad, isGrounded: character.isGrounded, rideBodyId: bodies[character.rideBodyIndex]?.declaration.id ?? null, collisionLayerName: world.collisionLayers[character.ownLayerIndex].name, own: character.own };
1018
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1019
+ const floats = batch.floats();
1020
+ const velocityMPerSec = isKinematicKind ? { x: character.velocity.x, y: character.velocity.y, z: character.velocity.z } : { x: floats[7], y: floats[8], z: floats[9] };
1021
+ return { positionM: { x: floats[0], y: floats[1] - world.character.heightM / 2, z: floats[2] }, velocityMPerSec, facingYawRad: character.facingYawRad, isGrounded: character.isGrounded, rideBodyId: bodies[character.rideBodyIndex]?.declaration.id ?? null, collisionLayerName: world.collisionLayers[character.ownLayerIndex].name, characterSizeName: character.characterSizeName, own: character.own };
727
1022
  },
728
1023
  /**
729
1024
  * Ties or lets go a joint from a step (a press that takes a cart's handles), so it's run again exactly on a
@@ -735,6 +1030,16 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
735
1030
  return true;
736
1031
  },
737
1032
  /** Puts a character on one of the world's collision layers from its step (walking through his own cart while he holds it). */
1033
+ /**
1034
+ * Gives a character another of the world's characterSizes from its step (a crouch, standing up again), or null
1035
+ * for the world's own character's: its feet stay where they are. Answers false, and changes nothing, where the
1036
+ * size has no room (a low roof over a crouched head).
1037
+ */
1038
+ setSize(character, characterSizeName) {
1039
+ const sizeIndex = characterSizeIndexByName.get(characterSizeName);
1040
+ if (sizeIndex === undefined) refuse("bad_argument", `setSize was given ${JSON.stringify(characterSizeName)}.`, "characterSizeName", `Use one of the world's characterSizes (${world.characterSizes.map((size) => size.name).join(", ") || "it names none"}), or null for the world's own character.`);
1041
+ return setCharacterSize(character, sizeIndex, true);
1042
+ },
738
1043
  setLayer(character, collisionLayerName) {
739
1044
  const layerIndex = layerIndexByName.get(collisionLayerName);
740
1045
  if (layerIndex === undefined || collisionLayerName === RIDING_LAYER_NAME) refuse("bad_argument", `setLayer was given ${JSON.stringify(collisionLayerName)}.`, "collisionLayerName", `Use one of the world's collisionLayers: ${world.collisionLayers.filter((layer) => layer.name !== RIDING_LAYER_NAME).map((layer) => layer.name).join(", ")}.`);
@@ -746,26 +1051,348 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
746
1051
 
747
1052
  // The kind's own fields that go on the wire: a step that changes any of them leaves its character awake, so they're sent.
748
1053
  const sharedOwnNames = characterKind.stateFields.filter((field) => field.isShared !== false && typeof field.name === "string").map((field) => field.name);
749
- const sharedOwnOf = (character) => {
750
- if (!sharedOwnNames.length) return null;
751
- const own = characterKind.readOwn(character, stepTools) ?? {};
752
- return sharedOwnNames.map((name) => (own[name] !== null && typeof own[name] === "object" ? JSON.stringify(own[name]) : own[name]));
1054
+ const NO_OWN = Object.freeze({});
1055
+ /** A character's shared own fields into a list kept for it: a group as its text, so a change inside it shows. */
1056
+ const sharedOwnInto = (character, ownValues) => {
1057
+ const own = characterKind.readOwn(character, stepTools) ?? NO_OWN;
1058
+ for (let nameIndex = 0; nameIndex < sharedOwnNames.length; nameIndex += 1) {
1059
+ const ownValue = own[sharedOwnNames[nameIndex]];
1060
+ ownValues[nameIndex] = ownValue !== null && typeof ownValue === "object" ? JSON.stringify(ownValue) : ownValue;
1061
+ }
753
1062
  };
754
- const isSameOwn = (before, after) => before === null || after.every((fieldValue, fieldIndex) => fieldValue === before[fieldIndex]);
1063
+ const ownBefore = new Array(sharedOwnNames.length);
1064
+ const ownAfter = new Array(sharedOwnNames.length);
1065
+
1066
+
1067
+ // ---- Timetables: kinematic bodies whose place is the step's index and nothing else ----
1068
+ //
1069
+ // A lift, a sliding platform, a turning arm: where it is at a step is worked out the same in every game and on the
1070
+ // game server, so nothing of it is sent, and a step run again finds it where it was. A character standing on one
1071
+ // goes with it, and one in its way is pushed.
1072
+
1073
+ const isSamePlace = (first, second) => first.x === second.x && first.y === second.y && first.z === second.z && first.rotationX === second.rotationX && first.rotationY === second.rotationY && first.rotationZ === second.rotationZ && first.rotationW === second.rotationW;
1074
+
1075
+ /** How far from a body's own place its shapes reach, in metres: a ball around it that holds them all. */
1076
+ function reachOf(declaration) {
1077
+ let reachM = 0;
1078
+ for (const shape of declaration.shapes) {
1079
+ let shapeReachM = 0;
1080
+ if (shape.pointsM) for (let pointIndex = 0; pointIndex < shape.pointsM.length; pointIndex += 3) shapeReachM = Math.max(shapeReachM, Math.hypot(shape.pointsM[pointIndex], shape.pointsM[pointIndex + 1], shape.pointsM[pointIndex + 2]));
1081
+ else if (shape.sizeM) shapeReachM = Math.hypot(shape.sizeM.x, shape.sizeM.y, shape.sizeM.z) / 2;
1082
+ else shapeReachM = Math.hypot(shape.radiusM ?? 0, (shape.heightM ?? 0) / 2) + (shape.radiusM ?? 0);
1083
+ const offsetM = shape.positionM ? Math.hypot(shape.positionM.x, shape.positionM.y, shape.positionM.z) : 0;
1084
+ reachM = Math.max(reachM, offsetM + shapeReachM);
1085
+ }
1086
+ return reachM;
1087
+ }
1088
+
1089
+ function addTimetableBody(body) {
1090
+ body.timetable = body.declaration.timetable;
1091
+ body.reachM = reachOf(body.declaration);
1092
+ // Where it is at the step being run, where that step takes it, and where the engine has it now.
1093
+ body.fromPlace = blankPlace();
1094
+ body.toPlace = blankPlace();
1095
+ body.nowPlace = blankPlace();
1096
+ body.heldPlace = blankPlace();
1097
+ const { positionM, rotation } = body.declaration;
1098
+ copyPlace({ x: positionM.x, y: positionM.y, z: positionM.z, rotationX: rotation.x, rotationY: rotation.y, rotationZ: rotation.z, rotationW: rotation.w }, body.heldPlace);
1099
+ copyPlace(body.heldPlace, body.nowPlace);
1100
+ timetableBodies.push(body);
1101
+ timetableTickIndex = null;
1102
+ }
1103
+
1104
+ /** Works out where each timetable has its body at a step, and where that step takes it. */
1105
+ function timetablesAt(tickIndex) {
1106
+ if (timetableTickIndex === tickIndex) return;
1107
+ timetableTickIndex = tickIndex;
1108
+ for (const body of timetableBodies) {
1109
+ timetablePlaceInto(body.timetable, tickIndex * tickDurationSec, body.fromPlace);
1110
+ const { fromPlace: from, toPlace: to } = body;
1111
+ timetablePlaceInto(body.timetable, (tickIndex + 1) * tickDurationSec, to);
1112
+ // The same rotation has two sets of numbers: the one nearer the step's start, so the way between them is the short one.
1113
+ if (from.rotationX * to.rotationX + from.rotationY * to.rotationY + from.rotationZ * to.rotationZ + from.rotationW * to.rotationW < 0) {
1114
+ to.rotationX = -to.rotationX;
1115
+ to.rotationY = -to.rotationY;
1116
+ to.rotationZ = -to.rotationZ;
1117
+ to.rotationW = -to.rotationW;
1118
+ }
1119
+ }
1120
+ }
1121
+
1122
+ /**
1123
+ * Puts every body on a timetable where it is at a step: before that step runs, and before anything is asked of the
1124
+ * world as it stands at it. A body already there is left alone.
1125
+ */
1126
+ function placeTimetables(tickIndex) {
1127
+ if (!timetableBodies.length) return;
1128
+ timetablesAt(tickIndex);
1129
+ for (const body of timetableBodies) {
1130
+ const place = body.fromPlace;
1131
+ if (isSamePlace(place, body.heldPlace)) continue;
1132
+ copyPlace(place, body.heldPlace);
1133
+ const { handle } = body.rigidBody;
1134
+ batch.bodies.rbSetTranslation(handle, place.x, place.y, place.z, false);
1135
+ batch.bodies.rbSetRotation(handle, place.rotationX, place.rotationY, place.rotationZ, place.rotationW, false);
1136
+ isPropagationOwed = true;
1137
+ isSceneOwed = true;
1138
+ }
1139
+ }
1140
+
1141
+ /** A place between two a step apart: straight between them, its rotation brought back to length (the two are the same way round, and close). */
1142
+ function placeBetween(from, to, shareNumber, into) {
1143
+ into.x = from.x + (to.x - from.x) * shareNumber;
1144
+ into.y = from.y + (to.y - from.y) * shareNumber;
1145
+ into.z = from.z + (to.z - from.z) * shareNumber;
1146
+ const rotationX = from.rotationX + (to.rotationX - from.rotationX) * shareNumber;
1147
+ const rotationY = from.rotationY + (to.rotationY - from.rotationY) * shareNumber;
1148
+ const rotationZ = from.rotationZ + (to.rotationZ - from.rotationZ) * shareNumber;
1149
+ const rotationRealNumber = from.rotationW + (to.rotationW - from.rotationW) * shareNumber;
1150
+ const lengthNumber = Math.sqrt(rotationX * rotationX + rotationY * rotationY + rotationZ * rotationZ + rotationRealNumber * rotationRealNumber) || 1;
1151
+ into.rotationX = rotationX / lengthNumber;
1152
+ into.rotationY = rotationY / lengthNumber;
1153
+ into.rotationZ = rotationZ / lengthNumber;
1154
+ into.rotationW = rotationRealNumber / lengthNumber;
1155
+ return into;
1156
+ }
1157
+
1158
+ /** How far the bodies on timetables have gone of this step's way when the characters step, at most, in metres. */
1159
+ let timetableLeadM = 0;
1160
+ /**
1161
+ * Notes where each body on a timetable is while the characters step: shareNumber of the way from where the step
1162
+ * found it to where the step leaves it (none of it where nothing else is stepped; a world's first substep otherwise).
1163
+ */
1164
+ function timetablesNow(shareNumber) {
1165
+ timetableLeadM = 0;
1166
+ for (const body of timetableBodies) {
1167
+ placeBetween(body.fromPlace, body.toPlace, shareNumber, body.nowPlace);
1168
+ timetableLeadM = Math.max(timetableLeadM, Math.hypot(body.nowPlace.x - body.fromPlace.x, body.nowPlace.y - body.fromPlace.y, body.nowPlace.z - body.fromPlace.z));
1169
+ }
1170
+ }
1171
+
1172
+ const startPlace = blankPlace();
1173
+ const aimedPlace = blankPlace();
1174
+ /**
1175
+ * Before a substep: each body on a timetable is put where the substep starts, exactly, with the speed and spin that
1176
+ * take it to where the substep ends. So the engine moves it there, carrying and pushing what it meets, and no
1177
+ * rounding ever adds up. Only adding and multiplying: the same numbers in every browser and on the game server.
1178
+ */
1179
+ function aimTimetables(substepIndex) {
1180
+ const isLast = substepIndex === world.substepCount - 1;
1181
+ for (const body of timetableBodies) {
1182
+ const { fromPlace: from, toPlace: to } = body;
1183
+ const { handle } = body.rigidBody;
1184
+ if (isSamePlace(from, to)) {
1185
+ // Waiting at a stop: the speed it arrived with ends there.
1186
+ if (body.hasSpeed) raw.writeBody(batch.bodies, handle, to.x, to.y, to.z, to.rotationX, to.rotationY, to.rotationZ, to.rotationW, 0, 0, 0, 0, 0, 0, WRITE_MOVING_NUMBER);
1187
+ body.hasSpeed = false;
1188
+ continue;
1189
+ }
1190
+ const start = substepIndex === 0 ? from : placeBetween(from, to, substepIndex / world.substepCount, startPlace);
1191
+ const aimed = isLast ? to : placeBetween(from, to, (substepIndex + 1) / world.substepCount, aimedPlace);
1192
+ // The turn from one to the other, as a spin: twice the small rotation between them, over the substep's time.
1193
+ const turnRealNumber = aimed.rotationW * start.rotationW + aimed.rotationX * start.rotationX + aimed.rotationY * start.rotationY + aimed.rotationZ * start.rotationZ;
1194
+ const turnX = -aimed.rotationW * start.rotationX + aimed.rotationX * start.rotationW - aimed.rotationY * start.rotationZ + aimed.rotationZ * start.rotationY;
1195
+ const turnY = -aimed.rotationW * start.rotationY + aimed.rotationY * start.rotationW - aimed.rotationZ * start.rotationX + aimed.rotationX * start.rotationZ;
1196
+ const turnZ = -aimed.rotationW * start.rotationZ + aimed.rotationZ * start.rotationW - aimed.rotationX * start.rotationY + aimed.rotationY * start.rotationX;
1197
+ const spinNumber = (turnRealNumber < 0 ? -2 : 2) / substepDurationSec;
1198
+ raw.writeBody(batch.bodies, handle, start.x, start.y, start.z, start.rotationX, start.rotationY, start.rotationZ, start.rotationW, (aimed.x - start.x) / substepDurationSec, (aimed.y - start.y) / substepDurationSec, (aimed.z - start.z) / substepDurationSec, turnX * spinNumber, turnY * spinNumber, turnZ * spinNumber, WRITE_MOVING_NUMBER);
1199
+ body.hasSpeed = true;
1200
+ if (isLast) copyPlace(to, body.heldPlace);
1201
+ }
1202
+ }
1203
+
1204
+ /**
1205
+ * Before the characters step: the bodies on timetables stand still to them. The engine's own character move would
1206
+ * take a character part of the way a moving body under it goes, by the body's speed; a timetable's rider is
1207
+ * carried exactly instead, the same where nothing is stepped. The next substep gives each its speed again.
1208
+ */
1209
+ function stillTimetables() {
1210
+ for (const body of timetableBodies) {
1211
+ if (!body.hasSpeed) continue;
1212
+ body.hasSpeed = false;
1213
+ const now = body.nowPlace;
1214
+ raw.writeBody(batch.bodies, body.rigidBody.handle, now.x, now.y, now.z, now.rotationX, now.rotationY, now.rotationZ, now.rotationW, 0, 0, 0, 0, 0, 0, WRITE_MOVING_NUMBER);
1215
+ }
1216
+ }
1217
+
1218
+ /** Whether a point is within reach of a body on a timetable: only then is a character asked what it touches. */
1219
+ function isNearTimetable(x, y, z) {
1220
+ for (const body of timetableBodies) {
1221
+ const reachM = body.reachM + tallestCharacterHeightM;
1222
+ const awayX = x - body.nowPlace.x;
1223
+ const awayY = y - body.nowPlace.y;
1224
+ const awayZ = z - body.nowPlace.z;
1225
+ if (awayX * awayX + awayY * awayY + awayZ * awayZ <= reachM * reachM) return true;
1226
+ }
1227
+ return false;
1228
+ }
1229
+
1230
+ /** What a character's capsule touches, within marginM of it: the contact count, read from the batch's answer. */
1231
+ const characterContactsOf = (character, x, y, z, marginM) =>
1232
+ raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, x, y + CHARACTER_SKIN_M + character.size.riseM, z, 0, 0, 0, 1, character.size.radiusM, character.size.halfSegmentM, marginM, groupsOf(character.layerIndex), character.rigidBody.handle, SKIPS_CHARACTERS_FLAG_NUMBER | EXCLUDES_BODY_FLAG_NUMBER);
1233
+ /** The body on a timetable a contact's tag is of, or null. */
1234
+ const timetableBodyOfTag = (tagNumber) => ((tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? (bodies[tagNumber >>> 8]?.timetable ? bodies[tagNumber >>> 8] : null) : null);
1235
+
1236
+ /**
1237
+ * Takes a character from where it is to the same place on a body that went from one place to another, turned
1238
+ * about it too, as far as whatever else is in the way lets it: the body it rides is what it leaves room for itself.
1239
+ */
1240
+ function carryCharacter(character, x, y, z, ridden, from, to, extraX = 0, extraY = 0, extraZ = 0) {
1241
+ // The character's place seen from the body where it was, then put where the body is.
1242
+ const awayX = x - from.x;
1243
+ const awayY = y - from.y;
1244
+ const awayZ = z - from.z;
1245
+ const backX = -from.rotationX;
1246
+ const backY = -from.rotationY;
1247
+ const backZ = -from.rotationZ;
1248
+ let crossX = backY * awayZ - backZ * awayY;
1249
+ let crossY = backZ * awayX - backX * awayZ;
1250
+ let crossZ = backX * awayY - backY * awayX;
1251
+ const ownX = awayX + 2 * (from.rotationW * crossX + backY * crossZ - backZ * crossY);
1252
+ const ownY = awayY + 2 * (from.rotationW * crossY + backZ * crossX - backX * crossZ);
1253
+ const ownZ = awayZ + 2 * (from.rotationW * crossZ + backX * crossY - backY * crossX);
1254
+ crossX = to.rotationY * ownZ - to.rotationZ * ownY;
1255
+ crossY = to.rotationZ * ownX - to.rotationX * ownZ;
1256
+ crossZ = to.rotationX * ownY - to.rotationY * ownX;
1257
+ const shiftX = to.x + ownX + 2 * (to.rotationW * crossX + to.rotationY * crossZ - to.rotationZ * crossY) - x + extraX;
1258
+ const shiftY = to.y + ownY + 2 * (to.rotationW * crossY + to.rotationZ * crossX - to.rotationX * crossZ) - y + extraY;
1259
+ const shiftZ = to.z + ownZ + 2 * (to.rotationW * crossZ + to.rotationX * crossY - to.rotationY * crossX) - z + extraZ;
1260
+ shiftCharacter(character, x, y, z, shiftX, shiftY, shiftZ, ridden);
1261
+ }
1262
+
1263
+ /** Moves a character by a shift a body on a timetable gives it, as far as whatever else is in the way lets it go. */
1264
+ function shiftCharacter(character, x, y, z, shiftX, shiftY, shiftZ, mover) {
1265
+ const shiftM = Math.hypot(shiftX, shiftY, shiftZ);
1266
+ if (shiftM < 1e-7) return;
1267
+ const isBlocked = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, 1, character.size.radiusM, character.size.halfSegmentM, 0, 0, 0, 1, x, y + CHARACTER_SKIN_M + character.size.riseM, z, shiftX / shiftM, shiftY / shiftM, shiftZ / shiftM, shiftM, false, groupsOf(character.layerIndex), mover.rigidBody.handle, SKIPS_CHARACTERS_FLAG_NUMBER | EXCLUDES_BODY_FLAG_NUMBER);
1268
+ const freeNumber = isBlocked ? Math.max(batch.floats()[0] - CHARACTER_SKIN_M, 0) / shiftM : 1;
1269
+ if (freeNumber <= 0) return;
1270
+ batch.bodies.rbSetTranslation(character.rigidBody.handle, x + shiftX * freeNumber, y + shiftY * freeNumber, z + shiftZ * freeNumber, false);
1271
+ isPropagationOwed = true;
1272
+ propagateIfOwed();
1273
+ character.isCarried = true;
1274
+ }
1275
+
1276
+ /**
1277
+ * Before a character's step. One standing on a body on a timetable catches up with it: the body has gone part of
1278
+ * this step's way already where a world steps first. One in a body's way is pushed out of it, as far as the world
1279
+ * lets it go.
1280
+ */
1281
+ function meetTimetables(character, x, y, z) {
1282
+ const contactCount = characterContactsOf(character, x, y, z, RIDE_REACH_M + timetableLeadM);
1283
+ if (!contactCount) return;
1284
+ const floats = batch.floats();
1285
+ const numbers = batch.numbers();
1286
+ let ridden = null;
1287
+ let closestM = -Infinity;
1288
+ let deepestM = 1e-4;
1289
+ let pusher = null;
1290
+ let pushX = 0;
1291
+ let pushY = 0;
1292
+ let pushZ = 0;
1293
+ for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
1294
+ const body = timetableBodyOfTag(numbers[contactIndex * CONTACT_NUMBER_COUNT]);
1295
+ if (!body) continue;
1296
+ const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
1297
+ const depthM = floats[firstIndex + 6];
1298
+ // Under its feet: a surface that faces up enough to stand on.
1299
+ if (floats[firstIndex + 4] >= character.size.minimumStandNormalNumber) {
1300
+ if (depthM > closestM) {
1301
+ closestM = depthM;
1302
+ ridden = body;
1303
+ }
1304
+ } else if (depthM > deepestM) {
1305
+ deepestM = depthM;
1306
+ pusher = body;
1307
+ // Out of it, and as far from it as a character keeps from anything. What comes from the side shoves along
1308
+ // the ground, never up: a low platform's edge doesn't lift what it meets onto itself.
1309
+ const normalX = floats[firstIndex + 3];
1310
+ const normalY = floats[firstIndex + 4];
1311
+ const normalZ = floats[firstIndex + 5];
1312
+ const levelNumber = Math.hypot(normalX, normalZ);
1313
+ const isFromSide = levelNumber > 0.3;
1314
+ const pushM = (depthM + CHARACTER_SKIN_M) / (isFromSide ? levelNumber : 1);
1315
+ pushX = (isFromSide ? normalX / levelNumber : normalX) * pushM;
1316
+ pushY = isFromSide ? 0 : normalY * pushM;
1317
+ pushZ = (isFromSide ? normalZ / levelNumber : normalZ) * pushM;
1318
+ }
1319
+ }
1320
+ if (ridden) {
1321
+ if (!isSamePlace(ridden.fromPlace, ridden.nowPlace)) carryCharacter(character, x, y, z, ridden, ridden.fromPlace, ridden.nowPlace);
1322
+ } else if (pusher) shiftCharacter(character, x, y, z, pushX, pushY, pushZ, pusher);
1323
+ }
1324
+
1325
+ /** After a character's step: one standing on a body on a timetable goes the rest of this step's way with it, so the next step finds it standing there still. */
1326
+ function rideTimetables(character) {
1327
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1328
+ let floats = batch.floats();
1329
+ const x = floats[0];
1330
+ const y = floats[1];
1331
+ const z = floats[2];
1332
+ const contactCount = characterContactsOf(character, x, y, z, RIDE_REACH_M);
1333
+ if (!contactCount) return;
1334
+ floats = batch.floats();
1335
+ const numbers = batch.numbers();
1336
+ let ridden = null;
1337
+ let closestM = -Infinity;
1338
+ let normalX = 0;
1339
+ let normalY = 0;
1340
+ let normalZ = 0;
1341
+ for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
1342
+ const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
1343
+ if (floats[firstIndex + 4] < character.size.minimumStandNormalNumber || floats[firstIndex + 6] <= closestM) continue;
1344
+ const body = timetableBodyOfTag(numbers[contactIndex * CONTACT_NUMBER_COUNT]);
1345
+ if (!body) continue;
1346
+ closestM = floats[firstIndex + 6];
1347
+ normalX = floats[firstIndex + 3];
1348
+ normalY = floats[firstIndex + 4];
1349
+ normalZ = floats[firstIndex + 5];
1350
+ ridden = body;
1351
+ }
1352
+ if (!ridden) return;
1353
+ // Nearer the body than a character keeps from anything (a body that came up under it, a turn's rounding): out to that gap again.
1354
+ const liftM = closestM + CHARACTER_SKIN_M > 1e-4 ? closestM + CHARACTER_SKIN_M : 0;
1355
+ if (liftM > 0 || !isSamePlace(ridden.nowPlace, ridden.toPlace)) carryCharacter(character, x, y, z, ridden, ridden.nowPlace, ridden.toPlace, normalX * liftM, normalY * liftM, normalZ * liftM);
1356
+ }
1357
+
1358
+ /** One character's step by its kind's rules, with the bodies on timetables around it: it rides the one it stands on, and is pushed by one in its way. */
1359
+ function stepKind(character, input, stepContext) {
1360
+ if (!timetableBodies.length || !isKinematicKind) return characterKind.step(character, input, stepContext);
1361
+ character.isCarried = false;
1362
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1363
+ const floats = batch.floats();
1364
+ const x = floats[0];
1365
+ const y = floats[1];
1366
+ const z = floats[2];
1367
+ if (!isNearTimetable(x, y, z)) return characterKind.step(character, input, stepContext);
1368
+ meetTimetables(character, x, y, z);
1369
+ characterKind.step(character, input, stepContext);
1370
+ rideTimetables(character);
1371
+ }
755
1372
 
756
1373
  function stepCharacters(stepContext) {
1374
+ if (timetableBodies.length) stillTimetables();
1375
+ const isMoveNoted = isKinematicKind && world.substepCount > 1 && !characterKind.isSteppedBeforeWorld;
757
1376
  for (const character of characters) {
758
1377
  if (!character || character.isWaiting) continue;
759
1378
  const input = stepContext.inputOf(character.id) ?? characterKind.idleInput;
760
- const ownBefore = sharedOwnOf(character);
1379
+ if (sharedOwnNames.length) sharedOwnInto(character, ownBefore);
761
1380
  // A rider goes where its seat goes: its kind may keep its own fields going there (stamina back on a drive).
762
1381
  if (character.rideBodyIndex >= 0) characterKind.stepRiding?.(character, input, stepContext);
763
- else {
764
- const startM = isKinematicKind && world.substepCount > 1 && !characterKind.isSteppedBeforeWorld ? character.rigidBody.translation() : null;
765
- characterKind.step(character, input, stepContext);
766
- if (startM) noteKinematicMove(character, startM);
1382
+ else if (isMoveNoted) {
1383
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1384
+ const floats = batch.floats();
1385
+ const startX = floats[0];
1386
+ const startY = floats[1];
1387
+ const startZ = floats[2];
1388
+ stepKind(character, input, stepContext);
1389
+ noteKinematicMove(character, startX, startY, startZ);
1390
+ } else stepKind(character, input, stepContext);
1391
+ character.isOwnChanged = false;
1392
+ if (sharedOwnNames.length) {
1393
+ sharedOwnInto(character, ownAfter);
1394
+ for (let nameIndex = 0; nameIndex < sharedOwnNames.length; nameIndex += 1) if (ownAfter[nameIndex] !== ownBefore[nameIndex]) character.isOwnChanged = true;
767
1395
  }
768
- character.isOwnChanged = ownBefore !== null && !isSameOwn(ownBefore, sharedOwnOf(character));
769
1396
  }
770
1397
  }
771
1398
 
@@ -775,21 +1402,30 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
775
1402
  * the step's first substep would have it, and moves the rest of the way through the substeps left, at its speed.
776
1403
  */
777
1404
  const movedCharacters = [];
778
- function noteKinematicMove(character, startM) {
779
- const endM = character.rigidBody.translation();
780
- if (startM.x === endM.x && startM.y === endM.y && startM.z === endM.z) return;
781
- character.moveStartM = { x: startM.x, y: startM.y, z: startM.z };
782
- character.moveEndM = { x: endM.x, y: endM.y, z: endM.z };
1405
+ function noteKinematicMove(character, startX, startY, startZ) {
1406
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1407
+ const floats = batch.floats();
1408
+ if (startX === floats[0] && startY === floats[1] && startZ === floats[2]) return;
1409
+ const startM = (character.moveStartM ??= { x: 0, y: 0, z: 0 });
1410
+ const endM = (character.moveEndM ??= { x: 0, y: 0, z: 0 });
1411
+ startM.x = startX;
1412
+ startM.y = startY;
1413
+ startM.z = startZ;
1414
+ endM.x = floats[0];
1415
+ endM.y = floats[1];
1416
+ endM.z = floats[2];
783
1417
  movedCharacters.push(character);
784
1418
  }
785
1419
  function placeMovedCharacters(substepIndex) {
786
1420
  if (!movedCharacters.length) return;
787
1421
  const isFirst = substepIndex === 1;
1422
+ const nowNumber = substepIndex / world.substepCount;
1423
+ const nextNumber = (substepIndex + 1) / world.substepCount;
788
1424
  for (const character of movedCharacters) {
789
1425
  const { moveStartM: startM, moveEndM: endM } = character;
790
- const along = (fractionNumber) => ({ x: startM.x + (endM.x - startM.x) * fractionNumber, y: startM.y + (endM.y - startM.y) * fractionNumber, z: startM.z + (endM.z - startM.z) * fractionNumber });
791
- if (isFirst) character.rigidBody.setTranslation(along(substepIndex / world.substepCount), false);
792
- character.rigidBody.setNextKinematicTranslation(along((substepIndex + 1) / world.substepCount));
1426
+ const { handle } = character.rigidBody;
1427
+ if (isFirst) batch.bodies.rbSetTranslation(handle, startM.x + (endM.x - startM.x) * nowNumber, startM.y + (endM.y - startM.y) * nowNumber, startM.z + (endM.z - startM.z) * nowNumber, false);
1428
+ batch.bodies.rbSetNextKinematicTranslation(handle, startM.x + (endM.x - startM.x) * nextNumber, startM.y + (endM.y - startM.y) * nextNumber, startM.z + (endM.z - startM.z) * nextNumber);
793
1429
  }
794
1430
  if (isFirst) rapierWorld.propagateModifiedBodyPositionsToColliders();
795
1431
  if (substepIndex === world.substepCount - 1) movedCharacters.length = 0;
@@ -810,9 +1446,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
810
1446
  isSceneOwed = false;
811
1447
  const savedTimestep = rapierWorld.timestep;
812
1448
  rapierWorld.timestep = 0;
813
- rapierWorld.step(eventQueue);
1449
+ stepEngine();
814
1450
  rapierWorld.timestep = savedTimestep;
815
- eventQueue.clear();
816
1451
  }
817
1452
  function stepCharacterAlone(index, input, stepContext) {
818
1453
  const character = characters[index];
@@ -822,42 +1457,42 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
822
1457
  stepCount += 1;
823
1458
  pruneGround();
824
1459
  }
1460
+ if (timetableBodies.length) {
1461
+ placeTimetables(stepContext.tickIndex);
1462
+ timetablesNow(0);
1463
+ }
825
1464
  propagateIfOwed();
826
- if (grounds.length) keepGroundAround(character.rigidBody.translation(), world.groundReachM, stepCount + GROUND_KEPT_STEP_COUNT);
1465
+ if (grounds.length) {
1466
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1467
+ const floats = batch.floats();
1468
+ const x = floats[0];
1469
+ const y = floats[1];
1470
+ const z = floats[2];
1471
+ keepGroundAround(x, y, z, world.groundReachM, stepCount + GROUND_KEPT_STEP_COUNT);
1472
+ }
827
1473
  refreshScene();
828
- characterKind.step(character, input, stepContext);
1474
+ stepKind(character, input, stepContext);
829
1475
  }
830
1476
 
831
1477
  /** Notes, for every moving body a character is touching now, that it did: what a character pushes is drawn with it. */
832
1478
  function noteTouches() {
833
1479
  for (const character of characters) {
834
1480
  if (!character || character.isWaiting) continue;
835
- rapierWorld.contactPairsWith(character.collider, (otherCollider) => {
836
- const owner = ownerByColliderHandle.get(otherCollider.handle);
837
- if (!owner || owner.isCharacter || bodies[owner.index]?.motionIndex !== 0) return;
838
- let isTouching = false;
839
- rapierWorld.contactPair(character.collider, otherCollider, (manifold) => {
840
- if (manifold.numContacts() > 0) isTouching = true;
841
- });
842
- if (isTouching) (bodies[owner.index].touchStepCountByCharacterIndex ??= new Map()).set(character.index, stepCount);
843
- });
1481
+ const touchedCount = raw.touchedBodies(batch.narrowPhase, batch.bodies, batch.colliders, character.collider.handle);
1482
+ if (!touchedCount) continue;
1483
+ const numbers = batch.numbers();
1484
+ for (let touchedIndex = 0; touchedIndex < touchedCount; touchedIndex += 1) {
1485
+ const body = bodies[numbers[touchedIndex]];
1486
+ if (body?.motionIndex === 0) (body.touchStepCountByCharacterIndex ??= new Map()).set(character.index, stepCount);
1487
+ }
844
1488
  }
845
1489
  }
846
1490
 
847
- function noteHits() {
848
- eventQueue.drainCollisionEvents((firstHandle, secondHandle, isStarted) => {
849
- if (!isStarted) return;
850
- const first = ownerByColliderHandle.get(firstHandle);
851
- const second = ownerByColliderHandle.get(secondHandle);
852
- if (!first || !second) return;
853
- for (const [own, other] of [[first, second], [second, first]]) {
854
- if (own.isCharacter || bodies[own.index]?.motionIndex !== 0) continue;
855
- const before = bodies[own.index].velocityBefore;
856
- const otherBefore = other.isCharacter ? (characters[other.index]?.rigidBody.linvel() ?? { x: 0, y: 0, z: 0 }) : bodies[other.index]?.motionIndex === 0 ? bodies[other.index].velocityBefore : { x: 0, y: 0, z: 0 };
857
- const hitSpeedMPerSec = Math.hypot(before.x - otherBefore.x, before.y - otherBefore.y, before.z - otherBefore.z);
858
- if (hitSpeedMPerSec >= MINIMUM_TOLD_HIT_SPEED_M_PER_SEC) hits.push({ bodyIndex: own.index, otherBodyIndex: other.isCharacter ? -1 : other.index, otherCharacterIndex: other.isCharacter ? other.index : -1, speedMPerSec: hitSpeedMPerSec });
859
- }
860
- });
1491
+ /** Takes the hits the engine's last step told: each a moving body that started touching something hard enough to hear. */
1492
+ function noteHits(hitCount) {
1493
+ const floats = batch.floats();
1494
+ const numbers = batch.numbers();
1495
+ for (let hitIndex = 0; hitIndex < hitCount; hitIndex += 1) hits.push({ bodyIndex: numbers[hitIndex * 3], otherBodyIndex: numbers[hitIndex * 3 + 1] - 1, otherCharacterIndex: numbers[hitIndex * 3 + 2] - 1, speedMPerSec: floats[hitIndex] });
861
1496
  }
862
1497
 
863
1498
  /**
@@ -867,6 +1502,10 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
867
1502
  */
868
1503
  function step(stepContext) {
869
1504
  const worldStepContext = { ...stepTools, ...stepContext };
1505
+ if (timetableBodies.length) {
1506
+ placeTimetables(stepContext.timetableTickIndex ?? stepContext.tickIndex);
1507
+ timetablesNow(characterKind.isSteppedBeforeWorld ? 0 : 1 / world.substepCount);
1508
+ }
870
1509
  // What was written since the last step (the word, a teleport) moves its colliders before anything searches them.
871
1510
  propagateIfOwed();
872
1511
  layGround();
@@ -875,55 +1514,101 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
875
1514
  driveVehicles(worldStepContext);
876
1515
  for (let substepIndex = 0; substepIndex < world.substepCount; substepIndex += 1) {
877
1516
  if (substepIndex > 0 && !characterKind.isSteppedBeforeWorld) placeMovedCharacters(substepIndex);
878
- rapierWorld.forEachActiveRigidBody((rigidBody) => {
879
- const bodyIndex = movingBodyByHandle.get(rigidBody.handle);
880
- if (bodyIndex === undefined) return;
881
- const velocity = rigidBody.linvel();
882
- const before = bodies[bodyIndex].velocityBefore;
883
- before.x = velocity.x;
884
- before.y = velocity.y;
885
- before.z = velocity.z;
886
- // A small quick thing looks ahead as far as it goes in a substep, and a little more: the engine's own
887
- // continuous collision misses heightfield ground, so a 7 cm apple at 4 m/s would fall through it.
888
- if (bodies[bodyIndex].isSmall) rigidBody.setSoftCcdPrediction(Math.min(Math.hypot(velocity.x, velocity.y, velocity.z) * substepDurationSec * SMALL_BODY_LOOK_AHEAD_NUMBER + SMALL_BODY_LOOK_AHEAD_MARGIN_M, MAXIMUM_LOOK_AHEAD_M));
889
- });
1517
+ if (timetableBodies.length) aimTimetables(substepIndex);
1518
+ // Every awake moving body's speed is noted (what a hit is told from), and a small quick thing looks ahead as far
1519
+ // as it goes in a substep, and a little more: the engine's own continuous collision misses heightfield ground,
1520
+ // so a 7 cm apple at 4 m/s would fall through it.
1521
+ raw.beforeSubstep(batch.bodies, batch.islands, substepDurationSec);
890
1522
  updateVehicles();
891
- rapierWorld.step(eventQueue);
892
- noteHits();
1523
+ const hitCount = stepEngine();
1524
+ if (hitCount) noteHits(hitCount);
893
1525
  if (substepIndex === 0 && !characterKind.isSteppedBeforeWorld) stepCharacters(worldStepContext);
894
1526
  }
895
1527
  stepCount += 1;
896
1528
  for (const character of characters) if (character && !character.isWaiting && character.rideBodyIndex >= 0) placeRider(character);
897
1529
  if (tracksTouches) noteTouches();
898
1530
  characterKind.afterWorldStep?.(worldStepContext);
1531
+ settle();
1532
+ }
1533
+
1534
+ /**
1535
+ * The step's last act: every awake body is put on the wire's steps inside the engine, and kept as the step left it
1536
+ * until the next one. So what's read after a step is already what the wire carries, and writing it back changes
1537
+ * nothing.
1538
+ */
1539
+ function settle() {
1540
+ settledCount = raw.settleAwake(batch.bodies, batch.islands, ANSWER_FLOAT_COUNT, ANSWER_NUMBER_COUNT);
1541
+ settledStepCount = stepCount;
1542
+ if (!settledCount) return;
1543
+ const numbers = batch.numbers();
1544
+ for (let settledIndex = 0; settledIndex < settledCount; settledIndex += 1) {
1545
+ const body = bodies[numbers[ANSWER_NUMBER_COUNT + settledIndex] & 0x7fffffff];
1546
+ if (!body) continue;
1547
+ body.settledIndex = settledIndex;
1548
+ body.settledStepCount = stepCount;
1549
+ }
1550
+ // Their colliders follow before anything searches them.
1551
+ isPropagationOwed = true;
899
1552
  }
900
1553
 
901
1554
  // ---- What's shared: each thing's fields, read after a step and written when the word differs ----
902
1555
 
1556
+ const blankBodyFields = () => ({ x: 0, y: 0, z: 0, rotation: { x: 0, y: 0, z: 0, w: 1 }, velocityX: 0, velocityY: 0, velocityZ: 0, spinX: 0, spinY: 0, spinZ: 0, layerNumber: 0, motionNumber: 0, steerNumber: 0, massKg: 0 });
1557
+ /** A body's fields from the engine's 13 floats: its place, rotation, speed and spin, with its layer and how it moves now. */
1558
+ function bodyFieldsFrom(body, floats, firstIndex, fields) {
1559
+ fields.x = floats[firstIndex];
1560
+ fields.y = floats[firstIndex + 1];
1561
+ fields.z = floats[firstIndex + 2];
1562
+ const { rotation } = fields;
1563
+ rotation.x = floats[firstIndex + 3];
1564
+ rotation.y = floats[firstIndex + 4];
1565
+ rotation.z = floats[firstIndex + 5];
1566
+ rotation.w = floats[firstIndex + 6];
1567
+ fields.velocityX = floats[firstIndex + 7];
1568
+ fields.velocityY = floats[firstIndex + 8];
1569
+ fields.velocityZ = floats[firstIndex + 9];
1570
+ fields.spinX = floats[firstIndex + 10];
1571
+ fields.spinY = floats[firstIndex + 11];
1572
+ fields.spinZ = floats[firstIndex + 12];
1573
+ fields.layerNumber = body.layerIndex;
1574
+ fields.motionNumber = body.motionIndex;
1575
+ fields.steerNumber = body.vehicle ? body.vehicle.steerNumber : 0;
1576
+ fields.massKg = body.massKg ?? 0;
1577
+ return fields;
1578
+ }
1579
+
903
1580
  /** A body's fields: its place, rotation, speed and spin, its layer and how it moves now. */
904
1581
  function readBody(index) {
905
1582
  const body = bodies[index];
906
- const { rigidBody } = body;
907
- const position = rigidBody.translation();
908
- const rotation = rigidBody.rotation();
909
- const velocity = rigidBody.linvel();
910
- const spin = rigidBody.angvel();
911
- return {
912
- x: position.x,
913
- y: position.y,
914
- z: position.z,
915
- rotation: { x: rotation.x, y: rotation.y, z: rotation.z, w: rotation.w },
916
- velocityX: velocity.x,
917
- velocityY: velocity.y,
918
- velocityZ: velocity.z,
919
- spinX: spin.x,
920
- spinY: spin.y,
921
- spinZ: spin.z,
922
- layerNumber: body.layerIndex,
923
- motionNumber: body.motionIndex,
924
- steerNumber: body.vehicle ? body.vehicle.steerNumber : 0,
925
- massKg: body.massKg ?? 0,
926
- };
1583
+ raw.readBody(batch.bodies, body.rigidBody.handle);
1584
+ return bodyFieldsFrom(body, batch.floats(), 0, blankBodyFields());
1585
+ }
1586
+
1587
+ /**
1588
+ * readBody for whoever reads the fields at once and keeps nothing (the wire, after a step): the body's own object
1589
+ * filled again, with its number and its kind's. A body the step left awake is read from what the step left, on the
1590
+ * wire's steps already.
1591
+ */
1592
+ function readSteppedBody(index) {
1593
+ const body = bodies[index];
1594
+ const fields = (body.steppedFields ??= { ...blankBodyFields(), bodyNumber: index, bodyKindNumber: body.declaration.bodyKindNumber });
1595
+ // A body on a timetable is where the step's index says: what's shared of it is where it was declared, said once.
1596
+ if (body.timetable) {
1597
+ const { positionM, rotation } = body.declaration;
1598
+ fields.x = positionM.x;
1599
+ fields.y = positionM.y;
1600
+ fields.z = positionM.z;
1601
+ fields.rotation.x = rotation.x;
1602
+ fields.rotation.y = rotation.y;
1603
+ fields.rotation.z = rotation.z;
1604
+ fields.rotation.w = rotation.w;
1605
+ fields.layerNumber = body.layerIndex;
1606
+ fields.motionNumber = body.motionIndex;
1607
+ return fields;
1608
+ }
1609
+ if (body.settledStepCount === stepCount) return bodyFieldsFrom(body, batch.floats(), ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT, fields);
1610
+ raw.readBody(batch.bodies, body.rigidBody.handle);
1611
+ return bodyFieldsFrom(body, batch.floats(), 0, fields);
927
1612
  }
928
1613
 
929
1614
  /** Puts a body where readBody's fields say, moving so; at rest when isResting. Its colliders go with it at once. */
@@ -931,48 +1616,71 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
931
1616
  const body = bodies[index];
932
1617
  if (!body || body.declaredMotionIndex === 2) return;
933
1618
  if (fields.layerNumber !== undefined && fields.layerNumber < world.collisionLayers.length) setBodyLayer(body, fields.layerNumber);
1619
+ // A body on a timetable takes its layer from the word, and its place from the step's index alone.
1620
+ if (body.timetable) return;
934
1621
  if (fields.motionNumber !== undefined && fields.motionNumber >= 0 && fields.motionNumber <= 2) setBodyMotion(body, fields.motionNumber);
935
1622
  // Only a real change: the wire's grain (a hundredth of a kilogram) on a declared mass is the same body.
936
1623
  if (fields.massKg > 0 && body.massKg && Math.abs(fields.massKg - body.massKg) > 0.006) setBodyMass(body, fields.massKg);
937
- const { rigidBody } = body;
938
- rigidBody.setTranslation({ x: fields.x, y: fields.y, z: fields.z }, false);
939
- rigidBody.setRotation(fields.rotation, false);
940
1624
  if (body.vehicle && fields.steerNumber !== undefined) body.vehicle.steerNumber = fields.steerNumber;
941
- isPropagationOwed = true;
942
- if (body.motionIndex === 2) return;
943
- if (isResting && body.motionIndex === 0) {
944
- rigidBody.setLinvel({ x: 0, y: 0, z: 0 }, false);
945
- rigidBody.setAngvel({ x: 0, y: 0, z: 0 }, false);
946
- rigidBody.sleep();
947
- } else {
948
- // Written every step (the wire's numbers), so it mustn't wake what's settling down: only what's asleep and moving now.
949
- const isMovingNow = fields.velocityX !== 0 || fields.velocityY !== 0 || fields.velocityZ !== 0 || fields.spinX !== 0 || fields.spinY !== 0 || fields.spinZ !== 0;
950
- const isWoken = rigidBody.isSleeping() && isMovingNow;
951
- rigidBody.setLinvel({ x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ }, isWoken);
952
- rigidBody.setAngvel({ x: fields.spinX, y: fields.spinY, z: fields.spinZ }, isWoken);
1625
+ const { rotation } = fields;
1626
+ const isPutToRest = isResting && body.motionIndex === 0;
1627
+ if (!isPutToRest && body.settledStepCount === stepCount) {
1628
+ // The step left it on the wire's steps: the same numbers back (the wire's, every step) change nothing.
1629
+ const floats = batch.floats();
1630
+ const firstIndex = ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT;
1631
+ if (
1632
+ floats[firstIndex] === Math.fround(fields.x) &&
1633
+ floats[firstIndex + 1] === Math.fround(fields.y) &&
1634
+ floats[firstIndex + 2] === Math.fround(fields.z) &&
1635
+ floats[firstIndex + 3] === Math.fround(rotation.x) &&
1636
+ floats[firstIndex + 4] === Math.fround(rotation.y) &&
1637
+ floats[firstIndex + 5] === Math.fround(rotation.z) &&
1638
+ floats[firstIndex + 6] === Math.fround(rotation.w) &&
1639
+ floats[firstIndex + 7] === Math.fround(fields.velocityX) &&
1640
+ floats[firstIndex + 8] === Math.fround(fields.velocityY) &&
1641
+ floats[firstIndex + 9] === Math.fround(fields.velocityZ) &&
1642
+ floats[firstIndex + 10] === Math.fround(fields.spinX) &&
1643
+ floats[firstIndex + 11] === Math.fround(fields.spinY) &&
1644
+ floats[firstIndex + 12] === Math.fround(fields.spinZ)
1645
+ ) {
1646
+ sameWriteCount += 1;
1647
+ return;
1648
+ }
953
1649
  }
1650
+ changedWriteCount += 1;
1651
+ body.settledStepCount = -1;
1652
+ body.groundKeptStepCount = -Infinity;
1653
+ // Written every step where it differs, so it mustn't wake what's settling down: only what's asleep and moving now.
1654
+ raw.writeBody(batch.bodies, body.rigidBody.handle, fields.x, fields.y, fields.z, rotation.x, rotation.y, rotation.z, rotation.w, fields.velocityX, fields.velocityY, fields.velocityZ, fields.spinX, fields.spinY, fields.spinZ, body.motionIndex === 2 ? WRITE_PLACE_ONLY_NUMBER : isPutToRest ? WRITE_RESTING_NUMBER : WRITE_MOVING_NUMBER);
1655
+ isPropagationOwed = true;
954
1656
  }
955
1657
 
956
1658
  /** A character's fields: the piece's own (its place, speed, facing, footing, seat and layer) and its kind's. */
957
1659
  function readCharacter(index) {
1660
+ return characterFieldsInto(characters[index], {});
1661
+ }
1662
+ function characterFieldsInto(character, fields) {
1663
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1664
+ const floats = batch.floats();
1665
+ fields.x = floats[0];
1666
+ fields.y = floats[1];
1667
+ fields.z = floats[2];
1668
+ fields.velocityX = isKinematicKind ? character.velocity.x : floats[7];
1669
+ fields.velocityY = isKinematicKind ? character.velocity.y : floats[8];
1670
+ fields.velocityZ = isKinematicKind ? character.velocity.z : floats[9];
1671
+ fields.facingYawRad = character.facingYawRad;
1672
+ fields.isGrounded = character.isGrounded;
1673
+ fields.airTickCount = character.airTickCount;
1674
+ fields.rideBodyNumber = character.rideBodyIndex + 1;
1675
+ fields.seatIndex = character.seatIndex;
1676
+ fields.layerNumber = character.ownLayerIndex;
1677
+ fields.sizeNumber = character.sizeIndex;
1678
+ return Object.assign(fields, characterKind.readOwn(character, stepTools));
1679
+ }
1680
+ /** readCharacter for whoever reads the fields at once and keeps nothing (the wire, after a step): the character's own object filled again. */
1681
+ function readSteppedCharacter(index) {
958
1682
  const character = characters[index];
959
- const position = character.rigidBody.translation();
960
- const velocity = isKinematicKind ? character.velocity : character.rigidBody.linvel();
961
- return {
962
- x: position.x,
963
- y: position.y,
964
- z: position.z,
965
- velocityX: velocity.x,
966
- velocityY: velocity.y,
967
- velocityZ: velocity.z,
968
- facingYawRad: character.facingYawRad,
969
- isGrounded: character.isGrounded,
970
- airTickCount: character.airTickCount,
971
- rideBodyNumber: character.rideBodyIndex + 1,
972
- seatIndex: character.seatIndex,
973
- layerNumber: character.ownLayerIndex,
974
- ...characterKind.readOwn(character, stepTools),
975
- };
1683
+ return characterFieldsInto(character, (character.steppedFields ??= {}));
976
1684
  }
977
1685
 
978
1686
  /** Puts a character where readCharacter's fields say; at rest when isResting. */
@@ -985,7 +1693,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
985
1693
  rigidBody.setEnabled(true);
986
1694
  }
987
1695
  if (fields.layerNumber !== undefined && fields.layerNumber < world.collisionLayers.length && fields.layerNumber !== ridingLayerIndex) character.ownLayerIndex = fields.layerNumber;
988
- rigidBody.setTranslation({ x: fields.x, y: fields.y, z: fields.z }, false);
1696
+ if (fields.sizeNumber !== undefined && fields.sizeNumber !== character.sizeIndex) setCharacterSize(character, fields.sizeNumber);
1697
+ batch.bodies.rbSetTranslation(rigidBody.handle, fields.x, fields.y, fields.z, false);
989
1698
  isPropagationOwed = true;
990
1699
  character.facingYawRad = fields.facingYawRad;
991
1700
  character.isGrounded = fields.isGrounded;
@@ -1001,13 +1710,17 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1001
1710
  setCharacterLayer(character, character.ownLayerIndex);
1002
1711
  }
1003
1712
  characterKind.writeOwn(character, fields, stepTools);
1004
- if (isKinematicKind) character.velocity = isResting ? { x: 0, y: 0, z: 0 } : { x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ };
1713
+ if (isKinematicKind) {
1714
+ character.velocity.x = isResting ? 0 : fields.velocityX;
1715
+ character.velocity.y = isResting ? 0 : fields.velocityY;
1716
+ character.velocity.z = isResting ? 0 : fields.velocityZ;
1717
+ }
1005
1718
  else if (isResting && characterKind.canRest?.(character, stepTools) !== false) {
1006
- rigidBody.setLinvel({ x: 0, y: 0, z: 0 }, false);
1719
+ raw.setSpeed(batch.bodies, rigidBody.handle, 0, 0, 0, false);
1007
1720
  rigidBody.sleep();
1008
1721
  } else {
1009
1722
  const isMovingNow = fields.velocityX !== 0 || fields.velocityY !== 0 || fields.velocityZ !== 0;
1010
- rigidBody.setLinvel({ x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ }, rigidBody.isSleeping() && isMovingNow);
1723
+ raw.setSpeed(batch.bodies, rigidBody.handle, fields.velocityX, fields.velocityY, fields.velocityZ, rigidBody.isSleeping() && isMovingNow);
1011
1724
  }
1012
1725
  }
1013
1726
 
@@ -1026,7 +1739,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1026
1739
  body.rigidBody.setAngularDamping(body.declaration.angularDampingNumber ?? nextTuning.angularDampingNumber);
1027
1740
  body.rigidBody.wakeUp();
1028
1741
  }
1029
- controller?.setCharacterMass(nextTuning.characterMassKg ?? 70);
1742
+ for (const size of characterSizes) size.controller?.setCharacterMass(nextTuning.characterMassKg ?? 70);
1030
1743
  characterKind.onTuning?.(nextTuning, stepTools);
1031
1744
  }
1032
1745
 
@@ -1035,9 +1748,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1035
1748
  // Fixed bodies never move, and moving ones start where they're declared: a step settles what the engine knows of them.
1036
1749
  const savedTimestep = rapierWorld.timestep;
1037
1750
  rapierWorld.timestep = 0;
1038
- rapierWorld.step(eventQueue);
1751
+ stepEngine();
1039
1752
  rapierWorld.timestep = savedTimestep;
1040
- eventQueue.clear();
1041
1753
 
1042
1754
  const simulation = {
1043
1755
  world,
@@ -1052,6 +1764,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1052
1764
  tickDurationSec,
1053
1765
  stepTools,
1054
1766
  addBody,
1767
+ freeBodyIndex,
1055
1768
  removeBody,
1056
1769
  addCharacter,
1057
1770
  removeCharacter,
@@ -1069,15 +1782,26 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1069
1782
  stepCharacterAlone,
1070
1783
  refreshScene,
1071
1784
  readBody,
1785
+ readSteppedBody,
1786
+ /** Whether the last step left this body on the wire's steps (it was awake, and nothing has written it since). */
1787
+ isBodyOnSteps: (index) => bodies[index]?.settledStepCount === stepCount && !bodies[index].timetable,
1788
+ /** Puts the bodies on timetables where they are at a step, before the world as it stands then is asked anything. */
1789
+ placeTimetables,
1790
+ /** Where a body on a timetable is at a step (a whole one, or between two for what's drawn): written into { x, y, z, rotationX, rotationY, rotationZ, rotationW }. Null for a body without one. */
1791
+ timetablePlace(index, tickNumber, into) {
1792
+ const timetable = bodies[index]?.timetable;
1793
+ return timetable ? timetablePlaceInto(timetable, tickNumber * tickDurationSec, into) : null;
1794
+ },
1072
1795
  writeBody,
1073
1796
  readCharacter,
1797
+ readSteppedCharacter,
1074
1798
  writeCharacter,
1075
1799
  setTuning,
1076
1800
  ...queries,
1077
1801
  /** Lays the ground near a place for the next step, though nothing moves there: a camera looking past, a query far off. */
1078
1802
  keepGroundNear(point) {
1079
1803
  keptPoints.push({ x: point.x, y: point.y, z: point.z });
1080
- keepGroundAround(point, world.groundReachM, stepCount + GROUND_KEPT_STEP_COUNT);
1804
+ keepGroundAround(point.x, point.y, point.z, world.groundReachM, stepCount + GROUND_KEPT_STEP_COUNT);
1081
1805
  },
1082
1806
  /** A vehicle's wheels as they hang now: [{ suspensionM, spinRad, steerRad, isOnGround }], each how far its spring reaches, how far round it's turned, its steering, and whether it touches anything. Empty for a body without wheels. */
1083
1807
  wheelStates(bodyId) {
@@ -1087,19 +1811,19 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1087
1811
  return body.declaration.wheels.map((wheel, wheelIndex) => ({ suspensionM: controller.wheelSuspensionLength(wheelIndex) ?? wheel.suspensionRestM, spinRad: controller.wheelRotation(wheelIndex) ?? 0, steerRad: controller.wheelSteering(wheelIndex) ?? 0, isOnGround: Boolean(controller.wheelIsInContact(wheelIndex)) }));
1088
1812
  },
1089
1813
  setOffTriangleGroups,
1090
- /** Which triangle groups are off now: a bit for each, group 1 the lowest. */
1091
- offTriangleGroupMaskNumber: () => offTriangleGroupMaskNumber,
1814
+ /** Which triangle groups are off now: one of the three whole numbers setOffTriangleGroups takes, the first when none is asked for. */
1815
+ offTriangleGroupMaskNumber: (maskIndex = 0) => offTriangleGroupMaskNumbers[maskIndex],
1092
1816
  /** How many tiles of ground are laid now. */
1093
1817
  laidGroundTileCount: () => grounds.reduce((total, ground) => total + ground.tiles.size, 0),
1094
1818
  /** Whether a body is at rest: asleep, so nothing about it changes until something touches it. A fixed one always is. */
1095
- isBodyResting: (index) => bodies[index].motionIndex === 2 || (bodies[index].motionIndex === 0 && bodies[index].rigidBody.isSleeping()),
1819
+ isBodyResting: (index) => bodies[index].motionIndex === 2 || Boolean(bodies[index].timetable) || (bodies[index].motionIndex === 0 && bodies[index].rigidBody.isSleeping()),
1096
1820
  isCharacterResting(index) {
1097
1821
  const character = characters[index];
1098
1822
  // A step that changed the kind's own fields (taking a cart's handles, breath coming back) wakes it, so they're sent.
1099
1823
  if (character.isOwnChanged) return false;
1100
1824
  // A rider rests with its vehicle.
1101
1825
  if (character.rideBodyIndex >= 0) return bodies[character.rideBodyIndex]?.rigidBody.isSleeping() ?? true;
1102
- if (isKinematicKind) return character.isGrounded && character.velocity.x === 0 && character.velocity.y === 0 && character.velocity.z === 0 && characterKind.isResting?.(character, stepTools) !== false;
1826
+ if (isKinematicKind) return !character.isCarried && character.isGrounded && character.velocity.x === 0 && character.velocity.y === 0 && character.velocity.z === 0 && characterKind.isResting?.(character, stepTools) !== false;
1103
1827
  return character.rigidBody.isSleeping();
1104
1828
  },
1105
1829
  /** The characters that touched a body in its last quarter second of steps, oldest first; empty where touches aren't kept. */
@@ -1115,11 +1839,30 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1115
1839
  },
1116
1840
  /** Calls a function with the index of every moving body that isn't at rest. */
1117
1841
  forEachAwakeBody(listener) {
1118
- rapierWorld.forEachActiveRigidBody((rigidBody) => {
1119
- const bodyIndex = movingBodyByHandle.get(rigidBody.handle);
1120
- if (bodyIndex !== undefined) listener(bodyIndex);
1842
+ if (settledStepCount !== stepCount) {
1843
+ for (const body of unfixedBodies) if (body.motionIndex === 0 && !body.rigidBody.isSleeping()) listener(body.index);
1844
+ return;
1845
+ }
1846
+ for (let settledIndex = 0; settledIndex < settledCount; settledIndex += 1) {
1847
+ const number = batch.numbers()[ANSWER_NUMBER_COUNT + settledIndex];
1848
+ if (number >= 0x80000000 && bodies[number & 0x7fffffff]?.settledStepCount === stepCount) listener(number & 0x7fffffff);
1849
+ }
1850
+ },
1851
+ /** Adds to a list the index of every moving body the last step left awake below a height: what fell out of the world. */
1852
+ addAwakeBodiesBelow(heightM, found) {
1853
+ simulation.forEachAwakeBody((bodyIndex) => {
1854
+ const body = bodies[bodyIndex];
1855
+ let y;
1856
+ if (body.settledStepCount === stepCount) y = batch.floats()[ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT + 1];
1857
+ else {
1858
+ raw.readBody(batch.bodies, body.rigidBody.handle);
1859
+ y = batch.floats()[1];
1860
+ }
1861
+ if (y < heightM) found.push(bodyIndex);
1121
1862
  });
1122
1863
  },
1864
+ /** How many written bodies already were as written since the simulation was made, and how many weren't. */
1865
+ writeCounts: () => ({ sameWriteCount, changedWriteCount }),
1123
1866
  /** Hits since the last call. */
1124
1867
  takeHits() {
1125
1868
  const taken = hits;
@@ -1128,7 +1871,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1128
1871
  },
1129
1872
  /** Frees the engine's memory: the simulation is over. */
1130
1873
  dispose() {
1131
- eventQueue.free();
1874
+ batch.free();
1132
1875
  rapierWorld.free();
1133
1876
  },
1134
1877
  };