@zaisma/physics 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,7 +43,7 @@ export const valley = definePhysicsWorld({
43
43
  - **Collision layers:** named, each saying what it touches, and changed while playing (`setBody`, `setCharacter`): how a ghost passes walls, or a thing goes out of play.
44
44
  - **Queries:** `castRay`, `castBall`, `castCapsule`, `overlapBall` and `overlapCapsule`, answering whose body or character, where, the surface's normal, which of a mesh's triangles (`triangleIndex`) and its surface (`surfaceName`); a capsule's contacts say how deep it is in each, to push a game's own movement out of walls, one a body or, with `isEachTriangle`, one for every triangle it touches. A cast writes into an object the game keeps when given one (`castRay(query, hit)`), and so do `overlapCapsule(query, contacts)` and a step's `moveAndSlide(character, movedM, moved)`, so thousands a second make nothing new.
45
45
  - **Surfaces:** a world names its surfaces (`surfaceNames: ["grass", "metal_grate", "glass"]`), a shape says which it is (`surfaceName`) or a mesh says triangle by triangle (`triangleSurfaceIndices`), and every hit and contact answers the name: footsteps, bullet marks, tyre grip. `castBall` and `castCapsule` with `isStoppedAtPenetration: false` move out of what they start touching (a camera pressed to a wall).
46
- - **A level's collision as it ships:** a mesh takes a `Float32Array` of points and a `Uint32Array` of indices as they are, up to 2,000,000 triangles, and `triangleGroupNumbers` puts triangles in up to 63 groups the world switches on and off (`setTriangleGroup`: a door that opens, a bridge that falls). A group may sit on a collision layer of its own (`triangleGroups: [{ groupNumber: 4, collisionLayerName: "glass" }]`: glass that stops soldiers and lets shots through). The engine holds a mesh once however many worlds are made from it: every room a game server copy runs, a menu's world and the match's.
46
+ - **A level's collision as it ships:** a mesh takes a `Float32Array` of points and a `Uint32Array` of indices as they are, up to 2,000,000 triangles (built in tiles past 65,536, so opening one needs little more memory than the 94 bytes a triangle it ends up holding), and `triangleGroupNumbers` puts triangles in up to 63 groups the world switches on and off (`setTriangleGroup`: a door that opens, a bridge that falls). A group may sit on a collision layer of its own (`triangleGroups: [{ groupNumber: 4, collisionLayerName: "glass" }]`: glass that stops soldiers and lets shots through). The engine holds a mesh once however many worlds are made from it: every room a game server copy runs, a menu's world and the match's.
47
47
  - **The engine itself:** `physicsEngine()` answers Rapier as the piece ships it; `rapier/rapier.d.ts` types all of it (what a game uses most closely, the rest loosely). A body a game makes straight in the engine (`stepContext.rapierWorld`) isn't the piece's: it's never sent, nor put back on a replay, so online it differs in every game. Declare it (or add it with `addBody`), or hold it to a character with a joint (`otherBodyId`), and it's shared like any other; keep the engine's own for what's only drawn.
48
48
 
49
49
  ## Characters
@@ -74,6 +74,10 @@ export const soldiers = defineCharacterKind({
74
74
 
75
75
  Its fields ride the wire with the character's own, so a replay runs it exactly; a field with `isShared: false` is each game's own memory instead (sprinting, stopped at deep water), worked out by each step and never sent. `stepContext` has `moveAndSlide`, the queries, `bodyState` and `characterState` to read what's around, `setJoint` to take or let go a cart's handles and `setLayer` to walk through it while held (both run again exactly on a replay), `emit`, `isInCharge`, `isReplay` and the engine. `stepRiding` keeps a seated character's own fields going. A character rests (and isn't sent) only on a step that changed none of its own fields, a rider with its vehicle parked. `vehicleControls(input, vehicle, stepContext)` reads the vehicle as `bodyState` does, with its `bodyId`. `canPushBodies: false` walks into a parked cart without shoving it. A kinematic character moves through the engine's substeps at its speed, so what it pulls on a joint is carried at that speed and what it walks into is pushed, not shoved. A kind can also step bodies before and after the world (`beforeWorldStep`, `afterWorldStep`), drive vehicles its way, and add calls, settings and hooks of its own: that's how `@zaisma/physics-party` is built. Every hook is in `index.d.ts`, and a game's shared declarations import `world.js` (typed by `world.d.ts`).
76
76
 
77
+ **Sizes.** The world's `character` is the size every character starts as, and `characterSizes` names the others: `[{ name: "crouched", heightM: 1 }, { name: "giant", heightM: 4, radiusM: 0.8, stepHeightM: 0.8 }]`. A step takes one with `stepContext.setSize(character, "crouched")` (`null` for the world's own) and is answered `false` where it has no room, so a soldier who lets go of crouch under a low roof stays crouched until he's out. `addCharacter(id, { characterSizeName })` adds one at its size and `setCharacter(id, { characterSizeName })` sets it at once. The feet stay where they are, every side runs it the same, and `characterState` and `drawnCharacter` say `characterSizeName`. Since 2.6.0 every character has a `sizeNumber` field of its own, so a kind's own field takes another name.
78
+
79
+ **Standing still costs nothing.** A walker with nothing asked of it, standing on what never moves, skips its move, so a crowd costs what its moving part costs. A kind of the game's own does the same by returning early when `stepContext.isRestingOnLevel(character)` is true and it has nothing to do.
80
+
77
81
  ## Characters over a level
78
82
 
79
83
  A shooter's soldiers each move on their own: only their own player predicts them, everyone else draws them a moment behind, and a hit is judged by what the shooter saw. `levelCharactersKind` is that, over a world's level (its fixed and kinematic bodies), with a game's own character kind for the rules:
@@ -147,27 +151,57 @@ Opened like every piece's ([`@zaisma/piece`](../piece)), and changed while playi
147
151
 
148
152
  Online, whoever runs the world decides them. Hooks: `beforePutBack` (where something that fell out of the world comes back) and `bodyHit` (for a thud or dust). A character kind adds its own (`characterSettings`, `characterHooks`).
149
153
 
154
+ ## Limits
155
+
156
+ What one world holds, each with what it costs at the limit (measured as below):
157
+
158
+ | What | At most | At the limit |
159
+ | --- | --- | --- |
160
+ | Bodies that move or may (moving, kinematic, and every one added while playing) | 2,000 | all at rest: 0.25 ms a step |
161
+ | Fixed bodies: a level's pieces, never sent, never counted with the others | 20,000 | 62 MB, opens in 0.14 s, 0.13 ms a step with 500 crates at rest on them |
162
+ | Characters, players' and the game's own, each its own size | 250 | all walking: 3.7 ms a step; all standing: 0.35 ms |
163
+ | Joints | 1,000 | |
164
+ | Triangles in one mesh from typed arrays or a data file | 2,000,000 | 190 MB, opens in 0.55 s, a ray 1.75 µs |
165
+
166
+ A world declares at most 2,048 bodies that aren't fixed and joints together (what the online core takes from the start); the rest are added while playing. Costs follow what moves: a body asleep, a character standing still and a level's pieces take almost nothing from a step. A game server copy holds 128 MB in all, so a world with a game server stays under about a million mesh triangles, or 20,000 pieces with a smaller mesh.
167
+
150
168
  ## Measured
151
169
 
152
- What the piece costs, measured on a MacBook (Apple M5, 10 cores) with other work running, on version 2.5.0 (December 4, 2026). `node --expose-gc scripts/physics-bench.mjs` in Zaisma's repository measures it again.
170
+ What the piece costs, measured on a MacBook (Apple M5, 10 cores) with other work running, on version 2.6.0 (December 4, 2026). `node --expose-gc scripts/physics-bench.mjs` in Zaisma's repository measures it again.
153
171
 
154
172
  | What | Measured |
155
173
  | --- | --- |
156
- | A step of 999 crates falling, 2 substeps | 6.1 ms; the engine alone takes 5.8 (1.04 times); through a game server's room 8.0 |
157
- | The same 999 at rest | 0.14 ms |
158
- | Garbage a step leaves, 999 crates | 5 to 10 KB (2.4.1 left 7.5 MB) |
159
- | 999 things spread over a 1 km heightfield, falling | 6.4 ms a step, worst 10.5; at rest 0.2 ms |
160
- | 64 characters walking | 0.9 ms a step |
161
- | 8 players and 300 crates kept moving, to one player | 9.7 KB a second down, 0.6 up |
174
+ | A step of 999 crates falling, 2 substeps | 6.1 ms; the engine alone takes 5.7 (1.04 times); through a game server's room 7.4 |
175
+ | The same 999 at rest | 0.07 ms |
176
+ | Garbage a step leaves, 999 crates | 5 to 9 KB (2.4.1 left 7.5 MB) |
177
+ | 999 things spread over a 1 km heightfield, falling | 5.6 ms a step, worst 9.2; at rest 0.1 ms |
178
+ | 500 crates on a level of 1,000 fixed pieces | opens in 29 ms; 1.7 ms a step falling, 0.05 at rest |
179
+ | The same on 20,000 fixed pieces | opens in 136 ms; 2.9 ms a step falling, 0.13 at rest; 3.1 KB a piece |
180
+ | 64 characters walking | 0.7 ms a step |
181
+ | 250 characters walking | 3.7 ms a step; standing still, 0.35 |
182
+ | A mesh of 500,000 triangles, built in tiles | 52 MB; 94 bytes a triangle |
183
+ | 8 players and 300 crates kept moving, to one player | 9.6 KB a second down, 0.6 up |
162
184
 
163
185
  A shooter's real levels, beside that shooter's own collision code written for nothing else (Shieldbreak: the same 20,000 rays and capsules through both):
164
186
 
165
187
  | Level | Triangles | Memory | Opens in | A second room | A ray | A capsule's contacts |
166
188
  | --- | --- | --- | --- | --- | --- | --- |
167
- | Cascade | 72,442 | 6.5 MB (its own: 5.7) | 37 ms (35) | 0.04 MB, 5 ms | 1.1 µs (1.3) | 2.1 µs (2.3) |
168
- | Liftoff | 48,696 | 4.4 MB (1.6) | 22 ms (22) | 0.04 MB, 3 ms | 1.2 µs (1.4) | 1.9 µs (1.9) |
169
- | Caldera | 99,087 | 9.0 MB (7.9) | 45 ms (43) | 0.04 MB, 6 ms | 1.4 µs (1.3) | 1.8 µs (2.0) |
189
+ | Cascade | 72,442 | 6.5 MB (its own: 5.7) | 27 ms (24) | 0.04 MB, 3 ms | 0.66 µs (0.64) | 1.3 µs (1.3) |
190
+ | Liftoff | 48,696 | 4.4 MB (1.0) | 12 ms (10) | 0.04 MB, 2 ms | 0.72 µs (0.81) | 0.9 µs (1.0) |
191
+ | Caldera | 99,087 | 9.0 MB (7.9) | 34 ms (23) | 0.04 MB, 4 ms | 0.85 µs (0.71) | 1.2 µs (1.2) |
170
192
 
171
193
  Every ray answered the same as the shooter's own, and a query leaves 100 to 300 bytes of garbage.
172
194
 
195
+ On a phone (an iPhone on iOS 27.2, over https), in the browser:
196
+
197
+ | What | Measured |
198
+ | --- | --- |
199
+ | A step of 250 crates falling | 0.9 ms |
200
+ | 500 crates falling | 1.9 ms |
201
+ | 999 crates falling | 4.3 ms, worst 9; at rest 0.07 |
202
+ | 64 characters walking | 0.7 ms a step |
203
+ | A level of 100,352 triangles | opens in 35 ms; a ray 0.73 µs, a capsule's contacts 1.0 µs |
204
+
205
+ Since iOS 27 an iPhone runs a page opened over plain `http://` (a computer's Wi-Fi address while testing) without its compiler, about 20 times slower, in every browser. Test on a phone over https; a published game always is.
206
+
173
207
  `index.d.ts`, `server.d.ts` and `rapier/rapier.d.ts` (the engine, through `physicsEngine()`) are the reference. How pieces work: [docs/PIECES.md](https://github.com/zaisma/zaisma-sdk/blob/main/docs/PIECES.md). PolyForm Shield 1.0.0 licensed (`LICENSE.txt`): use it in any game, sold or free, on Zaisma, on your own server or anywhere else; only a product that competes with it, or with what Zaisma makes with it, is ruled out. Versions before 2.4.0 were MIT licensed and stay so; Rapier is Apache-2.0 licensed (`rapier/LICENSE.txt`).
package/batch.js CHANGED
@@ -91,65 +91,116 @@ export function createBatch(engine, rapierWorld) {
91
91
  const heldByTriangleIndices = new WeakMap();
92
92
  const letGo = typeof FinalizationRegistry === "undefined" ? { register() {} } : new FinalizationRegistry((raws) => raws.forEach((raw) => raw.free()));
93
93
 
94
- /**
95
- * A mesh as a collider is made from it (new engine.ColliderDesc(mesh.shape)), built the first time it's asked for
96
- * and shared after. With groupNumbers (a group for each triangle), only groupNumber's triangles and the points they
97
- * use. Answers { shape, triangleIndexes }: triangleIndexes says which of the whole mesh's triangles each of the
98
- * shape's is, or null when they're the same. Null when the triangles make no mesh.
99
- */
100
- export function heldMesh(engine, pointsM, triangleIndices, groupNumbers = null, groupNumber = 0) {
94
+ /** A mesh of more triangles than this is built in tiles of about MESH_TILE_TRIANGLE_COUNT, side by side over its two longest sides. */
95
+ export const WHOLE_MESH_TRIANGLE_COUNT = 65536;
96
+ const MESH_TILE_TRIANGLE_COUNT = 32768;
97
+
98
+ function heldOf(pointsM, triangleIndices, groupNumbers) {
101
99
  let held = heldByTriangleIndices.get(triangleIndices);
102
100
  if (!held || held.pointsM !== pointsM || held.groupNumbers !== groupNumbers) {
103
101
  // The same triangles with other points or groups: a colliders' own hold keeps what it was made from.
104
102
  held?.raws.splice(0).forEach((raw) => raw.free());
105
- held = { pointsM, groupNumbers, raws: [], meshByGroupNumber: new Map() };
103
+ held = { pointsM, groupNumbers, raws: [], parts: null };
106
104
  heldByTriangleIndices.set(triangleIndices, held);
107
105
  letGo.register(triangleIndices, held.raws);
108
106
  }
109
- // -1 for the whole mesh, not a group of it.
110
- const heldGroupNumber = groupNumbers ? groupNumber : -1;
111
- if (held.meshByGroupNumber.has(heldGroupNumber)) return held.meshByGroupNumber.get(heldGroupNumber);
112
- let meshPointsM = pointsM;
113
- let meshTriangleIndices = triangleIndices;
114
- let triangleIndexes = null;
115
- if (groupNumbers) {
116
- let triangleCount = 0;
117
- for (let triangleIndex = 0; triangleIndex < groupNumbers.length; triangleIndex += 1) if (groupNumbers[triangleIndex] === groupNumber) triangleCount += 1;
118
- triangleIndexes = new Uint32Array(triangleCount);
119
- meshTriangleIndices = new Uint32Array(triangleCount * 3);
120
- // Only the points the group's triangles use, numbered again in the order they're met.
121
- const newPointIndexes = new Int32Array(pointsM.length / 3).fill(-1);
107
+ return held;
108
+ }
109
+
110
+ /** Which tile each triangle of a big mesh is in, by where its middle is: [tileNumbers, tileCount]. */
111
+ function tilesOf(pointsM, triangleIndices) {
112
+ const triangleCount = triangleIndices.length / 3;
113
+ const lowestM = [Infinity, Infinity, Infinity];
114
+ const highestM = [-Infinity, -Infinity, -Infinity];
115
+ for (let index = 0; index < pointsM.length; index += 1) {
116
+ const axisIndex = index % 3;
117
+ if (pointsM[index] < lowestM[axisIndex]) lowestM[axisIndex] = pointsM[index];
118
+ if (pointsM[index] > highestM[axisIndex]) highestM[axisIndex] = pointsM[index];
119
+ }
120
+ // Tiles over the mesh's two longest sides: a level spreads over its ground, a tower over its height.
121
+ const [firstAxisIndex, secondAxisIndex] = [0, 1, 2].sort((first, second) => highestM[second] - lowestM[second] - (highestM[first] - lowestM[first]));
122
+ const sideTileCount = Math.ceil(Math.sqrt(triangleCount / MESH_TILE_TRIANGLE_COUNT));
123
+ const tileOf = (axisIndex, triangleIndex) => {
124
+ const middleM = (pointsM[triangleIndices[triangleIndex * 3] * 3 + axisIndex] + pointsM[triangleIndices[triangleIndex * 3 + 1] * 3 + axisIndex] + pointsM[triangleIndices[triangleIndex * 3 + 2] * 3 + axisIndex]) / 3;
125
+ const lengthM = highestM[axisIndex] - lowestM[axisIndex];
126
+ return lengthM > 0 ? Math.min(Math.floor(((middleM - lowestM[axisIndex]) / lengthM) * sideTileCount), sideTileCount - 1) : 0;
127
+ };
128
+ const tileNumbers = new Uint32Array(triangleCount);
129
+ for (let triangleIndex = 0; triangleIndex < triangleCount; triangleIndex += 1) tileNumbers[triangleIndex] = tileOf(firstAxisIndex, triangleIndex) * sideTileCount + tileOf(secondAxisIndex, triangleIndex);
130
+ return [tileNumbers, sideTileCount * sideTileCount];
131
+ }
132
+
133
+ /**
134
+ * A mesh as colliders are made from it (new engine.ColliderDesc(part.shape)), built the first time it's asked for
135
+ * and shared after: a part for each of its triangle groups (groupNumbers, a group for each triangle; one group when
136
+ * null), and a big mesh's groups in tiles, so building it never needs much more memory than it ends up holding.
137
+ * Answers [{ groupNumber, shape, triangleIndexes }]: triangleIndexes says which of the whole mesh's triangles each of
138
+ * the part's is, or null when they're the same. Empty when the triangles make no mesh.
139
+ */
140
+ export function heldMeshParts(engine, pointsM, triangleIndices, groupNumbers = null) {
141
+ const held = heldOf(pointsM, triangleIndices, groupNumbers);
142
+ if (held.parts) return held.parts;
143
+ held.parts = [];
144
+ const triangleCount = triangleIndices.length / 3;
145
+ if (triangleCount === 0) return held.parts;
146
+ const addPart = (groupNumber, partPointsM, partTriangleIndices, triangleIndexes) => {
147
+ const raw = new engine.TriMesh(partPointsM, partTriangleIndices).intoRaw();
148
+ if (!raw) return;
149
+ held.raws.push(raw);
150
+ // A collider takes its own hold on the shape and frees it once it's made: the one kept here stays.
151
+ held.parts.push({ groupNumber, shape: { type: engine.ShapeType.TriMesh, intoRaw: () => engine.RawBatch.sharedShape(raw) }, triangleIndexes });
152
+ };
153
+ const isBig = triangleCount > WHOLE_MESH_TRIANGLE_COUNT;
154
+ if (!groupNumbers && !isBig) {
155
+ addPart(0, pointsM, triangleIndices, null);
156
+ return held.parts;
157
+ }
158
+ const [tileNumbers, tileCount] = isBig ? tilesOf(pointsM, triangleIndices) : [null, 1];
159
+ // The triangles in the order of their parts (a group's tile), each part's in the mesh's own order.
160
+ let highestGroupNumber = 0;
161
+ if (groupNumbers) for (let triangleIndex = 0; triangleIndex < triangleCount; triangleIndex += 1) if (groupNumbers[triangleIndex] > highestGroupNumber) highestGroupNumber = groupNumbers[triangleIndex];
162
+ const partNumberOf = (triangleIndex) => (groupNumbers ? groupNumbers[triangleIndex] : 0) * tileCount + (tileNumbers ? tileNumbers[triangleIndex] : 0);
163
+ const firstIndexes = new Uint32Array((highestGroupNumber + 1) * tileCount + 1);
164
+ for (let triangleIndex = 0; triangleIndex < triangleCount; triangleIndex += 1) firstIndexes[partNumberOf(triangleIndex) + 1] += 1;
165
+ for (let partNumber = 0; partNumber + 1 < firstIndexes.length; partNumber += 1) firstIndexes[partNumber + 1] += firstIndexes[partNumber];
166
+ const orderedTriangleIndexes = new Uint32Array(triangleCount);
167
+ const writtenCounts = new Uint32Array(firstIndexes.length);
168
+ for (let triangleIndex = 0; triangleIndex < triangleCount; triangleIndex += 1) {
169
+ const partNumber = partNumberOf(triangleIndex);
170
+ orderedTriangleIndexes[firstIndexes[partNumber] + writtenCounts[partNumber]] = triangleIndex;
171
+ writtenCounts[partNumber] += 1;
172
+ }
173
+ // Only the points a part's triangles use, numbered again in the order they're met. Which part last took a point
174
+ // is noted beside its new number, so neither list is cleared between parts.
175
+ const newPointIndexes = new Uint32Array(pointsM.length / 3);
176
+ const takenByPartNumbers = new Uint32Array(pointsM.length / 3);
177
+ for (let partNumber = 0; partNumber + 1 < firstIndexes.length; partNumber += 1) {
178
+ const partTriangleCount = firstIndexes[partNumber + 1] - firstIndexes[partNumber];
179
+ if (partTriangleCount === 0) continue;
180
+ const triangleIndexes = orderedTriangleIndexes.slice(firstIndexes[partNumber], firstIndexes[partNumber + 1]);
181
+ const partTriangleIndices = new Uint32Array(partTriangleCount * 3);
122
182
  let pointCount = 0;
123
- let writtenCount = 0;
124
- for (let triangleIndex = 0; triangleIndex < groupNumbers.length; triangleIndex += 1) {
125
- if (groupNumbers[triangleIndex] !== groupNumber) continue;
126
- triangleIndexes[writtenCount] = triangleIndex;
127
- for (let cornerIndex = 0; cornerIndex < 3; cornerIndex += 1) {
128
- const pointIndex = triangleIndices[triangleIndex * 3 + cornerIndex];
129
- if (newPointIndexes[pointIndex] === -1) {
130
- newPointIndexes[pointIndex] = pointCount;
131
- pointCount += 1;
132
- }
133
- meshTriangleIndices[writtenCount * 3 + cornerIndex] = newPointIndexes[pointIndex];
183
+ for (let cornerIndex = 0; cornerIndex < partTriangleIndices.length; cornerIndex += 1) {
184
+ const pointIndex = triangleIndices[triangleIndexes[Math.floor(cornerIndex / 3)] * 3 + (cornerIndex % 3)];
185
+ if (takenByPartNumbers[pointIndex] !== partNumber + 1) {
186
+ takenByPartNumbers[pointIndex] = partNumber + 1;
187
+ newPointIndexes[pointIndex] = pointCount;
188
+ pointCount += 1;
134
189
  }
135
- writtenCount += 1;
190
+ partTriangleIndices[cornerIndex] = newPointIndexes[pointIndex];
136
191
  }
137
- meshPointsM = new Float32Array(pointCount * 3);
138
- for (let pointIndex = 0; pointIndex < newPointIndexes.length; pointIndex += 1) {
139
- const newPointIndex = newPointIndexes[pointIndex];
140
- if (newPointIndex === -1) continue;
141
- meshPointsM[newPointIndex * 3] = pointsM[pointIndex * 3];
142
- meshPointsM[newPointIndex * 3 + 1] = pointsM[pointIndex * 3 + 1];
143
- meshPointsM[newPointIndex * 3 + 2] = pointsM[pointIndex * 3 + 2];
192
+ const partPointsM = new Float32Array(pointCount * 3);
193
+ for (let cornerIndex = 0; cornerIndex < partTriangleIndices.length; cornerIndex += 1) {
194
+ const pointIndex = triangleIndices[triangleIndexes[Math.floor(cornerIndex / 3)] * 3 + (cornerIndex % 3)];
195
+ const newPointIndex = partTriangleIndices[cornerIndex];
196
+ partPointsM[newPointIndex * 3] = pointsM[pointIndex * 3];
197
+ partPointsM[newPointIndex * 3 + 1] = pointsM[pointIndex * 3 + 1];
198
+ partPointsM[newPointIndex * 3 + 2] = pointsM[pointIndex * 3 + 2];
144
199
  }
200
+ addPart(Math.floor(partNumber / tileCount), partPointsM, partTriangleIndices, triangleIndexes);
145
201
  }
146
- const raw = meshTriangleIndices.length ? new engine.TriMesh(meshPointsM, meshTriangleIndices).intoRaw() : undefined;
147
- let mesh = null;
148
- if (raw) {
149
- held.raws.push(raw);
150
- // A collider takes its own hold on the shape and frees it once it's made: the one kept here stays.
151
- mesh = { shape: { type: engine.ShapeType.TriMesh, intoRaw: () => engine.RawBatch.sharedShape(raw) }, triangleIndexes };
152
- }
153
- held.meshByGroupNumber.set(heldGroupNumber, mesh);
154
- return mesh;
202
+ return held.parts;
155
203
  }
204
+
205
+ /** Whether a mesh is built in tiles: more triangles than one collider is made from. */
206
+ export const isBigMesh = (triangleIndices) => triangleIndices.length / 3 > WHOLE_MESH_TRIANGLE_COUNT;
package/characters.js CHANGED
@@ -8,7 +8,7 @@ import { refuse } from "./declare.js";
8
8
 
9
9
  const BODY_KINDS = ["kinematic", "dynamic"];
10
10
  /** The fields every character shares whatever its kind: a kind's own fields take other names. */
11
- export const CHARACTER_BASE_FIELD_NAMES = ["x", "y", "z", "velocityX", "velocityY", "velocityZ", "facingYawRad", "isGrounded", "airTickCount", "rideBodyNumber", "seatIndex", "layerNumber"];
11
+ export const CHARACTER_BASE_FIELD_NAMES = ["x", "y", "z", "velocityX", "velocityY", "velocityZ", "facingYawRad", "isGrounded", "airTickCount", "rideBodyNumber", "seatIndex", "layerNumber", "sizeNumber"];
12
12
  const KIND_KEYS = ["name", "bodyKind", "stateFields", "inputFields", "step", "stepRiding", "vehicleControls", "isSteppedBeforeWorld", "canPushBodies"];
13
13
  /** What a piece built on physics may give too: hooks into the world's step, and calls of its own. */
14
14
  const EXTENSION_KEYS = ["startKindState", "beforeWorldStep", "afterWorldStep", "onBodyRemoved", "onCharacterAdded", "onCharacterRemoved", "canRest", "isResting", "onTuning", "drawnWith", "settings", "settingsStatement", "syncedSettingNames", "tuning", "calls", "serverCalls", "drawnCharacter", "startOwn", "readOwn", "writeOwn"];
@@ -43,10 +43,13 @@ export function stickVehicleControls(input) {
43
43
  * cooldowns), as @zaisma/net's fields: shared on the wire, so every side steps from the same.
44
44
  * - inputFields: what moves it, as @zaisma/net's input fields.
45
45
  * - step(character, input, stepContext): one fixed step of one character. character has id, own (the kind's fields,
46
- * change them in place), velocity { x, y, z } (a kinematic one's), facingYawRad, isGrounded, airTickCount, and
47
- * rigidBody and collider (the engine's). stepContext has moveAndSlide(character, movedM, into), castRay, castBall,
48
- * overlapBall, bodyState(bodyId), characterState(characterId), setJoint(jointId, { isEnabled }),
49
- * setLayer(character, collisionLayerName), tickDurationSec, tuning (the world's numbers), isInCharge, isReplay and emit.
46
+ * change them in place), velocity { x, y, z } (a kinematic one's), facingYawRad, isGrounded, airTickCount,
47
+ * characterSizeName (which of the world's characterSizes it is, null for the world's own) and rigidBody and collider
48
+ * (the engine's). stepContext has moveAndSlide(character, movedM, into), castRay, castBall, overlapBall,
49
+ * bodyState(bodyId), characterState(characterId), setJoint(jointId, { isEnabled }), setLayer(character,
50
+ * collisionLayerName), setSize(character, characterSizeName) (a crouch; false where the size has no room),
51
+ * isRestingOnLevel(character) (it stands on what never moves and touches nothing else: with nothing asked of it and
52
+ * no speed, a step would leave it where it is, and the kind may return before its move), tickDurationSec, tuning (the world's numbers), isInCharge, isReplay and emit.
50
53
  * A field with isShared: false is the kind's own memory in each game, never sent nor compared: set by each step
51
54
  * afresh, read by drawnCharacter and characterState (sprinting, stopped at deep water). It isn't put back on a replay.
52
55
  * - stepRiding(character, input, stepContext): one fixed step of a character sitting in a seat, to keep its own fields
@@ -164,6 +167,9 @@ export function walkStep(character, input, stepContext) {
164
167
  const wish = wishOf(input, stepWish);
165
168
  const speedMPerSec = tuning.walkSpeedMPerSec * (input.isRunning ? RUN_SPEED_PCT / 100 : 1);
166
169
  const velocity = character.velocity;
170
+ // Standing still on what never moves, with nothing asked: this step would leave it exactly here, so it's skipped,
171
+ // and a crowd standing about costs nothing.
172
+ if (wish.lengthNumber === 0 && !input.jump && character.isGrounded && velocity.x === 0 && velocity.y === 0 && velocity.z === 0 && stepContext.isRestingOnLevel?.(character)) return;
167
173
  const accelerationMPerSecPerSec = character.isGrounded ? GROUND_ACCELERATION_M_PER_SEC_PER_SEC : AIR_ACCELERATION_M_PER_SEC_PER_SEC;
168
174
  // In the air with nothing asked, a walker keeps the speed it left the ground with.
169
175
  if (character.isGrounded || wish.lengthNumber > 0.01) {
package/declare.js CHANGED
@@ -16,10 +16,14 @@ export const JOINT_KINDS = ["fixed", "ball", "hinge", "slider", "spring", "rope"
16
16
  export const PLAYER_CHARACTER_MODES = ["on_join", "by_game"];
17
17
  const ID_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/;
18
18
 
19
- /** Bodies one world holds at most, declared and added while playing together. */
20
- export const MAXIMUM_BODY_COUNT = 1000;
19
+ /** Bodies that move or may (moving and kinematic ones, and every body added while playing) one world holds at most. */
20
+ export const MAXIMUM_BODY_COUNT = 2000;
21
+ /** Bodies declared fixed one world holds at most: a level's pieces, which never move and are never sent. */
22
+ export const MAXIMUM_FIXED_BODY_COUNT = 20_000;
21
23
  /** Characters one world holds at most: players' and bots'. */
22
- export const MAXIMUM_CHARACTER_COUNT = 64;
24
+ export const MAXIMUM_CHARACTER_COUNT = 250;
25
+ /** Sizes of character a world names at most, beside its own character's. */
26
+ export const MAXIMUM_CHARACTER_SIZE_COUNT = 31;
23
27
  const MAXIMUM_SHAPE_COUNT = 16;
24
28
  const MAXIMUM_HULL_POINT_COUNT = 255;
25
29
  const MAXIMUM_MESH_TRIANGLE_COUNT = 50_000;
@@ -31,6 +35,8 @@ const MAXIMUM_HEIGHTFIELD_SIDE_COUNT = 4096;
31
35
  export const MAXIMUM_COLLISION_LAYER_COUNT = 16;
32
36
  /** Joints one world holds at most, declared and added while playing together. */
33
37
  export const MAXIMUM_JOINT_COUNT = 1000;
38
+ /** Bodies that aren't fixed and joints a world declares together at most: what the online core takes from the start. More come while playing, with addBody and addJoint. */
39
+ export const MAXIMUM_DECLARED_THING_COUNT = 2048;
34
40
  const MAXIMUM_WHEEL_COUNT = 8;
35
41
  const MAXIMUM_SEAT_COUNT = 8;
36
42
  /** The layer a character riding in a seat is on: it touches nothing, not its seat nor the body under it. */
@@ -42,7 +48,7 @@ export const WORLD_REACH_M = 10_000;
42
48
  /** How heavy a cubic metre of a body is when it doesn't say its mass: furniture is mostly air. */
43
49
  export const DEFAULT_DENSITY_KG_PER_M3_NUMBER = 250;
44
50
 
45
- const WORLD_KEYS = ["bodies", "bodyKinds", "character", "playerCharacterMode", "startPositionsM", "fallOutHeightM", "collisionLayers", "surfaceNames", "joints", "substepCount", "groundReachM"];
51
+ const WORLD_KEYS = ["bodies", "bodyKinds", "character", "characterSizes", "playerCharacterMode", "startPositionsM", "fallOutHeightM", "collisionLayers", "surfaceNames", "joints", "substepCount", "groundReachM"];
46
52
  const BODY_KEYS = ["id", "bodyKindName", "motionKind", "positionM", "rotationDeg", "massKg", "bouncePct", "gripPct", "linearDampingNumber", "angularDampingNumber", "canBeGrabbed", "shapes", "collisionLayerName", "wheels", "vehicle", "seats", "timetable"];
47
53
  const BODY_KIND_KEYS = ["massKg", "bouncePct", "gripPct", "linearDampingNumber", "angularDampingNumber", "canBeGrabbed", "shapes", "collisionLayerName", "wheels", "vehicle", "seats"];
48
54
  const WHEEL_KEYS = ["positionM", "radiusM", "suspensionRestM", "suspensionTravelM", "isSteered", "isDriven"];
@@ -87,6 +93,7 @@ export const triangleGroupBitNumberOf = (groupNumber) => 1 << ((groupNumber - 1)
87
93
  /** Surfaces one world names at most (what a hit says it met: concrete, metal, water). */
88
94
  export const MAXIMUM_SURFACE_COUNT = 255;
89
95
  const CHARACTER_KEYS = ["heightM", "radiusM", "stepHeightM", "maximumSlopeDeg"];
96
+ const CHARACTER_SIZE_KEYS = ["name", ...CHARACTER_KEYS];
90
97
 
91
98
  const isPlainObject = (given) => given !== null && typeof given === "object" && !Array.isArray(given);
92
99
  const isFiniteNumber = (given) => typeof given === "number" && Number.isFinite(given);
@@ -610,6 +617,17 @@ function checkBodyKinds(given) {
610
617
  });
611
618
  }
612
619
 
620
+ /** A character's size, checked: what it leaves out is the size it starts from (the piece's own for world.character, world.character for a named size). */
621
+ function checkCharacterSize(given, what, from, keys) {
622
+ refuseUnknownKeys(given, keys, "bad_world", what);
623
+ const radiusM = given.radiusM === undefined ? from.radiusM : lengthOf(given.radiusM, "bad_world", `${what}.radiusM`, { minimumM: 0.05, maximumM: 5 });
624
+ const heightM = given.heightM === undefined ? from.heightM : lengthOf(given.heightM, "bad_world", `${what}.heightM`, { minimumM: 0.2, maximumM: 20 });
625
+ if (heightM < radiusM * 2) refuse("bad_world", `${what} is shorter than it is wide.`, `${what}.heightM`, "Give a heightM of at least twice the radiusM: a character is a capsule standing up.");
626
+ const stepHeightM = given.stepHeightM === undefined ? from.stepHeightM : lengthOf(given.stepHeightM, "bad_world", `${what}.stepHeightM`, { minimumM: 0, maximumM: 5 });
627
+ if (given.maximumSlopeDeg !== undefined && (!isFiniteNumber(given.maximumSlopeDeg) || given.maximumSlopeDeg < 0 || given.maximumSlopeDeg > 89)) refuse("bad_world", `${what}.maximumSlopeDeg is ${JSON.stringify(given.maximumSlopeDeg)}.`, `${what}.maximumSlopeDeg`, "Give the steepest ground a character walks up, in degrees from 0 to 89.");
628
+ return { heightM, radiusM, stepHeightM, maximumSlopeDeg: given.maximumSlopeDeg ?? from.maximumSlopeDeg };
629
+ }
630
+
613
631
  /**
614
632
  * A physics world, checked: what createPhysics and physicsKind take. Write it in a file of its own that the game's
615
633
  * page and, with a game server, the game server both import, so both build the same world. Throws PieceError
@@ -620,7 +638,7 @@ export function definePhysicsWorld(given = {}) {
620
638
  const { bodies = [], character = {}, playerCharacterMode = "on_join", startPositionsM = [{ x: 0, y: 0, z: 0 }], fallOutHeightM = -30, joints = [], substepCount = 2, groundReachM = 24 } = given;
621
639
  const collisionLayers = checkCollisionLayers(given.collisionLayers);
622
640
  const bodyKinds = checkBodyKinds(given.bodyKinds);
623
- if (!Array.isArray(bodies) || bodies.length > MAXIMUM_BODY_COUNT) refuse("bad_world", `world.bodies isn't a list of up to ${MAXIMUM_BODY_COUNT} bodies.`, "world.bodies", 'Give the world\'s bodies, like [{ id: "floor", motionKind: "fixed", shapes: [...] }].');
641
+ if (!Array.isArray(bodies) || bodies.length > MAXIMUM_BODY_COUNT + MAXIMUM_FIXED_BODY_COUNT) refuse("bad_world", "world.bodies isn't a list of bodies.", "world.bodies", 'Give the world\'s bodies, like [{ id: "floor", motionKind: "fixed", shapes: [...] }].');
624
642
  const ids = new Set();
625
643
  const checkedBodies = bodies.map((body, bodyIndex) => {
626
644
  const checked = checkBody(body, `world.bodies[${bodyIndex}]`, bodyKinds);
@@ -628,6 +646,9 @@ export function definePhysicsWorld(given = {}) {
628
646
  ids.add(checked.id);
629
647
  return checked;
630
648
  });
649
+ const fixedBodyCount = checkedBodies.reduce((count, body) => count + (body.motionKind === "fixed" ? 1 : 0), 0);
650
+ if (fixedBodyCount > MAXIMUM_FIXED_BODY_COUNT) refuse("bad_world", `world.bodies has ${fixedBodyCount} fixed bodies, and a world holds ${MAXIMUM_FIXED_BODY_COUNT}.`, "world.bodies", "Make pieces that sit together one body of several shapes, or one mesh.");
651
+ if (checkedBodies.length - fixedBodyCount > MAXIMUM_BODY_COUNT) refuse("bad_world", `world.bodies has ${checkedBodies.length - fixedBodyCount} bodies that aren't fixed, and a world holds ${MAXIMUM_BODY_COUNT}.`, "world.bodies", 'Declare what never moves with motionKind: "fixed": those aren\'t counted here.');
631
652
  const { surfaceNames = [] } = given;
632
653
  if (!Array.isArray(surfaceNames) || surfaceNames.length > MAXIMUM_SURFACE_COUNT || surfaceNames.some((name) => typeof name !== "string" || !BODY_KIND_NAME_PATTERN.test(name)) || new Set(surfaceNames).size !== surfaceNames.length) refuse("bad_world", "world.surfaceNames isn't a list of surfaces, each named once.", "world.surfaceNames", `Give up to ${MAXIMUM_SURFACE_COUNT} names in lowercase words joined by underscores, like ["concrete", "metal", "wet_grass"]: what a shape's surfaceName and a mesh's triangleSurfaceIndices pick from, and what a hit says it met.`);
633
654
  const named = { collisionLayers, surfaceNames };
@@ -644,6 +665,8 @@ export function definePhysicsWorld(given = {}) {
644
665
  for (const name of wheelLayerNames ?? []) if (!layerNames.includes(name)) refuse("bad_world", `${what}.vehicle.wheelCollisionLayerNames names "${name}".`, `${what}.vehicle.wheelCollisionLayerNames`, `Use the world's collisionLayers: ${layerNames.join(", ")}.`);
645
666
  }
646
667
  if (!Array.isArray(joints) || joints.length > MAXIMUM_JOINT_COUNT) refuse("bad_world", `world.joints isn't a list of up to ${MAXIMUM_JOINT_COUNT} joints.`, "world.joints", 'Give joints like [{ id: "door:hinge", jointKind: "hinge", bodyId: "door", anchorM: { x: -0.45, y: 0, z: 0 } }].');
668
+ const declaredThingCount = checkedBodies.length - fixedBodyCount + joints.length;
669
+ if (declaredThingCount > MAXIMUM_DECLARED_THING_COUNT) refuse("bad_world", `world declares ${checkedBodies.length - fixedBodyCount} bodies that aren't fixed and ${joints.length} joints, and a world starts with ${MAXIMUM_DECLARED_THING_COUNT} of them together.`, "world.joints", "Declare fewer, and add the rest while playing with addBody and addJoint.");
647
670
  const jointIds = new Set();
648
671
  const checkedJoints = joints.map((joint, jointIndex) => {
649
672
  const checked = checkJoint(joint, `world.joints[${jointIndex}]`, (bodyId) => ids.has(bodyId));
@@ -653,20 +676,25 @@ export function definePhysicsWorld(given = {}) {
653
676
  });
654
677
  if (!Number.isInteger(substepCount) || substepCount < 1 || substepCount > 8) refuse("bad_world", `world.substepCount is ${JSON.stringify(substepCount)}.`, "world.substepCount", "Give how many times the engine steps in each of the room's fixed steps, from 1 to 8: 2 (the default) steps a 30-a-second room 60 times a second, which cars and quick things want.");
655
678
  const groundReach = lengthOf(groundReachM, "bad_world", "world.groundReachM", { minimumM: 2, maximumM: 1000 });
656
- refuseUnknownKeys(character, CHARACTER_KEYS, "bad_world", "world.character");
657
- const radiusM = character.radiusM === undefined ? 0.28 : lengthOf(character.radiusM, "bad_world", "world.character.radiusM", { minimumM: 0.05, maximumM: 5 });
658
- const heightM = character.heightM === undefined ? 1.5 : lengthOf(character.heightM, "bad_world", "world.character.heightM", { minimumM: 0.2, maximumM: 20 });
659
- if (heightM < radiusM * 2) refuse("bad_world", "world.character is shorter than it is wide.", "world.character.heightM", "Give a heightM of at least twice the radiusM: a character is a capsule standing up.");
660
- const stepHeightM = character.stepHeightM === undefined ? 0.35 : lengthOf(character.stepHeightM, "bad_world", "world.character.stepHeightM", { minimumM: 0, maximumM: 5 });
661
- if (character.maximumSlopeDeg !== undefined && (!isFiniteNumber(character.maximumSlopeDeg) || character.maximumSlopeDeg < 0 || character.maximumSlopeDeg > 89)) refuse("bad_world", `world.character.maximumSlopeDeg is ${JSON.stringify(character.maximumSlopeDeg)}.`, "world.character.maximumSlopeDeg", "Give the steepest ground a character walks up, in degrees from 0 to 89.");
662
- const maximumSlopeDeg = character.maximumSlopeDeg ?? 50;
679
+ const ownCharacter = checkCharacterSize(character, "world.character", { heightM: 1.5, radiusM: 0.28, stepHeightM: 0.35, maximumSlopeDeg: 50 }, CHARACTER_KEYS);
680
+ const { characterSizes = [] } = given;
681
+ if (!Array.isArray(characterSizes) || characterSizes.length > MAXIMUM_CHARACTER_SIZE_COUNT) refuse("bad_world", `world.characterSizes isn't a list of up to ${MAXIMUM_CHARACTER_SIZE_COUNT} sizes.`, "world.characterSizes", 'Give the other sizes a character takes, like [{ name: "crouched", heightM: 1 }]: what a size leaves out is world.character\'s.');
682
+ const checkedCharacterSizes = characterSizes.map((size, sizeIndex) => {
683
+ const what = `world.characterSizes[${sizeIndex}]`;
684
+ if (!isPlainObject(size) || typeof size.name !== "string" || !BODY_KIND_NAME_PATTERN.test(size.name)) refuse("bad_world", `${what} has no name.`, `${what}.name`, 'Give each size a name in lowercase words joined by underscores, like "crouched".');
685
+ if (characterSizes.findIndex((other) => other?.name === size.name) !== sizeIndex) refuse("bad_world", `world.characterSizes names "${size.name}" twice.`, `${what}.name`, "Give each size its own name.");
686
+ return { name: size.name, ...checkCharacterSize(size, what, ownCharacter, CHARACTER_SIZE_KEYS) };
687
+ });
663
688
  if (!PLAYER_CHARACTER_MODES.includes(playerCharacterMode)) refuse("bad_world", `world.playerCharacterMode is ${JSON.stringify(playerCharacterMode)}.`, "world.playerCharacterMode", `Use: ${PLAYER_CHARACTER_MODES.join(", ")}.`);
664
689
  if (!Array.isArray(startPositionsM) || !startPositionsM.length || startPositionsM.length > MAXIMUM_CHARACTER_COUNT) refuse("bad_world", "world.startPositionsM isn't a list of places.", "world.startPositionsM", "Give where characters start, their feet on the ground, like [{ x: 0, y: 0, z: 0 }, { x: 2, y: 0, z: 0 }]: each new character takes the next.");
665
690
  if (!isFiniteNumber(fallOutHeightM) || Math.abs(fallOutHeightM) > WORLD_REACH_M) refuse("bad_world", `world.fallOutHeightM is ${JSON.stringify(fallOutHeightM)}.`, "world.fallOutHeightM", "Give the height in metres below which anything that falls is put back where it started, like -30.");
666
691
  return {
667
692
  bodies: checkedBodies,
693
+ bodyById: new Map(checkedBodies.map((body) => [body.id, body])),
694
+ fixedBodyIds: checkedBodies.filter((body) => body.motionKind === "fixed").map((body) => body.id),
668
695
  bodyKinds,
669
- character: { heightM, radiusM, stepHeightM, maximumSlopeDeg },
696
+ character: ownCharacter,
697
+ characterSizes: checkedCharacterSizes,
670
698
  collisionLayers,
671
699
  surfaceNames: [...surfaceNames],
672
700
  joints: checkedJoints,
package/index.d.ts CHANGED
@@ -269,7 +269,12 @@ export interface JointDeclaration {
269
269
  }
270
270
 
271
271
  export interface WorldDeclaration {
272
- /** The world's bodies, up to 1000. A body added while playing (addBody) counts too. */
272
+ /**
273
+ * The world's bodies. Up to 2,000 that move or may: moving and kinematic ones, and every body added while playing
274
+ * (addBody). And up to 20,000 declared "fixed": a level's pieces, which never move, are never sent and aren't
275
+ * counted with the others (about 3 KB each, and nothing a step once the world rests). The bodies that aren't
276
+ * fixed and the joints a world declares come to 2,048 together at most; more are added while playing.
277
+ */
273
278
  bodies?: readonly BodyDeclaration[];
274
279
  /** Kinds of body by name, up to 250: bodies that are alike, and what can be added while playing. */
275
280
  bodyKinds?: Record<string, BodyKindDeclaration>;
@@ -289,9 +294,15 @@ export interface WorldDeclaration {
289
294
  * (stepHeightM, default 0.35) and the steepest slope it climbs (maximumSlopeDeg, default 50).
290
295
  */
291
296
  character?: { heightM?: number; radiusM?: number; stepHeightM?: number; maximumSlopeDeg?: number };
297
+ /**
298
+ * The other sizes a character takes, each named: a crouch, a giant, a small creature. What a size leaves out is
299
+ * `character`'s. A character starts as `character` and is given another with addCharacter's or setCharacter's
300
+ * characterSizeName, or from its kind's step with stepContext.setSize; its feet stay where they are.
301
+ */
302
+ characterSizes?: { name: string; heightM?: number; radiusM?: number; stepHeightM?: number; maximumSlopeDeg?: number }[];
292
303
  /** "on_join" (the default): every player gets a character with their id as they join. "by_game": the game adds them (addCharacter). */
293
304
  playerCharacterMode?: "on_join" | "by_game";
294
- /** Where characters start, their feet on the ground: each new character takes the next, round again. */
305
+ /** Where characters start, their feet on the ground: each new character takes the next, round again. A world holds up to 250 characters, players' and the game's own. */
295
306
  startPositionsM?: Point[];
296
307
  /** The height below which anything that falls is put back where it started; default -30. */
297
308
  fallOutHeightM?: number;
@@ -309,6 +320,7 @@ export interface PhysicsWorld {
309
320
  readonly joints: readonly JointDeclaration[];
310
321
  readonly collisionLayers: readonly { name: string; touchedNames: string[] }[];
311
322
  readonly character: { heightM: number; radiusM: number; stepHeightM: number; maximumSlopeDeg: number };
323
+ readonly characterSizes: readonly { name: string; heightM: number; radiusM: number; stepHeightM: number; maximumSlopeDeg: number }[];
312
324
  readonly playerCharacterMode: "on_join" | "by_game";
313
325
  readonly startPositionsM: readonly Point[];
314
326
  readonly fallOutHeightM: number;
@@ -348,6 +360,8 @@ export interface SteppedCharacter {
348
360
  facingYawRad: number;
349
361
  isGrounded: boolean;
350
362
  airTickCount: number;
363
+ /** Which of the world's characterSizes it is now, or null for the world's own character's. Changed with stepContext.setSize. */
364
+ readonly characterSizeName: string | null;
351
365
  /** The kind's own fields, by name. */
352
366
  own: Record<string, any>;
353
367
  readonly rigidBody: Engine.RigidBody;
@@ -462,11 +476,23 @@ export interface CharacterStepContext {
462
476
  /** A body as the world has it now, read only (pulling a cart: how fast it lets him go), or null. */
463
477
  bodyState(bodyId: string): (Omit<BodyState, "riderCharacterIds"> & { massKg: number | null }) | null;
464
478
  /** Another character as the world has it now, read only, or null. */
465
- characterState(characterId: string): { positionM: Point; velocityMPerSec: Point; facingYawRad: number; isGrounded: boolean; rideBodyId: string | null; collisionLayerName: string; own: Record<string, any> } | null;
479
+ characterState(characterId: string): { positionM: Point; velocityMPerSec: Point; facingYawRad: number; isGrounded: boolean; rideBodyId: string | null; collisionLayerName: string; characterSizeName: string | null; own: Record<string, any> } | null;
466
480
  /** Ties or lets go a joint from the step (a press that takes a cart's handles), so a replay runs it exactly. Answers false for a joint that isn't here. */
467
481
  setJoint(jointId: string, changes: { isEnabled: boolean }): boolean;
468
482
  /** Puts the character on one of the world's collision layers from its step (through his own cart while he holds it). */
469
483
  setLayer(character: SteppedCharacter, collisionLayerName: string): void;
484
+ /**
485
+ * Gives a character another of the world's characterSizes (a crouch, standing up again), or null for the world's
486
+ * own character's: its feet stay where they are. False, and nothing changes, where the size has no room: a low
487
+ * roof over a crouched head.
488
+ */
489
+ setSize(character: SteppedCharacter, characterSizeName: string | null): boolean;
490
+ /**
491
+ * Whether the character stands on what never moves and touches nothing else. With nothing asked of it and no
492
+ * speed, a step would leave it exactly where it is, so a kind may return before its move: the piece's walk does,
493
+ * and a crowd standing about costs nothing.
494
+ */
495
+ isRestingOnLevel(character: SteppedCharacter): boolean;
470
496
  /** The engine, for what the piece doesn't do. */
471
497
  engine: typeof Engine;
472
498
  rapierWorld: Engine.World;
@@ -611,6 +637,8 @@ export interface CharacterView {
611
637
  rideBodyId: string | null;
612
638
  seatIndex: number | null;
613
639
  collisionLayerName: string;
640
+ /** Which of the world's characterSizes it is, or null for the world's own character's. */
641
+ characterSizeName: string | null;
614
642
  own: Record<string, any>;
615
643
  /** A character kind's own (with @zaisma/physics-party: holderCharacterIds on a body; heldBodyId, handPositionM, loadPct on a character). */
616
644
  [kindOwn: string]: any;
@@ -631,10 +659,10 @@ export interface PhysicsChanges {
631
659
  characterIds(): string[];
632
660
  hasCharacter(characterId: string): boolean;
633
661
  characterState(characterId: string): CharacterView | null;
634
- addCharacter(characterId: string, addOptions?: { positionM?: Point }): boolean;
662
+ addCharacter(characterId: string, addOptions?: { positionM?: Point; characterSizeName?: string | null }): boolean;
635
663
  removeCharacter(characterId: string): boolean;
636
- /** Sets a character at once: its feet's place (a teleport), speed, facing, layer, or its kind's own fields. */
637
- setCharacter(characterId: string, changes: { positionM?: Point; velocityMPerSec?: Point; facingYawRad?: number; collisionLayerName?: string; own?: Record<string, any> }): boolean;
664
+ /** Sets a character at once: its feet's place (a teleport), speed, facing, layer, size (whether or not it fits where it stands), or its kind's own fields. */
665
+ setCharacter(characterId: string, changes: { positionM?: Point; velocityMPerSec?: Point; facingYawRad?: number; collisionLayerName?: string; characterSizeName?: string | null; own?: Record<string, any> }): boolean;
638
666
  /** Seats a character in a body's seat (the first drives one with wheels); with bodyId null, lets it out where it is. Answers false for a seat that's taken. */
639
667
  seatCharacter(characterId: string, bodyId: string | null, seatIndex?: number): boolean;
640
668
  jointIds(): string[];
@@ -32,7 +32,8 @@ export const levelCharactersKindFrom = (charactersKind) => (givenWorld, given =
32
32
  const kind = given.characters === undefined ? walkingCharacters() : defineCharacterKind(given.characters);
33
33
  const { settings } = openPiece(statement, { settings: given.settings });
34
34
  // The level: what doesn't move. Bodies that move, and joints, are a world's (physicsKind), never a level's.
35
- const level = { ...world, bodies: world.bodies.filter((body) => body.motionKind !== "moving"), joints: [] };
35
+ const levelBodies = world.bodies.filter((body) => body.motionKind !== "moving");
36
+ const level = { ...world, bodies: levelBodies, bodyById: new Map(levelBodies.map((body) => [body.id, body])), joints: [] };
36
37
  const sharedFields = characterFieldsOf(kind).filter((field) => !RIDING_FIELD_NAMES.includes(field.name));
37
38
  // A level whose meshes have triangle groups (doors, bridges) switches them room by room: which are off is the room's own.
38
39
  const hasGroups = level.bodies.some((body) => body.shapes.some((shape) => shape.triangleGroupNumbers));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/physics",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "description": "Physics that works as it's added, alone and online, for every kind of game: one world of bodies (moving, kinematic or fixed), ground for big outdoor maps, joints, wheeled vehicles, seats, collision layers and queries, with characters that move by the game's own rules. Rapier is the engine, shipped inside.",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "homepage": "https://zaisma.com",
package/piece.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "statement_version_number": 1,
3
3
  "name": "@zaisma/physics",
4
- "piece_version": "2.5.0",
4
+ "piece_version": "2.6.0",
5
5
  "kind": "foundation",
6
6
  "standard": "@zaisma/standard",
7
7
  "summary": "Physics that works as it's added, alone and online, for every kind of game: one world of bodies (moving, kinematic or fixed), ground for big outdoor maps, joints, wheeled vehicles, seats, collision layers and queries, with characters that move by the game's own rules. Rapier is the engine, shipped inside.",
package/piece.json.js CHANGED
@@ -2,7 +2,7 @@
2
2
  export default {
3
3
  "statement_version_number": 1,
4
4
  "name": "@zaisma/physics",
5
- "piece_version": "2.5.0",
5
+ "piece_version": "2.6.0",
6
6
  "kind": "foundation",
7
7
  "standard": "@zaisma/standard",
8
8
  "summary": "Physics that works as it's added, alone and online, for every kind of game: one world of bodies (moving, kinematic or fixed), ground for big outdoor maps, joints, wheeled vehicles, seats, collision layers and queries, with characters that move by the game's own rules. Rapier is the engine, shipped inside.",
package/rapier/CHANGES.md CHANGED
@@ -4,12 +4,14 @@
4
4
 
5
5
  ## What Zaisma changed
6
6
 
7
- Nothing of Rapier's own is removed or behaves differently: its whole JavaScript API is there as in the stock package, and `rapier.d.ts` is the stock one. Added:
7
+ Nothing of Rapier's own is removed: its whole JavaScript API is there as in the stock package, and `rapier.d.ts` is the stock one. Two things in its broad phase behave differently, both below, and neither changes what a world does. Added:
8
8
 
9
9
  - **One Rust module, `RawBatch`,** compiled into the bindings. It does in one call, with plain numbers written into two buffers read straight from the engine's memory, what the stock JavaScript API does a number at a time through an object made for each answer: one substep of the world with what was hit, every awake body's place, rotation, speed and spin after a step (put on the steps the piece sends them at), a body's read and write, rays, a ball's and a capsule's sweep, overlaps, a capsule's contacts triangle by triangle, a character's move and a vehicle's update.
10
10
  - **A count of the memory the engine holds,** kept by its allocator and read with `RawBatch.heldByteCount()`, `RawBatch.mostHeldByteCount()` and `RawBatch.restartMostHeldByteCount()`: what a level costs is measured exactly instead of guessed from how far the WebAssembly memory has grown.
11
11
  - **Shapes shared between colliders,** with `RawBatch.sharedShape(shape)`: a second collider made from the same triangle mesh holds the mesh itself, not a copy, in any world.
12
12
  - **Three fields made visible inside the crate** (`pub(crate)`), so the module can reach them: the character controller's `controller`, `result` and `events` (`src/control/character_controller.rs`), and the vehicle controller's `controller` (`src/control/ray_cast_vehicle_controller.rs`).
13
+ - **Level colliders, never paired with each other** (build 2). `RawBatch.markLevelCollider(colliders, collider)` sets the lowest bit of a collider's `user_data`; the broad phase of the `rapier3d` crate (`src/geometry/broad_phase_bvh.rs`, patched in the published 0.30.1 source, whose checksum the build checks) then never keeps a pair of two marked colliders. The stock one keeps every pair of touching fixed colliders and walks them all each step, which made a level of thousands of pieces slow and heavy; two fixed colliders never collide, so nothing else changes. A game that sets `user_data` on its own colliders keeps that bit clear.
14
+ - **A broad phase that rests** (build 2). A step in which no collider moved, came or went leaves the broad phase as it is, where the stock one rewrites its whole tree every step: a world at rest costs the same however big its level.
13
15
  - **The loader**: one module that starts the engine from WebAssembly the piece is given (`startEngine`, `startEngineLater`) instead of fetching its own, and that also exports `RawBatch`, `ENGINE_VERSION` and `engineMemory()`.
14
16
  - **The crate versions** are locked by Zaisma's own `Cargo.lock`: the tag's lock file was a version behind its `Cargo.toml`.
15
17