@zaisma/physics 2.6.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/README.md +18 -4
- package/batch.js +6 -1
- package/bodies.js +72 -0
- package/characters.js +19 -5
- package/declare.js +110 -8
- package/index.d.ts +195 -37
- package/index.js +2 -2
- package/package.json +2 -1
- package/piece.json +18 -1
- package/piece.json.js +18 -1
- package/rapier/CHANGES.md +2 -0
- package/rapier/rapier.js +298 -6
- package/rapier/rapier.wasm +0 -0
- package/simulation.js +483 -57
- package/sync.js +280 -52
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, heldMeshParts, isBigMesh } 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;
|
|
@@ -105,6 +109,12 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
105
109
|
let movableBodyCount = 0;
|
|
106
110
|
/** The bodies that aren't fixed for good, by index: what a step goes through, however many pieces the level is made of. */
|
|
107
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;
|
|
108
118
|
let lowestFreeBodyIndex = 0;
|
|
109
119
|
const bodies = [];
|
|
110
120
|
const bodyIndexById = new Map();
|
|
@@ -354,8 +364,14 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
354
364
|
.setAngularDamping(declaration.angularDampingNumber ?? currentTuning.angularDampingNumber);
|
|
355
365
|
const rigidBody = rapierWorld.createRigidBody(description);
|
|
356
366
|
const layerIndex = layerIndexByName.get(declaration.collisionLayerName);
|
|
357
|
-
const
|
|
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 };
|
|
358
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
|
+
}
|
|
359
375
|
if (motionIndex !== 2) {
|
|
360
376
|
// Kept in the order of their indexes, so every side goes through them alike.
|
|
361
377
|
let placeIndex = unfixedBodies.length;
|
|
@@ -454,6 +470,9 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
454
470
|
}
|
|
455
471
|
lowestFreeBodyIndex = Math.min(lowestFreeBodyIndex, index);
|
|
456
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);
|
|
457
476
|
rapierWorld.removeRigidBody(body.rigidBody);
|
|
458
477
|
bodyIndexById.delete(body.declaration.id);
|
|
459
478
|
bodies[index] = null;
|
|
@@ -543,6 +562,75 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
543
562
|
}
|
|
544
563
|
}
|
|
545
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
|
+
|
|
546
634
|
// ---- Joints ----
|
|
547
635
|
|
|
548
636
|
/** The engine body a joint end names: a body's, or a character's, by id. */
|
|
@@ -560,7 +648,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
560
648
|
const second = declaration.otherBodyId === null ? null : endOf(declaration.otherBodyId);
|
|
561
649
|
if (!first || (declaration.otherBodyId !== null && !second)) return false;
|
|
562
650
|
worldAnchor ??= rapierWorld.createRigidBody(engine.RigidBodyDesc.fixed());
|
|
563
|
-
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 };
|
|
564
652
|
joints.set(declaration.id, joint);
|
|
565
653
|
setJointEnabled(joint, isEnabled);
|
|
566
654
|
return true;
|
|
@@ -572,8 +660,11 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
572
660
|
if (!isEnabled) {
|
|
573
661
|
if (joint.rapierJoint) rapierWorld.removeImpulseJoint(joint.rapierJoint, true);
|
|
574
662
|
joint.rapierJoint = null;
|
|
663
|
+
breakableJoints.delete(joint);
|
|
575
664
|
return;
|
|
576
665
|
}
|
|
666
|
+
// Held again, it's whole again.
|
|
667
|
+
setJointBroken(joint, false);
|
|
577
668
|
const { declaration } = joint;
|
|
578
669
|
const { anchorM, otherAnchorM, axis } = declaration;
|
|
579
670
|
const otherRigidBody = joint.second?.rigidBody ?? worldAnchor;
|
|
@@ -586,12 +677,47 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
586
677
|
else jointData = engine.JointData.rope(declaration.restLengthM, anchorM, otherAnchorM);
|
|
587
678
|
joint.rapierJoint = rapierWorld.createImpulseJoint(jointData, joint.first.rigidBody, otherRigidBody, true);
|
|
588
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
|
+
}
|
|
589
714
|
}
|
|
590
715
|
|
|
591
716
|
function removeJoint(jointId) {
|
|
592
717
|
const joint = joints.get(jointId);
|
|
593
718
|
if (!joint) return false;
|
|
594
719
|
setJointEnabled(joint, false);
|
|
720
|
+
setJointBroken(joint, false);
|
|
595
721
|
joints.delete(jointId);
|
|
596
722
|
return true;
|
|
597
723
|
}
|
|
@@ -604,31 +730,31 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
604
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;
|
|
605
731
|
* its capsule is raised or lowered on it to stand on the same feet.
|
|
606
732
|
*/
|
|
607
|
-
const characterSizes = [{ name: null, ...world.character }, ...world.characterSizes].map((
|
|
733
|
+
const characterSizes = [{ name: null, ...world.character }, ...world.characterSizes].map((characterSize) => {
|
|
608
734
|
const controller = isKinematicKind ? rapierWorld.createCharacterController(CHARACTER_SKIN_M) : null;
|
|
609
735
|
if (controller) {
|
|
610
736
|
controller.setUp({ x: 0, y: 1, z: 0 });
|
|
611
737
|
controller.setSlideEnabled(true);
|
|
612
|
-
if (
|
|
613
|
-
controller.setMaxSlopeClimbAngle((
|
|
614
|
-
controller.setMinSlopeSlideAngle?.(((
|
|
615
|
-
controller.enableSnapToGround(
|
|
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);
|
|
616
742
|
controller.setApplyImpulsesToDynamicBodies(characterKind.canPushBodies !== false);
|
|
617
743
|
controller.setCharacterMass(currentTuning.characterMassKg ?? 70);
|
|
618
744
|
}
|
|
619
745
|
return {
|
|
620
|
-
...
|
|
621
|
-
halfSegmentM:
|
|
746
|
+
...characterSize,
|
|
747
|
+
halfSegmentM: characterSize.heightM / 2 - characterSize.radiusM,
|
|
622
748
|
/** How far above the body's place the capsule's middle is. */
|
|
623
|
-
riseM: (
|
|
749
|
+
riseM: (characterSize.heightM - world.character.heightM) / 2,
|
|
624
750
|
controller,
|
|
625
751
|
/** How far up a surface under the character faces, at least, for it to stand there: the steepest slope it climbs. */
|
|
626
|
-
minimumStandNormalNumber: Math.cos((
|
|
752
|
+
minimumStandNormalNumber: Math.cos((characterSize.maximumSlopeDeg * Math.PI) / 180),
|
|
627
753
|
};
|
|
628
754
|
});
|
|
629
755
|
const characterHalfSegmentM = characterSizes[0].halfSegmentM;
|
|
630
|
-
const tallestCharacterHeightM = Math.max(...characterSizes.map((
|
|
631
|
-
const characterSizeIndexByName = new Map(characterSizes.map((
|
|
756
|
+
const tallestCharacterHeightM = Math.max(...characterSizes.map((characterSize) => characterSize.heightM));
|
|
757
|
+
const characterSizeIndexByName = new Map(characterSizes.map((characterSize, sizeIndex) => [characterSize.name, sizeIndex]));
|
|
632
758
|
|
|
633
759
|
/**
|
|
634
760
|
* Adds a character with its feet at a place, at an index: the next free one, or the one given. Answers the index.
|
|
@@ -661,7 +787,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
661
787
|
isWaiting,
|
|
662
788
|
rigidBody,
|
|
663
789
|
collider,
|
|
664
|
-
|
|
790
|
+
characterSize: characterSizes[0],
|
|
665
791
|
sizeIndex: 0,
|
|
666
792
|
/** Which of the world's characterSizes it is now, or null for the world's own character's. */
|
|
667
793
|
characterSizeName: null,
|
|
@@ -689,6 +815,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
689
815
|
characterKind.onCharacterRemoved?.(character, stepTools);
|
|
690
816
|
for (const [jointId, joint] of joints) if (joint.characterIndexes.includes(index)) removeJoint(jointId);
|
|
691
817
|
disownCollider(character.collider);
|
|
818
|
+
leaveZones(characterTagOf(index), null, character.id);
|
|
692
819
|
rapierWorld.removeRigidBody(character.rigidBody);
|
|
693
820
|
characterIndexById.delete(character.id);
|
|
694
821
|
characters[index] = null;
|
|
@@ -726,7 +853,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
726
853
|
const tagNumber = numbers[contactIndex * CONTACT_NUMBER_COUNT];
|
|
727
854
|
const body = (tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? bodies[tagNumber >>> 8] : null;
|
|
728
855
|
if (!body || body.motionIndex !== 2) return false;
|
|
729
|
-
if (floats[contactIndex * CONTACT_FLOAT_COUNT + 4] >= character.
|
|
856
|
+
if (floats[contactIndex * CONTACT_FLOAT_COUNT + 4] >= character.characterSize.minimumStandNormalNumber) isStanding = true;
|
|
730
857
|
}
|
|
731
858
|
rest.isResting = isStanding;
|
|
732
859
|
return isStanding;
|
|
@@ -740,23 +867,23 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
740
867
|
*/
|
|
741
868
|
function setCharacterSize(character, sizeIndex, isFitChecked = false) {
|
|
742
869
|
if (character.sizeIndex === sizeIndex) return true;
|
|
743
|
-
const
|
|
744
|
-
if (!
|
|
870
|
+
const characterSize = characterSizes[sizeIndex];
|
|
871
|
+
if (!characterSize) return false;
|
|
745
872
|
if (isFitChecked && !character.isWaiting) {
|
|
746
873
|
raw.readBody(batch.bodies, character.rigidBody.handle);
|
|
747
874
|
let floats = batch.floats();
|
|
748
|
-
const contactCount = raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, floats[0], floats[1] + CHARACTER_SKIN_M +
|
|
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);
|
|
749
876
|
floats = batch.floats();
|
|
750
877
|
for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
|
|
751
878
|
const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
|
|
752
|
-
if (floats[firstIndex + 6] > SIZE_FIT_DEPTH_M && floats[firstIndex + 4] <
|
|
879
|
+
if (floats[firstIndex + 6] > SIZE_FIT_DEPTH_M && floats[firstIndex + 4] < characterSize.minimumStandNormalNumber) return false;
|
|
753
880
|
}
|
|
754
881
|
}
|
|
755
|
-
character.
|
|
882
|
+
character.characterSize = characterSize;
|
|
756
883
|
character.sizeIndex = sizeIndex;
|
|
757
|
-
character.characterSizeName =
|
|
758
|
-
character.collider.setShape(new engine.Capsule(
|
|
759
|
-
character.collider.setTranslationWrtParent({ x: 0, y: colliderRiseM +
|
|
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 });
|
|
760
887
|
isPropagationOwed = true;
|
|
761
888
|
isSceneOwed = true;
|
|
762
889
|
return true;
|
|
@@ -846,12 +973,11 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
846
973
|
* A hit as a query answers it, written into the caller's own object when it gives one (a game casting thousands of
|
|
847
974
|
* rays a second keeps one), else a new one.
|
|
848
975
|
*/
|
|
849
|
-
function hitInto(into,
|
|
976
|
+
function hitInto(into, tagNumber, triangleNumber, colliderNumber, pointX, pointY, pointZ, normalX, normalY, normalZ, distanceM) {
|
|
850
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 };
|
|
851
|
-
const tagNumber = numbers[0];
|
|
852
978
|
hit.bodyId = bodyIdOfTag(tagNumber);
|
|
853
979
|
hit.characterId = characterIdOfTag(tagNumber);
|
|
854
|
-
noteSurface(hit,
|
|
980
|
+
noteSurface(hit, colliderNumber, triangleNumber);
|
|
855
981
|
hit.pointM ??= { x: 0, y: 0, z: 0 };
|
|
856
982
|
hit.normal ??= { x: 0, y: 0, z: 0 };
|
|
857
983
|
hit.pointM.x = pointX;
|
|
@@ -863,14 +989,47 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
863
989
|
hit.distanceM = distanceM;
|
|
864
990
|
return hit;
|
|
865
991
|
}
|
|
866
|
-
/** A ball (shapeKindNumber 0)
|
|
867
|
-
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) {
|
|
868
994
|
const lengthNumber = Math.hypot(directionM.x, directionM.y, directionM.z) || 1;
|
|
869
995
|
const excluded = excludedOf(excludedId);
|
|
870
|
-
const isHit = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, shapeKindNumber, radiusM, halfSegmentM, rotation.x, rotation.y, rotation.z, rotation.w, fromM.x, fromM.y, fromM.z, directionM.x / lengthNumber, directionM.y / lengthNumber, directionM.z / lengthNumber, maximumDistanceM, isStoppedAtPenetration, queryGroupsOf(collisionLayerNames), excluded ? excluded.handle : 0, queryFlagsOf(excluded));
|
|
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));
|
|
871
997
|
if (!isHit) return null;
|
|
872
998
|
const floats = batch.floats();
|
|
873
|
-
|
|
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;
|
|
874
1033
|
}
|
|
875
1034
|
/** Contacts' objects a caller's own list held and no longer shows, kept for the next longer answer. */
|
|
876
1035
|
const spareContacts = [];
|
|
@@ -888,8 +1047,71 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
888
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));
|
|
889
1048
|
if (!isHit) return null;
|
|
890
1049
|
const floats = batch.floats();
|
|
1050
|
+
const numbers = batch.numbers();
|
|
891
1051
|
const distanceM = floats[0];
|
|
892
|
-
return hitInto(into,
|
|
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);
|
|
893
1115
|
},
|
|
894
1116
|
/** The first thing a ball meets moving along a direction: { bodyId, characterId, pointM, normal, distanceM }, or null. With into, written there. */
|
|
895
1117
|
castBall(query, into = null) {
|
|
@@ -939,21 +1161,166 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
939
1161
|
},
|
|
940
1162
|
/** Everything a ball overlaps: [{ bodyId, characterId }]. */
|
|
941
1163
|
overlapBall({ centerM, radiusM, collisionLayerNames = null, excludedId = null }) {
|
|
942
|
-
|
|
943
|
-
|
|
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);
|
|
944
1178
|
const found = [];
|
|
945
1179
|
const numbers = batch.numbers();
|
|
946
|
-
for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1)
|
|
947
|
-
const tagNumber = numbers[foundIndex];
|
|
948
|
-
if ((tagNumber & TAG_KIND_MASK_NUMBER) === 0) continue;
|
|
949
|
-
const bodyId = bodyIdOfTag(tagNumber);
|
|
950
|
-
const characterId = characterIdOfTag(tagNumber);
|
|
951
|
-
if (!found.some((each) => each.bodyId === bodyId && each.characterId === characterId)) found.push({ bodyId, characterId });
|
|
952
|
-
}
|
|
1180
|
+
for (let foundIndex = 0; foundIndex < foundCount; foundIndex += 1) found.push(zones[numbers[foundIndex]].id);
|
|
953
1181
|
return found;
|
|
954
1182
|
},
|
|
955
1183
|
};
|
|
956
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
|
+
|
|
957
1324
|
/**
|
|
958
1325
|
* Moves a kinematic character by as much of desiredM as the world lets it: sliding along walls, up steps and
|
|
959
1326
|
* slopes it can climb, snapped down to the ground under it. Answers { movedM, isGrounded }: a new one, or into
|
|
@@ -961,7 +1328,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
961
1328
|
*/
|
|
962
1329
|
function moveAndSlide(character, desiredM, into = null) {
|
|
963
1330
|
const moved = into ?? { movedM: { x: 0, y: 0, z: 0 }, isGrounded: false };
|
|
964
|
-
const { controller } = character.
|
|
1331
|
+
const { controller } = character.characterSize;
|
|
965
1332
|
if (!controller) {
|
|
966
1333
|
moved.movedM.x = 0;
|
|
967
1334
|
moved.movedM.y = 0;
|
|
@@ -993,6 +1360,15 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
993
1360
|
...queries,
|
|
994
1361
|
moveAndSlide,
|
|
995
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),
|
|
996
1372
|
bodies,
|
|
997
1373
|
characters,
|
|
998
1374
|
bodyIndexById,
|
|
@@ -1004,12 +1380,12 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1004
1380
|
},
|
|
1005
1381
|
/** The character kind's own memory for this world (what's held, what changed): its startKindState's answer. */
|
|
1006
1382
|
kindState: null,
|
|
1007
|
-
/** 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. */
|
|
1008
1384
|
bodyState(bodyId) {
|
|
1009
1385
|
const body = bodies[bodyIndexById.get(bodyId)];
|
|
1010
1386
|
if (!body) return null;
|
|
1011
1387
|
const fields = readBody(body.index);
|
|
1012
|
-
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 };
|
|
1013
1389
|
},
|
|
1014
1390
|
/** A character as the world has it now, read only: { positionM (its feet), velocityMPerSec, facingYawRad, isGrounded, rideBodyId, collisionLayerName, own }, or null. */
|
|
1015
1391
|
characterState(characterId) {
|
|
@@ -1021,12 +1397,17 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1021
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 };
|
|
1022
1398
|
},
|
|
1023
1399
|
/**
|
|
1024
|
-
* Ties or lets go a joint from a step (a press that takes a cart's handles),
|
|
1025
|
-
* replay. Answers false for a
|
|
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.
|
|
1026
1403
|
*/
|
|
1027
1404
|
setJoint(jointId, changes) {
|
|
1028
|
-
|
|
1029
|
-
|
|
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);
|
|
1030
1411
|
return true;
|
|
1031
1412
|
},
|
|
1032
1413
|
/** Puts a character on one of the world's collision layers from its step (walking through his own cart while he holds it). */
|
|
@@ -1037,7 +1418,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1037
1418
|
*/
|
|
1038
1419
|
setSize(character, characterSizeName) {
|
|
1039
1420
|
const sizeIndex = characterSizeIndexByName.get(characterSizeName);
|
|
1040
|
-
if (sizeIndex === undefined) refuse("bad_argument", `setSize was given ${JSON.stringify(characterSizeName)}.`, "characterSizeName", `Use one of the world's characterSizes (${world.characterSizes.map((
|
|
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.`);
|
|
1041
1422
|
return setCharacterSize(character, sizeIndex, true);
|
|
1042
1423
|
},
|
|
1043
1424
|
setLayer(character, collisionLayerName) {
|
|
@@ -1229,7 +1610,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1229
1610
|
|
|
1230
1611
|
/** What a character's capsule touches, within marginM of it: the contact count, read from the batch's answer. */
|
|
1231
1612
|
const characterContactsOf = (character, x, y, z, marginM) =>
|
|
1232
|
-
raw.capsuleContacts(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, x, y + CHARACTER_SKIN_M + character.
|
|
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);
|
|
1233
1614
|
/** The body on a timetable a contact's tag is of, or null. */
|
|
1234
1615
|
const timetableBodyOfTag = (tagNumber) => ((tagNumber & TAG_KIND_MASK_NUMBER) === BODY_TAG_NUMBER ? (bodies[tagNumber >>> 8]?.timetable ? bodies[tagNumber >>> 8] : null) : null);
|
|
1235
1616
|
|
|
@@ -1264,7 +1645,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1264
1645
|
function shiftCharacter(character, x, y, z, shiftX, shiftY, shiftZ, mover) {
|
|
1265
1646
|
const shiftM = Math.hypot(shiftX, shiftY, shiftZ);
|
|
1266
1647
|
if (shiftM < 1e-7) return;
|
|
1267
|
-
const isBlocked = raw.castShape(batch.broadPhase, batch.narrowPhase, batch.bodies, batch.colliders, 1, character.
|
|
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);
|
|
1268
1649
|
const freeNumber = isBlocked ? Math.max(batch.floats()[0] - CHARACTER_SKIN_M, 0) / shiftM : 1;
|
|
1269
1650
|
if (freeNumber <= 0) return;
|
|
1270
1651
|
batch.bodies.rbSetTranslation(character.rigidBody.handle, x + shiftX * freeNumber, y + shiftY * freeNumber, z + shiftZ * freeNumber, false);
|
|
@@ -1296,7 +1677,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1296
1677
|
const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
|
|
1297
1678
|
const depthM = floats[firstIndex + 6];
|
|
1298
1679
|
// Under its feet: a surface that faces up enough to stand on.
|
|
1299
|
-
if (floats[firstIndex + 4] >= character.
|
|
1680
|
+
if (floats[firstIndex + 4] >= character.characterSize.minimumStandNormalNumber) {
|
|
1300
1681
|
if (depthM > closestM) {
|
|
1301
1682
|
closestM = depthM;
|
|
1302
1683
|
ridden = body;
|
|
@@ -1340,7 +1721,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1340
1721
|
let normalZ = 0;
|
|
1341
1722
|
for (let contactIndex = 0; contactIndex < contactCount; contactIndex += 1) {
|
|
1342
1723
|
const firstIndex = contactIndex * CONTACT_FLOAT_COUNT;
|
|
1343
|
-
if (floats[firstIndex + 4] < character.
|
|
1724
|
+
if (floats[firstIndex + 4] < character.characterSize.minimumStandNormalNumber || floats[firstIndex + 6] <= closestM) continue;
|
|
1344
1725
|
const body = timetableBodyOfTag(numbers[contactIndex * CONTACT_NUMBER_COUNT]);
|
|
1345
1726
|
if (!body) continue;
|
|
1346
1727
|
closestM = floats[firstIndex + 6];
|
|
@@ -1502,6 +1883,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1502
1883
|
*/
|
|
1503
1884
|
function step(stepContext) {
|
|
1504
1885
|
const worldStepContext = { ...stepTools, ...stepContext };
|
|
1886
|
+
isBeforeSubsteps = true;
|
|
1505
1887
|
if (timetableBodies.length) {
|
|
1506
1888
|
placeTimetables(stepContext.timetableTickIndex ?? stepContext.tickIndex);
|
|
1507
1889
|
timetablesNow(characterKind.isSteppedBeforeWorld ? 0 : 1 / world.substepCount);
|
|
@@ -1509,21 +1891,29 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1509
1891
|
// What was written since the last step (the word, a teleport) moves its colliders before anything searches them.
|
|
1510
1892
|
propagateIfOwed();
|
|
1511
1893
|
layGround();
|
|
1894
|
+
if (zones.length) stepZones();
|
|
1512
1895
|
characterKind.beforeWorldStep?.(worldStepContext);
|
|
1513
1896
|
if (characterKind.isSteppedBeforeWorld) stepCharacters(worldStepContext);
|
|
1514
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);
|
|
1515
1901
|
for (let substepIndex = 0; substepIndex < world.substepCount; substepIndex += 1) {
|
|
1516
1902
|
if (substepIndex > 0 && !characterKind.isSteppedBeforeWorld) placeMovedCharacters(substepIndex);
|
|
1517
1903
|
if (timetableBodies.length) aimTimetables(substepIndex);
|
|
1518
1904
|
// Every awake moving body's speed is noted (what a hit is told from), and a small quick thing looks ahead as far
|
|
1519
1905
|
// as it goes in a substep, and a little more: the engine's own continuous collision misses heightfield ground,
|
|
1520
1906
|
// so a 7 cm apple at 4 m/s would fall through it.
|
|
1907
|
+
if (hasZoneEffects) raw.slowZones(batch.bodies, substepDurationSec);
|
|
1521
1908
|
raw.beforeSubstep(batch.bodies, batch.islands, substepDurationSec);
|
|
1522
1909
|
updateVehicles();
|
|
1523
1910
|
const hitCount = stepEngine();
|
|
1524
1911
|
if (hitCount) noteHits(hitCount);
|
|
1525
1912
|
if (substepIndex === 0 && !characterKind.isSteppedBeforeWorld) stepCharacters(worldStepContext);
|
|
1526
1913
|
}
|
|
1914
|
+
if (hasZoneEffects) raw.endZoneForces(batch.bodies);
|
|
1915
|
+
if (forcedBodies.size) endForces();
|
|
1916
|
+
if (breakableJoints.size) breakJoints();
|
|
1527
1917
|
stepCount += 1;
|
|
1528
1918
|
for (const character of characters) if (character && !character.isWaiting && character.rideBodyIndex >= 0) placeRider(character);
|
|
1529
1919
|
if (tracksTouches) noteTouches();
|
|
@@ -1574,8 +1964,14 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1574
1964
|
fields.motionNumber = body.motionIndex;
|
|
1575
1965
|
fields.steerNumber = body.vehicle ? body.vehicle.steerNumber : 0;
|
|
1576
1966
|
fields.massKg = body.massKg ?? 0;
|
|
1967
|
+
if (body.behavior) ownInto(body, fields);
|
|
1577
1968
|
return fields;
|
|
1578
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
|
+
}
|
|
1579
1975
|
|
|
1580
1976
|
/** A body's fields: its place, rotation, speed and spin, its layer and how it moves now. */
|
|
1581
1977
|
function readBody(index) {
|
|
@@ -1604,6 +2000,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1604
2000
|
fields.rotation.w = rotation.w;
|
|
1605
2001
|
fields.layerNumber = body.layerIndex;
|
|
1606
2002
|
fields.motionNumber = body.motionIndex;
|
|
2003
|
+
if (body.behavior) ownInto(body, fields);
|
|
1607
2004
|
return fields;
|
|
1608
2005
|
}
|
|
1609
2006
|
if (body.settledStepCount === stepCount) return bodyFieldsFrom(body, batch.floats(), ANSWER_FLOAT_COUNT + body.settledIndex * BODY_FLOAT_COUNT, fields);
|
|
@@ -1616,6 +2013,10 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1616
2013
|
const body = bodies[index];
|
|
1617
2014
|
if (!body || body.declaredMotionIndex === 2) return;
|
|
1618
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
|
+
}
|
|
1619
2020
|
// A body on a timetable takes its layer from the word, and its place from the step's index alone.
|
|
1620
2021
|
if (body.timetable) return;
|
|
1621
2022
|
if (fields.motionNumber !== undefined && fields.motionNumber >= 0 && fields.motionNumber <= 2) setBodyMotion(body, fields.motionNumber);
|
|
@@ -1739,12 +2140,13 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1739
2140
|
body.rigidBody.setAngularDamping(body.declaration.angularDampingNumber ?? nextTuning.angularDampingNumber);
|
|
1740
2141
|
body.rigidBody.wakeUp();
|
|
1741
2142
|
}
|
|
1742
|
-
for (const
|
|
2143
|
+
for (const characterSize of characterSizes) characterSize.controller?.setCharacterMass(nextTuning.characterMassKg ?? 70);
|
|
1743
2144
|
characterKind.onTuning?.(nextTuning, stepTools);
|
|
1744
2145
|
}
|
|
1745
2146
|
|
|
1746
2147
|
for (const declaration of world.bodies) addBody(declaration);
|
|
1747
2148
|
for (const declaration of world.joints) addJoint(declaration);
|
|
2149
|
+
addZones();
|
|
1748
2150
|
// Fixed bodies never move, and moving ones start where they're declared: a step settles what the engine knows of them.
|
|
1749
2151
|
const savedTimestep = rapierWorld.timestep;
|
|
1750
2152
|
rapierWorld.timestep = 0;
|
|
@@ -1776,6 +2178,23 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1776
2178
|
const joint = joints.get(jointId);
|
|
1777
2179
|
if (joint) setJointEnabled(joint, isEnabled);
|
|
1778
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,
|
|
1779
2198
|
seat,
|
|
1780
2199
|
unseat,
|
|
1781
2200
|
step,
|
|
@@ -1784,7 +2203,9 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1784
2203
|
readBody,
|
|
1785
2204
|
readSteppedBody,
|
|
1786
2205
|
/** Whether the last step left this body on the wire's steps (it was awake, and nothing has written it since). */
|
|
1787
|
-
isBodyOnSteps: (index) => bodies[index]?.settledStepCount === stepCount && !bodies[index].timetable,
|
|
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,
|
|
1788
2209
|
/** Puts the bodies on timetables where they are at a step, before the world as it stands then is asked anything. */
|
|
1789
2210
|
placeTimetables,
|
|
1790
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. */
|
|
@@ -1798,6 +2219,11 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1798
2219
|
writeCharacter,
|
|
1799
2220
|
setTuning,
|
|
1800
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)),
|
|
1801
2227
|
/** Lays the ground near a place for the next step, though nothing moves there: a camera looking past, a query far off. */
|
|
1802
2228
|
keepGroundNear(point) {
|
|
1803
2229
|
keptPoints.push({ x: point.x, y: point.y, z: point.z });
|
|
@@ -1816,7 +2242,7 @@ export function createSimulation(engine, world, { tickDurationSec, characterKind
|
|
|
1816
2242
|
/** How many tiles of ground are laid now. */
|
|
1817
2243
|
laidGroundTileCount: () => grounds.reduce((total, ground) => total + ground.tiles.size, 0),
|
|
1818
2244
|
/** Whether a body is at rest: asleep, so nothing about it changes until something touches it. A fixed one always is. */
|
|
1819
|
-
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())),
|
|
1820
2246
|
isCharacterResting(index) {
|
|
1821
2247
|
const character = characters[index];
|
|
1822
2248
|
// A step that changed the kind's own fields (taking a cart's handles, breath coming back) wakes it, so they're sent.
|