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
Files: ranged reads; HUD: selectable tables (hud.choose) (#111)
Evan (Yifeng) Wang3d2297e88d31
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex c5b4b79..8bac46c 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -400,6 +400,7 @@ Messages an app sends:| `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?, ... }`, `caps?: string[]` | once, after setup: how the app opened the game. Kept as `host.launch` (`{}` before it comes, and for an app that sends none); `caps`, the families of requests the app answers (`"files"`, `"store"`), as `host.caps` (`[]` before, and for an app that lists none) || `files.picked`, `files.data`, `store.*` | below | the answers to `files.*` and `store.*` ("Files", below) |+| `hud.choose` | `item`, `row` | the player clicked or tapped a row of a selectable HUD table ("HUD", below) || `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:@@ -548,13 +549,31 @@ hud.flash("damage", 1.2); // the player was hit from 1.2 rad clockwise of| `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 |+ | `table` | `columns`, `rows`, `title?`, `highlight?`, `selectable?`, `id?` | a scoreboard: listed while it is to be seen (`f.input.down("Tab")`); `highlight` is the row to set apart. A `selectable` table is a menu (below); `id` names it, unique among the tables |- **`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`.+- **Menus: selectable tables.** A table with `selectable: true` is a menu the player can click (with the pointer+ free) or tap. The app makes each row a target and, when one is chosen, sends `{ t: "hud.choose", item, row }`:+ `item` is the table's `id` (a string), or its index in `items` when it has none (a number); `row` is the row's+ index in `rows`. The game takes it with `host.on("hud.choose", (m, world) => ...)` like any message of the app, and+ decides what it means; a choice changes nothing by itself (the game moves its `highlight`, opens what was chosen).+ Keys and a gamepad drive the same menu through the game's own `highlight`, so a menu works on a keyboard, a+ gamepad and a touch screen alike. With the pointer captured for look there is nothing to click: a game that wants+ clicks shows its menu with the pointer free (`pointer: "free"`, or the player lets go with Esc), and an app on a+ touch screen has no capture to begin with. `threert-render play` draws no HUD: with `--hud-log` it prints each+ selectable table and the stdin line that chooses a row (`{"cmd":"host","messages":[{"t":"hud.choose","item":"maps",+ "row":0}]}`); the three.js view makes the rows clickable (`tools/three/hud.ts`). Rust apps:+ `host::hud_selectables(hud)` lists them, `host::hud_choose_message(item, row)` is the message.++ ```ts+ hud.set({ items: [{ type: "table", anchor: "center", id: "maps", title: "Maps", columns: ["Map", "Size"],+ rows: maps.map((m) => [m.name, m.size]), highlight: current, selectable: true }] });+ host.on("hud.choose", (m) => { if (m.item === "maps") open(maps[m.row]); });+ ```- **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.@@ -627,7 +646,7 @@ async function importMaps() { // from theconst picked = await files.pick({ mode: "folder", accept: [".bsp", ".wad"], title: "Your Counter-Strike folder" });if (!picked) return; // the player closed the pickerfor (const e of picked.entries.filter((e) => e.path.endsWith(".bsp"))) {- const bsp = await files.read(picked.pick, e.path); // Uint8Array, the whole file+ const bsp = await files.read(picked.pick, e.path); // Uint8Array, the whole file (or { offset, length })jobs.push({ name: e.path, job: sliced(convert(bsp)) }); // convert: a generator, it yields often}}@@ -653,7 +672,7 @@ same `id`.| game → app | app → game || --- | --- || `{ t: "files.pick", id, mode: "folder" \| "files", accept?: string[], title?: string }` | `{ t: "files.picked", id, ok: true, pick, name, entries: [{ path, size }] }` or `{ t: "files.picked", id, ok: false, reason }` |-| `{ t: "files.read", id, pick, path }` | `{ t: "files.data", id, ok: true, data, size }` or `{ ..., ok: false, reason }` |+| `{ t: "files.read", id, pick, path, offset?, length? }` | `{ t: "files.data", id, ok: true, data, offset, size }` or `{ ..., ok: false, reason }` |- `accept`: lower-case extensions with the dot (`[".bsp", ".wad", ".rad"]`); a file matches without regard to case.No `accept`: every file.@@ -664,10 +683,20 @@ same `id`.lasts for the game session (until the game is closed or reloaded).- `reason`: `"canceled"` (the player closed the picker), `"busy"` (a picker is already open), `"unsupported"`,`"denied"`, or a sentence.-- `files.read`: `path` must be one of the grant's entries (anything else: `ok: false, reason: "denied"`). `data` is- the whole file in base64. Files larger than 64 MiB are refused (`reason: "too large"`).-- `files.pick(o)` resolves to `{ pick, name, entries }`, or `null` when the player canceled; `files.read(pick, path)`- to the file's bytes. Any other `ok: false` rejects with a `HostRequestError` whose `reason` is the app's.+- `files.read`: `path` must be one of the grant's entries (anything else: `ok: false, reason: "denied"`). Without+ `offset` and `length`, `data` is the whole file in base64. With them (whole numbers of bytes; `offset` 0 by default,+ `length` to the end by default) it is `length` bytes from `offset`, fewer where the file ends first; an `offset`+ past the end is `reason: "out of range"` (at the end: no bytes). The answer's `offset` is where `data` starts and+ `size` is always the whole file's size. At most 64 MiB at once (`reason: "too large"`): a larger file is read in+ parts. Read only what is needed: a 38 MB texture archive for its directory and a few textures is a few small reads,+ where the whole of it is 50 MB of base64 in one message and a frame of a tenth of a second.+- `files.pick(o)` resolves to `{ pick, name, entries }`, or `null` when the player canceled; `files.read(pick, path,+ { offset?, length? }?)` to the bytes. Any other `ok: false` rejects with a `HostRequestError` whose `reason` is the+ app's.+- **The pointer while the picker is open.** A picker is the app's own window or sheet over the game, and the game+ cannot let go of the pointer itself: an app that has the pointer captured for look releases it when it opens a+ picker (as when the window loses the keyboard: everything held is let go), and the player captures it again with a+ click once the picker is closed.**`store.*`: the app's own storage for this game (read and write, persistent, local).**@@ -728,6 +757,7 @@ threert-render play game.js --assets games/openstrike \```- `--store <dir>`: the game's store (default `<assets>/.threert/store`), also the user root of `user:` assets.+- `files.read` with `offset` / `length` reads only that part (`Grant::read_range`).- `--pick <dir|file>[,<dir|file>...]` answers `files.pick` requests in order with those paths instead of a dialog: afolder for `mode: "folder"`; a file, or a folder standing for the files in it (not below), for `mode: "files"`.After the last one each pick is `"canceled"`; with no `--pick` at all each is `"unsupported"`. The launch lists@@ -741,7 +771,8 @@ threert-render play game.js --assets games/openstrike \`Picker` that asks the player) and `UserFiles` (all of it as `HostServices`, on its thread), and`files::set_user_root` with the game's store directory.- Checked: `renderer/src/userfiles.rs` tests (paths refused: `..`, absolute, bad characters, too long; the quota;- atomic writes under a concurrent reader; `--pick` answers in order; `files.read` refused outside the grant; hidden+ atomic writes under a concurrent reader; `--pick` answers in order; `files.read` refused outside the grant, and in+ parts (a file past 64 MiB read by ranges); hiddenfiles, depth and count bounds), `files.rs` (`user:` models and sounds from the store, never outside it, missingwithout a root), `script.rs` (base64 natively, the size bounds, a 64 MiB file within a budget), `host.rs` (caps in`launch`, services as one), `packages/gameplay/test/files.test.ts`; and `games/host/files.game.ts` in `play`diff --git a/packages/gameplay/README.md b/packages/gameplay/README.mdindex 318f150..69ff4df 100644--- a/packages/gameplay/README.md+++ b/packages/gameplay/README.md@@ -61,9 +61,9 @@ 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).+- **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, a scoreboard and menus (a `selectable` table: a click or a tap on a row is a `hud.choose` message) for the app to draw; `host.post` / `host.on` reach what the app owns (a WebSocket, an HTTP request, how the game was opened).- **Sound.** `audio.play("assets/sounds/shot.ogg", { at: muzzle, pitch: 1.04 })` plays a file of the game at a place in the world (or, without `at`, in the player's head); the engine decodes, places and mixes it the same way on every platform, with the camera as the ears. `audio.preload`, `audio.stop(key)` and `audio.move(key, at)` for the rest.-- **The player's files.** Where the app allows it (`files.available()`), `files.pick({ mode: "folder", accept: [".bsp"] })` lets the player choose content they own and `files.read(pick, path)` reads it; `store.write` / `read` / `list` / `remove` keep what the game made of it on the device, and `store.uri(path)` (`"user:maps/x.glb"`) shows it as a model or a texture. Nothing leaves the device. `sliced(generator)` runs a long conversion a few milliseconds a frame.+- **The player's files.** Where the app allows it (`files.available()`), `files.pick({ mode: "folder", accept: [".bsp"] })` lets the player choose content they own and `files.read(pick, path, { offset, length }?)` reads it, whole or in parts; `store.write` / `read` / `list` / `remove` keep what the game made of it on the device, and `store.uri(path)` (`"user:maps/x.glb"`) shows it as a model or a texture. Nothing leaves the device. `sliced(generator)` runs a long conversion a few milliseconds a frame.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/files.ts b/packages/gameplay/src/files.tsindex 7b013cd..1febd35 100644--- a/packages/gameplay/src/files.ts+++ b/packages/gameplay/src/files.ts@@ -7,7 +7,7 @@// host.on("launch", () => { canImport = files.available() && store.available(); }); // host.caps, after launch// const picked = await files.pick({ mode: "folder", accept: [".bsp", ".wad"], title: "Your Counter-Strike folder" });// if (picked) for (const e of picked.entries) if (e.path.endsWith(".bsp")) {-// const bsp = await files.read(picked.pick, e.path); // Uint8Array+// const bsp = await files.read(picked.pick, e.path); // Uint8Array; a part: { offset, length }// const job = sliced(convert(bsp)); // a generator: a little work a step// ... frame(f) { const r = job.step(8); if (r.done) await store.write("maps/de_x/map.glb", r.value); }// }@@ -61,8 +61,18 @@ export interface Files {available(): boolean;/** Asks the player; null when they closed the picker. */pick(options: PickOptions): Promise<Picked | null>;- /** A file of a pick: one of its entries, the whole file. */- read(pick: string, path: string): Promise<Uint8Array>;+ /**+ * A file of a pick (one of its entries): the whole file, or `length` bytes from `offset` (to its end without+ * `length`, never past it; the entry's `size` is the whole file's). Read a large file in parts: a directory, then+ * the pieces it names. At most 64 MiB at once.+ */+ read(pick: string, path: string, range?: ReadRange): Promise<Uint8Array>;+}++/** A part of a file: `offset` (0 by default) and `length` in bytes. */+export interface ReadRange {+ offset?: number;+ length?: number;}export interface UserStore {@@ -235,9 +245,16 @@ export const files: Files = {}},- async read(pick, path) {+ async read(pick, path, range) {if (typeof pick !== "string" || typeof path !== "string") throw new TypeError("files.read(pick, path): two strings");- const a = await request("files", "files.read", "files.data", { pick, path });+ const fields: Record<string, unknown> = { pick, path };+ for (const k of ["offset", "length"] as const) {+ const v = range?.[k];+ if (v === undefined) continue;+ if (!Number.isSafeInteger(v) || v < 0) throw new TypeError(`files.read: ${k} is a whole number of bytes, not ${String(v)}`);+ fields[k] = v;+ }+ const a = await request("files", "files.read", "files.data", fields);return fromBase64(String(a.data ?? ""));},};diff --git a/packages/gameplay/src/host.ts b/packages/gameplay/src/host.tsindex 99fcf06..19673e2 100644--- a/packages/gameplay/src/host.ts+++ b/packages/gameplay/src/host.ts@@ -58,6 +58,8 @@ export interface HostEvents {"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 };+ /** The player clicked or tapped a row of a selectable HUD table (hud.ts): `item` is its `id`, or its index. */+ "hud.choose": { t: "hud.choose"; item: string | number; row: number };/** Once after setup. `caps`: the families of requests the app answers (`"files"`, `"store"`); none: `[]`. */launch: { t: "launch"; params: LaunchParams; caps?: string[] };}diff --git a/packages/gameplay/src/hud.ts b/packages/gameplay/src/hud.tsindex 527c5a0..547ff84 100644--- a/packages/gameplay/src/hud.ts+++ b/packages/gameplay/src/hud.ts@@ -20,6 +20,8 @@// 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.+// - A `selectable` table is a menu the player can click or tap: the app answers with `{ t: "hud.choose", item, row }`+// (`host.on("hud.choose", (m) => ...)`).import { host } from "./host.ts";import { canonicalJson } from "./store.ts";@@ -68,15 +70,33 @@ export interface HudList {lines: (string | HudLine)[];}-/** A table: a scoreboard, shown while the game lists it (`f.input.down("Tab")`). */+/**+ * A table: a scoreboard, shown while the game lists it (`f.input.down("Tab")`), or a menu. A `selectable` table's+ * rows can be chosen with a click or a tap: the app then sends `{ t: "hud.choose", item, row }` (`item` is the+ * table's `id`, or its index in `items` without one; `row` the row's index), which the game takes with+ * `host.on("hud.choose", ...)`. Keys and a gamepad drive the same menu through the game's own `highlight`.+ */export interface HudTable {type: "table";anchor: HudAnchor;title?: string;columns: string[];rows: (string | number)[][];- /** The row to set apart (the player's own). */+ /** The row to set apart (the player's own; a menu's current choice). */highlight?: number;+ /** The rows can be clicked or tapped (`hud.choose`). */+ selectable?: boolean;+ /** The table's name in `hud.choose` (its index in `items` without one). */+ id?: string;+}++/** What the app sends when the player clicks or taps a row of a selectable table. */+export interface HudChoose {+ t: "hud.choose";+ /** The table's `id`, or its index in `items`. */+ item: string | number;+ /** The row's index in `rows`. */+ row: number;}export type HudItem = HudText | HudBar | HudList | HudTable;@@ -118,7 +138,15 @@ function check(h: Hud): void {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(", ")}`);+ if (item.type === "table") {+ if (!Array.isArray(item.columns) || !Array.isArray(item.rows) || !item.rows.every((r) => Array.isArray(r))) throw new TypeError(`hud.set: items[${k}]: a table has columns and rows (arrays)`);+ if (item.selectable !== undefined && typeof item.selectable !== "boolean") throw new TypeError(`hud.set: items[${k}].selectable is true or false`);+ if (item.id !== undefined && (typeof item.id !== "string" || item.id === "")) throw new TypeError(`hud.set: items[${k}].id is a non-empty string`);+ if (item.highlight !== undefined && !Number.isInteger(item.highlight)) throw new TypeError(`hud.set: items[${k}].highlight is a row's index`);+ }}+ const ids = (h.items ?? []).flatMap((item) => (item.type === "table" && item.id !== undefined ? [item.id] : []));+ if (new Set(ids).size !== ids.length) throw new TypeError("hud.set: two tables have the same id");}class HudState {diff --git a/packages/gameplay/src/index.ts b/packages/gameplay/src/index.tsindex b095cd9..674df09 100644--- a/packages/gameplay/src/index.ts+++ b/packages/gameplay/src/index.ts@@ -9,11 +9,11 @@ export type { Host, HostEvents, HostListener, HostMessage, LaunchParams, NetPostexport { InputState } from "./input.ts";export type { Input, InputMessage } from "./input.ts";export { files, HostRequestError, sliced, store } from "./files.ts";-export type { FileEntry, Files, Picked, PickOptions, Sliced, SliceResult, UserStore } from "./files.ts";+export type { FileEntry, Files, Picked, PickOptions, ReadRange, Sliced, SliceResult, UserStore } from "./files.ts";export { audio } from "./audio.ts";export type { Audio, AudioPoint, AudioPost, PlayOptions } from "./audio.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 type { Hud, HudAnchor, HudBar, HudChoose, 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/test/files.test.ts b/packages/gameplay/test/files.test.tsindex 690b0f2..c5f4669 100644--- a/packages/gameplay/test/files.test.ts+++ b/packages/gameplay/test/files.test.ts@@ -34,7 +34,10 @@ function app(caps: string[]) {return { t: "files.picked", id, ok: true, pick: "pick-1", name: "cstrike", entries: [...folder].map(([path, b]) => ({ path, size: b.length })) };case "files.read": {const b = m.pick === "pick-1" ? folder.get(m.path as string) : undefined;- return b ? { t: "files.data", id, ok: true, data: Buffer.from(b).toString("base64"), size: b.length } : no("files.data", "denied");+ if (!b) return no("files.data", "denied");+ const offset = (m.offset as number | undefined) ?? 0;+ const part = b.subarray(offset, m.length === undefined ? undefined : offset + (m.length as number));+ return { t: "files.data", id, ok: true, data: Buffer.from(part).toString("base64"), offset, size: b.length };}case "store.write":disk.set(m.path as string, m.data !== undefined ? Buffer.from(m.data as string, "base64") : Buffer.from(m.text as string));@@ -117,6 +120,11 @@ test("pick a folder, read its files, convert, store, read back, list, remove", aassert.deepEqual(picked, { pick: "pick-1", name: "cstrike", entries: [{ path: "maps/de_x.bsp", size: 5 }, { path: "cstrike.wad", size: 4 }] });const bsp = await settle(a, files.read(picked!.pick, "maps/de_x.bsp"));assert.deepEqual([...bsp], [30, 0, 0, 0, 7]);+ // A part of it.+ assert.deepEqual([...(await settle(a, files.read(picked!.pick, "maps/de_x.bsp", { offset: 3, length: 2 })))], [0, 7]);+ assert.deepEqual([...(await settle(a, files.read(picked!.pick, "maps/de_x.bsp", { offset: 4 })))], [7]);+ await assert.rejects(files.read(picked!.pick, "maps/de_x.bsp", { offset: -1 }), TypeError);+ await assert.rejects(files.read(picked!.pick, "maps/de_x.bsp", { length: 1.5 }), TypeError);await assert.rejects(settle(a, files.read(picked!.pick, "../secret")), (e: unknown) => e instanceof HostRequestError && e.reason === "denied");// The player closes the picker: null.assert.equal(await settle(a, files.pick({ mode: "files" })), null);@@ -144,6 +152,7 @@ test("the messages are the contract's", async () => {const seen: Msg[] = [];const take = () => seen.push(...a.posts.map((m) => ({ ...m, id: m.id ? "ID" : undefined })));void files.pick({ mode: "folder", accept: [".bsp"] }); take(); await a.pump();+ void files.read("pick-1", "cstrike.wad", { offset: 2, length: 1 }); take(); await a.pump();void store.write("a/b.bin", new Uint16Array([1, 256])); take(); await a.pump();void store.write("t.txt", "é"); take(); await a.pump();void store.readText("t.txt"); take(); await a.pump();@@ -151,6 +160,7 @@ test("the messages are the contract's", async () => {void store.remove("a"); take(); await a.pump();assert.deepEqual(seen, [{ t: "files.pick", id: "ID", mode: "folder", accept: [".bsp"] },+ { t: "files.read", id: "ID", pick: "pick-1", path: "cstrike.wad", offset: 2, length: 1 },{ t: "store.write", id: "ID", path: "a/b.bin", data: "AQAAAQ==" },{ t: "store.write", id: "ID", path: "t.txt", text: "é" },{ t: "store.read", id: "ID", path: "t.txt", as: "text" },diff --git a/packages/gameplay/test/host.test.ts b/packages/gameplay/test/host.test.tsindex 8b8e527..644665f 100644--- a/packages/gameplay/test/host.test.ts+++ b/packages/gameplay/test/host.test.ts@@ -239,3 +239,29 @@ test("the HUD is posted when it changed, and only then", () => {a.close();}});++test("a selectable table is a menu: the app's hud.choose reaches the game's listener", () => {+ const a = app();+ try {+ hud.reset();+ const menu = { type: "table" as const, anchor: "center" as const, id: "maps", title: "Maps", columns: ["Map", "Size"], rows: [["de_dust2", "4.2 MB"], ["cs_office", "3.1 MB"]], highlight: 0, selectable: true };+ assert.equal(hud.set({ items: [{ type: "text", anchor: "top-left", text: "x" }, menu] }), true);+ assert.deepEqual((a.posts.at(-1)!.hud as Hud).items![1], menu);+ assert.throws(() => hud.set({ items: [{ ...menu, selectable: "yes" as never }] }), /selectable/);+ assert.throws(() => hud.set({ items: [{ ...menu, id: "" }] }), /id/);+ assert.throws(() => hud.set({ items: [menu, { ...menu }] }), /same id/);+ assert.throws(() => hud.set({ items: [{ ...menu, rows: "none" as never }] }), /rows/);+ assert.throws(() => hud.set({ items: [{ ...menu, highlight: 0.5 }] }), /highlight/);+ // The app's click on a row, as the game hears it.+ const g = defineGame({ state: {}, setup: scene, handlers: {} });+ const h = installNodeHost(g, new RecordingEngine());+ h.setup("node");+ const chosen: [string | number, number][] = [];+ const off = host.on("hud.choose", (m) => void chosen.push([m.item, m.row]));+ send(h, { t: "hud.choose", item: "maps", row: 1 }, { t: "hud.choose", item: 0, row: 0 });+ off();+ assert.deepEqual(chosen, [["maps", 1], [0, 0]]);+ } finally {+ a.close();+ }+});diff --git a/renderer/src/host.rs b/renderer/src/host.rsindex f7bc118..681f929 100644--- a/renderer/src/host.rs+++ b/renderer/src/host.rs@@ -70,6 +70,25 @@ pub fn launch_message_with_caps(params: Option<&Value>, caps: &[&str]) -> Valuejson!({ "t": "launch", "params": params.filter(|p| p.is_object()).cloned().unwrap_or_else(|| json!({})), "caps": caps })}+/// The selectable tables of a HUD description (`{ t: "hud", hud }`'s `hud`; packages/gameplay/src/hud.ts): each as+/// the `item` its `hud.choose` names (its `id`, or its index in `items`), its title and its rows' count. An app that+/// draws the HUD makes their rows clickable or tappable.+pub fn hud_selectables(hud: &Value) -> Vec<(Value, String, usize)> {+ let items = hud["items"].as_array().map(Vec::as_slice).unwrap_or_default();+ items+ .iter()+ .enumerate()+ .filter(|(_, t)| t["type"] == "table" && t["selectable"] == true)+ .map(|(k, t)| (t["id"].as_str().map_or_else(|| json!(k), |id| json!(id)), t["title"].as_str().unwrap_or("").to_string(), t["rows"].as_array().map_or(0, Vec::len)))+ .collect()+}++/// The message for the game when the player clicked or tapped row `row` of the selectable table `item`+/// (`hud_selectables`).+pub fn hud_choose_message(item: &Value, row: usize) -> Value {+ json!({ "t": "hud.choose", "item": item, "row": row })+}+/// A window's keys and pointer between two frames, and the `input` message of a frame.#[derive(Default)]pub struct InputTracker {@@ -208,6 +227,19 @@ mod tests {assert_eq!(launch_message(Some(&json!("x")))["params"], json!({}));}+ #[test]+ fn a_huds_selectable_tables() {+ let hud = json!({ "items": [+ { "type": "text", "anchor": "top-left", "text": "x" },+ { "type": "table", "anchor": "center", "id": "maps", "title": "Maps", "columns": ["Map"], "rows": [["de_x"], ["cs_y"]], "selectable": true },+ { "type": "table", "anchor": "center", "columns": ["Player"], "rows": [["Ada"]] },+ { "type": "table", "anchor": "right", "columns": ["Mode"], "rows": [["a"], ["b"], ["c"]], "selectable": true },+ ] });+ assert_eq!(hud_selectables(&hud), vec![(json!("maps"), "Maps".to_string(), 2), (json!(3), String::new(), 3)]);+ assert!(hud_selectables(&json!({})).is_empty());+ assert_eq!(hud_choose_message(&json!("maps"), 1), json!({ "t": "hud.choose", "item": "maps", "row": 1 }));+ }+/// Services that answer a family and services that answer none, as the window's one list.struct Echo(&'static str, Vec<Value>);impl HostServices for Echo {diff --git a/renderer/src/userfiles.rs b/renderer/src/userfiles.rsindex e04b3c6..8578904 100644--- a/renderer/src/userfiles.rs+++ b/renderer/src/userfiles.rs@@ -283,12 +283,37 @@ impl Grant {/// The file `path` of the grant: `"denied"` for one that is not among its entries.pub fn read(&self, path: &str) -> Result<Vec<u8>, String> {+ self.read_range(path, 0, None).map(|(bytes, _)| bytes)+ }++ /// `length` bytes of the file `path` from `offset` (to its end without `length`, and never past it), and the+ /// file's whole size. `"denied"` for a file that is not among the grant's entries, `"out of range"` for an offset+ /// past its end, `"too large"` for more than `MAX_FILE` bytes at once.+ pub fn read_range(&self, path: &str, offset: u64, length: Option<u64>) -> Result<(Vec<u8>, u64), String> {+ use std::io::{Read, Seek, SeekFrom};let file = self.files.get(path).ok_or("denied")?;- let len = std::fs::metadata(file).map_err(|e| format!("{path}: {e}"))?.len();- if len > MAX_FILE {+ let io = |e: std::io::Error| format!("{path}: {e}");+ let mut f = std::fs::File::open(file).map_err(io)?;+ let size = f.metadata().map_err(io)?.len();+ if offset > size {+ return Err("out of range".into());+ }+ let n = length.map_or(size - offset, |l| l.min(size - offset));+ if n > MAX_FILE {return Err("too large".into());}- std::fs::read(file).map_err(|e| format!("{path}: {e}"))+ f.seek(SeekFrom::Start(offset)).map_err(io)?;+ let mut bytes = vec![0; n as usize];+ f.read_exact(&mut bytes).map_err(io)?;+ Ok((bytes, size))+ }+}++/// A request's `offset` / `length`: absent, or a whole number of bytes.+fn bytes_field(m: &Value, k: &str) -> Result<Option<u64>, String> {+ match &m[k] {+ Value::Null => Ok(None),+ v => v.as_u64().map(Some).ok_or_else(|| format!("{k} is a whole number of bytes")),}}@@ -334,12 +359,14 @@ impl Requests {Err(e) => fail("files.picked", e),},"files.read" => {- let r = match (m["pick"].as_str().and_then(|p| self.grants.get(p)), m["path"].as_str()) {- (Some(g), Some(path)) => g.read(path),+ let range = bytes_field(m, "offset").and_then(|o| Ok((o.unwrap_or(0), bytes_field(m, "length")?)));+ let r = match (m["pick"].as_str().and_then(|p| self.grants.get(p)), m["path"].as_str(), range) {+ (_, _, Err(e)) => Err(e),+ (Some(g), Some(path), Ok((offset, length))) => g.read_range(path, offset, length).map(|(b, size)| (b, offset, size)),_ => Err("denied".into()),};match r {- Ok(b) => json!({ "t": "files.data", "id": id, "ok": true, "data": b64().encode(&b), "size": b.len() }),+ Ok((b, offset, size)) => json!({ "t": "files.data", "id": id, "ok": true, "data": b64().encode(&b), "offset": offset, "size": size }),Err(e) => fail("files.data", e),}}@@ -609,7 +636,22 @@ mod tests {assert_eq!(a["entries"], json!([{ "path": "a/b/c/d/e/f.bsp", "size": 5 }, { "path": "cstrike.wad", "size": 3 }, { "path": "maps/DE_Y.BSP", "size": 4 }, { "path": "maps/de_x.bsp", "size": 3 }]));let pick = a["pick"].as_str().unwrap().to_string();let a = ask(&mut r, json!({ "t": "files.read", "id": "r1", "pick": pick, "path": "maps/de_x.bsp" }));- assert_eq!(a, json!({ "t": "files.data", "id": "r1", "ok": true, "data": b64().encode("BSP"), "size": 3 }));+ assert_eq!(a, json!({ "t": "files.data", "id": "r1", "ok": true, "data": b64().encode("BSP"), "offset": 0, "size": 3 }));+ // A part of a file: `size` is the whole file's; a length past the end stops at it.+ let a = ask(&mut r, json!({ "t": "files.read", "id": "r5", "pick": pick, "path": "a/b/c/d/e/f.bsp", "offset": 1, "length": 3 }));+ assert_eq!(a, json!({ "t": "files.data", "id": "r5", "ok": true, "data": b64().encode("eep"), "offset": 1, "size": 5 }));+ let a = ask(&mut r, json!({ "t": "files.read", "id": "r6", "pick": pick, "path": "a/b/c/d/e/f.bsp", "offset": 3, "length": 100 }));+ assert_eq!((a["data"].clone(), a["size"].clone()), (json!(b64().encode("p6")), json!(5)));+ let a = ask(&mut r, json!({ "t": "files.read", "id": "r7", "pick": pick, "path": "a/b/c/d/e/f.bsp", "offset": 2 }));+ assert_eq!(a["data"], b64().encode("ep6"));+ let a = ask(&mut r, json!({ "t": "files.read", "id": "r8", "pick": pick, "path": "a/b/c/d/e/f.bsp", "offset": 5 }));+ assert_eq!((a["ok"].clone(), a["data"].clone()), (json!(true), json!("")));+ assert_eq!(ask(&mut r, json!({ "t": "files.read", "id": "r9", "pick": pick, "path": "a/b/c/d/e/f.bsp", "offset": 6 }))["reason"], "out of range");+ for bad in [json!({ "offset": -1 }), json!({ "offset": 1.5 }), json!({ "length": "3" })] {+ let mut m = json!({ "t": "files.read", "id": "r10", "pick": pick, "path": "a/b/c/d/e/f.bsp" });+ m.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());+ assert_eq!(ask(&mut r, m)["ok"], false);+ }for denied in ["maps/readme.txt", "../secret.bsp", "/etc/passwd", ".hidden/z.bsp", "a/b/c/d/e/f/g.bsp", "maps/../../secret.bsp"] {let a = ask(&mut r, json!({ "t": "files.read", "id": "r2", "pick": pick, "path": denied }));assert_eq!(a, json!({ "t": "files.data", "id": "r2", "ok": false, "reason": "denied" }), "{denied}");@@ -634,6 +676,25 @@ mod tests {let _ = std::fs::remove_dir_all(root);}+ #[test]+ fn a_file_past_the_limit_is_read_in_parts() {+ let root = temp("parts");+ let f = std::fs::File::create(root.join("big.wad")).unwrap();+ f.set_len(MAX_FILE + 16).unwrap();+ drop(f);+ std::fs::OpenOptions::new().write(true).open(root.join("big.wad")).and_then(|mut f| {+ use std::io::{Seek, SeekFrom};+ f.seek(SeekFrom::Start(MAX_FILE + 12))?;+ f.write_all(b"WAD3")+ }).unwrap();+ let g = Grant::folder(&root, &[".wad".into()]).unwrap();+ assert_eq!(g.read("big.wad"), Err("too large".into()));+ assert_eq!(g.read_range("big.wad", 0, Some(MAX_FILE + 1)), Err("too large".into()));+ assert_eq!(g.read_range("big.wad", MAX_FILE + 12, Some(64)), Ok((b"WAD3".to_vec(), MAX_FILE + 16)));+ assert_eq!(g.read_range("big.wad", 16, Some(MAX_FILE)).map(|(b, _)| b.len() as u64), Ok(MAX_FILE));+ let _ = std::fs::remove_dir_all(root);+ }+#[test]fn a_folder_has_at_most_its_entries() {let root = temp("many");diff --git a/renderer/src/view.rs b/renderer/src/view.rsindex a3e4ad5..bf68357 100644--- a/renderer/src/view.rs+++ b/renderer/src/view.rs@@ -12,7 +12,7 @@//! 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), the game's `net.*` messages are the binary's sockets and HTTP (src/net.rs), and its `audio.*` messages are+//! none; a selectable table's rows are chosen on stdin with a `hud.choose` host message, which it prints), the game's `net.*` messages are the binary's sockets and HTTP (src/net.rs), and its `audio.*` messages are//! played (src/audio, the `audio` feature: the ears are the camera of each frame). Its `files.*` and `store.*` are//! answered from `--pick <dir|file>[,...]` (the player's picks, in order) and `--store <dir>` (the game's storage,//! `<assets>/.threert/store` by default; `user:` assets resolve there): src/userfiles.rs.@@ -577,6 +577,10 @@ fn frame(s: &mut State, cmds: &mpsc::Receiver<Cmd>, services: &mut dyn HostServiservices.post(p);if args.hud_log && p["t"] == "hud" {eprintln!("hud: {}", p["hud"]);+ // (The window draws no HUD: a menu's row is chosen on stdin, as an app that draws it sends the click.)+ for (item, title, rows) in crate::host::hud_selectables(&p["hud"]) {+ eprintln!("hud: selectable table {item} \"{title}\", {rows} rows: choose one with {}", serde_json::json!({ "cmd": "host", "messages": [crate::host::hud_choose_message(&item, 0)] }));+ }}}if !posts.is_empty() {diff --git a/tools/three/hud.ts b/tools/three/hud.tsindex a1f5350..0beb9e4 100644--- a/tools/three/hud.ts+++ b/tools/three/hud.ts@@ -7,8 +7,9 @@// - 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";+// - The overlay takes no pointer events (clicks and the pointer lock stay the canvas's), but for the rows of a+// `selectable` table: a click or a tap on one is `{ t: "hud.choose", item, row }` for the game (`onChoose`).+import type { Hud, HudAnchor, HudChoose, 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"];@@ -38,6 +39,7 @@ const CSS = `.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-table tr.pick { pointer-events: auto; cursor: pointer; } .hud-table tr.pick:hover td { background: rgba(255,255,255,.1); }.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; }@@ -80,7 +82,11 @@ export class HudOverlay {private timers: number[] = [];private flashed = 0;- constructor(parent: HTMLElement = document.body) {+ /** `onChoose`: a row of a selectable table was clicked or tapped (the page hands the message to the game). */+ private readonly onChoose?: (m: HudChoose) => void;++ constructor(parent: HTMLElement = document.body, onChoose?: (m: HudChoose) => void) {+ this.onChoose = onChoose;if (!document.getElementById("hud-style")) {const style = el("style", "", CSS);style.id = "hud-style";@@ -105,7 +111,7 @@ export class HudOverlay {this.timers = [];for (const a of this.anchors.values()) a.replaceChildren();for (const item of hud.items ?? []) {- const e = this.item(item);+ const e = this.item(item, (hud.items ?? []).indexOf(item));if (e) this.anchors.get(item.anchor)?.appendChild(e);}this.message.replaceChildren();@@ -130,7 +136,7 @@ export class HudOverlay {}}- private item(item: HudItem): HTMLElement | null {+ private item(item: HudItem, index: number): HTMLElement | null {switch (item.type) {case "text": {const box = tone(el("div", ""), item.tone);@@ -176,7 +182,14 @@ export class HudOverlay {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" : ""));+ const row = table.appendChild(el("tr", [k === item.highlight ? "own" : "", item.selectable && this.onChoose ? "pick" : ""].filter(Boolean).join(" ")));+ if (item.selectable && this.onChoose) {+ const choose = this.onChoose;+ row.addEventListener("click", (e) => {+ e.stopPropagation();+ choose({ t: "hud.choose", item: item.id ?? index, row: k });+ });+ }item.columns.forEach((_, c) => row.appendChild(el("td", numeric[c] ? "n" : "", r[c] === undefined ? "" : String(r[c]))));});return box;diff --git a/tools/three/view.ts b/tools/three/view.tsindex 34f01ca..da7e665 100644--- a/tools/three/view.ts+++ b/tools/three/view.ts@@ -69,9 +69,11 @@ export async function run(mod: SceneModule): Promise<void> {const net = new PageNet();const sound = new PageAudio();let hud: HudOverlay | null = null;+ // A row of a selectable HUD table the player clicked: to the game with the next frame's messages.+ const chosen: HostMessage[] = [];const flush = () => {for (const m of posts.splice(0)) {- if (m.t === "hud") (hud ??= new HudOverlay()).set((m.hud ?? {}) as Hud);+ if (m.t === "hud") (hud ??= new HudOverlay(document.body, (c) => void chosen.push({ ...c }))).set((m.hud ?? {}) as Hud);else if (!sound.post(m)) net.post(m);}};@@ -211,7 +213,7 @@ export async function run(mod: SceneModule): Promise<void> {// 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()];+ const messages = [...(input ? [input.message()] : []), ...net.poll(), ...chosen.splice(0)];if (messages.length) node.hostMessages(JSON.stringify(messages), Date.now());node.frame(dt, Date.now());} catch (e) {