@zaisma/physics 2.6.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -4
- package/batch.js +6 -1
- package/bodies.js +72 -0
- package/characters.js +19 -5
- package/declare.js +110 -8
- package/index.d.ts +195 -37
- package/index.js +2 -2
- package/package.json +2 -1
- package/piece.json +18 -1
- package/piece.json.js +18 -1
- package/rapier/CHANGES.md +2 -0
- package/rapier/rapier.js +298 -6
- package/rapier/rapier.wasm +0 -0
- package/simulation.js +483 -57
- package/sync.js +280 -52
package/README.md
CHANGED
|
@@ -36,12 +36,15 @@ export const valley = definePhysicsWorld({
|
|
|
36
36
|
- **Bodies** are `moving` (physics moves them), `kinematic` (the game moves them: lifts, doors on rails, platforms) or `fixed`, made of shapes: `box`, `ball`, `capsule`, `cylinder`, `hull`, and for the fixed world `mesh` and `heightfield`. Metres, kilograms, +Y up. `setBody(id, { motionKind })` parks one or lets it go.
|
|
37
37
|
- **Bodies on a timetable:** a kinematic body with a `timetable` goes between its stops by itself: a lift, a tram, a turning arm, a sweeper. 2 to 32 `stops`, each a place, a turn, how long the trip there takes and how long it waits; `repeatMode` `loop`, `back_and_forth` or `once`; `easeKind` `linear` or `smooth`. Every game and the game server work out where it is from the room's step alone, so nothing of it is sent and a step run again finds it where it was. It carries the characters and bodies standing on it and pushes what's in its way.
|
|
38
38
|
- **Ground for a big map:** a heightfield or a mesh too big to write inline is read from a data file (`dataPath`, formats in `data.js`; name it `.bin`, a file type Zaisma's upload takes): `loadPhysicsData(world)` in a game, `readDataFile` where the world opens on a game server. Only the ground near something that moves is laid, so a 1,500 m valley costs what the few hundred metres around its players cost. `keepGroundNear(pointM)` keeps it laid where a camera or a query looks.
|
|
39
|
-
- **Joints:** `fixed`, `ball`, `hinge`, `slider`, `spring` and `rope`, between two bodies, a body and a character, or a body and the world, with limits; declared, or added and let go while playing.
|
|
39
|
+
- **Joints:** `fixed`, `ball`, `hinge`, `slider`, `spring` and `rope`, between two bodies, a body and a character, or a body and the world, with limits; declared, or added and let go while playing. A hinge's angle and a slider's distance (limits and motor targets alike) are measured as the other end, or the world, seen from the body: flip the axis and the measure flips.
|
|
40
|
+
- **Motors and joints that break:** a hinge or slider takes a `motor` (`motorKind` `position`, to a target angle or distance with `stiffnessNumber` and `dampingNumber`, or `speed`, at a target speed, each with its `maximumForceNewtons`): a door that swings shut, a winch, a turret. `setJoint(id, { motorTargetNumber })` moves its target while playing, sent to everyone. A joint with `breakForceNewtons` lets go when pulled harder than that (a rope under a load, a trailer's hitch), tells `jointBroke` once, and `setJoint(id, { isEnabled: true })` mends it. A rigid joint to a character the game moves wants a `spring` or a break force: nothing stops the character, so the joint is all that holds what it drags against a wall.
|
|
40
41
|
- **Vehicles:** a body with `wheels` and `vehicle` drives on ray-cast wheels: suspension, engine, brakes, steering. Whoever sits in seat 0 drives it from their input (`vehicleControls`, by default the stick and `isBraking`); others ride along, seated at once. Wheels never stand on characters (and only on `wheelCollisionLayerNames` when given), a heavy vehicle's springs hold its weight (`maximumSuspensionForceNewtons`), and `drawnBody` answers each wheel's spring and spin to draw it by.
|
|
41
42
|
- **Bodies while playing:** `setBody` sets a body's place, speed, motion kind, layer or `massKg` (what rides in a cart's bed weighs on it); `addBody` takes a `motionKind` (a building piece placed `fixed` at once); a body or kind may slow at its own `linearDampingNumber` and `angularDampingNumber`. A world played alone frees its engine with `dispose()`.
|
|
42
43
|
- **Small quick things** (lighter than 8 kg: food, stones, bullets you can see) look ahead for what they'll meet, so they hold on heightfield ground and thin walls up to about 20 m/s at the default `substepCount`; anything faster wants more substeps.
|
|
44
|
+
- **Zones:** places that tell who came in and left (`zoneEntered`, `zoneLeft`, `zoneOccupants(id)`, `zonesAt`): a capture point, a checkpoint, water, a door's trigger. One may turn gravity (`gravityPct`: 0 floats things, 200 doubles it), push (`pushMPerSecPerSec`: a fan, wind, a current) and slow (`dampingNumber`: water, mud), for the layers it names, and may ride on a body (`bodyId`: inside a lift). `setZone(id, { isEnabled })` switches one, sent to everyone. Bodies feel it as real forces; a character kind reads it with `stepContext.zoneEffectsOf(character)`, and the walking characters wade, float and drift by it.
|
|
45
|
+
- **Body kinds with rules of their own:** `bodies: { hover: { stateFields, step(body, driverInput, stepContext) } }` on `createPhysics` and `physicsKind` steps every body of a kind by the game's rules, before the engine moves the world, the mirror of a character kind: a boat, an aircraft, a bike, a hover, a mine with a fuse. Its `stateFields` are the body's own (`body.own`), sent with it; whoever sits in seat 0 is its driver, and their input is `driverInput`. A body at rest with nobody aboard isn't stepped unless `isSteppedAtRest`. `stepContext.addForce(body, forceNewtons, atM)` and `addTorque` push it for the step, through every substep, against gravity and what it leans on; `stepContext.bodyMotion(body)` reads where it is and how it moves. Up to 8 kinds may have fields of their own.
|
|
43
46
|
- **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
|
-
- **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.
|
|
47
|
+
- **Queries:** `castRay`, `castBall`, `castCapsule`, `castBox`, `overlapBall`, `overlapBox` and `overlapCapsule`, and `castRayAll` (every hit along a ray, nearest first: a shot through glass and a wall) and `castRays` (many rays in one call, from a `Float32Array`: a shotgun, sensors, a car's whiskers), 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
48
|
- **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
49
|
- **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
50
|
- **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.
|
|
@@ -74,6 +77,8 @@ export const soldiers = defineCharacterKind({
|
|
|
74
77
|
|
|
75
78
|
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
79
|
|
|
80
|
+
`moveAndSlide` slides along every surface it touches at once and answers no move only in a corner or straight at a wall (since 2.7.0; before, a walker along a wall or on ground far from the world's middle could be answered nothing for a step, on steps that turned on a tenth of a millimetre). A replay agrees with the game server only as far as the world does: a step that turns on a hair (whether a foot clears a step's edge, which side of a corner it goes) may go one way in a player's game and the other on the server, so a kind's own thresholds (a stamina running dry) want no tolerance, and its moves hold up best kept a skin's width off walls.
|
|
81
|
+
|
|
77
82
|
**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
83
|
|
|
79
84
|
**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.
|
|
@@ -149,7 +154,7 @@ Opened like every piece's ([`@zaisma/piece`](../piece)), and changed while playi
|
|
|
149
154
|
| `walkSpeedMPerSec`, `jumpHeightM` | the walking characters' speed and jump; a kind of the game's own reads them as `tuning` |
|
|
150
155
|
| `characterMassKg` | how heavy a character is beside what it pushes |
|
|
151
156
|
|
|
152
|
-
Online, whoever runs the world decides them. Hooks: `beforePutBack` (where something that fell out of the world comes back)
|
|
157
|
+
Online, whoever runs the world decides them. Hooks: `beforePutBack` (where something that fell out of the world comes back), `bodyHit` (for a thud or dust), `zoneEntered` and `zoneLeft`, and `jointBroke`. A character kind adds its own (`characterSettings`, `characterHooks`).
|
|
153
158
|
|
|
154
159
|
## Limits
|
|
155
160
|
|
|
@@ -162,12 +167,16 @@ What one world holds, each with what it costs at the limit (measured as below):
|
|
|
162
167
|
| 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
168
|
| Joints | 1,000 | |
|
|
164
169
|
| 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 |
|
|
170
|
+
| Zones, each of up to 8 shapes | 250 | every one full of things: 1.1 ms more a step |
|
|
171
|
+
| Body kinds with fields and a step of their own | 8 | 500 hover craft: 0.50 ms a step (plain bodies: 0.34) |
|
|
172
|
+
| Hits answered along one ray | 256 | through a heap: about 4 µs |
|
|
173
|
+
| Rays asked in one call | 65,536 | 0.50 µs a ray (0.63 one at a time) |
|
|
165
174
|
|
|
166
175
|
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
176
|
|
|
168
177
|
## Measured
|
|
169
178
|
|
|
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.
|
|
179
|
+
What the piece costs, measured on a MacBook (Apple M5, 10 cores) with other work running, on version 2.6.0 (December 4, 2026), and a game's own rules on 2.7.0 (December 5, 2026). `node --expose-gc scripts/physics-bench.mjs` in Zaisma's repository measures it again.
|
|
171
180
|
|
|
172
181
|
| What | Measured |
|
|
173
182
|
| --- | --- |
|
|
@@ -181,6 +190,11 @@ What the piece costs, measured on a MacBook (Apple M5, 10 cores) with other work
|
|
|
181
190
|
| 250 characters walking | 3.7 ms a step; standing still, 0.35 |
|
|
182
191
|
| A mesh of 500,000 triangles, built in tiles | 52 MB; 94 bytes a triangle |
|
|
183
192
|
| 8 players and 300 crates kept moving, to one player | 9.6 KB a second down, 0.6 up |
|
|
193
|
+
| 999 crates heaping under 250 zones, 3,030 crates inside them | 6.2 ms a step falling (5.0 without the zones), 6.0 heaped (4.9) |
|
|
194
|
+
| 10,000 rays in one call (`castRays`) | 0.50 µs a ray, 5 KB of garbage the call; one at a time 0.63 µs |
|
|
195
|
+
| A box cast, and every hit along a ray (16 on average) | about 4 µs each |
|
|
196
|
+
| 500 hover craft held up by a step of their own, two fields each | 0.50 ms a step (500 plain bodies falling: 0.34) |
|
|
197
|
+
| 500 bobs on ropes that could break | 0.76 ms a step (on ropes that can't: 0.70) |
|
|
184
198
|
|
|
185
199
|
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):
|
|
186
200
|
|
package/batch.js
CHANGED
|
@@ -16,6 +16,11 @@ export const CONTACT_FLOAT_COUNT = 10;
|
|
|
16
16
|
/** Whole numbers for one contact: its owner's tag, which triangle (or NO_TRIANGLE_INDEX) and which collider. */
|
|
17
17
|
export const CONTACT_NUMBER_COUNT = 3;
|
|
18
18
|
|
|
19
|
+
/** Floats for one of a ray's hits: how far (1) and the surface's normal there (3). */
|
|
20
|
+
export const RAY_HIT_FLOAT_COUNT = 4;
|
|
21
|
+
/** How many rays castRays hands the engine in one call: each is 6 floats in, and 4 floats and 3 whole numbers out, all before the awake bodies. */
|
|
22
|
+
export const RAYS_PER_CALL_COUNT = 256;
|
|
23
|
+
|
|
19
24
|
/** A tag's low bits: whose a body or a collider is. Its number is above them, from bit 8. */
|
|
20
25
|
export const BODY_TAG_NUMBER = 1;
|
|
21
26
|
export const CHARACTER_TAG_NUMBER = 2;
|
|
@@ -118,7 +123,7 @@ function tilesOf(pointsM, triangleIndices) {
|
|
|
118
123
|
if (pointsM[index] > highestM[axisIndex]) highestM[axisIndex] = pointsM[index];
|
|
119
124
|
}
|
|
120
125
|
// 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((
|
|
126
|
+
const [firstAxisIndex, secondAxisIndex] = [0, 1, 2].sort((firstIndex, secondIndex) => highestM[secondIndex] - lowestM[secondIndex] - (highestM[firstIndex] - lowestM[firstIndex]));
|
|
122
127
|
const sideTileCount = Math.ceil(Math.sqrt(triangleCount / MESH_TILE_TRIANGLE_COUNT));
|
|
123
128
|
const tileOf = (axisIndex, triangleIndex) => {
|
|
124
129
|
const middleM = (pointsM[triangleIndices[triangleIndex * 3] * 3 + axisIndex] + pointsM[triangleIndices[triangleIndex * 3 + 1] * 3 + axisIndex] + pointsM[triangleIndices[triangleIndex * 3 + 2] * 3 + axisIndex]) / 3;
|
package/bodies.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Body kinds with rules of their own: how a kind of body in a physics world behaves beyond what physics does to it.
|
|
2
|
+
// The world says what each kind of body is made of (its bodyKinds: shapes, mass, seats); a game gives a kind its own
|
|
3
|
+
// fields and a step, run once a fixed step for each body of that kind, the same in every player's game and on the
|
|
4
|
+
// game server: a boat that floats and is steered, an aircraft, a hover bike, a turret that tracks, a mine that
|
|
5
|
+
// counts down. The step pushes its body with forces (stepContext.addForce, addTorque), reads the world with the
|
|
6
|
+
// same queries a character kind's step has, and keeps what it must remember in the body's own fields, which go on
|
|
7
|
+
// the wire like the body's place.
|
|
8
|
+
import { startValueOf } from "./characters.js";
|
|
9
|
+
import { refuse } from "./declare.js";
|
|
10
|
+
|
|
11
|
+
/** The fields every body shares whatever its kind: a kind's own fields take other names. */
|
|
12
|
+
export const BODY_BASE_FIELD_NAMES = ["x", "y", "z", "rotation", "velocityX", "velocityY", "velocityZ", "spinX", "spinY", "spinZ", "bodyNumber", "bodyKindNumber", "layerNumber", "motionNumber", "steerNumber", "massKg"];
|
|
13
|
+
/** How many of a world's body kinds may have fields of their own: each is a kind of thing of its own on the wire. */
|
|
14
|
+
export const MAXIMUM_OWN_FIELD_BODY_KIND_COUNT = 8;
|
|
15
|
+
const BEHAVIOR_KEYS = ["stateFields", "step", "isSteppedAtRest"];
|
|
16
|
+
const FIELD_NAME_PATTERN = /^[a-z][A-Za-z0-9]{0,39}$/;
|
|
17
|
+
|
|
18
|
+
const isPlainObject = (given) => given !== null && typeof given === "object" && !Array.isArray(given);
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The rules a game gives its world's body kinds, checked: { <bodyKindName>: { stateFields, step, isSteppedAtRest } }.
|
|
22
|
+
*
|
|
23
|
+
* - stateFields: what the kind keeps of each body beyond the piece's own (its throttle, its fuel, its fuse), as
|
|
24
|
+
* @zaisma/net's fields: shared on the wire, so every side steps from the same. Left out, it keeps nothing.
|
|
25
|
+
* - step(body, driverInput, stepContext): one fixed step of one body, before the engine moves the world. body has
|
|
26
|
+
* id, bodyKindName, own (the kind's fields, change them in place), driverCharacterId (who sits in its first seat,
|
|
27
|
+
* or null) and rigidBody (the engine's). driverInput is that character's input this step, null with nobody
|
|
28
|
+
* there. stepContext has what a character kind's step has (the queries, bodyState, characterState, setJoint,
|
|
29
|
+
* tickDurationSec, tuning, isInCharge, isReplay, emit) and bodyMotion(body) (its place, rotation, speed and spin
|
|
30
|
+
* now), addForce(body, forceNewtons, atM) and addTorque(body, torqueNewtonMetres), which push for this one step.
|
|
31
|
+
* - isSteppedAtRest: true to step a body of this kind even while it lies at rest with nobody in its first seat (a
|
|
32
|
+
* mine's fuse, a turret that watches). By default such a body isn't stepped, and costs nothing.
|
|
33
|
+
*
|
|
34
|
+
* Answers the rules by the world's body kind numbers (a list with gaps), or null when there are none.
|
|
35
|
+
*/
|
|
36
|
+
export function defineBodyBehaviors(given, world) {
|
|
37
|
+
if (given === undefined) return null;
|
|
38
|
+
if (!isPlainObject(given)) refuse("bad_body_behavior", "bodies isn't an object of rules by body kind.", "bodies", 'Give { <a name in the world\'s bodyKinds>: { stateFields, step } }, or leave bodies out.');
|
|
39
|
+
const behaviors = [];
|
|
40
|
+
let ownFieldKindCount = 0;
|
|
41
|
+
for (const [bodyKindName, each] of Object.entries(given)) {
|
|
42
|
+
const what = `bodies.${bodyKindName}`;
|
|
43
|
+
const bodyKindNumber = world.bodyKinds.findIndex((bodyKind) => bodyKind.name === bodyKindName) + 1;
|
|
44
|
+
if (bodyKindNumber === 0) refuse("bad_body_behavior", `bodies names "${bodyKindName}", which isn't one of the world's bodyKinds.`, what, world.bodyKinds.length ? `Use one of: ${world.bodyKinds.map((bodyKind) => bodyKind.name).join(", ")}.` : "Declare the kind in the world's bodyKinds first, in the game and on its game server.");
|
|
45
|
+
if (!isPlainObject(each)) refuse("bad_body_behavior", `${what} isn't an object.`, what, "Give { stateFields, step }.");
|
|
46
|
+
for (const key of Object.keys(each)) if (!BEHAVIOR_KEYS.includes(key)) refuse("bad_body_behavior", `${what} has no "${key}".`, `${what}.${key}`, `It takes: ${BEHAVIOR_KEYS.join(", ")}.`);
|
|
47
|
+
const { stateFields = [], step, isSteppedAtRest = false } = each;
|
|
48
|
+
if (typeof step !== "function") refuse("bad_body_behavior", `${what}.step isn't a function.`, `${what}.step`, "Give step(body, driverInput, stepContext): one fixed step of one body of this kind.");
|
|
49
|
+
if (typeof isSteppedAtRest !== "boolean") refuse("bad_body_behavior", `${what}.isSteppedAtRest isn't true or false.`, `${what}.isSteppedAtRest`, "Give true to step a body of this kind while it lies at rest with nobody in its first seat, or leave it out.");
|
|
50
|
+
if (!Array.isArray(stateFields) || stateFields.some((field) => !isPlainObject(field) || typeof field.name !== "string" || !FIELD_NAME_PATTERN.test(field.name))) refuse("bad_body_behavior", `${what}.stateFields isn't a list of fields.`, `${what}.stateFields`, 'Give fields as @zaisma/net takes them, like [{ name: "throttleNumber", valueKind: "number", minimumNumber: -1, maximumNumber: 1, stepSizeNumber: 0.01 }], or leave it out.');
|
|
51
|
+
for (const field of stateFields) {
|
|
52
|
+
if (BODY_BASE_FIELD_NAMES.includes(field.name)) refuse("bad_body_behavior", `${what}.stateFields names "${field.name}", which every body has already.`, `${what}.stateFields`, `Give your own fields other names than: ${BODY_BASE_FIELD_NAMES.join(", ")}.`);
|
|
53
|
+
if (Array.isArray(field.fields) || field.isShared !== undefined) refuse("bad_body_behavior", `${what}.stateFields' "${field.name}" is a group of fields, or says isShared.`, `${what}.stateFields`, "Give plain fields, each shared on the wire: what only one game needs to remember, it keeps itself by the body's id.");
|
|
54
|
+
}
|
|
55
|
+
if (stateFields.length) ownFieldKindCount += 1;
|
|
56
|
+
if (ownFieldKindCount > MAXIMUM_OWN_FIELD_BODY_KIND_COUNT) refuse("bad_body_behavior", `More than ${MAXIMUM_OWN_FIELD_BODY_KIND_COUNT} body kinds have stateFields of their own.`, "bodies", `Give at most ${MAXIMUM_OWN_FIELD_BODY_KIND_COUNT} kinds their own fields: kinds that keep the same things can be one kind, and a kind with only a step counts for none.`);
|
|
57
|
+
const fieldNames = stateFields.map((field) => field.name);
|
|
58
|
+
behaviors[bodyKindNumber] = {
|
|
59
|
+
bodyKindName,
|
|
60
|
+
bodyKindNumber,
|
|
61
|
+
stateFields,
|
|
62
|
+
fieldNames,
|
|
63
|
+
step,
|
|
64
|
+
isSteppedAtRest,
|
|
65
|
+
/** Which kind of thing a body of this kind is on the wire: one of its own when it has fields of its own. */
|
|
66
|
+
entityKindName: stateFields.length ? `body_kind_${bodyKindNumber}` : "body",
|
|
67
|
+
/** Each body's own fields as they start. */
|
|
68
|
+
startOwn: () => Object.fromEntries(stateFields.map((field) => [field.name, startValueOf(field)])),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return behaviors.length ? behaviors : null;
|
|
72
|
+
}
|
package/characters.js
CHANGED
|
@@ -19,7 +19,7 @@ const NAME_PATTERN = /^[a-z][a-z0-9_]{0,39}$/;
|
|
|
19
19
|
const isPlainObject = (given) => given !== null && typeof given === "object" && !Array.isArray(given);
|
|
20
20
|
|
|
21
21
|
/** A field's value when nothing's said: its default, or what its kind starts at. */
|
|
22
|
-
function startValueOf(field) {
|
|
22
|
+
export function startValueOf(field) {
|
|
23
23
|
if (field.defaultValue !== undefined) return field.valueKind === "rotation" ? { ...field.defaultValue } : field.defaultValue;
|
|
24
24
|
if (field.valueKind === "boolean" || field.valueKind === "press") return false;
|
|
25
25
|
if (field.valueKind === "choice") return field.choices[0];
|
|
@@ -118,6 +118,8 @@ const TURN_SPEED_RAD_PER_SEC = 12;
|
|
|
118
118
|
const COYOTE_TICK_COUNT = 4;
|
|
119
119
|
/** How much faster running is than walking. */
|
|
120
120
|
const RUN_SPEED_PCT = 180;
|
|
121
|
+
/** How quickly a walker's legs answer what slows it (a zone's dampingNumber): it wades at 1 / (1 + dampingNumber x this) of its speed. */
|
|
122
|
+
const WADE_RESPONSE_SEC = 0.25;
|
|
121
123
|
|
|
122
124
|
/**
|
|
123
125
|
* Where the player pushes, in the world, from a stick and where they look: moveY forward along the view, moveX to
|
|
@@ -165,14 +167,18 @@ export function walkingCharacters() {
|
|
|
165
167
|
export function walkStep(character, input, stepContext) {
|
|
166
168
|
const { tickDurationSec, tuning } = stepContext;
|
|
167
169
|
const wish = wishOf(input, stepWish);
|
|
168
|
-
const speedMPerSec = tuning.walkSpeedMPerSec * (input.isRunning ? RUN_SPEED_PCT / 100 : 1);
|
|
169
170
|
const velocity = character.velocity;
|
|
171
|
+
// What the zones it stands in do to it: their pull, push and slowing (wind, water, a room without gravity).
|
|
172
|
+
const zoneEffects = stepContext.zoneEffectsOf?.(character) ?? null;
|
|
173
|
+
// Its legs work against what slows it: it wades at a share of its speed, the same at any step rate.
|
|
174
|
+
const speedMPerSec = (tuning.walkSpeedMPerSec * (input.isRunning ? RUN_SPEED_PCT / 100 : 1)) / (1 + (zoneEffects?.dampingNumber ?? 0) * WADE_RESPONSE_SEC);
|
|
170
175
|
// Standing still on what never moves, with nothing asked: this step would leave it exactly here, so it's skipped,
|
|
171
176
|
// 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;
|
|
177
|
+
if (!zoneEffects && wish.lengthNumber === 0 && !input.jump && character.isGrounded && velocity.x === 0 && velocity.y === 0 && velocity.z === 0 && stepContext.isRestingOnLevel?.(character)) return;
|
|
173
178
|
const accelerationMPerSecPerSec = character.isGrounded ? GROUND_ACCELERATION_M_PER_SEC_PER_SEC : AIR_ACCELERATION_M_PER_SEC_PER_SEC;
|
|
174
179
|
// In the air with nothing asked, a walker keeps the speed it left the ground with.
|
|
175
|
-
|
|
180
|
+
const isWalking = character.isGrounded || wish.lengthNumber > 0.01;
|
|
181
|
+
if (isWalking) {
|
|
176
182
|
const missingX = wish.x * speedMPerSec - velocity.x;
|
|
177
183
|
const missingZ = wish.z * speedMPerSec - velocity.z;
|
|
178
184
|
const missingMPerSec = Math.hypot(missingX, missingZ);
|
|
@@ -183,7 +189,15 @@ export function walkStep(character, input, stepContext) {
|
|
|
183
189
|
if (input.jump && character.airTickCount <= COYOTE_TICK_COUNT && velocity.y <= tuning.jumpSpeedMPerSec * 0.5) {
|
|
184
190
|
velocity.y = tuning.jumpSpeedMPerSec;
|
|
185
191
|
character.airTickCount = COYOTE_TICK_COUNT + 1;
|
|
186
|
-
} else velocity.y -= tuning.gravityMPerSecPerSec * tickDurationSec;
|
|
192
|
+
} else velocity.y -= ((tuning.gravityMPerSecPerSec * (zoneEffects?.gravityPct ?? 100)) / 100) * tickDurationSec;
|
|
193
|
+
if (zoneEffects) {
|
|
194
|
+
// What its legs don't drive (its fall, and its drift through the air) is slowed as a body's is.
|
|
195
|
+
const slowedNumber = 1 / (1 + zoneEffects.dampingNumber * tickDurationSec);
|
|
196
|
+
const driftSlowedNumber = isWalking ? 1 : slowedNumber;
|
|
197
|
+
velocity.x = (velocity.x + zoneEffects.pushMPerSecPerSec.x * tickDurationSec) * driftSlowedNumber;
|
|
198
|
+
velocity.y = (velocity.y + zoneEffects.pushMPerSecPerSec.y * tickDurationSec) * slowedNumber;
|
|
199
|
+
velocity.z = (velocity.z + zoneEffects.pushMPerSecPerSec.z * tickDurationSec) * driftSlowedNumber;
|
|
200
|
+
}
|
|
187
201
|
stepDesiredM.x = velocity.x * tickDurationSec;
|
|
188
202
|
stepDesiredM.y = velocity.y * tickDurationSec;
|
|
189
203
|
stepDesiredM.z = velocity.z * tickDurationSec;
|
package/declare.js
CHANGED
|
@@ -48,7 +48,7 @@ export const WORLD_REACH_M = 10_000;
|
|
|
48
48
|
/** How heavy a cubic metre of a body is when it doesn't say its mass: furniture is mostly air. */
|
|
49
49
|
export const DEFAULT_DENSITY_KG_PER_M3_NUMBER = 250;
|
|
50
50
|
|
|
51
|
-
const WORLD_KEYS = ["bodies", "bodyKinds", "character", "characterSizes", "playerCharacterMode", "startPositionsM", "fallOutHeightM", "collisionLayers", "surfaceNames", "joints", "substepCount", "groundReachM"];
|
|
51
|
+
const WORLD_KEYS = ["bodies", "bodyKinds", "character", "characterSizes", "playerCharacterMode", "startPositionsM", "fallOutHeightM", "collisionLayers", "surfaceNames", "joints", "substepCount", "groundReachM", "zones"];
|
|
52
52
|
const BODY_KEYS = ["id", "bodyKindName", "motionKind", "positionM", "rotationDeg", "massKg", "bouncePct", "gripPct", "linearDampingNumber", "angularDampingNumber", "canBeGrabbed", "shapes", "collisionLayerName", "wheels", "vehicle", "seats", "timetable"];
|
|
53
53
|
const BODY_KIND_KEYS = ["massKg", "bouncePct", "gripPct", "linearDampingNumber", "angularDampingNumber", "canBeGrabbed", "shapes", "collisionLayerName", "wheels", "vehicle", "seats"];
|
|
54
54
|
const WHEEL_KEYS = ["positionM", "radiusM", "suspensionRestM", "suspensionTravelM", "isSteered", "isDriven"];
|
|
@@ -69,7 +69,23 @@ export const MAXIMUM_TIMETABLE_STOP_COUNT = 32;
|
|
|
69
69
|
const TIMETABLE_STEPS_PER_M = 1000;
|
|
70
70
|
/** The longest a trip between two stops, or a wait at one, lasts, in seconds. */
|
|
71
71
|
export const MAXIMUM_TIMETABLE_DURATION_SEC = 3600;
|
|
72
|
-
const JOINT_KEYS = ["id", "jointKind", "bodyId", "otherBodyId", "anchorM", "otherAnchorM", "axis", "minimumNumber", "maximumNumber", "restLengthM", "stiffnessNumber", "dampingNumber"];
|
|
72
|
+
const JOINT_KEYS = ["id", "jointKind", "bodyId", "otherBodyId", "anchorM", "otherAnchorM", "axis", "minimumNumber", "maximumNumber", "restLengthM", "stiffnessNumber", "dampingNumber", "motor", "breakForceNewtons"];
|
|
73
|
+
const MOTOR_KEYS = ["motorKind", "targetNumber", "maximumForceNumber", "stiffnessNumber", "dampingNumber"];
|
|
74
|
+
/** What a joint's motor holds: a speed (a wheel that turns, a lift's winch) or a position (a door that closes itself, a crane's arm). */
|
|
75
|
+
export const MOTOR_KINDS = ["speed", "position"];
|
|
76
|
+
/** The furthest a motor's target goes either way: radians (a second) about a hinge, metres (a second) along a slider. */
|
|
77
|
+
export const MAXIMUM_MOTOR_TARGET_NUMBER = 10_000;
|
|
78
|
+
const ZONE_KEYS = ["id", "shapes", "positionM", "rotationDeg", "bodyId", "collisionLayerNames", "gravityPct", "pushMPerSecPerSec", "dampingNumber", "isEnabled"];
|
|
79
|
+
const ZONE_SHAPE_KEYS = ["shapeKind", "sizeM", "radiusM", "heightM", "positionM", "rotationDeg"];
|
|
80
|
+
/** The shapes a zone is made of, in the order the engine numbers them. */
|
|
81
|
+
export const ZONE_SHAPE_KINDS = ["ball", "capsule", "box", "cylinder"];
|
|
82
|
+
/** A world holds this many zones, each of up to 8 shapes. */
|
|
83
|
+
export const MAXIMUM_ZONE_COUNT = 250;
|
|
84
|
+
const MAXIMUM_ZONE_SHAPE_COUNT = 8;
|
|
85
|
+
/** The most a zone turns gravity (in percent of it, either way), pushes (metres a second each second) and slows. */
|
|
86
|
+
const MAXIMUM_ZONE_GRAVITY_PCT = 1000;
|
|
87
|
+
const MAXIMUM_ZONE_PUSH_M_PER_SEC_PER_SEC = 1000;
|
|
88
|
+
const MAXIMUM_ZONE_DAMPING_NUMBER = 100;
|
|
73
89
|
const COLLISION_LAYER_KEYS = ["touches"];
|
|
74
90
|
const DATA_PATH_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9_./-]{0,199}$/;
|
|
75
91
|
const BODY_KIND_NAME_PATTERN = /^[a-z][a-z0-9_]{0,39}$/;
|
|
@@ -597,6 +613,83 @@ export function checkJoint(given, what, bodyIdOf = () => true) {
|
|
|
597
613
|
restLengthM: numberOf("restLengthM", 0, 0, WORLD_REACH_M),
|
|
598
614
|
stiffnessNumber: numberOf("stiffnessNumber", 2000, 0, 1e9),
|
|
599
615
|
dampingNumber: numberOf("dampingNumber", 100, 0, 1e9),
|
|
616
|
+
motor: motorOf(given.motor, jointKind, `${what}.motor`),
|
|
617
|
+
// How hard it pulls or pushes its ends before it breaks. Left out, it never breaks.
|
|
618
|
+
breakForceNewtons: given.breakForceNewtons === undefined ? null : numberOf("breakForceNewtons", 0, 0.001, 1e12),
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** A joint's motor, checked: what turns a hinge or slides a slider by itself. Null for a joint without one. */
|
|
623
|
+
function motorOf(given, jointKind, what) {
|
|
624
|
+
if (given === undefined) return null;
|
|
625
|
+
if (jointKind !== "hinge" && jointKind !== "slider") refuse("bad_joint", `${what} is on a ${jointKind} joint.`, what, "Only a hinge (it turns about its axis) and a slider (it slides along its axis) take a motor.");
|
|
626
|
+
refuseUnknownKeys(given, MOTOR_KEYS, "bad_joint", what);
|
|
627
|
+
if (!MOTOR_KINDS.includes(given.motorKind)) refuse("bad_joint", `${what}.motorKind is ${JSON.stringify(given.motorKind)}.`, `${what}.motorKind`, `Use: ${MOTOR_KINDS.join(", ")}.`);
|
|
628
|
+
const numberOf = (key, fallbackNumber, minimumNumber, maximumNumber) => {
|
|
629
|
+
if (given[key] === undefined) return fallbackNumber;
|
|
630
|
+
if (!isFiniteNumber(given[key]) || given[key] < minimumNumber || given[key] > maximumNumber) refuse("bad_joint", `${what}.${key} is ${JSON.stringify(given[key])}.`, `${what}.${key}`, `Give a number from ${minimumNumber} to ${maximumNumber}, or leave it out.`);
|
|
631
|
+
return given[key];
|
|
632
|
+
};
|
|
633
|
+
const isSpeed = given.motorKind === "speed";
|
|
634
|
+
return {
|
|
635
|
+
motorKind: given.motorKind,
|
|
636
|
+
targetNumber: numberOf("targetNumber", 0, -MAXIMUM_MOTOR_TARGET_NUMBER, MAXIMUM_MOTOR_TARGET_NUMBER),
|
|
637
|
+
maximumForceNumber: given.maximumForceNumber === undefined ? null : numberOf("maximumForceNumber", 0, 0, 1e12),
|
|
638
|
+
// A speed is held by damping alone; a position by a spring and its damping.
|
|
639
|
+
stiffnessNumber: isSpeed ? 0 : numberOf("stiffnessNumber", 2000, 0, 1e9),
|
|
640
|
+
dampingNumber: numberOf("dampingNumber", isSpeed ? 10_000 : 200, 0, 1e9),
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** One shape of a zone, checked: as the engine takes it (its kind's number and three lengths), placed in the zone. */
|
|
645
|
+
function zoneShapeOf(given, what) {
|
|
646
|
+
refuseUnknownKeys(given, ZONE_SHAPE_KEYS, "bad_zone", what);
|
|
647
|
+
const { shapeKind } = given;
|
|
648
|
+
if (!ZONE_SHAPE_KINDS.includes(shapeKind)) refuse("bad_zone", `${what}.shapeKind is ${JSON.stringify(shapeKind)}.`, `${what}.shapeKind`, `Use: ${ZONE_SHAPE_KINDS.join(", ")}.`);
|
|
649
|
+
const takes = { box: ["sizeM"], ball: ["radiusM"], capsule: ["radiusM", "heightM"], cylinder: ["radiusM", "heightM"] }[shapeKind];
|
|
650
|
+
for (const key of ["sizeM", "radiusM", "heightM"]) if (takes.includes(key) !== (given[key] !== undefined)) refuse("bad_zone", takes.includes(key) ? `${what} is a ${shapeKind} with no ${key}.` : `${what} is a ${shapeKind}, which has no ${key}.`, `${what}.${key}`, `A ${shapeKind} takes: ${takes.join(", ")}.`);
|
|
651
|
+
let lengthsM;
|
|
652
|
+
if (shapeKind === "box") {
|
|
653
|
+
const sizeM = pointOf(given.sizeM, null, "bad_zone", `${what}.sizeM`);
|
|
654
|
+
if (!(sizeM.x > 0 && sizeM.y > 0 && sizeM.z > 0)) refuse("bad_zone", `${what}.sizeM is ${JSON.stringify(given.sizeM)}.`, `${what}.sizeM`, "Give how wide (x), tall (y) and deep (z) the box is, each above 0, in metres.");
|
|
655
|
+
lengthsM = [sizeM.x / 2, sizeM.y / 2, sizeM.z / 2];
|
|
656
|
+
} else {
|
|
657
|
+
const radiusM = lengthOf(given.radiusM, "bad_zone", `${what}.radiusM`);
|
|
658
|
+
if (shapeKind === "ball") lengthsM = [radiusM, 0, 0];
|
|
659
|
+
else {
|
|
660
|
+
const heightM = lengthOf(given.heightM, "bad_zone", `${what}.heightM`);
|
|
661
|
+
if (shapeKind === "capsule" && heightM < radiusM * 2) refuse("bad_zone", `${what}.heightM is ${heightM}, less than twice its radius.`, `${what}.heightM`, "A capsule's height is its whole height, round ends included: at least twice its radius.");
|
|
662
|
+
lengthsM = [radiusM, shapeKind === "capsule" ? heightM / 2 - radiusM : heightM / 2, 0];
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
return { shapeKind, shapeKindNumber: ZONE_SHAPE_KINDS.indexOf(shapeKind), lengthsM, positionM: pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_zone", `${what}.positionM`), rotation: rotationOf(given.rotationDeg, "bad_zone", `${what}.rotationDeg`) };
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** A zone, checked: a place that tells who's in it, and may pull, push and slow what is. */
|
|
669
|
+
function checkZone(given, what, { bodyById, layerNames }) {
|
|
670
|
+
refuseUnknownKeys(given, ZONE_KEYS, "bad_zone", what);
|
|
671
|
+
const { id, shapes, bodyId = null, collisionLayerNames = null, gravityPct = 100, dampingNumber = 0, isEnabled = true } = given;
|
|
672
|
+
if (typeof id !== "string" || !ID_PATTERN.test(id)) refuse("bad_zone", `${what}.id is ${JSON.stringify(id)}.`, `${what}.id`, 'Give 1 to 64 letters, digits, "_", ".", ":" or "-", like "capture:a".');
|
|
673
|
+
if (!Array.isArray(shapes) || !shapes.length || shapes.length > MAXIMUM_ZONE_SHAPE_COUNT) refuse("bad_zone", `${what}.shapes isn't a list of 1 to ${MAXIMUM_ZONE_SHAPE_COUNT} shapes.`, `${what}.shapes`, 'Give the room it takes, like [{ shapeKind: "box", sizeM: { x: 6, y: 3, z: 6 } }].');
|
|
674
|
+
if (bodyId !== null && !bodyById.has(bodyId)) refuse("bad_zone", `${what}.bodyId is ${JSON.stringify(bodyId)}.`, `${what}.bodyId`, "Give the id of one of the world's bodies for the zone to ride (its place is then in that body's own space), or leave it out.");
|
|
675
|
+
if (collisionLayerNames !== null && (!Array.isArray(collisionLayerNames) || !collisionLayerNames.length || collisionLayerNames.some((name) => !layerNames.includes(name)))) refuse("bad_zone", `${what}.collisionLayerNames is ${JSON.stringify(collisionLayerNames)}.`, `${what}.collisionLayerNames`, `Give which of the world's collisionLayers it counts (${layerNames.join(", ")}), or leave it out for all of them.`);
|
|
676
|
+
if (!isFiniteNumber(gravityPct) || Math.abs(gravityPct) > MAXIMUM_ZONE_GRAVITY_PCT) refuse("bad_zone", `${what}.gravityPct is ${JSON.stringify(gravityPct)}.`, `${what}.gravityPct`, `Give how much of gravity pulls in the zone, from -${MAXIMUM_ZONE_GRAVITY_PCT} to ${MAXIMUM_ZONE_GRAVITY_PCT}: 100 (the default) is all of it, 0 none, below 0 lifts.`);
|
|
677
|
+
const pushMPerSecPerSec = pointOf(given.pushMPerSecPerSec, { x: 0, y: 0, z: 0 }, "bad_zone", `${what}.pushMPerSecPerSec`);
|
|
678
|
+
if (Math.hypot(pushMPerSecPerSec.x, pushMPerSecPerSec.y, pushMPerSecPerSec.z) > MAXIMUM_ZONE_PUSH_M_PER_SEC_PER_SEC) refuse("bad_zone", `${what}.pushMPerSecPerSec is ${JSON.stringify(given.pushMPerSecPerSec)}.`, `${what}.pushMPerSecPerSec`, `Give how it speeds things up, in metres a second each second, up to ${MAXIMUM_ZONE_PUSH_M_PER_SEC_PER_SEC} long.`);
|
|
679
|
+
if (!isFiniteNumber(dampingNumber) || dampingNumber < 0 || dampingNumber > MAXIMUM_ZONE_DAMPING_NUMBER) refuse("bad_zone", `${what}.dampingNumber is ${JSON.stringify(dampingNumber)}.`, `${what}.dampingNumber`, `Give how quickly speed and spin die away in the zone, 0 (not at all, the default) to ${MAXIMUM_ZONE_DAMPING_NUMBER}: water is about 2.`);
|
|
680
|
+
if (typeof isEnabled !== "boolean") refuse("bad_zone", `${what}.isEnabled is ${JSON.stringify(isEnabled)}.`, `${what}.isEnabled`, "Give false for a zone that starts switched off (setZone switches it), or leave it out.");
|
|
681
|
+
return {
|
|
682
|
+
id,
|
|
683
|
+
shapes: shapes.map((shape, shapeIndex) => zoneShapeOf(shape, `${what}.shapes[${shapeIndex}]`)),
|
|
684
|
+
positionM: pointOf(given.positionM, { x: 0, y: 0, z: 0 }, "bad_zone", `${what}.positionM`),
|
|
685
|
+
rotation: rotationOf(given.rotationDeg, "bad_zone", `${what}.rotationDeg`),
|
|
686
|
+
bodyId,
|
|
687
|
+
collisionLayerNames: collisionLayerNames === null ? null : [...collisionLayerNames],
|
|
688
|
+
gravityPct,
|
|
689
|
+
pushMPerSecPerSec,
|
|
690
|
+
dampingNumber,
|
|
691
|
+
hasEffects: gravityPct !== 100 || dampingNumber !== 0 || pushMPerSecPerSec.x !== 0 || pushMPerSecPerSec.y !== 0 || pushMPerSecPerSec.z !== 0,
|
|
692
|
+
isEnabled,
|
|
600
693
|
};
|
|
601
694
|
}
|
|
602
695
|
|
|
@@ -646,7 +739,7 @@ export function definePhysicsWorld(given = {}) {
|
|
|
646
739
|
ids.add(checked.id);
|
|
647
740
|
return checked;
|
|
648
741
|
});
|
|
649
|
-
const fixedBodyCount = checkedBodies.reduce((
|
|
742
|
+
const fixedBodyCount = checkedBodies.reduce((fixedCount, body) => fixedCount + (body.motionKind === "fixed" ? 1 : 0), 0);
|
|
650
743
|
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
744
|
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.');
|
|
652
745
|
const { surfaceNames = [] } = given;
|
|
@@ -679,18 +772,27 @@ export function definePhysicsWorld(given = {}) {
|
|
|
679
772
|
const ownCharacter = checkCharacterSize(character, "world.character", { heightM: 1.5, radiusM: 0.28, stepHeightM: 0.35, maximumSlopeDeg: 50 }, CHARACTER_KEYS);
|
|
680
773
|
const { characterSizes = [] } = given;
|
|
681
774
|
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((
|
|
775
|
+
const checkedCharacterSizes = characterSizes.map((characterSize, sizeIndex) => {
|
|
683
776
|
const what = `world.characterSizes[${sizeIndex}]`;
|
|
684
|
-
if (!isPlainObject(
|
|
685
|
-
if (characterSizes.findIndex((other) => other?.name ===
|
|
686
|
-
return { name:
|
|
777
|
+
if (!isPlainObject(characterSize) || typeof characterSize.name !== "string" || !BODY_KIND_NAME_PATTERN.test(characterSize.name)) refuse("bad_world", `${what} has no name.`, `${what}.name`, 'Give each characterSize a name in lowercase words joined by underscores, like "crouched".');
|
|
778
|
+
if (characterSizes.findIndex((other) => other?.name === characterSize.name) !== sizeIndex) refuse("bad_world", `world.characterSizes names "${characterSize.name}" twice.`, `${what}.name`, "Give each characterSize its own name.");
|
|
779
|
+
return { name: characterSize.name, ...checkCharacterSize(characterSize, what, ownCharacter, CHARACTER_SIZE_KEYS) };
|
|
780
|
+
});
|
|
781
|
+
const { zones = [] } = given;
|
|
782
|
+
if (!Array.isArray(zones) || zones.length > MAXIMUM_ZONE_COUNT) refuse("bad_world", `world.zones isn't a list of up to ${MAXIMUM_ZONE_COUNT} zones.`, "world.zones", 'Give zones like [{ id: "capture:a", positionM: { x: 0, y: 1.5, z: 0 }, shapes: [{ shapeKind: "box", sizeM: { x: 6, y: 3, z: 6 } }] }].');
|
|
783
|
+
const bodyById = new Map(checkedBodies.map((body) => [body.id, body]));
|
|
784
|
+
const checkedZones = zones.map((zone, zoneIndex) => {
|
|
785
|
+
const checked = checkZone(zone, `world.zones[${zoneIndex}]`, { bodyById, layerNames });
|
|
786
|
+
if (zones.findIndex((other) => other?.id === checked.id) !== zoneIndex) refuse("bad_world", `world.zones names "${checked.id}" twice.`, `world.zones[${zoneIndex}].id`, "Give each zone its own id.");
|
|
787
|
+
return checked;
|
|
687
788
|
});
|
|
688
789
|
if (!PLAYER_CHARACTER_MODES.includes(playerCharacterMode)) refuse("bad_world", `world.playerCharacterMode is ${JSON.stringify(playerCharacterMode)}.`, "world.playerCharacterMode", `Use: ${PLAYER_CHARACTER_MODES.join(", ")}.`);
|
|
689
790
|
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.");
|
|
690
791
|
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.");
|
|
691
792
|
return {
|
|
692
793
|
bodies: checkedBodies,
|
|
693
|
-
bodyById
|
|
794
|
+
bodyById,
|
|
795
|
+
zones: checkedZones,
|
|
694
796
|
fixedBodyIds: checkedBodies.filter((body) => body.motionKind === "fixed").map((body) => body.id),
|
|
695
797
|
bodyKinds,
|
|
696
798
|
character: ownCharacter,
|