The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
The host channel, input and a HUD: real-time games as game code (a first-person arena, sockets owned by the app) (#51)
Evan (Yifeng) Wange7f2c72f14a5
diff --git a/README.md b/README.mdindex ab110d4..06ddb57 100644--- a/README.md+++ b/README.md@@ -118,7 +118,7 @@ The same address in any browser shows the game as three.js. The full walk-throug| Package | What ||---|---|| [`@threert/scene`](packages/scene) | The three.js-style scene API: meshes, PBR materials, lights, glTF models, physics, volumes |-| [`@threert/gameplay`](packages/gameplay) | Games: state, transactional handlers, world handlers, frame scripts; deterministic and replayable |+| [`@threert/gameplay`](packages/gameplay) | Games: state, transactional handlers, world handlers, frame scripts; input, a HUD and a channel to the app that runs the game; deterministic and replayable || [`@threert/voxel`](packages/voxel) | Destructible voxel levels: explosions, cuts, and pieces that break off as rigid bodies |```bashdiff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex e54fced..37432c5 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -47,10 +47,11 @@ runtime, and drives the engine directly, the way a UE game drives its actors:| Scene binding | `packages/scene/src/engine.ts` `SceneBinding` | Keeps the engine in step with a DSL scene. Objects report their own changes (core.ts change tracking: transforms, visibility, power, shadow flag, mesh geometry / material, add / remove), so a sync visits only what changed. Lights, cameras and materials are compared against what was last sent. || World | `renderer/src/world.rs` | The engine's objects, resources, environment and settings, and what changed since the last commit: parameter changes (power, light / material parameters, environment, camera) or structural ones. Asset paths must stay inside the asset root (game code is untrusted on nodes). || Live commit | `renderer/src/live.rs` `LiveCore::commit`, `tables.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF, wetness / rain / fog, camera), and so does hiding or showing a volume, a light without a card or a particle system that is not light-sampled by its own `visible`. Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. |-| Scene runtime | `renderer/src/script.rs` `ScriptHost` | QuickJS (rquickjs) with no I/O (no fs, network or timers). Loads a bundle (one script) or ES modules (`game.js` + `threert-runtime.js`, the cloud layout). Memory capped at 1 GiB. Time budgets: setup 120 s, event 1 s, frame 50 ms; the interrupt handler aborts overruns. The time the engine spends inside a voxel call (`voxelExplode`, `voxelEdit`, `voxelFrame`) is the engine's, not the script's: the deadline moves by it as measured, up to 250 ms an entry; past that it counts against the script, and a voxel call made after the deadline throws "interrupted" at once. A prelude adds `TextEncoder`, `structuredClone`, `atob` and `console`. |-| Node host | `packages/gameplay/src/node-host.ts` | `globalThis.__threert`: `setup(room, seed)`, `event(type, payload, ts)` (local authority: execute + commit), `commit(writes, seq)` / `setState(state, seq)` (room authority), `state()`, `frame(dt, now)`, and the editor's `outline()`, `inspect(name)`, `edit(name, path, value)`. |+| Scene runtime | `renderer/src/script.rs` `ScriptHost` | QuickJS (rquickjs) with no I/O (no fs, network or timers; what needs the outside is asked of the app, "The host channel"). Loads a bundle (one script) or ES modules (`game.js` + `threert-runtime.js`, the cloud layout). Memory capped at 1 GiB. Time budgets: setup 120 s, event 1 s, frame 50 ms; the interrupt handler aborts overruns. The time the engine spends inside a voxel call (`voxelExplode`, `voxelEdit`, `voxelFrame`) is the engine's, not the script's: the deadline moves by it as measured, up to 250 ms an entry; past that it counts against the script, and a voxel call made after the deadline throws "interrupted" at once. A prelude adds `TextEncoder`, `structuredClone`, `atob` and `console`. |+| Node host | `packages/gameplay/src/node-host.ts` | `globalThis.__threert`: `setup(room, seed)`, `event(type, payload, ts)` (local authority: execute + commit), `commit(writes, seq)` / `setState(state, seq)` (room authority), `state()`, `frame(dt, now)`, `hostMessages(list, ts)` (the app's messages), and the editor's `outline()`, `inspect(name)`, `edit(name, path, value)`. || World handlers | `packages/gameplay/src/world.ts` | `on[type](world, ev)`: an event handled on this node, changing the scene at once. `WorldContext`: `scene`, `camera`, read-only `state`, `object(id)`, `time`, `now`, `random()`, `emit(type, payload)`. |-| Frame scripts | `packages/gameplay/src/frame.ts` | `FrameContext`: `time`, `dt`, `snap`, `now`, read-only `state`, `scene`, `camera`, `object(id)`, `random()`. |+| Frame scripts | `packages/gameplay/src/frame.ts` | `FrameContext`: `time`, `dt`, `snap`, `now`, read-only `state`, `scene`, `camera`, `object(id)`, `random()`, `input`. |+| Host channel | `packages/gameplay/src/host.ts`, `input.ts`, `hud.ts`; `renderer/src/host.rs`, `script.rs` (`__host_post`, `GameSession::take_posts` / `host_messages`) | Messages between game code and the app that embeds the engine: the app's input every frame (`f.input`), sockets and HTTP the app owns (`net.*`), the HUD the app draws (`hud.set`), how the game was opened (`launch`). See "The host channel" below. || Game session | `renderer/src/script.rs` `GameSession` | A runtime + its live view: events, clicks (CPU pick → `click {target, point, ray: {origin, direction}}`, with `instanceId` on an `InstancedMesh`; `ray` is the view ray, for a `Raycaster`), frame script, the physics world's ticks, editor edits, each followed by a commit. Shared by `play`, `live` and the playground. || Physics | `renderer/physics-core` (`Physics` on Rapier, `bridge::Bridge`), `renderer/src/physics.rs`, `packages/scene` (`Object3D.physics`, joints, `Raycaster.intersectPhysics`, `Shapecaster`) | The session's physics world, made by the first physics call (none: nothing runs). The engine steps it at 1 / 60 s after the frame script (at most 5 ticks a frame; offline renders step to their scene time) and places the objects of the bodies that moved: instances, so a move is a TLAS transform. Scripts cannot step it. See "Physics" below. |@@ -58,7 +59,9 @@ runtime, and drives the engine directly, the way a UE game drives its actors:```threert-render play <bundle.js> [--assets DIR] native window; keys / clicks go to the game+ [--launch JSON] [--hud-log] [--sensitivity N] the host channel: input, sockets, the HUD printedthreert-render live <bundle.js> [--assets DIR] headless 60 fps; {"cmd":"event"} / {"cmd":"click"} on stdin+ [--launch JSON] {"cmd":"host","messages":[..]} in, {"host":[..]} lines outthreert-render render <bundle.js> -o out.png [--state s.json] [--camera {position,target,fov}] [--time t] [--preset p]threert-render serve JSON-lines jobs {game, runtime?, assets, room, seed, state, ...}threert-render setup <bundle.js> setup cost in the runtime@@ -107,7 +110,8 @@ export default defineGame({engine through the scene binding when it returns: no commit, and `frame` is not run again for it.- **The context** (`world`): `scene`, `camera`, the committed `state` (read-only), `object(id)`, `time` (the frameclock, s), `now` (the event's time, ms), `random()` (the event's own stream; `Math.random` and `Date` in the handler- are the event's too), and `emit(type, payload)`, which starts a state transaction (`handlers[type]`).+ are the event's too), `emit(type, payload)`, which starts a state transaction (`handlers[type]`), and `input` (what+ the player holds, for a game that asked for input: "Input", below).- **With `handlers[type]` for the same event:** the world handler runs first, on the state as committed before theevent; then the handler's transaction; then what the world handler emitted, in order; then the frame script showsthe new state. A room that is the authority runs `handlers` on its own, so neither may rely on the other having run.@@ -260,6 +264,229 @@ crate.position.set(0, 5, 0); // a write moves the body there- Ids in a call (`body`, `collider`, `skip`, ...) are whole numbers however they are written: scene code handsback an id it read from an answer as a double.+## The host channel++A script has no I/O and no timers, and the engine draws the scene and nothing else. What a game needs beyond that+belongs to the app that embeds the engine: the keys and the pointer, sockets, a HUD over the picture, how the game+was opened. The host channel is how the two talk: messages, JSON objects with a string `t`, queued one way and+handed over in batches the other.++```ts+import { defineGame, host, hud } from "@threert/gameplay";++host.on("launch", (m) => host.post({ t: "net.open", id: "room", url: `wss://example.org/rooms/${m.params.room}` }));+host.on("net.messages", (m, world) => { // on the node that owns the scene, like a world handler+ for (const text of m.list) world.emit("remote", JSON.parse(text)); // a state transaction: handlers.remote+});++export default defineGame({+ pointer: "look", // this game reads input and owns its camera+ frame(f) {+ yaw -= f.input.look.dx;+ if (f.input.pressed("Mouse0")) host.post({ t: "net.send", id: "room", data: JSON.stringify({ fire: true }) });+ hud.set({ crosshair: { style: "cross" }, items: [{ type: "text", anchor: "top-left", label: "Score", text: String(f.state.score) }] });+ },+ ...+});+```++- **Script → app:** `host.post({ t, ... })` (`packages/gameplay/src/host.ts`) queues the message's JSON text through+ the native `__host_post`. The queue holds 1,024 messages of at most 1 MiB each until the app takes them+ (`GameSession::take_posts`); past that `post` returns false and the message is dropped, and where no app is there+ at all (a test, a page that set no `__host_post`) it returns false too. A session nobody drains (`render`, `serve`)+ keeps the first 1,024 and nothing else.+- **App → script:** the app hands a batch to the session (`GameSession::host_messages`), one script entry for the+ batch (the node host's `hostMessages(list, ts)`), under an event's time budget (1 s). Each message goes to the+ listeners added with `host.on(type, fn)`, in the order they were added; `on` returns the function that removes the+ listener.+- **Listeners run like world handlers** ("World handlers", above): on the node that owns the scene, with the same+ context as their second argument (`scene`, `camera`, the committed `state`, `object(id)`, `time`, `now`,+ `random()`, `emit`, `input`). What they change in the scene reaches the engine when the batch returns, once.+ What they `emit` are state transactions, run after the batch's listeners, followed by the frame script as after+ any event. A listener that throws does not stop the batch: the error is logged and the next listener runs.+- **The same object is `globalThis.__threert_host`** (`{ post, on, launch }`), for a library that does not import+ `@threert/gameplay`. A second copy of the package in one runtime finds the first's channel.+- **It is not one of the four channels** of "The runtime's shape" below: those are between the script and the+ engine. This one is between the script and the app, and the engine only carries it.+- **Every family below is optional.** An app implements what it has; a message it does not know is ignored, both+ ways. A game must go on without an answer (the socket that never opens, the HUD nobody draws), and must not+ expect one within a frame.++Messages a game posts:++| `t` | fields | what the app does |+| --- | --- | --- |+| `net.open` | `id`, `url`, `protocols?` | opens a WebSocket (`ws:` / `wss:`) the game calls `id`; answers `net.opened`, or `net.closed` if it cannot |+| `net.send` | `id`, `data` | sends the text `data`; before `net.opened`, once the socket is open; to a socket that is gone, nothing |+| `net.close` | `id`, `code?`, `reason?` | closes it (1000 unless `code` is 3000–4999); answers `net.closed` |+| `net.fetch` | `id`, `url`, `method?`, `headers?`, `body?` | one HTTP request (`GET` unless `method`); answers `net.fetched` |+| `hud` | `hud` | draws the HUD it describes ("HUD", below). `hud.set` posts it; a game does not post it by hand |++Messages an app sends:++| `t` | fields | when |+| --- | --- | --- |+| `net.opened` | `id` | the socket is open |+| `net.messages` | `id`, `list: string[]` | the text messages that arrived on `id` since the last frame, in order: one batch a socket a frame |+| `net.closed` | `id`, `code`, `reason` | the socket closed (the close frame's code; 1005 without one), or failed (1006, `reason` says why) |+| `net.fetched` | `id`, `status`, `body`, `error?` | the response's status and body as text; `status` 0 and `error` when the request failed |+| `launch` | `params: { room?, name?, ... }` | once, after setup: how the app opened the game. Kept as `host.launch` (`{}` before it comes, and for an app that sends none) |+| `input` | below | once a frame, before the frame script, to a game that asked for input. The node host keeps it; it has no listeners |++`id` is the game's own name for a socket or a request (a string); the app's answers carry it back. Messages are text:+a binary WebSocket frame is dropped. Which addresses a game may reach is the app's decision, not the engine's.++**What an app does** (Rust: whoever holds the `GameSession`; `renderer/src/view.rs` is the example to read):++1. After the scene is built: `session.host_messages(&mut core, &[host::launch_message(params)])`.+2. Every frame, before `session.frame`: one `host_messages` with the frame's `input` message (if the game asked:+ `session.host.pointer()` is `Some("look")` or `Some("free")`) and what its services have for the game (a+ `net.messages` batch a socket, answers). An empty batch is no entry at all.+3. After the frame: `session.take_posts()`, each message to whatever implements its family.+4. For a game with `pointer`: leave the camera alone (a commit makes the view follow the scene's camera, and the+ game moves that) and give up its own keys and pointer gestures. For `"look"`: capture the pointer on a click+ (that click is not the game's), let go on Esc and when the window loses the keyboard, and send the motion as+ `dx` / `dy`.+5. A game without `pointer` gets no `input` and is shown as before: the app's own camera controls, `keys` and+ clicks as discrete events. `keys` and (unless the pointer is captured for look) clicks work for every game.++The apps in this repository:++| app | input | `net.*` | `launch` | HUD |+| --- | --- | --- | --- | --- |+| `threert-render play` (`view.rs`) | keys by physical position, mouse buttons, wheel; the pointer captured for `"look"` (a click; Esc lets go, Esc again quits) | WebSockets and HTTP on a thread each (`src/net.rs`: tungstenite and ureq on rustls; text frames of at most 1 MiB, bodies of at most 4 MiB, 16 sockets, 32 requests at once), any address | `--launch '{"room":"K7Q4MZ"}'` | not drawn; `--hud-log` prints each description |+| `threert-render live` (`live.rs`) | whatever the driver sends | none: the driver is the app | `--launch` | on stdout with every other post |+| the three.js view (`tools/three/view.ts`, `host.ts`, `hud.ts`) | keyboard, mouse, the Pointer Lock API | `WebSocket`, `fetch` (the browser's rules: same-origin policy, CORS) | the page's query (`?room=K7Q4MZ&name=Ada`) | DOM over the canvas |++- `live` speaks the channel as JSON lines, so a game's use of it is testable without a window: on stdin+ `{"cmd":"host","messages":[{"t":"net.opened","id":"room"}, ...]}`, on stdout one line `{"host":[...]}` with what+ the game posted since the last one. `play` takes the same command and writes `{"type":"host","messages":[...]}`.+- The sockets of `play` are in the binary and behind the `net` cargo feature (on by default). The library has no+ network in it; a program that embeds it and wants its dependency graph without the three crates sets+ `default-features = false`, as `renderer/web` does. A build without the feature answers every `net.open` and+ `net.fetch` with a failure that says so.+- The three.js view has three.js for the picture and the engine's own physics for the rest (`tools/three/physics.ts`):+ the world and the physics as a wasm32 module (`renderer/examples/physics_scene.rs`: the code `__engine` runs+ natively, without the renderer and without wasm-bindgen), which `node tools/three/open.ts <game>` builds for a+ game whose source names the physics. Bodies move and `intersectPhysics` / `Shapecaster` answer as in the renderer.+ Without the module the view is the baseline it was: bodies stay where the scene put them.+- Checked: `packages/gameplay/test/host.test.ts` (the channel, input, the HUD's change detection, in Node);+ `renderer/src/host.rs` and `script.rs` tests (the queue's bounds, a batch's delivery, the input message);+ `node tools/host-echo.ts` (`games/host/echo.game.ts` in `live` with the script as the app, in `play` against a+ WebSocket and HTTP server on the machine, and in the three.js view in Chrome); `node tools/fps-arena.ts` and+ `node tools/three-arena.ts` (below).+- Not built: the channel in the engine's own page (`renderer/web/www`: its `main.ts` sets no `__host_post` and sends+ no input); binary socket messages; gamepads and touch in the three apps above (the `input` message has their+ fields).++### Input++A game that reads input says so in its definition, and `describe()` reports it:++```ts+defineGame({ pointer: "look", ... }) // or "free"+```++| `pointer` | the app | the camera |+| --- | --- | --- |+| left out | sends no input; its own controls work as before | the app's (orbit, fly), following the game's when a handler moves it |+| `"free"` | sends input every frame; the pointer stays free, `input.pointer` is where it is; a click is still a `click` event | the game's |+| `"look"` | the same, and captures the pointer: its motion is `input.look`; no `click` events | the game's |++Game code reads it as `f.input` in the frame script and `world.input` in world handlers and host listeners+(`packages/gameplay/src/input.ts`):++| | |+| --- | --- |+| `input.down(key)` | the key is held |+| `input.pressed(key)`, `input.released(key)` | it went down / up since the last frame |+| `input.axis(negative, positive)` | -1, 0 or 1 from two keys |+| `input.move` | `{ x, y }`: the app's move stick if it sent one, else W A S D; x right, y forward, never longer than 1 |+| `input.look` | `{ dx, dy }`, radians to turn this frame: right and down are positive |+| `input.button(n)` | mouse button `n` is held (0 left, 1 middle, 2 right); the same as `down("Mouse<n>")`, and `pressed("Mouse0")` is its edge |+| `input.pointer` | `{ u, v }`, 0..1 from the picture's top left; (0.5, 0.5) while captured |+| `input.wheel`, `input.captured` | wheel notches this frame (away from the player is positive); the app holds the pointer |++The message, every field optional but `t`:++| field | |+| --- | --- |+| `keys: string[]` | every key held now |+| `pressed`, `released: string[]` | keys (and `"Mouse<n>"`) that went down / up since the last message. Left out: derived from how `keys` and `buttons` changed, which misses a tap shorter than a frame |+| `buttons: number[]` | mouse buttons held now |+| `u`, `v` | the pointer |+| `dx`, `dy` | look since the last message, radians |+| `wheel` | notches since the last message |+| `captured` | the pointer is captured |+| `move: [x, y] \| null` | a move stick (gamepad, touch), each -1..1; `null` or left out: none |++- **Keys are named by their place on a US keyboard**, not by what the layout prints (W A S D stay where they are on+ AZERTY): `"A"`–`"Z"`, `"0"`–`"9"`, `"Space"`, `"Shift"`, `"Ctrl"`, `"Alt"`, `"Meta"`, `"Tab"`, `"Enter"`,+ `"Escape"`, `"Backspace"`, `"Left"`, `"Right"`, `"Up"`, `"Down"`, `"F1"`–`"F12"`, `"Minus"`, `"Equal"`,+ `"BracketLeft"`, `"BracketRight"`, `"Semicolon"`, `"Quote"`, `"Comma"`, `"Period"`, `"Slash"`, `"Backslash"`,+ `"Backquote"`. Either shift key is `"Shift"`. (The discrete `keys` of a game are matched by the character typed,+ as they were.)+- **Look is an angle, not counts.** The app turns its device into radians: a mouse at 0.0025 rad a count (a point on+ macOS, a CSS pixel in a browser) times the player's sensitivity (`play --sensitivity`, the view's `?sensitivity=`),+ a stick's rate times the frame's time. A game applies `dx` / `dy` as they are, and sensitivity is the app's+ setting, where the player's other settings are.+- **A gamepad or a touch screen** sends `move` for its move stick, its look in `dx` / `dy`, and its buttons under+ the names of the keys they stand for (`"Space"` for jump, `"Mouse0"` for fire): a game written for the keyboard+ needs nothing more.+- **Edges last one frame:** from the input message that brought them to the end of the next frame script, so a world+ handler that runs between the two sees them too. Two messages before one frame add up (their edges, their look,+ their wheel). A frame without a message: what was held stays held, nothing is pressed or released, `look` and+ `wheel` are 0.+- **Input is not state.** It is this node's, read by the frame script and world handlers; nothing of it is committed+ or replayed. What a room must agree on goes through `world.emit` (a handler) or to the app's socket.++`games/fps/arena.game.ts` is the reference: a first-person walk with mouse look, a capsule the frame script moves by+shape sweeps (`Shapecaster.sweep`: stop a skin short of what is met, slide along it with what is left, so a long+frame cannot pass a wall), a jump, targets tagged by the view ray (`Raycaster.intersectPhysics`), and its HUD.+Checked on numbers in the renderer with scripted input (`node tools/fps-arena.ts`: `live`, lockstep), on the same+numbers on three.js with the engine's physics in Node (`tools/three/test/physics.test.ts`), and in Chrome with the+events a keyboard and a mouse send (`node tools/three-arena.ts`).++### HUD++The engine draws no text. A game describes its HUD and the app draws it its own way (`packages/gameplay/src/hud.ts`):++```ts+hud.set({+ crosshair: { style: "cross", gap: 0.3 },+ items: [+ { type: "text", anchor: "top-left", label: "Ammo", text: "24 / 90", size: "large" },+ { type: "bar", anchor: "bottom-left", label: "Health", value: 0.72, tone: "good" },+ { type: "list", anchor: "top-right", lines: [{ id: "k17", text: "Ada tagged Lin", ttl: 4 }] },+ { type: "table", anchor: "center", title: "Round 2", columns: ["Player", "Score"], rows: [["Ada", 7], ["Lin", 5]], highlight: 0 },+ ],+ message: { title: "Round 2", subtitle: "Tag every target" },+});+hud.flash("damage", 1.2); // the player was hit from 1.2 rad clockwise of straight ahead+```++- **The description is the whole HUD.** What is not in it is not shown. A game calls `hud.set` every frame with what+ the frame shows; `{ t: "hud", hud }` is posted only when the description differs from the last one posted (compared+ as canonical JSON), and `set` says whether it was.+- **Nine anchors:** `top-left`, `top`, `top-right`, `left`, `center`, `right`, `bottom-left`, `bottom`,+ `bottom-right`. Items of one anchor stack in their order.+- **Items:**++ | `type` | fields | |+ | --- | --- | --- |+ | `text` | `text`, `label?`, `tone?`, `size?` (`small`, `normal`, `large`) | a figure or a line, with a small label over it |+ | `bar` | `value` (0..1), `label?`, `text?`, `tone?` | health, a reload, a round's time; `text` is a figure beside it |+ | `list` | `lines: (string \| { text, tone?, ttl?, id? })[]` | short lines, newest last. A line with `ttl` is shown that many seconds from when the app first got it (the same `id`, or the same text), then left out, whether or not the game still lists it |+ | `table` | `columns`, `rows`, `title?`, `highlight?` | a scoreboard: listed while it is to be seen (`f.input.down("Tab")`); `highlight` is the row to set apart |+- **`crosshair`:** `style` (`dot`, `cross`, `circle`), `gap` (0..1: how far it opens, a weapon's spread), `tone?`.+ **`message`:** `title`, `subtitle?`, `tone?`, at the picture's centre.+- **`flash`** is the one event: `hud.flash(kind, angle?)` posts the HUD as last set with `flash: { kind, angle?, n }`,+ `n` one more each time. An app plays it when `n` changes: `hit` (a hit marker at the crosshair), `kill`, `damage`+ (the player was hit; `angle`, radians clockwise from straight ahead, is where from).+- **Tones** say what a value means, for the app to colour: `default`, `good`, `warn`, `bad`, `accent`, `dim`.+- **Text is text.** An app shows a game's strings as they are, never as markup.+- A scene built anew in the same runtime posts its first description whatever the last one was.+## The runtime's shape: Rust owns the world, the script engine is a guestDecided by the user on 2026-11-10, with the measurements below.diff --git a/games/fps/arena.game.ts b/games/fps/arena.game.tsnew file mode 100644index 0000000..d9d0709--- /dev/null+++ b/games/fps/arena.game.ts@@ -0,0 +1,242 @@+// A first-person game in one file: a courtyard to walk around in and five targets to tag. It is the reference for+// games that read input every frame (docs/RUNTIME.md "The host channel", "Input", "HUD"):+//+// - `pointer: "look"` asks the app for input and for the pointer: a click captures it, its motion is `f.input.look`,+// and the camera is the game's own (the app's orbit and fly controls are off).+// - The player is a capsule the frame script moves itself: no body, so nothing pushes it around. Each frame it is+// swept through the physics world (`Shapecaster.sweep`) along where it wants to go and stops a skin short of what it+// meets, then slides along that surface with what is left of the move. A sweep is continuous: however long the frame+// took, the capsule cannot pass through a wall.+// - A click casts the view ray into the physics world (`Raycaster.intersectPhysics`): the first body it meets, if it+// is a target, is tagged and knocked back.+// - The HUD (a crosshair, the count, a hint, a message at the end) is described with `hud.set` every frame; the app+// draws it. Nothing is posted while it does not change.+// - The game state is empty: this game is one player's on one node. What a room would have to agree on (who tagged+// what) belongs in `state`, changed by handlers.+//+// node tools/bundle-game.ts games/fps/arena.game.ts -o out/bundles/fps-arena.js+// renderer/target/release/threert-render play out/bundles/fps-arena.js --hud-log (the native window)+// node tools/three/open.ts games/fps/arena.game.ts (three.js, in a browser)+// node tools/fps-arena.ts (headless: scripted input, numbers)+// node tools/three-arena.ts (the three.js view in Chrome, real key and mouse events)+import {+ BoxGeometry, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera, Raycaster, Scene, Shapecaster, SkyAtmosphere, SphereGeometry, Vector3,+} from "@threert/scene";+import { defineGame, host, hud, type FrameContext } from "@threert/gameplay";++/** The courtyard: its half size (m), its walls' height, and where the player starts (the capsule's centre). */+export const HALF = 12;+export const WALL = 4;+export const START = [0, 0.92, 9] as const;+/** The player's capsule (m): 1.8 tall. The eyes are `EYE` above its centre. */+export const RADIUS = 0.35;+export const HALF_HEIGHT = 0.55;+const EYE = 0.7;+/** How close a sweep lets the capsule come to a surface. It rests this far above the ground. */+export const SKIN = 0.02;+/** Walking and sprinting (m/s), the jump's speed, gravity (m/s²). */+export const WALK = 4.5;+export const SPRINT = 7.5;+const JUMP = 5;+const GRAVITY = 14;+/** A surface is ground when its normal points up at least this much (a 45 degree slope). */+const GROUND = 0.7;+/** Where the targets stand. */+export const TARGETS: readonly (readonly [number, number, number])[] = [[-6, 1.3, -6], [6, 0.4, -7], [0, 2.4, -9.5], [-8.5, 0.4, 3], [8, 1.9, 1]];++const position = new Vector3();+const velocity = new Vector3();+let yaw = 0, pitch = 0, grounded = false, tagged = 0, shots = 0;+const targets: Mesh[] = [];+const caster = new Shapecaster({ type: "capsule", halfHeight: HALF_HEIGHT, radius: RADIUS });+const raycaster = new Raycaster();+const idle = new MeshStandardMaterial({ name: "target", color: 0xd9a441, roughness: 0.5 });+const hit = new MeshStandardMaterial({ name: "tagged", color: 0x2e9f5b, roughness: 0.5, emissive: 0x2e9f5b, emissiveIntensity: 40 });++/** Something that stands still: a box with a fixed body. */+function block(name: string, size: [number, number, number], at: [number, number, number], material: MeshStandardMaterial): Mesh {+ const mesh = new Mesh(new BoxGeometry(...size), material);+ mesh.name = name;+ mesh.position.set(...at);+ mesh.physics = "fixed";+ return mesh;+}++/** The player back at the start. */+function spawn(): void {+ position.set(...START);+ velocity.set(0, 0, 0);+ [yaw, pitch, grounded] = [0, 0, false];+}++/** A new game: the player at the start, the targets back where they stood. */+function restart(): void {+ spawn();+ [tagged, shots] = [0, 0];+ targets.forEach((t, k) => {+ t.material = idle;+ t.position.set(...TARGETS[k]);+ t.quaternion.set(0, 0, 0, 1);+ t.setLinearVelocity(new Vector3());+ t.setAngularVelocity(new Vector3());+ });+}++/**+ * Moves the capsule by `delta`, sliding along what it meets: sweep, stop a skin short, take out of what is left the+ * part that goes into the surface, and go on with the rest (a wall, then the wall it meets in a corner).+ * Returns the normal of the last surface met, if any.+ */+function slide(delta: Vector3): Vector3 | null {+ let met: Vector3 | null = null;+ const left = delta.clone();+ for (let turn = 0; turn < 4; turn++) {+ const length = left.length();+ if (length < 1e-6) break;+ const direction = left.clone().multiplyScalar(1 / length);+ caster.set(position);+ caster.far = length + SKIN;+ const h = caster.sweep(direction);+ if (!h || !h.normal) {+ position.add(left);+ break;+ }+ const go = Math.max(h.distance - SKIN, 0);+ position.addScaledVector(direction, go);+ left.addScaledVector(direction, -go);+ left.addScaledVector(h.normal, -left.dot(h.normal));+ met = h.normal;+ // A target in the way is shoved, not walked through.+ if (targets.includes(h.object as Mesh)) h.object.applyImpulse(direction.clone().multiplyScalar(2), h.point);+ }+ return met;+}++/** One frame of the player: look, walk, jump, fall. */+function move(f: FrameContext<unknown>): void {+ const input = f.input;+ yaw -= input.look.dx;+ pitch = Math.max(-1.5, Math.min(1.5, pitch - input.look.dy));+ // Walk where the camera faces, on the ground plane. `move` is W A S D or a stick, never longer than 1.+ const forward = new Vector3(-Math.sin(yaw), 0, -Math.cos(yaw)), right = new Vector3(Math.cos(yaw), 0, -Math.sin(yaw));+ const speed = input.down("Shift") ? SPRINT : WALK;+ const wish = forward.multiplyScalar(input.move.y * speed).addScaledVector(right, input.move.x * speed);+ velocity.x = wish.x;+ velocity.z = wish.z;+ if (grounded && input.pressed("Space")) velocity.y = JUMP;+ velocity.y -= GRAVITY * f.dt;+ // Sideways first, sliding along walls. A low kerb is climbed by the capsule's round end: the slide goes up it.+ slide(new Vector3(velocity.x * f.dt, 0, velocity.z * f.dt));+ // Then up or down. Ground stops the fall where it is met; a slope too steep to stand on is slid down.+ const fall = velocity.y * f.dt;+ caster.set(position);+ caster.far = Math.abs(fall) + SKIN;+ const h = caster.sweep(new Vector3(0, Math.sign(fall) || -1, 0));+ grounded = false;+ if (!h || !h.normal) position.y += fall;+ else {+ position.y += Math.sign(fall) * Math.max(h.distance - SKIN, 0);+ if (fall > 0) velocity.y = 0; // a ceiling+ else if (h.normal.y >= GROUND) [grounded, velocity.y] = [true, 0];+ else slide(new Vector3(0, fall, 0));+ }+ // Fell out of the world (it has no holes; a game that had some would decide here).+ if (position.y < -20) spawn();+}++/** The view ray into the physics world: the first body it meets is tagged if it is a target. */+function fire(): void {+ shots++;+ const direction = new Vector3(-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch));+ raycaster.set(new Vector3(position.x, position.y + EYE, position.z), direction);+ const h = raycaster.intersectPhysics()[0];+ const target = h && targets.find((t) => t === h.object);+ if (!h || !target) return;+ target.applyImpulse(direction.multiplyScalar(30), h.point);+ if (target.material === hit) return;+ target.material = hit;+ tagged++;+ hud.flash("hit");+ console.log(`arena ${JSON.stringify({ tagged: target.name, shots })}`);+}++export default defineGame({+ state: {},+ pointer: "look",+ keys: { R: "restart" },+ setup: () => {+ const scene = new Scene();+ const sun = new DirectionalLight(0xffffff, 90000);+ sun.setSunAngles(50, 215);+ scene.add(sun);+ scene.environment = new SkyAtmosphere({ sun });+ const camera = new PerspectiveCamera(75, 16 / 9, 0.05, 200);+ camera.setManualExposure(14);+ scene.add(camera);++ const stone = new MeshStandardMaterial({ name: "stone", color: 0x8c8c88, roughness: 0.9 });+ const brick = new MeshStandardMaterial({ name: "brick", color: 0xb07a62, roughness: 0.85 });+ const wood = new MeshStandardMaterial({ name: "wood", color: 0x8a6a4a, roughness: 0.7 });+ const t = 0.5; // the walls' thickness+ scene.add(+ block("ground", [2 * HALF + 2, 1, 2 * HALF + 2], [0, -0.5, 0], new MeshStandardMaterial({ name: "ground", color: 0x6f7468, roughness: 0.95 })),+ block("wall north", [2 * HALF + 2 * t, WALL, t], [0, WALL / 2, -HALF - t / 2], brick),+ block("wall south", [2 * HALF + 2 * t, WALL, t], [0, WALL / 2, HALF + t / 2], brick),+ block("wall west", [t, WALL, 2 * HALF], [-HALF - t / 2, WALL / 2, 0], brick),+ block("wall east", [t, WALL, 2 * HALF], [HALF + t / 2, WALL / 2, 0], brick),+ // Things to walk around, onto and behind: a pillar, a crate with a kerb to it, a platform with steps, a low wall.+ block("pillar", [1, WALL, 1], [-3, WALL / 2, 2], stone),+ block("crate", [1.8, 0.9, 1.8], [-6, 0.45, -6], wood),+ block("kerb", [3, 0.2, 3], [-6, 0.1, -6], stone),+ block("platform", [4, 2, 2.4], [0, 1, -10], stone),+ block("step 1", [1.2, 0.5, 2.4], [-3.8, 0.25, -10], stone),+ block("step 2", [1.2, 1, 2.4], [-2.6, 0.5, -10], stone),+ block("step 3", [1.2, 1.5, 2.4], [-1.4, 0.75, -10], stone),+ block("low wall", [0.4, 1.5, 5], [8, 0.75, 1], stone),+ );+ targets.length = 0;+ TARGETS.forEach((at, k) => {+ const target = new Mesh(new SphereGeometry(0.4, 24, 12), idle);+ target.name = `target ${k + 1}`;+ target.position.set(...at);+ target.physics = { type: "dynamic", density: 60 }; // 16 kg+ scene.add(target);+ targets.push(target);+ });+ spawn();+ [tagged, shots] = [0, 0];+ return { scene, camera, options: { name: "fps-arena", width: 1280, height: 720, preset: "cinematic" as const } };+ },+ on: {+ // A discrete key, as before input: `keys` handlers fire for every game.+ restart,+ // Where the player is, on the console (the scripted test reads it).+ report() {+ const r = (v: number) => Math.round(v * 1e4) / 1e4;+ console.log(`arena ${JSON.stringify({ at: position.toArray().map(r), yaw: r(yaw), pitch: r(pitch), grounded, tagged, shots })}`);+ },+ },+ frame(f) {+ if (f.dt > 0) {+ move(f);+ // (Only with the pointer captured: the click that captures it is the app's, and never arrives here.)+ if (f.input.captured && f.input.pressed("Mouse0")) fire();+ }+ f.camera.position.set(position.x, position.y + EYE, position.z);+ f.camera.rotation.set(pitch, yaw, 0, "YXZ");++ const done = tagged === targets.length;+ const name = typeof host.launch.name === "string" ? host.launch.name : "Player";+ hud.set({+ // The crosshair opens with the player's speed.+ crosshair: { style: "cross", gap: Math.round(Math.min(Math.hypot(velocity.x, velocity.z) / SPRINT, 1) * 10) / 10 },+ items: [+ { type: "text", anchor: "top-left", label: "Tagged", text: `${tagged} / ${targets.length}`, tone: done ? "good" : "default", size: "large" },+ { type: "text", anchor: "top-right", text: name, tone: "dim", size: "small" },+ { type: "bar", anchor: "bottom-left", label: "Targets", value: tagged / targets.length, tone: "accent" },+ ...(f.input.captured ? [] : [{ type: "text" as const, anchor: "bottom" as const, text: "Click to look around · W A S D to move · Shift to sprint · Space to jump · click to tag", tone: "dim" as const }]),+ ],+ message: done ? { title: "All tagged", subtitle: `${shots} shots · R to play again`, tone: "good" } : null,+ });+ },+});diff --git a/games/host/echo.game.ts b/games/host/echo.game.tsnew file mode 100644index 0000000..07552b4--- /dev/null+++ b/games/host/echo.game.ts@@ -0,0 +1,84 @@+// The host channel in one small game (docs/RUNTIME.md "The host channel"): a game has no sockets of its own, so it+// asks the app that runs it. Opened with a socket's address (`launch`), it has the app open the socket, says hello,+// and answers each of the first messages that come back; every message raises the cube a step. Opened with an+// address to fetch, it has the app make the request.+//+// - `host.post` asks; `host.on` hears the answer, on the node that owns the scene (a listener gets the same `world` a+// world handler gets).+// - What a message means to the game is a state transaction (`world.emit("received")`), so the scene follows the+// state in `frame` like anything else that happens in the game.+// - An app without a network never answers. The game then stays as it started: the cube on the ground, the HUD+// saying "offline".+//+// node tools/bundle-game.ts games/host/echo.game.ts -o out/bundles/host-echo.js+// renderer/target/release/threert-render play out/bundles/host-echo.js --launch '{"url":"wss://echo.example/socket"}'+// node tools/host-echo.ts (the channel checked: this script as the app, then the window's real sockets)+import { BoxGeometry, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera, Scene, SkyAtmosphere } from "@threert/scene";+import { defineGame, host, hud } from "@threert/gameplay";++/** How many messages the game answers before it closes the socket. */+export const ROUNDS = 3;+const SOCKET = "echo";+let status = "offline";++host.on("launch", (m) => {+ if (typeof m.params.url === "string") {+ status = "connecting";+ host.post({ t: "net.open", id: SOCKET, url: m.params.url });+ }+ if (typeof m.params.fetch === "string") host.post({ t: "net.fetch", id: "page", url: m.params.fetch });+});+host.on("net.opened", (m) => {+ status = "open";+ host.post({ t: "net.send", id: m.id, data: "hello" });+});+host.on("net.messages", (m, world) => {+ // One batch a frame: every message that arrived since the last one, in order.+ for (const text of m.list) {+ console.log(`echo got ${JSON.stringify(text)}`);+ world.emit("received", { text });+ }+ const seen = (world.state as { received: number }).received + m.list.length;+ if (seen < ROUNDS) host.post({ t: "net.send", id: m.id, data: `again ${seen}` });+ else host.post({ t: "net.close", id: m.id });+});+host.on("net.closed", (m) => {+ status = `closed (${m.code})`;+ console.log(`echo closed ${m.code} ${m.reason}`);+});+host.on("net.fetched", (m) => console.log(`echo fetched ${m.status} ${JSON.stringify(m.body.slice(0, 40))}${m.error ? ` ${m.error}` : ""}`));++export default defineGame({+ state: { received: 0 },+ setup: () => {+ const scene = new Scene();+ const sun = new DirectionalLight(0xffffff, 90000);+ sun.setSunAngles(50, 215);+ scene.add(sun);+ scene.environment = new SkyAtmosphere({ sun });+ const camera = new PerspectiveCamera(45, 16 / 9, 0.1, 100);+ camera.position.set(3, 2.5, 6);+ camera.lookAt(0, 1, 0);+ camera.setManualExposure(14);+ const ground = new Mesh(new BoxGeometry(12, 0.2, 12), new MeshStandardMaterial({ name: "ground", color: 0x6f7468, roughness: 0.95 }));+ ground.position.y = -0.1;+ const cube = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ name: "cube", color: 0x3d7ec8, roughness: 0.6 }));+ cube.id = "cube";+ scene.add(camera, ground, cube);+ return { scene, camera, options: { name: "host-echo", width: 1280, height: 720, preset: "cinematic" as const } };+ },+ handlers: {+ received(tx) {+ tx.state.received += 1;+ },+ },+ frame(f) {+ f.object("cube")!.position.y = 0.5 + 0.5 * f.state.received;+ hud.set({+ items: [+ { type: "text", anchor: "top-left", label: "Socket", text: status, tone: status === "open" ? "good" : "dim" },+ { type: "text", anchor: "top-left", label: "Messages", text: String(f.state.received) },+ ],+ });+ },+});diff --git a/packages/gameplay/README.md b/packages/gameplay/README.mdindex f8b212e..a020c8e 100644--- a/packages/gameplay/README.md+++ b/packages/gameplay/README.md@@ -61,6 +61,7 @@ export default defineGame({- **Handlers are transactions.** A click reaches the game as a `click` event whose `target` is the object under the cursor. `tx.decide` refuses an event, and nothing is half-written.- **Deterministic and replayable.** Events are logged with what they read and wrote; `replayLog` and `verifyLog` rebuild a world from its log, and seeded randomness (`seededRandom`) gives the same result on every machine.- **World handlers** (`on`) reach the engine's own world: physics, a ray cast into the scene, objects added and removed as an event arrives.+- **Input, a HUD and the app.** A game with `pointer: "look"` reads the keys and the mouse every frame (`f.input.move`, `f.input.look`, `f.input.pressed("Space")`); `hud.set(...)` describes a crosshair, figures, bars and a scoreboard for the app to draw; `host.post` / `host.on` reach what the app owns (a WebSocket, an HTTP request, how the game was opened).How scene code runs in the engine is in [RUNTIME.md](https://github.com/meshy-dev/ThreeRT/blob/main/docs/RUNTIME.md).diff --git a/packages/gameplay/src/frame.ts b/packages/gameplay/src/frame.tsindex 1c8ee7b..d3e7c5e 100644--- a/packages/gameplay/src/frame.ts+++ b/packages/gameplay/src/frame.ts@@ -13,6 +13,7 @@// changes, not every frame on a big street.import type { Object3D, PerspectiveCamera, Scene } from "@threert/scene";+import { InputState, type Input } from "./input.ts";import { seededRandom } from "./random.ts";import type { Store } from "./store.ts";@@ -34,6 +35,8 @@ export interface FrameContext<S> {object(id: string): Object3D | undefined;/** Random stream of this node's frame loop (seeded from the room seed). */random(): number;+ /** What the player holds and moves this frame (input.ts): nothing, unless the game asked for input (`pointer`). */+ readonly input: Input;}export type FrameFn<S> = (f: FrameContext<S>) => void;@@ -48,8 +51,11 @@ export class FrameRunner<S> {readonly scene: Scene;readonly camera: PerspectiveCamera;private ids = new Map<string, Object3D>();+ /** The node's input, as the app last sent it (`f.input`, `world.input`). */+ readonly input: InputState;- constructor(fn: FrameFn<S> | undefined, store: Store, seed: number, scene: Scene, camera: PerspectiveCamera) {+ constructor(fn: FrameFn<S> | undefined, store: Store, seed: number, scene: Scene, camera: PerspectiveCamera, input = new InputState()) {+ this.input = input;this.fn = fn;this.store = store;this.scene = scene;@@ -97,7 +103,7 @@ export class FrameRunner<S> {dt = Math.min(Math.max(dt, 0), 0.1);this.time += dt;if (!this.fn) return;- this.fn({ time: this.time, dt, snap, now, state: this.committed(), scene: this.scene, camera: this.camera, object: (id) => this.object(id), random: this.random });+ this.fn({ time: this.time, dt, snap, now, state: this.committed(), scene: this.scene, camera: this.camera, object: (id) => this.object(id), random: this.random, input: this.input });}}diff --git a/packages/gameplay/src/game.ts b/packages/gameplay/src/game.tsindex 11f1946..fb0d183 100644--- a/packages/gameplay/src/game.ts+++ b/packages/gameplay/src/game.ts@@ -50,6 +50,14 @@ export interface GameDefinition<S = JsonObject> {on?: Record<string, WorldHandler<S>>;/** Keyboard shortcuts of the native viewer and the playground: key ("R", "Space") -> handler or world handler. */keys?: Record<string, string>;+ /**+ * The game reads input every frame (`f.input`, `world.input`; input.ts) and its camera is its own: the app that+ * shows it sends the input and leaves the camera alone (no orbit or fly controls of its own).+ * - `"look"`: the app captures the pointer (Esc lets go, a click takes it again) and its motion is `input.look`.+ * - `"free"`: the pointer stays free; `input.pointer` is where it is.+ * Left out: no input is sent, and the app keeps its own camera controls. `keys` work in every case.+ */+ pointer?: "look" | "free";}/** What `defineGame` takes: a game, whose `handlers` may be left out when it has world handlers (`on`) only. */@@ -72,14 +80,15 @@ export function defineGame<S>(input: GameInput<S>): GameDefinition<S> {if (!game.handlers || typeof game.handlers !== "object") throw new TypeError("defineGame: handlers are required");for (const [type, h] of Object.entries(game.handlers)) if (typeof h !== "function") throw new TypeError(`defineGame: handler "${type}" is not a function`);if (game.frame !== undefined && typeof game.frame !== "function") throw new TypeError("defineGame: frame must be a function");+ if (game.pointer !== undefined && game.pointer !== "look" && game.pointer !== "free") throw new TypeError('defineGame: pointer must be "look" or "free"');for (const [key, h] of Object.entries(game.keys ?? {})) if (!game.handlers[h] && !game.on?.[h]) throw new TypeError(`defineGame: key "${key}" maps to unknown handler "${h}"`);if (canonicalJson(game.state) !== canonicalJson(JSON.parse(JSON.stringify(game.state ?? {})))) throw new TypeError("defineGame: state must be plain JSON");return game;}/** What a game has: `handlers` are the state's (a room runs them), `on` the world's (the node that owns the scene). */-export function describeGame(game: GameDefinition<unknown>): { handlers: string[]; on: string[]; tick: boolean; frame: boolean; keys: Record<string, string>; seed: number | null } {- return { handlers: Object.keys(game.handlers), on: Object.keys(game.on ?? {}), tick: typeof game.tick === "function", frame: typeof game.frame === "function", keys: gameKeys(game), seed: game.seed ?? null };+export function describeGame(game: GameDefinition<unknown>): { handlers: string[]; on: string[]; tick: boolean; frame: boolean; keys: Record<string, string>; seed: number | null; pointer: "look" | "free" | null } {+ return { handlers: Object.keys(game.handlers), on: Object.keys(game.on ?? {}), tick: typeof game.tick === "function", frame: typeof game.frame === "function", keys: gameKeys(game), seed: game.seed ?? null, pointer: game.pointer ?? null };}/** The room's seed: the game's, else derived from the room id. */diff --git a/packages/gameplay/src/host.ts b/packages/gameplay/src/host.tsnew file mode 100644index 0000000..6cd79aa--- /dev/null+++ b/packages/gameplay/src/host.ts@@ -0,0 +1,136 @@+// The host channel: messages between game code and the app that embeds the engine (the native window, a browser page,+// a client of its own). Scripts have no I/O and no timers; what needs the outside (a socket, an HTTP request, a HUD+// drawn over the picture, how the game was opened) is asked of the app, which answers when it has something.+//+// host.post({ t: "net.open", id: "lobby", url: "wss://example.org/room/K7Q4MZ" }); // script -> app+// const off = host.on("net.messages", (m, world) => { for (const text of m.list) ... }); // app -> script+//+// - A message is a JSON object with a string `t`, its type. `post` queues its JSON text for the app; the app drains+// the queue after each entry into the script (at least once a frame).+// - The app hands its messages to the node host in batches (node-host.ts `hostMessages`); each goes to the listeners+// of its type, in the order they were added. Listeners run on the node that owns the scene, as world handlers do+// (world.ts): they get the same context, may change the scene, and what they changed reaches the engine when the+// batch returns. `world.emit(type, payload)` starts a state transaction.+// - A listener that throws does not stop the batch: the next listener and the next message run all the same, and+// the error is logged.+// - An app may implement none of it. A post nobody takes is dropped (`post` returns false when no app is there),+// and a game must not wait for an answer in order to go on.+// - The same object is `globalThis.__threert_host`, for a library that does not import this package.+//+// The message families an app may implement are in docs/RUNTIME.md ("The host channel"): `net.*` (sockets and HTTP+// the app owns), `hud` (hud.ts), `launch` (how the game was opened), and `input` (input.ts), which the node host+// takes itself.++import type { WorldContext } from "./world.ts";++/** A message of the channel, either way: plain JSON with its type in `t`. */+export interface HostMessage {+ t: string;+ [key: string]: unknown;+}++/** How the app opened the game (`{ t: "launch", params }`): a room to join, the player's name, anything else. */+export interface LaunchParams {+ room?: string;+ name?: string;+ [key: string]: unknown;+}++/** What a game posts to an app that implements `net.*`. `id` is the game's name for the socket or the request. */+export type NetPost =+ | { t: "net.open"; id: string; url: string; protocols?: string[] }+ | { t: "net.send"; id: string; data: string }+ | { t: "net.close"; id: string; code?: number; reason?: string }+ | { t: "net.fetch"; id: string; method?: string; url: string; headers?: Record<string, string>; body?: string };++/** What the app answers, by type. */+export interface HostEvents {+ /** The socket `id` is open: `net.send` goes out from here on. */+ "net.opened": { t: "net.opened"; id: string };+ /** The text messages that arrived on `id` since the last frame, in order: one batch a frame. */+ "net.messages": { t: "net.messages"; id: string; list: string[] };+ /** The socket closed, or never opened (`code` 1006, `reason` says why). */+ "net.closed": { t: "net.closed"; id: string; code: number; reason: string };+ /** A `net.fetch`'s answer. `status` 0: the request failed (`error`). */+ "net.fetched": { t: "net.fetched"; id: string; status: number; body: string; error?: string };+ /** Once after setup. */+ launch: { t: "launch"; params: LaunchParams };+}++// eslint-disable-next-line @typescript-eslint/no-explicit-any+export type HostListener<M = any> = (message: M, world: WorldContext<any>) => void;++export interface Host {+ /**+ * Queues a message for the app. True if an app's queue took it; false when the game runs where nothing listens+ * (a render node, a test). Throws on a message that is not JSON with a string `t`.+ */+ post(message: NetPost | HostMessage): boolean;+ /** Calls `fn` with every message of type `type` the app sends. Returns the function that removes it. */+ on<K extends keyof HostEvents>(type: K, fn: HostListener<HostEvents[K]>): () => void;+ on(type: string, fn: HostListener<HostMessage>): () => void;+ /** The `launch` message's `params`; `{}` until the app has sent one (and for an app that never does). */+ readonly launch: Readonly<LaunchParams>;+}++/** The node host's side of the channel (node-host.ts). */+export interface HostChannel extends Host {+ /** Whether a message of this type has a listener. */+ listens(type: string): boolean;+ /** Hands `message` to its listeners. Returns the errors of those that threw. */+ deliver(message: HostMessage, world: WorldContext<unknown>): string[];+ setLaunch(params: unknown): void;+}++function makeHost(): HostChannel {+ const listeners = new Map<string, HostListener[]>();+ let launch: Readonly<LaunchParams> = Object.freeze({});+ return {+ post(message) {+ if (!message || typeof message !== "object" || typeof message.t !== "string" || !message.t) throw new TypeError('host.post: a message is an object with a string "t"');+ const text = JSON.stringify(message) as string | undefined;+ if (text === undefined) throw new TypeError(`host.post(${message.t}): the message must be plain JSON`);+ // The app's queue: a native of the embedded runtime, or a function the page set before it loaded the game.+ const sink = (globalThis as { __host_post?: (text: string) => unknown }).__host_post;+ return typeof sink === "function" ? sink(text) !== false : false;+ },+ on(type: string, fn: HostListener) {+ if (typeof type !== "string" || !type) throw new TypeError("host.on: the message type must be a non-empty string");+ if (typeof fn !== "function") throw new TypeError(`host.on(${type}): the listener must be a function`);+ const list = listeners.get(type) ?? [];+ listeners.set(type, [...list, fn]);+ return () => {+ const now = listeners.get(type) ?? [];+ const k = now.indexOf(fn);+ if (k >= 0) listeners.set(type, [...now.slice(0, k), ...now.slice(k + 1)]);+ };+ },+ get launch() {+ return launch;+ },+ listens: (type) => (listeners.get(type)?.length ?? 0) > 0,+ deliver(message, world) {+ const errors: string[] = [];+ // (The list as it was when the message arrived: a listener that removes itself, or adds one, changes the next.)+ for (const fn of listeners.get(message.t) ?? []) {+ try {+ const r: unknown = fn(message, world);+ if (typeof (r as PromiseLike<unknown> | undefined)?.then === "function") throw new Error("host listeners must be synchronous: the engine's next tick does not wait for an await");+ } catch (e) {+ errors.push(e instanceof Error ? (e.stack ?? e.message) : String(e));+ }+ }+ return errors;+ },+ setLaunch(params) {+ launch = Object.freeze(params && typeof params === "object" && !Array.isArray(params) ? { ...(params as LaunchParams) } : {});+ },+ };+}++/** One channel a runtime, whoever asks first: a second copy of this module (a library's own) finds the first's. */+const shared = globalThis as { __threert_host?: HostChannel };+export const channel: HostChannel = (shared.__threert_host ??= makeHost());++/** The host channel (the same object as `globalThis.__threert_host`). */+export const host: Host = channel;diff --git a/packages/gameplay/src/hud.ts b/packages/gameplay/src/hud.tsnew file mode 100644index 0000000..527c5a0--- /dev/null+++ b/packages/gameplay/src/hud.ts@@ -0,0 +1,162 @@+// The HUD: what the app draws over the picture, described by the game. The engine draws none of it: `hud.set(...)`+// posts `{ t: "hud", hud }` on the host channel (host.ts) when the description changed, and the app that embeds the+// engine draws it its own way (a DOM overlay in a browser, native views in a client; `threert-render play --hud-log`+// prints it). An app that draws no HUD ignores the message.+//+// frame(f) {+// hud.set({+// crosshair: { style: "cross", gap: spread },+// items: [+// { type: "text", anchor: "top-left", label: "Tagged", text: `${tagged} / ${total}` },+// { type: "bar", anchor: "bottom-left", label: "Health", value: health / 100, tone: health < 30 ? "bad" : "good" },+// { type: "list", anchor: "top-right", lines: feed }, // a kill feed: lines with a ttl+// ...(f.input.down("Tab") ? [{ type: "table" as const, anchor: "center" as const, columns: ["Player", "Score"], rows }] : []),+// ],+// message: round ? { title: `Round ${round}`, subtitle: "Tag every target" } : undefined,+// });+// }+//+// - The description is the whole HUD: what is not in it is not shown. Call `hud.set` every frame with what the frame+// shows; nothing is posted while it stays the same.+// - `hud.flash(kind, angle?)` is the one thing that is an event: a hit marker, or the direction damage came from.+// - Text is plain text: an app shows it as it is, never as markup.++import { host } from "./host.ts";+import { canonicalJson } from "./store.ts";++/** Where an item sits: the corners, the edges' middles, the centre. Items of one anchor stack in their order. */+export type HudAnchor = "top-left" | "top" | "top-right" | "left" | "center" | "right" | "bottom-left" | "bottom" | "bottom-right";++/** What a value means, for the app to colour: `good` (health, a gain), `warn`, `bad` (danger, a loss), `accent` (the+ * player's own), `dim` (secondary). */+export type HudTone = "default" | "good" | "warn" | "bad" | "accent" | "dim";++/** A figure or a line of text, with an optional small label ("Ammo" over "24 / 90"). */+export interface HudText {+ type: "text";+ anchor: HudAnchor;+ text: string;+ label?: string;+ tone?: HudTone;+ size?: "small" | "normal" | "large";+}++/** A bar filled to `value` (0..1): health, a reload, a round's time. */+export interface HudBar {+ type: "bar";+ anchor: HudAnchor;+ value: number;+ label?: string;+ /** A figure beside the bar ("72"). */+ text?: string;+ tone?: HudTone;+}++/** A line of a list. With `ttl` the app shows it for that many seconds from when it first got it (the same `id`, or+ * the same text without one) and then drops it, whether or not the game still lists it. */+export interface HudLine {+ text: string;+ tone?: HudTone;+ ttl?: number;+ id?: string;+}++/** Short lines, newest last: a kill feed, objectives. */+export interface HudList {+ type: "list";+ anchor: HudAnchor;+ lines: (string | HudLine)[];+}++/** A table: a scoreboard, shown while the game lists it (`f.input.down("Tab")`). */+export interface HudTable {+ type: "table";+ anchor: HudAnchor;+ title?: string;+ columns: string[];+ rows: (string | number)[][];+ /** The row to set apart (the player's own). */+ highlight?: number;+}++export type HudItem = HudText | HudBar | HudList | HudTable;++/** The mark at the picture's centre. `gap` (0..1) opens it: a weapon's spread, a moving player's. */+export interface HudCrosshair {+ style: "dot" | "cross" | "circle";+ gap?: number;+ tone?: HudTone;+}++/** The centre message: "Round 2", "You were eliminated". */+export interface HudMessage {+ title: string;+ subtitle?: string;+ tone?: HudTone;+}++/** A flash: `hit` (the shot landed: a hit marker at the crosshair), `kill`, `damage` (the player was hit; `angle`,+ * radians clockwise from straight ahead, is where it came from). The app plays it when `n` changes. */+export interface HudFlash {+ kind: "hit" | "kill" | "damage";+ angle?: number;+ n: number;+}++export interface Hud {+ crosshair?: HudCrosshair | null;+ items?: HudItem[];+ message?: HudMessage | null;+ flash?: HudFlash;+}++const ANCHORS: readonly string[] = ["top-left", "top", "top-right", "left", "center", "right", "bottom-left", "bottom", "bottom-right"];+const ITEMS: readonly string[] = ["text", "bar", "list", "table"];++function check(h: Hud): void {+ if (!h || typeof h !== "object") throw new TypeError("hud.set: the HUD is an object ({ crosshair, items, message })");+ for (const [k, item] of (h.items ?? []).entries()) {+ if (!item || !ITEMS.includes(item.type)) throw new TypeError(`hud.set: items[${k}].type must be one of ${ITEMS.join(", ")}`);+ if (!ANCHORS.includes(item.anchor)) throw new TypeError(`hud.set: items[${k}].anchor must be one of ${ANCHORS.join(", ")}`);+ }+}++class HudState {+ private sent: string | null = null;+ private flashed: HudFlash | null = null;+ private last: Hud = {};++ /** Shows `h` as the whole HUD. Posts it when it differs from the last one posted; true if it did. */+ set(h: Hud): boolean {+ check(h);+ this.last = h;+ // (The last flash stays in what is posted: an app plays one when its `n` changes, not when it is there.)+ const hud: Hud = this.flashed ? { ...h, flash: this.flashed } : h;+ const text = canonicalJson(hud);+ if (text === this.sent) return false;+ this.sent = text;+ host.post({ t: "hud", hud: JSON.parse(text) as Hud });+ return true;+ }++ /** A flash, now: the HUD as last set is posted again with it. */+ flash(kind: HudFlash["kind"], angle?: number): void {+ this.flashed = { kind, ...(angle === undefined ? {} : { angle }), n: (this.flashed?.n ?? 0) + 1 };+ this.set(this.last);+ }++ /** Nothing shown. */+ clear(): void {+ this.set({});+ }++ /** Forgets what was posted (the node host, when the scene is built anew): the next `set` posts. */+ reset(): void {+ this.sent = null;+ this.last = {};+ }+}++/** The game's HUD. */+export const hud = new HudState();+export type { HudState };diff --git a/packages/gameplay/src/index.ts b/packages/gameplay/src/index.tsindex d6b699c..e9866f9 100644--- a/packages/gameplay/src/index.ts+++ b/packages/gameplay/src/index.ts@@ -4,6 +4,12 @@ export type { FrameContext, FrameFn } from "./frame.ts";export { installNodeHost } from "./node-host.ts";export type { NodeHost } from "./node-host.ts";export type { ExecResult, GameDefinition, GameInput, Handler, LogEntry, SetupContext, SetupResult, VerifyReport } from "./game.ts";+export { host } from "./host.ts";+export type { Host, HostEvents, HostListener, HostMessage, LaunchParams, NetPost } from "./host.ts";+export { InputState } from "./input.ts";+export type { Input, InputMessage } from "./input.ts";+export { hud } from "./hud.ts";+export type { Hud, HudAnchor, HudBar, HudCrosshair, HudFlash, HudItem, HudLine, HudList, HudMessage, HudState, HudTable, HudText, HudTone } from "./hud.ts";export { runWorldHandler } from "./world.ts";export type { WorldContext, WorldHandler } from "./world.ts";export { Failure, isFailure, normalizeRenderRequest, Transaction } from "./tx.ts";diff --git a/packages/gameplay/src/input.ts b/packages/gameplay/src/input.tsnew file mode 100644index 0000000..d85bbcc--- /dev/null+++ b/packages/gameplay/src/input.ts@@ -0,0 +1,157 @@+// Input: what the player holds and moves, read by game code every frame (`f.input` in the frame script, `world.input`+// in world handlers and host listeners). The app sends one `{ t: "input", ... }` message a frame, before the frame+// script (the host channel, host.ts); the node host keeps it here.+//+// frame(f) {+// const { x, y } = f.input.move; // WASD, or a stick: x right, y forward, length <= 1+// yaw -= f.input.look.dx; pitch -= f.input.look.dy; // radians+// if (f.input.pressed("Space") && grounded) jump();+// if (f.input.pressed("Mouse0")) fire();+// }+//+// - Keys are named by their place on a US keyboard, whatever the layout prints on them: "A".."Z", "0".."9",+// "Space", "Shift", "Ctrl", "Alt", "Meta", "Tab", "Enter", "Escape", "Backspace", "Left", "Right", "Up", "Down",+// "F1".."F12", "Minus", "Equal", "BracketLeft", "BracketRight", "Semicolon", "Quote", "Comma", "Period", "Slash",+// "Backslash", "Backquote". Mouse buttons are keys too: "Mouse0" (left), "Mouse1" (middle), "Mouse2" (right). A+// gamepad's or a touch screen's buttons arrive under the names of the keys they stand for.+// - `pressed` / `released` are true for one frame: from the input message that brought them to the end of the next+// frame script. A key tapped between two frames is pressed and released in the same frame, and not down.+// - `look` is an angle, radians: how far to turn this frame, `dx` to the right, `dy` down. The app turns its device+// into it (mouse counts at the player's sensitivity, a stick's rate over the frame), so a game applies it as it is.+// - A game asks for input in its definition: `pointer: "look"` (the app captures the pointer and sends `look`) or+// `pointer: "free"` (the pointer stays free; `pointer` is where it is). Without either the app sends none, and+// everything here reads as nothing held.+// - A frame without an input message: what was held stays held, nothing is pressed or released, `look` and `wheel`+// are 0.++/** The app's input message: everything optional but `t`; a field left out keeps (state) or is 0 (deltas). */+export interface InputMessage {+ t: "input";+ /** Every key and mouse button held now (the names above). */+ keys?: string[];+ /** Keys that went down / up since the last message. Left out: taken from how `keys` changed. */+ pressed?: string[];+ released?: string[];+ /** Mouse buttons held now, by number (0 left, 1 middle, 2 right): the same as "Mouse<n>" in `keys`. */+ buttons?: number[];+ /** The pointer in the picture, 0..1 from its top left; (0.5, 0.5) while captured. */+ u?: number;+ v?: number;+ /** Look since the last message, radians: right and down are positive. */+ dx?: number;+ dy?: number;+ /** Wheel notches since the last message; away from the player is positive. */+ wheel?: number;+ /** The pointer is captured (its motion is `dx` / `dy`, the cursor hidden). */+ captured?: boolean;+ /** A move stick (gamepad, touch): x right, y forward, each -1..1. Null or left out: none, `move` is WASD. */+ move?: [number, number] | null;+}++/** The input as game code reads it. */+export interface Input {+ /** The key (or "Mouse0"...) is held. */+ down(key: string): boolean;+ /** It went down since the last frame. */+ pressed(key: string): boolean;+ /** It went up since the last frame. */+ released(key: string): boolean;+ /** -1 with `negative` held, 1 with `positive`, 0 with both or neither. */+ axis(negative: string, positive: string): number;+ /** Mouse button `n` is held (0 left, 1 middle, 2 right): `down("Mouse<n>")`. */+ button(n: number): boolean;+ /** How far to turn this frame, radians. */+ readonly look: { readonly dx: number; readonly dy: number };+ /** Where the pointer is in the picture, 0..1 from the top left. */+ readonly pointer: { readonly u: number; readonly v: number };+ /** Wheel notches this frame. */+ readonly wheel: number;+ /** The app has the pointer captured. */+ readonly captured: boolean;+ /** Where to move: the app's stick if it sent one, else W A S D. x right, y forward; never longer than 1. */+ readonly move: { readonly x: number; readonly y: number };+}++const finite = (v: unknown, d = 0): number => (typeof v === "number" && Number.isFinite(v) ? v : d);+const names = (v: unknown): string[] => (Array.isArray(v) ? v.filter((k): k is string => typeof k === "string" && k.length > 0 && k.length <= 32) : []);++/** The node host's input state: `apply` takes the app's message, `endFrame` ends what lasts a frame. */+export class InputState implements Input {+ /** What `keys` and `buttons` last said, and the two together. */+ private keys = new Set<string>();+ private buttons = new Set<string>();+ private held = new Set<string>();+ private went = new Set<string>();+ private left = new Set<string>();+ private stick: [number, number] | null = null;+ look = { dx: 0, dy: 0 };+ pointer = { u: 0.5, v: 0.5 };+ wheel = 0;+ captured = false;++ down(key: string): boolean {+ return this.held.has(key);+ }++ pressed(key: string): boolean {+ return this.went.has(key);+ }++ released(key: string): boolean {+ return this.left.has(key);+ }++ axis(negative: string, positive: string): number {+ return (this.held.has(positive) ? 1 : 0) - (this.held.has(negative) ? 1 : 0);+ }++ button(n: number): boolean {+ return this.held.has(`Mouse${n}`);+ }++ get move(): { x: number; y: number } {+ let [x, y] = this.stick ?? [this.axis("A", "D"), this.axis("S", "W")];+ const l = Math.hypot(x, y);+ if (l > 1) [x, y] = [x / l, y / l];+ return { x, y };+ }++ /** An input message of the app. Two before one frame add up: their edges, their look, their wheel. */+ apply(m: InputMessage): void {+ if (m.keys !== undefined) this.keys = new Set(names(m.keys));+ if (m.buttons !== undefined) this.buttons = new Set((Array.isArray(m.buttons) ? m.buttons : []).filter((b) => Number.isInteger(b) && b >= 0 && b < 16).map((b) => `Mouse${b}`));+ if (m.keys !== undefined || m.buttons !== undefined) {+ const now = new Set([...this.keys, ...this.buttons]);+ // (Edges the app did not name: how the held set changed.)+ if (m.pressed === undefined) for (const k of now) if (!this.held.has(k)) this.went.add(k);+ if (m.released === undefined) for (const k of this.held) if (!now.has(k)) this.left.add(k);+ this.held = now;+ }+ for (const k of names(m.pressed)) this.went.add(k);+ for (const k of names(m.released)) this.left.add(k);+ this.look = { dx: this.look.dx + finite(m.dx), dy: this.look.dy + finite(m.dy) };+ this.wheel += finite(m.wheel);+ if (m.u !== undefined || m.v !== undefined) this.pointer = { u: finite(m.u, this.pointer.u), v: finite(m.v, this.pointer.v) };+ if (m.captured !== undefined) this.captured = m.captured === true;+ if (m.move !== undefined) this.stick = Array.isArray(m.move) ? [Math.max(-1, Math.min(1, finite(m.move[0]))), Math.max(-1, Math.min(1, finite(m.move[1])))] : null;+ }++ /** A frame script ran: what was pressed, released, turned and scrolled is over. */+ endFrame(): void {+ if (this.went.size) this.went = new Set();+ if (this.left.size) this.left = new Set();+ if (this.look.dx !== 0 || this.look.dy !== 0) this.look = { dx: 0, dy: 0 };+ this.wheel = 0;+ }++ /** Nothing held (a scene built anew). */+ reset(): void {+ this.keys = new Set();+ this.buttons = new Set();+ this.held = new Set();+ this.stick = null;+ this.captured = false;+ this.pointer = { u: 0.5, v: 0.5 };+ this.endFrame();+ }+}diff --git a/packages/gameplay/src/node-host.ts b/packages/gameplay/src/node-host.tsindex 19c3e85..4a4f5dc 100644--- a/packages/gameplay/src/node-host.ts+++ b/packages/gameplay/src/node-host.ts@@ -10,6 +10,9 @@// setState(state, seq) replace the state (a render of a room's current state)// state() the committed state and its sequence number// frame(dt, now) the game's frame script+// hostMessages(list, ts) the app's messages (host.ts), a batch in one entry: `input` is kept for `f.input`+// and `world.input` (input.ts), the others go to their `host.on` listeners, which+// change the scene as world handlers do// seek(time, now) the frame script's clock set to `time`, the scene shown settled at that moment (an// offline render at a scene time: the timeline a frame script draws)// outline() / inspect(name) / edit(name, path, value) the editor: the live scene, not a document (name "" = the@@ -23,8 +26,12 @@ import {} from "@threert/scene";import { buildScene, describeGame, executeEvent, gameKeys, initialWorld, type GameDefinition } from "./game.ts";import { FrameRunner } from "./frame.ts";+import { channel, type HostMessage } from "./host.ts";+import { hud } from "./hud.ts";+import { InputState, type InputMessage } from "./input.ts";+import { withDeterminism } from "./random.ts";import { applyCommitted, commit, createStore, type Json, type JsonObject, type Store, type Write } from "./store.ts";-import { runWorldHandler } from "./world.ts";+import { runWorldHandler, worldContext } from "./world.ts";export interface NodeHost {describe(): string;@@ -34,6 +41,7 @@ export interface NodeHost {setState(state: string, seq: number): void;state(): string;frame(dt: number, now: number): void;+ hostMessages(list: string, ts: number): void;seek(time: number, now: number): void;outline(): string;inspect(name: string): string;@@ -45,6 +53,8 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):let frames: FrameRunner<unknown> | null = null;let binding: SceneBinding | null = null;let eventId = 0;+ // (The node's input outlives a scene built anew in the same runtime: the keys the player holds are still held.)+ const input = new InputState();const live = () => {if (!store || !frames || !binding) throw new Error("setup() has not run");return { store, frames, binding };@@ -56,6 +66,26 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):frames.run(0, now, snap);binding.sync();};+ /** The state transactions of `queue`, each with the events it emits after it; what they wrote and how they went. */+ const transact = (queue: { type: string; payload: Json; id?: number }[], ts: number, writes: Write[], log: string[]) => {+ const { store } = live();+ while (queue.length) {+ const ev = queue.shift()!;+ const res = executeEvent(game, store, { id: ev.id ?? ++eventId, type: ev.type, payload: ev.payload, ts });+ if (res.status === "error") {+ log.push(`✗ ${ev.type}: error ${res.failure?.split("\n")[0]}`);+ continue;+ }+ const c = commit(store, res);+ if (!c.ok) {+ log.push(`✗ ${ev.type}: conflict on ${c.conflicts.join(", ")}`);+ continue;+ }+ writes.push(...c.applied);+ queue.push(...res.emits.map((e) => ({ type: e.type, payload: e.payload })));+ if (ev.type !== "tick") log.push(`${res.status === "ok" ? "✓" : "✗"} seq ${c.seq} ${ev.type}${res.failure ? ` — ${res.failure}` : ""} · ${Object.keys(res.reads).length}R/${res.writes.length}W`);+ }+ };const object = (name: string): Object3D => {const o = live().binding.objectNamed(name);if (!o) throw new Error(`no object "${name}"`);@@ -68,7 +98,9 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):const t0 = Date.now();const s = buildScene(game, { roomId, seed: seed ?? undefined });store = createStore(initialWorld(game), s.seed);- frames = new FrameRunner(game.frame, store, s.seed, s.scene, s.camera);+ frames = new FrameRunner(game.frame, store, s.seed, s.scene, s.camera, input);+ // (An app that kept the HUD of the scene before gets this one's first description whatever it says.)+ hud.reset();const eng = engine ?? (globalThis as { __engine?: Engine }).__engine;if (!eng) throw new Error("no engine: run the bundle in the renderer (threert-render play / live / render)");binding = new SceneBinding(eng, s.scene, s.camera, s.options);@@ -99,22 +131,7 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):binding.sync();return JSON.stringify({ writes, log, seq: store.seq });}- while (queue.length) {- const ev = queue.shift()!;- const res = executeEvent(game, store, { id: ev.id ?? ++eventId, type: ev.type, payload: ev.payload, ts });- if (res.status === "error") {- log.push(`✗ ${ev.type}: error ${res.failure?.split("\n")[0]}`);- continue;- }- const c = commit(store, res);- if (!c.ok) {- log.push(`✗ ${ev.type}: conflict on ${c.conflicts.join(", ")}`);- continue;- }- writes.push(...c.applied);- queue.push(...res.emits.map((e) => ({ type: e.type, payload: e.payload })));- if (ev.type !== "tick") log.push(`${res.status === "ok" ? "✓" : "✗"} seq ${c.seq} ${ev.type}${res.failure ? ` — ${res.failure}` : ""} · ${Object.keys(res.reads).length}R/${res.writes.length}W`);- }+ transact(queue, ts, writes, log);refresh(ts);return JSON.stringify({ writes, log, seq: store.seq });},@@ -150,6 +167,8 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):} catch (error) {failed = { error };}+ // What the input message brought for a frame (pressed, released, look, wheel) ends with the frame.+ input.endFrame();try {binding.sync();} catch (error) {@@ -159,6 +178,38 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):if (failed) throw failed.error;},+ hostMessages(list, ts) {+ const { store, frames, binding } = live();+ const messages = JSON.parse(list) as unknown;+ if (!Array.isArray(messages)) throw new TypeError("hostMessages: a JSON array of messages");+ // One context for the batch, made when the first listener is to run: a batch of input alone (every frame's)+ // runs no game code and sends the engine nothing.+ let ctx: ReturnType<typeof worldContext<unknown>> | null = null;+ for (const m of messages as (HostMessage | null)[]) {+ if (!m || typeof m !== "object" || typeof m.t !== "string") continue;+ if (m.t === "input") {+ input.apply(m as unknown as InputMessage);+ continue;+ }+ if (m.t === "launch") channel.setLaunch(m.params);+ if (!channel.listens(m.t)) continue;+ ctx ??= worldContext(frames, store.seed, { id: ++eventId, ts });+ const { world, random } = ctx;+ for (const error of withDeterminism(ts, random, () => channel.deliver(m, world))) console.error(`host message ${m.t}: ${error}`);+ }+ if (!ctx) return;+ // As after a world handler: the engine follows the scene as the listeners left it; the state events they+ // emitted are transactions, and the frame script then shows the new state.+ if (!ctx.emits.length) {+ binding.sync();+ return;+ }+ const log: string[] = [];+ transact(ctx.emits.splice(0), ts, [], log);+ for (const l of log) if (l.startsWith("✗")) console.error(l);+ refresh(ts);+ },+seek(time, now) {live().frames.seek(time);refresh(now, true);diff --git a/packages/gameplay/src/world.ts b/packages/gameplay/src/world.tsindex 1b0ff3f..2c0b622 100644--- a/packages/gameplay/src/world.ts+++ b/packages/gameplay/src/world.ts@@ -36,6 +36,7 @@import type { Object3D, PerspectiveCamera, Scene } from "@threert/scene";import type { FrameRunner } from "./frame.ts";+import type { Input } from "./input.ts";import { seededRandom, withDeterminism } from "./random.ts";import type { GameEvent } from "./tx.ts";import type { Json } from "./store.ts";@@ -56,6 +57,8 @@ export interface WorldContext<S> {random(): number;/** Starts a state transaction: `handlers[type]` runs with `payload` after this handler and the event's own. */emit(type: string, payload?: unknown): void;+ /** What the player holds and moves (input.ts), as of the app's last input message. */+ readonly input: Input;}/** A world handler: receives a copy of the event payload. Must be synchronous. */@@ -65,11 +68,9 @@ export type WorldHandler<S> = (world: WorldContext<S>, ev: any) => void;/** The random stream of a world handler's event (the transaction of the same event has stream `event.id`). */const WORLD_STREAM = 0x40000000;-/**- * Runs `on[event.type]` on this node. Returns the state events it emitted and its error, if it threw (what it had- * emitted before is dropped with it, as a failed transaction's emits are).- */-export function runWorldHandler<S>(handler: WorldHandler<S>, frames: FrameRunner<S>, seed: number, event: GameEvent): { emits: { type: string; payload: Json }[]; error?: string } {+/** The context of what runs on this node for `event` (a world handler, the listeners of a batch of host messages),+ * with the state events it emits and its random stream. */+export function worldContext<S>(frames: FrameRunner<S>, seed: number, event: { id: number; ts: number }): { world: WorldContext<S>; emits: { type: string; payload: Json }[]; random: () => number } {const emits: { type: string; payload: Json }[] = [];const random = seededRandom(seed, (event.id + WORLD_STREAM) >>> 0);const world: WorldContext<S> = {@@ -86,7 +87,17 @@ export function runWorldHandler<S>(handler: WorldHandler<S>, frames: FrameRunnerif (text === undefined) throw new TypeError(`emit(${type}): the payload must be plain JSON`);emits.push({ type, payload: JSON.parse(text) as Json });},+ input: frames.input,};+ return { world, emits, random };+}++/**+ * Runs `on[event.type]` on this node. Returns the state events it emitted and its error, if it threw (what it had+ * emitted before is dropped with it, as a failed transaction's emits are).+ */+export function runWorldHandler<S>(handler: WorldHandler<S>, frames: FrameRunner<S>, seed: number, event: GameEvent): { emits: { type: string; payload: Json }[]; error?: string } {+ const { world, emits, random } = worldContext(frames, seed, event);try {withDeterminism(event.ts, random, () => {const r: unknown = handler(world, structuredClone(event.payload));diff --git a/packages/gameplay/test/host.test.ts b/packages/gameplay/test/host.test.tsnew file mode 100644index 0000000..a90864a--- /dev/null+++ b/packages/gameplay/test/host.test.ts@@ -0,0 +1,231 @@+// The host channel (src/host.ts), input (src/input.ts) and the HUD (src/hud.ts): what a game posts reaches the app's+// queue, what the app sends reaches the game's listeners on the node that owns the scene, the input message becomes+// `f.input` / `world.input` with edges that last a frame, and the HUD is posted when it changed.+import { test } from "node:test";+import assert from "node:assert/strict";+import { BoxGeometry, Mesh, MeshStandardMaterial, PerspectiveCamera, RecordingEngine, Scene } from "@threert/scene";+import { defineGame, host, hud, InputState, type GameDefinition, type Hud, type Input } from "../src/index.ts";+import * as gameplay from "../src/index.ts";++type AnyGame = GameDefinition<unknown>;+const installNodeHost = <S>(g: GameDefinition<S>, engine?: RecordingEngine) => gameplay.installNodeHost(g as AnyGame, engine);+const kinds = (calls: [string, ...unknown[]][]) => calls.map((c) => c[0]);++/** The app's queue: what `__host_post` (a native in the renderer, a function in a page) is given. */+function app(): { posts: { t: string; [k: string]: unknown }[]; close(): void } {+ const posts: { t: string }[] = [];+ const g = globalThis as { __host_post?: (text: string) => unknown };+ g.__host_post = (text) => void posts.push(JSON.parse(text));+ return { posts, close: () => void delete g.__host_post };+}++function scene() {+ const scene = new Scene(), camera = new PerspectiveCamera(50, 16 / 9);+ const ground = new Mesh(new BoxGeometry(10, 0.1, 10), new MeshStandardMaterial({ name: "ground" }));+ ground.id = "ground";+ scene.add(camera, ground);+ return { scene, camera };+}++const send = (h: gameplay.NodeHost, ...messages: object[]) => h.hostMessages(JSON.stringify(messages), 1000);++test("a post goes to the app's queue as JSON text; without an app it is dropped", () => {+ assert.equal((globalThis as { __threert_host?: unknown }).__threert_host, host, "the channel is a global too");+ assert.equal(host.post({ t: "net.open", id: "a", url: "wss://example.org" }), false, "nobody listens");+ const a = app();+ assert.equal(host.post({ t: "net.open", id: "a", url: "wss://example.org" }), true);+ host.post({ t: "anything", nested: { list: [1, "two"] } });+ assert.deepEqual(a.posts, [{ t: "net.open", id: "a", url: "wss://example.org" }, { t: "anything", nested: { list: [1, "two"] } }]);+ // An app whose queue is full says so.+ (globalThis as { __host_post?: unknown }).__host_post = () => false;+ assert.equal(host.post({ t: "x" }), false);+ a.close();+ assert.throws(() => host.post({} as never), /string "t"/);+ assert.throws(() => host.post({ t: "" }), /string "t"/);+ assert.throws(() => host.post({ t: "x", big: 1n } as never), TypeError);+});++test("the app's messages reach their listeners on the node: the scene they change is synced, once, when the batch returns", () => {+ const seen: string[] = [];+ let frames = 0;+ const g = defineGame({ state: {}, setup: scene, handlers: {}, frame: () => void frames++ });+ const engine = new RecordingEngine();+ const h = installNodeHost(g, engine);+ h.setup("node");+ engine.take();+ const ran = frames;+ const off = host.on("net.messages", (m, world) => {+ seen.push(`${m.id}: ${m.list.join(",")} at ${world.now}`);+ (world.object("ground") as Mesh).power = 0.5;+ const box = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ name: "box" }));+ world.scene.add(box);+ });+ const offAny = host.on("custom", (m) => void seen.push(`custom ${JSON.stringify(m)}`));+ send(h, { t: "net.messages", id: "a", list: ["1", "2"] }, { t: "custom", n: 1 }, { t: "nobody.listens" }, null as never, { no: "type" });+ assert.deepEqual(seen, ["a: 1,2 at 1000", 'custom {"t":"custom","n":1}']);+ assert.deepEqual(kinds(engine.take()), ["power", "geometry", "material", "object", "transform"], "what the listener changed, in the engine when the batch returns");+ assert.equal(frames, ran, "no state changed: the frame script has nothing new to show");+ // Removed listeners get nothing; a batch nobody listens to runs nothing and sends nothing.+ off();+ offAny();+ send(h, { t: "net.messages", id: "a", list: ["3"] }, { t: "custom" });+ assert.equal(seen.length, 2);+ assert.deepEqual(engine.take(), []);+ assert.throws(() => h.hostMessages("{}", 0), /array/);+});++test("a listener that throws does not stop the batch; a listener may start a state transaction", () => {+ const trace: string[] = [];+ const g = defineGame<{ score: number }>({+ state: { score: 0 },+ setup: scene,+ handlers: { score(tx, ev: { points: number }) { tx.state.score += ev.points; } },+ frame: (f) => void trace.push(`frame score ${f.state.score}`),+ });+ const h = installNodeHost(g, new RecordingEngine());+ h.setup("node");+ trace.length = 0;+ const errors: unknown[] = [];+ const error = console.error;+ console.error = (...a: unknown[]) => void errors.push(a.join(" "));+ const offs = [+ host.on("net.fetched", () => { throw new Error("first listener"); }),+ host.on("net.fetched", (m, world) => { trace.push(`second ${m.status}`); world.emit("score", { points: 5 }); }),+ host.on("later", (_m, world) => void trace.push(`later score ${world.state.score}`)),+ ];+ try {+ send(h, { t: "net.fetched", id: "r", status: 200, body: "" }, { t: "later" });+ } finally {+ console.error = error;+ offs.forEach((off) => off());+ }+ assert.deepEqual(trace, ["second 200", "later score 0", "frame score 5"], "the batch's listeners see the state as committed before it; then the transaction, then the frame script");+ assert.equal(errors.length, 1);+ assert.match(String(errors[0]), /host message net\.fetched: Error: first listener/);+ assert.equal(JSON.parse(h.state()).state.score, 5);+});++test("launch: the app's parameters, to listeners and as host.launch", () => {+ const h = installNodeHost(defineGame({ state: {}, setup: scene, handlers: {} }), new RecordingEngine());+ h.setup("node");+ assert.deepEqual(host.launch, {});+ let got: unknown = null;+ const off = host.on("launch", (m) => void (got = m.params));+ send(h, { t: "launch", params: { room: "K7Q4MZ", name: "Ada" } });+ off();+ assert.deepEqual(got, { room: "K7Q4MZ", name: "Ada" });+ assert.deepEqual(host.launch, { room: "K7Q4MZ", name: "Ada" });+ assert.ok(Object.isFrozen(host.launch));+ send(h, { t: "launch", params: "nonsense" });+ assert.deepEqual(host.launch, {});+});++test("input: held keys, edges that last one frame, a frame without input, two messages before one frame", () => {+ const seen: Record<string, unknown>[] = [];+ const read = (i: Input) => ({ w: i.down("W"), wPressed: i.pressed("W"), wReleased: i.released("W"), space: i.pressed("Space"), look: i.look.dx, wheel: i.wheel, move: i.move });+ const g = defineGame({+ state: {},+ setup: scene,+ handlers: {},+ pointer: "look",+ frame: (f) => void (f.dt > 0 && seen.push(read(f.input))),+ on: { peek: (world) => void seen.push({ handler: true, ...read(world.input) }) },+ });+ assert.equal(JSON.parse(installNodeHost(g, new RecordingEngine()).describe()).pointer, "look");+ const h = installNodeHost(g, new RecordingEngine());+ h.setup("node");+ const frame = () => h.frame(1 / 60, 0);+ frame();+ assert.deepEqual(seen.pop(), { w: false, wPressed: false, wReleased: false, space: false, look: 0, wheel: 0, move: { x: 0, y: 0 } }, "before any input");+ // W goes down: the app names the edge, and a tap of Space between two frames is pressed though never held.+ send(h, { t: "input", keys: ["W"], pressed: ["W", "Space"], released: ["Space"], dx: 0.01, dy: -0.02, wheel: 1 });+ h.event("peek", "{}", 0);+ assert.deepEqual(seen.pop(), { handler: true, w: true, wPressed: true, wReleased: false, space: true, look: 0.01, wheel: 1, move: { x: 0, y: 1 } }, "a world handler before the frame sees it");+ frame();+ assert.deepEqual(seen.pop(), { w: true, wPressed: true, wReleased: false, space: true, look: 0.01, wheel: 1, move: { x: 0, y: 1 } });+ // A frame without an input message: still held, nothing pressed, nothing turned.+ frame();+ assert.deepEqual(seen.pop(), { w: true, wPressed: false, wReleased: false, space: false, look: 0, wheel: 0, move: { x: 0, y: 1 } });+ // An app that sends only what is held: the edges are how the held set changed.+ send(h, { t: "input", keys: ["W", "D"] });+ frame();+ assert.deepEqual(seen.pop()!.move, { x: 1 / Math.hypot(1, 1), y: 1 / Math.hypot(1, 1) }, "W and D together are no faster than W");+ send(h, { t: "input", keys: ["D"] });+ frame();+ assert.deepEqual(seen.pop(), { w: false, wPressed: false, wReleased: true, space: false, look: 0, wheel: 0, move: { x: 1, y: 0 } });+ // Two messages before one frame: their looks add up and neither's edge is lost.+ send(h, { t: "input", keys: ["D", "W"], dx: 0.25 });+ send(h, { t: "input", keys: ["D"], dx: 0.5 });+ frame();+ assert.deepEqual(seen.pop(), { w: false, wPressed: true, wReleased: true, space: false, look: 0.75, wheel: 0, move: { x: 1, y: 0 } });+ frame();+ assert.deepEqual(seen.pop(), { w: false, wPressed: false, wReleased: false, space: false, look: 0, wheel: 0, move: { x: 1, y: 0 } });+});++test("input: mouse buttons are keys, the pointer, capture, a stick", () => {+ const i = new InputState();+ i.apply({ t: "input", keys: ["Shift"], buttons: [0], u: 0.25, v: 0.75, captured: true });+ assert.ok(i.button(0) && i.down("Mouse0") && i.pressed("Mouse0") && !i.button(2) && i.down("Shift"));+ assert.deepEqual([i.pointer, i.captured], [{ u: 0.25, v: 0.75 }, true]);+ i.endFrame();+ // A message that does not mention the buttons leaves them held; one that does not mention the keys, the keys.+ i.apply({ t: "input", keys: ["Shift", "A"] });+ assert.ok(i.button(0) && !i.pressed("Mouse0") && i.pressed("A"));+ i.apply({ t: "input", buttons: [] });+ assert.ok(!i.button(0) && i.released("Mouse0") && i.down("A") && i.down("Shift"));+ assert.equal(i.axis("A", "D"), -1);+ assert.equal(i.axis("Left", "Right"), 0);+ // A stick replaces W A S D for `move`, clamped; null gives the keys back.+ i.apply({ t: "input", move: [0.3, -4] });+ assert.deepEqual(i.move, { x: 0.3 / Math.hypot(0.3, 1), y: -1 / Math.hypot(0.3, 1) });+ i.apply({ t: "input", move: null });+ assert.deepEqual(i.move, { x: -1, y: 0 });+ // Numbers that are not numbers are nothing.+ i.endFrame();+ i.apply({ t: "input", dx: Number.NaN, wheel: "x" as never, keys: [7 as never, "B"] });+ assert.deepEqual([i.look, i.wheel, i.down("B"), i.down("A")], [{ dx: 0, dy: 0 }, 0, true, false]);+ i.reset();+ assert.ok(!i.down("B") && !i.captured);+});++test("a game without `pointer` asks for no input; `pointer` is checked", () => {+ const g = defineGame({ state: {}, setup: scene, handlers: {} });+ assert.equal(JSON.parse(installNodeHost(g, new RecordingEngine()).describe()).pointer, null);+ assert.equal(gameplay.describeGame(defineGame({ state: {}, setup: scene, handlers: {}, pointer: "free" }) as AnyGame).pointer, "free");+ assert.throws(() => defineGame({ state: {}, setup: scene, handlers: {}, pointer: "locked" as never }), /pointer must be/);+});++test("the HUD is posted when it changed, and only then", () => {+ const a = app();+ try {+ hud.reset();+ const view = (score: number): Hud => ({+ crosshair: { style: "cross", gap: 0.2 },+ items: [{ type: "text", anchor: "top-left", label: "Tagged", text: `${score} / 5` }, { type: "bar", anchor: "bottom-left", value: 0.5, tone: "good" }],+ });+ assert.equal(hud.set(view(0)), true);+ assert.equal(hud.set(view(0)), false, "the same description, built anew");+ assert.equal(hud.set({ items: view(0).items, crosshair: { gap: 0.2, style: "cross" } }), false, "the order of its keys is not a change");+ assert.equal(hud.set(view(1)), true);+ assert.deepEqual(a.posts.map((p) => p.t), ["hud", "hud"]);+ assert.deepEqual((a.posts[1].hud as Hud).items![0], { type: "text", anchor: "top-left", label: "Tagged", text: "1 / 5" });+ // A flash is an event: the HUD as last set, posted again with a new `n` each time.+ hud.flash("hit");+ hud.flash("damage", 1.5);+ assert.deepEqual(a.posts.slice(2).map((p) => (p.hud as Hud).flash), [{ kind: "hit", n: 1 }, { kind: "damage", angle: 1.5, n: 2 }]);+ assert.deepEqual((a.posts[3].hud as Hud).items, view(1).items);+ assert.equal(hud.set(view(1)), false, "the flash stays in the description: its n says it was played");+ hud.clear();+ assert.deepEqual(a.posts.at(-1)!.hud, { flash: { kind: "damage", angle: 1.5, n: 2 } });+ assert.throws(() => hud.set({ items: [{ type: "gauge" as never, anchor: "top" } as never] }), /items\[0\]\.type/);+ assert.throws(() => hud.set({ items: [{ type: "text", anchor: "middle" as never, text: "" }] }), /items\[0\]\.anchor/);+ // A scene built anew: the first description is posted whatever the last one was.+ hud.set(view(2));+ const n = a.posts.length;+ installNodeHost(defineGame({ state: {}, setup: scene, handlers: {} }), new RecordingEngine()).setup("node");+ assert.equal(hud.set(view(2)), true);+ assert.equal(a.posts.length, n + 1);+ } finally {+ a.close();+ }+});diff --git a/renderer/Cargo.lock b/renderer/Cargo.lockindex 00cf6a6..24560ba 100644--- a/renderer/Cargo.lock+++ b/renderer/Cargo.lock@@ -137,6 +137,12 @@ version = "0.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"+[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"+[[package]]name = "bit-set"version = "0.10.0"@@ -179,6 +185,15 @@ dependencies = ["generic-array",]+[[package]]+name = "block-buffer"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"+dependencies = [+ "hybrid-array",+]+[[package]]name = "block2"version = "0.5.1"@@ -291,6 +306,17 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"+[[package]]+name = "chacha20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.1",+ "rand_core",+]+[[package]]name = "codespan-reporting"version = "0.13.1"@@ -321,6 +347,12 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "const-oid"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"+[[package]]name = "core-foundation"version = "0.9.4"@@ -370,6 +402,15 @@ dependencies = ["libc",]+[[package]]+name = "cpufeatures"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"+dependencies = [+ "libc",+]+[[package]]name = "crc32fast"version = "1.5.4"@@ -420,20 +461,46 @@ dependencies = ["typenum",]+[[package]]+name = "crypto-common"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"+dependencies = [+ "hybrid-array",+]+[[package]]name = "cursor-icon"version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"+[[package]]+name = "data-encoding"+version = "2.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"+[[package]]name = "digest"version = "0.10.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = [- "block-buffer",- "crypto-common",+ "block-buffer 0.10.4",+ "crypto-common 0.1.7",+]++[[package]]+name = "digest"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"+dependencies = [+ "block-buffer 0.12.1",+ "const-oid",+ "crypto-common 0.2.2",][[package]]@@ -638,6 +705,17 @@ dependencies = ["windows-link",]+[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "libc",+ "wasi",+]+[[package]]name = "getrandom"version = "0.3.4"@@ -659,6 +737,7 @@ dependencies = ["cfg-if","libc","r-efi 6.0.0",+ "rand_core",][[package]]@@ -732,7 +811,7 @@ version = "1.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3ce1918195723ce6ac74e80542c5a96a40c2b26162c1957a5cd70799b8cacf7"dependencies = [- "base64",+ "base64 0.13.1","byteorder","gltf-json","image",@@ -848,6 +927,31 @@ version = "0.5.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"+[[package]]+name = "http"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "hybrid-array"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"+dependencies = [+ "typenum",+]+[[package]]name = "image"version = "0.25.10"@@ -1888,6 +1992,23 @@ version = "6.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"+[[package]]+name = "rand"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"+dependencies = [+ "chacha20",+ "getrandom 0.4.3",+ "rand_core",+]++[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"+[[package]]name = "range-alloc"version = "0.1.5"@@ -2018,6 +2139,20 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"+[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]+[[package]]name = "robust"version = "1.2.0"@@ -2105,6 +2240,41 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "rustls"+version = "0.23.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"+dependencies = [+ "log",+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-pki-types"+version = "1.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"+dependencies = [+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]+[[package]]name = "rustversion"version = "1.0.23"@@ -2203,6 +2373,17 @@ dependencies = ["zmij",]+[[package]]+name = "sha1"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.1",+ "digest 0.11.3",+]+[[package]]name = "sha2"version = "0.10.9"@@ -2210,8 +2391,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"dependencies = ["cfg-if",- "cpufeatures",- "digest",+ "cpufeatures 0.2.17",+ "digest 0.10.7",][[package]]@@ -2349,6 +2530,12 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"+[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+[[package]]name = "syn"version = "2.0.119"@@ -2437,9 +2624,12 @@ dependencies = ["pollster","rayon","rquickjs",+ "rustls","serde","serde_json","sha2",+ "tungstenite",+ "ureq","voxel-core","web-time","wgpu",@@ -2532,6 +2722,25 @@ version = "0.25.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"+[[package]]+name = "tungstenite"+version = "0.30.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22"+dependencies = [+ "bytes",+ "data-encoding",+ "http",+ "httparse",+ "log",+ "rand",+ "rustls",+ "rustls-pki-types",+ "sha1",+ "thiserror 2.0.21",+ "webpki-roots 0.26.11",+]+[[package]]name = "typenum"version = "1.20.1"@@ -2556,12 +2765,53 @@ version = "0.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"+[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "ureq"+version = "3.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d"+dependencies = [+ "base64 0.23.1",+ "flate2",+ "log",+ "percent-encoding",+ "rustls",+ "rustls-pki-types",+ "ureq-proto",+ "utf8-zero",+ "webpki-roots 1.0.12",+]++[[package]]+name = "ureq-proto"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3"+dependencies = [+ "base64 0.23.1",+ "http",+ "httparse",+ "log",+]+[[package]]name = "urlencoding"version = "2.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"+[[package]]+name = "utf8-zero"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"+[[package]]name = "version_check"version = "0.9.5"@@ -2582,6 +2832,12 @@ dependencies = ["winapi-util",]+[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"+[[package]]name = "wasip2"version = "1.0.4+wasi-0.2.12"@@ -2775,6 +3031,24 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "webpki-roots"+version = "0.26.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"+dependencies = [+ "webpki-roots 1.0.12",+]++[[package]]+name = "webpki-roots"+version = "1.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297"+dependencies = [+ "rustls-pki-types",+]+[[package]]name = "wgpu"version = "30.0.1"@@ -3318,6 +3592,12 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "zeroize"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"+[[package]]name = "zlib-rs"version = "0.6.8"diff --git a/renderer/Cargo.toml b/renderer/Cargo.tomlindex 823922b..ad2830e 100644--- a/renderer/Cargo.toml+++ b/renderer/Cargo.toml@@ -40,6 +40,14 @@ oidn = { version = "2.5", optional = true }# Scene runtime of the render node (game bundles run in the renderer process, src/script.rs).rquickjs = "0.12"+# The `threert-render` binary's sockets and HTTP, for the games its window runs (src/net.rs: the `net.*` messages of+# the host channel, docs/RUNTIME.md). Only the binary uses them, and only with the `net` feature: the library has no+# network in it, and a program that embeds the library leaves them out with `default-features = false` (the browser+# module does). TLS is rustls with the ring provider and the webpki roots: no system TLS library.+tungstenite = { version = "0.30", optional = true, default-features = false, features = ["handshake", "rustls-tls-webpki-roots"] }+ureq = { version = "3", optional = true, default-features = false, features = ["rustls", "gzip"] }+rustls = { version = "0.23", optional = true, default-features = false, features = ["ring", "std"] }+# The performance cores' count (src/physics.rs: the physics' threads).[target.'cfg(target_os = "macos")'.dependencies]libc = "0.2"@@ -54,7 +62,16 @@ naga = { version = "30", features = ["wgsl-in"] }name = "physics_bits"crate-type = ["cdylib"]+# tools/three/physics.ts: the engine's world and physics as a wasm32 module, for the three.js view.+[[example]]+name = "physics_scene"+crate-type = ["cdylib"]+[features]+default = ["net"]+# WebSockets and HTTP in `threert-render play` (above). Without it the window answers every `net.*` request with a+# failure that says so.+net = ["dep:tungstenite", "dep:ureq", "dep:rustls"]# Intel Open Image Denoise (needs OIDN_DIR at build time and the shared libs at runtime).oidn = ["dep:oidn"]diff --git a/renderer/examples/physics_scene.rs b/renderer/examples/physics_scene.rsnew file mode 100644index 0000000..216132d--- /dev/null+++ b/renderer/examples/physics_scene.rs@@ -0,0 +1,166 @@+//! The engine's world and its physics for a host that draws the scene itself: the three.js view (tools/three), which+//! has three.js for the picture and nothing for `mesh.physics`, `Raycaster.intersectPhysics` or a `Shapecaster`.+//! Built for `wasm32-unknown-unknown` as a plain module (no wasm-bindgen: tools/three/physics.ts builds and loads+//! it), it holds the objects and geometries the scene binding sends, as the renderer's world does, and the physics+//! world on them: the calls go through the code the renderer's own `__engine` runs (`api`, `physics_core::bridge`),+//! and the world is stepped at the same fixed tick, so a game moves here as it does in the renderer.+//!+//! The boundary is by pointer and length into the module's memory (`scene_alloc` / `scene_free`); text is UTF-8.+//! A call returns 0, or 1 with its error as the answer (`scene_answer` / `scene_answer_len`).+use physics_core::bridge::Bridge;+use std::alloc::Layout;+use std::cell::RefCell;+use threert_render::{api, world::World};++#[derive(Default)]+struct State {+ world: World,+ bridge: Bridge,+ /// The last call's answer (a physics call's JSON, an error's text), and the poses as last asked for.+ answer: String,+ poses: Vec<f32>,+}++thread_local! {+ static STATE: RefCell<State> = RefCell::default();+}++fn layout(len: usize) -> Layout {+ Layout::from_size_align(len.max(1), 8).expect("a layout")+}++/// `len` bytes of the module's memory for the caller to fill (aligned for numbers).+#[no_mangle]+pub extern "C" fn scene_alloc(len: usize) -> *mut u8 {+ unsafe { std::alloc::alloc(layout(len)) }+}++/// # Safety+/// `ptr` and `len` as `scene_alloc` gave and took them.+#[no_mangle]+pub unsafe extern "C" fn scene_free(ptr: *mut u8, len: usize) {+ std::alloc::dealloc(ptr, layout(len))+}++unsafe fn text<'a>(ptr: *const u8, len: usize) -> &'a str {+ std::str::from_utf8(std::slice::from_raw_parts(ptr, len)).unwrap_or("")+}++unsafe fn numbers<'a, T>(ptr: *const T, len: usize) -> &'a [T] {+ if len == 0 {+ &[]+ } else {+ std::slice::from_raw_parts(ptr, len)+ }+}++/// The call's result as its status, its answer (or its error) kept for the caller to read.+fn done(s: &mut State, r: Result<String, String>) -> i32 {+ let ok = r.is_ok();+ s.answer = r.unwrap_or_else(|e| e);+ if ok {+ 0+ } else {+ 1+ }+}++fn with(f: impl FnOnce(&mut State) -> Result<String, String>) -> i32 {+ STATE.with_borrow_mut(|s| {+ let r = f(s);+ done(s, r)+ })+}++#[no_mangle]+pub extern "C" fn scene_answer() -> *const u8 {+ STATE.with_borrow(|s| s.answer.as_ptr())+}++#[no_mangle]+pub extern "C" fn scene_answer_len() -> usize {+ STATE.with_borrow(|s| s.answer.len())+}++/// `__engine.geometry`: what a collider is made from (positions, three numbers a vertex, and triangle indices).+/// # Safety+/// The pointers and lengths name numbers in the module's memory.+#[no_mangle]+pub unsafe extern "C" fn scene_geometry(id: u32, positions: *const f32, np: usize, indices: *const u32, ni: usize) -> i32 {+ let (p, i) = (numbers(positions, np), numbers(indices, ni));+ // (Normals and texture coordinates are the picture's: the world wants their counts right, the physics reads neither.)+ with(|s| api::geometry(&mut s.world, id, p, &vec![0.0; p.len()], &vec![0.0; p.len() / 3 * 2], i, None, None).map(|_| String::new()).map_err(|e| e.to_string()))+}++/// `__engine.object`: the descriptor's JSON.+/// # Safety+/// As above.+#[no_mangle]+pub unsafe extern "C" fn scene_object(id: u32, desc: *const u8, len: usize) -> i32 {+ let d = text(desc, len);+ with(|s| {+ let j: serde_json::Value = serde_json::from_str(d).map_err(|e| format!("engine.object: {e}"))?;+ api::object(&mut s.world, id, &j).map(|_| String::new()).map_err(|e| e.to_string())+ })+}++/// `__engine.transform`: position, rotation (xyzw), scale.+/// # Safety+/// As above.+#[no_mangle]+pub unsafe extern "C" fn scene_transform(id: u32, trs: *const f32, len: usize) -> i32 {+ let t = numbers(trs, len);+ with(|s| api::transform(&mut s.world, id, t).map(|_| String::new()).map_err(|e| e.to_string()))+}++/// `__engine.remove`: the object, what is under it, and their bodies.+#[no_mangle]+pub extern "C" fn scene_remove(id: u32) {+ STATE.with_borrow_mut(|s| {+ let gone = s.world.remove(id);+ s.bridge.objects_removed(&gone);+ })+}++/// `__engine.physics(op, args)`: the answer is its JSON.+/// # Safety+/// As above.+#[no_mangle]+pub unsafe extern "C" fn scene_physics(op: *const u8, op_len: usize, args: *const u8, args_len: usize) -> i32 {+ let (op, args) = (text(op, op_len), text(args, args_len));+ with(|s| {+ let a: serde_json::Value = serde_json::from_str(args).map_err(|e| format!("engine.physics: {e}"))?;+ let State { world, bridge, .. } = s;+ bridge.call(world, op, &a).map(|v| v.to_string())+ })+}++/// A frame of `dt` seconds: the whole ticks that fit, and the objects of the bodies that moved placed. Returns the+/// ticks made.+#[no_mangle]+pub extern "C" fn scene_advance(dt: f64) -> u32 {+ STATE.with_borrow_mut(|s| {+ let ticks = s.bridge.due(dt);+ for _ in 0..ticks {+ s.bridge.tick();+ }+ s.bridge.sync(&mut s.world);+ // (Nobody draws this world: what changed in it is the host's to show, from the poses.)+ s.world.take_changes();+ ticks+ })+}++/// `__engine.physicsPoses()`: seven numbers a slot (position, rotation xyzw), in the space of the object's parent.+#[no_mangle]+pub extern "C" fn scene_poses() -> *const f32 {+ STATE.with_borrow_mut(|s| {+ s.poses = s.bridge.poses().to_vec();+ s.poses.as_ptr()+ })+}++#[no_mangle]+pub extern "C" fn scene_poses_len() -> usize {+ STATE.with_borrow(|s| s.poses.len())+}diff --git a/renderer/src/host.rs b/renderer/src/host.rsnew file mode 100644index 0000000..25b5b28--- /dev/null+++ b/renderer/src/host.rs@@ -0,0 +1,176 @@+//! The app's side of the host channel (docs/RUNTIME.md "The host channel"): what whoever embeds a `GameSession`+//! does with the messages the game posts (`GameSession::take_posts`) and what it sends back+//! (`GameSession::host_messages`). The session only carries the messages; sockets, a HUD and the input devices+//! belong to the app. Here: the services a window takes its answers from (`HostServices`: the `threert-render`+//! binary's are its sockets and HTTP, src/net.rs), and the input message built from a window's key and pointer events+//! (`InputTracker`), with no window system in it.++use serde_json::{json, Value};+use std::collections::{BTreeMap, BTreeSet};++/// What an app offers the game beyond the picture: it is handed every message the game posts and asked once a frame+/// for what it has to say.+pub trait HostServices {+ /// A message the game posted (`{ "t": ..., ... }`). One the services do not know is not theirs: ignored.+ fn post(&mut self, message: &Value);+ /// The messages for the game since the last call, in order.+ fn poll(&mut self) -> Vec<Value>;+}++/// An app without services: posts go nowhere, nothing comes back.+pub struct NoServices;++impl HostServices for NoServices {+ fn post(&mut self, _: &Value) {}+ fn poll(&mut self) -> Vec<Value> {+ vec![]+ }+}++/// `input.look` is an angle (packages/gameplay/src/input.ts): radians a count of mouse motion at sensitivity 1 (a+/// point of a macOS pointer, a CSS pixel in a browser). 1,000 counts turn 143 degrees.+pub const LOOK_RADIANS: f32 = 0.0025;++/// The `launch` message: how the app opened the game.+pub fn launch_message(params: Option<&Value>) -> Value {+ json!({ "t": "launch", "params": params.filter(|p| p.is_object()).cloned().unwrap_or_else(|| json!({})) })+}++/// A window's keys and pointer between two frames, and the `input` message of a frame.+#[derive(Default)]+pub struct InputTracker {+ /// Physical keys down (by the window system's own name for them), and how many of them hold each key name+ /// ("Shift" is either shift key).+ codes: BTreeMap<String, String>,+ held: BTreeMap<String, u32>,+ buttons: BTreeSet<u8>,+ pressed: Vec<String>,+ released: Vec<String>,+ look: (f32, f32),+ wheel: f32,+ pointer: (f32, f32),+ pub captured: bool,+}++impl InputTracker {+ pub fn new() -> InputTracker {+ InputTracker { pointer: (0.5, 0.5), ..Default::default() }+ }++ /// A key went down or up: `code` is the physical key, `name` what game code calls it.+ pub fn key(&mut self, code: &str, name: &str, down: bool) {+ if down {+ if self.codes.insert(code.to_string(), name.to_string()).is_none() {+ let n = self.held.entry(name.to_string()).or_default();+ *n += 1;+ if *n == 1 {+ self.pressed.push(name.to_string());+ }+ }+ } else if let Some(name) = self.codes.remove(code) {+ if let Some(n) = self.held.get_mut(&name) {+ *n -= 1;+ if *n == 0 {+ self.held.remove(&name);+ self.released.push(name);+ }+ }+ }+ }++ /// A mouse button (0 left, 1 middle, 2 right) went down or up.+ pub fn button(&mut self, n: u8, down: bool) {+ if down && self.buttons.insert(n) {+ self.pressed.push(format!("Mouse{n}"));+ } else if !down && self.buttons.remove(&n) {+ self.released.push(format!("Mouse{n}"));+ }+ }++ /// The pointer moved by (dx, dy) counts while captured: look, at `sensitivity`.+ pub fn motion(&mut self, dx: f32, dy: f32, sensitivity: f32) {+ self.look.0 += dx * LOOK_RADIANS * sensitivity;+ self.look.1 += dy * LOOK_RADIANS * sensitivity;+ }++ pub fn wheel(&mut self, notches: f32) {+ self.wheel += notches;+ }++ /// Where the pointer is in the picture (0..1 from the top left).+ pub fn pointer(&mut self, u: f32, v: f32) {+ self.pointer = (u.clamp(0.0, 1.0), v.clamp(0.0, 1.0));+ }++ /// The window lost the keyboard: everything held is let go (its key-up events go elsewhere).+ pub fn release_all(&mut self) {+ self.codes.clear();+ self.released.extend(std::mem::take(&mut self.held).into_keys());+ self.released.extend(std::mem::take(&mut self.buttons).into_iter().map(|n| format!("Mouse{n}")));+ }++ /// The frame's `input` message; what lasts a frame (edges, look, wheel) starts again.+ pub fn message(&mut self) -> Value {+ let (dx, dy) = std::mem::take(&mut self.look);+ let (u, v) = if self.captured { (0.5, 0.5) } else { self.pointer };+ json!({+ "t": "input",+ "keys": self.held.keys().collect::<Vec<_>>(),+ "pressed": std::mem::take(&mut self.pressed),+ "released": std::mem::take(&mut self.released),+ "buttons": self.buttons.iter().collect::<Vec<_>>(),+ "u": u, "v": v, "dx": dx, "dy": dy,+ "wheel": std::mem::take(&mut self.wheel),+ "captured": self.captured,+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_frames_input_message() {+ let mut i = InputTracker::new();+ i.key("KeyW", "W", true);+ i.key("KeyW", "W", true); // the window system's key repeat+ i.key("ShiftLeft", "Shift", true);+ i.key("ShiftRight", "Shift", true);+ i.key("Space", "Space", true);+ i.key("Space", "Space", false); // a tap between two frames+ i.button(0, true);+ i.motion(100.0, -40.0, 2.0);+ i.wheel(1.0);+ i.pointer(0.25, 2.0);+ let m = i.message();+ assert_eq!(m["keys"], json!(["Shift", "W"]));+ assert_eq!(m["pressed"], json!(["W", "Shift", "Space", "Mouse0"]));+ assert_eq!(m["released"], json!(["Space"]));+ assert_eq!(m["buttons"], json!([0]));+ assert_eq!((m["u"].as_f64(), m["v"].as_f64()), (Some(0.25), Some(1.0)));+ assert!((m["dx"].as_f64().unwrap() - 0.5).abs() < 1e-6 && (m["dy"].as_f64().unwrap() + 0.2).abs() < 1e-6, "{m}");+ assert_eq!(m["wheel"], json!(1.0));+ // The next frame: still held, nothing new.+ i.key("ShiftLeft", "Shift", false); // the other shift key still holds it+ i.captured = true;+ let m = i.message();+ assert_eq!(m["keys"], json!(["Shift", "W"]));+ assert_eq!((m["pressed"].clone(), m["released"].clone()), (json!([]), json!([])));+ assert_eq!((m["dx"].as_f64(), m["wheel"].as_f64(), m["u"].as_f64(), m["captured"].as_bool()), (Some(0.0), Some(0.0), Some(0.5), Some(true)));+ i.key("ShiftRight", "Shift", false);+ i.key("KeyQ", "Q", false); // an up without its down (it went down in another window)+ assert_eq!(i.message()["released"], json!(["Shift"]));+ // Focus lost: all let go.+ i.release_all();+ let m = i.message();+ assert_eq!((m["keys"].clone(), m["buttons"].clone(), m["released"].clone()), (json!([]), json!([]), json!(["W", "Mouse0"])));+ }++ #[test]+ fn the_launch_message() {+ assert_eq!(launch_message(None), json!({ "t": "launch", "params": {} }));+ assert_eq!(launch_message(Some(&json!({ "room": "K7Q4MZ" }))), json!({ "t": "launch", "params": { "room": "K7Q4MZ" } }));+ assert_eq!(launch_message(Some(&json!("x")))["params"], json!({}));+ }+}diff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex 1f54fb7..eda8fa8 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -10,6 +10,8 @@ pub mod denoise;pub mod desc;pub mod files;pub mod gpu;+#[cfg(not(target_arch = "wasm32"))]+pub mod host;pub mod live;pub mod ltree;pub mod merged;diff --git a/renderer/src/live.rs b/renderer/src/live.rsindex bdd0448..8ed3447 100644--- a/renderer/src/live.rs+++ b/renderer/src/live.rs@@ -58,6 +58,8 @@ pub struct LiveOpts {pub frame_log: Option<PathBuf>,/// The output's pixels a point of its display (1: the output is in points).pub display_scale: f32,+ /// `--launch`: the `params` of the host channel's `launch` message (docs/RUNTIME.md "The host channel").+ pub launch: Option<serde_json::Value>,}/// Lowest dynamic-resolution scale (UE r.DynamicRes.MinScreenPercentage default) of a view whose pixels are the@@ -1066,6 +1068,9 @@ pub enum Cmd {Event(String, serde_json::Value),/// A click at (u, v) for the in-process game (picks the node under it).Click(f32, f32),+ /// Messages of the host channel for the in-process game (`{"cmd":"host","messages":[{"t":...}, ...]}`: what an+ /// app would send, its input among them; docs/RUNTIME.md "The host channel").+ Host(Vec<serde_json::Value>),/// Snapshot (path) of the first frame whose history length reaches `after` (None = any) and that is at least the/// `frames`-th frame from now (None = the next).Snapshot(PathBuf, Option<u32>, Option<u32>),@@ -4361,6 +4366,12 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {let (cmd_tx, cmd_rx) = mpsc::channel::<Cmd>();spawn_stdin_reader(cmd_tx);let (mut game, mut core) = crate::script::GameSession::start(&opts.bundle, &opts.room, &opts.assets, gpu::Gpu::new()?, presets, w, h)?;+ // The host channel: this runner is the app. How the game was opened, once after setup; what the game posts goes+ // out on stdout (`emit_posts`), and whoever drives the runner answers with `{"cmd":"host"}`.+ if let Err(e) = game.host_messages(&mut core, &[crate::host::launch_message(opts.launch.as_ref())]) {+ eprintln!("live: launch: {e:#}");+ }+ emit_posts(&mut game);// Frame-script cost (script + commit), reported every 2 s.let (mut fs_sum, mut fs_max, mut fs_n) = (0.0f32, 0.0f32, 0u32);core.bounces = opts.bounces;@@ -4434,12 +4445,18 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {eprintln!("live: click failed: {e:#}");}}+ Cmd::Host(messages) => {+ if let Err(e) = game.host_messages(&mut core, &messages) {+ eprintln!("live: host messages failed: {e:#}");+ }+ }Cmd::SppCap(_) | Cmd::Status(_) => {}Cmd::Quit => return Ok(()),}}// The frame script runs on wall-clock time (frames slower than the target rate still animate at real speed).if lockstep.is_some() && budget == 0 {+ emit_posts(&mut game);continue; // commands without frames (events, switches): wait for a step}let dt = if freeze_time() { 0.0 } else { lockstep.unwrap_or_else(|| last.elapsed().as_secs_f32().min(0.1)) };@@ -4448,6 +4465,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {if let Err(e) = game.frame(&mut core, dt) {eprintln!("live: frame script: {e:#}");}+ emit_posts(&mut game);if game.host.has_frame() {(fs_sum, fs_max, fs_n) = (fs_sum + game.frame_ms, fs_max.max(game.frame_ms), fs_n + 1);if fs_n == opts.fps * 2 {@@ -4533,6 +4551,19 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {}}+#[cfg(not(target_arch = "wasm32"))]+/// What the game posted on the host channel since the last call, as one line on stdout: `{"host":[{"t":...}, ...]}`+/// (nothing when it posted nothing).+fn emit_posts(game: &mut crate::script::GameSession) {+ use std::io::Write;+ let posts = game.take_posts();+ if !posts.is_empty() {+ let mut out = std::io::stdout().lock();+ let _ = writeln!(out, "{}", serde_json::json!({ "host": posts }));+ let _ = out.flush();+ }+}+#[cfg(not(target_arch = "wasm32"))]/// Sleeps until `t` without trusting the timer's precision: macOS gives a process that is not a foreground app timer/// leeway of half the interval (a 16 ms sleep returned after 24, measured from a terminal-launched viewport and from@@ -4597,6 +4628,7 @@ pub fn parse_cmd(line: &str) -> Option<Cmd> {"lockstep" => Cmd::Lockstep(if v["on"].as_bool().unwrap_or(true) { Some(v["dt"].as_f64().unwrap_or(1.0 / 60.0) as f32) } else { None }),"event" => Cmd::Event(v["type"].as_str()?.to_string(), if v["payload"].is_null() { serde_json::json!({}) } else { v["payload"].clone() }),"click" => Cmd::Click(v["u"].as_f64()? as f32, v["v"].as_f64()? as f32),+ "host" => Cmd::Host(v["messages"].as_array()?.clone()),"snapshot" => Cmd::Snapshot(PathBuf::from(v["path"].as_str().unwrap_or("snapshot.png")), v["after"].as_u64().map(|a| a as u32), v["frames"].as_u64().map(|a| a as u32)),"reset" => Cmd::Reset,"time" => Cmd::Time(v["t"].as_f64()? as f32),@@ -4626,9 +4658,16 @@ pub fn parse_opts(args: &[String]) -> Result<LiveOpts> {room: flag("--room").unwrap_or_else(|| "local".into()),frame_log: flag("--frame-log").map(PathBuf::from),display_scale: flag("--display-scale").map(|v| v.parse::<f32>()).transpose()?.unwrap_or(1.0),+ launch: parse_launch(flag("--launch").as_deref())?,})}+#[cfg(not(target_arch = "wasm32"))]+/// `--launch '{"room":"K7Q4MZ","name":"Ada"}'`: the `params` of the host channel's `launch` message.+pub fn parse_launch(v: Option<&str>) -> Result<Option<serde_json::Value>> {+ v.map(|t| serde_json::from_str::<serde_json::Value>(t).ok().filter(|p| p.is_object()).ok_or_else(|| anyhow!("--launch must be a JSON object, as in --launch '{{\"room\":\"K7Q4MZ\"}}'"))).transpose()+}+#[cfg(not(target_arch = "wasm32"))]/// `--scale`: a fraction (0.25 .. 1) or `auto` (dynamic resolution).pub fn parse_scale(v: Option<&str>, default: Option<f32>) -> Result<Option<f32>> {diff --git a/renderer/src/main.rs b/renderer/src/main.rsindex d12b57a..dfcfce1 100644--- a/renderer/src/main.rs+++ b/renderer/src/main.rs@@ -13,6 +13,8 @@//! threert-render edit-check <bundle.js> --events '[{"type":..,"payload":..}]'//! threert-render info # print adapter info+mod net;+use threert_render::script::ScriptHost;use threert_render::{compare, default_presets_dir, denoise, gpu, live, post, prepare, scene, view};@@ -222,7 +224,9 @@ fn main() -> Result<()> {println!("{}", serde_json::to_string(&r)?);}"view" | "play" => {- view::run(view::parse_args(&args, &presets)?)?;+ // The window is the app of the game's host channel: its `net.*` messages are this binary's sockets and+ // HTTP (src/net.rs; a build without the `net` feature answers that it has none).+ view::run(view::parse_args(&args, &presets)?, Box::new(net::Net::new()))?;}"setup" => {// Setup cost of a game bundle in the embedded runtime (as on a render node).diff --git a/renderer/src/net.rs b/renderer/src/net.rsnew file mode 100644index 0000000..9ddd27a--- /dev/null+++ b/renderer/src/net.rs@@ -0,0 +1,379 @@+//! The window's network: the `net.*` messages of the host channel (docs/RUNTIME.md "The host channel") on real+//! WebSockets and HTTP. A game has no I/O; it posts `net.open` / `net.send` / `net.close` / `net.fetch`, and the app+//! that runs it owns the sockets. Here the app is `threert-render play`: every socket and every request has a thread+//! of its own, and what they receive waits in a queue the window empties once a frame (`poll`), so a socket's+//! messages reach the game as one `net.messages` batch a frame, in the order they arrived.+//!+//! Text messages only (a binary frame is dropped). Whoever runs `play` chose the game, so any ws / wss / http / https+//! address is allowed; an app that runs games it did not choose decides for itself what they may reach.+//!+//! Built with the `net` feature (on by default; tungstenite and ureq on rustls). Without it every request is answered+//! with a failure that says so, and the game goes on as it must with an app that has no network.++use serde_json::{json, Value};+use std::collections::HashMap;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::{mpsc, Arc};+use threert_render::host::HostServices;++/// Sockets open at once, requests under way at once.+const MAX_SOCKETS: usize = 16;+const MAX_FETCHES: usize = 32;++/// What a socket's or a request's thread reports, by the game's id for it.+#[cfg_attr(not(feature = "net"), allow(dead_code))]+enum Event {+ Opened(Value),+ Message(Value, String),+ Closed(Value, u16, String),+ /// Status (0: the request failed), body, the failure.+ Fetched(Value, u16, String, Option<String>),+}++/// What the window tells a socket's thread.+#[cfg_attr(not(feature = "net"), allow(dead_code))]+enum Out {+ Text(String),+ Close(u16, String),+}++pub struct Net {+ tx: mpsc::Sender<Event>,+ rx: mpsc::Receiver<Event>,+ sockets: HashMap<String, mpsc::Sender<Out>>,+ fetches: Arc<AtomicUsize>,+}++/// An id as a map's key: the game's string, or whatever JSON it used.+fn key(id: &Value) -> String {+ id.as_str().map_or_else(|| id.to_string(), String::from)+}++impl Net {+ pub fn new() -> Net {+ // (The TLS provider of this process, for both crates.)+ #[cfg(feature = "net")]+ let _ = rustls::crypto::ring::default_provider().install_default();+ let (tx, rx) = mpsc::channel();+ Net { tx, rx, sockets: HashMap::new(), fetches: Arc::default() }+ }++ fn open(&mut self, id: Value, m: &Value) {+ let k = key(&id);+ let refuse = |why: &str| {+ let _ = self.tx.send(Event::Closed(id.clone(), 1006, why.to_string()));+ };+ let Some(url) = m["url"].as_str() else { return refuse("net.open: no url") };+ if self.sockets.contains_key(&k) {+ // (Not a `net.closed`: the socket of that id is open, and stays.)+ return eprintln!("net: net.open: a socket \"{k}\" is open already");+ }+ if self.sockets.len() >= MAX_SOCKETS {+ return refuse(&format!("net.open: {MAX_SOCKETS} sockets are open already"));+ }+ let protocols: Vec<String> = m["protocols"].as_array().map(|a| a.iter().filter_map(|p| p.as_str().map(String::from)).collect()).unwrap_or_default();+ let (out, queue) = mpsc::channel();+ self.sockets.insert(k, out);+ let (url, events) = (url.to_string(), self.tx.clone());+ #[cfg(feature = "net")]+ std::thread::spawn(move || imp::socket(id, &url, &protocols, queue, events));+ #[cfg(not(feature = "net"))]+ {+ let _ = (url, protocols, queue);+ let _ = events.send(Event::Closed(id, 1006, NO_NET.to_string()));+ }+ }++ fn fetch(&mut self, id: Value, m: &Value) {+ let fail = |why: &str| {+ let _ = self.tx.send(Event::Fetched(id.clone(), 0, String::new(), Some(why.to_string())));+ };+ let Some(url) = m["url"].as_str() else { return fail("net.fetch: no url") };+ if self.fetches.load(Ordering::Relaxed) >= MAX_FETCHES {+ return fail(&format!("net.fetch: {MAX_FETCHES} requests are under way already"));+ }+ let method = m["method"].as_str().unwrap_or("GET").to_uppercase();+ let headers: Vec<(String, String)> = m["headers"].as_object().map(|h| h.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect()).unwrap_or_default();+ let body = m["body"].as_str().map(String::from);+ let (url, events, count) = (url.to_string(), self.tx.clone(), self.fetches.clone());+ count.fetch_add(1, Ordering::Relaxed);+ #[cfg(feature = "net")]+ std::thread::spawn(move || {+ let r = imp::fetch(&method, &url, &headers, body);+ count.fetch_sub(1, Ordering::Relaxed);+ let _ = events.send(match r {+ Ok((status, body)) => Event::Fetched(id, status, body, None),+ Err(e) => Event::Fetched(id, 0, String::new(), Some(e)),+ });+ });+ #[cfg(not(feature = "net"))]+ {+ let _ = (method, url, headers, body);+ count.fetch_sub(1, Ordering::Relaxed);+ let _ = events.send(Event::Fetched(id, 0, String::new(), Some(NO_NET.to_string())));+ }+ }+}++#[cfg(not(feature = "net"))]+const NO_NET: &str = "this threert-render was built without its network (the `net` feature)";++impl HostServices for Net {+ fn post(&mut self, m: &Value) {+ let id = m["id"].clone();+ match m["t"].as_str() {+ Some("net.open") => self.open(id, m),+ Some("net.fetch") => self.fetch(id, m),+ // (To a socket that is not open yet: sent once it is. To one that is gone, or never was: dropped.)+ Some("net.send") => {+ if let (Some(s), Some(data)) = (self.sockets.get(&key(&id)), m["data"].as_str()) {+ let _ = s.send(Out::Text(data.to_string()));+ }+ }+ Some("net.close") => {+ if let Some(s) = self.sockets.get(&key(&id)) {+ let code = m["code"].as_u64().filter(|c| *c == 1000 || (3000..5000).contains(c)).unwrap_or(1000) as u16;+ let _ = s.send(Out::Close(code, m["reason"].as_str().unwrap_or("").chars().take(60).collect()));+ }+ }+ _ => {}+ }+ }++ fn poll(&mut self) -> Vec<Value> {+ let mut out: Vec<Value> = vec![];+ // Where each socket's batch of this frame is in `out`.+ let mut batch: HashMap<String, usize> = HashMap::new();+ while let Ok(e) = self.rx.try_recv() {+ match e {+ Event::Opened(id) => out.push(json!({ "t": "net.opened", "id": id })),+ Event::Message(id, text) => match batch.get(&key(&id)) {+ Some(&k) => out[k]["list"].as_array_mut().expect("a batch").push(text.into()),+ None => {+ batch.insert(key(&id), out.len());+ out.push(json!({ "t": "net.messages", "id": id, "list": [text] }));+ }+ },+ Event::Closed(id, code, reason) => {+ self.sockets.remove(&key(&id));+ out.push(json!({ "t": "net.closed", "id": id, "code": code, "reason": reason }));+ }+ Event::Fetched(id, status, body, error) => {+ let mut m = json!({ "t": "net.fetched", "id": id, "status": status, "body": body });+ if let Some(e) = error {+ m["error"] = e.into();+ }+ out.push(m);+ }+ }+ }+ out+ }+}++#[cfg(feature = "net")]+mod imp {+ use super::{Event, Out};+ use serde_json::Value;+ use std::net::{TcpStream, ToSocketAddrs};+ use std::sync::mpsc;+ use std::time::{Duration, Instant};+ use tungstenite::client::IntoClientRequest;+ use tungstenite::protocol::{frame::coding::CloseCode, CloseFrame, WebSocketConfig};+ use tungstenite::stream::MaybeTlsStream;+ use tungstenite::{Error, Message, WebSocket};++ /// To connect and to shake hands; a request in all; a close's answer.+ const CONNECT: Duration = Duration::from_secs(10);+ const FETCH: Duration = Duration::from_secs(30);+ const CLOSE: Duration = Duration::from_secs(2);+ /// How long a socket's thread waits for the server before it looks at what the game wants sent: what a `net.send`+ /// waits at most.+ const TURN: Duration = Duration::from_millis(2);+ /// The largest message a socket takes, the largest body a request reads.+ const MAX_MESSAGE: usize = 1 << 20;+ const MAX_BODY: u64 = 4 << 20;++ fn connect(url: &str, protocols: &[String]) -> Result<WebSocket<MaybeTlsStream<TcpStream>>, String> {+ let mut request = url.into_client_request().map_err(|e| format!("{url}: {e}"))?;+ let uri = request.uri().clone();+ let port = match uri.scheme_str() {+ Some("ws") => uri.port_u16().unwrap_or(80),+ Some("wss") => uri.port_u16().unwrap_or(443),+ _ => return Err(format!("{url}: a socket's address is ws:// or wss://")),+ };+ let host = uri.host().ok_or_else(|| format!("{url}: no host"))?.trim_start_matches('[').trim_end_matches(']').to_string();+ if !protocols.is_empty() {+ request.headers_mut().insert("Sec-WebSocket-Protocol", protocols.join(", ").parse().map_err(|_| "net.open: protocols are not header text".to_string())?);+ }+ let mut last = format!("{host}: no address");+ let stream = (host.as_str(), port).to_socket_addrs().map_err(|e| format!("{host}: {e}"))?.find_map(|a| TcpStream::connect_timeout(&a, CONNECT).map_err(|e| last = format!("{a}: {e}")).ok()).ok_or(last)?;+ let io = |e: std::io::Error| e.to_string();+ stream.set_nodelay(true).map_err(io)?;+ stream.set_read_timeout(Some(CONNECT)).map_err(io)?;+ stream.set_write_timeout(Some(CONNECT)).map_err(io)?;+ // (The same socket: its timeouts are set through this handle once the handshake is over.)+ let control = stream.try_clone().map_err(io)?;+ let config = WebSocketConfig::default().max_message_size(Some(MAX_MESSAGE)).max_frame_size(Some(MAX_MESSAGE));+ let (ws, _) = tungstenite::client_tls_with_config(request, stream, Some(config), None).map_err(|e| format!("{url}: {e}"))?;+ control.set_read_timeout(Some(TURN)).map_err(io)?;+ control.set_write_timeout(None).map_err(io)?;+ Ok(ws)+ }++ /// A socket's thread: connects, then turns between what the game wants sent and what the server says, until+ /// either side closes or the window is gone.+ pub fn socket(id: Value, url: &str, protocols: &[String], out: mpsc::Receiver<Out>, events: mpsc::Sender<Event>) {+ let mut ws = match connect(url, protocols) {+ Ok(ws) => ws,+ Err(e) => {+ let _ = events.send(Event::Closed(id, 1006, e));+ return;+ }+ };+ let _ = events.send(Event::Opened(id.clone()));+ // When we asked to close.+ let mut closing: Option<Instant> = None;+ let (code, reason) = 'open: loop {+ loop {+ match out.try_recv() {+ Ok(Out::Text(text)) if closing.is_none() => {+ if let Err(e) = ws.send(Message::text(text)) {+ break 'open (1006, e.to_string());+ }+ }+ Ok(Out::Text(_)) => {}+ Ok(Out::Close(code, reason)) => {+ if closing.is_none() {+ let _ = ws.close(Some(CloseFrame { code: CloseCode::from(code), reason: reason.into() }));+ closing = Some(Instant::now());+ }+ }+ Err(mpsc::TryRecvError::Empty) => break,+ // (The window is gone.)+ Err(mpsc::TryRecvError::Disconnected) => {+ if closing.is_none() {+ let _ = ws.close(None);+ closing = Some(Instant::now());+ }+ break;+ }+ }+ }+ match ws.read() {+ Ok(Message::Text(text)) => {+ if events.send(Event::Message(id.clone(), text.to_string())).is_err() {+ return;+ }+ }+ // The server's close: its answer to ours, or its own (ours to it goes out with the flush). The+ // socket is done either way; a server that keeps the connection open after it is not waited for.+ Ok(Message::Close(f)) => {+ let _ = ws.flush();+ break f.map_or((1005, String::new()), |f| (u16::from(f.code), f.reason.to_string()));+ }+ Ok(_) => {}+ Err(Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}+ Err(Error::ConnectionClosed | Error::AlreadyClosed) => break (1005, String::new()),+ Err(e) => break (1006, e.to_string()),+ }+ if closing.is_some_and(|t| t.elapsed() > CLOSE) {+ break (1006, "the server did not answer the close".to_string());+ }+ };+ let _ = events.send(Event::Closed(id, code, reason));+ }++ /// One HTTP request: its status and its body as text.+ pub fn fetch(method: &str, url: &str, headers: &[(String, String)], body: Option<String>) -> Result<(u16, String), String> {+ if !(url.starts_with("http://") || url.starts_with("https://")) {+ return Err(format!("{url}: a request's address is http:// or https://"));+ }+ let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(FETCH)).http_status_as_error(false).build().into();+ let mut request = ureq::http::Request::builder().method(method).uri(url);+ for (k, v) in headers {+ request = request.header(k.as_str(), v.as_str());+ }+ let bad = |e: ureq::http::Error| format!("net.fetch: {e}");+ let mut response = match body {+ Some(text) => agent.run(request.body(text).map_err(bad)?),+ None => agent.run(request.body(()).map_err(bad)?),+ }+ .map_err(|e| format!("{url}: {e}"))?;+ let status = response.status().as_u16();+ let text = response.body_mut().with_config().limit(MAX_BODY).read_to_string().map_err(|e| format!("{url}: {e}"))?;+ Ok((status, text))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// What the threads reported since the last frame, as the game gets it: a socket's messages in one batch, in+ /// order, between its `net.opened` and its `net.closed`; a closed socket's id is free again.+ #[test]+ fn a_frame_gets_one_batch_a_socket() {+ let mut net = Net::new();+ let (a, b) = (json!("a"), json!(7));+ net.sockets.insert("a".into(), mpsc::channel().0);+ for e in [+ Event::Opened(a.clone()),+ Event::Message(a.clone(), "1".into()),+ Event::Message(b.clone(), "x".into()),+ Event::Message(a.clone(), "2".into()),+ Event::Fetched(json!("page"), 200, "body".into(), None),+ Event::Closed(a.clone(), 1000, String::new()),+ Event::Fetched(json!("gone"), 0, String::new(), Some("no route".into())),+ ] {+ net.tx.send(e).unwrap();+ }+ assert_eq!(+ net.poll(),+ vec![+ json!({ "t": "net.opened", "id": "a" }),+ json!({ "t": "net.messages", "id": "a", "list": ["1", "2"] }),+ json!({ "t": "net.messages", "id": 7, "list": ["x"] }),+ json!({ "t": "net.fetched", "id": "page", "status": 200, "body": "body" }),+ json!({ "t": "net.closed", "id": "a", "code": 1000, "reason": "" }),+ json!({ "t": "net.fetched", "id": "gone", "status": 0, "body": "", "error": "no route" }),+ ]+ );+ assert!(net.sockets.is_empty() && net.poll().is_empty());+ }++ /// Requests the window refuses itself are answered like any other, at the next frame; posts of other families+ /// and sends to sockets that are not there are not this module's.+ #[test]+ fn what_cannot_be_asked_is_answered_with_a_failure() {+ let mut net = Net::new();+ net.post(&json!({ "t": "net.open", "id": "a" }));+ net.post(&json!({ "t": "net.fetch", "id": "f" }));+ net.post(&json!({ "t": "net.send", "id": "nobody", "data": "x" }));+ net.post(&json!({ "t": "net.close", "id": "nobody" }));+ net.post(&json!({ "t": "hud", "hud": {} }));+ let out = net.poll();+ assert_eq!(out.len(), 2, "{out:?}");+ assert_eq!((out[0]["t"].as_str(), out[0]["code"].as_u64(), out[0]["reason"].as_str()), (Some("net.closed"), Some(1006), Some("net.open: no url")));+ assert_eq!((out[1]["t"].as_str(), out[1]["status"].as_u64(), out[1]["error"].as_str()), (Some("net.fetched"), Some(0), Some("net.fetch: no url")));+ // An address that is no socket's fails on the socket's thread, and says why.+ #[cfg(feature = "net")]+ {+ net.post(&json!({ "t": "net.open", "id": "b", "url": "http://127.0.0.1:9/" }));+ net.post(&json!({ "t": "net.fetch", "id": "g", "url": "ftp://127.0.0.1/" }));+ let mut got = vec![];+ for _ in 0..200 {+ got.extend(net.poll());+ if got.len() == 2 {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ got.sort_by_key(|m| m["t"].as_str().map(String::from));+ assert_eq!(got.len(), 2, "{got:?}");+ assert!(got[0]["reason"].as_str().is_some_and(|r| r.contains("ws:// or wss://")), "{got:?}");+ assert!(got[1]["error"].as_str().is_some_and(|r| r.contains("http:// or https://")), "{got:?}");+ assert!(net.sockets.is_empty());+ }+ }+}diff --git a/renderer/src/script.rs b/renderer/src/script.rsindex 21cb2bd..103698a 100644--- a/renderer/src/script.rs+++ b/renderer/src/script.rs@@ -5,8 +5,9 @@//! then applies what changed (GPU tables in place, or a rebuild).//!//! Sandbox: the engine has no I/O at all (no fs, network, timers or module loader); the host adds only a log sink, a-//! monotonic clock and the engine API. Memory is capped and every call runs under a time budget (the interrupt-//! handler aborts it).+//! monotonic clock, the engine API and the host channel's queue (`__host_post`: messages for the app that embeds the+//! session, which may answer with `host_messages`; docs/RUNTIME.md "The host channel"). Memory is capped and every+//! call runs under a time budget (the interrupt handler aborts it).use crate::world::World;use anyhow::{anyhow, Result};@@ -83,6 +84,11 @@ const SETUP_MS: u64 = 120_000;const EVENT_MS: u64 = 1_000;const FRAME_MS: u64 = 50;+/// The host channel's queue (`__host_post`): the most messages it holds until the app takes them (a session nobody+/// drains, a render node's, keeps the first of them and drops the rest), and the most bytes of one.+const MAX_POSTS: usize = 1024;+const MAX_POST_BYTES: usize = 1 << 20;+/// The most engine time one entry into the script (a frame, an event, setup) is lent, µs: past it the time the engine/// spends in voxel calls counts against the script's budget again. 250 ms: the largest single edit measured on the/// benchmark level, the 30 x 30 m cut, takes 115 ms of engine time, so two of those fit; a frame that spends more in@@ -150,6 +156,8 @@ pub struct ScriptHost {pub voxels: Rc<RefCell<crate::voxel::VoxelWorld>>,/// The physics world (`__engine.physics`; renderer/src/physics.rs): None until scene code makes a physics call.pub physics: Rc<RefCell<Option<crate::physics::PhysicsWorld>>>,+ /// What the game posted for the app (`host.post`: JSON texts), until `take_posts`.+ posts: Rc<RefCell<Vec<String>>>,}pub struct EventOut {@@ -380,8 +388,8 @@ impl ScriptHost {let ctx = Context::full(&rt)?;let world = Rc::new(RefCell::new(World::default()));let voxels = Rc::new(RefCell::new(crate::voxel::VoxelWorld::default()));- let mut h = ScriptHost { _rt: rt, ctx, budget, epoch, info: serde_json::Value::Null, world, voxels, physics: Default::default() };- let (w, v, ph, d2) = (h.world.clone(), h.voxels.clone(), h.physics.clone(), h.budget.clone());+ let mut h = ScriptHost { _rt: rt, ctx, budget, epoch, info: serde_json::Value::Null, world, voxels, physics: Default::default(), posts: Default::default() };+ let (w, v, ph, d2, posts) = (h.world.clone(), h.voxels.clone(), h.physics.clone(), h.budget.clone(), h.posts.clone());let info: String = h.call(SETUP_MS, |ctx| {let g = ctx.globals();g.set("__host_log", Function::new(ctx.clone(), |level: String, msg: String| {@@ -391,6 +399,19 @@ impl ScriptHost {}})?)?;g.set("__host_now", Function::new(ctx.clone(), move || epoch.elapsed().as_secs_f64() * 1000.0)?)?;+ // The host channel, script to app: a message's JSON text onto the queue the app drains. False when the+ // queue is full (nobody drains it); a message past the size bound is the script's error.+ g.set("__host_post", Function::new(ctx.clone(), move |ctx: Ctx, text: String| -> rquickjs::Result<bool> {+ if text.len() > MAX_POST_BYTES {+ return Err(Exception::throw_range(&ctx, &format!("host.post: a message of {} bytes (at most {MAX_POST_BYTES})", text.len())));+ }+ let mut q = posts.borrow_mut();+ let room = q.len() < MAX_POSTS;+ if room {+ q.push(text);+ }+ Ok(room)+ })?)?;install_engine(ctx, &w, &v, &ph, &d2)?;ctx.eval::<(), _>(PRELUDE)?;code(ctx)?;@@ -417,6 +438,32 @@ impl ScriptHost {self.info["frame"].as_bool().unwrap_or(false)}+ /// The input the game asked for (`pointer` in its definition): "look" (the app captures the pointer) or "free".+ /// None: the game reads no input, and the app keeps its own camera controls.+ pub fn pointer(&self) -> Option<&str> {+ self.info["pointer"].as_str()+ }++ /// The messages the game posted for the app since the last call (`host.post`), as JSON values, in order.+ pub fn take_posts(&self) -> Vec<serde_json::Value> {+ std::mem::take(&mut *self.posts.borrow_mut()).iter().filter_map(|t| serde_json::from_str(t).ok()).collect()+ }++ /// The app's messages for the game, a batch in one entry (the node host's `hostMessages`): `input` is kept for+ /// the frame script, the others go to their `host.on` listeners. Bundles built before the channel have no such+ /// entry: nothing to do then.+ pub fn host_messages(&self, messages: &[serde_json::Value]) -> Result<()> {+ if messages.is_empty() {+ return Ok(());+ }+ let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_millis() as f64);+ let list = serde_json::Value::Array(messages.to_vec()).to_string();+ self.call(EVENT_MS, |ctx| match host(ctx)?.get::<_, Option<Function>>("hostMessages")? {+ Some(f) => f.call((list, ts)),+ None => Ok(()),+ })+ }+/// Handler bound to a key ("R", "Space"), if any.pub fn handler_for_key(&self, key: &str) -> Option<String> {self.info["keys"][key].as_str().map(String::from)@@ -679,6 +726,25 @@ impl GameSession {Ok(Some(e))}+ /// The app's messages for the game (the host channel: its input, what its sockets received, `launch`), a batch in+ /// one script entry; what the game's listeners changed in the scene is applied. True if that rebuilt the scene.+ /// Listeners that throw do not fail the batch (their errors are in the game's log).+ pub fn host_messages(&mut self, core: &mut crate::live::LiveCore, messages: &[serde_json::Value]) -> Result<bool> {+ if messages.is_empty() {+ return Ok(false);+ }+ let sent = self.host.host_messages(messages);+ let rebuilt = self.commit(core)?;+ sent?;+ Ok(rebuilt)+ }++ /// The messages the game posted for the app since the last call (`host.post`), in order: to be taken after each+ /// entry into the script, or once a frame.+ pub fn take_posts(&mut self) -> Vec<serde_json::Value> {+ self.host.take_posts()+ }+/// A frame was drawn: the first one after a click is timed (THREERT_CLICK_LOG=1).pub fn click_shown(&mut self) {if let Some(t) = self.clicked.take() {@@ -1010,6 +1076,35 @@ mod tests {assert!((up - 500.0 / 336.0).abs() < 0.05, "{up} m/s");}+ /// The host channel: what the script posts is the app's to take, in order, and bounded; the app's messages go to+ /// the node host's `hostMessages` as one JSON array; a bundle without that entry (built before the channel) is+ /// left alone.+ #[test]+ fn the_host_channel_queues_posts_and_delivers_batches() {+ let game = GAME.replace("frame: (dt) => { frames++; },", "frame: (dt) => { frames++; }, hostMessages: (list, ts) => { for (const m of JSON.parse(list)) __host_post(JSON.stringify({ t: 'echo', of: m, timed: ts > 0 })); },");+ assert!(game.contains("hostMessages"));+ let h = ScriptHost::new(&game).unwrap();+ assert!(h.take_posts().is_empty());+ h.host_messages(&[serde_json::json!({ "t": "net.opened", "id": "a" }), serde_json::json!({ "t": "input", "keys": ["W"] })]).unwrap();+ assert_eq!(h.take_posts(), vec![serde_json::json!({ "t": "echo", "of": { "t": "net.opened", "id": "a" }, "timed": true }), serde_json::json!({ "t": "echo", "of": { "t": "input", "keys": ["W"] }, "timed": true })]);+ assert!(h.take_posts().is_empty(), "taken once");+ // A queue nobody drains keeps its first messages and says no to the rest; a message past the bound throws.+ let kept: i32 = h.call(1000, |ctx| ctx.eval("let kept = 0; for (let i = 0; i < 3000; i++) if (__host_post(JSON.stringify({ t: 'n', i }))) kept++; kept")).unwrap();+ assert_eq!(kept as usize, MAX_POSTS);+ let posts = h.take_posts();+ assert_eq!((posts.len(), posts[0]["i"].as_u64(), posts[MAX_POSTS - 1]["i"].as_u64()), (MAX_POSTS, Some(0), Some(MAX_POSTS as u64 - 1)));+ let err = h.call(1000, |ctx| ctx.eval::<bool, _>("__host_post('x'.repeat(2 << 20))")).unwrap_err();+ assert!(format!("{err}").contains("host.post"), "{err}");+ assert!(h.take_posts().is_empty());+ // No `pointer` in the game's description: it asks for no input.+ assert_eq!(h.pointer(), None);+ assert_eq!(ScriptHost::new(&game.replace("frame: true,", "frame: true, pointer: 'look',")).unwrap().pointer(), Some("look"));+ // A bundle from before the channel.+ let old = ScriptHost::new(GAME).unwrap();+ old.host_messages(&[serde_json::json!({ "t": "launch", "params": {} })]).unwrap();+ assert!(old.take_posts().is_empty());+ }+#[test]fn budgets_and_errors() {let h = ScriptHost::new(GAME).unwrap();diff --git a/renderer/src/view.rs b/renderer/src/view.rsindex c69ad9a..f3fca51 100644--- a/renderer/src/view.rs+++ b/renderer/src/view.rs@@ -6,12 +6,22 @@//! The game runs in this process (script.rs): its code builds the scene, key bindings and clicks run its handlers, its//! frame script animates. `view` is the same window.//!+//! A game that reads input (`pointer` in its definition; docs/RUNTIME.md "Input") has the keys, the pointer and the+//! camera to itself: the window sends it an `input` message every frame and keeps none of the controls below but+//! Esc. With `pointer: "look"` a click captures the pointer (its motion is the game's look), Esc lets go of it, and+//! Esc again quits. The window is the app of the host channel: `--launch '{"room":"K7Q4MZ"}'` is the `launch`+//! message, `--sensitivity 1.5` scales the look, `--hud-log` prints the HUD the game describes (the window draws+//! none), and the game's `net.*` messages are the binary's sockets and HTTP (src/net.rs).+//!//! Controls: left-drag orbit · right/shift-drag pan · wheel zoom · WASD/QE fly · R reset camera · 1/2/4/8 cap spp,//! 0 adaptive · P snapshot · Esc quit. Scripted over stdio://! stdin JSON lines: {"cmd":"event","type":t,"payload":{..}} | {"cmd":"camera",...} | {"cmd":"snapshot","path":p} | {"cmd":"quit"}+//! | {"cmd":"host","messages":[{"t":..}, ..]}//! stdout JSON lines: {"type":"ready"} | {"type":"click","u":..,"v":..,"cam":{..},"seq":n} | {"type":"key","key":"L"}+//! | {"type":"host","messages":[..]} (what the game posted)use crate::gpu;+use crate::host::{launch_message, HostServices, InputTracker};use crate::live::{next_spp, parse_cmd, parse_scale, save_bgra, Camera, Cmd, LiveCore};use crate::script::GameSession;use anyhow::Result;@@ -22,10 +32,10 @@ use std::sync::{mpsc, Arc};use std::time::{Duration, Instant};use winit::application::ApplicationHandler;use winit::dpi::{LogicalSize, PhysicalPosition};-use winit::event::{ElementState, MouseButton, MouseScrollDelta, WindowEvent};+use winit::event::{DeviceEvent, DeviceId, ElementState, MouseButton, MouseScrollDelta, WindowEvent};use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};-use winit::keyboard::{Key, ModifiersState, NamedKey};-use winit::window::{Window, WindowId};+use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};+use winit::window::{CursorGrabMode, Window, WindowId};pub struct ViewArgs {/// Game bundle to run in-process.@@ -40,6 +50,12 @@ pub struct ViewArgs {pub bounces: u32,/// Render scale; None = dynamic resolution (default).pub scale: Option<f32>,+ /// `--launch`: the `params` of the host channel's `launch` message.+ pub launch: Option<serde_json::Value>,+ /// `--hud-log`: the HUD the game describes, printed when it changes.+ pub hud_log: bool,+ /// `--sensitivity`: scales the pointer's motion into the game's look (1: `host::LOOK_RADIANS` a count).+ pub sensitivity: f32,}/// Editor-style orbit camera around a target point.@@ -90,10 +106,68 @@ struct State {last: Instant,snapshot: Option<PathBuf>,game: GameSession,+ /// The game reads input (`pointer`): the keys and the pointer between two frames. None: the window's own+ /// controls, as for every game before input.+ input: Option<InputTracker>,+ /// `pointer: "look"`: a click captures the pointer.+ look: bool,+}++impl State {+ /// Captures the pointer for the game's look (hidden, held in the window), or lets go of it.+ fn capture(&mut self, on: bool) {+ let Some(i) = self.input.as_mut() else { return };+ if on == i.captured {+ return;+ }+ if on {+ // (Locked where the system has it, macOS among them; held inside the window elsewhere.)+ if self.window.set_cursor_grab(CursorGrabMode::Locked).or_else(|_| self.window.set_cursor_grab(CursorGrabMode::Confined)).is_err() {+ return eprintln!("view: the pointer cannot be captured here");+ }+ self.window.set_cursor_visible(false);+ } else {+ let _ = self.window.set_cursor_grab(CursorGrabMode::None);+ self.window.set_cursor_visible(true);+ }+ i.captured = on;+ }+}++/// A key by its place on the keyboard, as game code names it (packages/gameplay/src/input.ts).+fn key_name(code: KeyCode) -> Option<String> {+ use KeyCode::*;+ let fixed = match code {+ Space => "Space",+ ShiftLeft | ShiftRight => "Shift",+ ControlLeft | ControlRight => "Ctrl",+ AltLeft | AltRight => "Alt",+ SuperLeft | SuperRight => "Meta",+ Tab => "Tab",+ Enter | NumpadEnter => "Enter",+ Escape => "Escape",+ Backspace => "Backspace",+ ArrowLeft => "Left",+ ArrowRight => "Right",+ ArrowUp => "Up",+ ArrowDown => "Down",+ Minus | Equal | BracketLeft | BracketRight | Semicolon | Quote | Comma | Period | Slash | Backslash | Backquote => return Some(format!("{code:?}")),+ _ => {+ // KeyW -> "W", Digit1 -> "1", F5 -> "F5".+ let name = format!("{code:?}");+ return match name.strip_prefix("Key").or_else(|| name.strip_prefix("Digit")) {+ Some(k) if k.len() == 1 => Some(k.to_string()),+ _ => (name.len() <= 3 && name.starts_with('F') && name[1..].parse::<u8>().is_ok()).then_some(name),+ };+ }+ };+ Some(fixed.to_string())}struct App {args: ViewArgs,+ /// What the window offers the game beyond the picture (the binary's sockets and HTTP).+ services: Box<dyn HostServices>,cmds: mpsc::Receiver<Cmd>,state: Option<State>,error: Option<anyhow::Error>,@@ -132,7 +206,15 @@ impl App {// The view is the window's physical pixels (`--width` / `--height` are its size in points): the temporal upscaler// resolves to the display, and nothing is stretched after it.let (vw, vh) = (config.width, config.height);- let (game, mut core) = GameSession::start(&a.bundle, &a.room, &a.assets, g, &a.presets, vw, vh)?;+ let (mut game, mut core) = GameSession::start(&a.bundle, &a.room, &a.assets, g, &a.presets, vw, vh)?;+ // The host channel: how the game was opened, once after setup.+ if let Err(e) = game.host_messages(&mut core, &[launch_message(a.launch.as_ref())]) {+ eprintln!("game: launch: {e:#}");+ }+ let pointer = game.host.pointer().map(String::from);+ if let Some(p) = &pointer {+ eprintln!("view: the game reads input (pointer: {p}){}", if p == "look" { ": click to capture the pointer, Esc lets go" } else { "" });+ }core.set_display_scale(window.scale_factor() as f32);core.bounces = a.bounces;if let Some(s) = a.scale {@@ -190,6 +272,8 @@ impl App {last: Instant::now(),snapshot: None,game,+ input: pointer.is_some().then(InputTracker::new),+ look: pointer.as_deref() == Some("look"),});Ok(())}@@ -211,9 +295,25 @@ impl ApplicationHandler for App {match event {WindowEvent::CloseRequested => el.exit(),WindowEvent::ModifiersChanged(m) => s.mods = m.state(),+ WindowEvent::Focused(false) => {+ // (The keys' ups go to whoever has the keyboard now.)+ s.capture(false);+ if let Some(i) = s.input.as_mut() {+ i.release_all();+ }+ }WindowEvent::CursorMoved { position, .. } => {let (dx, dy) = ((position.x - s.cursor.x) as f32, (position.y - s.cursor.y) as f32);s.cursor = position;+ if let Some(i) = s.input.as_mut() {+ let size = s.window.inner_size();+ i.pointer((position.x / size.width.max(1) as f64) as f32, (position.y / size.height.max(1) as f64) as f32);+ // (The game's pointer: nothing orbits. A click is still a click: below.)+ if let Some((_, start, moved)) = &mut s.press {+ *moved |= (position.x - start.x).hypot(position.y - start.y) > 4.0 * s.window.scale_factor();+ }+ return;+ }let scale = s.window.scale_factor() as f32;if let Some((button, start, moved)) = &mut s.press {if (position.x - start.x).hypot(position.y - start.y) > 4.0 * scale as f64 {@@ -232,9 +332,36 @@ impl ApplicationHandler for App {}}}+ WindowEvent::MouseInput { state, button, .. } if s.look => {+ // The pointer is the game's look: the first click captures it, and from then on the buttons are+ // the game's input (no `click` event: there is no place the pointer points at).+ let n = match button {+ MouseButton::Left => 0,+ MouseButton::Middle => 1,+ MouseButton::Right => 2,+ _ => return,+ };+ let captured = s.input.as_ref().is_some_and(|i| i.captured);+ if !captured && state == ElementState::Pressed {+ s.capture(true);+ } else if let Some(i) = s.input.as_mut() {+ // (An up always: of a button that went down while captured.)+ if captured || state == ElementState::Released {+ i.button(n, state == ElementState::Pressed);+ }+ }+ }WindowEvent::MouseInput { state, button, .. } => match state {- ElementState::Pressed => s.press = Some((button, s.cursor, false)),+ ElementState::Pressed => {+ s.press = Some((button, s.cursor, false));+ if let (Some(i), Some(n)) = (s.input.as_mut(), button_number(button)) {+ i.button(n, true);+ }+ }ElementState::Released => {+ if let (Some(i), Some(n)) = (s.input.as_mut(), button_number(button)) {+ i.button(n, false);+ }if let Some((MouseButton::Left, _, false)) = s.press.take() {let size = s.window.inner_size();let (u, v) = ((s.cursor.x / size.width as f64) as f32, (s.cursor.y / size.height as f64) as f32);@@ -256,9 +383,18 @@ impl ApplicationHandler for App {MouseScrollDelta::LineDelta(_, y) => y * 40.0,MouseScrollDelta::PixelDelta(p) => p.y as f32,};+ if let Some(i) = s.input.as_mut() {+ return i.wheel(dy / 40.0);+ }s.orbit.dist = (s.orbit.dist * (-dy * 0.002).exp()).clamp(0.3, 100.0);}WindowEvent::KeyboardInput { event, .. } => {+ // The game's input: the key by its place on the keyboard, down or up.+ if let (Some(i), PhysicalKey::Code(code)) = (s.input.as_mut(), event.physical_key) {+ if let Some(name) = key_name(code) {+ i.key(&format!("{code:?}"), &name, event.state == ElementState::Pressed);+ }+ }let name = match &event.logical_key {Key::Character(c) => c.to_uppercase(),Key::Named(NamedKey::Escape) => "Escape".into(),@@ -273,6 +409,15 @@ impl ApplicationHandler for App {eprintln!("game: {h} failed: {e:#}");}follow_game_camera(s, cam);+ } else if s.input.is_some() {+ // The keys are the game's. Esc lets go of a captured pointer, and quits without one.+ if name == "Escape" && !event.repeat {+ if s.input.as_ref().is_some_and(|i| i.captured) {+ s.capture(false);+ } else {+ el.exit();+ }+ }} else if !event.repeat {match name.as_str() {"Escape" => el.exit(),@@ -292,7 +437,7 @@ impl ApplicationHandler for App {}}WindowEvent::RedrawRequested => {- if let Err(e) = frame(s, &self.cmds, fps) {+ if let Err(e) = frame(s, &self.cmds, self.services.as_mut(), &self.args, fps) {eprintln!("view: {e:#}");}if s.keys.contains("__quit") {@@ -303,6 +448,15 @@ impl ApplicationHandler for App {}}+ fn device_event(&mut self, _el: &ActiveEventLoop, _id: DeviceId, event: DeviceEvent) {+ // A captured pointer does not move: its motion comes from the device, and is the game's look.+ if let (DeviceEvent::MouseMotion { delta }, Some(s)) = (event, self.state.as_mut()) {+ if let Some(i) = s.input.as_mut().filter(|i| i.captured) {+ i.motion(delta.0 as f32, delta.1 as f32, self.args.sensitivity);+ }+ }+ }+fn about_to_wait(&mut self, el: &ActiveEventLoop) {// Present on every vsync (Fifo blocks); `frame` decides whether to render a new image or re-show the last.if let Some(s) = &self.state {@@ -312,7 +466,16 @@ impl ApplicationHandler for App {}}-fn frame(s: &mut State, cmds: &mpsc::Receiver<Cmd>, fps: u32) -> Result<()> {+fn button_number(b: MouseButton) -> Option<u8> {+ match b {+ MouseButton::Left => Some(0),+ MouseButton::Middle => Some(1),+ MouseButton::Right => Some(2),+ _ => None,+ }+}++fn frame(s: &mut State, cmds: &mpsc::Receiver<Cmd>, services: &mut dyn HostServices, args: &ViewArgs, fps: u32) -> Result<()> {// Content runs at `fps` regardless of the display's refresh rate (120 Hz panels re-show the last image).let render_new = s.last.elapsed() >= Duration::from_secs_f64(1.0 / fps as f64) - Duration::from_millis(2);if !render_new {@@ -353,27 +516,56 @@ fn frame(s: &mut State, cmds: &mpsc::Receiver<Cmd>, fps: u32) -> Result<()> {s.game.click(&mut s.core, u, v)?;follow_game_camera(s, cam);}+ Cmd::Host(messages) => {+ let cam = s.core.scene_camera();+ s.game.host_messages(&mut s.core, &messages)?;+ follow_game_camera(s, cam);+ }Cmd::Quit => {s.keys.insert("__quit".into());}}}- // WASD / QE fly: move the orbit target in the view plane.- let speed = s.orbit.dist * 0.8 * dt;- let fwd = Vec3::new(-s.orbit.yaw.sin(), 0.0, -s.orbit.yaw.cos());- let right = Vec3::new(s.orbit.yaw.cos(), 0.0, -s.orbit.yaw.sin());- for (k, dir) in [("W", fwd), ("S", -fwd), ("D", right), ("A", -right), ("E", Vec3::Y), ("Q", -Vec3::Y)] {- if s.keys.contains(k) {- s.orbit.target += dir * speed;+ // WASD / QE fly: move the orbit target in the view plane (the keys of a game that reads input are its own).+ if s.input.is_none() {+ let speed = s.orbit.dist * 0.8 * dt;+ let fwd = Vec3::new(-s.orbit.yaw.sin(), 0.0, -s.orbit.yaw.cos());+ let right = Vec3::new(s.orbit.yaw.cos(), 0.0, -s.orbit.yaw.sin());+ for (k, dir) in [("W", fwd), ("S", -fwd), ("D", right), ("A", -right), ("E", Vec3::Y), ("Q", -Vec3::Y)] {+ if s.keys.contains(k) {+ s.orbit.target += dir * speed;+ }}}let cam = s.core.scene_camera();s.core.advance_time(dt);+ // The host channel, app to game, before the frame script: the frame's input (for a game that reads it), then+ // what the services have (a batch of each socket's messages, answers to requests). One entry for all of it.+ let mut messages: Vec<serde_json::Value> = s.input.as_mut().map(|i| i.message()).into_iter().collect();+ messages.extend(services.poll());+ if let Err(e) = s.game.host_messages(&mut s.core, &messages) {+ eprintln!("game: host messages: {e:#}");+ }if let Err(e) = s.game.frame(&mut s.core, dt) {eprintln!("game: frame script: {e:#}");}- follow_game_camera(s, cam);- s.core.set_camera(s.orbit.camera(s.tan));+ // Game to app: what the game posted in this frame's entries (events among them).+ let posts = s.game.take_posts();+ for p in &posts {+ services.post(p);+ if args.hud_log && p["t"] == "hud" {+ eprintln!("hud: {}", p["hud"]);+ }+ }+ if !posts.is_empty() {+ emit(serde_json::json!({ "type": "host", "messages": posts }));+ }+ // A game that reads input has the camera to itself (the view follows it with every commit); any other game is+ // looked at through the window's orbit camera, which follows the game's when a handler moves it.+ if s.input.is_none() {+ follow_game_camera(s, cam);+ s.core.set_camera(s.orbit.camera(s.tan));+ }let tex = match s.surface.get_current_texture() {wgpu::CurrentSurfaceTexture::Success(t) | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,@@ -519,7 +711,8 @@ fn texel(x: i32, y: i32) -> vec4<f32> {}"#;-pub fn run(args: ViewArgs) -> Result<()> {+/// Opens the window. `services`: what the app answers the game's posts with (`host::NoServices`: nothing).+pub fn run(args: ViewArgs, services: Box<dyn HostServices>) -> Result<()> {let (tx, rx) = mpsc::channel::<Cmd>();std::thread::spawn(move || {for line in std::io::stdin().lock().lines() {@@ -536,7 +729,7 @@ pub fn run(args: ViewArgs) -> Result<()> {}});let el = EventLoop::new()?;- let mut app = App { args, cmds: rx, state: None, error: None };+ let mut app = App { args, services, cmds: rx, state: None, error: None };el.run_app(&mut app)?;if let Some(e) = app.error {return Err(e);@@ -557,5 +750,8 @@ pub fn parse_args(args: &[String], presets: &Path) -> Result<ViewArgs> {fps: num("--fps", 60),bounces: num("--bounces", 4),scale: parse_scale(flag("--scale").as_deref(), None)?,+ launch: crate::live::parse_launch(flag("--launch").as_deref())?,+ hud_log: args.iter().any(|a| a == "--hud-log"),+ sensitivity: flag("--sensitivity").map(|v| v.parse::<f32>()).transpose()?.filter(|v| v.is_finite()).unwrap_or(1.0),})}diff --git a/renderer/web/Cargo.toml b/renderer/web/Cargo.tomlindex 8af4ada..8383fc6 100644--- a/renderer/web/Cargo.toml+++ b/renderer/web/Cargo.toml@@ -10,7 +10,8 @@ publish = falsecrate-type = ["cdylib"][dependencies]-threert-render = { path = ".." }+# (Without its default features: `net` is the native binary's sockets, not the library's.)+threert-render = { path = "..", default-features = false }wgpu = "30"glam = "0.30"serde_json = "1"diff --git a/tools/fps-arena.ts b/tools/fps-arena.tsnew file mode 100644index 0000000..873532a--- /dev/null+++ b/tools/fps-arena.ts@@ -0,0 +1,155 @@+// The first-person arena without a window (games/fps/arena.game.ts; docs/RUNTIME.md "The host channel", "Input",+// "HUD"): the game in the live renderer in lockstep, with this script as the app of its host channel. The app sends+// `launch` (the runner's `--launch`) and `input` messages (`{"cmd":"host","messages":[...]}` on stdin) and reads what+// the game posts (`{"host":[...]}` lines on stdout: its HUD). Checked on numbers:+// 1. launch: the player's name from `--launch` is in the HUD; the capsule rests a skin above the ground;+// 2. W held for a second: 4.5 m forward, and nothing more once the key is let go;+// 3. sprinting at the platform with frames of 0.1 s (0.75 m a frame, more than a wall is thick): stopped a skin+// off its face, not inside it and not behind it;+// 4. walking into a wall at 45 degrees: it slides along the wall, and stops in the corner;+// 5. Space: a jump of v² / 2g, and back on the ground; held Space does not jump again;+// 6. the view turned onto a target by `look`, a press of the mouse button: tagged, once; the HUD says 1 / 5 with a+// hit flash; a second press on it tags nothing; `restart` (the R key's handler) puts it back.+// Exit 1 on a failed check, 2 when the GPU lock is held. The GPU lock is held.+// node tools/fps-arena.ts+import { execFileSync } from "node:child_process";+import { join } from "node:path";+import { HALF, HALF_HEIGHT, RADIUS, SKIN, SPRINT, START, TARGETS, WALK } from "../games/fps/arena.game.ts";+import type { Hud, HudText } from "@threert/gameplay";+import { acquireGpuLock, rendererBin, repoRoot } from "./lib/bench.ts";+import { branchBuild } from "./lib/build-at.ts";+import { startLive } from "./lib/live.ts";++const holder = acquireGpuLock("fps-arena");+if (holder) { console.log(`not run: GPU lock held by ${holder.tool} (pid ${holder.pid}) since ${holder.started}`); process.exit(2); }+const bundle = join(repoRoot, "out/bundles/fps-arena.js");+execFileSync("node", [join(repoRoot, "tools/bundle-game.ts"), join(repoRoot, "games/fps/arena.game.ts"), "-o", bundle], { stdio: "ignore" });++// What the game posted: every message, and the HUD as last described.+const posts: { t: string; hud?: Hud }[] = [];+const live = startLive(branchBuild(rendererBin), bundle, {+ width: 640, height: 360,+ args: ["--launch", JSON.stringify({ name: "Ada", room: "K7Q4MZ" })],+ stdout: (line) => { try { posts.push(...((JSON.parse(line) as { host?: { t: string }[] }).host ?? [])); } catch { /* not a line of ours */ } },+});+await live.firstFrame;+const DT = 1 / 60;+live.send({ cmd: "lockstep", dt: DT });+let id = 0;+const step = async (frames: number) => {+ const sync = `s${++id}`;+ live.send({ cmd: "frames", n: frames, sync });+ await live.wait((l) => l.includes(`live: sync ${sync}`));+};+/** An input message, as an app sends one a frame (here: when something changes; what is held stays held). */+const input = (m: object) => live.send({ cmd: "host", messages: [{ t: "input", captured: true, ...m }] });+interface Report { at: [number, number, number]; yaw: number; pitch: number; grounded: boolean; tagged: number; shots: number }+const report = async (): Promise<Report> => {+ const n = live.lines.length;+ live.send({ cmd: "event", type: "report" });+ await step(1);+ const line = live.lines.slice(n).map((l) => /arena (\{"at".*\})/.exec(l)?.[1]).find((x) => x);+ if (!line) throw new Error("no report");+ return JSON.parse(line) as Report;+};+const hud = (): Hud => posts.filter((p) => p.t === "hud").at(-1)?.hud ?? {};+const text = (h: Hud, label: string) => (h.items ?? []).find((i): i is HudText => i.type === "text" && i.label === label)?.text;++const failures: string[] = [];+const check = (ok: boolean, what: string) => { console.log(`${ok ? "ok " : "FAIL"} ${what}`); if (!ok) failures.push(what); };+const f = (v: number) => v.toFixed(3);+const REST = HALF_HEIGHT + RADIUS + SKIN;++// 1. Launch, and rest.+await step(30);+let r = await report();+check(JSON.stringify(hud()).includes('"Ada"'), "the HUD has the name the app launched the game with");+check(hud().crosshair?.style === "cross" && text(hud(), "Tagged") === `0 / ${TARGETS.length}`, `the HUD: a crosshair, Tagged ${text(hud(), "Tagged")}`);+check(r.grounded && Math.abs(r.at[1] - REST) < 2e-3 && r.at[0] === START[0] && r.at[2] === START[2], `at rest on the ground: y ${f(r.at[1])} (${f(REST)}: the capsule a skin above it)`);+const quiet = posts.length;+await step(30);+check(posts.length === quiet, "nothing posted while the HUD does not change");++// 2. Walk.+input({ keys: ["W"] });+await step(60);+input({ keys: [] });+await step(10);+r = await report();+check(Math.abs(START[2] - r.at[2] - WALK) < 0.02 && Math.abs(r.at[0]) < 1e-3, `W for 60 frames: ${f(START[2] - r.at[2])} m forward (${WALK} m/s), then still`);++// 3. Sprint at the platform's face (z = -8.8) with long frames.+live.send({ cmd: "lockstep", dt: 0.1 });+input({ keys: ["W", "Shift"] });+await step(40);+input({ keys: [] });+live.send({ cmd: "lockstep", dt: DT });+await step(2);+r = await report();+const face = -8.8 + RADIUS;+check(r.at[2] >= face && r.at[2] - face < 2 * SKIN + 1e-3, `sprinting ${f(SPRINT * 0.1)} m a frame at the platform: stopped at z ${f(r.at[2])}, ${f(r.at[2] - face)} m off its face`);++// 4. Back to the middle, then into the west wall at 45 degrees: it slides north along it into the corner.+live.send({ cmd: "event", type: "restart" });+input({ dx: -Math.PI / 4 }); // (to the left: yaw is the other way from look's dx)+await step(1);+input({ keys: ["W", "Shift"] });+await step(180);+r = await report();+const west = -HALF + RADIUS;+check(Math.abs(r.yaw - Math.PI / 4) < 1e-4, `look.dx of -45 degrees turned the view 45 degrees left (yaw ${f(r.yaw)})`);+check(r.at[0] >= west && r.at[0] - west < 2 * SKIN + 1e-3 && r.at[2] < START[2] - 8, `along the west wall: x ${f(r.at[0])} (${f(r.at[0] - west)} m off it), z ${f(r.at[2])}`);+await step(240);+input({ keys: [] });+await step(2);+r = await report();+const north = -HALF + RADIUS;+check(r.at[0] - west < 2 * SKIN + 1e-3 && r.at[2] >= north && r.at[2] - north < 2 * SKIN + 1e-3, `in the corner: (${f(r.at[0])}, ${f(r.at[2])}), inside both walls`);++// 5. Jump.+live.send({ cmd: "event", type: "restart" });+await step(5);+input({ keys: ["Space"], pressed: ["Space"] });+let top = 0;+for (let k = 0; k < 60; k++) {+ await step(1);+ top = Math.max(top, (await report()).at[1]);+}+r = await report();+const rise = 5 * 5 / (2 * 14);+check(Math.abs(top - REST - rise) < 0.06, `Space: up ${f(top - REST)} m (v² / 2g = ${f(rise)})`);+check(r.grounded && Math.abs(r.at[1] - REST) < 2e-3, "and down again; Space still held does not jump twice");+input({ keys: [] });++// 6. Turn onto a target and tag it.+const target = TARGETS[4];+const eye = [r.at[0], r.at[1] + 0.7, r.at[2]];+const d = [target[0] - eye[0], target[1] - eye[1], target[2] - eye[2]];+const yaw = Math.atan2(-d[0], -d[2]), pitch = Math.asin(d[1] / Math.hypot(...d));+input({ dx: r.yaw - yaw, dy: r.pitch - pitch });+await step(1);+input({ buttons: [0], pressed: ["Mouse0"] });+await step(1);+input({ buttons: [], released: ["Mouse0"] });+await step(2);+r = await report();+const tags = live.lines.filter((l) => l.includes('arena {"tagged"'));+check(r.tagged === 1 && r.shots === 1 && tags.length === 1 && tags[0].includes("target 5"), `the view ray tags ${/"tagged":"([^"]+)"/.exec(tags[0] ?? "")?.[1] ?? "nothing"} with one shot`);+check(text(hud(), "Tagged") === `1 / ${TARGETS.length}` && hud().flash?.kind === "hit" && hud().flash?.n === 1, `the HUD: Tagged ${text(hud(), "Tagged")}, a hit flash`);+input({ buttons: [0], pressed: ["Mouse0"] });+await step(1);+input({ buttons: [] });+await step(1);+r = await report();+check(r.tagged === 1 && r.shots === 2, "a second shot on it tags nothing more");+live.send({ cmd: "event", type: "restart" });+await step(2);+r = await report();+check(r.tagged === 0 && text(hud(), "Tagged") === `0 / ${TARGETS.length}`, "restart (the R key's handler): none tagged");++await live.quit();+const errors = live.lines.filter((l) => /frame script:|host messages failed|\[game error\]/.test(l));+check(errors.length === 0, `no script error${errors.length ? `: ${errors[0]}` : ""}`);+console.log(`fps arena: ${posts.length} messages posted by the game (${posts.filter((p) => p.t === "hud").length} HUD descriptions) over ${id} steps`);+if (failures.length) { console.error(`fps arena: ${failures.length} check(s) failed`); process.exit(1); }+console.log("fps arena: all checks pass");diff --git a/tools/host-echo.ts b/tools/host-echo.tsnew file mode 100644index 0000000..f82e4e6--- /dev/null+++ b/tools/host-echo.ts@@ -0,0 +1,175 @@+// The host channel end to end (docs/RUNTIME.md "The host channel"), on games/host/echo.game.ts: a game that has the+// app open a socket, says hello, answers the first messages that come back, and has the app fetch a page.+//+// 1. `threert-render live`, with this script as the app: the game's posts are read from the runner's stdout+// (`{"host":[...]}`), and answered on its stdin (`{"cmd":"host","messages":[...]}`). Checked: the order of the+// game's posts (net.open, net.send x 3, net.close; net.fetch), that a batch of messages reaches its listeners,+// that what they emit is committed (the state's count is in the HUD), and that the HUD is posted as it changes.+// 2. `threert-render play` (a window, for about three seconds), which is an app itself: the same game against a+// WebSocket and HTTP server on this machine, through the binary's own sockets. Checked: the server got the+// game's three messages in order, the game got the three answers, the close and the page.+// 3. the three.js view in headless Chrome (tools/three/view.ts), an app too: the same game against the same server,+// through the browser's WebSocket and fetch, its HUD read off the page.+//+// Exit 1 on a failed check, 2 when the GPU lock is held. The GPU lock is held.+// node tools/host-echo.ts [--no-play] [--no-three]+import { execFileSync, spawn } from "node:child_process";+import { createHash } from "node:crypto";+import { createServer } from "node:http";+import { createInterface } from "node:readline";+import { join } from "node:path";+import type { Duplex } from "node:stream";+import { ROUNDS } from "../games/host/echo.game.ts";+import type { Hud, HudText } from "@threert/gameplay";+import { acquireGpuLock, rendererBin, repoRoot } from "./lib/bench.ts";+import { branchBuild } from "./lib/build-at.ts";+import { startLive } from "./lib/live.ts";+import { bundlePage, launch as launchChrome, root, serve } from "./three/browser.ts";++const holder = acquireGpuLock("host-echo");+if (holder) { console.log(`not run: GPU lock held by ${holder.tool} (pid ${holder.pid}) since ${holder.started}`); process.exit(2); }+const bundle = join(repoRoot, "out/bundles/host-echo.js");+execFileSync("node", [join(repoRoot, "tools/bundle-game.ts"), join(repoRoot, "games/host/echo.game.ts"), "-o", bundle], { stdio: "ignore" });+const failures: string[] = [];+const check = (ok: boolean, what: string) => { console.log(`${ok ? "ok " : "FAIL"} ${what}`); if (!ok) failures.push(what); };+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));+type Post = { t: string; id?: string; url?: string; data?: string; hud?: Hud };+const messages = (h: Hud | undefined) => (h?.items ?? []).find((i): i is HudText => i.type === "text" && i.label === "Messages")?.text;+const answers = (lines: string[]) => lines.map((l) => /echo got (".*")/.exec(l)?.[1]).filter((x): x is string => !!x).map((x) => JSON.parse(x) as string);++/** A WebSocket and HTTP server on this machine: it answers every text message with "echo: <text>". */+async function echoServer(): Promise<{ port: number; got: string[]; closeCode(): number; close(): void }> {+ const got: string[] = [];+ let closeCode = 0;+ const server = createServer((_req, res) => res.writeHead(200, { "content-type": "text/plain", "access-control-allow-origin": "*" }).end("hello from http"));+ server.on("upgrade", (req, socket: Duplex) => {+ const accept = createHash("sha1").update(`${req.headers["sec-websocket-key"]}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64");+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);+ const frame = (op: number, payload: Buffer) => socket.write(Buffer.concat([Buffer.from([0x80 | op, payload.length]), payload]));+ let buf: Buffer = Buffer.alloc(0);+ socket.on("data", (d: Buffer) => {+ buf = Buffer.concat([buf, d]);+ // (Short masked frames, as this game sends them.)+ while (buf.length >= 6 && buf.length >= 6 + (buf[1] & 127)) {+ const n = buf[1] & 127, mask = buf.subarray(2, 6);+ const payload = Buffer.from(buf.subarray(6, 6 + n).map((b, k) => b ^ mask[k % 4]));+ const op = buf[0] & 15;+ buf = buf.subarray(6 + n);+ if (op === 1) {+ got.push(payload.toString());+ frame(1, Buffer.from(`echo: ${payload.toString()}`));+ } else if (op === 8) {+ closeCode = n >= 2 ? payload.readUInt16BE(0) : 1005;+ frame(8, payload.subarray(0, 2));+ socket.end();+ }+ }+ });+ socket.on("error", () => {});+ });+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));+ return { port: (server.address() as { port: number }).port, got, closeCode: () => closeCode, close: () => void server.close() };+}++// ---------------------------------------------------------------------------------------------- 1. live+{+ const posts: Post[] = [];+ let handled = 0;+ const live = startLive(branchBuild(rendererBin), bundle, {+ width: 320, height: 180,+ args: ["--launch", JSON.stringify({ url: "ws://app.test/echo", fetch: "http://app.test/hello" })],+ stdout: (line) => { try { posts.push(...((JSON.parse(line) as { host?: Post[] }).host ?? [])); } catch { /* not ours */ } },+ });+ await live.firstFrame;+ live.send({ cmd: "lockstep", dt: 1 / 60 });+ let id = 0;+ const step = async (frames: number) => {+ const sync = `s${++id}`;+ live.send({ cmd: "frames", n: frames, sync });+ await live.wait((l) => l.includes(`live: sync ${sync}`));+ };+ // The app: what an embedder does with each post, a frame at a time, until the game closes its socket.+ let closed = false;+ for (let frame = 0; frame < 60 && !closed; frame++) {+ await step(1);+ const out: object[] = [];+ for (const p of posts.slice(handled)) {+ if (p.t === "net.open") out.push({ t: "net.opened", id: p.id });+ else if (p.t === "net.send") out.push({ t: "net.messages", id: p.id, list: [`echo: ${p.data}`] });+ else if (p.t === "net.fetch") out.push({ t: "net.fetched", id: p.id, status: 200, body: "hello from the app" });+ else if (p.t === "net.close") { out.push({ t: "net.closed", id: p.id, code: 1000, reason: "" }); closed = true; }+ }+ handled = posts.length;+ if (out.length) live.send({ cmd: "host", messages: out });+ }+ await step(2);+ await live.quit();+ const net = posts.filter((p) => p.t.startsWith("net."));+ console.log("host echo: live, this script as the app");+ check(net.map((p) => p.t).join() === ["net.open", "net.fetch", ...Array(ROUNDS).fill("net.send"), "net.close"].join(), `the game's posts: ${net.map((p) => p.t).join(", ")}`);+ check(net[0].url === "ws://app.test/echo" && net[1].url === "http://app.test/hello", "launch: the addresses the app opened the game with");+ check(net.filter((p) => p.t === "net.send").map((p) => p.data).join() === "hello,again 1,again 2", `it sent ${net.filter((p) => p.t === "net.send").map((p) => p.data).join(", ")}`);+ check(answers(live.lines).join() === "echo: hello,echo: again 1,echo: again 2", `its listeners got ${answers(live.lines).join(", ")}`);+ check(live.lines.some((l) => l.includes('echo fetched 200 "hello from the app"')) && live.lines.some((l) => l.includes("echo closed 1000")), "and the page, and the close");+ const huds = posts.filter((p) => p.t === "hud").map((p) => messages(p.hud));+ check(huds.at(-1) === String(ROUNDS) && new Set(huds).size === ROUNDS + 1, `what the listeners emitted is in the state: the HUD counted ${[...new Set(huds)].join(", ")}`);+}++// ---------------------------------------------------------------------------------------------- 2. play+if (!process.argv.includes("--no-play")) {+ const { port, got, closeCode, close } = await echoServer();+ const launch = JSON.stringify({ url: `ws://127.0.0.1:${port}/socket`, fetch: `http://127.0.0.1:${port}/hello` });+ const p = spawn(rendererBin, ["play", bundle, "--assets", repoRoot, "--presets", join(repoRoot, "presets"), "--width", "480", "--height", "270", "--launch", launch], { stdio: ["pipe", "pipe", "pipe"] });+ const lines: string[] = [];+ const posts: Post[] = [];+ createInterface({ input: p.stderr! }).on("line", (l) => lines.push(l));+ createInterface({ input: p.stdout! }).on("line", (l) => { try { const m = JSON.parse(l) as { type?: string; messages?: Post[] }; if (m.type === "host") posts.push(...(m.messages ?? [])); } catch { /* not ours */ } });+ const exited = new Promise<void>((r) => p.on("exit", () => r()));+ const done = () => lines.some((l) => l.includes("echo closed")) && lines.some((l) => l.includes("echo fetched"));+ for (let k = 0; k < 100 && !done() && p.exitCode === null; k++) await sleep(100);+ await sleep(300);+ p.stdin!.write(JSON.stringify({ cmd: "quit" }) + "\n");+ const kill = setTimeout(() => p.kill(), 5000);+ await exited;+ clearTimeout(kill);+ close();+ console.log("host echo: play, the window's own sockets");+ check(got.join() === "hello,again 1,again 2", `the server got ${got.join(", ") || "nothing"}`);+ check(answers(lines).join() === "echo: hello,echo: again 1,echo: again 2", `the game got ${answers(lines).join(", ") || "nothing"}`);+ check(closeCode() === 1000 && lines.some((l) => l.includes("echo closed 1000")), `the game's close reached the server (${closeCode()}) and came back`);+ check(lines.some((l) => l.includes('echo fetched 200 "hello from http"')), "the page was fetched");+ check(messages(posts.filter((q) => q.t === "hud").at(-1)?.hud) === String(ROUNDS), "the window passes the HUD on");+ const errors = lines.filter((l) => /host messages:|frame script:|\[game error\]/.test(l));+ check(errors.length === 0, `no script error${errors.length ? `: ${errors[0]}` : ""}`);+}++// ---------------------------------------------------------------------------------------------- 3. three.js+if (!process.argv.includes("--no-three")) {+ const { port, got, closeCode, close } = await echoServer();+ const lines: string[] = [];+ const { html } = await bundlePage("host-echo-view", join(repoRoot, "games/host/echo.game.ts"), join(root, "tools/three/view.ts"));+ const { server, origin } = await serve(root);+ const browser = await launchChrome((l) => lines.push(l));+ let shown = "";+ try {+ const page = await browser.open(`${origin}${html}?url=${encodeURIComponent(`ws://127.0.0.1:${port}/socket`)}&fetch=${encodeURIComponent(`http://127.0.0.1:${port}/hello`)}`);+ const done = () => lines.some((l) => l.includes("echo closed")) && lines.some((l) => l.includes("echo fetched"));+ for (let k = 0; k < 300 && !done(); k++) await sleep(100);+ await sleep(300);+ shown = await page.evaluate<string>(`document.querySelector(".hud")?.innerText ?? ""`);+ await page.close();+ } finally {+ browser.close();+ server.close();+ close();+ }+ console.log("host echo: the three.js view, the browser's sockets");+ check(got.join() === "hello,again 1,again 2", `the server got ${got.join(", ") || "nothing"}`);+ check(answers(lines).join() === "echo: hello,echo: again 1,echo: again 2", `the game got ${answers(lines).join(", ") || "nothing"}`);+ check(closeCode() === 1000 && lines.some((l) => l.includes("echo closed 1000")), `the game's close reached the server (${closeCode()}) and came back`);+ check(lines.some((l) => l.includes('echo fetched 200 "hello from http"')), "the page was fetched");+ check(/MESSAGES\s+3/i.test(shown) && /closed \(1000\)/.test(shown), `the HUD on the page: ${JSON.stringify(shown.replace(/\s+/g, " "))}`);+}++if (failures.length) { console.error(`host echo: ${failures.length} check(s) failed`); process.exit(1); }+console.log("host echo: all checks pass");diff --git a/tools/lib/live.ts b/tools/lib/live.tsindex b5aeebf..66d5206 100644--- a/tools/lib/live.ts+++ b/tools/lib/live.ts@@ -80,7 +80,8 @@ export interface Live {quit(): Promise<void>;}-export function startLive(b: Build, bundle: string, o: { scale?: string; env?: Record<string, string>; frameLog?: string; profile?: boolean; room?: string; width?: number; height?: number; bounces?: number } = {}): Live {+/** `stdout`: the runner's stdout lines (what the game posts on the host channel: `{"host":[...]}`); `args`: more flags. */+export function startLive(b: Build, bundle: string, o: { scale?: string; env?: Record<string, string>; frameLog?: string; profile?: boolean; room?: string; width?: number; height?: number; bounces?: number; stdout?: (line: string) => void; args?: string[] } = {}): Live {const args = ["live", bundle, "--assets", b.assets, "--presets", b.presets, "--width", String(o.width ?? 1280), "--height", String(o.height ?? 720), "--scale", o.scale ?? "0.5"];if (o.bounces) args.push("--bounces", String(o.bounces));if (o.room) args.push("--room", o.room);@@ -90,7 +91,9 @@ export function startLive(b: Build, bundle: string, o: { scale?: string; env?: R}const t0 = performance.now();const env = { ...process.env, ...(o.profile ? switches("PROFILE", "1") : {}), ...o.env };- const p = spawn(b.bin, args, { stdio: ["pipe", "ignore", "pipe"], env });+ if (o.args) args.push(...o.args);+ const p = spawn(b.bin, args, { stdio: ["pipe", o.stdout ? "pipe" : "ignore", "pipe"], env });+ if (o.stdout) createInterface({ input: p.stdout! }).on("line", o.stdout);const lines: string[] = [];let waiters: [(l: string) => boolean, (l: string) => void][] = [];createInterface({ input: p.stderr! }).on("line", (l) => {diff --git a/tools/npm-pack.ts b/tools/npm-pack.tsindex 2536b8b..791a0af 100644--- a/tools/npm-pack.ts+++ b/tools/npm-pack.ts@@ -120,7 +120,7 @@ function check(dirs: string[]): void {writeFileSync(join(project, "package.json"), JSON.stringify({ name: "check", private: true, type: "module" }));run("npm", ["install", "--silent", "--no-audit", "--no-fund", "--ignore-scripts", ...tarballs], project);writeFileSync(join(project, "use.ts"), `import { Scene, PerspectiveCamera, Mesh, BoxGeometry, MeshStandardMaterial, DirectionalLight, SkyAtmosphere, resolvePreset } from "@threert/scene";-import { defineGame, describeGame, type GameDefinition } from "@threert/gameplay";+import { defineGame, describeGame, host, hud, type GameDefinition, type Hud, type Input } from "@threert/gameplay";import { VoxelGrid } from "@threert/voxel";const game = defineGame({@@ -139,10 +139,19 @@ const game = defineGame({return { scene, camera };},handlers: { click(tx) { tx.state.lit = !tx.state.lit; } },+ pointer: "look",+ frame(f) {+ const input: Input = f.input;+ const view: Hud = { crosshair: { style: "dot" }, items: [{ type: "text", anchor: "top-left", text: input.down("W") ? "walking" : "still" }] };+ hud.set(view);+ },});+// The host channel: nobody listens in Node, so a post is dropped; a listener is typed by its message.+const off = host.on("net.messages", (m) => void m.list.length);+off();const about = describeGame(game as GameDefinition<unknown>);const built = game.setup({} as Parameters<typeof game.setup>[0]);-if (!about.handlers.includes("click") || !(built.scene instanceof Scene) || typeof resolvePreset("preview") !== "object" || new VoxelGrid(0.1).size !== 0.1) throw new Error("the packages did not load as expected");+if (!about.handlers.includes("click") || about.pointer !== "look" || host.post({ t: "net.close", id: "none" }) !== false || !(built.scene instanceof Scene) || typeof resolvePreset("preview") !== "object" || new VoxelGrid(0.1).size !== 0.1) throw new Error("the packages did not load as expected");`);// What a user's compiler makes of the declarations: strict, nothing skipped, no Node or DOM types given; resolved// as a bundler does, and as Node does.@@ -151,7 +160,7 @@ if (!about.handlers.includes("click") || !(built.scene instanceof Scene) || typestep(`the check's typecheck (${moduleResolution})`, process.execPath, [tsc, "-p", project], project);}step("the check's run", process.execPath, ["use.ts"], project);- console.log("check: the tarballs install, typecheck (strict, no skipLibCheck, no Node or DOM types) and build a scene and a game in Node");+ console.log("check: the tarballs install, typecheck (strict, no skipLibCheck, no Node or DOM types) and build a scene and a game (with input, a HUD and the host channel) in Node");}const dirs = NAMES.map(build);diff --git a/tools/three-arena.ts b/tools/three-arena.tsnew file mode 100644index 0000000..045681d--- /dev/null+++ b/tools/three-arena.ts@@ -0,0 +1,101 @@+// The first-person arena in the three.js view, in a real browser (games/fps/arena.game.ts; tools/three/view.ts;+// docs/RUNTIME.md "The host channel"): headless Chrome driven over the DevTools protocol with the events a keyboard+// and a mouse send, so the page's own input path is what is checked (key codes, the pointer lock, the mouse's+// motion), with the engine's physics loaded (tools/three/physics.ts). Real time, so the distances are checked loosely;+// the exact numbers are tools/three/test/physics.test.ts's and tools/fps-arena.ts's.+// 1. launch: the name in the page's query is in the HUD, which is DOM over the canvas;+// 2. W held for a second: about 4.5 m forward;+// 3. a click takes the pointer lock and is not a shot; the mouse moved 100 px turns the view 0.25 rad;+// 4. Shift + W into the platform: stopped at its face;+// 5. a click with the pointer held is a shot.+// Writes a screenshot (out/three/arena.png). Exit 1 on a failed check.+// node tools/three-arena.ts+import { mkdirSync } from "node:fs";+import { join } from "node:path";+import { RADIUS, SKIN, START, WALK } from "../games/fps/arena.game.ts";+import { bundlePage, launch, root, serve } from "./three/browser.ts";+import { buildScenePhysics, SCENE_PHYSICS } from "./three/physics-build.ts";++const lines: string[] = [];+const { html } = await bundlePage("fps-arena-view", join(root, "games/fps/arena.game.ts"), join(root, "tools/three/view.ts"));+buildScenePhysics();+const { server, origin } = await serve(root);+const browser = await launch((l) => lines.push(l));+const failures: string[] = [];+const check = (ok: boolean, what: string) => { console.log(`${ok ? "ok " : "FAIL"} ${what}`); if (!ok) failures.push(what); };+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));+try {+ const page = await browser.open(`${origin}${html}?physics=/${SCENE_PHYSICS}&name=Ada&room=K7Q4MZ`);+ await page.evaluate(`new Promise((ok, fail) => { const t0 = Date.now(); const k = setInterval(() => { if (document.querySelector(".hud-text")) { clearInterval(k); ok(true); } else if (Date.now() - t0 > 60000) { clearInterval(k); fail(new Error("no HUD after 60 s")); } }, 100); })`);+ await sleep(500);+ interface Report { at: [number, number, number]; yaw: number; pitch: number; grounded: boolean; tagged: number; shots: number }+ const report = async (): Promise<Report> => {+ const n = lines.length;+ await page.evaluate(`void __threert.event("report", "{}", Date.now())`);+ for (let k = 0; k < 50; k++) {+ const l = lines.slice(n).map((x) => /arena (\{"at".*\})/.exec(x)?.[1]).find((x) => x);+ if (l) return JSON.parse(l) as Report;+ await sleep(20);+ }+ throw new Error("no report");+ };+ const key = (type: "keyDown" | "keyUp", code: string, vk: number) => page.input("dispatchKeyEvent", { type, code, key: code.replace(/^Key/, "").toLowerCase(), windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk });+ const mouse = (type: "mousePressed" | "mouseReleased" | "mouseMoved", x: number, y: number, held = false) =>+ page.input("dispatchMouseEvent", { type, x, y, button: type === "mouseMoved" && !held ? "none" : "left", buttons: type === "mousePressed" || held ? 1 : 0, clickCount: type === "mouseMoved" ? 0 : 1 });+ const hud = () => page.evaluate<string>(`document.querySelector(".hud").innerText`);++ // 1. Launch and the HUD.+ let r = await report();+ const text = await hud();+ check(text.includes("Ada") && /0 \/ 5/.test(text) && /click to look around/i.test(text), `the HUD is on the page: ${JSON.stringify(text.replace(/\s+/g, " ").slice(0, 90))}`);+ check(r.grounded && r.at[0] === START[0] && Math.abs(r.at[1] - 0.92) < 2e-3, `the capsule rests on the engine's ground: y ${r.at[1]}`);+ // 2. W for a second.+ await key("keyDown", "KeyW", 87);+ await sleep(1000);+ await key("keyUp", "KeyW", 87);+ await sleep(100);+ r = await report();+ const walked = START[2] - r.at[2];+ check(Math.abs(walked - WALK) < 0.6, `W for a second: ${walked.toFixed(2)} m forward (${WALK} m/s)`);+ // 3. The pointer lock, and look.+ await mouse("mouseMoved", 640, 360);+ await mouse("mousePressed", 640, 360);+ await mouse("mouseReleased", 640, 360);+ await sleep(300);+ const locked = await page.evaluate<boolean>(`document.pointerLockElement === document.querySelector("canvas")`);+ r = await report();+ check(locked && r.shots === 0, `a click takes the pointer lock (${locked}) and is not a shot`);+ check(!/click to look around/i.test(await hud()), "the HUD's hint goes once the pointer is the game's");+ for (let k = 1; k <= 10; k++) await mouse("mouseMoved", 640 + 10 * k, 360);+ await sleep(100);+ r = await report();+ check(Math.abs(r.yaw + 0.25) < 0.02, `the mouse moved 100 px to the right: yaw ${r.yaw} (0.0025 rad a pixel)`);+ for (let k = 9; k >= 0; k--) await mouse("mouseMoved", 640 + 10 * k, 360);+ await sleep(100);+ mkdirSync(join(root, "out/three"), { recursive: true });+ await page.screenshot(join(root, "out/three/arena.png"));+ // 4. Sprint into the platform.+ await page.input("dispatchKeyEvent", { type: "keyDown", code: "ShiftLeft", key: "Shift", windowsVirtualKeyCode: 16, nativeVirtualKeyCode: 16 });+ await key("keyDown", "KeyW", 87);+ await sleep(2500);+ await key("keyUp", "KeyW", 87);+ await page.input("dispatchKeyEvent", { type: "keyUp", code: "ShiftLeft", key: "Shift", windowsVirtualKeyCode: 16, nativeVirtualKeyCode: 16 });+ await sleep(100);+ r = await report();+ const face = -8.8 + RADIUS;+ check(Math.abs(r.yaw) < 0.02 && r.at[2] >= face && r.at[2] - face < 2 * SKIN + 1e-3, `sprinting at the platform: stopped at z ${r.at[2]} (${(r.at[2] - face).toFixed(3)} m off its face)`);+ // 5. A shot.+ await mouse("mousePressed", 640, 360);+ await mouse("mouseReleased", 640, 360);+ await sleep(150);+ r = await report();+ check(r.shots === 1, "a click with the pointer held is a shot");+ const errors = lines.filter((l) => /\[page (exception|error)\]|frame script:/.test(l));+ check(errors.length === 0, `no error on the page${errors.length ? `: ${errors[0]}` : ""}`);+ await page.close();+} finally {+ browser.close();+ server.close();+}+if (failures.length) { console.error(`three arena: ${failures.length} check(s) failed`); process.exit(1); }+console.log("three arena: all checks pass (out/three/arena.png)");diff --git a/tools/three/browser.ts b/tools/three/browser.tsindex 6f3d816..7b048e3 100644--- a/tools/three/browser.ts+++ b/tools/three/browser.ts@@ -42,7 +42,7 @@ export async function bundlePage(id: string, src: string, page = join(root, "tooconst TYPES: Record<string, string> = {".html": "text/html", ".js": "text/javascript", ".json": "application/json", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",".glb": "model/gltf-binary", ".gltf": "model/gltf+json", ".bin": "application/octet-stream", ".exr": "application/octet-stream", ".hdr": "application/octet-stream",- ".ktx2": "image/ktx2", ".webp": "image/webp",+ ".ktx2": "image/ktx2", ".webp": "image/webp", ".wasm": "application/wasm",};/** Static file server for the repo root (read-only, no directory listings); `assets/...` may also come from another@@ -106,6 +106,8 @@ export interface Page {evaluate<T = unknown>(expression: string, timeoutMs?: number): Promise<T>;/** A PNG of the viewport. */screenshot(file: string): Promise<void>;+ /** An input event as the browser gets one from a device (DevTools' `Input.<method>`): a key, the mouse. */+ input(method: string, params: object): Promise<void>;close(): Promise<void>;}@@ -200,6 +202,9 @@ export async function launch(log: (line: string) => void = () => {}): Promise<Brconst r = await cdp.send("Page.captureScreenshot", { format: "png" }, sessionId);writeFileSync(file, Buffer.from(r.data, "base64"));},+ async input(method, params) {+ await cdp.send(`Input.${method}`, params, sessionId);+ },async close() {await cdp.send("Target.closeTarget", { targetId }).catch(() => {});},diff --git a/tools/three/engine.ts b/tools/three/engine.tsindex e31234d..d5e1bc5 100644--- a/tools/three/engine.ts+++ b/tools/three/engine.ts@@ -27,6 +27,7 @@ import type {AnimationDesc, CameraDesc, Engine, EnvironmentDesc, LightDesc, MaterialDesc, ObjectDesc, SettingsDesc, SwayDesc, TextureDesc,} from "@threert/scene";import { windAngle, windPhase } from "@threert/scene";+import type { ScenePhysics } from "./physics.ts";import { bakeEquirect, gradientRadiance, type Mask, SKY_NITS_PER_LUX, sunTransmittance, type V3 } from "./sky.ts";interface Node {@@ -144,6 +145,11 @@ export class ThreeEngine implements Engine {private sky: THREE.Mesh | null = null;private envTexture: THREE.Texture | null = null;private readonly droppedBy = new Map<string, Set<string>>();+ /** The engine's physics, when the view loaded it (tools/three/physics.ts): without it bodies stay where the scene+ * put them and the queries find nothing, as before. Set before the game's setup. */+ bodies: ScenePhysics | null = null;+ /** The bodies that drive an object: body id -> its object and its slot of the pose table. */+ private readonly driven = new Map<number, { object: number; slot: number }>();/** `backend`: a WebGLRenderer (the baseline) or any ThreeBackend (the WebGPU one of tools/compare). */constructor(backend: THREE.WebGLRenderer | ThreeBackend) {@@ -181,6 +187,7 @@ export class ThreeEngine implements Engine {if (uvs.length) g.setAttribute("uv", new THREE.BufferAttribute(uvs.slice(), 2));g.setIndex(new THREE.BufferAttribute(indices.slice(), 1));g.computeBoundingSphere();+ this.bodies?.geometry(id, positions, indices);const old = this.geometries.get(id);this.geometries.set(id, g);if (old) {@@ -307,10 +314,42 @@ export class ThreeEngine implements Engine {particlesSpawn(): void {}- physics(op: string): string {- // No physics in this baseline: driven objects stay where the scene put them.- this.notes.add(`physics ${op}`);- return "null";+ physics(op: string, args?: object): string {+ if (!this.bodies) {+ // Without the engine's physics (the measured baseline): driven objects stay where the scene put them.+ this.notes.add(`physics ${op}`);+ return "null";+ }+ const answer = this.bodies.physics(op, args ?? {});+ // Which object each body moves: `step` places it from the body's slot of the pose table.+ const a = (args ?? {}) as { id?: number; object?: number; slot?: number; body?: number };+ if (op === "body" && a.id !== undefined && a.object !== undefined && a.slot !== undefined) this.driven.set(a.id, { object: a.object, slot: a.slot });+ else if (op === "remove" && a.body !== undefined) this.driven.delete(a.body);+ return answer;+ }++ physicsPoses(): Float32Array {+ return this.bodies?.poses() ?? new Float32Array(0);+ }++ /** A frame of the physics world (the view calls it after the frame script, as the renderer steps its own): the+ * ticks that fit in `dt`, then the objects of the bodies placed where the bodies are. */+ step(dt: number): void {+ if (!this.bodies) return;+ this.bodies.advance(dt);+ const poses = this.bodies.poses();+ for (const [body, { object, slot }] of this.driven) {+ const n = this.nodes.get(object);+ if (!n || slot * 7 + 6 >= poses.length) {+ // (The object went, and its body with it.)+ if (!n) this.driven.delete(body);+ continue;+ }+ const k = slot * 7;+ n.holder.position.set(poses[k], poses[k + 1], poses[k + 2]);+ n.rest.set(poses[k + 3], poses[k + 4], poses[k + 5], poses[k + 6]);+ n.holder.quaternion.copy(n.rest);+ }}gridProgram(name: string): void {@@ -420,6 +459,7 @@ export class ThreeEngine implements Engine {n = { id, desc, holder, content: null, power: 1, anim: null, mixer: null, sway: null, rest: new THREE.Quaternion() };this.nodes.set(id, n);}+ this.bodies?.object(id, desc);n.desc = desc;n.power = 1;n.holder.visible = true;@@ -513,6 +553,7 @@ export class ThreeEngine implements Engine {}transform(id: number, trs: Float32Array): void {+ this.bodies?.transform(id, trs);const n = this.node(id);const h = n.holder;h.position.set(trs[0], trs[1], trs[2]);@@ -740,6 +781,7 @@ export class ThreeEngine implements Engine {}remove(id: number): void {+ this.bodies?.remove(id);const n = this.nodes.get(id);if (!n) return;n.holder.parent?.remove(n.holder);diff --git a/tools/three/host.ts b/tools/three/host.tsnew file mode 100644index 0000000..cb95bb9--- /dev/null+++ b/tools/three/host.ts@@ -0,0 +1,233 @@+/// <reference lib="dom" />+// The app's side of the host channel in a page (docs/RUNTIME.md "The host channel", "Input"): what a browser does+// with the messages a game posts and what it sends back. Nothing here knows who draws the scene: the three.js view+// uses it (view.ts), and any page that runs a game's node host can.+//+// - `PageInput`: the keyboard and the mouse as the frame's `input` message. With `look` a click on the canvas asks+// for the pointer lock; while it is held the mouse's motion is the game's look, and Esc lets go (the browser's own).+// - `PageNet`: `net.open` / `net.send` / `net.close` on `WebSocket`, `net.fetch` on `fetch`. What the sockets received+// since the last frame goes back as one `net.messages` batch a socket. Text messages only.+// - `launchMessage`: the page's query as the `launch` message (`?room=K7Q4MZ&name=Ada`).+import type { HostMessage, InputMessage } from "@threert/gameplay";++/** `input.look` is an angle: radians a CSS pixel of mouse motion at sensitivity 1 (the native window's figure). */+export const LOOK_RADIANS = 0.0025;++const KEYS: Record<string, string> = {+ Space: "Space", ShiftLeft: "Shift", ShiftRight: "Shift", ControlLeft: "Ctrl", ControlRight: "Ctrl", AltLeft: "Alt", AltRight: "Alt",+ MetaLeft: "Meta", MetaRight: "Meta", Tab: "Tab", Enter: "Enter", NumpadEnter: "Enter", Escape: "Escape", Backspace: "Backspace",+ ArrowLeft: "Left", ArrowRight: "Right", ArrowUp: "Up", ArrowDown: "Down",+};+const PLAIN = ["Minus", "Equal", "BracketLeft", "BracketRight", "Semicolon", "Quote", "Comma", "Period", "Slash", "Backslash", "Backquote"];++/** A key by its place on the keyboard (`KeyboardEvent.code`), as game code names it (packages/gameplay/src/input.ts). */+export function keyName(code: string): string | null {+ if (/^Key[A-Z]$/.test(code)) return code.slice(3);+ if (/^Digit\d$/.test(code)) return code.slice(5);+ if (/^F\d{1,2}$/.test(code) || PLAIN.includes(code)) return code;+ return KEYS[code] ?? null;+}++/** The keyboard and the mouse of a page between two frames, and the frame's `input` message. */+export class PageInput {+ /** Physical keys down, and how many of them hold each name ("Shift" is either shift key). */+ private readonly codes = new Map<string, string>();+ private readonly held = new Map<string, number>();+ private readonly buttons = new Set<number>();+ private pressed: string[] = [];+ private released: string[] = [];+ private look = { dx: 0, dy: 0 };+ private wheel = 0;+ private pointer = { u: 0.5, v: 0.5 };+ private readonly off: (() => void)[] = [];+ private readonly canvas: HTMLCanvasElement;+ readonly sensitivity: number;++ constructor(canvas: HTMLCanvasElement, look: boolean, sensitivity = 1) {+ this.canvas = canvas;+ this.sensitivity = sensitivity;+ const on = <K extends keyof DocumentEventMap>(target: EventTarget, type: K | "blur", f: (e: DocumentEventMap[K]) => void, options?: AddEventListenerOptions) => {+ target.addEventListener(type, f as EventListener, options);+ this.off.push(() => target.removeEventListener(type, f as EventListener, options));+ };+ on(window, "keydown", (e) => {+ const name = keyName(e.code);+ if (!name || e.metaKey) return;+ // (The keys are the game's: Space does not scroll, Tab does not leave the page. Esc stays the browser's.)+ if (name !== "Escape") e.preventDefault();+ this.key(e.code, name, true);+ });+ on(window, "keyup", (e) => {+ const name = keyName(e.code);+ if (name) this.key(e.code, name, false);+ });+ on(canvas, "mousedown", (e) => {+ if (look && !this.captured) {+ // The click that takes the pointer is the page's, not the game's.+ void canvas.requestPointerLock();+ return;+ }+ if (!this.buttons.has(e.button)) {+ this.buttons.add(e.button);+ this.pressed.push(`Mouse${e.button}`);+ }+ });+ on(window, "mouseup", (e) => {+ if (this.buttons.delete(e.button)) this.released.push(`Mouse${e.button}`);+ });+ on(window, "mousemove", (e) => {+ if (this.captured) {+ this.look.dx += e.movementX * LOOK_RADIANS * sensitivity;+ this.look.dy += e.movementY * LOOK_RADIANS * sensitivity;+ } else {+ const r = canvas.getBoundingClientRect();+ this.pointer = { u: Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)), v: Math.min(1, Math.max(0, (e.clientY - r.top) / r.height)) };+ }+ });+ on(canvas, "wheel", (e) => {+ e.preventDefault();+ this.wheel -= (e as WheelEvent).deltaY / 100;+ }, { passive: false });+ on(canvas, "contextmenu", (e) => e.preventDefault());+ // The page lost the keyboard (another tab, another window): what was held is let go.+ on(window, "blur", () => this.releaseAll());+ on(document, "pointerlockchange", () => {+ if (!this.captured) this.releaseAll();+ });+ }++ /** The canvas holds the pointer lock. */+ get captured(): boolean {+ return document.pointerLockElement === this.canvas;+ }++ private key(code: string, name: string, down: boolean): void {+ if (down) {+ if (this.codes.has(code)) return; // the browser's key repeat+ this.codes.set(code, name);+ const n = (this.held.get(name) ?? 0) + 1;+ this.held.set(name, n);+ if (n === 1) this.pressed.push(name);+ } else if (this.codes.delete(code)) {+ const n = (this.held.get(name) ?? 1) - 1;+ if (n > 0) this.held.set(name, n);+ else {+ this.held.delete(name);+ this.released.push(name);+ }+ }+ }++ private releaseAll(): void {+ this.released.push(...this.held.keys(), ...[...this.buttons].map((b) => `Mouse${b}`));+ this.codes.clear();+ this.held.clear();+ this.buttons.clear();+ }++ /** The frame's `input` message; what lasts a frame (edges, look, wheel) starts again. */+ message(): InputMessage {+ const captured = this.captured;+ const m: InputMessage = {+ t: "input", keys: [...this.held.keys()].sort(), pressed: this.pressed, released: this.released, buttons: [...this.buttons].sort(),+ u: captured ? 0.5 : this.pointer.u, v: captured ? 0.5 : this.pointer.v, dx: this.look.dx, dy: this.look.dy, wheel: this.wheel, captured,+ };+ [this.pressed, this.released, this.look, this.wheel] = [[], [], { dx: 0, dy: 0 }, 0];+ return m;+ }++ dispose(): void {+ for (const f of this.off) f();+ }+}++/** Sockets open at once in a page. */+const MAX_SOCKETS = 16;++/** The game's sockets and requests, on the browser's. */+export class PageNet {+ private readonly sockets = new Map<string, { ws: WebSocket; id: unknown; queue: string[] }>();+ private events: HostMessage[] = [];++ /** A message the game posted: the `net.*` ones are acted on, any other is not this one's. */+ post(m: HostMessage): void {+ const id = m.id, key = typeof id === "string" ? id : JSON.stringify(id);+ const s = this.sockets.get(key);+ switch (m.t) {+ case "net.open": {+ const refuse = (reason: string) => void this.events.push({ t: "net.closed", id, code: 1006, reason });+ if (s) return void console.warn(`net.open: a socket "${key}" is open already`);+ if (this.sockets.size >= MAX_SOCKETS) return refuse(`net.open: ${MAX_SOCKETS} sockets are open already`);+ let ws: WebSocket;+ try {+ ws = new WebSocket(String(m.url), Array.isArray(m.protocols) ? (m.protocols as string[]) : undefined);+ } catch (e) {+ return refuse(e instanceof Error ? e.message : String(e));+ }+ const entry = { ws, id, queue: [] as string[] };+ this.sockets.set(key, entry);+ ws.addEventListener("open", () => {+ this.events.push({ t: "net.opened", id });+ // (What the game sent before the socket was open.)+ for (const data of entry.queue.splice(0)) ws.send(data);+ });+ ws.addEventListener("message", (e) => {+ if (typeof e.data === "string") this.events.push({ t: "net.message", id, data: e.data });+ });+ ws.addEventListener("close", (e) => {+ if (this.sockets.get(key) === entry) this.sockets.delete(key);+ this.events.push({ t: "net.closed", id, code: e.code, reason: e.reason });+ });+ return;+ }+ case "net.send":+ if (!s || typeof m.data !== "string") return;+ if (s.ws.readyState === WebSocket.OPEN) s.ws.send(m.data);+ else if (s.ws.readyState === WebSocket.CONNECTING) s.queue.push(m.data);+ return;+ case "net.close":+ // (The codes a page may close with: 1000, or one of the application's.)+ s?.ws.close(typeof m.code === "number" && m.code >= 3000 && m.code < 5000 ? m.code : 1000, typeof m.reason === "string" ? m.reason.slice(0, 60) : "");+ return;+ case "net.fetch": {+ const failed = (e: unknown) => void this.events.push({ t: "net.fetched", id, status: 0, body: "", error: e instanceof Error ? e.message : String(e) });+ fetch(String(m.url), { method: typeof m.method === "string" ? m.method : "GET", headers: (m.headers as Record<string, string> | undefined) ?? undefined, body: typeof m.body === "string" ? m.body : undefined })+ .then(async (r) => void this.events.push({ t: "net.fetched", id, status: r.status, body: await r.text() }))+ .catch(failed);+ return;+ }+ }+ }++ /** The messages for the game since the last call: each socket's texts as one `net.messages` batch, in order. */+ poll(): HostMessage[] {+ const out: HostMessage[] = [];+ const batch = new Map<unknown, string[]>();+ for (const e of this.events.splice(0)) {+ if (e.t !== "net.message") {+ if (e.t === "net.closed") batch.delete(e.id);+ out.push(e);+ continue;+ }+ let list = batch.get(e.id);+ if (!list) {+ batch.set(e.id, (list = []));+ out.push({ t: "net.messages", id: e.id, list });+ }+ list.push(e.data as string);+ }+ return out;+ }++ /** The page goes: its sockets close. */+ dispose(): void {+ for (const s of this.sockets.values()) s.ws.close();+ }+}++/** The page's query as the `launch` message, without the parameters that are the page's own (`own`). */+export function launchMessage(query: URLSearchParams, own: readonly string[] = []): HostMessage {+ const params: Record<string, string> = {};+ for (const [k, v] of query) if (!own.includes(k)) params[k] = v;+ return { t: "launch", params };+}diff --git a/tools/three/hud.ts b/tools/three/hud.tsnew file mode 100644index 0000000..a1f5350--- /dev/null+++ b/tools/three/hud.ts@@ -0,0 +1,204 @@+/// <reference lib="dom" />+// The HUD of a game in a page: what `hud.set(...)` describes (packages/gameplay/src/hud.ts; docs/RUNTIME.md "HUD"),+// drawn as DOM over the canvas. The game posts `{ t: "hud", hud }` when its description changed and the page hands+// it to `HudOverlay.set`; nothing here runs per frame. An app with its own UI toolkit draws the same description+// its own way: this is the browser's.+//+// - Game text is set as text, never as markup.+// - A list line with a `ttl` is shown for that long from when it first came and then left out, whether or not the+// game still lists it; a flash is played when its `n` changes.+// - The overlay takes no pointer events: clicks and the pointer lock stay the canvas's.+import type { Hud, HudAnchor, HudFlash, HudItem, HudLine, HudTone } from "@threert/gameplay";++const TONES: Record<HudTone, string> = { default: "#f2f2ee", good: "#6fdc8c", warn: "#f5c542", bad: "#ff6b5e", accent: "#62b6ff", dim: "rgba(242,242,238,.62)" };+const ANCHORS: HudAnchor[] = ["top-left", "top", "top-right", "left", "center", "right", "bottom-left", "bottom", "bottom-right"];++const CSS = `+.hud { position: fixed; inset: 0; pointer-events: none; user-select: none; overflow: hidden; color: ${TONES.default};+ font: 13px/1.35 ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-variant-numeric: tabular-nums;+ text-shadow: 0 1px 2px rgba(0,0,0,.65); }+.hud-anchor { position: absolute; display: flex; flex-direction: column; gap: 10px; padding: 22px 26px; max-width: 46vw; }+.hud-anchor[data-at^="top"] { top: 0; } .hud-anchor[data-at^="bottom"] { bottom: 0; }+.hud-anchor[data-at$="left"] { left: 0; align-items: flex-start; } .hud-anchor[data-at$="right"] { right: 0; align-items: flex-end; text-align: right; }+.hud-anchor[data-at="top"], .hud-anchor[data-at="bottom"], .hud-anchor[data-at="center"] { left: 50%; transform: translateX(-50%); align-items: center; text-align: center; }+.hud-anchor[data-at="left"], .hud-anchor[data-at="right"] { top: 50%; transform: translateY(-50%); }+.hud-anchor[data-at="center"] { top: 50%; transform: translate(-50%, -50%); }+.hud-label { font-size: 10px; letter-spacing: .1em; text-transform: uppercase; opacity: .72; }+.hud-text { font-size: 16px; font-weight: 600; white-space: pre-wrap; }+.hud-text[data-size="small"] { font-size: 12px; font-weight: 500; } .hud-text[data-size="large"] { font-size: 30px; line-height: 1.1; }+.hud-bar { display: flex; align-items: center; gap: 10px; }+.hud-track { width: 190px; height: 6px; border-radius: 3px; background: rgba(255,255,255,.2); box-shadow: 0 0 0 1px rgba(0,0,0,.35); overflow: hidden; }+.hud-fill { height: 100%; border-radius: 3px; background: currentColor; transition: width .15s ease-out; }+.hud-list { display: flex; flex-direction: column; gap: 4px; align-items: inherit; }+.hud-line { padding: 2px 9px; border-radius: 3px; background: rgba(8,10,14,.45); font-size: 12px; transition: opacity .4s; }+.hud-line.out { opacity: 0; }+.hud-table { padding: 14px 18px 12px; border-radius: 8px; background: rgba(8,10,14,.74); box-shadow: 0 0 0 1px rgba(255,255,255,.08), 0 12px 40px rgba(0,0,0,.45);+ -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); text-shadow: none; text-align: left; }+.hud-table h3 { margin: 0 0 8px; font-size: 12px; font-weight: 600; letter-spacing: .1em; text-transform: uppercase; }+.hud-table table { border-collapse: collapse; } .hud-table th { font-size: 10px; font-weight: 500; letter-spacing: .1em; text-transform: uppercase; opacity: .6; text-align: left; }+.hud-table th, .hud-table td { padding: 3px 22px 3px 8px; } .hud-table .n { text-align: right; padding-right: 8px; }+.hud-table tr.own td { background: rgba(98,182,255,.16); color: ${TONES.accent}; }+.hud-message { position: absolute; left: 50%; top: 27%; transform: translateX(-50%); text-align: center; white-space: nowrap; }+.hud-message b { display: block; font-size: 36px; line-height: 1.15; font-weight: 700; letter-spacing: .02em; }+.hud-message span { display: block; margin-top: 6px; font-size: 14px; opacity: .88; }+.hud-centre { position: absolute; left: 50%; top: 50%; width: 0; height: 0; }+.hud-centre i { position: absolute; background: currentColor; box-shadow: 0 0 0 1px rgba(0,0,0,.55); }+.hud-centre .ring { background: none; border: 2px solid currentColor; border-radius: 50%; }+.hud-vignette { position: absolute; inset: 0; box-shadow: inset 0 0 140px 30px rgba(215,40,30,.6); opacity: 0; }+`;++function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls: string, text?: string): HTMLElementTagNameMap[K] {+ const e = document.createElement(tag);+ if (cls) e.className = cls;+ if (text !== undefined) e.textContent = text;+ return e;+}++const tone = (e: HTMLElement, t?: HudTone) => {+ if (t && t !== "default") e.style.color = TONES[t] ?? TONES.default;+ return e;+};++/** Four marks around the centre at `radius` px, each `length` x 2 px, turned by `turn` degrees (0: a cross, 45: an x). */+function marks(parent: HTMLElement, radius: number, length: number, turn: number): void {+ for (let k = 0; k < 4; k++) {+ const m = el("i", "");+ m.style.cssText = `width:${length}px;height:2px;left:${radius}px;top:-1px;transform-origin:${-radius}px 1px;transform:rotate(${turn + 90 * k}deg)`;+ parent.appendChild(m);+ }+}++export class HudOverlay {+ readonly root: HTMLDivElement;+ private readonly anchors = new Map<HudAnchor, HTMLDivElement>();+ private readonly message: HTMLDivElement;+ private readonly crosshair: HTMLDivElement;+ private readonly marker: HTMLDivElement;+ private readonly vignette: HTMLDivElement;+ /** When each line with a `ttl` goes (ms, the page's clock), by its id or text. */+ private readonly expiry = new Map<string, number>();+ private timers: number[] = [];+ private flashed = 0;++ constructor(parent: HTMLElement = document.body) {+ if (!document.getElementById("hud-style")) {+ const style = el("style", "", CSS);+ style.id = "hud-style";+ document.head.appendChild(style);+ }+ this.root = el("div", "hud");+ this.vignette = this.root.appendChild(el("div", "hud-vignette"));+ for (const at of ANCHORS) {+ const a = this.root.appendChild(el("div", "hud-anchor"));+ a.dataset.at = at;+ this.anchors.set(at, a);+ }+ this.message = this.root.appendChild(el("div", "hud-message"));+ this.crosshair = this.root.appendChild(el("div", "hud-centre"));+ this.marker = this.root.appendChild(el("div", "hud-centre"));+ parent.appendChild(this.root);+ }++ /** Shows `hud` as the whole HUD: what is not in it is not shown. */+ set(hud: Hud): void {+ for (const t of this.timers) clearTimeout(t);+ this.timers = [];+ for (const a of this.anchors.values()) a.replaceChildren();+ for (const item of hud.items ?? []) {+ const e = this.item(item);+ if (e) this.anchors.get(item.anchor)?.appendChild(e);+ }+ this.message.replaceChildren();+ if (hud.message) {+ tone(this.message, hud.message.tone).appendChild(el("b", "", hud.message.title));+ if (hud.message.subtitle) this.message.appendChild(el("span", "", hud.message.subtitle));+ } else this.message.style.color = "";+ this.crosshair.replaceChildren();+ this.crosshair.style.color = TONES[hud.crosshair?.tone ?? "default"];+ if (hud.crosshair) {+ const gap = Math.max(0, Math.min(1, hud.crosshair.gap ?? 0));+ if (hud.crosshair.style === "cross") marks(this.crosshair, 5 + 22 * gap, 9, 0);+ else {+ const d = hud.crosshair.style === "dot" ? 4 : 14 + 48 * gap;+ const dot = this.crosshair.appendChild(el("i", hud.crosshair.style === "dot" ? "" : "ring"));+ dot.style.cssText = `width:${d}px;height:${d}px;left:${-d / 2}px;top:${-d / 2}px;border-radius:50%;box-sizing:border-box`;+ }+ }+ if (hud.flash && hud.flash.n !== this.flashed) {+ this.flashed = hud.flash.n;+ this.flash(hud.flash);+ }+ }++ private item(item: HudItem): HTMLElement | null {+ switch (item.type) {+ case "text": {+ const box = tone(el("div", ""), item.tone);+ if (item.label) box.appendChild(el("div", "hud-label", item.label));+ box.appendChild(el("div", "hud-text", item.text)).dataset.size = item.size ?? "normal";+ return box;+ }+ case "bar": {+ const box = tone(el("div", ""), item.tone);+ if (item.label) box.appendChild(el("div", "hud-label", item.label));+ const row = box.appendChild(el("div", "hud-bar"));+ row.appendChild(el("div", "hud-track")).appendChild(el("div", "hud-fill")).style.width = `${Math.max(0, Math.min(1, Number(item.value) || 0)) * 100}%`;+ if (item.text) row.appendChild(el("div", "hud-text", item.text)).dataset.size = "small";+ return box;+ }+ case "list": {+ const box = el("div", "hud-list");+ const now = performance.now();+ const seen = new Set<string>();+ for (const l of item.lines) {+ const line: HudLine = typeof l === "string" ? { text: l } : l;+ const row = tone(el("div", "hud-line", line.text), line.tone);+ if (line.ttl !== undefined) {+ const key = line.id ?? line.text;+ seen.add(key);+ if (!this.expiry.has(key)) this.expiry.set(key, now + line.ttl * 1000);+ const left = this.expiry.get(key)! - now;+ if (left <= 0) continue;+ // (Faded over its last 0.4 s.)+ this.timers.push(window.setTimeout(() => row.classList.add("out"), Math.max(0, left - 400)));+ }+ box.appendChild(row);+ }+ // (A line the game no longer lists is forgotten: the same text later is a new line.)+ if (item.lines.length) for (const key of [...this.expiry.keys()]) if (!seen.has(key) && this.expiry.get(key)! < now) this.expiry.delete(key);+ return box;+ }+ case "table": {+ const box = el("div", "hud-table");+ if (item.title) box.appendChild(el("h3", "", item.title));+ const table = box.appendChild(el("table", ""));+ const head = table.appendChild(el("tr", ""));+ const numeric = item.columns.map((_, c) => item.rows.length > 0 && item.rows.every((r) => typeof r[c] === "number"));+ item.columns.forEach((c, k) => head.appendChild(el("th", numeric[k] ? "n" : "", c)));+ item.rows.forEach((r, k) => {+ const row = table.appendChild(el("tr", k === item.highlight ? "own" : ""));+ item.columns.forEach((_, c) => row.appendChild(el("td", numeric[c] ? "n" : "", r[c] === undefined ? "" : String(r[c]))));+ });+ return box;+ }+ default:+ return null;+ }+ }++ /** A hit marker at the crosshair, or the red of a hit taken with a mark where it came from. */+ private flash(f: HudFlash): void {+ this.marker.replaceChildren();+ if (f.kind === "damage") {+ this.vignette.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 600, easing: "ease-out" });+ if (f.angle === undefined) return;+ // A bar on a circle around the centre, at the angle the hit came from (0: ahead, clockwise).+ const m = this.marker.appendChild(el("i", ""));+ m.style.cssText = `width:74px;height:5px;left:-37px;top:-112px;border-radius:3px;color:${TONES.bad};transform-origin:37px 112px;transform:rotate(${(f.angle * 180) / Math.PI}deg)`;+ } else {+ this.marker.style.color = f.kind === "kill" ? TONES.bad : TONES.default;+ marks(this.marker, 7, 9, 45);+ }+ this.marker.animate([{ opacity: 1 }, { opacity: 1, offset: 0.5 }, { opacity: 0 }], { duration: f.kind === "hit" ? 220 : 700, fill: "forwards" });+ }+}diff --git a/tools/three/open.ts b/tools/three/open.tsindex 15e5b05..dcde0b3 100644--- a/tools/three/open.ts+++ b/tools/three/open.ts@@ -1,22 +1,37 @@// Opens a scene / game module in three.js in an ordinary browser: bundles it with the interactive view// (tools/three/view.ts), serves the repo root (assets/ included) on localhost and opens the page.//-// node tools/three/open.ts scenes/bistro.ts [--port 8123] [--no-open]+// node tools/three/open.ts scenes/bistro.ts [--port 8123] [--no-open] [--physics | --no-physics]+// node tools/three/open.ts games/fps/arena.game.ts --launch 'room=K7Q4MZ&name=Ada'//-// The page stays up until Ctrl-C. URL parameters of the view: ev100, autoLights, width / height.+// A game is played in the page (view.ts): its frame script, its keys and clicks, its host channel. One whose source+// names the physics (`physics`, `Shapecaster`, `intersectPhysics`; `--physics` / `--no-physics` decide otherwise) gets+// the engine's own, built here as a wasm32 module (tools/three/physics-build.ts: cargo and the wasm32 target).+// `--launch` is the game's part of the page's query (the host channel's `launch` message).+//+// The page stays up until Ctrl-C. URL parameters of the view: ev100, autoLights, width / height, and those view.ts+// lists.import { spawn } from "node:child_process";+import { readFileSync } from "node:fs";import { basename, join, resolve } from "node:path";import { bundlePage, root, serve } from "./browser.ts";+import { buildScenePhysics, SCENE_PHYSICS } from "./physics-build.ts";const args = process.argv.slice(2);-const src = args.find((a, i) => !a.startsWith("--") && args[i - 1] !== "--port");+const src = args.find((a, i) => !a.startsWith("--") && args[i - 1] !== "--port" && args[i - 1] !== "--launch");if (!src) {- console.error("usage: node tools/three/open.ts <scene or game .ts> [--port N] [--no-open]");+ console.error("usage: node tools/three/open.ts <scene or game .ts> [--port N] [--no-open] [--physics | --no-physics] [--launch 'room=..&name=..']");process.exit(2);}const id = `${basename(src).replace(/\.(game\.)?ts$/, "")}-view`;const { html, bytes } = await bundlePage(id, resolve(src), join(root, "tools/three/view.ts"));const { origin } = await serve(root, Number(args.includes("--port") ? args[args.indexOf("--port") + 1] : 0));-const url = `${origin}${html}`;+const query = new URLSearchParams(args.includes("--launch") ? args[args.indexOf("--launch") + 1] : "");+const physics = args.includes("--physics") || (!args.includes("--no-physics") && /\bphysics\b|Shapecaster|intersectPhysics/.test(readFileSync(resolve(src), "utf8")));+if (physics) {+ buildScenePhysics();+ query.set("physics", `/${SCENE_PHYSICS}`);+}+const url = `${origin}${html}${query.size ? `?${query}` : ""}`;console.log(`${src}: ${(bytes / 1024).toFixed(0)} KiB page\n${url}\n(Ctrl-C to stop)`);if (!args.includes("--no-open")) spawn(process.platform === "darwin" ? "open" : "xdg-open", [url], { stdio: "ignore", detached: true }).unref();diff --git a/tools/three/physics-build.ts b/tools/three/physics-build.tsnew file mode 100644index 0000000..d541267--- /dev/null+++ b/tools/three/physics-build.ts@@ -0,0 +1,16 @@+// Builds the engine's world and physics as a wasm32 module for the three.js view (tools/three/physics.ts;+// renderer/examples/physics_scene.rs). Needs cargo and the wasm32 target (rustup target add wasm32-unknown-unknown);+// no other tool. The first build takes about a minute, the next ones nothing.+import { execFileSync } from "node:child_process";+import { join } from "node:path";++const renderer = join(import.meta.dirname, "../../renderer");++/** The module's path, from the repository's root. */+export const SCENE_PHYSICS = "renderer/target/wasm32-unknown-unknown/release/examples/physics_scene.wasm";++/** Builds the module (cargo decides whether there is anything to do). Returns its path. */+export function buildScenePhysics(): string {+ execFileSync("cargo", ["build", "--release", "--locked", "--quiet", "--target", "wasm32-unknown-unknown", "--example", "physics_scene"], { cwd: renderer, stdio: ["ignore", "ignore", "inherit"] });+ return join(renderer, "..", SCENE_PHYSICS);+}diff --git a/tools/three/physics.ts b/tools/three/physics.tsnew file mode 100644index 0000000..2cb1337--- /dev/null+++ b/tools/three/physics.ts@@ -0,0 +1,77 @@+// The engine's physics in the three.js view. three.js draws the scene; `mesh.physics`, `Raycaster.intersectPhysics`+// and `Shapecaster` are the engine's (Rapier, in Rust). Writing them a second time in JavaScript would give a game two+// physics that disagree, so the view loads the engine's own: its world and physics as a wasm32 module+// (renderer/examples/physics_scene.rs: the code the renderer's `__engine` runs, without the renderer), built by+// `buildScenePhysics` (tools/three/physics-build.ts). ThreeEngine sends it the objects and geometries it is sent,+// asks it the physics calls, steps it once a frame and places the objects of the bodies that moved.+//+// This file is the module's boundary (pointers and lengths into its memory), for a page and for Node alike.++/** The module's exports (renderer/examples/physics_scene.rs). */+interface Exports {+ memory: WebAssembly.Memory;+ scene_alloc(len: number): number;+ scene_free(ptr: number, len: number): void;+ scene_answer(): number;+ scene_answer_len(): number;+ scene_geometry(id: number, positions: number, np: number, indices: number, ni: number): number;+ scene_object(id: number, desc: number, len: number): number;+ scene_transform(id: number, trs: number, len: number): number;+ scene_remove(id: number): void;+ scene_physics(op: number, opLen: number, args: number, argsLen: number): number;+ scene_advance(dt: number): number;+ scene_poses(): number;+ scene_poses_len(): number;+}++/** The engine's world and physics behind a scene somebody else draws. */+export interface ScenePhysics {+ geometry(id: number, positions: Float32Array, indices: Uint32Array): void;+ object(id: number, desc: object): void;+ transform(id: number, trs: Float32Array): void;+ remove(id: number): void;+ /** `__engine.physics(op, args)`: its answer, JSON. Throws what the engine refuses. */+ physics(op: string, args: object): string;+ /** A frame of `dt` seconds: the ticks of 1 / 60 s that fit. Returns how many were made. */+ advance(dt: number): number;+ /** `__engine.physicsPoses()`: seven numbers a slot. */+ poses(): Float32Array;+}++/** Instantiates the module (its bytes) and wraps its exports. */+export async function loadScenePhysics(bytes: BufferSource): Promise<ScenePhysics> {+ const module = await WebAssembly.compile(bytes);+ // (The renderer's library names a few imports of the browser's glue it does not call here: each a function that+ // returns 0, as tools/physics-determinism.ts gives the same graph.)+ const imports: Record<string, Record<string, () => number>> = {};+ for (const i of WebAssembly.Module.imports(module)) (imports[i.module] ??= {})[i.name] = () => 0;+ const x = (await WebAssembly.instantiate(module, imports)).exports as unknown as Exports;+ const encoder = new TextEncoder(), decoder = new TextDecoder();+ /** Runs `f` with `data` copied into the module's memory. */+ const lend = <T>(data: Uint8Array | Float32Array | Uint32Array, f: (ptr: number, len: number) => T): T => {+ const bytes = data.byteLength;+ const ptr = x.scene_alloc(bytes);+ new Uint8Array(x.memory.buffer, ptr, bytes).set(new Uint8Array(data.buffer, data.byteOffset, bytes));+ try {+ return f(ptr, data.length);+ } finally {+ x.scene_free(ptr, bytes);+ }+ };+ const answer = () => decoder.decode(new Uint8Array(x.memory.buffer, x.scene_answer(), x.scene_answer_len()));+ const check = (status: number) => {+ if (status !== 0) throw new Error(answer());+ };+ return {+ geometry: (id, positions, indices) => check(lend(positions, (p, np) => lend(indices, (i, ni) => x.scene_geometry(id, p, np, i, ni)))),+ object: (id, desc) => check(lend(encoder.encode(JSON.stringify(desc)), (p, n) => x.scene_object(id, p, n))),+ transform: (id, trs) => check(lend(trs, (p, n) => x.scene_transform(id, p, n))),+ remove: (id) => x.scene_remove(id),+ physics(op, args) {+ check(lend(encoder.encode(op), (o, on) => lend(encoder.encode(JSON.stringify(args ?? null)), (a, an) => x.scene_physics(o, on, a, an))));+ return answer();+ },+ advance: (dt) => x.scene_advance(dt),+ poses: () => new Float32Array(x.memory.buffer, x.scene_poses(), x.scene_poses_len()).slice(),+ };+}diff --git a/tools/three/test/physics.test.ts b/tools/three/test/physics.test.tsnew file mode 100644index 0000000..f002121--- /dev/null+++ b/tools/three/test/physics.test.ts@@ -0,0 +1,96 @@+// The engine's physics behind the three.js view (tools/three/physics.ts; renderer/examples/physics_scene.rs): the+// first-person arena (games/fps/arena.game.ts) on ThreeEngine with the module loaded, driven by input messages as+// tools/fps-arena.ts drives it in the renderer. The numbers are the renderer's: one physics, whoever draws.+// Skipped where the module is not built (it needs cargo and the wasm32 target: `node tools/three/open.ts` on a game+// with physics builds it, or tools/three/physics-build.ts `buildScenePhysics`).+import assert from "node:assert/strict";+import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { test } from "node:test";+import * as THREE from "three";+import { installNodeHost, type GameDefinition } from "@threert/gameplay";+import arena, { HALF_HEIGHT, RADIUS, SKIN, START, TARGETS, WALK } from "../../../games/fps/arena.game.ts";+import { ThreeEngine, type ThreeBackend } from "../engine.ts";+import { loadScenePhysics } from "../physics.ts";+import { SCENE_PHYSICS } from "../physics-build.ts";++const backend: ThreeBackend = {+ pmrem: { fromScene: () => ({ texture: new THREE.Texture() }), fromEquirectangular: () => ({ texture: new THREE.Texture() }) },+ makeSky: () => new THREE.Mesh(),+ maxAnisotropy: 1,+};+const wasm = join(import.meta.dirname, "../../..", SCENE_PHYSICS);++test("the arena on three.js with the engine's physics: the walk, the wall, the tag, as in the renderer", { skip: existsSync(wasm) ? false : `${SCENE_PHYSICS} is not built` }, async () => {+ const engine = new ThreeEngine(backend);+ engine.bodies = await loadScenePhysics(readFileSync(wasm));+ const lines: string[] = [];+ const log = console.log;+ console.log = (...a: unknown[]) => void lines.push(a.map(String).join(" "));+ try {+ const node = installNodeHost(arena as GameDefinition<unknown>, engine);+ node.setup("local");+ let now = 1_000_000;+ const DT = 1 / 60;+ const step = (frames: number, dt = DT) => {+ for (let k = 0; k < frames; k++) {+ node.frame(dt, (now += 1000 * dt));+ engine.step(dt);+ }+ };+ const input = (m: object) => node.hostMessages(JSON.stringify([{ t: "input", captured: true, ...m }]), now);+ const report = () => {+ node.event("report", "{}", now);+ return JSON.parse(/arena (\{"at".*\})/.exec(lines.at(-1)!)![1]) as { at: [number, number, number]; yaw: number; pitch: number; grounded: boolean; tagged: number; shots: number };+ };+ const REST = HALF_HEIGHT + RADIUS + SKIN;+ step(30);+ let r = report();+ assert.ok(r.grounded && Math.abs(r.at[1] - REST) < 2e-3, `at rest a skin above the ground: y ${r.at[1]}`);+ // The targets are bodies of the engine's world: the one on the ground rests on it, its three.js object with it.+ const ball = engine.scene.getObjectByName("target 2")!;+ assert.ok(Math.abs(ball.position.y - 0.4) < 5e-3, `target 2 rests on the ground: y ${ball.position.y}`);+ // W for a second.+ input({ keys: ["W"] });+ step(60);+ input({ keys: [] });+ step(2);+ r = report();+ assert.ok(Math.abs(START[2] - r.at[2] - WALK) < 0.02, `${START[2] - r.at[2]} m forward in a second`);+ // Sprinting at the platform's face (z = -8.8) with frames of 0.1 s: stopped a skin off it.+ input({ keys: ["W", "Shift"] });+ step(40, 0.1);+ input({ keys: [] });+ step(2);+ r = report();+ assert.ok(r.at[2] >= -8.8 + RADIUS && r.at[2] + 8.8 - RADIUS < 2 * SKIN + 1e-3, `stopped at z ${r.at[2]}`);+ // The view turned onto the target on the low wall, and a press of the mouse button.+ node.event("restart", "{}", now);+ step(5);+ r = report();+ const d = [TARGETS[4][0] - r.at[0], TARGETS[4][1] - (r.at[1] + 0.7), TARGETS[4][2] - r.at[2]];+ input({ dx: r.yaw - Math.atan2(-d[0], -d[2]), dy: r.pitch - Math.asin(d[1] / Math.hypot(...d)) });+ step(1);+ input({ buttons: [0], pressed: ["Mouse0"] });+ step(1);+ input({ buttons: [] });+ step(30);+ r = report();+ assert.deepEqual([r.tagged, r.shots], [1, 1]);+ assert.ok(lines.some((l) => l.includes('arena {"tagged":"target 5"')));+ // The tagged target was knocked off the wall: its three.js object moved with its body.+ const tagged = engine.scene.getObjectByName("target 5")!;+ assert.ok(Math.hypot(tagged.position.x - TARGETS[4][0], tagged.position.y - TARGETS[4][1], tagged.position.z - TARGETS[4][2]) > 0.2, `target 5 moved: ${tagged.position.toArray()}`);+ assert.deepEqual([...engine.notes].filter((n) => n.startsWith("physics")), [], "no physics call left out");+ } finally {+ console.log = log;+ }+});++test("without the module the view is the baseline it was: physics calls are noted, nothing moves", () => {+ const engine = new ThreeEngine(backend);+ assert.equal(engine.physics("ray", {}), "null");+ assert.deepEqual([...engine.notes], ["physics ray"]);+ assert.equal(engine.physicsPoses().length, 0);+ engine.step(1 / 60);+});diff --git a/tools/three/view.ts b/tools/three/view.tsindex 421fbdf..d7f5637 100644--- a/tools/three/view.ts+++ b/tools/three/view.ts@@ -7,18 +7,36 @@// notes).//// Mouse: drag to orbit, right-drag to pan, wheel to dolly; R: back to the scene's camera; H: hide the overlay.+//+// A game is played, not only looked at: its frame script runs every frame, its `keys` run their handlers, a click is+// its `click` event (the object under it, the view ray), and the page is the app of its host channel+// (docs/RUNTIME.md "The host channel"; tools/three/host.ts, hud.ts): `net.*` on the browser's WebSocket and fetch,+// `launch` from the page's query (`?room=K7Q4MZ&name=Ada`), the HUD drawn as DOM over the canvas. A game that reads+// input (`pointer` in its definition) has the keys, the pointer and the camera to itself: no orbit controls, and+// with `pointer: "look"` a click takes the pointer lock (Esc lets go). With `physics=<the module's path>` the page+// loads the engine's own physics (tools/three/physics.ts; tools/three/open.ts builds it and adds the parameter), so+// bodies move and the physics queries answer as in the renderer.+//// URL parameters: ev100 (auto-exposure cameras), autoLights (the adapter's cap; 0 = none), width / height (a fixed// canvas instead of the window), check (after 120 frames publish `window.__result`: the overlay text and the frame as a-// PNG data URL, for an automated look; tools/three/browser.ts `run`).+// PNG data URL, for an automated look; tools/three/browser.ts `run`), play=0 (a game shown as its setup left it, as+// before games were played here), stats=1 (the overlay of figures, for a game that reads input), sensitivity (of the+// look), physics. Every other parameter is the game's (`launch`).import * as THREE from "three";import { OrbitControls } from "three/addons/controls/OrbitControls.js";import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js";import { OutputPass } from "three/addons/postprocessing/OutputPass.js";import { RenderPass } from "three/addons/postprocessing/RenderPass.js";import { ShaderPass } from "three/addons/postprocessing/ShaderPass.js";-import { defineGame, installNodeHost, type GameDefinition } from "@threert/gameplay";+import { defineGame, installNodeHost, type GameDefinition, type HostMessage, type Hud } from "@threert/gameplay";import { ThreeEngine } from "./engine.ts";+import { launchMessage, PageInput, PageNet } from "./host.ts";+import { HudOverlay } from "./hud.ts";import { VignetteShader } from "./page.ts";+import { loadScenePhysics } from "./physics.ts";++/** The page's own URL parameters: the rest are the game's (`launch`). */+const OWN = ["ev100", "autoLights", "width", "height", "check", "play", "stats", "sensitivity", "physics"];type SceneModule = (() => unknown) | GameDefinition<unknown>;@@ -43,10 +61,34 @@ export async function run(mod: SceneModule): Promise<void> {const engine = new ThreeEngine(renderer);const game = (typeof mod === "function" ? defineGame({ state: {}, setup: () => mod() as never, handlers: {} }) : mod) as GameDefinition<unknown>;+ // The page is the app of the game's host channel: what the game posts waits here until `flush`.+ const posts: HostMessage[] = [];+ (globalThis as { __host_post?: (text: string) => void }).__host_post = (text) => void posts.push(JSON.parse(text) as HostMessage);+ const net = new PageNet();+ let hud: HudOverlay | null = null;+ const flush = () => {+ for (const m of posts.splice(0)) {+ if (m.t === "hud") (hud ??= new HudOverlay()).set((m.hud ?? {}) as Hud);+ else net.post(m);+ }+ };+ // The engine's physics, when the page was opened with it.+ if (q.get("physics")) engine.bodies = await loadScenePhysics(await (await fetch(q.get("physics")!)).arrayBuffer());let t = performance.now();- installNodeHost(game, engine).setup("local");+ const node = installNodeHost(game, engine);+ const about = JSON.parse(node.describe()) as { handlers: string[]; on: string[]; frame: boolean; keys: Record<string, string>; pointer: "look" | "free" | null };+ node.setup("local");await engine.ready();const loadMs = performance.now() - t;+ // A game is played (its frame script, its events, its channel); a scene module, or `play=0`, is looked at.+ const play = typeof mod !== "function" && q.get("play") !== "0";+ // A game that reads input has the keys, the pointer and the camera to itself.+ const input = play && about.pointer ? new PageInput(canvas, about.pointer === "look", Number(q.get("sensitivity") ?? 1) || 1) : null;+ if (input && q.get("stats") !== "1") overlay.style.display = "none";+ if (play) {+ node.hostMessages(JSON.stringify([launchMessage(q, OWN)]), Date.now());+ flush();+ }const fixed = q.get("width") !== null;const size = () => (fixed ? { w: Number(q.get("width")), h: Number(q.get("height") ?? 720) } : { w: innerWidth, h: innerHeight });@@ -58,10 +100,13 @@ export async function run(mod: SceneModule): Promise<void> {const autoLights = q.get("autoLights") !== null ? Number(q.get("autoLights")) : undefined;engine.prepare({ width: w, height: h, autoLights });- // A free camera starting at the scene's camera; orbit about a point 10 m ahead.+ // A free camera starting at the scene's camera; orbit about a point 10 m ahead. (A game that reads input is seen+ // through its own camera instead: `view` below.)const sceneCam = engine.activeCamera;const cam = new THREE.PerspectiveCamera(sceneCam.fov, w / h, sceneCam.near, sceneCam.far);const controls = new OrbitControls(cam, canvas);+ controls.enabled = !input;+ const view = () => (input ? engine.activeCamera : cam);const reset = () => {sceneCam.updateWorldMatrix(true, false);cam.position.setFromMatrixPosition(sceneCam.matrixWorld);@@ -78,7 +123,8 @@ export async function run(mod: SceneModule): Promise<void> {const composer = new EffectComposer(renderer, target);composer.setPixelRatio(1);composer.setSize(w, h);- composer.addPass(new RenderPass(engine.scene, cam));+ const scenePass = new RenderPass(engine.scene, view());+ composer.addPass(scenePass);const vignettePass = new ShaderPass(VignetteShader);vignettePass.uniforms.intensity.value = vignette;vignettePass.uniforms.aspect.value = h / w;@@ -86,7 +132,7 @@ export async function run(mod: SceneModule): Promise<void> {composer.addPass(vignettePass);composer.addPass(new OutputPass());t = performance.now();- await renderer.compileAsync(engine.scene, cam);+ await renderer.compileAsync(engine.scene, view());const compileMs = performance.now() - t;addEventListener("resize", () => {@@ -98,10 +144,41 @@ export async function run(mod: SceneModule): Promise<void> {cam.updateProjectionMatrix();vignettePass.uniforms.aspect.value = h / w;});+ /** An event of the game on this page (local play: the page is the authority), then what it posted. */+ const event = (type: string, payload: object) => {+ try {+ node.event(type, JSON.stringify(payload), Date.now());+ } catch (e) {+ console.error(`${type}: ${e instanceof Error ? e.message : String(e)}`);+ }+ flush();+ };addEventListener("keydown", (e) => {+ // The game's `keys` first, named as the native window names them ("R", "Space", "Escape").+ const name = e.key === " " ? "Space" : e.key.length === 1 ? e.key.toUpperCase() : e.key;+ if (play && !e.repeat && about.keys[name]) return event(about.keys[name], {});+ if (input) return; // the other keys are the game's inputif (e.key === "r" || e.key === "R") reset();if (e.key === "h" || e.key === "H") overlay.style.display = overlay.style.display === "none" ? "" : "none";});+ // A click (not a drag) is the game's `click` event: the object under it and the view ray, as the renderer sends+ // them. Not while the pointer is the game's look: there is no place it points at.+ if (play && about.pointer !== "look" && (about.handlers.includes("click") || about.on.includes("click"))) {+ let down: { x: number; y: number } | null = null;+ canvas.addEventListener("pointerdown", (e) => void (down = e.button === 0 ? { x: e.clientX, y: e.clientY } : null));+ canvas.addEventListener("pointerup", (e) => {+ if (!down || Math.hypot(e.clientX - down.x, e.clientY - down.y) > 4) return;+ const r = canvas.getBoundingClientRect();+ const ray = new THREE.Raycaster();+ ray.setFromCamera(new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, 1 - ((e.clientY - r.top) / r.height) * 2), view());+ const hit = ray.intersectObjects(engine.scene.children, true).find((i) => (i.object as THREE.Mesh).isMesh && !i.object.name.startsWith("auto-light-"));+ if (!hit) return;+ // (The object's holder carries the name the scene gave it.)+ let named: THREE.Object3D | null = hit.object;+ while (named && !named.name) named = named.parent;+ event("click", { target: named?.name ?? "", point: hit.point.toArray(), player: "you", ray: { origin: ray.ray.origin.toArray(), direction: ray.ray.direction.toArray() } });+ });+ }// GPU time from timer queries (ANGLE / Metal reads high; the frame interval is the figure that counts).const ext = gl.getExtension("EXT_disjoint_timer_query_webgl2") as { TIME_ELAPSED_EXT: number; GPU_DISJOINT_EXT: number } | null;@@ -118,13 +195,37 @@ export async function run(mod: SceneModule): Promise<void> {const droppedText = Object.entries(engine.dropped).map(([k, v]) => ` ${v} × ${k}`);const notesText = [...engine.notes].map((n) => ` ${n}`);let frames = 0;+ let failed = "";const check = q.get("check") !== null;const frame = () => {frames++;const now = performance.now();intervals.push(now - last);if (intervals.length > 60) intervals.shift();+ const dt = Math.min((now - last) / 1000, 0.1);last = now;+ if (play) {+ // As the renderer's frame: the app's messages (this frame's input, what the sockets received), the frame+ // script, the physics' ticks, then what the game posted.+ try {+ const messages = [...(input ? [input.message()] : []), ...net.poll()];+ if (messages.length) node.hostMessages(JSON.stringify(messages), Date.now());+ node.frame(dt, Date.now());+ } catch (e) {+ // (A frame script that throws does not stop the world; its error is shown once.)+ const text = e instanceof Error ? e.message : String(e);+ if (text !== failed) console.error(`frame script: ${(failed = text)}`);+ }+ engine.step(dt);+ flush();+ // The game's camera, whichever it is now, at the canvas's shape.+ const c = view();+ if (c !== scenePass.camera || (input && c.aspect !== w / h)) {+ scenePass.camera = c;+ c.aspect = w / h;+ c.updateProjectionMatrix();+ }+ }controls.update();let qy: WebGLQuery | null = null;if (ext && pending.length < 4) {