@zaisma/physics 0.0.0-stage → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.txt ADDED
@@ -0,0 +1,93 @@
1
+ # PolyForm Shield License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/shield/1.0.0>
4
+
5
+ ## Acceptance
6
+
7
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
12
+
13
+ ## Distribution License
14
+
15
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
16
+
17
+ ## Notices
18
+
19
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
20
+
21
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
22
+
23
+ ## Changes and New Works License
24
+
25
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
26
+
27
+ ## Patent License
28
+
29
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
30
+
31
+ ## Noncompete
32
+
33
+ Any purpose is a permitted purpose, except for providing any product that competes with the software or any product the licensor or any of its affiliates provides using the software.
34
+
35
+ ## Competition
36
+
37
+ Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if they're written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge. If you market a product as a practical substitute for the software or another product, it definitely competes.
38
+
39
+ ## New Products
40
+
41
+ If you are using the software to provide a product that does not compete, but the licensor or any of its affiliates brings your product into competition by providing a new version of the software or another product using the software, you may continue using versions of the software available under these terms beforehand to provide your competing product, but not any later versions.
42
+
43
+ ## Discontinued Products
44
+
45
+ You may begin using the software to compete with a product or service that the licensor or any of its affiliates has stopped providing, unless the licensor includes a plain-text line beginning with `Licensor Line of Business:` with the software that mentions that line of business. For example:
46
+
47
+ > Licensor Line of Business: YoyodyneCMS Content Management System (http://example.com/cms)
48
+
49
+ ## Sales of Business
50
+
51
+ If the licensor or any of its affiliates sells a line of business developing the software or using the software to provide a product, the buyer can also enforce [Noncompete](#noncompete) for that product.
52
+
53
+ ## Fair Use
54
+
55
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
56
+
57
+ ## No Other Rights
58
+
59
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
60
+
61
+ ## Patent Defense
62
+
63
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
64
+
65
+ ## Violations
66
+
67
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
68
+
69
+ ## No Liability
70
+
71
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
72
+
73
+ ## Definitions
74
+
75
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
76
+
77
+ A **product** can be a good or service, or a combination of them.
78
+
79
+ **You** refers to the individual or entity agreeing to these terms.
80
+
81
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all its affiliates.
82
+
83
+ **Affiliates** means the other organizations than an organization has control over, is under the control of, or is under common control with.
84
+
85
+ **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
86
+
87
+ **Your licenses** are all the licenses granted to you for the software under these terms.
88
+
89
+ **Use** means anything you do with the software requiring one of your licenses.
90
+
91
+ Required Notice: Copyright (c) 2026 Zaisma LLC (https://zaisma.com)
92
+
93
+ Versions of @zaisma/physics before 2.4.0 were published under the MIT License, and stay under it.
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # @zaisma/physics
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Physics that works as it's added, alone and online, for every kind of game: a shooter's arena, a valley you farm, a race, a fort you build, a room you move furniture in. One world of **bodies**, **ground**, **joints**, **vehicles** and **characters**, and every player sees it the same.
4
+
5
+ ```
6
+ npx @zaisma/cli pieces add @zaisma/physics
7
+ ```
8
+
9
+ It brings the online core ([`@zaisma/net`](../net)) with it. The engine under it is [Rapier](https://rapier.rs), shipped inside the piece: about 0.6 MB as Zaisma serves it. Party characters that grab, carry and throw are a piece on top of it, [`@zaisma/physics-party`](../physics-party).
10
+
11
+ Version 2 makes the world a foundation. A game on 1.x keeps working and moves when it chooses: its characters and the `feel` setting are now `@zaisma/physics-party`'s.
12
+
13
+ ## A world
14
+
15
+ A world is data, in a file of its own, the same in a game and on its game server:
16
+
17
+ ```js
18
+ // world.js
19
+ import { definePhysicsWorld } from "./pieces/@zaisma/physics/world.js";
20
+
21
+ export const valley = definePhysicsWorld({
22
+ bodies: [
23
+ { id: "ground", motionKind: "fixed", shapes: [{ shapeKind: "heightfield", dataPath: "levels/valley-heights.bin", rowCount: 1501, columnCount: 1501, cellSizeM: 1 }] },
24
+ { id: "gate", positionM: { x: 40, y: 1, z: 0 }, massKg: 30, shapes: [{ shapeKind: "box", sizeM: { x: 2, y: 2, z: 0.1 } }] },
25
+ { id: "lift", motionKind: "kinematic", positionM: { x: 0, y: 0, z: 20 }, shapes: [{ shapeKind: "box", sizeM: { x: 3, y: 0.2, z: 3 } }] },
26
+ { id: "car:1", bodyKindName: "car", positionM: { x: 10, y: 2, z: 0 } },
27
+ ],
28
+ bodyKinds: { car: { massKg: 900, shapes: [{ shapeKind: "box", sizeM: { x: 1.8, y: 0.6, z: 4 } }], collisionLayerName: "vehicle", wheels: [/* positionM, radiusM, isSteered, isDriven */], seats: [{ positionM: { x: -0.4, y: 0.3, z: 0 } }] } },
29
+ joints: [{ id: "gate:hinge", jointKind: "hinge", bodyId: "gate", anchorM: { x: -1, y: 0, z: 0 }, otherAnchorM: { x: 39, y: 1, z: 0 }, axis: { x: 0, y: 1, z: 0 } }],
30
+ collisionLayers: { world: { touches: ["world", "body", "character", "vehicle"] }, body: { touches: ["world", "body", "character", "vehicle"] }, character: { touches: ["world", "body"] }, vehicle: { touches: ["world", "body", "vehicle"] } },
31
+ startPositionsM: [{ x: 0, y: 2, z: 0 }],
32
+ });
33
+ ```
34
+
35
+ - **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.
36
+ - **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.
37
+ - **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.
38
+ - **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.
39
+ - **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()`.
40
+ - **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.
41
+ - **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.
42
+ - **Queries:** `castRay`, `castBall`, `castCapsule`, `overlapBall` and `overlapCapsule`, answering whose body or character, where, and the surface's normal; a capsule's contacts say how deep it is in each, to push a game's own movement out of walls. A cast writes into an object the game keeps when given one (`castRay(query, hit)`), so thousands a second make nothing new. `castBall` and `castCapsule` with `isStoppedAtPenetration: false` move out of what they start touching (a camera pressed to a wall).
43
+ - **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 groups the world switches on and off (`setTriangleGroup`: a door that opens, a bridge that falls).
44
+ - **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.
45
+
46
+ ## Characters
47
+
48
+ A world's characters move by a **character kind**. The piece's own (`walkingCharacters`, the default) walks, runs, steps up ledges, holds to slopes it can climb and jumps; a game's own kind is its rules, on the same tools:
49
+
50
+ ```js
51
+ import { defineCharacterKind, walkStep } from "./pieces/@zaisma/physics/index.js";
52
+
53
+ export const soldiers = defineCharacterKind({
54
+ name: "soldier",
55
+ stateFields: [{ name: "fuelPct", valueKind: "number", minimumNumber: 0, maximumNumber: 100, stepSizeNumber: 0.1, defaultValue: 100 }],
56
+ inputFields: [
57
+ { name: "moveX", valueKind: "number", minimumNumber: -1, maximumNumber: 1, stepSizeNumber: 0.01 },
58
+ { name: "moveY", valueKind: "number", minimumNumber: -1, maximumNumber: 1, stepSizeNumber: 0.01 },
59
+ { name: "viewYawRad", valueKind: "angle", idleMode: "hold" },
60
+ { name: "isBoosting", valueKind: "boolean" },
61
+ ],
62
+ step(character, input, stepContext) {
63
+ if (input.isBoosting && character.own.fuelPct > 0) {
64
+ character.velocity.y = Math.max(character.velocity.y, 3);
65
+ character.own.fuelPct -= 50 * stepContext.tickDurationSec;
66
+ }
67
+ walkStep(character, input, stepContext); // or stepContext.moveAndSlide(character, movedM) for movement of its own
68
+ },
69
+ });
70
+ ```
71
+
72
+ 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`).
73
+
74
+ ## Characters over a level
75
+
76
+ 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:
77
+
78
+ ```js
79
+ const soldiers = net.use(levelCharactersKind(arena, { characters: soldierKind, eventNames: ["shot"] }));
80
+ soldiers.setInput({ moveX, moveY, viewYawRad, fire });
81
+ const drawn = soldiers.drawnCharacter(soldierId); // feet, facing, speed, the kind's own fields
82
+ const hit = soldiers.castRay({ fromM, directionM, maximumDistanceM: 200 }, keptHit);
83
+ // on the game server: soldiers.onServer(state, room).stateAt(targetId, viewTickNumber(shooterId)), setTriangleGroup(3, false)
84
+ ```
85
+
86
+ It's @zaisma/net's characters underneath, so everything they do is there (`audience: "own"`, `othersStepSizeNumber`, `roomFields`, `emit`). Nothing in the level moves and characters walk through each other; one copy of the level serves every room a game server runs, and each room switches its own triangle groups. The settings are declared alike in the game and on the game server.
87
+
88
+ ## Alone
89
+
90
+ ```js
91
+ import { createPhysics, loadPhysics, loadPhysicsData } from "./pieces/@zaisma/physics/index.js";
92
+ import { valley } from "./world.js";
93
+
94
+ await loadPhysics(); // fetches and starts the engine, once
95
+ await loadPhysicsData(valley); // the world's data files, from the game's folder
96
+ const physics = createPhysics(valley, { characters: soldiers });
97
+
98
+ function frame() {
99
+ physics.setInput({ moveX: stick.x, moveY: stick.y, viewYawRad, isBoosting: buttons.isHeld("boost") });
100
+ physics.update(); // runs the fixed steps that are due
101
+ for (const bodyId of physics.bodyIds()) physics.applyTo(meshes.get(bodyId), bodyId);
102
+ const drawn = physics.drawnCharacter(physics.ownCharacterId); // positionM, facingYawRad, isOnGround, rideBodyId, own ...
103
+ requestAnimationFrame(frame);
104
+ }
105
+ ```
106
+
107
+ ## Online
108
+
109
+ The same game through a room, as a world on the online core. A game writes nothing for the sync:
110
+
111
+ ```js
112
+ const net = createNet(room); // with a game server: createNet(room, { authorityKind: "server" })
113
+ const physics = net.use(physicsKind(valley, { characters: soldiers }));
114
+ // setInput and draw as alone; net.update() in place of physics.update()
115
+ ```
116
+
117
+ - **A player's own move answers at once,** and when the room's word differs, the game goes back to it and runs the steps since again; what's drawn eases there. Everything a replay needs (motion kinds, layers, joints, wheels, seats, a kind's own fields) is in the state, so going back never drifts.
118
+ - **Other players are drawn where they are,** and what they ride or push with them.
119
+ - **A body at rest costs nothing:** said once where it stopped, then nothing until it moves. Hundreds of resting blocks send nothing.
120
+ - **On the relay** the host's game runs the world, the next host's carrying on; **with a game server** the server runs it, the same file:
121
+
122
+ ```js
123
+ // zaisma-server/index.js: world.js and the character kind's file copied here as they are
124
+ import { defineNetServer } from "./pieces/@zaisma/net/server.js";
125
+ import { physicsKind } from "./pieces/@zaisma/physics/server.js";
126
+ import { valley } from "./world.js";
127
+
128
+ const physics = physicsKind(valley, { characters: soldiers });
129
+ export default defineNetServer({ kinds: [physics], ticksPerSec: 30 });
130
+ ```
131
+
132
+ `physics.onServer(state, room)` gives the game server's code the world: `bodyState`, `setBody`, `addBody`, `removeBody` (an id freed is free again at once), `addCharacter`, `setCharacter`, `seatCharacter`, joints, queries, and a bot's `setInput`.
133
+
134
+ ## Settings and hooks
135
+
136
+ Opened like every piece's ([`@zaisma/piece`](../piece)), and changed while playing: `physics.settings.set({ gravityMPerSecPerSec: 4 })`.
137
+
138
+ | Setting | What it turns |
139
+ | --- | --- |
140
+ | `gravityMPerSecPerSec` | how fast things fall; 9.81 is Earth's |
141
+ | `bouncePct`, `gripPct` | how bouncy and grippy surfaces are, for bodies that don't say |
142
+ | `walkSpeedMPerSec`, `jumpHeightM` | the walking characters' speed and jump; a kind of the game's own reads them as `tuning` |
143
+ | `characterMassKg` | how heavy a character is beside what it pushes |
144
+
145
+ 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`).
146
+
147
+ `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/characters.js ADDED
@@ -0,0 +1,189 @@
1
+ // Character kinds: how the characters in a physics world move. The world gives every character a capsule, a place
2
+ // on the wire (where it is, how fast it goes, where it faces, whether it stands, what it rides) and the world to
3
+ // move in; a character kind gives its rules, as a step run once a fixed step for each character, the same in every
4
+ // player's game and on the game server. The piece's own is walkingCharacters: walk, run, jump, ride. A game with
5
+ // movement of its own (thrusters, zip lines, speed by surface, stamina) gives its own with defineCharacterKind, and a
6
+ // piece built on physics (@zaisma/physics-party's hands that grab and carry) gives one with more of the hooks below.
7
+ import { refuse } from "./declare.js";
8
+
9
+ const BODY_KINDS = ["kinematic", "dynamic"];
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"];
12
+ const KIND_KEYS = ["name", "bodyKind", "stateFields", "inputFields", "step", "stepRiding", "vehicleControls", "isSteppedBeforeWorld", "canPushBodies"];
13
+ /** What a piece built on physics may give too: hooks into the world's step, and calls of its own. */
14
+ const EXTENSION_KEYS = ["startKindState", "beforeWorldStep", "afterWorldStep", "onBodyRemoved", "onCharacterAdded", "onCharacterRemoved", "canRest", "isResting", "onTuning", "drawnWith", "settings", "settingsStatement", "syncedSettingNames", "tuning", "calls", "serverCalls", "drawnCharacter", "startOwn", "readOwn", "writeOwn"];
15
+ /** The extension keys that aren't functions. */
16
+ const EXTENSION_VALUE_KEYS = ["settings", "settingsStatement", "syncedSettingNames"];
17
+ const NAME_PATTERN = /^[a-z][a-z0-9_]{0,39}$/;
18
+
19
+ const isPlainObject = (given) => given !== null && typeof given === "object" && !Array.isArray(given);
20
+
21
+ /** A field's value when nothing's said: its default, or what its kind starts at. */
22
+ function startValueOf(field) {
23
+ if (field.defaultValue !== undefined) return field.valueKind === "rotation" ? { ...field.defaultValue } : field.defaultValue;
24
+ if (field.valueKind === "boolean" || field.valueKind === "press") return false;
25
+ if (field.valueKind === "choice") return field.choices[0];
26
+ if (field.valueKind === "rotation") return { x: 0, y: 0, z: 0, w: 1 };
27
+ if (field.valueKind === "number" || field.valueKind === "integer") return Math.min(Math.max(0, field.minimumNumber), field.maximumNumber);
28
+ return 0;
29
+ }
30
+
31
+ /** Drives a vehicle from its driver's stick: forward and back on moveY, steering on moveX, brakes on isBraking. */
32
+ export function stickVehicleControls(input) {
33
+ return { engineNumber: Number(input.moveY) || 0, steerNumber: -(Number(input.moveX) || 0), brakeNumber: input.isBraking ? 1 : 0 };
34
+ }
35
+
36
+ /**
37
+ * A kind of character, checked. Give:
38
+ *
39
+ * - name: lowercase words joined by underscores, the same in the game and on its game server.
40
+ * - bodyKind: "kinematic" (the default: the kind moves it with stepContext.moveAndSlide, and what it walks into
41
+ * is pushed, never pushes it back) or "dynamic" (a body physics moves, which the kind pushes with forces).
42
+ * - stateFields: what the kind keeps of each character beyond the piece's own (its fuel, its stamina, its
43
+ * cooldowns), as @zaisma/net's fields: shared on the wire, so every side steps from the same.
44
+ * - inputFields: what moves it, as @zaisma/net's input fields.
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), 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.
50
+ * A field with isShared: false is the kind's own memory in each game, never sent nor compared: set by each step
51
+ * afresh, read by drawnCharacter and characterState (sprinting, stopped at deep water). It isn't put back on a replay.
52
+ * - stepRiding(character, input, stepContext): one fixed step of a character sitting in a seat, to keep its own fields
53
+ * going (stamina back on a drive); it goes where its seat goes. Left out, a rider isn't stepped.
54
+ * - canPushBodies: false for characters that never shove what they walk into (a parked handcart); true by default.
55
+ * - vehicleControls(input, vehicle, stepContext): how a driver's input drives (answers { engineNumber, steerNumber,
56
+ * brakeNumber }, each -1 to 1); the stick's by default. vehicle is the body as stepContext.bodyState reads it, with its bodyId.
57
+ * - isSteppedBeforeWorld: step before the world's first engine step instead of just after it (a dynamic kind that
58
+ * pushes with forces this step). Its queries then see where things were at the last step's start.
59
+ */
60
+ export function defineCharacterKind(given) {
61
+ if (given?.isCharacterKind === true) return given;
62
+ if (!isPlainObject(given)) refuse("bad_character_kind", "A character kind is an object.", "characters", "Give defineCharacterKind({ name, inputFields, step }), or leave characters out for the piece's walk.");
63
+ for (const key of Object.keys(given)) if (!KIND_KEYS.includes(key) && !EXTENSION_KEYS.includes(key)) refuse("bad_character_kind", `A character kind has no "${key}".`, `characters.${key}`, `It takes: ${KIND_KEYS.join(", ")}; and for a piece built on physics, ${EXTENSION_KEYS.join(", ")}.`);
64
+ const { name, bodyKind = "kinematic", stateFields = [], inputFields, step, vehicleControls = stickVehicleControls, isSteppedBeforeWorld = false } = given;
65
+ if (typeof name !== "string" || !NAME_PATTERN.test(name)) refuse("bad_character_kind", `The character kind's name is ${JSON.stringify(name)}.`, "characters.name", 'Give lowercase words joined by underscores, like "soldier".');
66
+ if (!BODY_KINDS.includes(bodyKind)) refuse("bad_character_kind", `characters.bodyKind is ${JSON.stringify(bodyKind)}.`, "characters.bodyKind", 'Use "kinematic" (the kind moves it, with moveAndSlide) or "dynamic" (physics moves it, the kind pushes it).');
67
+ if (!Array.isArray(stateFields) || stateFields.some((field) => !isPlainObject(field) || typeof field.name !== "string")) refuse("bad_character_kind", "characters.stateFields isn't a list of fields.", "characters.stateFields", "Give fields as @zaisma/net takes them, or leave it out.");
68
+ for (const field of stateFields) if (CHARACTER_BASE_FIELD_NAMES.includes(field.name)) refuse("bad_character_kind", `characters.stateFields names "${field.name}", which every character has already.`, "characters.stateFields", `Give your own fields other names than: ${CHARACTER_BASE_FIELD_NAMES.join(", ")}.`);
69
+ if (!Array.isArray(inputFields) || !inputFields.length) refuse("bad_character_kind", "characters.inputFields isn't a list of fields.", "characters.inputFields", 'Give what moves a character, like [{ name: "moveX", valueKind: "number", minimumNumber: -1, maximumNumber: 1, stepSizeNumber: 0.01 }].');
70
+ if (typeof step !== "function") refuse("bad_character_kind", "characters.step isn't a function.", "characters.step", "Give step(character, input, stepContext): one fixed step of one character.");
71
+ if (given.canPushBodies !== undefined && typeof given.canPushBodies !== "boolean") refuse("bad_character_kind", "characters.canPushBodies isn't true or false.", "characters.canPushBodies", "Give false for characters that walk into a parked cart without shoving it, or leave it out: they push what they walk into.");
72
+ for (const field of stateFields) if (field.isShared !== undefined && typeof field.isShared !== "boolean") refuse("bad_character_kind", `characters.stateFields' "${field.name}" has isShared ${JSON.stringify(field.isShared)}.`, "characters.stateFields", "Give isShared: false for a field each step works out afresh and only this game shows (never sent), or leave it out.");
73
+ for (const key of [...EXTENSION_KEYS.filter((each) => !EXTENSION_VALUE_KEYS.includes(each)), "vehicleControls", "stepRiding"]) if (given[key] !== undefined && typeof given[key] !== "function") refuse("bad_character_kind", `characters.${key} isn't a function.`, `characters.${key}`, "Give a function, or leave it out.");
74
+ const groupNames = stateFields.filter((field) => Array.isArray(field.fields)).map((field) => field.name);
75
+ return {
76
+ ...given,
77
+ isCharacterKind: true,
78
+ name,
79
+ bodyKind,
80
+ stateFields,
81
+ inputFields,
82
+ step,
83
+ vehicleControls,
84
+ isSteppedBeforeWorld: Boolean(isSteppedBeforeWorld),
85
+ /** Each character's own fields as they start. */
86
+ startOwn: given.startOwn ?? (() => {
87
+ const own = {};
88
+ for (const field of stateFields) own[field.name] = groupNames.includes(field.name) ? Array.from({ length: field.count }, () => Object.fromEntries(field.fields.map((inner) => [inner.name, startValueOf(inner)]))) : startValueOf(field);
89
+ return own;
90
+ }),
91
+ readOwn: given.readOwn ?? ((character) => character.own),
92
+ writeOwn:
93
+ given.writeOwn ??
94
+ ((character, fields) => {
95
+ for (const field of stateFields) if (fields[field.name] !== undefined) character.own[field.name] = groupNames.includes(field.name) ? fields[field.name].map((copy) => ({ ...copy })) : fields[field.name];
96
+ }),
97
+ /** What a character does with no input. */
98
+ idleInput: Object.freeze(Object.fromEntries(inputFields.filter((field) => !Array.isArray(field.fields)).map((field) => [field.name, startValueOf(field)]))),
99
+ };
100
+ }
101
+
102
+ const WALK_INPUT_FIELDS = [
103
+ { name: "moveX", valueKind: "number", minimumNumber: -1, maximumNumber: 1, stepSizeNumber: 0.01 },
104
+ { name: "moveY", valueKind: "number", minimumNumber: -1, maximumNumber: 1, stepSizeNumber: 0.01 },
105
+ { name: "viewYawRad", valueKind: "angle", idleMode: "hold" },
106
+ { name: "isRunning", valueKind: "boolean" },
107
+ { name: "isBraking", valueKind: "boolean" },
108
+ { name: "jump", valueKind: "press" },
109
+ ];
110
+ /** How quickly a walker reaches the speed asked of it, on the ground and in the air, and turns to face where it goes. */
111
+ const GROUND_ACCELERATION_M_PER_SEC_PER_SEC = 40;
112
+ const AIR_ACCELERATION_M_PER_SEC_PER_SEC = 8;
113
+ const TURN_SPEED_RAD_PER_SEC = 12;
114
+ /** Steps after walking off an edge in which a jump still counts. */
115
+ const COYOTE_TICK_COUNT = 4;
116
+ /** How much faster running is than walking. */
117
+ const RUN_SPEED_PCT = 180;
118
+
119
+ /**
120
+ * Where the player pushes, in the world, from a stick and where they look: moveY forward along the view, moveX to
121
+ * the view's right, never more than 1 long.
122
+ */
123
+ export function wishOf(input) {
124
+ const forwardX = Math.sin(input.viewYawRad ?? 0);
125
+ const forwardZ = Math.cos(input.viewYawRad ?? 0);
126
+ let wishX = -forwardZ * (input.moveX ?? 0) + forwardX * (input.moveY ?? 0);
127
+ let wishZ = forwardX * (input.moveX ?? 0) + forwardZ * (input.moveY ?? 0);
128
+ const wishNumber = Math.hypot(wishX, wishZ);
129
+ if (wishNumber > 1) {
130
+ wishX /= wishNumber;
131
+ wishZ /= wishNumber;
132
+ }
133
+ return { x: wishX, z: wishZ, lengthNumber: Math.min(wishNumber, 1) };
134
+ }
135
+
136
+ /**
137
+ * The piece's own character kind: it walks (and runs) where the stick points along the view, jumps, steps up stairs,
138
+ * climbs slopes up to the world's steepest, slides along walls, pushes what's in its way, rides what it stands on,
139
+ * and drives what it sits in the first seat of. How fast and how high are the world's settings (walkSpeedMPerSec,
140
+ * jumpHeightM). A game that moves its own way gives defineCharacterKind instead, and can call this one's step from
141
+ * its own for the walking part.
142
+ */
143
+ export function walkingCharacters() {
144
+ return defineCharacterKind({
145
+ name: "walking",
146
+ bodyKind: "kinematic",
147
+ inputFields: WALK_INPUT_FIELDS,
148
+ step: walkStep,
149
+ });
150
+ }
151
+
152
+ /** One step of walking: the speed the stick asks, gravity, a jump, the move, and where it faces. */
153
+ export function walkStep(character, input, stepContext) {
154
+ const { tickDurationSec, tuning } = stepContext;
155
+ const wish = wishOf(input);
156
+ const speedMPerSec = tuning.walkSpeedMPerSec * (input.isRunning ? RUN_SPEED_PCT / 100 : 1);
157
+ const velocity = character.velocity;
158
+ const accelerationMPerSecPerSec = character.isGrounded ? GROUND_ACCELERATION_M_PER_SEC_PER_SEC : AIR_ACCELERATION_M_PER_SEC_PER_SEC;
159
+ // In the air with nothing asked, a walker keeps the speed it left the ground with.
160
+ if (character.isGrounded || wish.lengthNumber > 0.01) {
161
+ const missingX = wish.x * speedMPerSec - velocity.x;
162
+ const missingZ = wish.z * speedMPerSec - velocity.z;
163
+ const missingMPerSec = Math.hypot(missingX, missingZ);
164
+ const reachedNumber = missingMPerSec > 0 ? Math.min(1, (accelerationMPerSecPerSec * tickDurationSec) / missingMPerSec) : 0;
165
+ velocity.x += missingX * reachedNumber;
166
+ velocity.z += missingZ * reachedNumber;
167
+ }
168
+ if (input.jump && character.airTickCount <= COYOTE_TICK_COUNT && velocity.y <= tuning.jumpSpeedMPerSec * 0.5) {
169
+ velocity.y = tuning.jumpSpeedMPerSec;
170
+ character.airTickCount = COYOTE_TICK_COUNT + 1;
171
+ } else velocity.y -= tuning.gravityMPerSecPerSec * tickDurationSec;
172
+ const moved = stepContext.moveAndSlide(character, { x: velocity.x * tickDurationSec, y: velocity.y * tickDurationSec, z: velocity.z * tickDurationSec });
173
+ // What a wall or the ground took away is gone from the speed too.
174
+ velocity.x = Math.abs(moved.movedM.x) < 1e-6 ? 0 : moved.movedM.x / tickDurationSec;
175
+ velocity.z = Math.abs(moved.movedM.z) < 1e-6 ? 0 : moved.movedM.z / tickDurationSec;
176
+ if (moved.isGrounded && velocity.y <= 0) velocity.y = 0;
177
+ // Its head met something: rising stops. (A wall it slides along takes a little of the rise, which isn't that.)
178
+ else if (velocity.y > 0 && moved.movedM.y < velocity.y * tickDurationSec * 0.5) velocity.y = 0;
179
+ character.isGrounded = moved.isGrounded && velocity.y <= 0;
180
+ character.airTickCount = character.isGrounded ? 0 : Math.min(character.airTickCount + 1, 250);
181
+ // A speed too small to see is none, so a walker standing still comes to rest and costs nothing.
182
+ for (const axis of ["x", "y", "z"]) if (Math.abs(velocity[axis]) < 1e-3) velocity[axis] = 0;
183
+ if (wish.lengthNumber > 0.1) {
184
+ const turnRad = Math.atan2(Math.sin(Math.atan2(wish.x, wish.z) - character.facingYawRad), Math.cos(Math.atan2(wish.x, wish.z) - character.facingYawRad));
185
+ const mostTurnRad = TURN_SPEED_RAD_PER_SEC * tickDurationSec;
186
+ character.facingYawRad += Math.min(Math.max(turnRad, -mostTurnRad), mostTurnRad);
187
+ character.facingYawRad = Math.atan2(Math.sin(character.facingYawRad), Math.cos(character.facingYawRad));
188
+ }
189
+ }
package/data.js ADDED
@@ -0,0 +1,85 @@
1
+ // A world's data files: a level's ground as a heightfield of heights, or as a mesh too big to write inline. Read
2
+ // once and kept by path, the same bytes in every player's game and on the game server, so every side builds the
3
+ // same ground. A player's game fetches them before the world opens (loadPhysicsData); a game server reads them as
4
+ // the world opens, from its own folder (room.readDataFile). The data is never changed, so every room shares it.
5
+ import { MAXIMUM_DATA_MESH_TRIANGLE_COUNT, refuse } from "./declare.js";
6
+
7
+ const dataByPath = new Map();
8
+
9
+ /** Every data file a world's shapes read, by path. */
10
+ function dataPathsOf(world) {
11
+ const paths = new Set();
12
+ for (const body of world.bodies) for (const shape of body.shapes) if (shape.dataPath) paths.add(shape.dataPath);
13
+ return [...paths];
14
+ }
15
+
16
+ /** Bytes as a little-endian view, whatever they came as. */
17
+ const viewOf = (bytes) => {
18
+ if (bytes instanceof ArrayBuffer) return new DataView(bytes);
19
+ if (ArrayBuffer.isView(bytes)) return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
20
+ refuse("bad_data_file", "A data file's bytes aren't bytes.", "bytes", "Give an ArrayBuffer or a typed array.");
21
+ };
22
+
23
+ /** A heightfield's heights from its file: rowCount times columnCount 32-bit floats, row after row. */
24
+ function heightsFrom(shape, bytes) {
25
+ const view = viewOf(bytes);
26
+ const heightCount = shape.rowCount * shape.columnCount;
27
+ if (view.byteLength !== heightCount * 4) refuse("bad_data_file", `${shape.dataPath} holds ${view.byteLength} bytes, and a heightfield of ${shape.rowCount} by ${shape.columnCount} is ${heightCount * 4}.`, "dataPath", "Write the heights as 32-bit floats, little endian, row after row: rowCount times columnCount of them, nothing before or after.");
28
+ const heights = new Float32Array(heightCount);
29
+ for (let index = 0; index < heightCount; index += 1) heights[index] = view.getFloat32(index * 4, true);
30
+ return heights;
31
+ }
32
+
33
+ /** A mesh from its file: point and triangle counts, then the points, then the triangles' point indexes. */
34
+ function meshFrom(path, bytes) {
35
+ const view = viewOf(bytes);
36
+ const fix = "Write the point count and triangle count as 32-bit whole numbers, then each point's x, y, z as 32-bit floats, then three point indexes for each triangle as 32-bit whole numbers, all little endian.";
37
+ if (view.byteLength < 8) refuse("bad_data_file", `${path} is too short to be a mesh.`, "dataPath", fix);
38
+ const pointCount = view.getUint32(0, true);
39
+ const triangleCount = view.getUint32(4, true);
40
+ if (!pointCount || !triangleCount || triangleCount > MAXIMUM_DATA_MESH_TRIANGLE_COUNT || view.byteLength !== 8 + pointCount * 12 + triangleCount * 12) refuse("bad_data_file", `${path} isn't a mesh of up to ${MAXIMUM_DATA_MESH_TRIANGLE_COUNT} triangles.`, "dataPath", fix);
41
+ const pointsM = new Float32Array(pointCount * 3);
42
+ for (let index = 0; index < pointCount * 3; index += 1) pointsM[index] = view.getFloat32(8 + index * 4, true);
43
+ const triangleIndices = new Uint32Array(triangleCount * 3);
44
+ const firstByteIndex = 8 + pointCount * 12;
45
+ for (let index = 0; index < triangleCount * 3; index += 1) {
46
+ triangleIndices[index] = view.getUint32(firstByteIndex + index * 4, true);
47
+ if (triangleIndices[index] >= pointCount) refuse("bad_data_file", `${path} has a triangle with a point it doesn't have.`, "dataPath", fix);
48
+ }
49
+ return { pointsM, triangleIndices };
50
+ }
51
+
52
+ /** Reads a shape's data from its file's bytes and keeps it by its path. */
53
+ function keep(shape, bytes) {
54
+ const shapeData = shape.shapeKind === "heightfield" ? { heightsM: heightsFrom(shape, bytes) } : meshFrom(shape.dataPath, bytes);
55
+ dataByPath.set(shape.dataPath, shapeData);
56
+ return shapeData;
57
+ }
58
+
59
+ const shapeOfPath = (world, path) => world.bodies.flatMap((body) => body.shapes).find((shape) => shape.dataPath === path);
60
+
61
+ /**
62
+ * In a player's game, before the world opens: fetches every data file the world's shapes read, from beside the
63
+ * page (or with readFile(path), answering its bytes, from anywhere), once. Answers when they're all in.
64
+ */
65
+ export async function loadPhysicsData(world, given = {}) {
66
+ if (given === null || typeof given !== "object" || Object.keys(given).some((key) => key !== "readFile")) refuse("unknown_argument", "loadPhysicsData takes a world, then { readFile }.", "given", "Give the world, and readFile(path) answering a file's bytes when they don't come from beside the page.");
67
+ const readFile = given.readFile ?? (async (path) => {
68
+ const response = await fetch(new URL(path, globalThis.document?.baseURI ?? globalThis.location?.href));
69
+ if (!response.ok) refuse("data_file_unreachable", `${path} didn't load (${response.status}).`, "dataPath", "Check that the file is in the game's folder at that path.");
70
+ return response.arrayBuffer();
71
+ });
72
+ await Promise.all(dataPathsOf(world).filter((path) => !dataByPath.has(path)).map(async (path) => keep(shapeOfPath(world, path), await readFile(path))));
73
+ }
74
+
75
+ /**
76
+ * A shape's data, where the world opens: kept already, or read now with readDataFile (a game server's room's, which
77
+ * reads its own folder at once). Throws PieceError "data_not_loaded" in a player's game that didn't load it first.
78
+ */
79
+ export function dataOf(shape, readDataFile = null) {
80
+ if (shape.heightsM) return { heightsM: shape.heightsM };
81
+ if (!shape.dataPath) return { pointsM: shape.pointsM instanceof Float32Array ? shape.pointsM : Float32Array.from(shape.pointsM), triangleIndices: shape.triangleIndices instanceof Uint32Array ? shape.triangleIndices : Uint32Array.from(shape.triangleIndices) };
82
+ if (dataByPath.has(shape.dataPath)) return dataByPath.get(shape.dataPath);
83
+ if (!readDataFile) refuse("data_not_loaded", `${shape.dataPath} isn't loaded.`, "dataPath", "In a player's game, await loadPhysicsData(world) before the world opens (before net.use or createPhysics).");
84
+ return keep(shape, readDataFile(shape.dataPath));
85
+ }