@zaisma/physics 0.0.0-stage → 2.4.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/LICENSE.txt +93 -0
- package/README.md +146 -2
- package/characters.js +189 -0
- package/data.js +85 -0
- package/declare.js +495 -0
- package/engine.js +48 -0
- package/index.d.ts +743 -0
- package/index.js +27 -0
- package/level-characters.js +139 -0
- package/package.json +54 -4
- package/piece.json +136 -0
- package/piece.json.js +137 -0
- package/rapier/LICENSE.txt +201 -0
- package/rapier/rapier.d.ts +903 -0
- package/rapier/rapier.js +12674 -0
- package/rapier/rapier.wasm +0 -0
- package/server.d.ts +34 -0
- package/server.js +17 -0
- package/simulation.js +1136 -0
- package/sync.js +1035 -0
- package/world.d.ts +4 -0
- package/world.js +5 -0
package/simulation.js
ADDED
|
@@ -0,0 +1,1136 @@
|
|
|
1
|
+
// The simulation: one physics world, stepped a fixed step at a time, the same code in a player's game, on a game
|
|
2
|
+
// server and in a game played alone. It holds the world's bodies (moving, kinematic or fixed), its ground (laid in
|
|
3
|
+
// tiles only near what moves, so a valley kilometres across costs what its busy corners cost), the joints that hold
|
|
4
|
+
// bodies together, the wheels of what drives, the seats characters ride in, and the characters themselves.
|
|
5
|
+
//
|
|
6
|
+
// A character is a capsule whose movement is someone else's: a character kind (characters.js has the piece's own
|
|
7
|
+
// walk; @zaisma/physics-party has hands that grab and carry; a game gives its own) steps it each fixed step with the
|
|
8
|
+
// world's queries in reach. Everything a step depends on is in what readBody, readCharacter and readJoint answer, so
|
|
9
|
+
// any side can be put where another says it is and carry on from there: a player's game from the game server's word,
|
|
10
|
+
// a game server from its room's saved state.
|
|
11
|
+
//
|
|
12
|
+
// The engine's index of where things are (what rays, sweeps and a character's move search) is only made again inside
|
|
13
|
+
// a world step. So a character kind steps just after the first of each fixed step's engine steps (or, if it asks,
|
|
14
|
+
// just before the first), when the index is where everything stood: the same in every game and on the game server,
|
|
15
|
+
// whatever was written in since.
|
|
16
|
+
import { MOTION_KINDS, RIDING_LAYER_NAME, refuse } from "./declare.js";
|
|
17
|
+
import { dataOf } from "./data.js";
|
|
18
|
+
|
|
19
|
+
/** A hit slower than this isn't told. */
|
|
20
|
+
const MINIMUM_TOLD_HIT_SPEED_M_PER_SEC = 1.2;
|
|
21
|
+
/** How many steps a touch is remembered for: a pushed body leaves its pusher for a moment at every shove. */
|
|
22
|
+
const TOUCH_MEMORY_STEP_COUNT = 15;
|
|
23
|
+
/** Cells a side in one tile of laid ground. */
|
|
24
|
+
const GROUND_TILE_CELL_COUNT = 32;
|
|
25
|
+
/** How long laid ground nothing came near is kept before it's taken up, in steps. */
|
|
26
|
+
const GROUND_KEPT_STEP_COUNT = 90;
|
|
27
|
+
/** The gap a character's controller keeps from what it touches. */
|
|
28
|
+
const CHARACTER_SKIN_M = 0.02;
|
|
29
|
+
const NO_TURN = Object.freeze({ x: 0, y: 0, z: 0, w: 1 });
|
|
30
|
+
|
|
31
|
+
/** An angle in radians, wrapped into -PI up to PI. */
|
|
32
|
+
export function wrapAngleRad(angleRad) {
|
|
33
|
+
const turnRad = Math.PI * 2;
|
|
34
|
+
return ((((angleRad + Math.PI) % turnRad) + turnRad) % turnRad) - Math.PI;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A point turned by a rotation. */
|
|
38
|
+
export function turned(point, rotation) {
|
|
39
|
+
const { x, y, z } = point;
|
|
40
|
+
const crossX = rotation.y * z - rotation.z * y;
|
|
41
|
+
const crossY = rotation.z * x - rotation.x * z;
|
|
42
|
+
const crossZ = rotation.x * y - rotation.y * x;
|
|
43
|
+
return {
|
|
44
|
+
x: x + 2 * (rotation.w * crossX + rotation.y * crossZ - rotation.z * crossY),
|
|
45
|
+
y: y + 2 * (rotation.w * crossY + rotation.z * crossX - rotation.x * crossZ),
|
|
46
|
+
z: z + 2 * (rotation.w * crossZ + rotation.x * crossY - rotation.y * crossX),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
export const turnedBack = (point, rotation) => turned(point, { x: -rotation.x, y: -rotation.y, z: -rotation.z, w: rotation.w });
|
|
50
|
+
/** Which way a rotation faces about +Y, in radians: 0 along +Z. */
|
|
51
|
+
export const yawOf = (rotation) => {
|
|
52
|
+
const forward = turned({ x: 0, y: 0, z: 1 }, rotation);
|
|
53
|
+
return Math.atan2(forward.x, forward.z);
|
|
54
|
+
};
|
|
55
|
+
const rotationAboutYOf = (yawRad) => ({ x: 0, y: Math.sin(yawRad / 2), z: 0, w: Math.cos(yawRad / 2) });
|
|
56
|
+
|
|
57
|
+
/** A moving body lighter than this is small and may be quick: it's watched for passing through things between steps. */
|
|
58
|
+
const SMALL_BODY_MASS_KG = 8;
|
|
59
|
+
/** How many substeps' travel a small body looks ahead for what it'll meet, and the least it looks. */
|
|
60
|
+
const SMALL_BODY_LOOK_AHEAD_NUMBER = 1.5;
|
|
61
|
+
const SMALL_BODY_LOOK_AHEAD_MARGIN_M = 0.02;
|
|
62
|
+
const MAXIMUM_LOOK_AHEAD_M = 2;
|
|
63
|
+
/** The engine's own cap on a wheel's spring, kept for a light vehicle; a heavy one gets this many times its weight on each wheel. */
|
|
64
|
+
const DEFAULT_MAXIMUM_SUSPENSION_FORCE_NEWTONS = 6000;
|
|
65
|
+
const SUSPENSION_FORCE_HEADROOM_NUMBER = 2.5;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Makes a simulation of a world (definePhysicsWorld's answer) on the engine, stepped tickDurationSec at a time.
|
|
69
|
+
* characterKind is how characters move (characters.js); tuning is the world's numbers (gravity, how surfaces grip and
|
|
70
|
+
* bounce, how motion dies away); readDataFile reads a data file where the world opens on a game server. Bodies and
|
|
71
|
+
* characters are known by an index from 0, which is what the wire carries; ids are for the game.
|
|
72
|
+
*/
|
|
73
|
+
export function createSimulation(engine, world, { tickDurationSec, characterKind, tuning, readDataFile = null, tracksTouches = false, isEachCharacterAlone = false }) {
|
|
74
|
+
let currentTuning = tuning;
|
|
75
|
+
let stepCount = 0;
|
|
76
|
+
const substepDurationSec = tickDurationSec / world.substepCount;
|
|
77
|
+
const rapierWorld = new engine.World({ x: 0, y: -currentTuning.gravityMPerSecPerSec, z: 0 });
|
|
78
|
+
rapierWorld.timestep = substepDurationSec;
|
|
79
|
+
const eventQueue = new engine.EventQueue(true);
|
|
80
|
+
const bodies = [];
|
|
81
|
+
const bodyIndexById = new Map();
|
|
82
|
+
const characters = [];
|
|
83
|
+
const characterIndexById = new Map();
|
|
84
|
+
/** Who a collider belongs to: { isCharacter, index }, or { isGround } for laid ground. */
|
|
85
|
+
const ownerByColliderHandle = new Map();
|
|
86
|
+
const movingBodyByHandle = new Map();
|
|
87
|
+
const joints = new Map();
|
|
88
|
+
let hits = [];
|
|
89
|
+
/** Whether bodies were put somewhere since their colliders last followed. */
|
|
90
|
+
let isPropagationOwed = false;
|
|
91
|
+
const propagateIfOwed = () => {
|
|
92
|
+
if (!isPropagationOwed) return;
|
|
93
|
+
isPropagationOwed = false;
|
|
94
|
+
rapierWorld.propagateModifiedBodyPositionsToColliders();
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
// ---- Collision layers: each a bit; a collider is in its layer's and touches the layers it touches ----
|
|
98
|
+
const layerIndexByName = new Map(world.collisionLayers.map((layer, layerIndex) => [layer.name, layerIndex]));
|
|
99
|
+
const groupsOfLayer = world.collisionLayers.map((layer) => {
|
|
100
|
+
let touchedLayerNumber = 0;
|
|
101
|
+
for (const touchedName of layer.touchedNames) touchedLayerNumber |= 1 << layerIndexByName.get(touchedName);
|
|
102
|
+
return ((1 << layerIndexByName.get(layer.name)) << 16) | touchedLayerNumber;
|
|
103
|
+
});
|
|
104
|
+
const ridingLayerIndex = layerIndexByName.get(RIDING_LAYER_NAME);
|
|
105
|
+
const characterLayerIndex = layerIndexByName.get("character");
|
|
106
|
+
const groupsOf = (layerIndex) => groupsOfLayer[layerIndex] >>> 0;
|
|
107
|
+
|
|
108
|
+
const gripNumberOf = (declaration) => (declaration.gripPct ?? currentTuning.gripPct) / 100;
|
|
109
|
+
const bounceNumberOf = (declaration) => (declaration.bouncePct ?? currentTuning.bouncePct) / 100;
|
|
110
|
+
|
|
111
|
+
function colliderDescriptionOf(shape) {
|
|
112
|
+
let description;
|
|
113
|
+
if (shape.shapeKind === "box") description = engine.ColliderDesc.cuboid(shape.sizeM.x / 2, shape.sizeM.y / 2, shape.sizeM.z / 2);
|
|
114
|
+
else if (shape.shapeKind === "ball") description = engine.ColliderDesc.ball(shape.radiusM);
|
|
115
|
+
else if (shape.shapeKind === "capsule") description = engine.ColliderDesc.capsule(shape.heightM / 2 - shape.radiusM, shape.radiusM);
|
|
116
|
+
else if (shape.shapeKind === "cylinder") description = engine.ColliderDesc.cylinder(shape.heightM / 2, shape.radiusM);
|
|
117
|
+
else if (shape.shapeKind === "hull") description = engine.ColliderDesc.convexHull(new Float32Array(shape.pointsM));
|
|
118
|
+
else {
|
|
119
|
+
const mesh = dataOf(shape, readDataFile);
|
|
120
|
+
description = engine.ColliderDesc.trimesh(mesh.pointsM, mesh.triangleIndices);
|
|
121
|
+
}
|
|
122
|
+
// A hull of points all in one plane has no inside: a small ball stands in, so the body is still there.
|
|
123
|
+
if (!description) description = engine.ColliderDesc.ball(0.05);
|
|
124
|
+
return description.setTranslation(shape.positionM.x, shape.positionM.y, shape.positionM.z).setRotation(shape.rotation);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ---- Ground: a heightfield laid in tiles near whatever moves, taken up when nothing comes near ----
|
|
128
|
+
const grounds = [];
|
|
129
|
+
/** Places the game wants ground under though nothing moves there (a camera looking past), this step. */
|
|
130
|
+
let keptPoints = [];
|
|
131
|
+
|
|
132
|
+
function addGround(body, shape) {
|
|
133
|
+
const { heightsM } = dataOf(shape, readDataFile);
|
|
134
|
+
// The heightfield's first height is at the shape's place; rows run along +z, columns along +x, as the body turns them.
|
|
135
|
+
grounds.push({ body, shape, heightsM, tiles: new Map(), rowTileCount: Math.ceil((shape.rowCount - 1) / GROUND_TILE_CELL_COUNT), columnTileCount: Math.ceil((shape.columnCount - 1) / GROUND_TILE_CELL_COUNT) });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function layTile(ground, rowTileIndex, columnTileIndex) {
|
|
139
|
+
const { shape, heightsM, body } = ground;
|
|
140
|
+
const firstRowIndex = rowTileIndex * GROUND_TILE_CELL_COUNT;
|
|
141
|
+
const firstColumnIndex = columnTileIndex * GROUND_TILE_CELL_COUNT;
|
|
142
|
+
const rowCellCount = Math.min(GROUND_TILE_CELL_COUNT, shape.rowCount - 1 - firstRowIndex);
|
|
143
|
+
const columnCellCount = Math.min(GROUND_TILE_CELL_COUNT, shape.columnCount - 1 - firstColumnIndex);
|
|
144
|
+
// The engine's heights: (rows + 1) by (columns + 1), rows along its z, stored column after column.
|
|
145
|
+
const tileHeights = new Float32Array((rowCellCount + 1) * (columnCellCount + 1));
|
|
146
|
+
for (let columnStepIndex = 0; columnStepIndex <= columnCellCount; columnStepIndex += 1) {
|
|
147
|
+
for (let rowStepIndex = 0; rowStepIndex <= rowCellCount; rowStepIndex += 1) tileHeights[columnStepIndex * (rowCellCount + 1) + rowStepIndex] = heightsM[(firstRowIndex + rowStepIndex) * shape.columnCount + firstColumnIndex + columnStepIndex];
|
|
148
|
+
}
|
|
149
|
+
const widthM = columnCellCount * shape.cellSizeM;
|
|
150
|
+
const depthM = rowCellCount * shape.cellSizeM;
|
|
151
|
+
const centerM = turned({ x: shape.positionM.x + (firstColumnIndex * shape.cellSizeM + widthM / 2), y: shape.positionM.y, z: shape.positionM.z + (firstRowIndex * shape.cellSizeM + depthM / 2) }, NO_TURN);
|
|
152
|
+
const description = engine.ColliderDesc.heightfield(rowCellCount, columnCellCount, tileHeights, { x: widthM, y: 1, z: depthM })
|
|
153
|
+
.setTranslation(centerM.x, centerM.y, centerM.z)
|
|
154
|
+
.setRotation(shape.rotation)
|
|
155
|
+
.setFriction(gripNumberOf(body.declaration))
|
|
156
|
+
.setRestitution(bounceNumberOf(body.declaration))
|
|
157
|
+
.setCollisionGroups(groupsOf(body.layerIndex));
|
|
158
|
+
const collider = rapierWorld.createCollider(description, body.rigidBody);
|
|
159
|
+
ownerByColliderHandle.set(collider.handle, { isCharacter: false, index: body.index, isGround: true });
|
|
160
|
+
isSceneOwed = true;
|
|
161
|
+
return { collider, keptUntilStepCount: 0 };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Lays the ground near a point (in the world), keeping it a while: every tile within reach of it. */
|
|
165
|
+
function keepGroundAround(point, reachM, untilStepCount) {
|
|
166
|
+
for (const ground of grounds) {
|
|
167
|
+
const bodyM = ground.body.rigidBody.translation();
|
|
168
|
+
const local = turnedBack({ x: point.x - bodyM.x, y: point.y - bodyM.y, z: point.z - bodyM.z }, ground.body.rigidBody.rotation());
|
|
169
|
+
const tileSizeM = GROUND_TILE_CELL_COUNT * ground.shape.cellSizeM;
|
|
170
|
+
const firstColumnTileIndex = Math.max(Math.floor((local.x - ground.shape.positionM.x - reachM) / tileSizeM), 0);
|
|
171
|
+
const lastColumnTileIndex = Math.min(Math.floor((local.x - ground.shape.positionM.x + reachM) / tileSizeM), ground.columnTileCount - 1);
|
|
172
|
+
const firstRowTileIndex = Math.max(Math.floor((local.z - ground.shape.positionM.z - reachM) / tileSizeM), 0);
|
|
173
|
+
const lastRowTileIndex = Math.min(Math.floor((local.z - ground.shape.positionM.z + reachM) / tileSizeM), ground.rowTileCount - 1);
|
|
174
|
+
for (let rowTileIndex = firstRowTileIndex; rowTileIndex <= lastRowTileIndex; rowTileIndex += 1) {
|
|
175
|
+
for (let columnTileIndex = firstColumnTileIndex; columnTileIndex <= lastColumnTileIndex; columnTileIndex += 1) {
|
|
176
|
+
const tileNumber = rowTileIndex * 65536 + columnTileIndex;
|
|
177
|
+
let tile = ground.tiles.get(tileNumber);
|
|
178
|
+
if (!tile) ground.tiles.set(tileNumber, (tile = layTile(ground, rowTileIndex, columnTileIndex)));
|
|
179
|
+
tile.keptUntilStepCount = Math.max(tile.keptUntilStepCount, untilStepCount);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Before each step: ground under everything that moves (asleep too, so it never wakes over a hole), and where the game asked. */
|
|
186
|
+
function layGround() {
|
|
187
|
+
if (!grounds.length) return;
|
|
188
|
+
const untilStepCount = stepCount + GROUND_KEPT_STEP_COUNT;
|
|
189
|
+
for (const body of bodies) if (body && body.motionIndex !== 2) keepGroundAround(body.rigidBody.translation(), world.groundReachM, untilStepCount);
|
|
190
|
+
for (const character of characters) if (character && !character.isWaiting) keepGroundAround(character.rigidBody.translation(), world.groundReachM, untilStepCount);
|
|
191
|
+
for (const point of keptPoints) keepGroundAround(point, world.groundReachM, untilStepCount);
|
|
192
|
+
keptPoints = [];
|
|
193
|
+
pruneGround();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Every so often, the ground nothing has kept lately is taken up. */
|
|
197
|
+
function pruneGround() {
|
|
198
|
+
if (stepCount % 30 !== 0) return;
|
|
199
|
+
for (const ground of grounds) {
|
|
200
|
+
for (const [tileNumber, tile] of ground.tiles) {
|
|
201
|
+
if (tile.keptUntilStepCount >= stepCount) continue;
|
|
202
|
+
ownerByColliderHandle.delete(tile.collider.handle);
|
|
203
|
+
rapierWorld.removeCollider(tile.collider, false);
|
|
204
|
+
ground.tiles.delete(tileNumber);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---- Bodies ----
|
|
210
|
+
|
|
211
|
+
const bodyTypeOf = (motionIndex) => (motionIndex === 0 ? engine.RigidBodyType.Dynamic : motionIndex === 1 ? engine.RigidBodyType.KinematicVelocityBased : engine.RigidBodyType.Fixed);
|
|
212
|
+
|
|
213
|
+
/** Adds a body (checkBody's answer) at an index: the next free one, or the one given. Answers the index. */
|
|
214
|
+
function addBody(declaration, givenIndex = null) {
|
|
215
|
+
let index = givenIndex;
|
|
216
|
+
if (index === null) {
|
|
217
|
+
index = bodies.findIndex((held) => held === null);
|
|
218
|
+
if (index === -1) index = bodies.length;
|
|
219
|
+
}
|
|
220
|
+
while (bodies.length <= index) bodies.push(null);
|
|
221
|
+
const motionIndex = MOTION_KINDS.indexOf(declaration.motionKind);
|
|
222
|
+
const description = (motionIndex === 0 ? engine.RigidBodyDesc.dynamic() : motionIndex === 1 ? engine.RigidBodyDesc.kinematicVelocityBased() : engine.RigidBodyDesc.fixed())
|
|
223
|
+
.setTranslation(declaration.positionM.x, declaration.positionM.y, declaration.positionM.z)
|
|
224
|
+
.setRotation(declaration.rotation)
|
|
225
|
+
.setLinearDamping(declaration.linearDampingNumber ?? currentTuning.linearDampingNumber)
|
|
226
|
+
.setAngularDamping(declaration.angularDampingNumber ?? currentTuning.angularDampingNumber);
|
|
227
|
+
const rigidBody = rapierWorld.createRigidBody(description);
|
|
228
|
+
const layerIndex = layerIndexByName.get(declaration.collisionLayerName);
|
|
229
|
+
const body = { index, declaration, rigidBody, colliders: [], motionIndex, declaredMotionIndex: motionIndex, layerIndex, velocityBefore: { x: 0, y: 0, z: 0 }, vehicle: null };
|
|
230
|
+
bodies[index] = body;
|
|
231
|
+
for (const shape of declaration.shapes) {
|
|
232
|
+
if (shape.shapeKind === "heightfield") {
|
|
233
|
+
addGround(body, shape);
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (shape.shapeKind === "mesh" && shape.triangleGroupNumbers) {
|
|
237
|
+
addGroupedMesh(body, shape);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
const collider = rapierWorld.createCollider(colliderDescriptionOf(shape).setDensity(1).setFriction(gripNumberOf(declaration)).setRestitution(bounceNumberOf(declaration)).setCollisionGroups(groupsOf(layerIndex)).setActiveEvents(motionIndex === 0 ? engine.ActiveEvents.COLLISION_EVENTS : engine.ActiveEvents.NONE), rigidBody);
|
|
241
|
+
ownerByColliderHandle.set(collider.handle, { isCharacter: false, index });
|
|
242
|
+
body.colliders.push(collider);
|
|
243
|
+
}
|
|
244
|
+
if (motionIndex === 0) {
|
|
245
|
+
// The shapes share the body's mass by how much room each takes.
|
|
246
|
+
body.massAtUnitDensityKg = rigidBody.mass();
|
|
247
|
+
setBodyMass(body, declaration.massKg);
|
|
248
|
+
// A small thing thrown hard would pass through a wall between two steps.
|
|
249
|
+
body.isSmall = declaration.massKg < SMALL_BODY_MASS_KG;
|
|
250
|
+
rigidBody.enableCcd(body.isSmall);
|
|
251
|
+
movingBodyByHandle.set(rigidBody.handle, index);
|
|
252
|
+
}
|
|
253
|
+
if (declaration.wheels.length) body.vehicle = addVehicle(body);
|
|
254
|
+
bodyIndexById.set(declaration.id, index);
|
|
255
|
+
return index;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Triangle groups by number: the colliders of each, switched on and off together. */
|
|
259
|
+
const groupColliders = new Map();
|
|
260
|
+
let offTriangleGroupMaskNumber = 0;
|
|
261
|
+
/** A mesh whose triangles come in groups: a collider for each group, so a door or a bridge can come and go. */
|
|
262
|
+
function addGroupedMesh(body, shape) {
|
|
263
|
+
const { pointsM, triangleIndices } = dataOf(shape, readDataFile);
|
|
264
|
+
const groupNumbers = shape.triangleGroupNumbers;
|
|
265
|
+
if (groupNumbers.length !== triangleIndices.length / 3) refuse("bad_body", `${body.declaration.id}'s mesh has ${triangleIndices.length / 3} triangles and ${groupNumbers.length} triangleGroupNumbers.`, "triangleGroupNumbers", "Give one group number for each of the mesh's triangles.");
|
|
266
|
+
const countByGroup = new Map();
|
|
267
|
+
for (const groupNumber of groupNumbers) countByGroup.set(groupNumber, (countByGroup.get(groupNumber) ?? 0) + 1);
|
|
268
|
+
for (const [groupNumber, triangleCount] of countByGroup) {
|
|
269
|
+
const groupIndices = new Uint32Array(triangleCount * 3);
|
|
270
|
+
let writtenCount = 0;
|
|
271
|
+
for (let triangleIndex = 0; triangleIndex < groupNumbers.length; triangleIndex += 1) {
|
|
272
|
+
if (groupNumbers[triangleIndex] !== groupNumber) continue;
|
|
273
|
+
groupIndices.set(triangleIndices.subarray(triangleIndex * 3, triangleIndex * 3 + 3), writtenCount);
|
|
274
|
+
writtenCount += 3;
|
|
275
|
+
}
|
|
276
|
+
const description = engine.ColliderDesc.trimesh(pointsM, groupIndices).setTranslation(shape.positionM.x, shape.positionM.y, shape.positionM.z).setRotation(shape.rotation);
|
|
277
|
+
const collider = rapierWorld.createCollider(description.setFriction(gripNumberOf(body.declaration)).setRestitution(bounceNumberOf(body.declaration)).setCollisionGroups(groupsOf(body.layerIndex)), body.rigidBody);
|
|
278
|
+
ownerByColliderHandle.set(collider.handle, { isCharacter: false, index: body.index });
|
|
279
|
+
body.colliders.push(collider);
|
|
280
|
+
if (groupNumber === 0) continue;
|
|
281
|
+
if (!groupColliders.has(groupNumber)) groupColliders.set(groupNumber, []);
|
|
282
|
+
groupColliders.get(groupNumber).push(collider);
|
|
283
|
+
collider.setEnabled(!(offTriangleGroupMaskNumber & (1 << (groupNumber - 1))));
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/** Which triangle groups are off: a bit for each, group 1 the lowest. */
|
|
287
|
+
function setOffTriangleGroups(maskNumber) {
|
|
288
|
+
if (maskNumber === offTriangleGroupMaskNumber) return;
|
|
289
|
+
offTriangleGroupMaskNumber = maskNumber;
|
|
290
|
+
for (const [groupNumber, colliders] of groupColliders) for (const collider of colliders) collider.setEnabled(!(maskNumber & (1 << (groupNumber - 1))));
|
|
291
|
+
isSceneOwed = true;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function removeBody(index) {
|
|
295
|
+
const body = bodies[index];
|
|
296
|
+
if (!body) return false;
|
|
297
|
+
characterKind.onBodyRemoved?.(index, stepTools);
|
|
298
|
+
for (const [jointId, joint] of joints) if (joint.bodyIndexes.includes(index)) removeJoint(jointId);
|
|
299
|
+
for (const character of characters) if (character?.rideBodyIndex === index) unseat(character);
|
|
300
|
+
if (body.vehicle) rapierWorld.removeVehicleController(body.vehicle.controller);
|
|
301
|
+
for (const collider of body.colliders) ownerByColliderHandle.delete(collider.handle);
|
|
302
|
+
for (const ground of grounds.filter((each) => each.body === body)) for (const tile of ground.tiles.values()) ownerByColliderHandle.delete(tile.collider.handle);
|
|
303
|
+
for (let groundIndex = grounds.length - 1; groundIndex >= 0; groundIndex -= 1) if (grounds[groundIndex].body === body) grounds.splice(groundIndex, 1);
|
|
304
|
+
movingBodyByHandle.delete(body.rigidBody.handle);
|
|
305
|
+
rapierWorld.removeRigidBody(body.rigidBody);
|
|
306
|
+
bodyIndexById.delete(body.declaration.id);
|
|
307
|
+
bodies[index] = null;
|
|
308
|
+
return true;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Makes a moving body this heavy, its shapes sharing it by how much room each takes: what rides in a cart weighs on it. */
|
|
312
|
+
function setBodyMass(body, massKg) {
|
|
313
|
+
if (body.massKg === massKg || !(body.massAtUnitDensityKg > 0)) return;
|
|
314
|
+
body.massKg = massKg;
|
|
315
|
+
const densityNumber = massKg / body.massAtUnitDensityKg;
|
|
316
|
+
for (const collider of body.colliders) collider.setDensity(densityNumber);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Changes how a body moves while playing: a parked cart made fixed, a lift made kinematic, and back. */
|
|
320
|
+
function setBodyMotion(body, motionIndex) {
|
|
321
|
+
if (body.motionIndex === motionIndex || body.declaredMotionIndex === 2) return;
|
|
322
|
+
body.motionIndex = motionIndex;
|
|
323
|
+
body.rigidBody.setBodyType(bodyTypeOf(motionIndex), true);
|
|
324
|
+
if (motionIndex === 0) movingBodyByHandle.set(body.rigidBody.handle, body.index);
|
|
325
|
+
else movingBodyByHandle.delete(body.rigidBody.handle);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function setBodyLayer(body, layerIndex) {
|
|
329
|
+
if (body.layerIndex === layerIndex) return;
|
|
330
|
+
body.layerIndex = layerIndex;
|
|
331
|
+
for (const collider of body.colliders) collider.setCollisionGroups(groupsOf(layerIndex));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ---- Vehicles: a body on wheels, driven by whoever sits in its first seat ----
|
|
335
|
+
|
|
336
|
+
function addVehicle(body) {
|
|
337
|
+
const controller = rapierWorld.createVehicleController(body.rigidBody);
|
|
338
|
+
controller.indexUpAxis = 1;
|
|
339
|
+
controller.setIndexForwardAxis = 2;
|
|
340
|
+
const { vehicle } = body.declaration;
|
|
341
|
+
body.declaration.wheels.forEach((wheel, wheelIndex) => {
|
|
342
|
+
controller.addWheel(wheel.positionM, { x: 0, y: -1, z: 0 }, { x: -1, y: 0, z: 0 }, wheel.suspensionRestM, wheel.radiusM);
|
|
343
|
+
controller.setWheelSuspensionStiffness(wheelIndex, vehicle.suspensionStiffnessNumber);
|
|
344
|
+
controller.setWheelSuspensionCompression(wheelIndex, vehicle.suspensionDampingNumber);
|
|
345
|
+
controller.setWheelSuspensionRelaxation(wheelIndex, vehicle.suspensionDampingNumber * 1.2);
|
|
346
|
+
controller.setWheelMaxSuspensionTravel(wheelIndex, wheel.suspensionTravelM);
|
|
347
|
+
controller.setWheelFrictionSlip(wheelIndex, vehicle.frictionSlipNumber);
|
|
348
|
+
controller.setWheelSideFrictionStiffness(wheelIndex, vehicle.sideFrictionNumber);
|
|
349
|
+
// The engine scales a spring's force by the body's mass: a heavy truck needs more than its 6,000 N cap, or it sits on its stops.
|
|
350
|
+
controller.setWheelMaxSuspensionForce(wheelIndex, vehicle.maximumSuspensionForceNewtons ?? Math.max(DEFAULT_MAXIMUM_SUSPENSION_FORCE_NEWTONS, (SUSPENSION_FORCE_HEADROOM_NUMBER * body.declaration.massKg * currentTuning.gravityMPerSecPerSec) / body.declaration.wheels.length));
|
|
351
|
+
});
|
|
352
|
+
// What the wheels stand on: the layers named, or every layer the vehicle touches but characters'. Never a character, never itself.
|
|
353
|
+
const wheelLayerNames = vehicle.wheelCollisionLayerNames ?? world.collisionLayers.filter((layer) => layer.name !== "character" && layer.name !== RIDING_LAYER_NAME && world.collisionLayers[body.layerIndex].touchedNames.includes(layer.name)).map((layer) => layer.name);
|
|
354
|
+
let wheelLayerMaskNumber = 0;
|
|
355
|
+
for (const name of wheelLayerNames) {
|
|
356
|
+
if (!layerIndexByName.has(name)) refuse("bad_body", `${body.declaration.id}'s vehicle.wheelCollisionLayerNames names "${name}", which isn't one of the world's collisionLayers.`, "vehicle.wheelCollisionLayerNames", `Use the world's collisionLayers: ${world.collisionLayers.map((layer) => layer.name).join(", ")}.`);
|
|
357
|
+
wheelLayerMaskNumber |= 1 << layerIndexByName.get(name);
|
|
358
|
+
}
|
|
359
|
+
return { controller, engineNumber: 0, steerNumber: 0, brakeNumber: 0, wheelGroupsNumber: (((0xffff << 16) | wheelLayerMaskNumber) >>> 0) };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Sets each vehicle's controls from its driver's input, or lets it roll with none. */
|
|
363
|
+
function driveVehicles(worldStepContext) {
|
|
364
|
+
const { inputOf } = worldStepContext;
|
|
365
|
+
for (const body of bodies) {
|
|
366
|
+
if (!body?.vehicle) continue;
|
|
367
|
+
const driver = characters.find((character) => character && character.rideBodyIndex === body.index && character.seatIndex === 0);
|
|
368
|
+
const controls = driver ? characterKind.vehicleControls(inputOf(driver.id) ?? characterKind.idleInput, { bodyId: body.declaration.id, ...stepTools.bodyState(body.declaration.id) }, worldStepContext) : { engineNumber: 0, steerNumber: 0, brakeNumber: 0 };
|
|
369
|
+
const { vehicle } = body.declaration;
|
|
370
|
+
const { controller } = body.vehicle;
|
|
371
|
+
const engineNumber = Math.min(Math.max(controls.engineNumber, -1), 1);
|
|
372
|
+
const steerRad = (Math.min(Math.max(controls.steerNumber, -1), 1) * vehicle.maximumSteerDeg * Math.PI) / 180;
|
|
373
|
+
const brakeNumber = Math.min(Math.max(controls.brakeNumber, 0), 1);
|
|
374
|
+
const drivenCount = body.declaration.wheels.filter((wheel) => wheel.isDriven).length || 1;
|
|
375
|
+
body.declaration.wheels.forEach((wheel, wheelIndex) => {
|
|
376
|
+
controller.setWheelEngineForce(wheelIndex, wheel.isDriven ? (engineNumber * vehicle.maximumEngineForceNewtons) / drivenCount : 0);
|
|
377
|
+
controller.setWheelSteering(wheelIndex, wheel.isSteered ? steerRad : 0);
|
|
378
|
+
// A vehicle nobody drives holds a little brake, so it doesn't roll away on a slope.
|
|
379
|
+
controller.setWheelBrake(wheelIndex, (driver ? brakeNumber : 0.05) * vehicle.maximumBrakeForceNewtons);
|
|
380
|
+
});
|
|
381
|
+
if (engineNumber !== 0 || brakeNumber !== 0) body.rigidBody.wakeUp();
|
|
382
|
+
body.vehicle.steerNumber = controls.steerNumber;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function updateVehicles() {
|
|
387
|
+
for (const body of bodies) {
|
|
388
|
+
if (!body?.vehicle || body.motionIndex !== 0 || body.rigidBody.isSleeping()) continue;
|
|
389
|
+
body.vehicle.controller.updateVehicle(substepDurationSec, engine.QueryFilterFlags.EXCLUDE_SENSORS, body.vehicle.wheelGroupsNumber, (collider) => {
|
|
390
|
+
const owner = ownerByColliderHandle.get(collider.handle);
|
|
391
|
+
return !owner?.isCharacter && owner?.index !== body.index;
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// ---- Joints ----
|
|
397
|
+
|
|
398
|
+
/** The engine body a joint end names: a body's, or a character's, by id. */
|
|
399
|
+
const endOf = (id) => {
|
|
400
|
+
if (bodyIndexById.has(id)) return { rigidBody: bodies[bodyIndexById.get(id)].rigidBody, bodyIndex: bodyIndexById.get(id), characterIndex: -1 };
|
|
401
|
+
if (characterIndexById.has(id)) return { rigidBody: characters[characterIndexById.get(id)].rigidBody, bodyIndex: -1, characterIndex: characterIndexById.get(id) };
|
|
402
|
+
return null;
|
|
403
|
+
};
|
|
404
|
+
let worldAnchor = null;
|
|
405
|
+
|
|
406
|
+
/** Adds a joint (checkJoint's answer). Answers false when an end isn't here (yet). */
|
|
407
|
+
function addJoint(declaration, isEnabled = true) {
|
|
408
|
+
if (joints.has(declaration.id)) return true;
|
|
409
|
+
const first = endOf(declaration.bodyId);
|
|
410
|
+
const second = declaration.otherBodyId === null ? null : endOf(declaration.otherBodyId);
|
|
411
|
+
if (!first || (declaration.otherBodyId !== null && !second)) return false;
|
|
412
|
+
worldAnchor ??= rapierWorld.createRigidBody(engine.RigidBodyDesc.fixed());
|
|
413
|
+
const joint = { declaration, rapierJoint: null, isEnabled: false, bodyIndexes: [first.bodyIndex, second?.bodyIndex ?? -1], characterIndexes: [first.characterIndex, second?.characterIndex ?? -1], first, second };
|
|
414
|
+
joints.set(declaration.id, joint);
|
|
415
|
+
setJointEnabled(joint, isEnabled);
|
|
416
|
+
return true;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function setJointEnabled(joint, isEnabled) {
|
|
420
|
+
if (joint.isEnabled === isEnabled) return;
|
|
421
|
+
joint.isEnabled = isEnabled;
|
|
422
|
+
if (!isEnabled) {
|
|
423
|
+
if (joint.rapierJoint) rapierWorld.removeImpulseJoint(joint.rapierJoint, true);
|
|
424
|
+
joint.rapierJoint = null;
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
const { declaration } = joint;
|
|
428
|
+
const { anchorM, otherAnchorM, axis } = declaration;
|
|
429
|
+
const otherRigidBody = joint.second?.rigidBody ?? worldAnchor;
|
|
430
|
+
let jointData;
|
|
431
|
+
if (declaration.jointKind === "fixed") jointData = engine.JointData.fixed(anchorM, NO_TURN, otherAnchorM, NO_TURN);
|
|
432
|
+
else if (declaration.jointKind === "ball") jointData = engine.JointData.spherical(anchorM, otherAnchorM);
|
|
433
|
+
else if (declaration.jointKind === "hinge") jointData = engine.JointData.revolute(anchorM, otherAnchorM, axis);
|
|
434
|
+
else if (declaration.jointKind === "slider") jointData = engine.JointData.prismatic(anchorM, otherAnchorM, axis);
|
|
435
|
+
else if (declaration.jointKind === "spring") jointData = engine.JointData.spring(declaration.restLengthM, declaration.stiffnessNumber, declaration.dampingNumber, anchorM, otherAnchorM);
|
|
436
|
+
else jointData = engine.JointData.rope(declaration.restLengthM, anchorM, otherAnchorM);
|
|
437
|
+
joint.rapierJoint = rapierWorld.createImpulseJoint(jointData, joint.first.rigidBody, otherRigidBody, true);
|
|
438
|
+
if ((declaration.jointKind === "hinge" || declaration.jointKind === "slider") && declaration.minimumNumber !== null && declaration.maximumNumber !== null) joint.rapierJoint.setLimits(declaration.minimumNumber, declaration.maximumNumber);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function removeJoint(jointId) {
|
|
442
|
+
const joint = joints.get(jointId);
|
|
443
|
+
if (!joint) return false;
|
|
444
|
+
setJointEnabled(joint, false);
|
|
445
|
+
joints.delete(jointId);
|
|
446
|
+
return true;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// ---- Characters ----
|
|
450
|
+
|
|
451
|
+
const characterHalfSegmentM = world.character.heightM / 2 - world.character.radiusM;
|
|
452
|
+
const isKinematicKind = characterKind.bodyKind === "kinematic";
|
|
453
|
+
const controller = isKinematicKind ? rapierWorld.createCharacterController(CHARACTER_SKIN_M) : null;
|
|
454
|
+
if (controller) {
|
|
455
|
+
controller.setUp({ x: 0, y: 1, z: 0 });
|
|
456
|
+
controller.setSlideEnabled(true);
|
|
457
|
+
if (world.character.stepHeightM > 0) controller.enableAutostep(world.character.stepHeightM, world.character.radiusM * 0.5, false);
|
|
458
|
+
controller.setMaxSlopeClimbAngle((world.character.maximumSlopeDeg * Math.PI) / 180);
|
|
459
|
+
controller.setMinSlopeSlideAngle?.(((world.character.maximumSlopeDeg + 5) * Math.PI) / 180);
|
|
460
|
+
controller.enableSnapToGround(world.character.stepHeightM > 0 ? world.character.stepHeightM : 0.1);
|
|
461
|
+
controller.setApplyImpulsesToDynamicBodies(characterKind.canPushBodies !== false);
|
|
462
|
+
controller.setCharacterMass(currentTuning.characterMassKg ?? 70);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Adds a character with its feet at a place, at an index: the next free one, or the one given. Answers the index.
|
|
467
|
+
* With isWaiting it's in the world's lists but not in the world, touching nothing, until writeCharacter says where
|
|
468
|
+
* it is: for a game that knows a character has joined before it knows where.
|
|
469
|
+
*/
|
|
470
|
+
function addCharacter(characterId, feetPositionM, givenIndex = null, isWaiting = false) {
|
|
471
|
+
let index = givenIndex;
|
|
472
|
+
if (index === null) {
|
|
473
|
+
index = characters.findIndex((held) => held === null);
|
|
474
|
+
if (index === -1) index = characters.length;
|
|
475
|
+
}
|
|
476
|
+
while (characters.length <= index) characters.push(null);
|
|
477
|
+
const description = (isKinematicKind ? engine.RigidBodyDesc.kinematicPositionBased() : engine.RigidBodyDesc.dynamic().lockRotations().setLinearDamping(0).setCcdEnabled(true)).setTranslation(feetPositionM.x, feetPositionM.y + world.character.heightM / 2, feetPositionM.z);
|
|
478
|
+
const rigidBody = rapierWorld.createRigidBody(description);
|
|
479
|
+
// No grip of its own, so a character never sticks to a wall it walks along: its feet's hold is in how it's moved.
|
|
480
|
+
// A kinematic character's capsule sits its controller's gap above the body's place: the controller keeps that gap
|
|
481
|
+
// from the ground, so the body stands exactly on it (and one placed exactly on the ground isn't already too close).
|
|
482
|
+
const colliderDescription = engine.ColliderDesc.capsule(characterHalfSegmentM, world.character.radiusM).setTranslation(0, isKinematicKind ? CHARACTER_SKIN_M : 0, 0).setFriction(0).setFrictionCombineRule(engine.CoefficientCombineRule.Min).setRestitution(0).setCollisionGroups(groupsOf(characterLayerIndex)).setActiveEvents(engine.ActiveEvents.COLLISION_EVENTS);
|
|
483
|
+
if (!isKinematicKind) colliderDescription.setMass(currentTuning.characterMassKg ?? 70);
|
|
484
|
+
const collider = rapierWorld.createCollider(colliderDescription, rigidBody);
|
|
485
|
+
ownerByColliderHandle.set(collider.handle, { isCharacter: true, index });
|
|
486
|
+
if (isWaiting) rigidBody.setEnabled(false);
|
|
487
|
+
const character = {
|
|
488
|
+
index,
|
|
489
|
+
id: characterId,
|
|
490
|
+
isWaiting,
|
|
491
|
+
rigidBody,
|
|
492
|
+
collider,
|
|
493
|
+
/** A kinematic character's speed: the engine doesn't keep one for it. */
|
|
494
|
+
velocity: { x: 0, y: 0, z: 0 },
|
|
495
|
+
facingYawRad: 0,
|
|
496
|
+
isGrounded: false,
|
|
497
|
+
airTickCount: 0,
|
|
498
|
+
rideBodyIndex: -1,
|
|
499
|
+
seatIndex: 0,
|
|
500
|
+
layerIndex: characterLayerIndex,
|
|
501
|
+
ownLayerIndex: characterLayerIndex,
|
|
502
|
+
/** The character kind's own fields, by name. */
|
|
503
|
+
own: characterKind.startOwn(stepTools),
|
|
504
|
+
};
|
|
505
|
+
characters[index] = character;
|
|
506
|
+
characterIndexById.set(characterId, index);
|
|
507
|
+
characterKind.onCharacterAdded?.(character, stepTools);
|
|
508
|
+
return index;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function removeCharacter(index) {
|
|
512
|
+
const character = characters[index];
|
|
513
|
+
if (!character) return false;
|
|
514
|
+
characterKind.onCharacterRemoved?.(character, stepTools);
|
|
515
|
+
for (const [jointId, joint] of joints) if (joint.characterIndexes.includes(index)) removeJoint(jointId);
|
|
516
|
+
ownerByColliderHandle.delete(character.collider.handle);
|
|
517
|
+
rapierWorld.removeRigidBody(character.rigidBody);
|
|
518
|
+
characterIndexById.delete(character.id);
|
|
519
|
+
characters[index] = null;
|
|
520
|
+
return true;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function setCharacterLayer(character, layerIndex) {
|
|
524
|
+
if (character.layerIndex === layerIndex) return;
|
|
525
|
+
character.layerIndex = layerIndex;
|
|
526
|
+
character.collider.setCollisionGroups(groupsOf(layerIndex));
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** Puts a character in a body's seat: it rides there, touching nothing, until it's let out. */
|
|
530
|
+
function seat(character, bodyIndex, seatIndex) {
|
|
531
|
+
const body = bodies[bodyIndex];
|
|
532
|
+
if (!body || !body.declaration.seats[seatIndex]) return false;
|
|
533
|
+
character.rideBodyIndex = bodyIndex;
|
|
534
|
+
character.seatIndex = seatIndex;
|
|
535
|
+
setCharacterLayer(character, ridingLayerIndex);
|
|
536
|
+
if (!isKinematicKind) character.rigidBody.setGravityScale(0, false);
|
|
537
|
+
placeRider(character);
|
|
538
|
+
return true;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function unseat(character) {
|
|
542
|
+
if (character.rideBodyIndex < 0) return;
|
|
543
|
+
character.rideBodyIndex = -1;
|
|
544
|
+
character.seatIndex = 0;
|
|
545
|
+
setCharacterLayer(character, character.ownLayerIndex);
|
|
546
|
+
if (!isKinematicKind) character.rigidBody.setGravityScale(1, true);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** A rider goes where its seat went, facing where it faces, moving as it moves. */
|
|
550
|
+
function placeRider(character) {
|
|
551
|
+
const body = bodies[character.rideBodyIndex];
|
|
552
|
+
const seatDeclaration = body?.declaration.seats[character.seatIndex];
|
|
553
|
+
if (!seatDeclaration) return void unseat(character);
|
|
554
|
+
const bodyM = body.rigidBody.translation();
|
|
555
|
+
const rotation = body.rigidBody.rotation();
|
|
556
|
+
const offset = turned(seatDeclaration.positionM, rotation);
|
|
557
|
+
const centerM = { x: bodyM.x + offset.x, y: bodyM.y + offset.y + world.character.heightM / 2, z: bodyM.z + offset.z };
|
|
558
|
+
character.rigidBody.setTranslation(centerM, true);
|
|
559
|
+
const velocity = body.rigidBody.velocityAtPoint(centerM);
|
|
560
|
+
if (isKinematicKind) character.velocity = { x: velocity.x, y: velocity.y, z: velocity.z };
|
|
561
|
+
else character.rigidBody.setLinvel(velocity, true);
|
|
562
|
+
character.facingYawRad = wrapAngleRad(yawOf(rotation) + seatDeclaration.facingYawRad);
|
|
563
|
+
character.isGrounded = true;
|
|
564
|
+
character.airTickCount = 0;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// ---- Queries, as a character kind and a game ask them ----
|
|
568
|
+
|
|
569
|
+
/** Who a collider is: { bodyId, characterId }, or null for something not the world's own. */
|
|
570
|
+
const whoOf = (collider) => {
|
|
571
|
+
const owner = ownerByColliderHandle.get(collider.handle);
|
|
572
|
+
if (!owner) return null;
|
|
573
|
+
return owner.isCharacter ? { bodyId: null, characterId: characters[owner.index]?.id ?? null } : { bodyId: bodies[owner.index]?.declaration.id ?? null, characterId: null };
|
|
574
|
+
};
|
|
575
|
+
/** The groups a query searches with: the layers named (all, when none), as a layer that touches them. */
|
|
576
|
+
const queryGroupsOf = (layerNames) => {
|
|
577
|
+
if (!layerNames) return 0xffffffff;
|
|
578
|
+
let layerMaskNumber = 0;
|
|
579
|
+
for (const name of layerNames) if (layerIndexByName.has(name)) layerMaskNumber |= 1 << layerIndexByName.get(name);
|
|
580
|
+
return ((0xffff << 16) | layerMaskNumber) >>> 0;
|
|
581
|
+
};
|
|
582
|
+
const excludedOf = (exclude) => {
|
|
583
|
+
if (!exclude) return null;
|
|
584
|
+
if (characterIndexById.has(exclude)) return characters[characterIndexById.get(exclude)].rigidBody;
|
|
585
|
+
if (bodyIndexById.has(exclude)) return bodies[bodyIndexById.get(exclude)].rigidBody;
|
|
586
|
+
return null;
|
|
587
|
+
};
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* A hit as a query answers it, written into the caller's own object when it gives one (a game casting thousands of
|
|
591
|
+
* rays a second keeps one), else a new one.
|
|
592
|
+
*/
|
|
593
|
+
function hitInto(into, collider, pointX, pointY, pointZ, normalX, normalY, normalZ, distanceM) {
|
|
594
|
+
const hit = into ?? { bodyId: null, characterId: null, pointM: { x: 0, y: 0, z: 0 }, normal: { x: 0, y: 0, z: 0 }, distanceM: 0 };
|
|
595
|
+
const who = whoOf(collider);
|
|
596
|
+
hit.bodyId = who?.bodyId ?? null;
|
|
597
|
+
hit.characterId = who?.characterId ?? null;
|
|
598
|
+
hit.pointM ??= { x: 0, y: 0, z: 0 };
|
|
599
|
+
hit.normal ??= { x: 0, y: 0, z: 0 };
|
|
600
|
+
hit.pointM.x = pointX;
|
|
601
|
+
hit.pointM.y = pointY;
|
|
602
|
+
hit.pointM.z = pointZ;
|
|
603
|
+
hit.normal.x = normalX;
|
|
604
|
+
hit.normal.y = normalY;
|
|
605
|
+
hit.normal.z = normalZ;
|
|
606
|
+
hit.distanceM = distanceM;
|
|
607
|
+
return hit;
|
|
608
|
+
}
|
|
609
|
+
/** A shape moved along a direction: the first thing it meets, or null. Its own space is turned by rotation. */
|
|
610
|
+
function castShapeQuery(shape, rotation, { fromM, directionM, maximumDistanceM, collisionLayerNames = null, excludedId = null, isStoppedAtPenetration = true }, into) {
|
|
611
|
+
const lengthNumber = Math.hypot(directionM.x, directionM.y, directionM.z) || 1;
|
|
612
|
+
const direction = { x: directionM.x / lengthNumber, y: directionM.y / lengthNumber, z: directionM.z / lengthNumber };
|
|
613
|
+
const hit = rapierWorld.castShape(fromM, rotation, direction, shape, 0, maximumDistanceM, isStoppedAtPenetration, engine.QueryFilterFlags.EXCLUDE_SENSORS, queryGroupsOf(collisionLayerNames), undefined, excludedOf(excludedId) ?? undefined, queryPredicate);
|
|
614
|
+
if (!hit) return null;
|
|
615
|
+
const distanceM = hit.time_of_impact;
|
|
616
|
+
// The point and the normal are the hit collider's own (its surface there, facing out toward the shape): put into the world by its place and turn.
|
|
617
|
+
const colliderAtM = hit.collider.translation();
|
|
618
|
+
const colliderRotation = hit.collider.rotation();
|
|
619
|
+
const witness = turned(hit.witness1, colliderRotation);
|
|
620
|
+
const normal = turned(hit.normal1, colliderRotation);
|
|
621
|
+
return hitInto(into, hit.collider, colliderAtM.x + witness.x, colliderAtM.y + witness.y, colliderAtM.z + witness.z, normal.x, normal.y, normal.z, distanceM);
|
|
622
|
+
}
|
|
623
|
+
/** A capsule standing up (or turned by rotation), as the engine takes it: its height is the whole, round ends included. */
|
|
624
|
+
const capsuleOf = (radiusM, heightM) => new engine.Capsule(Math.max(heightM / 2 - radiusM, 0), radiusM);
|
|
625
|
+
|
|
626
|
+
// Over a level, where each character moves alone, the level's searches see the level: a character's place there is no one's to find.
|
|
627
|
+
const queryPredicate = isEachCharacterAlone ? (collider) => !ownerByColliderHandle.get(collider.handle)?.isCharacter : undefined;
|
|
628
|
+
const queries = {
|
|
629
|
+
/** The first thing a ray meets: { bodyId, characterId, pointM, normal, distanceM }, or null. With into, written there. */
|
|
630
|
+
castRay({ fromM, directionM, maximumDistanceM, collisionLayerNames = null, excludedId = null }, into = null) {
|
|
631
|
+
const lengthNumber = Math.hypot(directionM.x, directionM.y, directionM.z) || 1;
|
|
632
|
+
const direction = { x: directionM.x / lengthNumber, y: directionM.y / lengthNumber, z: directionM.z / lengthNumber };
|
|
633
|
+
const hit = rapierWorld.castRayAndGetNormal(new engine.Ray(fromM, direction), maximumDistanceM, true, engine.QueryFilterFlags.EXCLUDE_SENSORS, queryGroupsOf(collisionLayerNames), undefined, excludedOf(excludedId) ?? undefined, queryPredicate);
|
|
634
|
+
if (!hit) return null;
|
|
635
|
+
const distanceM = hit.timeOfImpact;
|
|
636
|
+
return hitInto(into, hit.collider, fromM.x + direction.x * distanceM, fromM.y + direction.y * distanceM, fromM.z + direction.z * distanceM, hit.normal.x, hit.normal.y, hit.normal.z, distanceM);
|
|
637
|
+
},
|
|
638
|
+
/** The first thing a ball meets moving along a direction: { bodyId, characterId, pointM, normal, distanceM }, or null. With into, written there. */
|
|
639
|
+
castBall(query, into = null) {
|
|
640
|
+
return castShapeQuery(new engine.Ball(query.radiusM), NO_TURN, query, into);
|
|
641
|
+
},
|
|
642
|
+
/** The first thing a capsule (standing up, or turned by rotation) meets moving along a direction, or null. With into, written there. */
|
|
643
|
+
castCapsule(query, into = null) {
|
|
644
|
+
return castShapeQuery(capsuleOf(query.radiusM, query.heightM), query.rotation ?? NO_TURN, query, into);
|
|
645
|
+
},
|
|
646
|
+
/**
|
|
647
|
+
* Where a capsule (standing up, or turned by rotation) touches the world: each contact's body or character, its
|
|
648
|
+
* point, the surface's normal there (pointing out of it, toward the capsule) and how deep the capsule is in it
|
|
649
|
+
* (depthM, above 0 when it overlaps). The way a game's own movement pushes out of walls and stands on slopes.
|
|
650
|
+
*/
|
|
651
|
+
overlapCapsule({ centerM, radiusM, heightM, rotation = NO_TURN, collisionLayerNames = null, excludedId = null, marginM = 0 }) {
|
|
652
|
+
const shape = capsuleOf(radiusM, heightM);
|
|
653
|
+
const contacts = [];
|
|
654
|
+
rapierWorld.intersectionsWithShape(centerM, rotation, marginM > 0 ? capsuleOf(radiusM + marginM, heightM + marginM * 2) : shape, (collider) => {
|
|
655
|
+
const contact = collider.contactShape(shape, centerM, rotation, marginM);
|
|
656
|
+
if (!contact) return true;
|
|
657
|
+
const who = whoOf(collider);
|
|
658
|
+
contacts.push({ bodyId: who?.bodyId ?? null, characterId: who?.characterId ?? null, pointM: { x: contact.point1.x, y: contact.point1.y, z: contact.point1.z }, normal: { x: contact.normal1.x, y: contact.normal1.y, z: contact.normal1.z }, depthM: -contact.distance });
|
|
659
|
+
return true;
|
|
660
|
+
}, engine.QueryFilterFlags.EXCLUDE_SENSORS, queryGroupsOf(collisionLayerNames), undefined, excludedOf(excludedId) ?? undefined, queryPredicate);
|
|
661
|
+
return contacts;
|
|
662
|
+
},
|
|
663
|
+
/** Everything a ball overlaps: [{ bodyId, characterId }]. */
|
|
664
|
+
overlapBall({ centerM, radiusM, collisionLayerNames = null, excludedId = null }) {
|
|
665
|
+
const found = [];
|
|
666
|
+
rapierWorld.intersectionsWithShape(centerM, NO_TURN, new engine.Ball(radiusM), (collider) => {
|
|
667
|
+
const who = whoOf(collider);
|
|
668
|
+
if (who && !found.some((each) => each.bodyId === who.bodyId && each.characterId === who.characterId)) found.push(who);
|
|
669
|
+
return true;
|
|
670
|
+
}, engine.QueryFilterFlags.EXCLUDE_SENSORS, queryGroupsOf(collisionLayerNames), undefined, excludedOf(excludedId) ?? undefined, queryPredicate);
|
|
671
|
+
return found;
|
|
672
|
+
},
|
|
673
|
+
};
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* Moves a kinematic character by as much of desiredM as the world lets it: sliding along walls, up steps and
|
|
677
|
+
* slopes it can climb, snapped down to the ground under it. Answers { movedM, isGrounded }.
|
|
678
|
+
*/
|
|
679
|
+
function moveAndSlide(character, desiredM) {
|
|
680
|
+
if (!controller) return { movedM: { x: 0, y: 0, z: 0 }, isGrounded: false };
|
|
681
|
+
// Characters that each move alone (each player predicts only their own) walk through each other: where another is stands differently in every game.
|
|
682
|
+
controller.computeColliderMovement(character.collider, desiredM, engine.QueryFilterFlags.EXCLUDE_SENSORS, groupsOf(character.layerIndex), isEachCharacterAlone ? (collider) => !ownerByColliderHandle.get(collider.handle)?.isCharacter : (collider) => collider.handle !== character.collider.handle);
|
|
683
|
+
const moved = controller.computedMovement();
|
|
684
|
+
const atM = character.rigidBody.translation();
|
|
685
|
+
character.rigidBody.setTranslation({ x: atM.x + moved.x, y: atM.y + moved.y, z: atM.z + moved.z }, true);
|
|
686
|
+
// Its collider goes with it at once: the next character's move (and its own next) sees where it is.
|
|
687
|
+
rapierWorld.propagateModifiedBodyPositionsToColliders();
|
|
688
|
+
return { movedM: { x: moved.x, y: moved.y, z: moved.z }, isGrounded: controller.computedGrounded() };
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/** What a character kind's step reaches: the world's queries, the move, the bodies and characters by id. */
|
|
692
|
+
const stepTools = {
|
|
693
|
+
engine,
|
|
694
|
+
rapierWorld,
|
|
695
|
+
world,
|
|
696
|
+
tickDurationSec,
|
|
697
|
+
get tuning() {
|
|
698
|
+
return currentTuning;
|
|
699
|
+
},
|
|
700
|
+
...queries,
|
|
701
|
+
moveAndSlide,
|
|
702
|
+
bodies,
|
|
703
|
+
characters,
|
|
704
|
+
bodyIndexById,
|
|
705
|
+
characterIndexById,
|
|
706
|
+
ownerOf: (collider) => ownerByColliderHandle.get(collider.handle) ?? null,
|
|
707
|
+
characterHalfSegmentM,
|
|
708
|
+
get stepCount() {
|
|
709
|
+
return stepCount;
|
|
710
|
+
},
|
|
711
|
+
/** The character kind's own memory for this world (what's held, what changed): its startKindState's answer. */
|
|
712
|
+
kindState: null,
|
|
713
|
+
/** A body as the world has it now, read only: { positionM, rotation, velocityMPerSec, spinRadPerSec, massKg, motionKind, collisionLayerName, isResting }, or null. */
|
|
714
|
+
bodyState(bodyId) {
|
|
715
|
+
const body = bodies[bodyIndexById.get(bodyId)];
|
|
716
|
+
if (!body) return null;
|
|
717
|
+
const fields = readBody(body.index);
|
|
718
|
+
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) };
|
|
719
|
+
},
|
|
720
|
+
/** A character as the world has it now, read only: { positionM (its feet), velocityMPerSec, facingYawRad, isGrounded, rideBodyId, collisionLayerName, own }, or null. */
|
|
721
|
+
characterState(characterId) {
|
|
722
|
+
const character = characters[characterIndexById.get(characterId)];
|
|
723
|
+
if (!character) return null;
|
|
724
|
+
const centerM = character.rigidBody.translation();
|
|
725
|
+
const velocity = isKinematicKind ? character.velocity : character.rigidBody.linvel();
|
|
726
|
+
return { positionM: { x: centerM.x, y: centerM.y - world.character.heightM / 2, z: centerM.z }, velocityMPerSec: { x: velocity.x, y: velocity.y, z: velocity.z }, facingYawRad: character.facingYawRad, isGrounded: character.isGrounded, rideBodyId: bodies[character.rideBodyIndex]?.declaration.id ?? null, collisionLayerName: world.collisionLayers[character.ownLayerIndex].name, own: character.own };
|
|
727
|
+
},
|
|
728
|
+
/**
|
|
729
|
+
* 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
|
|
730
|
+
* replay. Answers false for a joint that isn't here.
|
|
731
|
+
*/
|
|
732
|
+
setJoint(jointId, changes) {
|
|
733
|
+
if (!joints.has(jointId) || typeof changes?.isEnabled !== "boolean") return false;
|
|
734
|
+
setJointEnabled(joints.get(jointId), changes.isEnabled);
|
|
735
|
+
return true;
|
|
736
|
+
},
|
|
737
|
+
/** Puts a character on one of the world's collision layers from its step (walking through his own cart while he holds it). */
|
|
738
|
+
setLayer(character, collisionLayerName) {
|
|
739
|
+
const layerIndex = layerIndexByName.get(collisionLayerName);
|
|
740
|
+
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(", ")}.`);
|
|
741
|
+
character.ownLayerIndex = layerIndex;
|
|
742
|
+
if (character.rideBodyIndex < 0) setCharacterLayer(character, layerIndex);
|
|
743
|
+
},
|
|
744
|
+
};
|
|
745
|
+
stepTools.kindState = characterKind.startKindState?.(stepTools) ?? {};
|
|
746
|
+
|
|
747
|
+
// The kind's own fields that go on the wire: a step that changes any of them leaves its character awake, so they're sent.
|
|
748
|
+
const sharedOwnNames = characterKind.stateFields.filter((field) => field.isShared !== false && typeof field.name === "string").map((field) => field.name);
|
|
749
|
+
const sharedOwnOf = (character) => {
|
|
750
|
+
if (!sharedOwnNames.length) return null;
|
|
751
|
+
const own = characterKind.readOwn(character, stepTools) ?? {};
|
|
752
|
+
return sharedOwnNames.map((name) => (own[name] !== null && typeof own[name] === "object" ? JSON.stringify(own[name]) : own[name]));
|
|
753
|
+
};
|
|
754
|
+
const isSameOwn = (before, after) => before === null || after.every((fieldValue, fieldIndex) => fieldValue === before[fieldIndex]);
|
|
755
|
+
|
|
756
|
+
function stepCharacters(stepContext) {
|
|
757
|
+
for (const character of characters) {
|
|
758
|
+
if (!character || character.isWaiting) continue;
|
|
759
|
+
const input = stepContext.inputOf(character.id) ?? characterKind.idleInput;
|
|
760
|
+
const ownBefore = sharedOwnOf(character);
|
|
761
|
+
// A rider goes where its seat goes: its kind may keep its own fields going there (stamina back on a drive).
|
|
762
|
+
if (character.rideBodyIndex >= 0) characterKind.stepRiding?.(character, input, stepContext);
|
|
763
|
+
else {
|
|
764
|
+
const startM = isKinematicKind && world.substepCount > 1 && !characterKind.isSteppedBeforeWorld ? character.rigidBody.translation() : null;
|
|
765
|
+
characterKind.step(character, input, stepContext);
|
|
766
|
+
if (startM) noteKinematicMove(character, startM);
|
|
767
|
+
}
|
|
768
|
+
character.isOwnChanged = ownBefore !== null && !isSameOwn(ownBefore, sharedOwnOf(character));
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* A kinematic character is put where it goes at once, so the characters after it see it there; but the engine then
|
|
774
|
+
* sees it standing still, and what it pushes or pulls on a joint is shoved, not carried. So it goes back to where
|
|
775
|
+
* the step's first substep would have it, and moves the rest of the way through the substeps left, at its speed.
|
|
776
|
+
*/
|
|
777
|
+
const movedCharacters = [];
|
|
778
|
+
function noteKinematicMove(character, startM) {
|
|
779
|
+
const endM = character.rigidBody.translation();
|
|
780
|
+
if (startM.x === endM.x && startM.y === endM.y && startM.z === endM.z) return;
|
|
781
|
+
character.moveStartM = { x: startM.x, y: startM.y, z: startM.z };
|
|
782
|
+
character.moveEndM = { x: endM.x, y: endM.y, z: endM.z };
|
|
783
|
+
movedCharacters.push(character);
|
|
784
|
+
}
|
|
785
|
+
function placeMovedCharacters(substepIndex) {
|
|
786
|
+
if (!movedCharacters.length) return;
|
|
787
|
+
const isFirst = substepIndex === 1;
|
|
788
|
+
for (const character of movedCharacters) {
|
|
789
|
+
const { moveStartM: startM, moveEndM: endM } = character;
|
|
790
|
+
const along = (fractionNumber) => ({ x: startM.x + (endM.x - startM.x) * fractionNumber, y: startM.y + (endM.y - startM.y) * fractionNumber, z: startM.z + (endM.z - startM.z) * fractionNumber });
|
|
791
|
+
if (isFirst) character.rigidBody.setTranslation(along(substepIndex / world.substepCount), false);
|
|
792
|
+
character.rigidBody.setNextKinematicTranslation(along((substepIndex + 1) / world.substepCount));
|
|
793
|
+
}
|
|
794
|
+
if (isFirst) rapierWorld.propagateModifiedBodyPositionsToColliders();
|
|
795
|
+
if (substepIndex === world.substepCount - 1) movedCharacters.length = 0;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* One step of one character on its own, against the world as it stands (nothing else moves): for characters each
|
|
800
|
+
* player predicts alone over a level, a shooter's soldiers. The world's own count moves on once a step.
|
|
801
|
+
*/
|
|
802
|
+
let lastAloneTickIndex = -Infinity;
|
|
803
|
+
/**
|
|
804
|
+
* Where nothing is stepped (characters over a level), the engine's searches see a change to what's there (ground
|
|
805
|
+
* laid, a group switched) only after a step: one of no time at all, run when something changed.
|
|
806
|
+
*/
|
|
807
|
+
let isSceneOwed = true;
|
|
808
|
+
function refreshScene() {
|
|
809
|
+
if (!isSceneOwed) return;
|
|
810
|
+
isSceneOwed = false;
|
|
811
|
+
const savedTimestep = rapierWorld.timestep;
|
|
812
|
+
rapierWorld.timestep = 0;
|
|
813
|
+
rapierWorld.step(eventQueue);
|
|
814
|
+
rapierWorld.timestep = savedTimestep;
|
|
815
|
+
eventQueue.clear();
|
|
816
|
+
}
|
|
817
|
+
function stepCharacterAlone(index, input, stepContext) {
|
|
818
|
+
const character = characters[index];
|
|
819
|
+
if (!character) return;
|
|
820
|
+
if (stepContext.tickIndex > lastAloneTickIndex) {
|
|
821
|
+
lastAloneTickIndex = stepContext.tickIndex;
|
|
822
|
+
stepCount += 1;
|
|
823
|
+
pruneGround();
|
|
824
|
+
}
|
|
825
|
+
propagateIfOwed();
|
|
826
|
+
if (grounds.length) keepGroundAround(character.rigidBody.translation(), world.groundReachM, stepCount + GROUND_KEPT_STEP_COUNT);
|
|
827
|
+
refreshScene();
|
|
828
|
+
characterKind.step(character, input, stepContext);
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/** Notes, for every moving body a character is touching now, that it did: what a character pushes is drawn with it. */
|
|
832
|
+
function noteTouches() {
|
|
833
|
+
for (const character of characters) {
|
|
834
|
+
if (!character || character.isWaiting) continue;
|
|
835
|
+
rapierWorld.contactPairsWith(character.collider, (otherCollider) => {
|
|
836
|
+
const owner = ownerByColliderHandle.get(otherCollider.handle);
|
|
837
|
+
if (!owner || owner.isCharacter || bodies[owner.index]?.motionIndex !== 0) return;
|
|
838
|
+
let isTouching = false;
|
|
839
|
+
rapierWorld.contactPair(character.collider, otherCollider, (manifold) => {
|
|
840
|
+
if (manifold.numContacts() > 0) isTouching = true;
|
|
841
|
+
});
|
|
842
|
+
if (isTouching) (bodies[owner.index].touchStepCountByCharacterIndex ??= new Map()).set(character.index, stepCount);
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
function noteHits() {
|
|
848
|
+
eventQueue.drainCollisionEvents((firstHandle, secondHandle, isStarted) => {
|
|
849
|
+
if (!isStarted) return;
|
|
850
|
+
const first = ownerByColliderHandle.get(firstHandle);
|
|
851
|
+
const second = ownerByColliderHandle.get(secondHandle);
|
|
852
|
+
if (!first || !second) return;
|
|
853
|
+
for (const [own, other] of [[first, second], [second, first]]) {
|
|
854
|
+
if (own.isCharacter || bodies[own.index]?.motionIndex !== 0) continue;
|
|
855
|
+
const before = bodies[own.index].velocityBefore;
|
|
856
|
+
const otherBefore = other.isCharacter ? (characters[other.index]?.rigidBody.linvel() ?? { x: 0, y: 0, z: 0 }) : bodies[other.index]?.motionIndex === 0 ? bodies[other.index].velocityBefore : { x: 0, y: 0, z: 0 };
|
|
857
|
+
const hitSpeedMPerSec = Math.hypot(before.x - otherBefore.x, before.y - otherBefore.y, before.z - otherBefore.z);
|
|
858
|
+
if (hitSpeedMPerSec >= MINIMUM_TOLD_HIT_SPEED_M_PER_SEC) hits.push({ bodyIndex: own.index, otherBodyIndex: other.isCharacter ? -1 : other.index, otherCharacterIndex: other.isCharacter ? other.index : -1, speedMPerSec: hitSpeedMPerSec });
|
|
859
|
+
}
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* One fixed step: ground laid under what moves; vehicles take their drivers' controls; the engine steps the
|
|
865
|
+
* world's substeps, the character kind stepping its characters after the first (or before it, if it asks); riders
|
|
866
|
+
* go where their seats went. stepContext: { tickIndex, isReplay, isInCharge, inputOf(id), emit }.
|
|
867
|
+
*/
|
|
868
|
+
function step(stepContext) {
|
|
869
|
+
const worldStepContext = { ...stepTools, ...stepContext };
|
|
870
|
+
// What was written since the last step (the word, a teleport) moves its colliders before anything searches them.
|
|
871
|
+
propagateIfOwed();
|
|
872
|
+
layGround();
|
|
873
|
+
characterKind.beforeWorldStep?.(worldStepContext);
|
|
874
|
+
if (characterKind.isSteppedBeforeWorld) stepCharacters(worldStepContext);
|
|
875
|
+
driveVehicles(worldStepContext);
|
|
876
|
+
for (let substepIndex = 0; substepIndex < world.substepCount; substepIndex += 1) {
|
|
877
|
+
if (substepIndex > 0 && !characterKind.isSteppedBeforeWorld) placeMovedCharacters(substepIndex);
|
|
878
|
+
rapierWorld.forEachActiveRigidBody((rigidBody) => {
|
|
879
|
+
const bodyIndex = movingBodyByHandle.get(rigidBody.handle);
|
|
880
|
+
if (bodyIndex === undefined) return;
|
|
881
|
+
const velocity = rigidBody.linvel();
|
|
882
|
+
const before = bodies[bodyIndex].velocityBefore;
|
|
883
|
+
before.x = velocity.x;
|
|
884
|
+
before.y = velocity.y;
|
|
885
|
+
before.z = velocity.z;
|
|
886
|
+
// A small quick thing looks ahead as far as it goes in a substep, and a little more: the engine's own
|
|
887
|
+
// continuous collision misses heightfield ground, so a 7 cm apple at 4 m/s would fall through it.
|
|
888
|
+
if (bodies[bodyIndex].isSmall) rigidBody.setSoftCcdPrediction(Math.min(Math.hypot(velocity.x, velocity.y, velocity.z) * substepDurationSec * SMALL_BODY_LOOK_AHEAD_NUMBER + SMALL_BODY_LOOK_AHEAD_MARGIN_M, MAXIMUM_LOOK_AHEAD_M));
|
|
889
|
+
});
|
|
890
|
+
updateVehicles();
|
|
891
|
+
rapierWorld.step(eventQueue);
|
|
892
|
+
noteHits();
|
|
893
|
+
if (substepIndex === 0 && !characterKind.isSteppedBeforeWorld) stepCharacters(worldStepContext);
|
|
894
|
+
}
|
|
895
|
+
stepCount += 1;
|
|
896
|
+
for (const character of characters) if (character && !character.isWaiting && character.rideBodyIndex >= 0) placeRider(character);
|
|
897
|
+
if (tracksTouches) noteTouches();
|
|
898
|
+
characterKind.afterWorldStep?.(worldStepContext);
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// ---- What's shared: each thing's fields, read after a step and written when the word differs ----
|
|
902
|
+
|
|
903
|
+
/** A body's fields: its place, rotation, speed and spin, its layer and how it moves now. */
|
|
904
|
+
function readBody(index) {
|
|
905
|
+
const body = bodies[index];
|
|
906
|
+
const { rigidBody } = body;
|
|
907
|
+
const position = rigidBody.translation();
|
|
908
|
+
const rotation = rigidBody.rotation();
|
|
909
|
+
const velocity = rigidBody.linvel();
|
|
910
|
+
const spin = rigidBody.angvel();
|
|
911
|
+
return {
|
|
912
|
+
x: position.x,
|
|
913
|
+
y: position.y,
|
|
914
|
+
z: position.z,
|
|
915
|
+
rotation: { x: rotation.x, y: rotation.y, z: rotation.z, w: rotation.w },
|
|
916
|
+
velocityX: velocity.x,
|
|
917
|
+
velocityY: velocity.y,
|
|
918
|
+
velocityZ: velocity.z,
|
|
919
|
+
spinX: spin.x,
|
|
920
|
+
spinY: spin.y,
|
|
921
|
+
spinZ: spin.z,
|
|
922
|
+
layerNumber: body.layerIndex,
|
|
923
|
+
motionNumber: body.motionIndex,
|
|
924
|
+
steerNumber: body.vehicle ? body.vehicle.steerNumber : 0,
|
|
925
|
+
massKg: body.massKg ?? 0,
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
/** Puts a body where readBody's fields say, moving so; at rest when isResting. Its colliders go with it at once. */
|
|
930
|
+
function writeBody(index, fields, isResting = false) {
|
|
931
|
+
const body = bodies[index];
|
|
932
|
+
if (!body || body.declaredMotionIndex === 2) return;
|
|
933
|
+
if (fields.layerNumber !== undefined && fields.layerNumber < world.collisionLayers.length) setBodyLayer(body, fields.layerNumber);
|
|
934
|
+
if (fields.motionNumber !== undefined && fields.motionNumber >= 0 && fields.motionNumber <= 2) setBodyMotion(body, fields.motionNumber);
|
|
935
|
+
// Only a real change: the wire's grain (a hundredth of a kilogram) on a declared mass is the same body.
|
|
936
|
+
if (fields.massKg > 0 && body.massKg && Math.abs(fields.massKg - body.massKg) > 0.006) setBodyMass(body, fields.massKg);
|
|
937
|
+
const { rigidBody } = body;
|
|
938
|
+
rigidBody.setTranslation({ x: fields.x, y: fields.y, z: fields.z }, false);
|
|
939
|
+
rigidBody.setRotation(fields.rotation, false);
|
|
940
|
+
if (body.vehicle && fields.steerNumber !== undefined) body.vehicle.steerNumber = fields.steerNumber;
|
|
941
|
+
isPropagationOwed = true;
|
|
942
|
+
if (body.motionIndex === 2) return;
|
|
943
|
+
if (isResting && body.motionIndex === 0) {
|
|
944
|
+
rigidBody.setLinvel({ x: 0, y: 0, z: 0 }, false);
|
|
945
|
+
rigidBody.setAngvel({ x: 0, y: 0, z: 0 }, false);
|
|
946
|
+
rigidBody.sleep();
|
|
947
|
+
} else {
|
|
948
|
+
// Written every step (the wire's numbers), so it mustn't wake what's settling down: only what's asleep and moving now.
|
|
949
|
+
const isMovingNow = fields.velocityX !== 0 || fields.velocityY !== 0 || fields.velocityZ !== 0 || fields.spinX !== 0 || fields.spinY !== 0 || fields.spinZ !== 0;
|
|
950
|
+
const isWoken = rigidBody.isSleeping() && isMovingNow;
|
|
951
|
+
rigidBody.setLinvel({ x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ }, isWoken);
|
|
952
|
+
rigidBody.setAngvel({ x: fields.spinX, y: fields.spinY, z: fields.spinZ }, isWoken);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/** A character's fields: the piece's own (its place, speed, facing, footing, seat and layer) and its kind's. */
|
|
957
|
+
function readCharacter(index) {
|
|
958
|
+
const character = characters[index];
|
|
959
|
+
const position = character.rigidBody.translation();
|
|
960
|
+
const velocity = isKinematicKind ? character.velocity : character.rigidBody.linvel();
|
|
961
|
+
return {
|
|
962
|
+
x: position.x,
|
|
963
|
+
y: position.y,
|
|
964
|
+
z: position.z,
|
|
965
|
+
velocityX: velocity.x,
|
|
966
|
+
velocityY: velocity.y,
|
|
967
|
+
velocityZ: velocity.z,
|
|
968
|
+
facingYawRad: character.facingYawRad,
|
|
969
|
+
isGrounded: character.isGrounded,
|
|
970
|
+
airTickCount: character.airTickCount,
|
|
971
|
+
rideBodyNumber: character.rideBodyIndex + 1,
|
|
972
|
+
seatIndex: character.seatIndex,
|
|
973
|
+
layerNumber: character.ownLayerIndex,
|
|
974
|
+
...characterKind.readOwn(character, stepTools),
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
/** Puts a character where readCharacter's fields say; at rest when isResting. */
|
|
979
|
+
function writeCharacter(index, fields, isResting = false) {
|
|
980
|
+
const character = characters[index];
|
|
981
|
+
if (!character) return;
|
|
982
|
+
const { rigidBody } = character;
|
|
983
|
+
if (character.isWaiting) {
|
|
984
|
+
character.isWaiting = false;
|
|
985
|
+
rigidBody.setEnabled(true);
|
|
986
|
+
}
|
|
987
|
+
if (fields.layerNumber !== undefined && fields.layerNumber < world.collisionLayers.length && fields.layerNumber !== ridingLayerIndex) character.ownLayerIndex = fields.layerNumber;
|
|
988
|
+
rigidBody.setTranslation({ x: fields.x, y: fields.y, z: fields.z }, false);
|
|
989
|
+
isPropagationOwed = true;
|
|
990
|
+
character.facingYawRad = fields.facingYawRad;
|
|
991
|
+
character.isGrounded = fields.isGrounded;
|
|
992
|
+
character.airTickCount = fields.airTickCount;
|
|
993
|
+
const rideBodyIndex = (fields.rideBodyNumber ?? 0) - 1;
|
|
994
|
+
if (rideBodyIndex >= 0 && bodies[rideBodyIndex]) {
|
|
995
|
+
character.rideBodyIndex = rideBodyIndex;
|
|
996
|
+
character.seatIndex = fields.seatIndex ?? 0;
|
|
997
|
+
setCharacterLayer(character, ridingLayerIndex);
|
|
998
|
+
if (!isKinematicKind) rigidBody.setGravityScale(0, false);
|
|
999
|
+
} else {
|
|
1000
|
+
unseat(character);
|
|
1001
|
+
setCharacterLayer(character, character.ownLayerIndex);
|
|
1002
|
+
}
|
|
1003
|
+
characterKind.writeOwn(character, fields, stepTools);
|
|
1004
|
+
if (isKinematicKind) character.velocity = isResting ? { x: 0, y: 0, z: 0 } : { x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ };
|
|
1005
|
+
else if (isResting && characterKind.canRest?.(character, stepTools) !== false) {
|
|
1006
|
+
rigidBody.setLinvel({ x: 0, y: 0, z: 0 }, false);
|
|
1007
|
+
rigidBody.sleep();
|
|
1008
|
+
} else {
|
|
1009
|
+
const isMovingNow = fields.velocityX !== 0 || fields.velocityY !== 0 || fields.velocityZ !== 0;
|
|
1010
|
+
rigidBody.setLinvel({ x: fields.velocityX, y: fields.velocityY, z: fields.velocityZ }, rigidBody.isSleeping() && isMovingNow);
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
/** Takes other numbers for the world (a setting changed): gravity, how surfaces hold and bounce, how motion dies away. */
|
|
1015
|
+
function setTuning(nextTuning) {
|
|
1016
|
+
currentTuning = nextTuning;
|
|
1017
|
+
rapierWorld.gravity = { x: 0, y: -nextTuning.gravityMPerSecPerSec, z: 0 };
|
|
1018
|
+
for (const body of bodies) {
|
|
1019
|
+
if (!body) continue;
|
|
1020
|
+
for (const collider of body.colliders) {
|
|
1021
|
+
collider.setFriction(gripNumberOf(body.declaration));
|
|
1022
|
+
collider.setRestitution(bounceNumberOf(body.declaration));
|
|
1023
|
+
}
|
|
1024
|
+
if (body.motionIndex !== 0) continue;
|
|
1025
|
+
body.rigidBody.setLinearDamping(body.declaration.linearDampingNumber ?? nextTuning.linearDampingNumber);
|
|
1026
|
+
body.rigidBody.setAngularDamping(body.declaration.angularDampingNumber ?? nextTuning.angularDampingNumber);
|
|
1027
|
+
body.rigidBody.wakeUp();
|
|
1028
|
+
}
|
|
1029
|
+
controller?.setCharacterMass(nextTuning.characterMassKg ?? 70);
|
|
1030
|
+
characterKind.onTuning?.(nextTuning, stepTools);
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
for (const declaration of world.bodies) addBody(declaration);
|
|
1034
|
+
for (const declaration of world.joints) addJoint(declaration);
|
|
1035
|
+
// Fixed bodies never move, and moving ones start where they're declared: a step settles what the engine knows of them.
|
|
1036
|
+
const savedTimestep = rapierWorld.timestep;
|
|
1037
|
+
rapierWorld.timestep = 0;
|
|
1038
|
+
rapierWorld.step(eventQueue);
|
|
1039
|
+
rapierWorld.timestep = savedTimestep;
|
|
1040
|
+
eventQueue.clear();
|
|
1041
|
+
|
|
1042
|
+
const simulation = {
|
|
1043
|
+
world,
|
|
1044
|
+
bodies,
|
|
1045
|
+
characters,
|
|
1046
|
+
joints,
|
|
1047
|
+
bodyIndexById,
|
|
1048
|
+
characterIndexById,
|
|
1049
|
+
get tuning() {
|
|
1050
|
+
return currentTuning;
|
|
1051
|
+
},
|
|
1052
|
+
tickDurationSec,
|
|
1053
|
+
stepTools,
|
|
1054
|
+
addBody,
|
|
1055
|
+
removeBody,
|
|
1056
|
+
addCharacter,
|
|
1057
|
+
removeCharacter,
|
|
1058
|
+
addJoint,
|
|
1059
|
+
removeJoint,
|
|
1060
|
+
/** Whether a joint holds now. */
|
|
1061
|
+
isJointEnabled: (jointId) => Boolean(joints.get(jointId)?.isEnabled),
|
|
1062
|
+
setJointEnabled(jointId, isEnabled) {
|
|
1063
|
+
const joint = joints.get(jointId);
|
|
1064
|
+
if (joint) setJointEnabled(joint, isEnabled);
|
|
1065
|
+
},
|
|
1066
|
+
seat,
|
|
1067
|
+
unseat,
|
|
1068
|
+
step,
|
|
1069
|
+
stepCharacterAlone,
|
|
1070
|
+
refreshScene,
|
|
1071
|
+
readBody,
|
|
1072
|
+
writeBody,
|
|
1073
|
+
readCharacter,
|
|
1074
|
+
writeCharacter,
|
|
1075
|
+
setTuning,
|
|
1076
|
+
...queries,
|
|
1077
|
+
/** Lays the ground near a place for the next step, though nothing moves there: a camera looking past, a query far off. */
|
|
1078
|
+
keepGroundNear(point) {
|
|
1079
|
+
keptPoints.push({ x: point.x, y: point.y, z: point.z });
|
|
1080
|
+
keepGroundAround(point, world.groundReachM, stepCount + GROUND_KEPT_STEP_COUNT);
|
|
1081
|
+
},
|
|
1082
|
+
/** A vehicle's wheels as they hang now: [{ suspensionM, spinRad, steerRad, isOnGround }], each how far its spring reaches, how far round it's turned, its steering, and whether it touches anything. Empty for a body without wheels. */
|
|
1083
|
+
wheelStates(bodyId) {
|
|
1084
|
+
const body = bodies[bodyIndexById.get(bodyId)];
|
|
1085
|
+
if (!body?.vehicle) return [];
|
|
1086
|
+
const { controller } = body.vehicle;
|
|
1087
|
+
return body.declaration.wheels.map((wheel, wheelIndex) => ({ suspensionM: controller.wheelSuspensionLength(wheelIndex) ?? wheel.suspensionRestM, spinRad: controller.wheelRotation(wheelIndex) ?? 0, steerRad: controller.wheelSteering(wheelIndex) ?? 0, isOnGround: Boolean(controller.wheelIsInContact(wheelIndex)) }));
|
|
1088
|
+
},
|
|
1089
|
+
setOffTriangleGroups,
|
|
1090
|
+
/** Which triangle groups are off now: a bit for each, group 1 the lowest. */
|
|
1091
|
+
offTriangleGroupMaskNumber: () => offTriangleGroupMaskNumber,
|
|
1092
|
+
/** How many tiles of ground are laid now. */
|
|
1093
|
+
laidGroundTileCount: () => grounds.reduce((total, ground) => total + ground.tiles.size, 0),
|
|
1094
|
+
/** Whether a body is at rest: asleep, so nothing about it changes until something touches it. A fixed one always is. */
|
|
1095
|
+
isBodyResting: (index) => bodies[index].motionIndex === 2 || (bodies[index].motionIndex === 0 && bodies[index].rigidBody.isSleeping()),
|
|
1096
|
+
isCharacterResting(index) {
|
|
1097
|
+
const character = characters[index];
|
|
1098
|
+
// A step that changed the kind's own fields (taking a cart's handles, breath coming back) wakes it, so they're sent.
|
|
1099
|
+
if (character.isOwnChanged) return false;
|
|
1100
|
+
// A rider rests with its vehicle.
|
|
1101
|
+
if (character.rideBodyIndex >= 0) return bodies[character.rideBodyIndex]?.rigidBody.isSleeping() ?? true;
|
|
1102
|
+
if (isKinematicKind) return character.isGrounded && character.velocity.x === 0 && character.velocity.y === 0 && character.velocity.z === 0 && characterKind.isResting?.(character, stepTools) !== false;
|
|
1103
|
+
return character.rigidBody.isSleeping();
|
|
1104
|
+
},
|
|
1105
|
+
/** The characters that touched a body in its last quarter second of steps, oldest first; empty where touches aren't kept. */
|
|
1106
|
+
touchingCharacterIndexes(index) {
|
|
1107
|
+
const touches = bodies[index]?.touchStepCountByCharacterIndex;
|
|
1108
|
+
if (!touches) return [];
|
|
1109
|
+
const touching = [];
|
|
1110
|
+
for (const [characterIndex, touchStepCount] of touches) {
|
|
1111
|
+
if (stepCount - touchStepCount > TOUCH_MEMORY_STEP_COUNT || !characters[characterIndex]) touches.delete(characterIndex);
|
|
1112
|
+
else touching.push(characterIndex);
|
|
1113
|
+
}
|
|
1114
|
+
return touching;
|
|
1115
|
+
},
|
|
1116
|
+
/** Calls a function with the index of every moving body that isn't at rest. */
|
|
1117
|
+
forEachAwakeBody(listener) {
|
|
1118
|
+
rapierWorld.forEachActiveRigidBody((rigidBody) => {
|
|
1119
|
+
const bodyIndex = movingBodyByHandle.get(rigidBody.handle);
|
|
1120
|
+
if (bodyIndex !== undefined) listener(bodyIndex);
|
|
1121
|
+
});
|
|
1122
|
+
},
|
|
1123
|
+
/** Hits since the last call. */
|
|
1124
|
+
takeHits() {
|
|
1125
|
+
const taken = hits;
|
|
1126
|
+
hits = [];
|
|
1127
|
+
return taken;
|
|
1128
|
+
},
|
|
1129
|
+
/** Frees the engine's memory: the simulation is over. */
|
|
1130
|
+
dispose() {
|
|
1131
|
+
eventQueue.free();
|
|
1132
|
+
rapierWorld.free();
|
|
1133
|
+
},
|
|
1134
|
+
};
|
|
1135
|
+
return simulation;
|
|
1136
|
+
}
|