@zaisma/physics 2.4.0 → 2.5.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, heldMesh } 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,54 @@ 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;
80
106
  const bodies = [];
81
107
  const bodyIndexById = new Map();
108
+ /** The bodies on a timetable, and the step their places were last worked out for. */
109
+ const timetableBodies = [];
110
+ let timetableTickIndex = null;
111
+ const blankPlace = () => ({ x: 0, y: 0, z: 0, rotationX: 0, rotationY: 0, rotationZ: 0, rotationW: 1 });
112
+ const copyPlace = (from, to) => {
113
+ to.x = from.x;
114
+ to.y = from.y;
115
+ to.z = from.z;
116
+ to.rotationX = from.rotationX;
117
+ to.rotationY = from.rotationY;
118
+ to.rotationZ = from.rotationZ;
119
+ to.rotationW = from.rotationW;
120
+ };
82
121
  const characters = [];
83
122
  const characterIndexById = new Map();
84
123
  /** Who a collider belongs to: { isCharacter, index }, or { isGround } for laid ground. */
85
124
  const ownerByColliderHandle = new Map();
86
- const movingBodyByHandle = new Map();
87
125
  const joints = new Map();
88
126
  let hits = [];
89
127
  /** Whether bodies were put somewhere since their colliders last followed. */
@@ -105,19 +143,47 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
105
143
  const characterLayerIndex = layerIndexByName.get("character");
106
144
  const groupsOf = (layerIndex) => groupsOfLayer[layerIndex] >>> 0;
107
145
 
146
+ // ---- What a hit says of the collider it met: which triangle of its whole mesh, and its surface ----
147
+ const handleFloats = new Float64Array(1);
148
+ const handleNumbers = new Uint32Array(handleFloats.buffer);
149
+ /** A collider's number, as the engine's calls answer it: the low half of its handle. */
150
+ const colliderNumberOf = (handle) => {
151
+ handleFloats[0] = handle;
152
+ return handleNumbers[0];
153
+ };
154
+ const surfaceIndexByName = new Map(world.surfaceNames.map((surfaceName, surfaceIndex) => [surfaceName, surfaceIndex]));
155
+ /** By collider number: { isMesh, triangleIndexes, surfaceIndices, surfaceName }, for a mesh's colliders and any with a surface. */
156
+ const hitInfoByColliderNumber = new Map();
157
+ /** Notes whose a collider is and, from its shape, what a hit on it says. mesh is heldMesh's answer for a mesh's collider. */
158
+ function ownCollider(collider, owner, shape = null, mesh = null) {
159
+ ownerByColliderHandle.set(collider.handle, owner);
160
+ const surfaceName = shape?.surfaceName ?? null;
161
+ 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 });
162
+ }
163
+ function disownCollider(collider) {
164
+ ownerByColliderHandle.delete(collider.handle);
165
+ hitInfoByColliderNumber.delete(colliderNumberOf(collider.handle));
166
+ }
167
+ /** Colliders on a collision layer of their own (a mesh's group that stops only shots): they stay there when their body changes layer. */
168
+ const ownLayerColliders = new WeakSet();
169
+
108
170
  const gripNumberOf = (declaration) => (declaration.gripPct ?? currentTuning.gripPct) / 100;
109
171
  const bounceNumberOf = (declaration) => (declaration.bouncePct ?? currentTuning.bouncePct) / 100;
110
172
 
173
+ /** The mesh colliderDescriptionOf last described a collider from, or null when it wasn't a mesh. */
174
+ let describedMesh = null;
111
175
  function colliderDescriptionOf(shape) {
112
176
  let description;
177
+ describedMesh = null;
113
178
  if (shape.shapeKind === "box") description = engine.ColliderDesc.cuboid(shape.sizeM.x / 2, shape.sizeM.y / 2, shape.sizeM.z / 2);
114
179
  else if (shape.shapeKind === "ball") description = engine.ColliderDesc.ball(shape.radiusM);
115
180
  else if (shape.shapeKind === "capsule") description = engine.ColliderDesc.capsule(shape.heightM / 2 - shape.radiusM, shape.radiusM);
116
181
  else if (shape.shapeKind === "cylinder") description = engine.ColliderDesc.cylinder(shape.heightM / 2, shape.radiusM);
117
182
  else if (shape.shapeKind === "hull") description = engine.ColliderDesc.convexHull(new Float32Array(shape.pointsM));
118
183
  else {
119
- const mesh = dataOf(shape, readDataFile);
120
- description = engine.ColliderDesc.trimesh(mesh.pointsM, mesh.triangleIndices);
184
+ const meshData = dataOf(shape, readDataFile);
185
+ describedMesh = heldMesh(engine, meshData.pointsM, meshData.triangleIndices);
186
+ description = describedMesh ? new engine.ColliderDesc(describedMesh.shape) : null;
121
187
  }
122
188
  // A hull of points all in one plane has no inside: a small ball stands in, so the body is still there.
123
189
  if (!description) description = engine.ColliderDesc.ball(0.05);
@@ -132,7 +198,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
132
198
  function addGround(body, shape) {
133
199
  const { heightsM } = dataOf(shape, readDataFile);
134
200
  // 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) });
201
+ 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
202
  }
137
203
 
138
204
  function layTile(ground, rowTileIndex, columnTileIndex) {
@@ -156,39 +222,94 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
156
222
  .setRestitution(bounceNumberOf(body.declaration))
157
223
  .setCollisionGroups(groupsOf(body.layerIndex));
158
224
  const collider = rapierWorld.createCollider(description, body.rigidBody);
159
- ownerByColliderHandle.set(collider.handle, { isCharacter: false, index: body.index, isGround: true });
225
+ ownCollider(collider, { isCharacter: false, index: body.index, isGround: true }, shape);
226
+ raw.setColliderTag(collider.handle, bodyTagOf(body.index));
160
227
  isSceneOwed = true;
161
228
  return { collider, keptUntilStepCount: 0 };
162
229
  }
163
230
 
231
+ /** Where a ground's body is and how it's turned: read once for one that never moves, each step for one that may. */
232
+ function placeGround(ground) {
233
+ raw.readBody(batch.bodies, ground.body.rigidBody.handle);
234
+ const floats = batch.floats();
235
+ ground.x = floats[0];
236
+ ground.y = floats[1];
237
+ ground.z = floats[2];
238
+ ground.rotationX = floats[3];
239
+ ground.rotationY = floats[4];
240
+ ground.rotationZ = floats[5];
241
+ ground.rotationW = floats[6];
242
+ ground.isPlaced = true;
243
+ }
244
+
164
245
  /** 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) {
246
+ function keepGroundAround(pointX, pointY, pointZ, reachM, untilStepCount) {
166
247
  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());
248
+ if (!ground.isPlaced) placeGround(ground);
249
+ // The point in the ground's own space: turned back by its body's rotation.
250
+ const x = pointX - ground.x;
251
+ const y = pointY - ground.y;
252
+ const z = pointZ - ground.z;
253
+ const crossX = -ground.rotationY * z + ground.rotationZ * y;
254
+ const crossZ = -ground.rotationX * y + ground.rotationY * x;
255
+ const crossY = -ground.rotationZ * x + ground.rotationX * z;
256
+ const localX = x + 2 * (ground.rotationW * crossX - ground.rotationY * crossZ + ground.rotationZ * crossY);
257
+ const localZ = z + 2 * (ground.rotationW * crossZ - ground.rotationX * crossY + ground.rotationY * crossX);
169
258
  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);
259
+ const firstColumnTileIndex = Math.max(Math.floor((localX - ground.shape.positionM.x - reachM) / tileSizeM), 0);
260
+ const lastColumnTileIndex = Math.min(Math.floor((localX - ground.shape.positionM.x + reachM) / tileSizeM), ground.columnTileCount - 1);
261
+ const firstRowTileIndex = Math.max(Math.floor((localZ - ground.shape.positionM.z - reachM) / tileSizeM), 0);
262
+ const lastRowTileIndex = Math.min(Math.floor((localZ - ground.shape.positionM.z + reachM) / tileSizeM), ground.rowTileCount - 1);
174
263
  for (let rowTileIndex = firstRowTileIndex; rowTileIndex <= lastRowTileIndex; rowTileIndex += 1) {
175
264
  for (let columnTileIndex = firstColumnTileIndex; columnTileIndex <= lastColumnTileIndex; columnTileIndex += 1) {
176
265
  const tileNumber = rowTileIndex * 65536 + columnTileIndex;
177
266
  let tile = ground.tiles.get(tileNumber);
178
267
  if (!tile) ground.tiles.set(tileNumber, (tile = layTile(ground, rowTileIndex, columnTileIndex)));
179
- tile.keptUntilStepCount = Math.max(tile.keptUntilStepCount, untilStepCount);
268
+ if (tile.keptUntilStepCount < untilStepCount) tile.keptUntilStepCount = untilStepCount;
180
269
  }
181
270
  }
182
271
  }
183
272
  }
184
273
 
185
- /** Before each step: ground under everything that moves (asleep too, so it never wakes over a hole), and where the game asked. */
274
+ /**
275
+ * Before each step: ground under everything that moves (asleep too, so it never wakes over a hole), and where the
276
+ * game asked. What the last step left awake is kept from where it left it; what's asleep hasn't moved, so its
277
+ * ground is kept again only now and then, well before it would be taken up.
278
+ */
186
279
  function layGround() {
187
280
  if (!grounds.length) return;
188
281
  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);
282
+ for (const ground of grounds) if (ground.body.motionIndex !== 2) ground.isPlaced = false;
283
+ const isSettled = settledStepCount === stepCount;
284
+ for (const body of bodies) {
285
+ if (!body || body.motionIndex === 2) continue;
286
+ if (isSettled && body.settledStepCount === stepCount) {
287
+ const floats = batch.floats();
288
+ const firstIndex = ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT;
289
+ const x = floats[firstIndex];
290
+ const y = floats[firstIndex + 1];
291
+ const z = floats[firstIndex + 2];
292
+ keepGroundAround(x, y, z, world.groundReachM, untilStepCount);
293
+ } else if (stepCount - body.groundKeptStepCount >= GROUND_KEPT_AGAIN_STEP_COUNT) {
294
+ raw.readBody(batch.bodies, body.rigidBody.handle);
295
+ const floats = batch.floats();
296
+ const x = floats[0];
297
+ const y = floats[1];
298
+ const z = floats[2];
299
+ keepGroundAround(x, y, z, world.groundReachM, untilStepCount);
300
+ } else continue;
301
+ body.groundKeptStepCount = stepCount;
302
+ }
303
+ for (const character of characters) {
304
+ if (!character || character.isWaiting) continue;
305
+ raw.readBody(batch.bodies, character.rigidBody.handle);
306
+ const floats = batch.floats();
307
+ const x = floats[0];
308
+ const y = floats[1];
309
+ const z = floats[2];
310
+ keepGroundAround(x, y, z, world.groundReachM, untilStepCount);
311
+ }
312
+ for (const point of keptPoints) keepGroundAround(point.x, point.y, point.z, world.groundReachM, untilStepCount);
192
313
  keptPoints = [];
193
314
  pruneGround();
194
315
  }
@@ -199,7 +320,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
199
320
  for (const ground of grounds) {
200
321
  for (const [tileNumber, tile] of ground.tiles) {
201
322
  if (tile.keptUntilStepCount >= stepCount) continue;
202
- ownerByColliderHandle.delete(tile.collider.handle);
323
+ disownCollider(tile.collider);
203
324
  rapierWorld.removeCollider(tile.collider, false);
204
325
  ground.tiles.delete(tileNumber);
205
326
  }
@@ -226,7 +347,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
226
347
  .setAngularDamping(declaration.angularDampingNumber ?? currentTuning.angularDampingNumber);
227
348
  const rigidBody = rapierWorld.createRigidBody(description);
228
349
  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 };
350
+ const body = { index, declaration, rigidBody, colliders: [], motionIndex, declaredMotionIndex: motionIndex, layerIndex, vehicle: null, settledIndex: 0, settledStepCount: -1, groundKeptStepCount: -Infinity, steppedFields: null };
230
351
  bodies[index] = body;
231
352
  for (const shape of declaration.shapes) {
232
353
  if (shape.shapeKind === "heightfield") {
@@ -238,9 +359,14 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
238
359
  continue;
239
360
  }
240
361
  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 });
362
+ ownCollider(collider, { isCharacter: false, index }, shape, describedMesh);
363
+ raw.setColliderTag(collider.handle, bodyTagOf(index));
242
364
  body.colliders.push(collider);
243
365
  }
366
+ if (motionIndex !== 2) {
367
+ movableBodyCount += 1;
368
+ batch.reserveAwake(movableBodyCount);
369
+ }
244
370
  if (motionIndex === 0) {
245
371
  // The shapes share the body's mass by how much room each takes.
246
372
  body.massAtUnitDensityKg = rigidBody.mass();
@@ -248,8 +374,9 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
248
374
  // A small thing thrown hard would pass through a wall between two steps.
249
375
  body.isSmall = declaration.massKg < SMALL_BODY_MASS_KG;
250
376
  rigidBody.enableCcd(body.isSmall);
251
- movingBodyByHandle.set(rigidBody.handle, index);
252
377
  }
378
+ raw.setBodyTag(rigidBody.handle, bodyTagOf(index, body.isSmall === true));
379
+ if (declaration.timetable) addTimetableBody(body);
253
380
  if (declaration.wheels.length) body.vehicle = addVehicle(body);
254
381
  bodyIndexById.set(declaration.id, index);
255
382
  return index;
@@ -257,37 +384,38 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
257
384
 
258
385
  /** Triangle groups by number: the colliders of each, switched on and off together. */
259
386
  const groupColliders = new Map();
260
- let offTriangleGroupMaskNumber = 0;
387
+ const offTriangleGroupMaskNumbers = [0, 0, 0];
388
+ const isTriangleGroupOff = (groupNumber) => Boolean(offTriangleGroupMaskNumbers[triangleGroupMaskIndexOf(groupNumber)] & triangleGroupBitNumberOf(groupNumber));
261
389
  /** A mesh whose triangles come in groups: a collider for each group, so a door or a bridge can come and go. */
262
390
  function addGroupedMesh(body, shape) {
263
391
  const { pointsM, triangleIndices } = dataOf(shape, readDataFile);
264
392
  const groupNumbers = shape.triangleGroupNumbers;
265
393
  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 });
394
+ if (shape.triangleSurfaceIndices && shape.triangleSurfaceIndices.length !== groupNumbers.length) refuse("bad_body", `${body.declaration.id}'s mesh has ${groupNumbers.length} triangles and ${shape.triangleSurfaceIndices.length} triangleSurfaceIndices.`, "triangleSurfaceIndices", "Give one surface for each of the mesh's triangles.");
395
+ for (const groupNumber of new Set(groupNumbers)) {
396
+ const mesh = heldMesh(engine, pointsM, triangleIndices, groupNumbers, groupNumber);
397
+ if (!mesh) continue;
398
+ // A group may be on a layer of its own: glass that stops players and not shots, a rail only vehicles meet.
399
+ const ownLayerName = shape.triangleGroups?.find((group) => group.groupNumber === groupNumber)?.collisionLayerName;
400
+ const description = new engine.ColliderDesc(mesh.shape).setTranslation(shape.positionM.x, shape.positionM.y, shape.positionM.z).setRotation(shape.rotation);
401
+ const collider = rapierWorld.createCollider(description.setFriction(gripNumberOf(body.declaration)).setRestitution(bounceNumberOf(body.declaration)).setCollisionGroups(groupsOf(ownLayerName === undefined ? body.layerIndex : layerIndexByName.get(ownLayerName))), body.rigidBody);
402
+ if (ownLayerName !== undefined) ownLayerColliders.add(collider);
403
+ ownCollider(collider, { isCharacter: false, index: body.index }, shape, mesh);
404
+ raw.setColliderTag(collider.handle, bodyTagOf(body.index));
279
405
  body.colliders.push(collider);
280
406
  if (groupNumber === 0) continue;
281
407
  if (!groupColliders.has(groupNumber)) groupColliders.set(groupNumber, []);
282
408
  groupColliders.get(groupNumber).push(collider);
283
- collider.setEnabled(!(offTriangleGroupMaskNumber & (1 << (groupNumber - 1))));
409
+ collider.setEnabled(!isTriangleGroupOff(groupNumber));
284
410
  }
285
411
  }
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))));
412
+ /** Which triangle groups are off: three whole numbers with a bit for each group (triangleGroupMaskIndexOf, triangleGroupBitNumberOf). */
413
+ function setOffTriangleGroups(firstMaskNumber, secondMaskNumber = 0, thirdMaskNumber = 0) {
414
+ if (firstMaskNumber === offTriangleGroupMaskNumbers[0] && secondMaskNumber === offTriangleGroupMaskNumbers[1] && thirdMaskNumber === offTriangleGroupMaskNumbers[2]) return;
415
+ offTriangleGroupMaskNumbers[0] = firstMaskNumber;
416
+ offTriangleGroupMaskNumbers[1] = secondMaskNumber;
417
+ offTriangleGroupMaskNumbers[2] = thirdMaskNumber;
418
+ for (const [groupNumber, colliders] of groupColliders) for (const collider of colliders) collider.setEnabled(!isTriangleGroupOff(groupNumber));
291
419
  isSceneOwed = true;
292
420
  }
293
421
 
@@ -298,10 +426,11 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
298
426
  for (const [jointId, joint] of joints) if (joint.bodyIndexes.includes(index)) removeJoint(jointId);
299
427
  for (const character of characters) if (character?.rideBodyIndex === index) unseat(character);
300
428
  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);
429
+ for (const collider of body.colliders) disownCollider(collider);
430
+ for (const ground of grounds.filter((each) => each.body === body)) for (const tile of ground.tiles.values()) disownCollider(tile.collider);
303
431
  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);
432
+ if (body.declaredMotionIndex !== 2) movableBodyCount -= 1;
433
+ if (body.timetable) timetableBodies.splice(timetableBodies.indexOf(body), 1);
305
434
  rapierWorld.removeRigidBody(body.rigidBody);
306
435
  bodyIndexById.delete(body.declaration.id);
307
436
  bodies[index] = null;
@@ -318,17 +447,16 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
318
447
 
319
448
  /** Changes how a body moves while playing: a parked cart made fixed, a lift made kinematic, and back. */
320
449
  function setBodyMotion(body, motionIndex) {
321
- if (body.motionIndex === motionIndex || body.declaredMotionIndex === 2) return;
450
+ if (body.motionIndex === motionIndex || body.declaredMotionIndex === 2 || body.timetable) return;
322
451
  body.motionIndex = motionIndex;
323
452
  body.rigidBody.setBodyType(bodyTypeOf(motionIndex), true);
324
- if (motionIndex === 0) movingBodyByHandle.set(body.rigidBody.handle, body.index);
325
- else movingBodyByHandle.delete(body.rigidBody.handle);
453
+ body.settledStepCount = -1;
326
454
  }
327
455
 
328
456
  function setBodyLayer(body, layerIndex) {
329
457
  if (body.layerIndex === layerIndex) return;
330
458
  body.layerIndex = layerIndex;
331
- for (const collider of body.colliders) collider.setCollisionGroups(groupsOf(layerIndex));
459
+ for (const collider of body.colliders) if (!ownLayerColliders.has(collider)) collider.setCollisionGroups(groupsOf(layerIndex));
332
460
  }
333
461
 
334
462
  // ---- Vehicles: a body on wheels, driven by whoever sits in its first seat ----
@@ -386,10 +514,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
386
514
  function updateVehicles() {
387
515
  for (const body of bodies) {
388
516
  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
- });
517
+ // Its wheels stand on what its layers say, never on a character and never on the vehicle itself.
518
+ raw.updateVehicle(body.vehicle.controller.raw, batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, substepDurationSec, body.vehicle.wheelGroupsNumber);
393
519
  }
394
520
  }
395
521
 
@@ -483,6 +609,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
483
609
  if (!isKinematicKind) colliderDescription.setMass(currentTuning.characterMassKg ?? 70);
484
610
  const collider = rapierWorld.createCollider(colliderDescription, rigidBody);
485
611
  ownerByColliderHandle.set(collider.handle, { isCharacter: true, index });
612
+ raw.setColliderTag(collider.handle, characterTagOf(index));
613
+ raw.setBodyTag(rigidBody.handle, characterTagOf(index));
486
614
  if (isWaiting) rigidBody.setEnabled(false);
487
615
  const character = {
488
616
  index,
@@ -513,7 +641,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
513
641
  if (!character) return false;
514
642
  characterKind.onCharacterRemoved?.(character, stepTools);
515
643
  for (const [jointId, joint] of joints) if (joint.characterIndexes.includes(index)) removeJoint(jointId);
516
- ownerByColliderHandle.delete(character.collider.handle);
644
+ disownCollider(character.collider);
517
645
  rapierWorld.removeRigidBody(character.rigidBody);
518
646
  characterIndexById.delete(character.id);
519
647
  characters[index] = null;
@@ -566,12 +694,6 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
566
694
 
567
695
  // ---- Queries, as a character kind and a game ask them ----
568
696
 
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
697
  /** The groups a query searches with: the layers named (all, when none), as a layer that touches them. */
576
698
  const queryGroupsOf = (layerNames) => {
577
699
  if (!layerNames) return 0xffffffff;
@@ -585,16 +707,37 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
585
707
  if (bodyIndexById.has(exclude)) return bodies[bodyIndexById.get(exclude)].rigidBody;
586
708
  return null;
587
709
  };
710
+ // 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.
711
+ const queryFlagsOf = (excluded) => (isEachCharacterAlone ? SKIPS_CHARACTERS_FLAG_NUMBER : 0) | (excluded ? EXCLUDES_BODY_FLAG_NUMBER : 0);
712
+ /** A tagNumber's body id, or null when it isn't a body's. */
713
+ const bodyIdOfTag = (tagNumber) => ((tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? (bodies[tagNumber >>> 8]?.declaration.id ?? null) : null);
714
+ const characterIdOfTag = (tagNumber) => ((tagNumber & TAG_KIND_MASK_NUMBER) === CHARACTER_TAG_NUMBER ? (characters[tagNumber >>> 8]?.id ?? null) : null);
588
715
 
716
+ /**
717
+ * Which of a mesh's triangles a hit or a contact is on (as the mesh was declared, whatever groups it's in), and
718
+ * what surface that is: null where the collider isn't a mesh, or names no surface.
719
+ */
720
+ function noteSurface(hit, colliderNumber, triangleNumber) {
721
+ const colliderInfo = hitInfoByColliderNumber.get(colliderNumber);
722
+ if (!colliderInfo) {
723
+ hit.triangleIndex = null;
724
+ hit.surfaceName = null;
725
+ return;
726
+ }
727
+ const triangleIndex = !colliderInfo.isMesh || triangleNumber === NO_TRIANGLE_INDEX ? null : colliderInfo.triangleIndexes ? colliderInfo.triangleIndexes[triangleNumber] : triangleNumber;
728
+ hit.triangleIndex = triangleIndex ?? null;
729
+ hit.surfaceName = colliderInfo.surfaceIndices && hit.triangleIndex !== null ? (world.surfaceNames[colliderInfo.surfaceIndices[hit.triangleIndex]] ?? null) : colliderInfo.surfaceName;
730
+ }
589
731
  /**
590
732
  * A hit as a query answers it, written into the caller's own object when it gives one (a game casting thousands of
591
733
  * rays a second keeps one), else a new one.
592
734
  */
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;
735
+ function hitInto(into, numbers, pointX, pointY, pointZ, normalX, normalY, normalZ, distanceM) {
736
+ 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 };
737
+ const tagNumber = numbers[0];
738
+ hit.bodyId = bodyIdOfTag(tagNumber);
739
+ hit.characterId = characterIdOfTag(tagNumber);
740
+ noteSurface(hit, numbers[2], numbers[1]);
598
741
  hit.pointM ??= { x: 0, y: 0, z: 0 };
599
742
  hit.normal ??= { x: 0, y: 0, z: 0 };
600
743
  hit.pointM.x = pointX;
@@ -606,86 +749,121 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
606
749
  hit.distanceM = distanceM;
607
750
  return hit;
608
751
  }
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) {
752
+ /** 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. */
753
+ function castShapeQuery(shapeKindNumber, radiusM, halfSegmentM, rotation, { fromM, directionM, maximumDistanceM, collisionLayerNames = null, excludedId = null, isStoppedAtPenetration = true }, into) {
611
754
  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);
755
+ const excluded = excludedOf(excludedId);
756
+ 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));
757
+ if (!isHit) return null;
758
+ const floats = batch.floats();
759
+ return hitInto(into, batch.numbers(), floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[0]);
760
+ }
761
+ /** Contacts' objects a caller's own list held and no longer shows, kept for the next longer answer. */
762
+ const spareContacts = [];
763
+ /** A capsule's half segment, as the engine takes it: its height is the whole, round ends included. */
764
+ const halfSegmentOf = (radiusM, heightM) => Math.max(heightM / 2 - radiusM, 0);
625
765
 
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
766
  const queries = {
629
- /** The first thing a ray meets: { bodyId, characterId, pointM, normal, distanceM }, or null. With into, written there. */
767
+ /** The first thing a ray meets: { bodyId, characterId, pointM, normal, distanceM, triangleIndex, surfaceName }, or null. With into, written there. */
630
768
  castRay({ fromM, directionM, maximumDistanceM, collisionLayerNames = null, excludedId = null }, into = null) {
631
769
  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);
770
+ const directionX = directionM.x / lengthNumber;
771
+ const directionY = directionM.y / lengthNumber;
772
+ const directionZ = directionM.z / lengthNumber;
773
+ const excluded = excludedOf(excludedId);
774
+ 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));
775
+ if (!isHit) return null;
776
+ const floats = batch.floats();
777
+ const distanceM = floats[0];
778
+ 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
779
  },
638
780
  /** The first thing a ball meets moving along a direction: { bodyId, characterId, pointM, normal, distanceM }, or null. With into, written there. */
639
781
  castBall(query, into = null) {
640
- return castShapeQuery(new engine.Ball(query.radiusM), NO_TURN, query, into);
782
+ return castShapeQuery(0, query.radiusM, 0, NO_TURN, query, into);
641
783
  },
642
784
  /** The first thing a capsule (standing up, or turned by rotation) meets moving along a direction, or null. With into, written there. */
643
785
  castCapsule(query, into = null) {
644
- return castShapeQuery(capsuleOf(query.radiusM, query.heightM), query.rotation ?? NO_TURN, query, into);
786
+ return castShapeQuery(1, query.radiusM, halfSegmentOf(query.radiusM, query.heightM), query.rotation ?? NO_TURN, query, into);
645
787
  },
646
788
  /**
647
789
  * 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.
790
+ * point, the surface's normal there (pointing out of it, toward the capsule), how deep the capsule is in it
791
+ * (depthM, above 0 when it overlaps), the flat normal of the triangle or face it's on (faceNormal), which of a
792
+ * mesh's triangles that is (triangleIndex) and its surface (surfaceName). The way a game's own movement pushes
793
+ * out of walls and stands on slopes. A mesh answers its deepest triangle, or with isEachTriangle every triangle
794
+ * it touches; isOneSided leaves out triangles facing away. With into (a list of the caller's own, kept and given
795
+ * again), written there instead of a new list.
650
796
  */
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);
797
+ overlapCapsule({ centerM, radiusM, heightM, rotation = NO_TURN, collisionLayerNames = null, excludedId = null, marginM = 0, isEachTriangle = false, isOneSided = false }, into = null) {
798
+ const excluded = excludedOf(excludedId);
799
+ 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));
800
+ const contacts = into ?? [];
801
+ const floats = batch.floats();
802
+ const numbers = batch.numbers();
803
+ // A list given again keeps its contacts' objects: the ones past this answer wait for a longer one.
804
+ while (contacts.length > contactCount) spareContacts.push(contacts.pop());
805
+ for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
806
+ const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
807
+ const firstNumberIndex = contactIndex * CONTACT_NUMBER_COUNT;
808
+ const tagNumber = numbers[firstNumberIndex];
809
+ 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 });
810
+ contact.bodyId = bodyIdOfTag(tagNumber);
811
+ contact.characterId = characterIdOfTag(tagNumber);
812
+ contact.pointM.x = floats[firstIndex];
813
+ contact.pointM.y = floats[firstIndex + 1];
814
+ contact.pointM.z = floats[firstIndex + 2];
815
+ contact.normal.x = floats[firstIndex + 3];
816
+ contact.normal.y = floats[firstIndex + 4];
817
+ contact.normal.z = floats[firstIndex + 5];
818
+ contact.depthM = floats[firstIndex + 6];
819
+ contact.faceNormal.x = floats[firstIndex + 7];
820
+ contact.faceNormal.y = floats[firstIndex + 8];
821
+ contact.faceNormal.z = floats[firstIndex + 9];
822
+ noteSurface(contact, numbers[firstNumberIndex + 2], numbers[firstNumberIndex + 1]);
823
+ }
661
824
  return contacts;
662
825
  },
663
826
  /** Everything a ball overlaps: [{ bodyId, characterId }]. */
664
827
  overlapBall({ centerM, radiusM, collisionLayerNames = null, excludedId = null }) {
828
+ const excluded = excludedOf(excludedId);
829
+ 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
830
  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);
831
+ const numbers = batch.numbers();
832
+ for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) {
833
+ const tagNumber = numbers[foundIndex];
834
+ if ((tagNumber & TAG_KIND_MASK_NUMBER) === 0) continue;
835
+ const bodyId = bodyIdOfTag(tagNumber);
836
+ const characterId = characterIdOfTag(tagNumber);
837
+ if (!found.some((each) => each.bodyId === bodyId && each.characterId === characterId)) found.push({ bodyId, characterId });
838
+ }
671
839
  return found;
672
840
  },
673
841
  };
674
842
 
675
843
  /**
676
844
  * 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 }.
845
+ * slopes it can climb, snapped down to the ground under it. Answers { movedM, isGrounded }: a new one, or into
846
+ * (an object of the step's own with a movedM, kept and given again) filled.
678
847
  */
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() };
848
+ function moveAndSlide(character, desiredM, into = null) {
849
+ const moved = into ?? { movedM: { x: 0, y: 0, z: 0 }, isGrounded: false };
850
+ if (!controller) {
851
+ moved.movedM.x = 0;
852
+ moved.movedM.y = 0;
853
+ moved.movedM.z = 0;
854
+ moved.isGrounded = false;
855
+ return moved;
856
+ }
857
+ // Characters that each move alone (each player predicts only their own) walk through each other: where another is
858
+ // stands differently in every game. The move puts the character's body there, its collider with it at once: the
859
+ // next character's move (and its own next) sees where it is.
860
+ 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);
861
+ const floats = batch.floats();
862
+ moved.movedM.x = floats[0];
863
+ moved.movedM.y = floats[1];
864
+ moved.movedM.z = floats[2];
865
+ moved.isGrounded = isGrounded;
866
+ return moved;
689
867
  }
690
868
 
691
869
  /** What a character kind's step reaches: the world's queries, the move, the bodies and characters by id. */
@@ -721,9 +899,10 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
721
899
  characterState(characterId) {
722
900
  const character = characters[characterIndexById.get(characterId)];
723
901
  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 };
902
+ raw.readBody(batch.bodies, character.rigidBody.handle);
903
+ const floats = batch.floats();
904
+ const velocityMPerSec = isKinematicKind ? { x: character.velocity.x, y: character.velocity.y, z: character.velocity.z } : { x: floats[7], y: floats[8], z: floats[9] };
905
+ 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, own: character.own };
727
906
  },
728
907
  /**
729
908
  * 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
@@ -746,26 +925,350 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
746
925
 
747
926
  // 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
927
  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]));
928
+ const NO_OWN = Object.freeze({});
929
+ /** A character's shared own fields into a list kept for it: a group as its text, so a change inside it shows. */
930
+ const sharedOwnInto = (character, ownValues) => {
931
+ const own = characterKind.readOwn(character, stepTools) ?? NO_OWN;
932
+ for (let nameIndex = 0; nameIndex < sharedOwnNames.length; nameIndex += 1) {
933
+ const ownValue = own[sharedOwnNames[nameIndex]];
934
+ ownValues[nameIndex] = ownValue !== null && typeof ownValue === "object" ? JSON.stringify(ownValue) : ownValue;
935
+ }
753
936
  };
754
- const isSameOwn = (before, after) => before === null || after.every((fieldValue, fieldIndex) => fieldValue === before[fieldIndex]);
937
+ const ownBefore = new Array(sharedOwnNames.length);
938
+ const ownAfter = new Array(sharedOwnNames.length);
939
+
940
+
941
+ // ---- Timetables: kinematic bodies whose place is the step's index and nothing else ----
942
+ //
943
+ // 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
944
+ // game server, so nothing of it is sent, and a step run again finds it where it was. A character standing on one
945
+ // goes with it, and one in its way is pushed.
946
+
947
+ 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;
948
+
949
+ /** How far from a body's own place its shapes reach, in metres: a ball around it that holds them all. */
950
+ function reachOf(declaration) {
951
+ let reachM = 0;
952
+ for (const shape of declaration.shapes) {
953
+ let shapeReachM = 0;
954
+ 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]));
955
+ else if (shape.sizeM) shapeReachM = Math.hypot(shape.sizeM.x, shape.sizeM.y, shape.sizeM.z) / 2;
956
+ else shapeReachM = Math.hypot(shape.radiusM ?? 0, (shape.heightM ?? 0) / 2) + (shape.radiusM ?? 0);
957
+ const offsetM = shape.positionM ? Math.hypot(shape.positionM.x, shape.positionM.y, shape.positionM.z) : 0;
958
+ reachM = Math.max(reachM, offsetM + shapeReachM);
959
+ }
960
+ return reachM;
961
+ }
962
+
963
+ function addTimetableBody(body) {
964
+ body.timetable = body.declaration.timetable;
965
+ body.reachM = reachOf(body.declaration);
966
+ // Where it is at the step being run, where that step takes it, and where the engine has it now.
967
+ body.fromPlace = blankPlace();
968
+ body.toPlace = blankPlace();
969
+ body.nowPlace = blankPlace();
970
+ body.heldPlace = blankPlace();
971
+ const { positionM, rotation } = body.declaration;
972
+ copyPlace({ x: positionM.x, y: positionM.y, z: positionM.z, rotationX: rotation.x, rotationY: rotation.y, rotationZ: rotation.z, rotationW: rotation.w }, body.heldPlace);
973
+ copyPlace(body.heldPlace, body.nowPlace);
974
+ timetableBodies.push(body);
975
+ timetableTickIndex = null;
976
+ }
977
+
978
+ /** Works out where each timetable has its body at a step, and where that step takes it. */
979
+ function timetablesAt(tickIndex) {
980
+ if (timetableTickIndex === tickIndex) return;
981
+ timetableTickIndex = tickIndex;
982
+ for (const body of timetableBodies) {
983
+ timetablePlaceInto(body.timetable, tickIndex * tickDurationSec, body.fromPlace);
984
+ const { fromPlace: from, toPlace: to } = body;
985
+ timetablePlaceInto(body.timetable, (tickIndex + 1) * tickDurationSec, to);
986
+ // The same rotation has two sets of numbers: the one nearer the step's start, so the way between them is the short one.
987
+ if (from.rotationX * to.rotationX + from.rotationY * to.rotationY + from.rotationZ * to.rotationZ + from.rotationW * to.rotationW < 0) {
988
+ to.rotationX = -to.rotationX;
989
+ to.rotationY = -to.rotationY;
990
+ to.rotationZ = -to.rotationZ;
991
+ to.rotationW = -to.rotationW;
992
+ }
993
+ }
994
+ }
995
+
996
+ /**
997
+ * Puts every body on a timetable where it is at a step: before that step runs, and before anything is asked of the
998
+ * world as it stands at it. A body already there is left alone.
999
+ */
1000
+ function placeTimetables(tickIndex) {
1001
+ if (!timetableBodies.length) return;
1002
+ timetablesAt(tickIndex);
1003
+ for (const body of timetableBodies) {
1004
+ const place = body.fromPlace;
1005
+ if (isSamePlace(place, body.heldPlace)) continue;
1006
+ copyPlace(place, body.heldPlace);
1007
+ const { handle } = body.rigidBody;
1008
+ batch.bodies.rbSetTranslation(handle, place.x, place.y, place.z, false);
1009
+ batch.bodies.rbSetRotation(handle, place.rotationX, place.rotationY, place.rotationZ, place.rotationW, false);
1010
+ isPropagationOwed = true;
1011
+ isSceneOwed = true;
1012
+ }
1013
+ }
1014
+
1015
+ /** 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). */
1016
+ function placeBetween(from, to, shareNumber, into) {
1017
+ into.x = from.x + (to.x - from.x) * shareNumber;
1018
+ into.y = from.y + (to.y - from.y) * shareNumber;
1019
+ into.z = from.z + (to.z - from.z) * shareNumber;
1020
+ const rotationX = from.rotationX + (to.rotationX - from.rotationX) * shareNumber;
1021
+ const rotationY = from.rotationY + (to.rotationY - from.rotationY) * shareNumber;
1022
+ const rotationZ = from.rotationZ + (to.rotationZ - from.rotationZ) * shareNumber;
1023
+ const rotationRealNumber = from.rotationW + (to.rotationW - from.rotationW) * shareNumber;
1024
+ const lengthNumber = Math.sqrt(rotationX * rotationX + rotationY * rotationY + rotationZ * rotationZ + rotationRealNumber * rotationRealNumber) || 1;
1025
+ into.rotationX = rotationX / lengthNumber;
1026
+ into.rotationY = rotationY / lengthNumber;
1027
+ into.rotationZ = rotationZ / lengthNumber;
1028
+ into.rotationW = rotationRealNumber / lengthNumber;
1029
+ return into;
1030
+ }
1031
+
1032
+ /** How far the bodies on timetables have gone of this step's way when the characters step, at most, in metres. */
1033
+ let timetableLeadM = 0;
1034
+ /**
1035
+ * Notes where each body on a timetable is while the characters step: shareNumber of the way from where the step
1036
+ * found it to where the step leaves it (none of it where nothing else is stepped; a world's first substep otherwise).
1037
+ */
1038
+ function timetablesNow(shareNumber) {
1039
+ timetableLeadM = 0;
1040
+ for (const body of timetableBodies) {
1041
+ placeBetween(body.fromPlace, body.toPlace, shareNumber, body.nowPlace);
1042
+ timetableLeadM = Math.max(timetableLeadM, Math.hypot(body.nowPlace.x - body.fromPlace.x, body.nowPlace.y - body.fromPlace.y, body.nowPlace.z - body.fromPlace.z));
1043
+ }
1044
+ }
1045
+
1046
+ const startPlace = blankPlace();
1047
+ const aimedPlace = blankPlace();
1048
+ /**
1049
+ * Before a substep: each body on a timetable is put where the substep starts, exactly, with the speed and spin that
1050
+ * take it to where the substep ends. So the engine moves it there, carrying and pushing what it meets, and no
1051
+ * rounding ever adds up. Only adding and multiplying: the same numbers in every browser and on the game server.
1052
+ */
1053
+ function aimTimetables(substepIndex) {
1054
+ const isLast = substepIndex === world.substepCount - 1;
1055
+ for (const body of timetableBodies) {
1056
+ const { fromPlace: from, toPlace: to } = body;
1057
+ const { handle } = body.rigidBody;
1058
+ if (isSamePlace(from, to)) {
1059
+ // Waiting at a stop: the speed it arrived with ends there.
1060
+ 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);
1061
+ body.hasSpeed = false;
1062
+ continue;
1063
+ }
1064
+ const start = substepIndex === 0 ? from : placeBetween(from, to, substepIndex / world.substepCount, startPlace);
1065
+ const aimed = isLast ? to : placeBetween(from, to, (substepIndex + 1) / world.substepCount, aimedPlace);
1066
+ // The turn from one to the other, as a spin: twice the small rotation between them, over the substep's time.
1067
+ const turnRealNumber = aimed.rotationW * start.rotationW + aimed.rotationX * start.rotationX + aimed.rotationY * start.rotationY + aimed.rotationZ * start.rotationZ;
1068
+ const turnX = -aimed.rotationW * start.rotationX + aimed.rotationX * start.rotationW - aimed.rotationY * start.rotationZ + aimed.rotationZ * start.rotationY;
1069
+ const turnY = -aimed.rotationW * start.rotationY + aimed.rotationY * start.rotationW - aimed.rotationZ * start.rotationX + aimed.rotationX * start.rotationZ;
1070
+ const turnZ = -aimed.rotationW * start.rotationZ + aimed.rotationZ * start.rotationW - aimed.rotationX * start.rotationY + aimed.rotationY * start.rotationX;
1071
+ const spinNumber = (turnRealNumber < 0 ? -2 : 2) / substepDurationSec;
1072
+ 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);
1073
+ body.hasSpeed = true;
1074
+ if (isLast) copyPlace(to, body.heldPlace);
1075
+ }
1076
+ }
1077
+
1078
+ /**
1079
+ * Before the characters step: the bodies on timetables stand still to them. The engine's own character move would
1080
+ * take a character part of the way a moving body under it goes, by the body's speed; a timetable's rider is
1081
+ * carried exactly instead, the same where nothing is stepped. The next substep gives each its speed again.
1082
+ */
1083
+ function stillTimetables() {
1084
+ for (const body of timetableBodies) {
1085
+ if (!body.hasSpeed) continue;
1086
+ body.hasSpeed = false;
1087
+ const now = body.nowPlace;
1088
+ 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);
1089
+ }
1090
+ }
1091
+
1092
+ /** Whether a point is within reach of a body on a timetable: only then is a character asked what it touches. */
1093
+ function isNearTimetable(x, y, z) {
1094
+ for (const body of timetableBodies) {
1095
+ const reachM = body.reachM + world.character.heightM;
1096
+ const awayX = x - body.nowPlace.x;
1097
+ const awayY = y - body.nowPlace.y;
1098
+ const awayZ = z - body.nowPlace.z;
1099
+ if (awayX * awayX + awayY * awayY + awayZ * awayZ <= reachM * reachM) return true;
1100
+ }
1101
+ return false;
1102
+ }
1103
+
1104
+ /** What a character's capsule touches, within marginM of it: the contact count, read from the batch's answer. */
1105
+ const characterContactsOf = (character, x, y, z, marginM) =>
1106
+ raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, x, y + CHARACTER_SKIN_M, z, 0, 0, 0, 1, world.character.radiusM, characterHalfSegmentM, marginM, groupsOf(character.layerIndex), character.rigidBody.handle, SKIPS_CHARACTERS_FLAG_NUMBER | EXCLUDES_BODY_FLAG_NUMBER);
1107
+ /** How far up a surface under a character faces, at least, for the character to stand on it: the world's steepest slope a character climbs. */
1108
+ const minimumStandNormalNumber = Math.cos((world.character.maximumSlopeDeg * Math.PI) / 180);
1109
+ /** The body on a timetable a contact's tag is of, or null. */
1110
+ const timetableBodyOfTag = (tagNumber) => ((tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? (bodies[tagNumber >>> 8]?.timetable ? bodies[tagNumber >>> 8] : null) : null);
1111
+
1112
+ /**
1113
+ * Takes a character from where it is to the same place on a body that went from one place to another, turned
1114
+ * 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.
1115
+ */
1116
+ function carryCharacter(character, x, y, z, ridden, from, to, extraX = 0, extraY = 0, extraZ = 0) {
1117
+ // The character's place seen from the body where it was, then put where the body is.
1118
+ const awayX = x - from.x;
1119
+ const awayY = y - from.y;
1120
+ const awayZ = z - from.z;
1121
+ const backX = -from.rotationX;
1122
+ const backY = -from.rotationY;
1123
+ const backZ = -from.rotationZ;
1124
+ let crossX = backY * awayZ - backZ * awayY;
1125
+ let crossY = backZ * awayX - backX * awayZ;
1126
+ let crossZ = backX * awayY - backY * awayX;
1127
+ const ownX = awayX + 2 * (from.rotationW * crossX + backY * crossZ - backZ * crossY);
1128
+ const ownY = awayY + 2 * (from.rotationW * crossY + backZ * crossX - backX * crossZ);
1129
+ const ownZ = awayZ + 2 * (from.rotationW * crossZ + backX * crossY - backY * crossX);
1130
+ crossX = to.rotationY * ownZ - to.rotationZ * ownY;
1131
+ crossY = to.rotationZ * ownX - to.rotationX * ownZ;
1132
+ crossZ = to.rotationX * ownY - to.rotationY * ownX;
1133
+ const shiftX = to.x + ownX + 2 * (to.rotationW * crossX + to.rotationY * crossZ - to.rotationZ * crossY) - x + extraX;
1134
+ const shiftY = to.y + ownY + 2 * (to.rotationW * crossY + to.rotationZ * crossX - to.rotationX * crossZ) - y + extraY;
1135
+ const shiftZ = to.z + ownZ + 2 * (to.rotationW * crossZ + to.rotationX * crossY - to.rotationY * crossX) - z + extraZ;
1136
+ shiftCharacter(character, x, y, z, shiftX, shiftY, shiftZ, ridden);
1137
+ }
1138
+
1139
+ /** 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. */
1140
+ function shiftCharacter(character, x, y, z, shiftX, shiftY, shiftZ, mover) {
1141
+ const shiftM = Math.hypot(shiftX, shiftY, shiftZ);
1142
+ if (shiftM < 1e-7) return;
1143
+ const isBlocked = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, 1, world.character.radiusM, characterHalfSegmentM, 0, 0, 0, 1, x, y + CHARACTER_SKIN_M, z, shiftX / shiftM, shiftY / shiftM, shiftZ / shiftM, shiftM, false, groupsOf(character.layerIndex), mover.rigidBody.handle, SKIPS_CHARACTERS_FLAG_NUMBER | EXCLUDES_BODY_FLAG_NUMBER);
1144
+ const freeNumber = isBlocked ? Math.max(batch.floats()[0] - CHARACTER_SKIN_M, 0) / shiftM : 1;
1145
+ if (freeNumber <= 0) return;
1146
+ batch.bodies.rbSetTranslation(character.rigidBody.handle, x + shiftX * freeNumber, y + shiftY * freeNumber, z + shiftZ * freeNumber, false);
1147
+ isPropagationOwed = true;
1148
+ propagateIfOwed();
1149
+ character.isCarried = true;
1150
+ }
1151
+
1152
+ /**
1153
+ * Before a character's step. One standing on a body on a timetable catches up with it: the body has gone part of
1154
+ * 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
1155
+ * lets it go.
1156
+ */
1157
+ function meetTimetables(character, x, y, z) {
1158
+ const contactCount = characterContactsOf(character, x, y, z, RIDE_REACH_M + timetableLeadM);
1159
+ if (!contactCount) return;
1160
+ const floats = batch.floats();
1161
+ const numbers = batch.numbers();
1162
+ let ridden = null;
1163
+ let closestM = -Infinity;
1164
+ let deepestM = 1e-4;
1165
+ let pusher = null;
1166
+ let pushX = 0;
1167
+ let pushY = 0;
1168
+ let pushZ = 0;
1169
+ for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
1170
+ const body = timetableBodyOfTag(numbers[contactIndex * CONTACT_NUMBER_COUNT]);
1171
+ if (!body) continue;
1172
+ const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
1173
+ const depthM = floats[firstIndex + 6];
1174
+ // Under its feet: a surface that faces up enough to stand on.
1175
+ if (floats[firstIndex + 4] >= minimumStandNormalNumber) {
1176
+ if (depthM > closestM) {
1177
+ closestM = depthM;
1178
+ ridden = body;
1179
+ }
1180
+ } else if (depthM > deepestM) {
1181
+ deepestM = depthM;
1182
+ pusher = body;
1183
+ // Out of it, and as far from it as a character keeps from anything. What comes from the side shoves along
1184
+ // the ground, never up: a low platform's edge doesn't lift what it meets onto itself.
1185
+ const normalX = floats[firstIndex + 3];
1186
+ const normalY = floats[firstIndex + 4];
1187
+ const normalZ = floats[firstIndex + 5];
1188
+ const levelNumber = Math.hypot(normalX, normalZ);
1189
+ const isFromSide = levelNumber > 0.3;
1190
+ const pushM = (depthM + CHARACTER_SKIN_M) / (isFromSide ? levelNumber : 1);
1191
+ pushX = (isFromSide ? normalX / levelNumber : normalX) * pushM;
1192
+ pushY = isFromSide ? 0 : normalY * pushM;
1193
+ pushZ = (isFromSide ? normalZ / levelNumber : normalZ) * pushM;
1194
+ }
1195
+ }
1196
+ if (ridden) {
1197
+ if (!isSamePlace(ridden.fromPlace, ridden.nowPlace)) carryCharacter(character, x, y, z, ridden, ridden.fromPlace, ridden.nowPlace);
1198
+ } else if (pusher) shiftCharacter(character, x, y, z, pushX, pushY, pushZ, pusher);
1199
+ }
1200
+
1201
+ /** 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. */
1202
+ function rideTimetables(character) {
1203
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1204
+ let floats = batch.floats();
1205
+ const x = floats[0];
1206
+ const y = floats[1];
1207
+ const z = floats[2];
1208
+ const contactCount = characterContactsOf(character, x, y, z, RIDE_REACH_M);
1209
+ if (!contactCount) return;
1210
+ floats = batch.floats();
1211
+ const numbers = batch.numbers();
1212
+ let ridden = null;
1213
+ let closestM = -Infinity;
1214
+ let normalX = 0;
1215
+ let normalY = 0;
1216
+ let normalZ = 0;
1217
+ for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
1218
+ const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
1219
+ if (floats[firstIndex + 4] < minimumStandNormalNumber || floats[firstIndex + 6] <= closestM) continue;
1220
+ const body = timetableBodyOfTag(numbers[contactIndex * CONTACT_NUMBER_COUNT]);
1221
+ if (!body) continue;
1222
+ closestM = floats[firstIndex + 6];
1223
+ normalX = floats[firstIndex + 3];
1224
+ normalY = floats[firstIndex + 4];
1225
+ normalZ = floats[firstIndex + 5];
1226
+ ridden = body;
1227
+ }
1228
+ if (!ridden) return;
1229
+ // 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.
1230
+ const liftM = closestM + CHARACTER_SKIN_M > 1e-4 ? closestM + CHARACTER_SKIN_M : 0;
1231
+ if (liftM > 0 || !isSamePlace(ridden.nowPlace, ridden.toPlace)) carryCharacter(character, x, y, z, ridden, ridden.nowPlace, ridden.toPlace, normalX * liftM, normalY * liftM, normalZ * liftM);
1232
+ }
1233
+
1234
+ /** 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. */
1235
+ function stepKind(character, input, stepContext) {
1236
+ if (!timetableBodies.length || !isKinematicKind) return characterKind.step(character, input, stepContext);
1237
+ character.isCarried = false;
1238
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1239
+ const floats = batch.floats();
1240
+ const x = floats[0];
1241
+ const y = floats[1];
1242
+ const z = floats[2];
1243
+ if (!isNearTimetable(x, y, z)) return characterKind.step(character, input, stepContext);
1244
+ meetTimetables(character, x, y, z);
1245
+ characterKind.step(character, input, stepContext);
1246
+ rideTimetables(character);
1247
+ }
755
1248
 
756
1249
  function stepCharacters(stepContext) {
1250
+ if (timetableBodies.length) stillTimetables();
1251
+ const isMoveNoted = isKinematicKind && world.substepCount > 1 && !characterKind.isSteppedBeforeWorld;
757
1252
  for (const character of characters) {
758
1253
  if (!character || character.isWaiting) continue;
759
1254
  const input = stepContext.inputOf(character.id) ?? characterKind.idleInput;
760
- const ownBefore = sharedOwnOf(character);
1255
+ if (sharedOwnNames.length) sharedOwnInto(character, ownBefore);
761
1256
  // A rider goes where its seat goes: its kind may keep its own fields going there (stamina back on a drive).
762
1257
  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);
1258
+ else if (isMoveNoted) {
1259
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1260
+ const floats = batch.floats();
1261
+ const startX = floats[0];
1262
+ const startY = floats[1];
1263
+ const startZ = floats[2];
1264
+ stepKind(character, input, stepContext);
1265
+ noteKinematicMove(character, startX, startY, startZ);
1266
+ } else stepKind(character, input, stepContext);
1267
+ character.isOwnChanged = false;
1268
+ if (sharedOwnNames.length) {
1269
+ sharedOwnInto(character, ownAfter);
1270
+ for (let nameIndex = 0; nameIndex < sharedOwnNames.length; nameIndex += 1) if (ownAfter[nameIndex] !== ownBefore[nameIndex]) character.isOwnChanged = true;
767
1271
  }
768
- character.isOwnChanged = ownBefore !== null && !isSameOwn(ownBefore, sharedOwnOf(character));
769
1272
  }
770
1273
  }
771
1274
 
@@ -775,21 +1278,30 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
775
1278
  * the step's first substep would have it, and moves the rest of the way through the substeps left, at its speed.
776
1279
  */
777
1280
  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 };
1281
+ function noteKinematicMove(character, startX, startY, startZ) {
1282
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1283
+ const floats = batch.floats();
1284
+ if (startX === floats[0] && startY === floats[1] && startZ === floats[2]) return;
1285
+ const startM = (character.moveStartM ??= { x: 0, y: 0, z: 0 });
1286
+ const endM = (character.moveEndM ??= { x: 0, y: 0, z: 0 });
1287
+ startM.x = startX;
1288
+ startM.y = startY;
1289
+ startM.z = startZ;
1290
+ endM.x = floats[0];
1291
+ endM.y = floats[1];
1292
+ endM.z = floats[2];
783
1293
  movedCharacters.push(character);
784
1294
  }
785
1295
  function placeMovedCharacters(substepIndex) {
786
1296
  if (!movedCharacters.length) return;
787
1297
  const isFirst = substepIndex === 1;
1298
+ const nowNumber = substepIndex / world.substepCount;
1299
+ const nextNumber = (substepIndex + 1) / world.substepCount;
788
1300
  for (const character of movedCharacters) {
789
1301
  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));
1302
+ const { handle } = character.rigidBody;
1303
+ 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);
1304
+ 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
1305
  }
794
1306
  if (isFirst) rapierWorld.propagateModifiedBodyPositionsToColliders();
795
1307
  if (substepIndex === world.substepCount - 1) movedCharacters.length = 0;
@@ -810,9 +1322,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
810
1322
  isSceneOwed = false;
811
1323
  const savedTimestep = rapierWorld.timestep;
812
1324
  rapierWorld.timestep = 0;
813
- rapierWorld.step(eventQueue);
1325
+ stepEngine();
814
1326
  rapierWorld.timestep = savedTimestep;
815
- eventQueue.clear();
816
1327
  }
817
1328
  function stepCharacterAlone(index, input, stepContext) {
818
1329
  const character = characters[index];
@@ -822,42 +1333,42 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
822
1333
  stepCount += 1;
823
1334
  pruneGround();
824
1335
  }
1336
+ if (timetableBodies.length) {
1337
+ placeTimetables(stepContext.tickIndex);
1338
+ timetablesNow(0);
1339
+ }
825
1340
  propagateIfOwed();
826
- if (grounds.length) keepGroundAround(character.rigidBody.translation(), world.groundReachM, stepCount + GROUND_KEPT_STEP_COUNT);
1341
+ if (grounds.length) {
1342
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1343
+ const floats = batch.floats();
1344
+ const x = floats[0];
1345
+ const y = floats[1];
1346
+ const z = floats[2];
1347
+ keepGroundAround(x, y, z, world.groundReachM, stepCount + GROUND_KEPT_STEP_COUNT);
1348
+ }
827
1349
  refreshScene();
828
- characterKind.step(character, input, stepContext);
1350
+ stepKind(character, input, stepContext);
829
1351
  }
830
1352
 
831
1353
  /** Notes, for every moving body a character is touching now, that it did: what a character pushes is drawn with it. */
832
1354
  function noteTouches() {
833
1355
  for (const character of characters) {
834
1356
  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
- });
1357
+ const touchedCount = raw.touchedBodies(batch.narrowPhase, batch.bodies, batch.colliders, character.collider.handle);
1358
+ if (!touchedCount) continue;
1359
+ const numbers = batch.numbers();
1360
+ for (let touchedIndex = 0; touchedIndex < touchedCount; touchedIndex += 1) {
1361
+ const body = bodies[numbers[touchedIndex]];
1362
+ if (body?.motionIndex === 0) (body.touchStepCountByCharacterIndex ??= new Map()).set(character.index, stepCount);
1363
+ }
844
1364
  }
845
1365
  }
846
1366
 
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
- });
1367
+ /** Takes the hits the engine's last step told: each a moving body that started touching something hard enough to hear. */
1368
+ function noteHits(hitCount) {
1369
+ const floats = batch.floats();
1370
+ const numbers = batch.numbers();
1371
+ 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
1372
  }
862
1373
 
863
1374
  /**
@@ -867,6 +1378,10 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
867
1378
  */
868
1379
  function step(stepContext) {
869
1380
  const worldStepContext = { ...stepTools, ...stepContext };
1381
+ if (timetableBodies.length) {
1382
+ placeTimetables(stepContext.timetableTickIndex ?? stepContext.tickIndex);
1383
+ timetablesNow(characterKind.isSteppedBeforeWorld ? 0 : 1 / world.substepCount);
1384
+ }
870
1385
  // What was written since the last step (the word, a teleport) moves its colliders before anything searches them.
871
1386
  propagateIfOwed();
872
1387
  layGround();
@@ -875,55 +1390,101 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
875
1390
  driveVehicles(worldStepContext);
876
1391
  for (let substepIndex = 0; substepIndex < world.substepCount; substepIndex += 1) {
877
1392
  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
- });
1393
+ if (timetableBodies.length) aimTimetables(substepIndex);
1394
+ // Every awake moving body's speed is noted (what a hit is told from), and a small quick thing looks ahead as far
1395
+ // as it goes in a substep, and a little more: the engine's own continuous collision misses heightfield ground,
1396
+ // so a 7 cm apple at 4 m/s would fall through it.
1397
+ raw.beforeSubstep(batch.bodies, batch.islands, substepDurationSec);
890
1398
  updateVehicles();
891
- rapierWorld.step(eventQueue);
892
- noteHits();
1399
+ const hitCount = stepEngine();
1400
+ if (hitCount) noteHits(hitCount);
893
1401
  if (substepIndex === 0 && !characterKind.isSteppedBeforeWorld) stepCharacters(worldStepContext);
894
1402
  }
895
1403
  stepCount += 1;
896
1404
  for (const character of characters) if (character && !character.isWaiting && character.rideBodyIndex >= 0) placeRider(character);
897
1405
  if (tracksTouches) noteTouches();
898
1406
  characterKind.afterWorldStep?.(worldStepContext);
1407
+ settle();
1408
+ }
1409
+
1410
+ /**
1411
+ * 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
1412
+ * until the next one. So what's read after a step is already what the wire carries, and writing it back changes
1413
+ * nothing.
1414
+ */
1415
+ function settle() {
1416
+ settledCount = raw.settleAwake(batch.bodies, batch.islands, ANSWER_FLOAT_COUNT, ANSWER_NUMBER_COUNT);
1417
+ settledStepCount = stepCount;
1418
+ if (!settledCount) return;
1419
+ const numbers = batch.numbers();
1420
+ for (let settledIndex = 0; settledIndex < settledCount; settledIndex += 1) {
1421
+ const body = bodies[numbers[ANSWER_NUMBER_COUNT + settledIndex] & 0x7fffffff];
1422
+ if (!body) continue;
1423
+ body.settledIndex = settledIndex;
1424
+ body.settledStepCount = stepCount;
1425
+ }
1426
+ // Their colliders follow before anything searches them.
1427
+ isPropagationOwed = true;
899
1428
  }
900
1429
 
901
1430
  // ---- What's shared: each thing's fields, read after a step and written when the word differs ----
902
1431
 
1432
+ 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 });
1433
+ /** A body's fields from the engine's 13 floats: its place, rotation, speed and spin, with its layer and how it moves now. */
1434
+ function bodyFieldsFrom(body, floats, firstIndex, fields) {
1435
+ fields.x = floats[firstIndex];
1436
+ fields.y = floats[firstIndex + 1];
1437
+ fields.z = floats[firstIndex + 2];
1438
+ const { rotation } = fields;
1439
+ rotation.x = floats[firstIndex + 3];
1440
+ rotation.y = floats[firstIndex + 4];
1441
+ rotation.z = floats[firstIndex + 5];
1442
+ rotation.w = floats[firstIndex + 6];
1443
+ fields.velocityX = floats[firstIndex + 7];
1444
+ fields.velocityY = floats[firstIndex + 8];
1445
+ fields.velocityZ = floats[firstIndex + 9];
1446
+ fields.spinX = floats[firstIndex + 10];
1447
+ fields.spinY = floats[firstIndex + 11];
1448
+ fields.spinZ = floats[firstIndex + 12];
1449
+ fields.layerNumber = body.layerIndex;
1450
+ fields.motionNumber = body.motionIndex;
1451
+ fields.steerNumber = body.vehicle ? body.vehicle.steerNumber : 0;
1452
+ fields.massKg = body.massKg ?? 0;
1453
+ return fields;
1454
+ }
1455
+
903
1456
  /** A body's fields: its place, rotation, speed and spin, its layer and how it moves now. */
904
1457
  function readBody(index) {
905
1458
  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
- };
1459
+ raw.readBody(batch.bodies, body.rigidBody.handle);
1460
+ return bodyFieldsFrom(body, batch.floats(), 0, blankBodyFields());
1461
+ }
1462
+
1463
+ /**
1464
+ * readBody for whoever reads the fields at once and keeps nothing (the wire, after a step): the body's own object
1465
+ * filled again, with its number and its kind's. A body the step left awake is read from what the step left, on the
1466
+ * wire's steps already.
1467
+ */
1468
+ function readSteppedBody(index) {
1469
+ const body = bodies[index];
1470
+ const fields = (body.steppedFields ??= { ...blankBodyFields(), bodyNumber: index, bodyKindNumber: body.declaration.bodyKindNumber });
1471
+ // A body on a timetable is where the step's index says: what's shared of it is where it was declared, said once.
1472
+ if (body.timetable) {
1473
+ const { positionM, rotation } = body.declaration;
1474
+ fields.x = positionM.x;
1475
+ fields.y = positionM.y;
1476
+ fields.z = positionM.z;
1477
+ fields.rotation.x = rotation.x;
1478
+ fields.rotation.y = rotation.y;
1479
+ fields.rotation.z = rotation.z;
1480
+ fields.rotation.w = rotation.w;
1481
+ fields.layerNumber = body.layerIndex;
1482
+ fields.motionNumber = body.motionIndex;
1483
+ return fields;
1484
+ }
1485
+ if (body.settledStepCount === stepCount) return bodyFieldsFrom(body, batch.floats(), ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT, fields);
1486
+ raw.readBody(batch.bodies, body.rigidBody.handle);
1487
+ return bodyFieldsFrom(body, batch.floats(), 0, fields);
927
1488
  }
928
1489
 
929
1490
  /** Puts a body where readBody's fields say, moving so; at rest when isResting. Its colliders go with it at once. */
@@ -931,48 +1492,70 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
931
1492
  const body = bodies[index];
932
1493
  if (!body || body.declaredMotionIndex === 2) return;
933
1494
  if (fields.layerNumber !== undefined && fields.layerNumber < world.collisionLayers.length) setBodyLayer(body, fields.layerNumber);
1495
+ // A body on a timetable takes its layer from the word, and its place from the step's index alone.
1496
+ if (body.timetable) return;
934
1497
  if (fields.motionNumber !== undefined && fields.motionNumber >= 0 && fields.motionNumber <= 2) setBodyMotion(body, fields.motionNumber);
935
1498
  // Only a real change: the wire's grain (a hundredth of a kilogram) on a declared mass is the same body.
936
1499
  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
1500
  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);
1501
+ const { rotation } = fields;
1502
+ const isPutToRest = isResting && body.motionIndex === 0;
1503
+ if (!isPutToRest && body.settledStepCount === stepCount) {
1504
+ // The step left it on the wire's steps: the same numbers back (the wire's, every step) change nothing.
1505
+ const floats = batch.floats();
1506
+ const firstIndex = ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT;
1507
+ if (
1508
+ floats[firstIndex] === Math.fround(fields.x) &&
1509
+ floats[firstIndex + 1] === Math.fround(fields.y) &&
1510
+ floats[firstIndex + 2] === Math.fround(fields.z) &&
1511
+ floats[firstIndex + 3] === Math.fround(rotation.x) &&
1512
+ floats[firstIndex + 4] === Math.fround(rotation.y) &&
1513
+ floats[firstIndex + 5] === Math.fround(rotation.z) &&
1514
+ floats[firstIndex + 6] === Math.fround(rotation.w) &&
1515
+ floats[firstIndex + 7] === Math.fround(fields.velocityX) &&
1516
+ floats[firstIndex + 8] === Math.fround(fields.velocityY) &&
1517
+ floats[firstIndex + 9] === Math.fround(fields.velocityZ) &&
1518
+ floats[firstIndex + 10] === Math.fround(fields.spinX) &&
1519
+ floats[firstIndex + 11] === Math.fround(fields.spinY) &&
1520
+ floats[firstIndex + 12] === Math.fround(fields.spinZ)
1521
+ ) {
1522
+ sameWriteCount += 1;
1523
+ return;
1524
+ }
953
1525
  }
1526
+ changedWriteCount += 1;
1527
+ body.settledStepCount = -1;
1528
+ body.groundKeptStepCount = -Infinity;
1529
+ // Written every step where it differs, so it mustn't wake what's settling down: only what's asleep and moving now.
1530
+ 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);
1531
+ isPropagationOwed = true;
954
1532
  }
955
1533
 
956
1534
  /** A character's fields: the piece's own (its place, speed, facing, footing, seat and layer) and its kind's. */
957
1535
  function readCharacter(index) {
1536
+ return characterFieldsInto(characters[index], {});
1537
+ }
1538
+ function characterFieldsInto(character, fields) {
1539
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1540
+ const floats = batch.floats();
1541
+ fields.x = floats[0];
1542
+ fields.y = floats[1];
1543
+ fields.z = floats[2];
1544
+ fields.velocityX = isKinematicKind ? character.velocity.x : floats[7];
1545
+ fields.velocityY = isKinematicKind ? character.velocity.y : floats[8];
1546
+ fields.velocityZ = isKinematicKind ? character.velocity.z : floats[9];
1547
+ fields.facingYawRad = character.facingYawRad;
1548
+ fields.isGrounded = character.isGrounded;
1549
+ fields.airTickCount = character.airTickCount;
1550
+ fields.rideBodyNumber = character.rideBodyIndex + 1;
1551
+ fields.seatIndex = character.seatIndex;
1552
+ fields.layerNumber = character.ownLayerIndex;
1553
+ return Object.assign(fields, characterKind.readOwn(character, stepTools));
1554
+ }
1555
+ /** readCharacter for whoever reads the fields at once and keeps nothing (the wire, after a step): the character's own object filled again. */
1556
+ function readSteppedCharacter(index) {
958
1557
  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
- };
1558
+ return characterFieldsInto(character, (character.steppedFields ??= {}));
976
1559
  }
977
1560
 
978
1561
  /** Puts a character where readCharacter's fields say; at rest when isResting. */
@@ -985,7 +1568,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
985
1568
  rigidBody.setEnabled(true);
986
1569
  }
987
1570
  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);
1571
+ batch.bodies.rbSetTranslation(rigidBody.handle, fields.x, fields.y, fields.z, false);
989
1572
  isPropagationOwed = true;
990
1573
  character.facingYawRad = fields.facingYawRad;
991
1574
  character.isGrounded = fields.isGrounded;
@@ -1001,13 +1584,17 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1001
1584
  setCharacterLayer(character, character.ownLayerIndex);
1002
1585
  }
1003
1586
  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 };
1587
+ if (isKinematicKind) {
1588
+ character.velocity.x = isResting ? 0 : fields.velocityX;
1589
+ character.velocity.y = isResting ? 0 : fields.velocityY;
1590
+ character.velocity.z = isResting ? 0 : fields.velocityZ;
1591
+ }
1005
1592
  else if (isResting && characterKind.canRest?.(character, stepTools) !== false) {
1006
- rigidBody.setLinvel({ x: 0, y: 0, z: 0 }, false);
1593
+ raw.setSpeed(batch.bodies, rigidBody.handle, 0, 0, 0, false);
1007
1594
  rigidBody.sleep();
1008
1595
  } else {
1009
1596
  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);
1597
+ raw.setSpeed(batch.bodies, rigidBody.handle, fields.velocityX, fields.velocityY, fields.velocityZ, rigidBody.isSleeping() && isMovingNow);
1011
1598
  }
1012
1599
  }
1013
1600
 
@@ -1035,9 +1622,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1035
1622
  // Fixed bodies never move, and moving ones start where they're declared: a step settles what the engine knows of them.
1036
1623
  const savedTimestep = rapierWorld.timestep;
1037
1624
  rapierWorld.timestep = 0;
1038
- rapierWorld.step(eventQueue);
1625
+ stepEngine();
1039
1626
  rapierWorld.timestep = savedTimestep;
1040
- eventQueue.clear();
1041
1627
 
1042
1628
  const simulation = {
1043
1629
  world,
@@ -1069,15 +1655,26 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1069
1655
  stepCharacterAlone,
1070
1656
  refreshScene,
1071
1657
  readBody,
1658
+ readSteppedBody,
1659
+ /** Whether the last step left this body on the wire's steps (it was awake, and nothing has written it since). */
1660
+ isBodyOnSteps: (index) => bodies[index]?.settledStepCount === stepCount && !bodies[index].timetable,
1661
+ /** Puts the bodies on timetables where they are at a step, before the world as it stands then is asked anything. */
1662
+ placeTimetables,
1663
+ /** 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. */
1664
+ timetablePlace(index, tickNumber, into) {
1665
+ const timetable = bodies[index]?.timetable;
1666
+ return timetable ? timetablePlaceInto(timetable, tickNumber * tickDurationSec, into) : null;
1667
+ },
1072
1668
  writeBody,
1073
1669
  readCharacter,
1670
+ readSteppedCharacter,
1074
1671
  writeCharacter,
1075
1672
  setTuning,
1076
1673
  ...queries,
1077
1674
  /** Lays the ground near a place for the next step, though nothing moves there: a camera looking past, a query far off. */
1078
1675
  keepGroundNear(point) {
1079
1676
  keptPoints.push({ x: point.x, y: point.y, z: point.z });
1080
- keepGroundAround(point, world.groundReachM, stepCount + GROUND_KEPT_STEP_COUNT);
1677
+ keepGroundAround(point.x, point.y, point.z, world.groundReachM, stepCount + GROUND_KEPT_STEP_COUNT);
1081
1678
  },
1082
1679
  /** 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
1680
  wheelStates(bodyId) {
@@ -1087,19 +1684,19 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1087
1684
  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
1685
  },
1089
1686
  setOffTriangleGroups,
1090
- /** Which triangle groups are off now: a bit for each, group 1 the lowest. */
1091
- offTriangleGroupMaskNumber: () => offTriangleGroupMaskNumber,
1687
+ /** Which triangle groups are off now: one of the three whole numbers setOffTriangleGroups takes, the first when none is asked for. */
1688
+ offTriangleGroupMaskNumber: (maskIndex = 0) => offTriangleGroupMaskNumbers[maskIndex],
1092
1689
  /** How many tiles of ground are laid now. */
1093
1690
  laidGroundTileCount: () => grounds.reduce((total, ground) => total + ground.tiles.size, 0),
1094
1691
  /** 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()),
1692
+ isBodyResting: (index) => bodies[index].motionIndex === 2 || Boolean(bodies[index].timetable) || (bodies[index].motionIndex === 0 && bodies[index].rigidBody.isSleeping()),
1096
1693
  isCharacterResting(index) {
1097
1694
  const character = characters[index];
1098
1695
  // A step that changed the kind's own fields (taking a cart's handles, breath coming back) wakes it, so they're sent.
1099
1696
  if (character.isOwnChanged) return false;
1100
1697
  // A rider rests with its vehicle.
1101
1698
  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;
1699
+ 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
1700
  return character.rigidBody.isSleeping();
1104
1701
  },
1105
1702
  /** The characters that touched a body in its last quarter second of steps, oldest first; empty where touches aren't kept. */
@@ -1115,11 +1712,30 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1115
1712
  },
1116
1713
  /** Calls a function with the index of every moving body that isn't at rest. */
1117
1714
  forEachAwakeBody(listener) {
1118
- rapierWorld.forEachActiveRigidBody((rigidBody) => {
1119
- const bodyIndex = movingBodyByHandle.get(rigidBody.handle);
1120
- if (bodyIndex !== undefined) listener(bodyIndex);
1715
+ if (settledStepCount !== stepCount) {
1716
+ for (const body of bodies) if (body && body.motionIndex === 0 && !body.rigidBody.isSleeping()) listener(body.index);
1717
+ return;
1718
+ }
1719
+ for (let settledIndex = 0; settledIndex < settledCount; settledIndex += 1) {
1720
+ const number = batch.numbers()[ANSWER_NUMBER_COUNT + settledIndex];
1721
+ if (number >= 0x80000000 && bodies[number & 0x7fffffff]?.settledStepCount === stepCount) listener(number & 0x7fffffff);
1722
+ }
1723
+ },
1724
+ /** Adds to a list the index of every moving body the last step left awake below a height: what fell out of the world. */
1725
+ addAwakeBodiesBelow(heightM, found) {
1726
+ simulation.forEachAwakeBody((bodyIndex) => {
1727
+ const body = bodies[bodyIndex];
1728
+ let y;
1729
+ if (body.settledStepCount === stepCount) y = batch.floats()[ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT + 1];
1730
+ else {
1731
+ raw.readBody(batch.bodies, body.rigidBody.handle);
1732
+ y = batch.floats()[1];
1733
+ }
1734
+ if (y < heightM) found.push(bodyIndex);
1121
1735
  });
1122
1736
  },
1737
+ /** How many written bodies already were as written since the simulation was made, and how many weren't. */
1738
+ writeCounts: () => ({ sameWriteCount, changedWriteCount }),
1123
1739
  /** Hits since the last call. */
1124
1740
  takeHits() {
1125
1741
  const taken = hits;
@@ -1128,7 +1744,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1128
1744
  },
1129
1745
  /** Frees the engine's memory: the simulation is over. */
1130
1746
  dispose() {
1131
- eventQueue.free();
1747
+ batch.free();
1132
1748
  rapierWorld.free();
1133
1749
  },
1134
1750
  };