@zaisma/physics 2.5.0 → 2.7.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
@@ -15,7 +15,7 @@
15
15
  // whatever was written in since.
16
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
+ import { ANSWER_FLOAT_COUNT, ANSWER_NUMBER_COUNT, RAYS_PER_CALL_COUNT, RAY_HIT_FLOAT_COUNT, BODY_FLOAT_COUNT, BODY_TAG_NUMBER, CHARACTER_TAG_NUMBER, CONTACT_FLOAT_COUNT, CONTACT_NUMBER_COUNT, EACH_TRIANGLE_FLAG_NUMBER, EXCLUDES_BODY_FLAG_NUMBER, NO_TRIANGLE_INDEX, ONE_SIDED_FLAG_NUMBER, SKIPS_CHARACTERS_FLAG_NUMBER, SMALL_TAG_NUMBER, TAG_KIND_MASK_NUMBER, WRITE_MOVING_NUMBER, WRITE_PLACE_ONLY_NUMBER, WRITE_RESTING_NUMBER, createBatch, heldMeshParts, isBigMesh } from "./batch.js";
19
19
 
20
20
  /** A hit slower than this isn't told. */
21
21
  const MINIMUM_TOLD_HIT_SPEED_M_PER_SEC = 1.2;
@@ -31,6 +31,8 @@ const GROUND_KEPT_AGAIN_STEP_COUNT = 30;
31
31
  const CHARACTER_SKIN_M = 0.02;
32
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
33
  const RIDE_REACH_M = CHARACTER_SKIN_M + 0.04;
34
+ /** A point asked of the zones is a ball this small. */
35
+ const POINT_RADIUS_M = 0.001;
34
36
  const NO_TURN = Object.freeze({ x: 0, y: 0, z: 0, w: 1 });
35
37
 
36
38
  /** An angle in radians, wrapped into -PI up to PI. */
@@ -79,12 +81,14 @@ const SUSPENSION_FORCE_HEADROOM_NUMBER = 2.5;
79
81
  * maximumNumber, stepSizeNumber, maximumStepCount }, rotationMaximumStepCount }): with it, the engine leaves every
80
82
  * awake body on those steps as a step ends, so every side steps on from the numbers the wire carries.
81
83
  */
82
- export function createSimulation(engine, world, { tickDurationSec, characterKind, tuning, readDataFile = null, tracksTouches = false, isEachCharacterAlone = false, bodyGrain = null }) {
84
+ export function createSimulation(engine, world, { tickDurationSec, characterKind, tuning, readDataFile = null, tracksTouches = false, isEachCharacterAlone = false, bodyGrain = null, bodyBehaviors = null }) {
83
85
  let currentTuning = tuning;
84
86
  let stepCount = 0;
85
87
  const substepDurationSec = tickDurationSec / world.substepCount;
86
88
  const rapierWorld = new engine.World({ x: 0, y: -currentTuning.gravityMPerSecPerSec, z: 0 });
87
89
  rapierWorld.timestep = substepDurationSec;
90
+ /** One of the engine solver's own small steps inside a substep: what a joint's impulse is read over. */
91
+ const solverStepDurationSec = substepDurationSec / rapierWorld.integrationParameters.numSolverIterations;
88
92
  // The engine's batch calls: a step, a read, a write and a query each cross into the engine once, with plain numbers.
89
93
  const batch = createBatch(engine, rapierWorld);
90
94
  const { raw } = batch;
@@ -103,6 +107,15 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
103
107
  let sameWriteCount = 0;
104
108
  let changedWriteCount = 0;
105
109
  let movableBodyCount = 0;
110
+ /** The bodies that aren't fixed for good, by index: what a step goes through, however many pieces the level is made of. */
111
+ const unfixedBodies = [];
112
+ /** The bodies whose kind has rules of its own (bodies.js), in the order of their indexes. */
113
+ const behavingBodies = [];
114
+ /** The bodies a step's forces push, until that step's end. */
115
+ const forcedBodies = new Set();
116
+ /** Whether the step is before its first engine substep: a force added now pushes through all of them. */
117
+ let isBeforeSubsteps = false;
118
+ let lowestFreeBodyIndex = 0;
106
119
  const bodies = [];
107
120
  const bodyIndexById = new Map();
108
121
  /** The bodies on a timetable, and the step their places were last worked out for. */
@@ -154,7 +167,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
154
167
  const surfaceIndexByName = new Map(world.surfaceNames.map((surfaceName, surfaceIndex) => [surfaceName, surfaceIndex]));
155
168
  /** By collider number: { isMesh, triangleIndexes, surfaceIndices, surfaceName }, for a mesh's colliders and any with a surface. */
156
169
  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. */
170
+ /** Notes whose a collider is and, from its shape, what a hit on it says. mesh is one of heldMeshParts' parts for a mesh's collider. */
158
171
  function ownCollider(collider, owner, shape = null, mesh = null) {
159
172
  ownerByColliderHandle.set(collider.handle, owner);
160
173
  const surfaceName = shape?.surfaceName ?? null;
@@ -182,7 +195,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
182
195
  else if (shape.shapeKind === "hull") description = engine.ColliderDesc.convexHull(new Float32Array(shape.pointsM));
183
196
  else {
184
197
  const meshData = dataOf(shape, readDataFile);
185
- describedMesh = heldMesh(engine, meshData.pointsM, meshData.triangleIndices);
198
+ describedMesh = heldMeshParts(engine, meshData.pointsM, meshData.triangleIndices)[0] ?? null;
186
199
  description = describedMesh ? new engine.ColliderDesc(describedMesh.shape) : null;
187
200
  }
188
201
  // A hull of points all in one plane has no inside: a small ball stands in, so the body is still there.
@@ -281,8 +294,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
281
294
  const untilStepCount = stepCount + GROUND_KEPT_STEP_COUNT;
282
295
  for (const ground of grounds) if (ground.body.motionIndex !== 2) ground.isPlaced = false;
283
296
  const isSettled = settledStepCount === stepCount;
284
- for (const body of bodies) {
285
- if (!body || body.motionIndex === 2) continue;
297
+ for (const body of unfixedBodies) {
298
+ if (body.motionIndex === 2) continue;
286
299
  if (isSettled && body.settledStepCount === stepCount) {
287
300
  const floats = batch.floats();
288
301
  const firstIndex = ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT;
@@ -332,12 +345,16 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
332
345
  const bodyTypeOf = (motionIndex) => (motionIndex === 0 ? engine.RigidBodyType.Dynamic : motionIndex === 1 ? engine.RigidBodyType.KinematicVelocityBased : engine.RigidBodyType.Fixed);
333
346
 
334
347
  /** Adds a body (checkBody's answer) at an index: the next free one, or the one given. Answers the index. */
348
+ /** The lowest index no body has. */
349
+ function freeBodyIndex() {
350
+ while (lowestFreeBodyIndex < bodies.length && bodies[lowestFreeBodyIndex] !== null) lowestFreeBodyIndex += 1;
351
+ return lowestFreeBodyIndex;
352
+ }
353
+
354
+ /** How many times what never moves has changed: a fixed body gone or set moving, a triangle group switched. What rests on it is judged again. */
355
+ let levelChangeCount = 0;
335
356
  function addBody(declaration, givenIndex = null) {
336
- let index = givenIndex;
337
- if (index === null) {
338
- index = bodies.findIndex((held) => held === null);
339
- if (index === -1) index = bodies.length;
340
- }
357
+ const index = givenIndex ?? freeBodyIndex();
341
358
  while (bodies.length <= index) bodies.push(null);
342
359
  const motionIndex = MOTION_KINDS.indexOf(declaration.motionKind);
343
360
  const description = (motionIndex === 0 ? engine.RigidBodyDesc.dynamic() : motionIndex === 1 ? engine.RigidBodyDesc.kinematicVelocityBased() : engine.RigidBodyDesc.fixed())
@@ -347,14 +364,26 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
347
364
  .setAngularDamping(declaration.angularDampingNumber ?? currentTuning.angularDampingNumber);
348
365
  const rigidBody = rapierWorld.createRigidBody(description);
349
366
  const layerIndex = layerIndexByName.get(declaration.collisionLayerName);
350
- const body = { index, declaration, rigidBody, colliders: [], motionIndex, declaredMotionIndex: motionIndex, layerIndex, vehicle: null, settledIndex: 0, settledStepCount: -1, groundKeptStepCount: -Infinity, steppedFields: null };
367
+ const behavior = bodyBehaviors?.[declaration.bodyKindNumber] ?? null;
368
+ const body = { index, id: declaration.id, bodyKindName: behavior?.bodyKindName ?? world.bodyKinds[declaration.bodyKindNumber - 1]?.name ?? null, declaration, rigidBody, colliders: [], motionIndex, declaredMotionIndex: motionIndex, layerIndex, vehicle: null, settledIndex: 0, settledStepCount: -1, groundKeptStepCount: -Infinity, steppedFields: null, behavior, own: behavior ? behavior.startOwn() : null, isOwnChanged: false, driverCharacterId: null, motion: null };
351
369
  bodies[index] = body;
370
+ if (behavior) {
371
+ let placeIndex = behavingBodies.length;
372
+ while (placeIndex > 0 && behavingBodies[placeIndex - 1].index > index) placeIndex -= 1;
373
+ behavingBodies.splice(placeIndex, 0, body);
374
+ }
375
+ if (motionIndex !== 2) {
376
+ // Kept in the order of their indexes, so every side goes through them alike.
377
+ let placeIndex = unfixedBodies.length;
378
+ while (placeIndex > 0 && unfixedBodies[placeIndex - 1].index > index) placeIndex -= 1;
379
+ unfixedBodies.splice(placeIndex, 0, body);
380
+ }
352
381
  for (const shape of declaration.shapes) {
353
382
  if (shape.shapeKind === "heightfield") {
354
383
  addGround(body, shape);
355
384
  continue;
356
385
  }
357
- if (shape.shapeKind === "mesh" && shape.triangleGroupNumbers) {
386
+ if (shape.shapeKind === "mesh" && (shape.triangleGroupNumbers || isBigMesh(dataOf(shape, readDataFile).triangleIndices))) {
358
387
  addGroupedMesh(body, shape);
359
388
  continue;
360
389
  }
@@ -363,6 +392,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
363
392
  raw.setColliderTag(collider.handle, bodyTagOf(index));
364
393
  body.colliders.push(collider);
365
394
  }
395
+ // A body fixed for good is a piece of the level: the engine never pairs two of them, however many touch.
396
+ if (motionIndex === 2) for (const collider of body.colliders) engine.RawBatch.markLevelCollider(batch.colliders, collider.handle);
366
397
  if (motionIndex !== 2) {
367
398
  movableBodyCount += 1;
368
399
  batch.reserveAwake(movableBodyCount);
@@ -386,15 +417,17 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
386
417
  const groupColliders = new Map();
387
418
  const offTriangleGroupMaskNumbers = [0, 0, 0];
388
419
  const isTriangleGroupOff = (groupNumber) => Boolean(offTriangleGroupMaskNumbers[triangleGroupMaskIndexOf(groupNumber)] & triangleGroupBitNumberOf(groupNumber));
389
- /** A mesh whose triangles come in groups: a collider for each group, so a door or a bridge can come and go. */
420
+ /**
421
+ * A mesh of several colliders: one for each group its triangles come in, so a door or a bridge can come and go,
422
+ * and a big mesh's in tiles.
423
+ */
390
424
  function addGroupedMesh(body, shape) {
391
425
  const { pointsM, triangleIndices } = dataOf(shape, readDataFile);
392
426
  const groupNumbers = shape.triangleGroupNumbers;
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.");
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;
427
+ if (groupNumbers && groupNumbers.length !== triangleIndices.length / 3) refuse("bad_body", `${body.declaration.id}'s mesh has ${triangleIndices.length / 3} triangles and ${groupNumbers.length} triangleGroupNumbers.`, "triangleGroupNumbers", "Give one group number for each of the mesh's triangles.");
428
+ if (shape.triangleSurfaceIndices && shape.triangleSurfaceIndices.length !== triangleIndices.length / 3) refuse("bad_body", `${body.declaration.id}'s mesh has ${triangleIndices.length / 3} triangles and ${shape.triangleSurfaceIndices.length} triangleSurfaceIndices.`, "triangleSurfaceIndices", "Give one surface for each of the mesh's triangles.");
429
+ for (const mesh of heldMeshParts(engine, pointsM, triangleIndices, groupNumbers)) {
430
+ const { groupNumber } = mesh;
398
431
  // A group may be on a layer of its own: glass that stops players and not shots, a rail only vehicles meet.
399
432
  const ownLayerName = shape.triangleGroups?.find((group) => group.groupNumber === groupNumber)?.collisionLayerName;
400
433
  const description = new engine.ColliderDesc(mesh.shape).setTranslation(shape.positionM.x, shape.positionM.y, shape.positionM.z).setRotation(shape.rotation);
@@ -415,6 +448,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
415
448
  offTriangleGroupMaskNumbers[0] = firstMaskNumber;
416
449
  offTriangleGroupMaskNumbers[1] = secondMaskNumber;
417
450
  offTriangleGroupMaskNumbers[2] = thirdMaskNumber;
451
+ levelChangeCount += 1;
418
452
  for (const [groupNumber, colliders] of groupColliders) for (const collider of colliders) collider.setEnabled(!isTriangleGroupOff(groupNumber));
419
453
  isSceneOwed = true;
420
454
  }
@@ -422,6 +456,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
422
456
  function removeBody(index) {
423
457
  const body = bodies[index];
424
458
  if (!body) return false;
459
+ levelChangeCount += 1;
425
460
  characterKind.onBodyRemoved?.(index, stepTools);
426
461
  for (const [jointId, joint] of joints) if (joint.bodyIndexes.includes(index)) removeJoint(jointId);
427
462
  for (const character of characters) if (character?.rideBodyIndex === index) unseat(character);
@@ -429,8 +464,15 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
429
464
  for (const collider of body.colliders) disownCollider(collider);
430
465
  for (const ground of grounds.filter((each) => each.body === body)) for (const tile of ground.tiles.values()) disownCollider(tile.collider);
431
466
  for (let groundIndex = grounds.length - 1; groundIndex >= 0; groundIndex -= 1) if (grounds[groundIndex].body === body) grounds.splice(groundIndex, 1);
432
- if (body.declaredMotionIndex !== 2) movableBodyCount -= 1;
467
+ if (body.declaredMotionIndex !== 2) {
468
+ movableBodyCount -= 1;
469
+ unfixedBodies.splice(unfixedBodies.indexOf(body), 1);
470
+ }
471
+ lowestFreeBodyIndex = Math.min(lowestFreeBodyIndex, index);
433
472
  if (body.timetable) timetableBodies.splice(timetableBodies.indexOf(body), 1);
473
+ if (body.behavior) behavingBodies.splice(behavingBodies.indexOf(body), 1);
474
+ forcedBodies.delete(body);
475
+ leaveZones(bodyTagOf(index), body.declaration.id, null);
434
476
  rapierWorld.removeRigidBody(body.rigidBody);
435
477
  bodyIndexById.delete(body.declaration.id);
436
478
  bodies[index] = null;
@@ -447,6 +489,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
447
489
 
448
490
  /** Changes how a body moves while playing: a parked cart made fixed, a lift made kinematic, and back. */
449
491
  function setBodyMotion(body, motionIndex) {
492
+ levelChangeCount += 1;
450
493
  if (body.motionIndex === motionIndex || body.declaredMotionIndex === 2 || body.timetable) return;
451
494
  body.motionIndex = motionIndex;
452
495
  body.rigidBody.setBodyType(bodyTypeOf(motionIndex), true);
@@ -490,8 +533,8 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
490
533
  /** Sets each vehicle's controls from its driver's input, or lets it roll with none. */
491
534
  function driveVehicles(worldStepContext) {
492
535
  const { inputOf } = worldStepContext;
493
- for (const body of bodies) {
494
- if (!body?.vehicle) continue;
536
+ for (const body of unfixedBodies) {
537
+ if (!body.vehicle) continue;
495
538
  const driver = characters.find((character) => character && character.rideBodyIndex === body.index && character.seatIndex === 0);
496
539
  const controls = driver ? characterKind.vehicleControls(inputOf(driver.id) ?? characterKind.idleInput, { bodyId: body.declaration.id, ...stepTools.bodyState(body.declaration.id) }, worldStepContext) : { engineNumber: 0, steerNumber: 0, brakeNumber: 0 };
497
540
  const { vehicle } = body.declaration;
@@ -512,13 +555,82 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
512
555
  }
513
556
 
514
557
  function updateVehicles() {
515
- for (const body of bodies) {
516
- if (!body?.vehicle || body.motionIndex !== 0 || body.rigidBody.isSleeping()) continue;
558
+ for (const body of unfixedBodies) {
559
+ if (!body.vehicle || body.motionIndex !== 0 || body.rigidBody.isSleeping()) continue;
517
560
  // Its wheels stand on what its layers say, never on a character and never on the vehicle itself.
518
561
  raw.updateVehicle(body.vehicle.controller.raw, batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, substepDurationSec, body.vehicle.wheelGroupsNumber);
519
562
  }
520
563
  }
521
564
 
565
+ // ---- Body kinds with rules of their own, and the forces a step pushes with ----
566
+
567
+ const bodyOwnBefore = [];
568
+ /** Steps every body whose kind has rules, before the engine moves the world: each by its driver's input. */
569
+ function stepBodies(worldStepContext) {
570
+ const { inputOf } = worldStepContext;
571
+ for (const body of behavingBodies) body.driverCharacterId = null;
572
+ for (const character of characters) {
573
+ if (!character || character.rideBodyIndex < 0 || character.seatIndex !== 0) continue;
574
+ const ridden = bodies[character.rideBodyIndex];
575
+ if (ridden?.behavior) ridden.driverCharacterId = character.id;
576
+ }
577
+ for (const body of behavingBodies) {
578
+ const { behavior, own } = body;
579
+ body.isOwnChanged = false;
580
+ // At rest with nobody at its controls, nothing about it changes: it isn't stepped, and costs nothing.
581
+ if (body.driverCharacterId === null && !behavior.isSteppedAtRest && (body.motionIndex === 2 || (body.motionIndex === 0 && body.rigidBody.isSleeping()))) continue;
582
+ const { fieldNames } = behavior;
583
+ for (let nameIndex = 0; nameIndex < fieldNames.length; nameIndex += 1) bodyOwnBefore[nameIndex] = own[fieldNames[nameIndex]];
584
+ behavior.step(body, body.driverCharacterId === null ? null : (inputOf(body.driverCharacterId) ?? characterKind.idleInput), worldStepContext);
585
+ // A step that changed the kind's own fields leaves its body awake on the wire, so they're sent.
586
+ for (let nameIndex = 0; nameIndex < fieldNames.length; nameIndex += 1) if (own[fieldNames[nameIndex]] !== bodyOwnBefore[nameIndex]) body.isOwnChanged = true;
587
+ }
588
+ }
589
+
590
+ const bodyGiven = (given) => (typeof given === "string" ? bodies[bodyIndexById.get(given)] : given);
591
+ /**
592
+ * Pushes a moving body for one step. Before the step's first engine substep (a body kind's step, a character
593
+ * kind that steps before the world) it's a force the engine works with through every substep, against gravity
594
+ * and what the body leans on; later in a step it's the same push given at once.
595
+ */
596
+ function forceBody(given, pushed, atM, isTurning) {
597
+ const body = bodyGiven(given);
598
+ if (!body || bodies[body.index] !== body || body.motionIndex !== 0) return false;
599
+ const isAt = !isTurning && atM !== null && atM !== undefined;
600
+ const sizeNumber = isBeforeSubsteps ? 1 : tickDurationSec;
601
+ engine.RawBatch.forceBody(batch.bodies, body.rigidBody.handle, pushed.x * sizeNumber, pushed.y * sizeNumber, pushed.z * sizeNumber, isAt ? atM.x : 0, isAt ? atM.y : 0, isAt ? atM.z : 0, (isAt ? 1 : 0) | (isBeforeSubsteps ? 0 : 2) | (isTurning ? 4 : 0));
602
+ if (isBeforeSubsteps) forcedBodies.add(body);
603
+ body.settledStepCount = -1;
604
+ return true;
605
+ }
606
+ /** The step's engine substeps are done: what pushed through them stops. */
607
+ function endForces() {
608
+ for (const body of forcedBodies) engine.RawBatch.resetBodyForces(batch.bodies, body.rigidBody.handle);
609
+ forcedBodies.clear();
610
+ }
611
+ /** A body's place, rotation, speed and spin now, in the body's own object, filled again at each call. */
612
+ function bodyMotion(given) {
613
+ const body = bodyGiven(given);
614
+ if (!body || bodies[body.index] !== body) return null;
615
+ const motion = (body.motion ??= { positionM: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, velocityMPerSec: { x: 0, y: 0, z: 0 }, spinRadPerSec: { x: 0, y: 0, z: 0 } });
616
+ raw.readBody(batch.bodies, body.rigidBody.handle);
617
+ const floats = batch.floats();
618
+ motion.positionM.x = floats[0];
619
+ motion.positionM.y = floats[1];
620
+ motion.positionM.z = floats[2];
621
+ motion.rotation.x = floats[3];
622
+ motion.rotation.y = floats[4];
623
+ motion.rotation.z = floats[5];
624
+ motion.rotation.w = floats[6];
625
+ motion.velocityMPerSec.x = floats[7];
626
+ motion.velocityMPerSec.y = floats[8];
627
+ motion.velocityMPerSec.z = floats[9];
628
+ motion.spinRadPerSec.x = floats[10];
629
+ motion.spinRadPerSec.y = floats[11];
630
+ motion.spinRadPerSec.z = floats[12];
631
+ return motion;
632
+ }
633
+
522
634
  // ---- Joints ----
523
635
 
524
636
  /** The engine body a joint end names: a body's, or a character's, by id. */
@@ -536,7 +648,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
536
648
  const second = declaration.otherBodyId === null ? null : endOf(declaration.otherBodyId);
537
649
  if (!first || (declaration.otherBodyId !== null && !second)) return false;
538
650
  worldAnchor ??= rapierWorld.createRigidBody(engine.RigidBodyDesc.fixed());
539
- const joint = { declaration, rapierJoint: null, isEnabled: false, bodyIndexes: [first.bodyIndex, second?.bodyIndex ?? -1], characterIndexes: [first.characterIndex, second?.characterIndex ?? -1], first, second };
651
+ const joint = { declaration, rapierJoint: null, isEnabled: false, isBroken: false, motorTargetNumber: declaration.motor?.targetNumber ?? 0, bodyIndexes: [first.bodyIndex, second?.bodyIndex ?? -1], characterIndexes: [first.characterIndex, second?.characterIndex ?? -1], first, second };
540
652
  joints.set(declaration.id, joint);
541
653
  setJointEnabled(joint, isEnabled);
542
654
  return true;
@@ -548,8 +660,11 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
548
660
  if (!isEnabled) {
549
661
  if (joint.rapierJoint) rapierWorld.removeImpulseJoint(joint.rapierJoint, true);
550
662
  joint.rapierJoint = null;
663
+ breakableJoints.delete(joint);
551
664
  return;
552
665
  }
666
+ // Held again, it's whole again.
667
+ setJointBroken(joint, false);
553
668
  const { declaration } = joint;
554
669
  const { anchorM, otherAnchorM, axis } = declaration;
555
670
  const otherRigidBody = joint.second?.rigidBody ?? worldAnchor;
@@ -562,37 +677,91 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
562
677
  else jointData = engine.JointData.rope(declaration.restLengthM, anchorM, otherAnchorM);
563
678
  joint.rapierJoint = rapierWorld.createImpulseJoint(jointData, joint.first.rigidBody, otherRigidBody, true);
564
679
  if ((declaration.jointKind === "hinge" || declaration.jointKind === "slider") && declaration.minimumNumber !== null && declaration.maximumNumber !== null) joint.rapierJoint.setLimits(declaration.minimumNumber, declaration.maximumNumber);
680
+ if (declaration.motor) runMotor(joint);
681
+ if (declaration.breakForceNewtons !== null) breakableJoints.add(joint);
682
+ }
683
+
684
+ /** Sets a joint's motor to its target: the speed it holds, or the place it goes to. */
685
+ function runMotor(joint) {
686
+ const { motor, jointKind } = joint.declaration;
687
+ if (motor.motorKind === "speed") joint.rapierJoint.configureMotorVelocity(joint.motorTargetNumber, motor.dampingNumber);
688
+ else joint.rapierJoint.configureMotorPosition(joint.motorTargetNumber, motor.stiffnessNumber, motor.dampingNumber);
689
+ if (motor.maximumForceNumber !== null) engine.RawBatch.setMotorMaximumForce(batch.impulseJoints, joint.rapierJoint.handle, jointKind === "hinge", motor.maximumForceNumber);
690
+ }
691
+ function setJointMotor(joint, motorTargetNumber) {
692
+ if (!joint.declaration.motor || joint.motorTargetNumber === motorTargetNumber) return;
693
+ joint.motorTargetNumber = motorTargetNumber;
694
+ if (joint.rapierJoint) runMotor(joint);
695
+ }
696
+
697
+ /** The joints that break when they pull or push too hard, while they hold. */
698
+ const breakableJoints = new Set();
699
+ /** How many times a joint has broken or been made whole: whoever tells of breaks looks again when it moves. */
700
+ let jointBreakChangeCount = 0;
701
+ function setJointBroken(joint, isBroken) {
702
+ if (joint.isBroken === isBroken) return;
703
+ joint.isBroken = isBroken;
704
+ jointBreakChangeCount += 1;
705
+ }
706
+ /** After a step's engine substeps: a joint held harder than it bears lets go, broken. */
707
+ function breakJoints() {
708
+ for (const joint of breakableJoints) {
709
+ // The engine keeps what the joint gave over one of its solver's small steps: that, as a force.
710
+ if (engine.RawBatch.jointImpulse(batch.impulseJoints, joint.rapierJoint.handle) <= joint.declaration.breakForceNewtons * solverStepDurationSec) continue;
711
+ setJointEnabled(joint, false);
712
+ setJointBroken(joint, true);
713
+ }
565
714
  }
566
715
 
567
716
  function removeJoint(jointId) {
568
717
  const joint = joints.get(jointId);
569
718
  if (!joint) return false;
570
719
  setJointEnabled(joint, false);
720
+ setJointBroken(joint, false);
571
721
  joints.delete(jointId);
572
722
  return true;
573
723
  }
574
724
 
575
725
  // ---- Characters ----
576
726
 
577
- const characterHalfSegmentM = world.character.heightM / 2 - world.character.radiusM;
578
727
  const isKinematicKind = characterKind.bodyKind === "kinematic";
579
- const controller = isKinematicKind ? rapierWorld.createCharacterController(CHARACTER_SKIN_M) : null;
580
- if (controller) {
581
- controller.setUp({ x: 0, y: 1, z: 0 });
582
- controller.setSlideEnabled(true);
583
- if (world.character.stepHeightM > 0) controller.enableAutostep(world.character.stepHeightM, world.character.radiusM * 0.5, false);
584
- controller.setMaxSlopeClimbAngle((world.character.maximumSlopeDeg * Math.PI) / 180);
585
- controller.setMinSlopeSlideAngle?.(((world.character.maximumSlopeDeg + 5) * Math.PI) / 180);
586
- controller.enableSnapToGround(world.character.stepHeightM > 0 ? world.character.stepHeightM : 0.1);
587
- controller.setApplyImpulsesToDynamicBodies(characterKind.canPushBodies !== false);
588
- controller.setCharacterMass(currentTuning.characterMassKg ?? 70);
589
- }
728
+ /**
729
+ * The sizes a character takes: the world's own first, then the ones it names. A character's body sits where its
730
+ * feet are and half the world's own height more, whatever its size, so a place on the wire means the same for all;
731
+ * its capsule is raised or lowered on it to stand on the same feet.
732
+ */
733
+ const characterSizes = [{ name: null, ...world.character }, ...world.characterSizes].map((characterSize) => {
734
+ const controller = isKinematicKind ? rapierWorld.createCharacterController(CHARACTER_SKIN_M) : null;
735
+ if (controller) {
736
+ controller.setUp({ x: 0, y: 1, z: 0 });
737
+ controller.setSlideEnabled(true);
738
+ if (characterSize.stepHeightM > 0) controller.enableAutostep(characterSize.stepHeightM, characterSize.radiusM * 0.5, false);
739
+ controller.setMaxSlopeClimbAngle((characterSize.maximumSlopeDeg * Math.PI) / 180);
740
+ controller.setMinSlopeSlideAngle?.(((characterSize.maximumSlopeDeg + 5) * Math.PI) / 180);
741
+ controller.enableSnapToGround(characterSize.stepHeightM > 0 ? characterSize.stepHeightM : 0.1);
742
+ controller.setApplyImpulsesToDynamicBodies(characterKind.canPushBodies !== false);
743
+ controller.setCharacterMass(currentTuning.characterMassKg ?? 70);
744
+ }
745
+ return {
746
+ ...characterSize,
747
+ halfSegmentM: characterSize.heightM / 2 - characterSize.radiusM,
748
+ /** How far above the body's place the capsule's middle is. */
749
+ riseM: (characterSize.heightM - world.character.heightM) / 2,
750
+ controller,
751
+ /** How far up a surface under the character faces, at least, for it to stand there: the steepest slope it climbs. */
752
+ minimumStandNormalNumber: Math.cos((characterSize.maximumSlopeDeg * Math.PI) / 180),
753
+ };
754
+ });
755
+ const characterHalfSegmentM = characterSizes[0].halfSegmentM;
756
+ const tallestCharacterHeightM = Math.max(...characterSizes.map((characterSize) => characterSize.heightM));
757
+ const characterSizeIndexByName = new Map(characterSizes.map((characterSize, sizeIndex) => [characterSize.name, sizeIndex]));
590
758
 
591
759
  /**
592
760
  * Adds a character with its feet at a place, at an index: the next free one, or the one given. Answers the index.
593
761
  * With isWaiting it's in the world's lists but not in the world, touching nothing, until writeCharacter says where
594
762
  * it is: for a game that knows a character has joined before it knows where.
595
763
  */
764
+ const colliderRiseM = isKinematicKind ? CHARACTER_SKIN_M : 0;
596
765
  function addCharacter(characterId, feetPositionM, givenIndex = null, isWaiting = false) {
597
766
  let index = givenIndex;
598
767
  if (index === null) {
@@ -605,7 +774,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
605
774
  // No grip of its own, so a character never sticks to a wall it walks along: its feet's hold is in how it's moved.
606
775
  // A kinematic character's capsule sits its controller's gap above the body's place: the controller keeps that gap
607
776
  // from the ground, so the body stands exactly on it (and one placed exactly on the ground isn't already too close).
608
- const colliderDescription = engine.ColliderDesc.capsule(characterHalfSegmentM, world.character.radiusM).setTranslation(0, isKinematicKind ? CHARACTER_SKIN_M : 0, 0).setFriction(0).setFrictionCombineRule(engine.CoefficientCombineRule.Min).setRestitution(0).setCollisionGroups(groupsOf(characterLayerIndex)).setActiveEvents(engine.ActiveEvents.COLLISION_EVENTS);
777
+ const colliderDescription = engine.ColliderDesc.capsule(characterHalfSegmentM, world.character.radiusM).setTranslation(0, colliderRiseM, 0).setFriction(0).setFrictionCombineRule(engine.CoefficientCombineRule.Min).setRestitution(0).setCollisionGroups(groupsOf(characterLayerIndex)).setActiveEvents(engine.ActiveEvents.COLLISION_EVENTS);
609
778
  if (!isKinematicKind) colliderDescription.setMass(currentTuning.characterMassKg ?? 70);
610
779
  const collider = rapierWorld.createCollider(colliderDescription, rigidBody);
611
780
  ownerByColliderHandle.set(collider.handle, { isCharacter: true, index });
@@ -618,6 +787,10 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
618
787
  isWaiting,
619
788
  rigidBody,
620
789
  collider,
790
+ characterSize: characterSizes[0],
791
+ sizeIndex: 0,
792
+ /** Which of the world's characterSizes it is now, or null for the world's own character's. */
793
+ characterSizeName: null,
621
794
  /** A kinematic character's speed: the engine doesn't keep one for it. */
622
795
  velocity: { x: 0, y: 0, z: 0 },
623
796
  facingYawRad: 0,
@@ -642,12 +815,80 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
642
815
  characterKind.onCharacterRemoved?.(character, stepTools);
643
816
  for (const [jointId, joint] of joints) if (joint.characterIndexes.includes(index)) removeJoint(jointId);
644
817
  disownCollider(character.collider);
818
+ leaveZones(characterTagOf(index), null, character.id);
645
819
  rapierWorld.removeRigidBody(character.rigidBody);
646
820
  characterIndexById.delete(character.id);
647
821
  characters[index] = null;
648
822
  return true;
649
823
  }
650
824
 
825
+ /** How near a character's capsule the ground it rests on is, at most: its controller's gap and a little more. */
826
+ const REST_REACH_M = CHARACTER_SKIN_M + 0.03;
827
+ /**
828
+ * Whether a character stands on what never moves and touches nothing else: then, with nothing asked of it and no
829
+ * speed, a step would leave it exactly where it is, and its kind may skip the move. Judged once where it stands,
830
+ * and again only when it has moved, changed size or layer, or the level under it has changed.
831
+ */
832
+ function isRestingOnLevel(character) {
833
+ if (character.rideBodyIndex >= 0) return false;
834
+ raw.readBody(batch.bodies, character.rigidBody.handle);
835
+ let floats = batch.floats();
836
+ const x = floats[0];
837
+ const y = floats[1];
838
+ const z = floats[2];
839
+ const rest = (character.rest ??= { x: NaN, y: NaN, z: NaN, sizeIndex: -1, layerIndex: -1, levelChangeCount: -1, isResting: false });
840
+ if (rest.x === x && rest.y === y && rest.z === z && rest.sizeIndex === character.sizeIndex && rest.layerIndex === character.layerIndex && rest.levelChangeCount === levelChangeCount) return rest.isResting;
841
+ rest.x = x;
842
+ rest.y = y;
843
+ rest.z = z;
844
+ rest.sizeIndex = character.sizeIndex;
845
+ rest.layerIndex = character.layerIndex;
846
+ rest.levelChangeCount = levelChangeCount;
847
+ rest.isResting = false;
848
+ const contactCount = characterContactsOf(character, x, y, z, REST_REACH_M);
849
+ floats = batch.floats();
850
+ const numbers = batch.numbers();
851
+ let isStanding = false;
852
+ for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
853
+ const tagNumber = numbers[contactIndex * CONTACT_NUMBER_COUNT];
854
+ const body = (tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? bodies[tagNumber >>> 8] : null;
855
+ if (!body || body.motionIndex !== 2) return false;
856
+ if (floats[contactIndex * CONTACT_FLOAT_COUNT + 4] >= character.characterSize.minimumStandNormalNumber) isStanding = true;
857
+ }
858
+ rest.isResting = isStanding;
859
+ return isStanding;
860
+ }
861
+
862
+ /** How deep something may reach into a size a character asks to take before the size doesn't fit. */
863
+ const SIZE_FIT_DEPTH_M = 0.02;
864
+ /**
865
+ * Gives a character another of the world's sizes, its feet where they are. With isFitChecked, only where the size
866
+ * has room: answers false, and changes nothing, when something other than the ground it stands on is in its way.
867
+ */
868
+ function setCharacterSize(character, sizeIndex, isFitChecked = false) {
869
+ if (character.sizeIndex === sizeIndex) return true;
870
+ const characterSize = characterSizes[sizeIndex];
871
+ if (!characterSize) return false;
872
+ if (isFitChecked && !character.isWaiting) {
873
+ raw.readBody(batch.bodies, character.rigidBody.handle);
874
+ let floats = batch.floats();
875
+ const contactCount = raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, floats[0], floats[1] + CHARACTER_SKIN_M + characterSize.riseM, floats[2], 0, 0, 0, 1, characterSize.radiusM, characterSize.halfSegmentM, 0, groupsOf(character.layerIndex), character.rigidBody.handle, (isEachCharacterAlone ? SKIPS_CHARACTERS_FLAG_NUMBER : 0) | EXCLUDES_BODY_FLAG_NUMBER | EACH_TRIANGLE_FLAG_NUMBER);
876
+ floats = batch.floats();
877
+ for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
878
+ const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
879
+ if (floats[firstIndex + 6] > SIZE_FIT_DEPTH_M && floats[firstIndex + 4] < characterSize.minimumStandNormalNumber) return false;
880
+ }
881
+ }
882
+ character.characterSize = characterSize;
883
+ character.sizeIndex = sizeIndex;
884
+ character.characterSizeName = characterSize.name;
885
+ character.collider.setShape(new engine.Capsule(characterSize.halfSegmentM, characterSize.radiusM));
886
+ character.collider.setTranslationWrtParent({ x: 0, y: colliderRiseM + characterSize.riseM, z: 0 });
887
+ isPropagationOwed = true;
888
+ isSceneOwed = true;
889
+ return true;
890
+ }
891
+
651
892
  function setCharacterLayer(character, layerIndex) {
652
893
  if (character.layerIndex === layerIndex) return;
653
894
  character.layerIndex = layerIndex;
@@ -732,12 +973,11 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
732
973
  * A hit as a query answers it, written into the caller's own object when it gives one (a game casting thousands of
733
974
  * rays a second keeps one), else a new one.
734
975
  */
735
- function hitInto(into, numbers, pointX, pointY, pointZ, normalX, normalY, normalZ, distanceM) {
976
+ function hitInto(into, tagNumber, triangleNumber, colliderNumber, pointX, pointY, pointZ, normalX, normalY, normalZ, distanceM) {
736
977
  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
978
  hit.bodyId = bodyIdOfTag(tagNumber);
739
979
  hit.characterId = characterIdOfTag(tagNumber);
740
- noteSurface(hit, numbers[2], numbers[1]);
980
+ noteSurface(hit, colliderNumber, triangleNumber);
741
981
  hit.pointM ??= { x: 0, y: 0, z: 0 };
742
982
  hit.normal ??= { x: 0, y: 0, z: 0 };
743
983
  hit.pointM.x = pointX;
@@ -749,14 +989,47 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
749
989
  hit.distanceM = distanceM;
750
990
  return hit;
751
991
  }
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) {
992
+ /** A ball (shapeKindNumber 0), a capsule (1) or a box (2: half its width, height and depth) moved along a direction: the first thing it meets, or null. Its own space is turned by rotation. */
993
+ function castShapeQuery(shapeKindNumber, radiusM, halfSegmentM, rotation, { fromM, directionM, maximumDistanceM, collisionLayerNames = null, excludedId = null, isStoppedAtPenetration = true }, into, halfDepthM = 0) {
754
994
  const lengthNumber = Math.hypot(directionM.x, directionM.y, directionM.z) || 1;
755
995
  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));
996
+ const isHit = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, shapeKindNumber, radiusM, halfSegmentM, halfDepthM, 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
997
  if (!isHit) return null;
758
998
  const floats = batch.floats();
759
- return hitInto(into, batch.numbers(), floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[0]);
999
+ const numbers = batch.numbers();
1000
+ return hitInto(into, numbers[0], numbers[1], numbers[2], floats[1], floats[2], floats[3], floats[4], floats[5], floats[6], floats[0]);
1001
+ }
1002
+ /** Everything a shape overlaps, each owner once: [{ bodyId, characterId }]. The lengths are as the engine's QueryShapes takes them. */
1003
+ function overlapShapeQuery(shapeKindNumber, firstM, secondM, thirdM, centerM, rotation, collisionLayerNames, excludedId) {
1004
+ const excluded = excludedOf(excludedId);
1005
+ const foundCount = raw.overlapShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, shapeKindNumber, firstM, secondM, thirdM, centerM.x, centerM.y, centerM.z, rotation.x, rotation.y, rotation.z, rotation.w, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded));
1006
+ const found = [];
1007
+ const numbers = batch.numbers();
1008
+ for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) {
1009
+ const tagNumber = numbers[foundIndex];
1010
+ if ((tagNumber & TAG_KIND_MASK_NUMBER) === 0) continue;
1011
+ const bodyId = bodyIdOfTag(tagNumber);
1012
+ const characterId = characterIdOfTag(tagNumber);
1013
+ if (!found.some((each) => each.bodyId === bodyId && each.characterId === characterId)) found.push({ bodyId, characterId });
1014
+ }
1015
+ return found;
1016
+ }
1017
+ /** Hits' objects a caller's own list held and no longer shows, kept for the next longer answer. */
1018
+ const spareHits = [];
1019
+ /** What castRays answers into when the game gives nothing of its own: arrays as long as the rays asked, and how to read one ray's hit whole. */
1020
+ function raysAnswerOf(rayCount, into) {
1021
+ const answer = into ?? { rayCount: 0, hitCount: 0, distancesM: new Float32Array(0), normals: new Float32Array(0), hitNumbers: new Uint32Array(0), rays: null, hitAt: null };
1022
+ if (!(answer.distancesM instanceof Float32Array) || answer.distancesM.length < rayCount) answer.distancesM = new Float32Array(rayCount);
1023
+ if (!(answer.normals instanceof Float32Array) || answer.normals.length < rayCount * 3) answer.normals = new Float32Array(rayCount * 3);
1024
+ if (!(answer.hitNumbers instanceof Uint32Array) || answer.hitNumbers.length < rayCount * 3) answer.hitNumbers = new Uint32Array(rayCount * 3);
1025
+ answer.hitAt ??= (rayIndex, givenHit = null) => {
1026
+ const distanceM = answer.distancesM[rayIndex];
1027
+ if (!(rayIndex >= 0 && rayIndex < answer.rayCount) || distanceM < 0) return null;
1028
+ const { rays, normals, hitNumbers } = answer;
1029
+ const lengthNumber = Math.hypot(rays[rayIndex * 6 + 3], rays[rayIndex * 6 + 4], rays[rayIndex * 6 + 5]) || 1;
1030
+ return hitInto(givenHit, hitNumbers[rayIndex * 3], hitNumbers[rayIndex * 3 + 1], hitNumbers[rayIndex * 3 + 2], rays[rayIndex * 6] + (rays[rayIndex * 6 + 3] / lengthNumber) * distanceM, rays[rayIndex * 6 + 1] + (rays[rayIndex * 6 + 4] / lengthNumber) * distanceM, rays[rayIndex * 6 + 2] + (rays[rayIndex * 6 + 5] / lengthNumber) * distanceM, normals[rayIndex * 3], normals[rayIndex * 3 + 1], normals[rayIndex * 3 + 2], distanceM);
1031
+ };
1032
+ return answer;
760
1033
  }
761
1034
  /** Contacts' objects a caller's own list held and no longer shows, kept for the next longer answer. */
762
1035
  const spareContacts = [];
@@ -774,8 +1047,71 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
774
1047
  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
1048
  if (!isHit) return null;
776
1049
  const floats = batch.floats();
1050
+ const numbers = batch.numbers();
777
1051
  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);
1052
+ return hitInto(into, numbers[0], numbers[1], numbers[2], fromM.x + directionX * distanceM, fromM.y + directionY * distanceM, fromM.z + directionZ * distanceM, floats[1], floats[2], floats[3], distanceM);
1053
+ },
1054
+ /**
1055
+ * Everything a ray passes through, nearest first, one hit a shape (a mesh answers where the ray first meets it):
1056
+ * a list of hits as castRay's, up to maximumHitCount (default 16). What a bullet that goes through thin walls
1057
+ * asks. With into (a list of the caller's own, kept and given again), written there.
1058
+ */
1059
+ castRayAll({ fromM, directionM, maximumDistanceM, maximumHitCount = 16, collisionLayerNames = null, excludedId = null }, into = null) {
1060
+ const lengthNumber = Math.hypot(directionM.x, directionM.y, directionM.z) || 1;
1061
+ const directionX = directionM.x / lengthNumber;
1062
+ const directionY = directionM.y / lengthNumber;
1063
+ const directionZ = directionM.z / lengthNumber;
1064
+ const excluded = excludedOf(excludedId);
1065
+ const hitCount = raw.castRayAll(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), maximumHitCount);
1066
+ const hits = into ?? [];
1067
+ while (hits.length > hitCount) spareHits.push(hits.pop());
1068
+ const floats = batch.floats();
1069
+ const numbers = batch.numbers();
1070
+ for (let hitIndex = 0; hitIndex < hitCount; hitIndex += 1) {
1071
+ const distanceM = floats[hitIndex * RAY_HIT_FLOAT_COUNT];
1072
+ hits[hitIndex] = hitInto(hits[hitIndex] ?? ((into && spareHits.pop()) || null), numbers[hitIndex * 3], numbers[hitIndex * 3 + 1], numbers[hitIndex * 3 + 2], fromM.x + directionX * distanceM, fromM.y + directionY * distanceM, fromM.z + directionZ * distanceM, floats[hitIndex * RAY_HIT_FLOAT_COUNT + 1], floats[hitIndex * RAY_HIT_FLOAT_COUNT + 2], floats[hitIndex * RAY_HIT_FLOAT_COUNT + 3], distanceM);
1073
+ }
1074
+ return hits;
1075
+ },
1076
+ /**
1077
+ * Many rays in one call (a shotgun's pellets, a lidar, a crowd's feet): rays holds six numbers a ray, where it
1078
+ * starts (x, y, z) and its direction (x, y, z, of any length). Answers { rayCount, hitCount, distancesM (how
1079
+ * far each went, -1 for one that met nothing), normals (three numbers a ray), hitAt(rayIndex, into) (one ray's
1080
+ * hit whole, as castRay's, or null) }. With into (an answer of the caller's own, kept and given again), written
1081
+ * there: nothing is left for the garbage collector.
1082
+ */
1083
+ castRays({ rays, rayCount = Math.floor(rays.length / 6), maximumDistanceM, collisionLayerNames = null, excludedId = null }, into = null) {
1084
+ const answer = raysAnswerOf(rayCount, into);
1085
+ const excluded = excludedOf(excludedId);
1086
+ const groupsNumber = queryGroupsOf(collisionLayerNames);
1087
+ const flagsNumber = queryFlagsOf(excluded);
1088
+ answer.rayCount = rayCount;
1089
+ answer.rays = rays;
1090
+ answer.hitCount = 0;
1091
+ // As many rays a call as answer before the awake bodies the last step left.
1092
+ for (let firstRayIndex = 0; firstRayIndex < rayCount; firstRayIndex += RAYS_PER_CALL_COUNT) {
1093
+ const callRayCount = Math.min(RAYS_PER_CALL_COUNT, rayCount - firstRayIndex);
1094
+ batch.floats().set(rays.subarray(firstRayIndex * 6, (firstRayIndex + callRayCount) * 6));
1095
+ answer.hitCount += raw.castRays(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, callRayCount, maximumDistanceM, groupsNumber, excluded ? excluded.handle : 0, flagsNumber);
1096
+ const floats = batch.floats();
1097
+ const numbers = batch.numbers();
1098
+ for (let rayIndex = 0; rayIndex < callRayCount; rayIndex += 1) {
1099
+ const firstIndex = callRayCount * 6 + rayIndex * RAY_HIT_FLOAT_COUNT;
1100
+ const intoIndex = firstRayIndex + rayIndex;
1101
+ answer.distancesM[intoIndex] = floats[firstIndex];
1102
+ answer.normals[intoIndex * 3] = floats[firstIndex + 1];
1103
+ answer.normals[intoIndex * 3 + 1] = floats[firstIndex + 2];
1104
+ answer.normals[intoIndex * 3 + 2] = floats[firstIndex + 3];
1105
+ answer.hitNumbers[intoIndex * 3] = numbers[rayIndex * 3];
1106
+ answer.hitNumbers[intoIndex * 3 + 1] = numbers[rayIndex * 3 + 1];
1107
+ answer.hitNumbers[intoIndex * 3 + 2] = numbers[rayIndex * 3 + 2];
1108
+ }
1109
+ }
1110
+ return answer;
1111
+ },
1112
+ /** The first thing a box (turned by rotation) meets moving along a direction, or null: what a crate's width, a vehicle's body or a melee swing sweeps. With into, written there. */
1113
+ castBox(query, into = null) {
1114
+ return castShapeQuery(2, query.sizeM.x / 2, query.sizeM.y / 2, query.rotation ?? NO_TURN, query, into, query.sizeM.z / 2);
779
1115
  },
780
1116
  /** The first thing a ball meets moving along a direction: { bodyId, characterId, pointM, normal, distanceM }, or null. With into, written there. */
781
1117
  castBall(query, into = null) {
@@ -825,21 +1161,166 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
825
1161
  },
826
1162
  /** Everything a ball overlaps: [{ bodyId, characterId }]. */
827
1163
  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));
1164
+ return overlapShapeQuery(0, radiusM, 0, 0, centerM, NO_TURN, collisionLayerNames, excludedId);
1165
+ },
1166
+ /** Everything a box (turned by rotation) overlaps: [{ bodyId, characterId }]. */
1167
+ overlapBox({ centerM, sizeM, rotation = NO_TURN, collisionLayerNames = null, excludedId = null }) {
1168
+ return overlapShapeQuery(2, sizeM.x / 2, sizeM.y / 2, sizeM.z / 2, centerM, rotation, collisionLayerNames, excludedId);
1169
+ },
1170
+ /**
1171
+ * The ids of the zones that are on and that a place touches now: a point (centerM alone), a ball (with radiusM)
1172
+ * or a capsule (with radiusM and heightM, standing up or turned by rotation).
1173
+ */
1174
+ zonesAt({ centerM, radiusM = 0, heightM = 0, rotation = NO_TURN }) {
1175
+ if (!zones.length) return [];
1176
+ const isCapsule = heightM > radiusM * 2;
1177
+ const foundCount = raw.zonesOfShape(batch.narrowPhase, batch.bodies, isCapsule ? 1 : 0, Math.max(radiusM, POINT_RADIUS_M), isCapsule ? heightM / 2 - radiusM : 0, 0, centerM.x, centerM.y, centerM.z, rotation.x, rotation.y, rotation.z, rotation.w);
830
1178
  const found = [];
831
1179
  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
- }
1180
+ for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) found.push(zones[numbers[foundIndex]].id);
839
1181
  return found;
840
1182
  },
841
1183
  };
842
1184
 
1185
+ // ---- Zones: places that take note of who's in them, and may pull, push and slow what is ----
1186
+
1187
+ /** The world's zones as the engine holds them, in the world's order; filled once the bodies they ride are in. */
1188
+ const zones = [];
1189
+ const zoneIndexById = new Map();
1190
+ /** Whether any zone pulls, pushes or slows: a kinematic character's kind asks what its place does to it. */
1191
+ let hasZoneEffects = false;
1192
+ /** Zones whose insides changed since they were last told, and who left by leaving the world. */
1193
+ let isAnyZoneChanged = false;
1194
+ let goneFromZones = [];
1195
+ function addZones() {
1196
+ for (const declared of world.zones ?? []) {
1197
+ const ridden = declared.bodyId === null ? null : bodies[bodyIndexById.get(declared.bodyId)];
1198
+ const zoneIndex = raw.addZone(declared.positionM.x, declared.positionM.y, declared.positionM.z, declared.rotation.x, declared.rotation.y, declared.rotation.z, declared.rotation.w, queryGroupsOf(declared.collisionLayerNames), declared.gravityPct / 100, declared.pushMPerSecPerSec.x, declared.pushMPerSecPerSec.y, declared.pushMPerSecPerSec.z, declared.dampingNumber);
1199
+ for (const shape of declared.shapes) raw.addZoneShape(zoneIndex, shape.shapeKindNumber, shape.lengthsM[0], shape.lengthsM[1], shape.lengthsM[2], shape.positionM.x, shape.positionM.y, shape.positionM.z, shape.rotation.x, shape.rotation.y, shape.rotation.z, shape.rotation.w);
1200
+ if (ridden) raw.setZoneBody(zoneIndex, ridden.rigidBody.handle);
1201
+ // A zone that rides a body this simulation doesn't hold (a moving one, over a level) isn't here.
1202
+ const isHere = declared.bodyId === null || Boolean(ridden);
1203
+ if (!declared.isEnabled || !isHere) raw.setZoneEnabled(zoneIndex, false);
1204
+ zones.push({ id: declared.id, declared, index: zoneIndex, isHere, isChanged: false, toldTagNumbers: new Set() });
1205
+ zoneIndexById.set(declared.id, zoneIndex);
1206
+ hasZoneEffects ||= declared.hasEffects;
1207
+ }
1208
+ }
1209
+ /** Before a step: who's in each zone now, and which moving bodies the zones' pull, push and slowing act on through the step's substeps. */
1210
+ function stepZones() {
1211
+ const changeCount = raw.stepZones(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders);
1212
+ if (!changeCount) return;
1213
+ const numbers = batch.numbers();
1214
+ for (let changeIndex = 0; changeIndex < changeCount; changeIndex += 1) zones[numbers[changeIndex * 2] & 0x7fffffff].isChanged = true;
1215
+ isAnyZoneChanged = true;
1216
+ }
1217
+ const idsOfTag = (tagNumber) => ({ bodyId: bodyIdOfTag(tagNumber), characterId: characterIdOfTag(tagNumber) });
1218
+ /** A body or a character left the world: it's out of every zone it was told to be in. */
1219
+ function leaveZones(tagNumber, bodyId, characterId) {
1220
+ if (!zones.length) return;
1221
+ for (const zone of zones) if (zone.toldTagNumbers.delete(tagNumber)) goneFromZones.push({ zoneId: zone.id, bodyId, characterId, isEntered: false });
1222
+ raw.forgetZoneOccupant(tagNumber);
1223
+ }
1224
+ /**
1225
+ * Who came into a zone and who left since this was last asked: [{ zoneId, bodyId, characterId, isEntered }]. It
1226
+ * goes by where everything is now, so a step run again tells nothing twice, and what one run got wrong is put
1227
+ * right by the next.
1228
+ */
1229
+ function takeZoneChanges() {
1230
+ const changes = goneFromZones;
1231
+ goneFromZones = [];
1232
+ if (!isAnyZoneChanged) return changes;
1233
+ isAnyZoneChanged = false;
1234
+ for (const zone of zones) {
1235
+ if (!zone.isChanged) continue;
1236
+ zone.isChanged = false;
1237
+ const occupantCount = raw.zoneOccupants(zone.index);
1238
+ const nowTagNumbers = new Set(batch.numbers().subarray(0, occupantCount));
1239
+ for (const tagNumber of zone.toldTagNumbers) {
1240
+ if (nowTagNumbers.has(tagNumber)) continue;
1241
+ zone.toldTagNumbers.delete(tagNumber);
1242
+ const ids = idsOfTag(tagNumber);
1243
+ if (ids.bodyId !== null || ids.characterId !== null) changes.push({ zoneId: zone.id, ...ids, isEntered: false });
1244
+ }
1245
+ for (const tagNumber of nowTagNumbers) {
1246
+ if (zone.toldTagNumbers.has(tagNumber)) continue;
1247
+ zone.toldTagNumbers.add(tagNumber);
1248
+ const ids = idsOfTag(tagNumber);
1249
+ if (ids.bodyId !== null || ids.characterId !== null) changes.push({ zoneId: zone.id, ...ids, isEntered: true });
1250
+ }
1251
+ }
1252
+ return changes;
1253
+ }
1254
+ /** Who was in a zone at the last step: [{ bodyId, characterId }]. Empty for a zone that isn't here, or is off. */
1255
+ function zoneOccupants(zoneId) {
1256
+ const zoneIndex = zoneIndexById.get(zoneId);
1257
+ if (zoneIndex === undefined) return [];
1258
+ const occupantCount = raw.zoneOccupants(zoneIndex);
1259
+ const occupants = [];
1260
+ const numbers = batch.numbers();
1261
+ for (let occupantIndex = 0; occupantIndex < occupantCount; occupantIndex += 1) {
1262
+ const ids = idsOfTag(numbers[occupantIndex]);
1263
+ if (ids.bodyId !== null || ids.characterId !== null) occupants.push(ids);
1264
+ }
1265
+ return occupants;
1266
+ }
1267
+ function setZoneEnabled(zoneId, isEnabled) {
1268
+ const zone = zones[zoneIndexById.get(zoneId)];
1269
+ if (!zone?.isHere) return false;
1270
+ raw.setZoneEnabled(zone.index, isEnabled);
1271
+ return true;
1272
+ }
1273
+ /** The numbers of the zones a character's capsule touches now, in the engine's whole numbers: answers how many. */
1274
+ function zonesOfCharacter(character) {
1275
+ raw.readBody(batch.bodies, character.rigidBody.handle);
1276
+ const floats = batch.floats();
1277
+ return raw.zonesOfShape(batch.narrowPhase, batch.bodies, 1, character.characterSize.radiusM, character.characterSize.halfSegmentM, 0, floats[0], floats[1] + colliderRiseM + character.characterSize.riseM, floats[2], 0, 0, 0, 1);
1278
+ }
1279
+ const zoneEffects = { gravityPct: 100, pushMPerSecPerSec: { x: 0, y: 0, z: 0 }, dampingNumber: 0 };
1280
+ /**
1281
+ * What the zones a character stands in do there, together: { gravityPct, pushMPerSecPerSec, dampingNumber }, or
1282
+ * null where nothing pulls, pushes or slows it. The object is the piece's own, filled again by the next call: a
1283
+ * kinematic character's kind reads it at once (the engine moves a dynamic one by it itself).
1284
+ */
1285
+ function zoneEffectsOf(character) {
1286
+ if (!hasZoneEffects) return null;
1287
+ const foundCount = zonesOfCharacter(character);
1288
+ if (!foundCount) return null;
1289
+ const numbers = batch.numbers();
1290
+ let gravityNumber = 1;
1291
+ let pushX = 0;
1292
+ let pushY = 0;
1293
+ let pushZ = 0;
1294
+ let dampingNumber = 0;
1295
+ let isAffected = false;
1296
+ for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) {
1297
+ const { declared } = zones[numbers[foundIndex]];
1298
+ if (!declared.hasEffects) continue;
1299
+ isAffected = true;
1300
+ gravityNumber *= declared.gravityPct / 100;
1301
+ pushX += declared.pushMPerSecPerSec.x;
1302
+ pushY += declared.pushMPerSecPerSec.y;
1303
+ pushZ += declared.pushMPerSecPerSec.z;
1304
+ dampingNumber += declared.dampingNumber;
1305
+ }
1306
+ if (!isAffected) return null;
1307
+ zoneEffects.gravityPct = gravityNumber * 100;
1308
+ zoneEffects.pushMPerSecPerSec.x = pushX;
1309
+ zoneEffects.pushMPerSecPerSec.y = pushY;
1310
+ zoneEffects.pushMPerSecPerSec.z = pushZ;
1311
+ zoneEffects.dampingNumber = dampingNumber;
1312
+ return zoneEffects;
1313
+ }
1314
+ /** The ids of the zones a character is in now. */
1315
+ function zoneIdsOf(character) {
1316
+ if (!zones.length) return [];
1317
+ const foundCount = zonesOfCharacter(character);
1318
+ const found = [];
1319
+ const numbers = batch.numbers();
1320
+ for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) found.push(zones[numbers[foundIndex]].id);
1321
+ return found;
1322
+ }
1323
+
843
1324
  /**
844
1325
  * Moves a kinematic character by as much of desiredM as the world lets it: sliding along walls, up steps and
845
1326
  * slopes it can climb, snapped down to the ground under it. Answers { movedM, isGrounded }: a new one, or into
@@ -847,6 +1328,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
847
1328
  */
848
1329
  function moveAndSlide(character, desiredM, into = null) {
849
1330
  const moved = into ?? { movedM: { x: 0, y: 0, z: 0 }, isGrounded: false };
1331
+ const { controller } = character.characterSize;
850
1332
  if (!controller) {
851
1333
  moved.movedM.x = 0;
852
1334
  moved.movedM.y = 0;
@@ -877,6 +1359,16 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
877
1359
  },
878
1360
  ...queries,
879
1361
  moveAndSlide,
1362
+ isRestingOnLevel,
1363
+ zoneIdsOf,
1364
+ zoneEffectsOf,
1365
+ zoneOccupants,
1366
+ /** A body's place, rotation, speed and spin now: { positionM, rotation, velocityMPerSec, spinRadPerSec }, the body's own object filled again at each call (copy what you keep). Give the body a step was given, or an id. */
1367
+ bodyMotion,
1368
+ /** Pushes a moving body with a force in newtons for this one step, at its centre of mass or at a place in the world (which turns it too). Answers false for a body that isn't moving by physics. */
1369
+ addForce: (body, forceNewtons, atM = null) => forceBody(body, forceNewtons, atM, false),
1370
+ /** Turns a moving body with a torque in newton metres about the world's axes, for this one step. */
1371
+ addTorque: (body, torqueNewtonMetres) => forceBody(body, torqueNewtonMetres, null, true),
880
1372
  bodies,
881
1373
  characters,
882
1374
  bodyIndexById,
@@ -888,12 +1380,12 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
888
1380
  },
889
1381
  /** The character kind's own memory for this world (what's held, what changed): its startKindState's answer. */
890
1382
  kindState: null,
891
- /** A body as the world has it now, read only: { positionM, rotation, velocityMPerSec, spinRadPerSec, massKg, motionKind, collisionLayerName, isResting }, or null. */
1383
+ /** A body as the world has it now, read only: { positionM, rotation, velocityMPerSec, spinRadPerSec, massKg, motionKind, collisionLayerName, isResting, bodyKindName, own }, or null. */
892
1384
  bodyState(bodyId) {
893
1385
  const body = bodies[bodyIndexById.get(bodyId)];
894
1386
  if (!body) return null;
895
1387
  const fields = readBody(body.index);
896
- return { positionM: { x: fields.x, y: fields.y, z: fields.z }, rotation: fields.rotation, velocityMPerSec: { x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ }, spinRadPerSec: { x: fields.spinX, y: fields.spinY, z: fields.spinZ }, massKg: body.massKg ?? null, motionKind: MOTION_KINDS[body.motionIndex], collisionLayerName: world.collisionLayers[body.layerIndex].name, isResting: simulation.isBodyResting(body.index) };
1388
+ return { positionM: { x: fields.x, y: fields.y, z: fields.z }, rotation: fields.rotation, velocityMPerSec: { x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ }, spinRadPerSec: { x: fields.spinX, y: fields.spinY, z: fields.spinZ }, massKg: body.massKg ?? null, motionKind: MOTION_KINDS[body.motionIndex], collisionLayerName: world.collisionLayers[body.layerIndex].name, isResting: simulation.isBodyResting(body.index), bodyKindName: body.bodyKindName, own: body.own ? { ...body.own } : null };
897
1389
  },
898
1390
  /** A character as the world has it now, read only: { positionM (its feet), velocityMPerSec, facingYawRad, isGrounded, rideBodyId, collisionLayerName, own }, or null. */
899
1391
  characterState(characterId) {
@@ -902,18 +1394,33 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
902
1394
  raw.readBody(batch.bodies, character.rigidBody.handle);
903
1395
  const floats = batch.floats();
904
1396
  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 };
1397
+ return { positionM: { x: floats[0], y: floats[1] - world.character.heightM / 2, z: floats[2] }, velocityMPerSec, facingYawRad: character.facingYawRad, isGrounded: character.isGrounded, rideBodyId: bodies[character.rideBodyIndex]?.declaration.id ?? null, collisionLayerName: world.collisionLayers[character.ownLayerIndex].name, characterSizeName: character.characterSizeName, own: character.own };
906
1398
  },
907
1399
  /**
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
909
- * replay. Answers false for a joint that isn't here.
1400
+ * Ties or lets go a joint from a step (a press that takes a cart's handles), or gives its motor another target
1401
+ * ({ isEnabled, motorTargetNumber }, either or both), so it's run again exactly on a replay. Answers false for a
1402
+ * joint that isn't here.
910
1403
  */
911
1404
  setJoint(jointId, changes) {
912
- if (!joints.has(jointId) || typeof changes?.isEnabled !== "boolean") return false;
913
- setJointEnabled(joints.get(jointId), changes.isEnabled);
1405
+ const joint = joints.get(jointId);
1406
+ const isSwitched = typeof changes?.isEnabled === "boolean";
1407
+ const isAimed = Number.isFinite(changes?.motorTargetNumber);
1408
+ if (!joint || (!isSwitched && !isAimed)) return false;
1409
+ if (isSwitched) setJointEnabled(joint, changes.isEnabled);
1410
+ if (isAimed) setJointMotor(joint, changes.motorTargetNumber);
914
1411
  return true;
915
1412
  },
916
1413
  /** Puts a character on one of the world's collision layers from its step (walking through his own cart while he holds it). */
1414
+ /**
1415
+ * Gives a character another of the world's characterSizes from its step (a crouch, standing up again), or null
1416
+ * for the world's own character's: its feet stay where they are. Answers false, and changes nothing, where the
1417
+ * size has no room (a low roof over a crouched head).
1418
+ */
1419
+ setSize(character, characterSizeName) {
1420
+ const sizeIndex = characterSizeIndexByName.get(characterSizeName);
1421
+ if (sizeIndex === undefined) refuse("bad_argument", `setSize was given ${JSON.stringify(characterSizeName)}.`, "characterSizeName", `Use one of the world's characterSizes (${world.characterSizes.map((characterSize) => characterSize.name).join(", ") || "it names none"}), or null for the world's own character.`);
1422
+ return setCharacterSize(character, sizeIndex, true);
1423
+ },
917
1424
  setLayer(character, collisionLayerName) {
918
1425
  const layerIndex = layerIndexByName.get(collisionLayerName);
919
1426
  if (layerIndex === undefined || collisionLayerName === RIDING_LAYER_NAME) refuse("bad_argument", `setLayer was given ${JSON.stringify(collisionLayerName)}.`, "collisionLayerName", `Use one of the world's collisionLayers: ${world.collisionLayers.filter((layer) => layer.name !== RIDING_LAYER_NAME).map((layer) => layer.name).join(", ")}.`);
@@ -1092,7 +1599,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1092
1599
  /** Whether a point is within reach of a body on a timetable: only then is a character asked what it touches. */
1093
1600
  function isNearTimetable(x, y, z) {
1094
1601
  for (const body of timetableBodies) {
1095
- const reachM = body.reachM + world.character.heightM;
1602
+ const reachM = body.reachM + tallestCharacterHeightM;
1096
1603
  const awayX = x - body.nowPlace.x;
1097
1604
  const awayY = y - body.nowPlace.y;
1098
1605
  const awayZ = z - body.nowPlace.z;
@@ -1103,9 +1610,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1103
1610
 
1104
1611
  /** What a character's capsule touches, within marginM of it: the contact count, read from the batch's answer. */
1105
1612
  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);
1613
+ raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, x, y + CHARACTER_SKIN_M + character.characterSize.riseM, z, 0, 0, 0, 1, character.characterSize.radiusM, character.characterSize.halfSegmentM, marginM, groupsOf(character.layerIndex), character.rigidBody.handle, SKIPS_CHARACTERS_FLAG_NUMBER | EXCLUDES_BODY_FLAG_NUMBER);
1109
1614
  /** The body on a timetable a contact's tag is of, or null. */
1110
1615
  const timetableBodyOfTag = (tagNumber) => ((tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? (bodies[tagNumber >>> 8]?.timetable ? bodies[tagNumber >>> 8] : null) : null);
1111
1616
 
@@ -1140,7 +1645,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1140
1645
  function shiftCharacter(character, x, y, z, shiftX, shiftY, shiftZ, mover) {
1141
1646
  const shiftM = Math.hypot(shiftX, shiftY, shiftZ);
1142
1647
  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);
1648
+ const isBlocked = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, 1, character.characterSize.radiusM, character.characterSize.halfSegmentM, 0, 0, 0, 0, 1, x, y + CHARACTER_SKIN_M + character.characterSize.riseM, z, shiftX / shiftM, shiftY / shiftM, shiftZ / shiftM, shiftM, false, groupsOf(character.layerIndex), mover.rigidBody.handle, SKIPS_CHARACTERS_FLAG_NUMBER | EXCLUDES_BODY_FLAG_NUMBER);
1144
1649
  const freeNumber = isBlocked ? Math.max(batch.floats()[0] - CHARACTER_SKIN_M, 0) / shiftM : 1;
1145
1650
  if (freeNumber <= 0) return;
1146
1651
  batch.bodies.rbSetTranslation(character.rigidBody.handle, x + shiftX * freeNumber, y + shiftY * freeNumber, z + shiftZ * freeNumber, false);
@@ -1172,7 +1677,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1172
1677
  const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
1173
1678
  const depthM = floats[firstIndex + 6];
1174
1679
  // Under its feet: a surface that faces up enough to stand on.
1175
- if (floats[firstIndex + 4] >= minimumStandNormalNumber) {
1680
+ if (floats[firstIndex + 4] >= character.characterSize.minimumStandNormalNumber) {
1176
1681
  if (depthM > closestM) {
1177
1682
  closestM = depthM;
1178
1683
  ridden = body;
@@ -1216,7 +1721,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1216
1721
  let normalZ = 0;
1217
1722
  for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
1218
1723
  const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
1219
- if (floats[firstIndex + 4] < minimumStandNormalNumber || floats[firstIndex + 6] <= closestM) continue;
1724
+ if (floats[firstIndex + 4] < character.characterSize.minimumStandNormalNumber || floats[firstIndex + 6] <= closestM) continue;
1220
1725
  const body = timetableBodyOfTag(numbers[contactIndex * CONTACT_NUMBER_COUNT]);
1221
1726
  if (!body) continue;
1222
1727
  closestM = floats[firstIndex + 6];
@@ -1378,6 +1883,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1378
1883
  */
1379
1884
  function step(stepContext) {
1380
1885
  const worldStepContext = { ...stepTools, ...stepContext };
1886
+ isBeforeSubsteps = true;
1381
1887
  if (timetableBodies.length) {
1382
1888
  placeTimetables(stepContext.timetableTickIndex ?? stepContext.tickIndex);
1383
1889
  timetablesNow(characterKind.isSteppedBeforeWorld ? 0 : 1 / world.substepCount);
@@ -1385,21 +1891,29 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1385
1891
  // What was written since the last step (the word, a teleport) moves its colliders before anything searches them.
1386
1892
  propagateIfOwed();
1387
1893
  layGround();
1894
+ if (zones.length) stepZones();
1388
1895
  characterKind.beforeWorldStep?.(worldStepContext);
1389
1896
  if (characterKind.isSteppedBeforeWorld) stepCharacters(worldStepContext);
1390
1897
  driveVehicles(worldStepContext);
1898
+ if (behavingBodies.length) stepBodies(worldStepContext);
1899
+ isBeforeSubsteps = false;
1900
+ if (hasZoneEffects) raw.forceZones(batch.bodies, rapierWorld.gravity.x, rapierWorld.gravity.y, rapierWorld.gravity.z);
1391
1901
  for (let substepIndex = 0; substepIndex < world.substepCount; substepIndex += 1) {
1392
1902
  if (substepIndex > 0 && !characterKind.isSteppedBeforeWorld) placeMovedCharacters(substepIndex);
1393
1903
  if (timetableBodies.length) aimTimetables(substepIndex);
1394
1904
  // Every awake moving body's speed is noted (what a hit is told from), and a small quick thing looks ahead as far
1395
1905
  // as it goes in a substep, and a little more: the engine's own continuous collision misses heightfield ground,
1396
1906
  // so a 7 cm apple at 4 m/s would fall through it.
1907
+ if (hasZoneEffects) raw.slowZones(batch.bodies, substepDurationSec);
1397
1908
  raw.beforeSubstep(batch.bodies, batch.islands, substepDurationSec);
1398
1909
  updateVehicles();
1399
1910
  const hitCount = stepEngine();
1400
1911
  if (hitCount) noteHits(hitCount);
1401
1912
  if (substepIndex === 0 && !characterKind.isSteppedBeforeWorld) stepCharacters(worldStepContext);
1402
1913
  }
1914
+ if (hasZoneEffects) raw.endZoneForces(batch.bodies);
1915
+ if (forcedBodies.size) endForces();
1916
+ if (breakableJoints.size) breakJoints();
1403
1917
  stepCount += 1;
1404
1918
  for (const character of characters) if (character && !character.isWaiting && character.rideBodyIndex >= 0) placeRider(character);
1405
1919
  if (tracksTouches) noteTouches();
@@ -1450,8 +1964,14 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1450
1964
  fields.motionNumber = body.motionIndex;
1451
1965
  fields.steerNumber = body.vehicle ? body.vehicle.steerNumber : 0;
1452
1966
  fields.massKg = body.massKg ?? 0;
1967
+ if (body.behavior) ownInto(body, fields);
1453
1968
  return fields;
1454
1969
  }
1970
+ /** A body's kind's own fields, beside the piece's. */
1971
+ function ownInto(body, fields) {
1972
+ const { fieldNames } = body.behavior;
1973
+ for (let nameIndex = 0; nameIndex < fieldNames.length; nameIndex += 1) fields[fieldNames[nameIndex]] = body.own[fieldNames[nameIndex]];
1974
+ }
1455
1975
 
1456
1976
  /** A body's fields: its place, rotation, speed and spin, its layer and how it moves now. */
1457
1977
  function readBody(index) {
@@ -1480,6 +2000,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1480
2000
  fields.rotation.w = rotation.w;
1481
2001
  fields.layerNumber = body.layerIndex;
1482
2002
  fields.motionNumber = body.motionIndex;
2003
+ if (body.behavior) ownInto(body, fields);
1483
2004
  return fields;
1484
2005
  }
1485
2006
  if (body.settledStepCount === stepCount) return bodyFieldsFrom(body, batch.floats(), ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT, fields);
@@ -1492,6 +2013,10 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1492
2013
  const body = bodies[index];
1493
2014
  if (!body || body.declaredMotionIndex === 2) return;
1494
2015
  if (fields.layerNumber !== undefined && fields.layerNumber < world.collisionLayers.length) setBodyLayer(body, fields.layerNumber);
2016
+ if (body.behavior) {
2017
+ const { fieldNames } = body.behavior;
2018
+ for (let nameIndex = 0; nameIndex < fieldNames.length; nameIndex += 1) if (fields[fieldNames[nameIndex]] !== undefined) body.own[fieldNames[nameIndex]] = fields[fieldNames[nameIndex]];
2019
+ }
1495
2020
  // A body on a timetable takes its layer from the word, and its place from the step's index alone.
1496
2021
  if (body.timetable) return;
1497
2022
  if (fields.motionNumber !== undefined && fields.motionNumber >= 0 && fields.motionNumber <= 2) setBodyMotion(body, fields.motionNumber);
@@ -1550,6 +2075,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1550
2075
  fields.rideBodyNumber = character.rideBodyIndex + 1;
1551
2076
  fields.seatIndex = character.seatIndex;
1552
2077
  fields.layerNumber = character.ownLayerIndex;
2078
+ fields.sizeNumber = character.sizeIndex;
1553
2079
  return Object.assign(fields, characterKind.readOwn(character, stepTools));
1554
2080
  }
1555
2081
  /** readCharacter for whoever reads the fields at once and keeps nothing (the wire, after a step): the character's own object filled again. */
@@ -1568,6 +2094,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1568
2094
  rigidBody.setEnabled(true);
1569
2095
  }
1570
2096
  if (fields.layerNumber !== undefined && fields.layerNumber < world.collisionLayers.length && fields.layerNumber !== ridingLayerIndex) character.ownLayerIndex = fields.layerNumber;
2097
+ if (fields.sizeNumber !== undefined && fields.sizeNumber !== character.sizeIndex) setCharacterSize(character, fields.sizeNumber);
1571
2098
  batch.bodies.rbSetTranslation(rigidBody.handle, fields.x, fields.y, fields.z, false);
1572
2099
  isPropagationOwed = true;
1573
2100
  character.facingYawRad = fields.facingYawRad;
@@ -1613,12 +2140,13 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1613
2140
  body.rigidBody.setAngularDamping(body.declaration.angularDampingNumber ?? nextTuning.angularDampingNumber);
1614
2141
  body.rigidBody.wakeUp();
1615
2142
  }
1616
- controller?.setCharacterMass(nextTuning.characterMassKg ?? 70);
2143
+ for (const characterSize of characterSizes) characterSize.controller?.setCharacterMass(nextTuning.characterMassKg ?? 70);
1617
2144
  characterKind.onTuning?.(nextTuning, stepTools);
1618
2145
  }
1619
2146
 
1620
2147
  for (const declaration of world.bodies) addBody(declaration);
1621
2148
  for (const declaration of world.joints) addJoint(declaration);
2149
+ addZones();
1622
2150
  // Fixed bodies never move, and moving ones start where they're declared: a step settles what the engine knows of them.
1623
2151
  const savedTimestep = rapierWorld.timestep;
1624
2152
  rapierWorld.timestep = 0;
@@ -1638,6 +2166,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1638
2166
  tickDurationSec,
1639
2167
  stepTools,
1640
2168
  addBody,
2169
+ freeBodyIndex,
1641
2170
  removeBody,
1642
2171
  addCharacter,
1643
2172
  removeCharacter,
@@ -1649,6 +2178,23 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1649
2178
  const joint = joints.get(jointId);
1650
2179
  if (joint) setJointEnabled(joint, isEnabled);
1651
2180
  },
2181
+ /** A joint's fields: whether it holds, whether it broke, and its motor's target. Written into the object given. */
2182
+ readJoint(jointId, into) {
2183
+ const joint = joints.get(jointId);
2184
+ if (!joint) return null;
2185
+ into.isEnabled = joint.isEnabled;
2186
+ into.isBroken = joint.isBroken;
2187
+ into.motorTargetNumber = joint.motorTargetNumber;
2188
+ return into;
2189
+ },
2190
+ writeJoint(jointId, fields) {
2191
+ const joint = joints.get(jointId);
2192
+ if (!joint) return;
2193
+ setJointEnabled(joint, fields.isEnabled);
2194
+ setJointBroken(joint, !fields.isEnabled && Boolean(fields.isBroken));
2195
+ if (fields.motorTargetNumber !== undefined) setJointMotor(joint, fields.motorTargetNumber);
2196
+ },
2197
+ jointBreakChangeCount: () => jointBreakChangeCount,
1652
2198
  seat,
1653
2199
  unseat,
1654
2200
  step,
@@ -1657,7 +2203,9 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1657
2203
  readBody,
1658
2204
  readSteppedBody,
1659
2205
  /** 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,
2206
+ isBodyOnSteps: (index) => bodies[index]?.settledStepCount === stepCount && !bodies[index].timetable && !bodies[index].behavior?.fieldNames.length,
2207
+ /** Whether the last step left a body's place, rotation, speed and spin on the wire's steps, whatever its kind's own fields. */
2208
+ isBodyMotionOnSteps: (index) => bodies[index]?.settledStepCount === stepCount && !bodies[index].timetable,
1661
2209
  /** Puts the bodies on timetables where they are at a step, before the world as it stands then is asked anything. */
1662
2210
  placeTimetables,
1663
2211
  /** 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. */
@@ -1671,6 +2219,11 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1671
2219
  writeCharacter,
1672
2220
  setTuning,
1673
2221
  ...queries,
2222
+ zoneOccupants,
2223
+ takeZoneChanges,
2224
+ setZoneEnabled,
2225
+ /** Whether a zone is on now. */
2226
+ isZoneEnabled: (zoneId) => zoneIndexById.has(zoneId) && raw.isZoneEnabled(zoneIndexById.get(zoneId)),
1674
2227
  /** Lays the ground near a place for the next step, though nothing moves there: a camera looking past, a query far off. */
1675
2228
  keepGroundNear(point) {
1676
2229
  keptPoints.push({ x: point.x, y: point.y, z: point.z });
@@ -1689,7 +2242,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1689
2242
  /** How many tiles of ground are laid now. */
1690
2243
  laidGroundTileCount: () => grounds.reduce((total, ground) => total + ground.tiles.size, 0),
1691
2244
  /** Whether a body is at rest: asleep, so nothing about it changes until something touches it. A fixed one always is. */
1692
- isBodyResting: (index) => bodies[index].motionIndex === 2 || Boolean(bodies[index].timetable) || (bodies[index].motionIndex === 0 && bodies[index].rigidBody.isSleeping()),
2245
+ isBodyResting: (index) => !bodies[index].isOwnChanged && (bodies[index].motionIndex === 2 || Boolean(bodies[index].timetable) || (bodies[index].motionIndex === 0 && bodies[index].rigidBody.isSleeping())),
1693
2246
  isCharacterResting(index) {
1694
2247
  const character = characters[index];
1695
2248
  // A step that changed the kind's own fields (taking a cart's handles, breath coming back) wakes it, so they're sent.
@@ -1713,7 +2266,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
1713
2266
  /** Calls a function with the index of every moving body that isn't at rest. */
1714
2267
  forEachAwakeBody(listener) {
1715
2268
  if (settledStepCount !== stepCount) {
1716
- for (const body of bodies) if (body && body.motionIndex === 0 && !body.rigidBody.isSleeping()) listener(body.index);
2269
+ for (const body of unfixedBodies) if (body.motionIndex === 0 && !body.rigidBody.isSleeping()) listener(body.index);
1717
2270
  return;
1718
2271
  }
1719
2272
  for (let settledIndex = 0; settledIndex < settledCount; settledIndex += 1) {