# Pebble3D > Pebble3D is a browser 3D game engine: scenes are JSON files validated by a zod schema, rendered with the three.js WebGPU renderer and simulated by Rapier physics compiled from Rust to WebAssembly. To build a game: `git clone https://github.com/pebble3d/pebble3d`, run `pnpm i` (no Rust needed: the physics WASM is prebuilt), then follow `skills/make-a-game/SKILL.md`. Write a scene as JSON, drive it from TypeScript with `createGame`, and verify it with screenshots, determinism hashes and headless Node runs. Start with the getting-started guide, then keep the scene and API references open. `llms-full.txt` is every page below concatenated, generated by `pnpm docs:gen`. The scene JSON Schema is `packages/sdk/scene.schema.json`; its fields are already tabulated in the scene reference. ## Docs - [Getting started](docs/getting-started.md): from nothing to a JSON scene in the playground, then a minimal game app with a fixed-tick sim and `?demo=1` bot. - [AGENTS.md](AGENTS.md): working rules for coding agents: layout, commands, invariants and the before-you-finish checklist. - [Scene reference](docs/scene-reference.md): every scene JSON field with its type, default and meaning. - [API reference](docs/api-reference.md): `createGame`, the `Game` object, state buffers, raycasts, and the exports of `@pebble3d/sdk` and `@pebble3d/renderer`. - [Verification](docs/verification.md): prove a change works with `pnpm shot`, determinism hashes, demo bots and fps benches. - [Troubleshooting](docs/troubleshooting.md): error messages and symptoms, each with cause and fix. ## Cookbook - [scene-basics](docs/cookbook/scene-basics.md): A valid scene: ground, bounds, static and dynamic props, camera presets. - [prefabs-and-spawners](docs/cookbook/prefabs-and-spawners.md): Reusable entity templates; seeded streams of spawned bodies. - [bodies-impulses-velocity](docs/cookbook/bodies-impulses-velocity.md): Impulses, velocity, teleport, runtime spawn; reading pose and velocity. - [raycasts](docs/cookbook/raycasts.md): Ground probes, line of sight, picking; the three filters. - [character-and-camera](docs/cookbook/character-and-camera.md): A player character with `accel`, clips matched to speed, the third-person camera. - [splat-environments](docs/cookbook/splat-environments.md): A Gaussian-splat capture as the level, with colliders and shadows. - [post-and-toon-style](docs/cookbook/post-and-toon-style.md): Exposure, bloom, AO; the opt-in `post.style: "toon"`. - [depth-of-field](docs/cookbook/depth-of-field.md): Photo-mode blur with `renderer.dof`. - [deterministic-game-loop](docs/cookbook/deterministic-game-loop.md): Fixed-tick rules, input logs, replays and ghosts. - [demo-bot-and-captures](docs/cookbook/demo-bot-and-captures.md): A `?demo=1` autoplayer and a reproducible capture script. - [instanced-crowds-and-perf](docs/cookbook/instanced-crowds-and-perf.md): Instancing, crowds, workers, the `fast` build, budgets. - [audio-sfx](docs/cookbook/audio-sfx.md): Synthesised WebAudio cues without autoplay warnings. - [json-levels-and-headless-verify](docs/cookbook/json-levels-and-headless-verify.md): Levels as data, proven in Node with `pnpm --filter chain-reaction verify`. - [assets-and-licensing](docs/cookbook/assets-and-licensing.md): Adding a model, HDRI or splat through the asset manifest. - [sub-path-hosting](docs/cookbook/sub-path-hosting.md): Serving a game under `/some/path/`: Vite `--base`, the asset base, shared assets. - [custom-camera](docs/cookbook/custom-camera.md): Driving the camera yourself: removing the orbit controls, follow and spring-arm cameras. - [owning-the-world](docs/cookbook/owning-the-world.md): Worlds your code creates, steps and draws next to `createGame`; stale views; `stateHash`. ## Skills Agent playbooks for building a game with Pebble3D. For any request to make a game, start with make-a-game and follow it. - [make-a-game](skills/make-a-game/SKILL.md): the entry point; it runs the steps in this order, each with an exit check: interview, brief, scaffold, build, game feel, art pass, complete loop, verify. - [game-interview](skills/game-interview/SKILL.md): turn a vague idea into a short design brief the developer approves, with a non-interactive fallback. - [start-a-game](skills/start-a-game/SKILL.md): scaffold a new app under `apps/` the way the demos are laid out and prove it boots, captures and tests. - [verify-your-work](skills/verify-your-work/SKILL.md): what done means: tests, captures, sidecars, looking at every image, both backends. - [engine-pitfalls](skills/engine-pitfalls/SKILL.md): known engine traps as "if you see X, do Y", each linked to the full fix. - [game-feel](skills/game-feel/SKILL.md): hit-stop, shake, camera punch, particles, buffering and sound, tuned by watching capture sequences. - [art-direction](skills/art-direction/SKILL.md): commit to one look (palette, toon or PBR, lighting, post) and judge captures against it. - [complete-game-loop](skills/complete-game-loop/SKILL.md): title, play, results and restart, pause, HUD, a demo bot and a README. - [genre-playbooks](skills/genre-playbooks/SKILL.md): per-genre recipes that reuse the shipped demo for racers, platformers, tower defence and more. ## Examples - [Examples map](docs/examples.md): where each engine feature is used in the showcase games and the playground, by file and line range. ## Optional - [README](README.md): project overview, quickstart, showcase games and known limitations. - [LICENSE](LICENSE): the repository licence. ===== docs/getting-started.md ===== # Getting started From nothing to a JSON scene in the playground, then to a minimal game app with a fixed-tick sim, a `?demo=1` bot and `window.__pebble3d` probes. > Asking a coding agent to make a game? Point it at [`skills/make-a-game/SKILL.md`](../skills/make-a-game/SKILL.md). It interviews you, writes a brief, builds the game and verifies it. This guide is the manual path. ## 0. Set up once ```bash pnpm i && pnpm fetch-assets ``` No Rust is needed: the physics WASM is committed, prebuilt, in `packages/sdk/wasm/`. `pnpm fetch-assets` is only needed for the HDRI, splats and avatars; the studio preset below needs none of them. ## 1. A scene Save this as `apps/playground/scenes/mine.json`: ```json { "version": 1, "environment": { "preset": "studio", "ground": {} }, "entities": [{ "id": "ball", "mesh": { "primitive": "sphere" }, "body": { "restitution": 0.5 }, "transform": { "position": [0, 4, 0] } }] } ``` | Piece | Meaning | | --- | --- | | `"version": 1` | Required schema version. | | `"preset": "studio"` | Neutral grey backdrop and lights; no assets needed. `"outdoor"` uses an HDRI. | | `"ground": {}` | A static ground plane with a collider at y = 0. | | `mesh` + `body` | A rendered sphere (diameter 1 m) with a dynamic Rapier body; the collider is fitted to the primitive. | Every field, type and default: [scene-reference.md](scene-reference.md). JSON Schema for editor validation: `packages/sdk/scene.schema.json` (set `"$schema"` to its path). ## 2. Run it in the playground ```bash pnpm dev # Vite on port 5173 # open http://localhost:5173/?scene=mine pnpm shot --scene mine --ticks 30 # headless: artifacts/shots/mine-default-webgpu-1280x720.png ``` Useful URL params (`apps/playground/src/main.ts`): `mode=fixed&ticks=` stops at a tick, `backend=webgl`, `cam=`, `overlay`. Backtick toggles the stats overlay. On Linux, Chromium needs `--enable-unsafe-webgpu --enable-features=Vulkan --use-angle=vulkan` for WebGPU. ## 3. A minimal game app The pattern from `apps/chain-reaction/src/main.ts`: `createGame` loads the scene, the wasm and the renderer and steps physics; your code adds rules in `game.onFrame`. This example (a ball you kick with Space) was built and captured with `pnpm shot --app hello-ball --param demo=1 --ticks 300` (exit 0, empty console, `kicks: 3` in the sidecar). ### Files ```text apps/hello-ball/ package.json index.html vite.config.ts copy apps/rockfall/vite.config.ts unchanged tsconfig.json copy apps/rockfall/tsconfig.json unchanged (it already includes test/ and vitest.config.ts) vitest.config.ts the app's vitest project (see "Tests in Node" below) scenes/court.json src/main.ts src/sim.ts test/sim.test.ts ``` `vite.config.ts` must be copied: it serves the Basis transcoder at `/basis/`, points `publicDir` at `../playground/public` (shared assets, `favicon.svg`) and lets Vite serve the wasm from `packages/sdk/wasm/`. Scenes and code keep asset paths root-absolute (`/assets/...`); to deploy under a sub-path, build with `vite build --base /some/path/` and the renderer prefixes them ([cookbook/sub-path-hosting.md](cookbook/sub-path-hosting.md)). After creating the folder, run `pnpm i` so pnpm links the workspace packages (in a sandbox without network, `pnpm i --offline` works once the store has every package). New-app checklist: `package.json`, `index.html`, copied `vite.config.ts` and `tsconfig.json`, your own `vitest.config.ts` **plus an `"apps/"` line in the root `vitest.config.ts` `projects` list** (without it vitest never runs the app's tests), then `pnpm i`. ### package.json ```json { "name": "hello-ball", "private": true, "type": "module", "scripts": { "dev": "vite --port 5260", "build": "vite build", "test": "vitest run", "typecheck": "tsc -p tsconfig.json --noEmit" }, "dependencies": { "@pebble3d/renderer": "workspace:*", "@pebble3d/sdk": "workspace:*", "three": "0.187.0" }, "devDependencies": { "vite": "^8.3.8", "vitest": "^5.1.1" } } ``` ### index.html The favicon link matters: without it the browser requests `/favicon.ico`, gets a 404, and `pnpm shot` fails on that console error. ```html Hello Ball ``` ### scenes/court.json ```json { "version": 1, "environment": { "preset": "studio", "ground": {} }, "camera": { "presets": { "hero": { "position": [0, 3, 8], "target": [0, 1, 0] } } }, "entities": [ { "id": "ball", "mesh": { "primitive": "sphere", "material": { "color": "#e8553a" } }, "body": { "restitution": 0.6 }, "transform": { "position": [0, 3, 0] } } ] } ``` ### src/sim.ts: the fixed-tick sim and the demo bot Rules run once per 60 Hz engine tick and touch the world only through the wasm `World` ([api-reference.md](api-reference.md)). The sim takes only the three `Game` members it uses (`sim`, `views`, `ids`), so a Node test can hand it the same three built without a browser. State is read from `game.views.curr` (8 floats per slot: `px, py, pz, qx, qy, qz, qw, flags`) and query results from `game.views.scratch`. Bigger sims in the repo: `apps/rockfall/src/game/sim.ts`, `apps/chain-reaction/src/puzzle/sim.ts`. ```ts import type { Game } from "@pebble3d/sdk/game"; /** What the sim needs from a game: `createGame`'s result in the browser, or the same three fields built in Node. */ export type SimHost = Pick; /** Scratch slots `linearVelocity` writes: [vx, vy, vz] at [12..15). */ const VEL = 12; export interface TickInput { kick: boolean; } /** * Game rules, advanced once per engine tick. No DOM, no Math.random, no Date: * the same inputs on the same ticks give the same state hash. */ export class BallSim { tick = 0; kicks = 0; private readonly ballId: number; private readonly slot: number; constructor(private readonly game: SimHost) { const id = game.ids.get("ball"); if (id === undefined) throw new Error('scene has no "ball" entity'); this.ballId = id; this.slot = game.sim.world.slotOf(id); } /** Ball height from the current state buffer (slot stride 8: px, py, pz, qx..qw, flags). */ ballY(): number { return this.game.views.curr[this.slot * 8 + 1] as number; } /** Ball vertical speed, read through the scratch buffer. */ ballVy(): number { const world = this.game.sim.world; return world.linearVelocity(this.ballId) ? (this.game.views.scratch[VEL + 1] as number) : 0; } step(input: TickInput): void { this.tick++; if (input.kick) { this.game.sim.world.applyImpulse(this.ballId, 0, 3, 0); this.kicks++; } } } /** `?demo=1` autoplayer: kicks whenever the ball is resting on the ground. */ export class DemoBot { next(sim: BallSim, out: TickInput): void { out.kick = sim.ballY() < 0.6 && Math.abs(sim.ballVy()) < 0.05; } } ``` ### src/main.ts: boot, input, probes ```ts import { createGame } from "@pebble3d/sdk/game"; import type { SceneInput } from "@pebble3d/sdk/schema"; import detWasmUrl from "../../../packages/sdk/wasm/det/engine_core_det_bg.wasm?url"; import fastWasmUrl from "../../../packages/sdk/wasm/fast/engine_core_fast_bg.wasm?url"; import sceneJson from "../scenes/court.json"; import { BallSim, DemoBot, type TickInput } from "./sim.ts"; async function main(): Promise { const canvas = document.getElementById("app"); if (!(canvas instanceof HTMLCanvasElement)) throw new Error("#app canvas missing"); const q = new URLSearchParams(location.search); const mode = q.get("mode") === "fixed" ? "fixed" : "realtime"; const ticks = q.get("ticks"); const game = await createGame({ canvas, scene: sceneJson as unknown as SceneInput, // JSON imports widen tuples; createGame validates at runtime mode, backend: q.get("backend") === "webgl" ? "webgl" : "webgpu", wasmUrls: { deterministic: detWasmUrl, fast: fastWasmUrl }, ...(ticks !== null ? { stopAtTick: Number(ticks) } : {}), }); game.setCamera(q.get("cam") ?? "hero"); const sim = new BallSim(game); const bot = q.get("demo") === "1" ? new DemoBot() : null; const input: TickInput = { kick: false }; let spaceHeld = false; window.addEventListener("keydown", (e) => { if (e.code === "Space") spaceHeld = true; }); window.addEventListener("keyup", (e) => { if (e.code === "Space") spaceHeld = false; }); // createGame steps the physics world; run one rules tick per engine tick it advanced. game.onFrame(() => { const world = game.sim.world; while (sim.tick < world.tick()) { if (bot) bot.next(sim, input); else input.kick = spaceHeld; sim.step(input); } }); // Extra probes for automation: pnpm shot copies `game` into its .json sidecar. Object.assign(window.__pebble3d ?? {}, { game: { kicks: () => sim.kicks, ballY: () => sim.ballY() }, }); game.start(); } main().catch((e: unknown) => { const msg = e instanceof Error ? `${e.name}: ${e.message}` : String(e); window.__pebble3d = { ...window.__pebble3d, ready: false, done: false, error: msg, }; console.error(msg); }); ``` ### What each part does | Piece | Why | | --- | --- | | `wasmUrls` with `?url` imports | Vite serves both `_bg.wasm` builds; the scene's `sim.build` (default `"deterministic"`) picks one. | | `mode`, `stopAtTick` | `pnpm shot` opens the page with `?mode=fixed&ticks=`: one tick per frame, and `__pebble3d.done` turns true at tick n. Read both params or captures time out. | | `game.onFrame(cb)` | Runs every frame after physics and `renderer.sync`, before `renderer.render`. In fixed mode `dt` is `ticks / 60`. | | `while (sim.tick < world.tick())` | Keeps rules in step with the engine tick. In fixed mode that is exactly one rules tick per physics tick, so captures repeat. In realtime a frame can advance 2+ ticks; if inputs must replay bit-exactly there too, own the loop as `apps/rockfall/src/main.ts` does (`FixedStepLoop`, then `sim.step(input)` once per tick). | | `?demo=1` bot | Produces the same `TickInput` a player would; every showcase game has one (see [verification.md](verification.md)). | | `window.__pebble3d` | `createGame` installs `ready`, `done`, `tick`, `stats()`, `stateHash()`, `setCamera()`, `player()`, `position()`. Add a `game` object of zero-argument functions; `pnpm shot` records their values. | | `main().catch` | Puts the error on `__pebble3d.error` so automation reports it instead of timing out. | ### Tick order With `createGame` in fixed mode (one tick per frame, as in `pnpm shot`), each engine tick is **physics first, then rules** (in realtime mode `createGame` may step several physics ticks before calling `onFrame` once): `createGame` calls `world.step`, then your `onFrame` runs `sim.step(input)`, whose impulses take effect in the *next* `world.step`. So after tick n the world has stepped n times and the rules have run n times, each seeing the world after its own step. A headless run that must reproduce the browser's `stateHash` (and `pnpm shot`'s sidecar) mirrors that order exactly: ```ts for (let t = 0; t < n; t++) { world.step(1); // what createGame does views.refresh(); // what createGame does before onFrame bot.next(sim, input); sim.step(input); // what your onFrame does } ``` Running rules *before* `world.step` instead (`sim.step(input); world.step(1)`) puts rules call k after step k-1 instead of after step k: anything keyed to the rules' own tick counter (a bot that presses Start at `sim.tick === 90`, a countdown, a spawn schedule) lands one physics tick earlier, and an input on the very last call is never stepped. In hello-ball, a kick keyed to `sim.tick === 90` gives different state hashes at tick 120 under the two orders (they reconverge only once the ball is at rest). Rules that react only to world state, like `DemoBot` above, can happen to match; do not rely on it. The other repo pattern, where the sim owns its world and calls `world.step(1)` at the end of its own `step()` ([cookbook/deterministic-game-loop.md](cookbook/deterministic-game-loop.md)), is rules-then-physics; it is equally valid because the browser and Node then call the same `sim.step` and nothing else steps the world. The rule is: one code path decides the order, and the headless verifier calls that path, never a re-implementation of it. ### Tests in Node vitest only runs projects listed in the root `vitest.config.ts`. Two edits register a new app: 1. `apps/hello-ball/vitest.config.ts` (copied from `apps/rockfall/vitest.config.ts`; `name` is what `--project` matches): ```ts import { defineProject } from "vitest/config"; export default defineProject({ test: { name: "hello-ball", include: ["test/**/*.test.ts"], testTimeout: 60_000 }, }); ``` 2. Add `"apps/hello-ball"` to the `projects` array in the root `vitest.config.ts`, next to the other apps. Without step 2, `npx vitest run --project hello-ball` fails with `No projects were found ... The filter matched no projects: hello-ball`, and `npx vitest run apps/hello-ball/test` prints `No test files found, exiting with code 0`: a silent pass that ran nothing. `test/sim.test.ts` runs the real deterministic wasm in Node, spawns the scene the way `createGame` does and drives the sim in the browser's tick order: ```ts import { readFileSync } from "node:fs"; import { expandScene } from "@pebble3d/sdk/expand"; import { parseScene } from "@pebble3d/sdk/schema"; import { loadSim, StateViews } from "@pebble3d/sdk/sim"; import { expect, it } from "vitest"; import courtJson from "../scenes/court.json"; import { BallSim, DemoBot, type TickInput } from "../src/sim.ts"; const wasm = readFileSync(new URL("../../../packages/sdk/wasm/det/engine_core_det_bg.wasm", import.meta.url)); it("the demo bot kicks the ball", async () => { const scene = parseScene(courtJson); const handle = await loadSim("deterministic", wasm, { seed: scene.sim.seed, gravity: scene.sim.gravity }); const ids = handle.spawnScene(expandScene(scene).sim); // sceneId -> sim id, "__ground" included const views = new StateViews(handle); const sim = new BallSim({ sim: handle, views, ids }); const bot = new DemoBot(); const input: TickInput = { kick: false }; for (let t = 0; t < 300; t++) { handle.world.step(1); views.refresh(); bot.next(sim, input); sim.step(input); } expect(sim.kicks).toBeGreaterThan(0); handle.world.free(); }); ``` ```bash npx vitest run --project hello-ball ``` More on headless spawning and reading state: [cookbook/json-levels-and-headless-verify.md](cookbook/json-levels-and-headless-verify.md#spawn-a-scene-and-read-state-in-node). ### Run and check it ```bash pnpm --filter hello-ball dev # http://localhost:5260 (Space kicks) or /?demo=1 (the bot plays) pnpm shot --app hello-ball --param demo=1 --ticks 300 --out artifacts/hello --name demo ``` The shot must exit 0. Open `artifacts/hello/demo.png` and check `artifacts/hello/demo.json`: `game.kicks` above 0, the same `stateHash` on every run. That `stateHash` equals `handle.world.stateHash()` after the same number of ticks of the Node loop above. Choosing `--ticks`: `--ticks n` captures right after engine tick n (fixed mode, one tick per frame), which is iteration n of the Node loop. To capture a moment (a goal, a result screen), run the loop in a test until the condition holds, note `t + 1`, and pass that plus a margin for anything you want visible after it, e.g. 30 ticks (0.5 s). See [cookbook/demo-bot-and-captures.md](cookbook/demo-bot-and-captures.md). ## Next - [verification.md](verification.md): shots, determinism, benches. - [troubleshooting.md](troubleshooting.md): when something fails. - [api-reference.md](api-reference.md): every `createGame` option, `Game` member and `World` method. - Next steps most games need: [cookbook/custom-camera.md](cookbook/custom-camera.md) (your own camera), [cookbook/owning-the-world.md](cookbook/owning-the-world.md) (worlds you create per round), [cookbook/sub-path-hosting.md](cookbook/sub-path-hosting.md) (deploying under a sub-path). - Real games to copy from: `apps/chain-reaction` (createGame plus its own worlds), `apps/rockfall` (custom boot, spawners, 1,800 bodies). ## Changing the physics (Rust) Only needed if you change the Rust crate in `crates/engine-core`. Install [rustup](https://rustup.rs) and `wasm-bindgen-cli` 0.2.130. `rust-toolchain.toml` pins Rust 1.94.1 (the toolchain the determinism hash was verified with) and the `wasm32-unknown-unknown` target, and rustup installs and selects them on first use inside the repo: ```bash cargo install wasm-bindgen-cli --version 0.2.130 --locked pnpm build:wasm # rebuilds packages/sdk/wasm/ and its SOURCE_HASH ``` Commit `packages/sdk/wasm/` with your Rust change. Until you rebuild, `pnpm test` fails with "Rust sources changed since the committed WASM was built". The build is reproducible, and CI rebuilds it and fails if the committed bytes differ. ===== AGENTS.md ===== # AGENTS.md Working rules for coding agents in the Pebble3D repo: where things are, the commands, the invariants you must not break, and what to run before you finish. Pebble3D is a browser 3D engine: JSON scenes validated by a zod schema, rendered by three.js 0.187 (WebGPU, WebGL fallback), simulated by Rapier compiled from Rust to WebAssembly. New here? Read [docs/getting-started.md](docs/getting-started.md) first. ## Skills For any request to make a game, start with `skills/make-a-game/SKILL.md` and follow it. It runs the other skills in this order: interview, brief, scaffold, build, game feel, art pass, complete loop, verify. | Skill | Use it for | | -------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | [make-a-game](skills/make-a-game/SKILL.md) | Entry point: interview, brief, scaffold, build, game feel, art pass, complete loop, verify. | | [game-interview](skills/game-interview/SKILL.md) | Turn a vague idea into a short design brief (with a non-interactive fallback). | | [start-a-game](skills/start-a-game/SKILL.md) | Scaffold a new app the way the demos are laid out and prove it boots. | | [verify-your-work](skills/verify-your-work/SKILL.md) | What done means: tests, captures, sidecars, looking at every image. | | [engine-pitfalls](skills/engine-pitfalls/SKILL.md) | Known engine traps as "if you see X, do Y". | | [game-feel](skills/game-feel/SKILL.md) | Hit-stop, shake, particles, buffering and sound that make actions land. | | [art-direction](skills/art-direction/SKILL.md) | Commit to one look and judge captures against it. | | [complete-game-loop](skills/complete-game-loop/SKILL.md) | Title, play, results, restart, a demo bot and a README. | | [genre-playbooks](skills/genre-playbooks/SKILL.md) | Per-genre recipes that reuse the shipped demo for that genre. | The same files are copied to `.claude/skills/`, where Claude Code, Cursor and GitHub Copilot discover project skills. Edit `skills/` only, then run `pnpm skills:sync`; a test fails if the copies are stale. ## Repo map | Path | What it is | | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `crates/engine-core` | Rust Rapier world compiled to wasm (`World`): spawn, step, state buffers, raycast, body control, state hash. Two builds: `deterministic` (default) and `fast` (SIMD). | | `packages/sdk` | `@pebble3d/sdk`: scene schema (`src/schema.ts`), `expandScene`, `loadSim`/`StateViews`, `FixedStepLoop`, `createGame`. Prebuilt wasm lands in `packages/sdk/wasm/` (gitignored). | | `packages/renderer` | `@pebble3d/renderer`: `createRenderer`, PBR/toon pipeline, splats, glTF, characters, camera controllers. | | `packages/studio-overlay` | `@pebble3d/studio-overlay`: the stats overlay (`mountOverlay`), toggled with the backtick key. | | `packages/mcp-server` | Placeholder, not implemented. | | `apps/playground` | Loads any scene in `apps/playground/scenes/` via `/?scene=`; owns `public/assets/` that every app serves. | | `apps/katana-defense` | Ronin Outpost (port 5180): toon horde defence, skinned crowds, IK. | | `apps/breakpoint` | Breakpoint (5210): physics demolition, sim in a Web Worker, `fast` build. | | `apps/ghostline` | Ghostline (5220): marble time trials, ghosts re-simulated from inputs. | | `apps/field-notes` | Field Notes (5231): photography in Gaussian-splat captures, depth of field. | | `apps/rockfall` | Rockfall (5240): survival under spawner-driven rock waves; boots renderer and sim itself. | | `apps/chain-reaction` | Chain Reaction (5250): JSON-level puzzle, headless Node verifier. | | `skills` | Agent skills: markdown playbooks for building a game, starting with `make-a-game`. Copied to `.claude/skills/` by `pnpm skills:sync`. | | `scripts/shot` | `pnpm shot`: build, serve, render in Chromium, write PNG + JSON sidecar. | | `scripts/docs` | `pnpm docs:gen`: regenerates the reference docs and `llms-full.txt`; drift-guard tests. | | `scripts/fetch-assets.mjs`, `scripts/assets` | Download and derive large assets per `apps/playground/assets.manifest.json`. | | `scripts/build-wasm.sh` | `pnpm build:wasm`: builds both wasm flavours with `wasm-bindgen-cli` 0.2.130. | ## Commands | Task | Command | | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | Install | `pnpm i` | | Build wasm (only after a Rust change) | `pnpm build:wasm` | | Fetch assets (HDRI, splats, avatars) | `pnpm fetch-assets` | | Playground dev server (port 5173) | `pnpm dev`, then `/?scene=showcase` | | One app's dev server | `pnpm --filter dev` (for example `pnpm --filter rockfall dev`) | | All TS tests | `pnpm test` (root vitest, every project) or `pnpm -r test` | | One project's tests | `npx vitest run --project rockfall` (a project must be listed in the root `vitest.config.ts`) | | Typecheck | `pnpm typecheck` | | Lint (biome) | `pnpm lint`; auto-fix with `npx biome check --write ` (never `--unsafe` on CSS: it deletes `!important`) | | Rust tests, both builds | `cargo test -p engine-core --features deterministic` and `cargo test -p engine-core --no-default-features --features fast` | | Determinism (Node) | `node --experimental-strip-types packages/sdk/test/determinism.mjs --expect "$(cat packages/sdk/test/fixtures/det-hash.txt)"` | | Screenshot | `pnpm shot --scene showcase --cam hero` or `pnpm shot --app rockfall --param demo=1 --ticks 600` | | Regenerate docs | `pnpm docs:gen` (not `pnpm docs`, which is a pnpm builtin); `pnpm docs:gen --check` exits 1 if stale | | Regenerate `scene.schema.json` after a schema edit | `pnpm --filter @pebble3d/sdk schema` | | Copy `skills/` to `.claude/skills/` | `pnpm skills:sync` | | Chain Reaction headless verify | `pnpm --filter chain-reaction verify` | Details: [docs/verification.md](docs/verification.md). ## Adding a new app 1. `apps//package.json` (scripts `dev`, `build`, `test: "vitest run"`, `typecheck`; deps `@pebble3d/sdk`, `@pebble3d/renderer` as `workspace:*`, `three` 0.187.0), `index.html` with ``. 2. Copy `apps/rockfall/vite.config.ts` and `apps/rockfall/tsconfig.json` unchanged. 3. Register its tests, or they never run: `apps//vitest.config.ts` with `defineProject({ test: { name: "", include: ["test/**/*.test.ts"] } })`, **and** an `"apps/"` entry in the root `vitest.config.ts` `projects` list. 4. `pnpm i`, then `npx vitest run --project `. 5. Node tests that must match the browser use the browser's tick order: with `createGame`, `world.step(1)` then the rules each tick. Walkthrough with every file: [docs/getting-started.md](docs/getting-started.md#3-a-minimal-game-app). ## Invariants - The determinism hash is `2d76d9927e780425`, from `packages/sdk/test/fixtures/det-hash.txt`. - No `Math.random` or `Date` in sim paths. - No per-frame allocation in hot paths. - Engine changes must be opt-in, with defaults unchanged. - The physics WASM is committed. Run `pnpm build:wasm` only after a Rust change, and commit `packages/sdk/wasm/` with it (`pnpm test` fails until you do). - `pnpm shot --out` must be inside `artifacts/`. - Linux Chromium needs `--enable-unsafe-webgpu --enable-features=Vulkan --use-angle=vulkan`. What they mean in practice: | Rule | How the repo does it | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Determinism | Sims draw randomness from a seeded generator (`apps/rockfall/src/game/rng.ts`). A random seed may be picked at boot outside the sim (`apps/rockfall/src/main.ts` uses `Date.now()` only in realtime mode; fixed mode uses seed 7). Never use `--write` on `determinism.mjs` to "fix" a mismatch. | | No per-frame allocation | Preallocate and reuse: event rings (`apps/chain-reaction/src/puzzle/sim.ts`), scratch reads via `game.views.scratch`. `world.bodyCounts()`, `world.transformOf()`, `__pebble3d.player()` and `position()` allocate: stats or debug only. | | Opt-in engine changes | New features default off (`post.style` defaults to `"pbr"`, `fixInternalEdges` defaults to false, `renderer.dof` starts disabled). The determinism hash and existing scenes must not change. | | Stale wasm | `packages/sdk/wasm/` is gitignored, so a pull or merge never updates it. See [docs/troubleshooting.md](docs/troubleshooting.md). | | Assets | Large files are not committed. Add them to `apps/playground/assets.manifest.json` with a sha256 and licence, then `pnpm fetch-assets` (it regenerates `apps/playground/public/assets/LICENSES.md`). Only licences that allow commercial use (CC0, CC BY, MIT); CC BY-NC captures were rejected. Apps serve the playground's `public/` via `publicDir: "../playground/public"` in their `vite.config.ts`. | ## Before you finish - [ ] `pnpm test` passes (and `cargo test` for both builds if you touched Rust). - [ ] `pnpm typecheck` and `pnpm lint` are clean. - [ ] The determinism script still prints `2d76d9927e780425`. - [ ] Rust changed: `pnpm build:wasm` ran, and the change is opt-in. - [ ] Schema changed: `pnpm --filter @pebble3d/sdk schema` and `pnpm docs:gen` ran, and their output is committed. - [ ] Rendering changed: a `pnpm shot` exits 0 with an empty console, and you looked at the PNG. - [ ] Game changed: its `?demo=1` bot still plays a full loop, and its `bench/capture-final.sh` still exits 0. - [ ] No `Math.random`/`Date` added to a sim, no allocation added to a per-frame path. ## Docs | Page | Use it for | | -------------------------------------------------- | --------------------------------------------------------------------------- | | [docs/getting-started.md](docs/getting-started.md) | A first scene, then a minimal game app. | | [docs/scene-reference.md](docs/scene-reference.md) | Every scene JSON field (generated). | | [docs/api-reference.md](docs/api-reference.md) | `@pebble3d/sdk`, `@pebble3d/renderer` and wasm `World` members (generated). | | [docs/verification.md](docs/verification.md) | `pnpm shot`, determinism checks, demo bots, fps benches. | | [docs/troubleshooting.md](docs/troubleshooting.md) | Error message or symptom, cause, fix. | ===== docs/scene-reference.md ===== # Scene reference Every field of a Pebble3D scene JSON file: type, default and meaning. Generated from `packages/sdk/scene.schema.json`. One table per object; nested objects are named by path (`entities[].body.collider`), `` is a record key, and `a | b` is a union or enum. ### scene | field | type | default | description | | --- | --- | --- | --- | | `$schema` | `string` | | | | `version` | `1` | `1` | | | `environment` | `object (environment)` | `{}` | | | `bounds` | `object (bounds)` | | Invisible static walls around [min, max] in XZ, from y = 0 up to `height`. | | `lighting` | `object (lighting)` | `{}` | | | `post` | `object (post)` | `{}` | | | `camera` | `object (camera)` | `{}` | | | `entities` | `object[] (entities[])` | `[]` | | | `sim` | `object (sim)` | `{}` | | | `prefabs` | `record)>` | `{}` | | ### environment | field | type | default | description | | --- | --- | --- | --- | | `preset` | `"outdoor" \| "studio"` | `"outdoor"` | | | `hdri` | `string` | | Equirect .hdr URL; the outdoor preset has a bundled default. | | `splat` | `object (environment.splat)` | | A Gaussian-splat capture (.spz, .ply, .splat or .ksplat) drawn with the meshes. Splats neither cast nor receive shadows; a shadow catcher at `floorY` shows mesh shadows on the capture floor. | | `fog` | `false \| object (environment.fog)` | | Range fog that hides the ground's far edge. `false` disables it. Defaults per preset (studio near 14 / far 42, outdoor near 25 / far 110). | | `backdrop` | `object (environment.backdrop)` | `{}` | Studio background: a vertical gradient from `horizon` (eye level and below) to `zenith` (overhead). Ignored by the outdoor preset. | | `ground` | `object (environment.ground)` | | Static ground plane collider, plus a visible plane unless `visible: false`. | ### environment.splat A Gaussian-splat capture (.spz, .ply, .splat or .ksplat) drawn with the meshes. Splats neither cast nor receive shadows; a shadow catcher at `floorY` shows mesh shadows on the capture floor. | field | type | default | description | | --- | --- | --- | --- | | `url` | `string (non-empty)` | required | | | `position` | `[number, number, number]` | `[0,0,0]` | | | `rotation` | `[number, number, number, number]` | `[0,0,0,1]` | | | `scale` | `number (> 0)` | `1` | | | `envFromSplat` | `boolean` | `false` | Image-based lighting from the capture: a cube capture at the splat's bounding-box centre, PMREM-filtered once at load. Replaces the preset's environment map (the background stays). | | `floorY` | `number` | `0` | World y of the capture's floor (after the transform); places the invisible shadow-catcher plane. | | `exposure` | `number (> 0)` | `1` | Splat colour multiplier (linear) before tone mapping. Compensates the tone mapper's compression; 1 = as captured. | | `saturation` | `number (>= 0)` | `1` | Splat colour saturation before tone mapping (1 = as captured). Compensates AgX desaturation. | ### environment.fog | field | type | default | description | | --- | --- | --- | --- | | `near` | `number (>= 0)` | | metres from the camera (view depth). Default: studio 14, outdoor 25. | | `far` | `number (>= 0)` | | Fully fogged from here. Default: studio 42, outdoor 110. | | `color` | `string` | | Default: studio = backdrop.horizon; outdoor = the HDRI's horizon colour in the view direction. | ### environment.backdrop Studio background: a vertical gradient from `horizon` (eye level and below) to `zenith` (overhead). Ignored by the outdoor preset. | field | type | default | description | | --- | --- | --- | --- | | `horizon` | `string` | `"#55504a"` | | | `zenith` | `string` | `"#141416"` | | ### environment.ground Static ground plane collider, plus a visible plane unless `visible: false`. | field | type | default | description | | --- | --- | --- | --- | | `y` | `number` | `0` | | | `size` | `number (> 0)` | `50` | | | `color` | `string` | `"#808080"` | | | `roughness` | `number (>= 0, <= 1)` | `0.9` | | | `visible` | `boolean` | `true` | | ### bounds Invisible static walls around [min, max] in XZ, from y = 0 up to `height`. | field | type | default | description | | --- | --- | --- | --- | | `min` | `[number, number]` | required | [x, z] | | `max` | `[number, number]` | required | [x, z] | | `height` | `number (> 0)` | `4` | | | `thickness` | `number (> 0)` | `0.5` | | ### lighting | field | type | default | description | | --- | --- | --- | --- | | `sun` | `object (lighting.sun)` | `{}` | | ### lighting.sun | field | type | default | description | | --- | --- | --- | --- | | `direction` | `[number, number, number]` | `[0.5,1,0.3]` | Direction from the scene towards the sun. | | `intensity` | `number (>= 0)` | `3` | | | `color` | `string` | `"#ffffff"` | | ### post | field | type | default | description | | --- | --- | --- | --- | | `exposure` | `number (> 0)` | `1` | | | `toneMapping` | `"agx" \| "aces" \| "none"` | `"agx"` | | | `bloom` | `object (post.bloom)` | `{}` | | | `ao` | `object (post.ao)` | `{}` | | | `style` | `"pbr" \| "toon"` | `"pbr"` | Art style. "toon": cel-banded mesh lighting (lit standard materials become ToonNodeMaterial), ink outlines from the mesh-only depth/normal prepass, and a posterised splat grade, tuned by `toon`. "pbr" (default) ignores `toon`. | | `toon` | `object (post.toon)` | `{}` | | ### post.bloom | field | type | default | description | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | | | `strength` | `number (>= 0)` | `0.3` | | | `threshold` | `number (>= 0)` | `2` | Linear HDR luminance (before tone mapping) a pixel must exceed to bloom. The default only catches specular highlights and emissives, not sunlit white surfaces. | ### post.ao | field | type | default | description | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | | | `radius` | `number (> 0)` | `0.5` | | ### post.toon | field | type | default | description | | --- | --- | --- | --- | | `bands` | `integer (>= 2, <= 8)` | `3` | Sun-light tones, shadow tone included. | | `shadowTone` | `number (>= 0, <= 1)` | `0` | Sun light kept by the darkest band (0 = ambient only). | | `terminator` | `number (>= -1, <= 1)` | `0` | Added to N·L before banding; > 0 widens the lit bands. | | `rim` | `number (>= 0)` | `0.35` | Sun-side rim light strength (per-material toonRim scales it). | | `rimWidth` | `number (>= 0, <= 1)` | `0.3` | | | `specular` | `number (>= 0)` | `0.6` | Stepped highlight strength (per-material toonSpecular scales it). | | `outline` | `object (post.toon.outline)` | `{}` | | | `splat` | `object (post.toon.splat)` | `{}` | | ### post.toon.outline | field | type | default | description | | --- | --- | --- | --- | | `enabled` | `boolean` | `true` | | | `width` | `number (> 0, <= 4)` | `1` | CSS pixels (scaled by the device pixel ratio). | | `color` | `string` | `"#1a1418"` | | | `opacity` | `number (>= 0, <= 1)` | `1` | | | `depthThreshold` | `number (> 0)` | `0.04` | Relative inverse-depth Laplacian that starts a line. | | `normalThreshold` | `number (> 0, <= 2)` | `0.35` | 1 - cos(angle) between neighbour normals that starts a crease line. | ### post.toon.splat | field | type | default | description | | --- | --- | --- | --- | | `levels` | `integer (>= 2, <= 32)` | `5` | Posterised lightness steps of the splat. | | `saturation` | `number (>= 0)` | `1.15` | | | `strength` | `number (>= 0, <= 1)` | `1` | Blend of the splat grade with the source colour. | | `shadowTint` | `string` | `"#4a5662"` | | | `highlightTint` | `string` | `"#fff2df"` | | ### camera | field | type | default | description | | --- | --- | --- | --- | | `controller` | `"thirdPerson" \| "orbit" \| "fly"` | `"orbit"` | | | `presets` | `record)>` | `{}` | | ### camera.presets. | field | type | default | description | | --- | --- | --- | --- | | `position` | `[number, number, number]` | required | | | `target` | `[number, number, number]` | `[0,0,0]` | | | `fov` | `number (> 0)` | `50` | | ### entities[] | field | type | default | description | | --- | --- | --- | --- | | `id` | `string (non-empty)` | required | | | `prefab` | `string` | | Prefab deep-merged under this entity (entity fields win). | | `transform` | `object (entities[].transform)` | | | | `mesh` | `object (entities[].mesh)` | | Exactly one of `primitive` or `gltf`. | | `body` | `object (entities[].body)` | | | | `character` | `object (entities[].character)` | | Requires a kinematic body with a capsule collider. | | `spawner` | `object (entities[].spawner)` | | | ### entities[].transform | field | type | default | description | | --- | --- | --- | --- | | `position` | `[number, number, number]` | `[0,0,0]` | | | `rotation` | `[number, number, number, number]` | `[0,0,0,1]` | Quaternion [x, y, z, w]. | | `scale` | `[number (> 0), number (> 0), number (> 0)]` | `[1,1,1]` | Primitives are unit-sized (box 1x1x1, sphere diameter 1, capsule diameter x by total height y, cylinder diameter x by height y), so scale is their size in metres. | ### entities[].mesh Exactly one of `primitive` or `gltf`. | field | type | default | description | | --- | --- | --- | --- | | `primitive` | `"box" \| "sphere" \| "capsule" \| "plane" \| "cylinder"` | | | | `gltf` | `object (entities[].mesh.gltf)` | | | | `material` | `object (entities[].mesh.material)` | | | | `castShadow` | `boolean` | `true` | | ### entities[].mesh.gltf | field | type | default | description | | --- | --- | --- | --- | | `url` | `string (non-empty)` | required | | | `animations` | `record<"idle" \| "walk" \| "run" \| "jump" \| "fall", string \| object (entities[].mesh.gltf.animations.)>` | | Animation state -> clip name, or { clip, speed? } in the glTF. | | `look` | `object (entities[].mesh.gltf.look)` | | Per-model look tweaks. | ### entities[].mesh.gltf.animations. | field | type | default | description | | --- | --- | --- | --- | | `clip` | `string (non-empty)` | required | | | `speed` | `number (> 0)` | | Authored ground speed of the clip, m/s. | ### entities[].mesh.gltf.look Per-model look tweaks. | field | type | default | description | | --- | --- | --- | --- | | `envIntensity` | `number (>= 0)` | | | | `saturation` | `number (>= 0, <= 2)` | | | ### entities[].mesh.material | field | type | default | description | | --- | --- | --- | --- | | `color` | `string` | `"#cccccc"` | | | `roughness` | `number (>= 0, <= 1)` | `0.5` | | | `metalness` | `number (>= 0, <= 1)` | `0` | | | `emissive` | `string` | | | ### entities[].body | field | type | default | description | | --- | --- | --- | --- | | `type` | `"dynamic" \| "static" \| "kinematic"` | | Default 'dynamic', or 'kinematic' when the entity has a `character`. | | `mass` | `number (> 0)` | | kg. Default: from collider volume at density 1. | | `friction` | `number (>= 0)` | `0.5` | | | `restitution` | `number (>= 0)` | `0` | | | `linearDamping` | `number (>= 0)` | `0` | | | `angularDamping` | `number (>= 0)` | `0` | | | `ccd` | `boolean` | `false` | | | `collider` | `"auto" \| { shape: "box" } \| { shape: "sphere" } \| { shape: "capsule" } \| { shape: "convexHull" } \| { shape: "trimesh" } \| { shape: "plane" }` | `"auto"` | 'auto' fits the mesh primitive and scale; for glTF it becomes a convex hull computed in JS. | ### entities[].body.collider (shape: "box") | field | type | default | description | | --- | --- | --- | --- | | `shape` | `"box"` | required | | | `halfExtents` | `[number (> 0), number (> 0), number (> 0)]` | required | | ### entities[].body.collider (shape: "sphere") | field | type | default | description | | --- | --- | --- | --- | | `shape` | `"sphere"` | required | | | `radius` | `number (> 0)` | required | | ### entities[].body.collider (shape: "capsule") | field | type | default | description | | --- | --- | --- | --- | | `shape` | `"capsule"` | required | | | `halfHeight` | `number (> 0)` | required | | | `radius` | `number (> 0)` | required | | ### entities[].body.collider (shape: "convexHull") | field | type | default | description | | --- | --- | --- | --- | | `shape` | `"convexHull"` | required | | | `points` | `number[]` | required | | ### entities[].body.collider (shape: "trimesh") | field | type | default | description | | --- | --- | --- | --- | | `shape` | `"trimesh"` | required | | | `vertices` | `number[]` | required | | | `indices` | `(integer (>= 0))[]` | required | | | `fixInternalEdges` | `boolean` | | Smooth contacts across triangle seams (a rolling ball does not bump on internal edges). Default false. | ### entities[].body.collider (shape: "plane") | field | type | default | description | | --- | --- | --- | --- | | `shape` | `"plane"` | required | | ### entities[].character Requires a kinematic body with a capsule collider. | field | type | default | description | | --- | --- | --- | --- | | `speed` | `number (> 0)` | `4` | Walk speed, m/s. | | `sprintSpeed` | `number (> 0)` | `7` | m/s. | | `jumpSpeed` | `number (>= 0)` | `5.5` | Initial upward velocity, m/s. | | `maxSlopeDeg` | `number (> 0, < 90)` | `45` | | | `stepHeight` | `number (>= 0)` | `0.35` | metres. | | `snap` | `number (>= 0)` | `0.3` | Ground snap distance, metres. | | `accel` | `number (>= 0)` | `0` | Horizontal acceleration toward the input velocity, m/s². Starts, stops and turns ramp instead of snapping; 0 (default) changes velocity instantly. | | `ridePlatforms` | `boolean` | `false` | Opt-in: while grounded on a kinematic body (a moving or rotating platform driven by `setKinematicPose`), move with it exactly and keep its velocity as momentum when jumping or walking off. Without it, walking on a kinematic body is unreliable. | ### entities[].spawner | field | type | default | description | | --- | --- | --- | --- | | `prefab` | `string` | required | Prefab to spawn; it must have a `body`. | | `rate` | `number (>= 0)` | required | Spawns per second. | | `count` | `integer (>= 0)` | required | Total spawns. | | `area` | `object (entities[].spawner.area)` | required | World-space box spawns land in, uniformly. | | `seed` | `integer (>= 0, <= 4294967295)` | | Default: sim.seed + entity index. | ### entities[].spawner.area World-space box spawns land in, uniformly. | field | type | default | description | | --- | --- | --- | --- | | `min` | `[number, number, number]` | required | | | `max` | `[number, number, number]` | required | | ### sim | field | type | default | description | | --- | --- | --- | --- | | `build` | `"deterministic" \| "fast"` | `"deterministic"` | | | `seed` | `integer (>= 0, <= 4294967295)` | `1` | | | `gravity` | `number` | `-9.81` | | ### prefabs. | field | type | default | description | | --- | --- | --- | --- | | `transform` | `object (entities[].transform)` | | | | `mesh` | `object (entities[].mesh)` | | Exactly one of `primitive` or `gltf`. | | `body` | `object (entities[].body)` | | | | `character` | `object (entities[].character)` | | Requires a kinematic body with a capsule collider. | ===== docs/api-reference.md ===== # API reference How to drive the engine from TypeScript: `createGame`, the `Game` object, the wasm `World`'s state and scratch buffers, raycasts and the `window.__pebble3d` probe. The member lists further down are generated by `pnpm docs:gen`. Task-sized examples: [cookbook/](cookbook/README.md). Where each feature is used in the games: [examples.md](examples.md). ## Imports | Import | What you get | | --- | --- | | `@pebble3d/sdk/game` | `createGame`, `Game`, `PlayerRig`, `Pebble3DHook` | | `@pebble3d/sdk/schema` | `parseScene`, `SceneSchema`, `SceneInput`, `mergePrefab`, `resolveCollider` | | `@pebble3d/sdk/expand` | `expandScene` (scene to sim descs and render entities) | | `@pebble3d/sdk/sim` | `loadSim`, `StateViews`, `SCRATCH_LEN` | | `@pebble3d/sdk/loop` | `FixedStepLoop` | | `@pebble3d/sdk/input` | `cameraRelativeInput` | | `@pebble3d/sdk/types` | `GameStats`, `EntityDescJson` (the JSON `World.spawn` takes) | | `@pebble3d/renderer` | `createRenderer`, controllers, `ToonNodeMaterial`, `InstanceRegistry`, state-flag constants | | `@pebble3d/studio-overlay` | `mountOverlay(game, el?, { startVisible })`: the stats overlay | Wasm URLs come from Vite `?url` imports of `packages/sdk/wasm/det/engine_core_det_bg.wasm` and `packages/sdk/wasm/fast/engine_core_fast_bg.wasm` (see [getting-started.md](getting-started.md#srcmaints-boot-input-probes)). ## createGame `createGame(opts)` parses and expands the scene, loads the wasm build named by `scene.sim.build`, spawns every entity, builds the renderer and the entity visuals, and returns a `Game`. It does not start: call `game.start()`. Source: `packages/sdk/src/game.ts`. | Option | Type | Default | Meaning | | --- | --- | --- | --- | | `canvas` | `HTMLCanvasElement` | required | Render target. Sized from `clientWidth`/`clientHeight` (DPR capped at 2) and re-sized by a `ResizeObserver`. | | `scene` | `SceneInput` | required | Scene JSON. Validated with `parseScene`; a bad scene throws `SceneError` with the field path. | | `wasmUrls` | `{ deterministic: string; fast: string }` | required | URLs of both `_bg.wasm` builds; only the one `scene.sim.build` names is loaded. | | `mode` | `"realtime" \| "fixed"` | `"realtime"` | `realtime`: ticks follow wall time, at most 5 per frame (the excess is dropped). `fixed`: exactly one tick per frame, render alpha 1 (screenshots, reproducible captures). | | `stopAtTick` | `number` | none | Fixed mode only: the sim stops advancing at this tick and `__pebble3d.done` turns true once that frame has rendered. | | `backend` | `"webgpu" \| "webgl"` | `"webgpu"` | A WebGPU request that falls back throws `BackendUnavailable: webgpu`; retry on a fresh canvas with `"webgl"` (`apps/playground/src/main.ts`, lines 200-212). | | `splatOnly` | `boolean` | `false` | Debug: draw only the splat, no meshes or post. | | `assetBase` | `string` | `VITE_PEBBLE3D_ASSET_BASE`, else Vite's `BASE_URL`, else `"/"` | Prefix for root-absolute asset URLs (`/assets/...` in the scene, `renderer.loadGltf`, the `/basis/` transcoder). See [cookbook/sub-path-hosting.md](cookbook/sub-path-hosting.md). | | `webglFallback` | `boolean` | on only with `VITE_PEBBLE3D_WEBGL_FALLBACK=1` or `?webglFallback=1` | When WebGPU is missing, keep WebGL on the same canvas (with a small notice) instead of throwing `BackendUnavailable`. | What happens each frame, in order: 1. `FixedStepLoop.advance` decides the tick count; `world.step(n)` runs them. 2. Bodies created by spawners are drained (`drainSpawned`) and given visuals (`renderer.addSpawned`). 3. `views.refresh()`, then `renderer.sync(prev, curr, alpha)` interpolates every body. 4. The player callback reads `characterState`, updates the character view and third-person camera, and sends `setCharacterInput` for the **next** tick. 5. Your `onFrame` callbacks run, in registration order. 6. `renderer.render(dt)`; `__pebble3d.frame`/`tick`/`ready`/`done` update. There is no per-tick hook. To run game rules once per tick, either count `world.tick()` inside `onFrame` (getting-started's `while (sim.tick < world.tick())`) or own the loop (see [cookbook/deterministic-game-loop.md](cookbook/deterministic-game-loop.md)). ## The Game object | Member | Meaning | | --- | --- | | `start()` / `stop()` | Start or cancel the `requestAnimationFrame` loop. `start()` twice is a no-op. | | `sim` | `SimHandle`: `world` (the wasm `World`), `memory` (its `WebAssembly.Memory`), `build`, `seed`, `spawnScene(entries)`. | | `views` | `StateViews`: `prev`, `curr` (Float32Array, 8 floats per slot), `scratch` (Float32Array of `SCRATCH_LEN`), `capacity`, `refresh()`. | | `ids` | `Map`. Includes the generated `__ground` and `__bounds.` statics. Spawner-created bodies are not in it. | | `player` | `PlayerRig \| null`, the scene's first entity with a `character`: `simId`, `view` (a `CharacterView`), `camera` (`ThirdPersonController` when `camera.controller` is `"thirdPerson"`, else null), `input` (`{ keys: { f, b, l, r }, jump, sprint }`). Keyboard listeners (WASD/arrows, Space, Shift) write `input`; scripts and bots may write it directly. Every frame, 0-tick frames included, `input` is sent with `setCharacterInput`, overwriting any `setCharacterInput` your code made for this character (re-send yours at the end of `onFrame`). Other characters get no animation until you call `renderer.attachCharacter` ([cookbook/character-and-camera.md](cookbook/character-and-camera.md)). | | `renderer` | `EngineRenderer`: `three` (`renderer`, `scene`, `camera`), `controller` (settable: `dispose()` it and set `null` to own the camera, [cookbook/custom-camera.md](cookbook/custom-camera.md)), `instances`, `dof`, `splatColor`, `style`, `stylize(root)`, `loadGltf(url)`, `assetUrl(url)`, `attachCharacter(simId, clipMap)`, `setCameraPreset(name)`, `reportError(msg)`. | | `onFrame(cb)` | `cb(dt)` every frame after `renderer.sync`, before `render`. `dt` is wall seconds in realtime and `ticks / 60` in fixed mode (`1/60`, or 0 once stopped). | | `setCamera(name)` | A camera preset from `camera.presets`, or `"controller"` to hand back to the scene's controller. A preset suspends the third-person camera; the player still moves relative to its yaw. | | `stats()` | `GameStats` (fps, frameMs, drawCalls, triangles, splats, physicsMs, activeBodies, sleepingBodies, build, tick, errors). Returns the same mutated object every call. | Read state from `views` only after `views.refresh()`: wasm memory can grow on any spawn, which detaches old typed-array views (they then read as empty, `byteLength` 0). `createGame` refreshes once per frame before `onFrame`; refresh again after you spawn or step yourself. Every world made from the same wasm module shares one memory, so a spawn in one world detaches the views of all the others. Read `views.curr` and `views.scratch` from the `views` object each time; a `Float32Array` kept in a local or a field across calls goes stale. ## State buffers Each body with a slot occupies 8 `f32` in both `views.prev` and `views.curr` (`STATE_STRIDE = 8`, the renderer's mirror in `packages/renderer/src/dynamics/instances.ts` of the Rust `STRIDE` in `crates/engine-core/src/slots.rs`). Get the slot with `world.slotOf(simId)` (-1 if none); slots are reused after `despawn`. | Offset | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Value | `px` | `py` | `pz` | `qx` | `qy` | `qz` | `qw` | `flags` | | Flag bit | Value | Meaning | | --- | --- | --- | | `ACTIVE` | 1 | The slot holds a live body (a freed slot reads 0). | | `SLEEPING` | 2 | Rapier put the body to sleep. | | `NO_INTERP` | 4 | Snap, don't interpolate: set on spawn and by `teleport`, cleared after the next tick. | The flags are stored as a float; read them with `views.curr[slot * 8 + 7] & 4` style integer tests (JS converts). The constants are exported from `@pebble3d/renderer` (`ACTIVE`, `SLEEPING`, `NO_INTERP`, `STATE_STRIDE`). `readSlot(prev, curr, slot, alpha, outPos, outQuat)` writes the interpolated pose and honours `NO_INTERP`. `prev` is the pose before the last tick, so `prev + (curr - prev) * alpha` is the render pose. ## Scratch buffer Query methods write results into a fixed `SCRATCH_LEN` (24) float region at `world.scratchPtr()` and return `true`; `views.scratch` is a view over it. They return `false` and leave the scratch untouched when the id is unknown (or not a character, for `characterState`). Read the values right away: the next query overwrites them. | Method | Writes | Indices | | --- | --- | --- | | `raycast(...)` | `toi, nx, ny, nz, hitId` | `[0..5)` | | `characterState(id)` | `grounded (0/1), vx, vz, vy` (note the order: vz before vy) | `[8..12)` | | `linearVelocity(id)` | `vx, vy, vz` (m/s) | `[12..15)` | | `angularVelocity(id)` | `wx, wy, wz` (rad/s) | `[16..19)` | `world.scratchLen()` returns 24 and the sdk's `SCRATCH_LEN` mirrors it (a test checks the match). Indices 5-7, 15 and 19-23 are unused. ## Raycasts ```ts const hit = world.raycast(ox, oy, oz, dx, dy, dz, maxToi, filter, excludeId); if (hit) { const sc = game.views.scratch; const dist = sc[0], hitId = sc[4]; // normal: sc[1], sc[2], sc[3] } ``` | `filter` | Hits | `excludeId` | | --- | --- | --- | | `0` | every collider | ignored (pass 0) | | `1` | static bodies only (ground, bounds, static entities) | ignored | | `2` | everything except the body of `excludeId` | the entity to skip (the caster itself) | The direction is normalised for you, so `toi` is metres. `hitId` is the entity id (compare with `game.ids`). Raycasts see the broad phase as of the last `step`: a body spawned since then is invisible until the next tick, and a world that has never stepped misses everything, static floor included. Step a new world once before probing it. A zero direction or `maxToi <= 0` returns false. The third-person camera uses filter 1 so moving props never pull the camera in. ## Body control All take the entity id and return `false` for unknown ids or the wrong body type. | Method | Works on | Effect | | --- | --- | --- | | `applyImpulse(id, ix, iy, iz)` | dynamic | Adds `impulse / mass` to the velocity (N·s); wakes the body. | | `applyTorqueImpulse(id, tx, ty, tz)` | dynamic | Angular impulse in **world** axes (N·m·s); the angular velocity changes by the inverse world-space inertia times it. Wakes the body. | | `setVelocity(id, vx, vy, vz, wx, wy, wz)` | dynamic | Sets linear and angular velocity; wakes the body. | | `setKinematicPose(id, px, py, pz, qx, qy, qz, qw)` | kinematic | Target pose, reached on the next step. Position and rotation only: colliders cannot be rescaled after spawn. | | `teleport(id, x, y, z)` | any with a body | Moves instantly, zeroes a dynamic body's velocity, sets `NO_INTERP`. Returns nothing. | | `setCharacterInput(id, wx, wz, jump, sprint)` | character | World-space XZ direction (clamped to length 1). `createGame` overwrites it every frame for `game.player`. | | `spawn(json)` / `despawn(id)` | | `spawn` takes an `EntityDescJson` string (camelCase: `position`, `rotation`, `body: { type, mass, friction, restitution, linearDamping, angularDamping, ccd, collider }`, `character`, `spawner`) and returns the id; it throws on bad JSON. Bodies spawned this way get no visual: add one yourself. | Default mass is collider volume at density 1 (a 1 m box is 1 kg, a 0.5 m radius sphere about 0.52 kg). The inertia tensor comes from the collider shape at uniform density; an explicit `mass` scales it with the mass. Damping defaults to 0, and Rapier has no rolling resistance, so a rolling sphere needs `angularDamping` to ever stop ([cookbook/bodies-impulses-velocity.md](cookbook/bodies-impulses-velocity.md)). There are no contact or collision events. Detect hits in your rules after each step from positions and velocities (overlap distance, closing speed, an unexplained one-tick velocity change); the bodies recipe has the patterns and the games that use them. ## The `window.__pebble3d` probe `createGame` installs it; `pnpm shot` and benches read it ([verification.md](verification.md)). | Field | Meaning | | --- | --- | | `ready` | True once the first frame rendered. | | `done` | Fixed mode: true once the frame at `stopAtTick` rendered. | | `frame`, `tick` | Frames rendered, current sim tick. | | `stats()` | `GameStats`. | | `adapterInfo` | `{ backend, vendor, architecture, device, description }`; `pnpm shot` refuses SwiftShader. | | `stateHash()` | `world.stateHash()`: 16 hex chars, FNV-1a 64 over the sim state. | | `setCamera(name)` | As `game.setCamera`. | | `player()` | `{ position, grounded, velocity, anim, modelMinY, camera, arm }` or null. Allocates. | | `position(sceneId)` | `[x, y, z]` of a scene entity's body, or null. Allocates. | | `error` | Set by your `main().catch` so automation reports the failure instead of timing out. | Add game probes with `Object.assign(window.__pebble3d ?? {}, { game: { score: () => sim.score } })`. `pnpm shot` calls every function in `game` and writes the results to the sidecar. An app that runs its game in its own worlds (Chain Reaction, Ringout, Pebble Garden) must override `stateHash` the same way, `Object.assign(window.__pebble3d ?? {}, { stateHash: () => myWorld.stateHash() })`, or every capture reports `createGame`'s idle world and the hash never changes ([cookbook/owning-the-world.md](cookbook/owning-the-world.md)). An app that boots without `createGame` must install the whole hook itself: `ready`, `done`, `frame`, `tick`, `stats`, `adapterInfo`, `stateHash`, `setCamera` (`apps/rockfall/src/main.ts`, lines 274-322). ## Validating scenes `parseScene(input)` (and `createGame`) throws a `SceneError` for the **first** problem only, with its `path` (`entities[3].prefab`). To list every problem at once (an editor, an import dialog, a level linter), call `SceneSchema.safeParse(input)` and walk `error.issues`; `formatPath(issue.path)` gives the same path text: ```ts import { formatPath, SceneSchema } from "@pebble3d/sdk/schema"; const r = SceneSchema.safeParse(json); if (!r.success) for (const i of r.error.issues) console.log(`${formatPath(i.path)}: ${i.message}`); ``` Validation runs in two passes. The cross-field checks (duplicate ids, unknown prefabs, "entity needs a mesh, body or spawner", collider/body combinations) run only once the whole scene passes the field-level schema, so a scene with a bad field reports only field errors; fix those and the cross-field errors appear on the next run. ## Booting without createGame For a sim that owns its world (bodies created in code, a different tick rate cap, a worker), compose the parts as `apps/rockfall/src/main.ts` does (lines 180-199 and 324-411): ```ts const scene = parseScene(sceneJson); const x = expandScene(scene); // x.settings feeds the renderer; x.sim are the spawn descs const [handle, renderer] = await Promise.all([ loadSim(scene.sim.build, wasmUrl, { seed: scene.sim.seed, gravity: scene.sim.gravity }), createRenderer(canvas, x.settings, { backend: "webgpu" }), ]); const loop = new FixedStepLoop({ mode, maxTicksPerFrame: 2 }); // per frame: adv = loop.advance(dt, tick); step adv.ticks times; // views.refresh(); renderer.sync(views.prev, views.curr, adv.alpha); renderer.render(dt); ``` In Node, pass the wasm bytes instead of a URL: `loadSim("deterministic", readFileSync(".../engine_core_det_bg.wasm"))` (`apps/chain-reaction/src/puzzle/node-engine.ts`). More worlds in the same module: `new (handle.world.constructor)(seed, gravity)`; each needs its own `StateViews`-style views and must be `free()`d (`apps/ghostline/src/game/physics.ts`). ## Headless: SimHandle, SimEntry, StateViews The `@pebble3d/sdk/sim` types you need to run a scene in Node (or own the world in the browser). Full worked example: [cookbook/json-levels-and-headless-verify.md](cookbook/json-levels-and-headless-verify.md#spawn-a-scene-and-read-state-in-node). | Name | Shape | Notes | | --- | --- | --- | | `loadSim(build, wasm, opts?)` | `Promise` | `wasm` is a URL (browser, async fetch) or the `_bg.wasm` bytes (Node, sync init). `opts`: `{ seed?: number; gravity?: number }`, defaults 1 and -9.81; pass `scene.sim.seed` / `scene.sim.gravity` to match `createGame`. | | `SimHandle` | `{ world: World; memory: WebAssembly.Memory; build: SimBuild; seed: number; spawnScene(entries: SimEntry[]): Map }` | `spawnScene` spawns in order and returns sceneId -> sim id (the same map as `game.ids`). | | `SimEntry` (`@pebble3d/sdk/types`) | `{ sceneId: string; desc: EntityDescJson }` | What `expandScene(scene).sim` holds: `__ground`, then `__bounds.`, then each entity. `desc` is the JSON `World.spawn` parses (`spawnScene` calls `world.spawn(JSON.stringify(e.desc))`). Entries listed in `pendingHulls` need glTF hull points first; Node skips them. | | `new StateViews(handle)` | `prev`, `curr`, `scratch` (`Float32Array`), `capacity`, `refresh(): boolean` | Needs only `handle.world` and `handle.memory`, so a second world gets views with `new StateViews({ ...handle, world: w2 })`. Call `refresh()` after spawning or stepping before reading. | Reading a body: `slot = world.slotOf(id)`, position `views.curr[slot * 8 + 0..2]` ([State buffers](#state-buffers)); velocity `if (world.linearVelocity(id))` then `views.scratch[12..14]` ([Scratch buffer](#scratch-buffer)). In tests, `world.transformOf(id)` returns `[px, py, pz, qx, qy, qz, qw]` (allocates). Tick order: `createGame` steps physics and then calls `onFrame`, so a headless run that must reproduce a `createGame` app's `stateHash` does `world.step(1); views.refresh();` and then the rules, every tick ([getting-started.md](getting-started.md#tick-order)). ## Generated member lists Every export of each package, and every `World` method, regenerated from source by `pnpm docs:gen`. ## @pebble3d/sdk ### @pebble3d/sdk/types Source: `packages/sdk/src/types.ts` | export | kind | type | summary | | --- | --- | --- | --- | | `BodyJson` | interface | | | | `CharacterJson` | interface | | | | `ColliderJson` | type | | | | `EntityDescJson` | interface | `{ name?: string; position: Vec3; rotation: Quat; body?: BodyJson \| null; character?: CharacterJson \| null; spawner?: SpawnerJson \| null }` | | | `ExpandedScene` | interface | `{ settings: RenderSettings; sim: SimEntry[]; render: RenderEntity[]; pendingHulls: string[] }` | | | `GameStats` | interface | | | | `Quat` | type | `[number, number, number, number]` | | | `RenderEntity` | interface | | | | `RenderSettings` | interface | | | | `RenderStats` | interface | `{ fps: number; frameMs: number; drawCalls: number; triangles: number; splats: number; textureMB?: number; backend: 'webgpu'\|'webgl' }` | | | `SimEntry` | interface | `{ sceneId: string; desc: EntityDescJson }` | | | `SpawnerJson` | interface | `{ template: EntityDescJson; rate: number; count: number; areaMin: Vec3; areaMax: Vec3; seed: number }` | | | `Vec3` | type | `[number, number, number]` | | ### @pebble3d/sdk/schema Source: `packages/sdk/src/schema.ts` | export | kind | type | summary | | --- | --- | --- | --- | | `ANIM_STATES` | const | `readonly ["idle", "walk", "run", "jump", "fall"]` | | | `ColliderResult` | type | `{ collider: ColliderJson; pendingHull: boolean } \| { error: string }` | | | `ENTITY_DEFAULTS` | const | | | | `ENV_DEFAULTS` | const | | Per-preset environment defaults, resolved by `expandScene` (they depend on `preset`). | | `PRIMITIVES` | const | `readonly ["box", "sphere", "capsule", "plane", "cylinder"]` | | | `Prefab` | type | `z.output` | | | `Scene` | type | `z.output` | | | `SceneEntity` | type | `z.output` | | | `SceneError` | class | `new (path: string, message: string)` | | | `SceneInput` | type | `z.input` | | | `SceneSchema` | const | | | | `bodyType` | function | `(e: Prefab) => "dynamic" \| "static" \| "kinematic"` | | | `deepMerge` | function | `>(base: Partial, over: T) => T` | Recursive merge; `over` wins. | | `formatPath` | function | `(path: readonly PropertyKey[]) => string` | | | `mergePrefab` | function | `(scene: Pick, e: SceneEntity) => SceneEntity` | The entity with its prefab (if any) merged underneath. | | `parseScene` | function | `(input: unknown) => Scene` | Validates a scene and fills defaults. | | `resolveCollider` | function | `(e: Prefab) => ColliderResult` | Resolves `collider` (explicit or `'auto'`) for an entity or prefab that has a body. | ### @pebble3d/sdk/expand Source: `packages/sdk/src/expand.ts` | export | kind | type | summary | | --- | --- | --- | --- | | `expandScene` | function | `(scene: Scene) => ExpandedScene` | Turns a parsed scene into sim descs (spawned in order: ground, bounds, then entities) and render entities. | ### @pebble3d/sdk/sim Source: `packages/sdk/src/sim.ts` | export | kind | type | summary | | --- | --- | --- | --- | | `LoadSimOptions` | interface | `{ seed?: number; gravity?: number }` | | | `SCRATCH_LEN` | const | `24` | Floats in the wasm query scratch region; mirrors engine-core `SCRATCH_LEN`. | | `SimBuild` | type | `"deterministic" \| "fast"` | | | `SimHandle` | interface | `{ world: World; memory: WebAssembly.Memory; build: SimBuild; seed: number; spawnScene(sim: SimEntry[]): Map }` | | | `StateViews` | class | `new (h: SimHandle)` | Typed-array views over the wasm state buffers; rebuilt when memory moves or grows. | | `loadSim` | function | `(build: SimBuild, wasm: BufferSource \| string, opts: LoadSimOptions = {}) => Promise` | Loads one wasm build. | ### @pebble3d/sdk/loop Source: `packages/sdk/src/loop.ts` | export | kind | type | summary | | --- | --- | --- | --- | | `FixedStepLoop` | class | `new (opts: FixedStepOptions)` | | | `FixedStepOptions` | interface | `{ mode: "realtime" \| "fixed"; dt?: number; maxTicksPerFrame?: number; stopAtTick?: number }` | | ### @pebble3d/sdk/game Source: `packages/sdk/src/game.ts` | export | kind | type | summary | | --- | --- | --- | --- | | `AdapterInfo` | interface | `{ backend: "webgpu" \| "webgl"; vendor: string; architecture: string; device: string; description: string }` | | | `CreateGameOptions` | interface | | | | `Game` | interface | | | | `Pebble3DHook` | interface | | Test/automation hook installed on `window.__pebble3d` (read by the shot CLI). | | `PlayerInput` | interface | `{ keys: MoveKeys; jump: boolean; sprint: boolean }` | The player's held input. | | `PlayerProbe` | interface | | | | `PlayerRig` | interface | `{ simId: number; view: CharacterView; camera: ThirdPersonController \| null; input: PlayerInput }` | The scene's first character, driven by `input` every frame. | | `createGame` | function | `(opts: CreateGameOptions) => Promise` | Builds a running game from a scene: parse, expand, load the sim build, spawn, build the renderer and entity visuals, then drive the fixed-step loop from requestAnimationFrame. | ### @pebble3d/sdk/input Source: `packages/sdk/src/input.ts` | export | kind | type | summary | | --- | --- | --- | --- | | `MoveKeys` | interface | `{ f: boolean; b: boolean; l: boolean; r: boolean }` | | | `cameraRelativeInput` | function | `(keys: MoveKeys, yaw: number, out: Float32Array) => void` | Turns WASD-style keys into a normalised world-space XZ move direction relative to the camera yaw (radians about +Y; yaw 0 looks down -Z). | ## @pebble3d/renderer Source: `packages/renderer/src/index.ts` | export | kind | type | summary | | --- | --- | --- | --- | | `ACTIVE` | const | `1` | | | `AO_RESOLUTION_SCALE` | const | `0.5` | | | `AnimClipSpec` | interface | `{ clip: string; speed?: number }` | | | `AnimState` | type | `'idle'\|'walk'\|'run'\|'jump'\|'fall'` | | | `ArmRaycast` | type | `(origin: Vector3, dir: Vector3, max: number) => number \| null` | Ray query used by the spring arm: origin, unit direction, max distance -> hit toi or null. | | `CROSSFADE_SECONDS` | const | `0.2` | Cross-fade length between animation states, seconds. | | `CSM_CASCADES` | const | `3` | Cascaded shadow map settings: 3 cascades, maxFar 120, practical splits, lightMargin 20. | | `CSM_LIGHT_MARGIN` | const | `20` | | | `CSM_MAX_FAR` | const | `120` | | | `CameraController` | interface | `{ update(dt: number): void; setPose(position: Vector3, target: Vector3): void; enabled: boolean; dispose(): void }` | Common shape of the camera controllers. | | `CharacterFrame` | interface | `{ grounded: boolean; vx: number; vz: number; vy: number; sprintSpeed: number }` | | | `CharacterView` | class | `new (root: Object3D, clips: AnimationClip[], clipMap: Partial>)` | Drives one character's visuals from its sim state: a state machine over the mapped clips (0.2 s cross-fades, only on a state change) and a facing that slerps toward `atan2(vx, vz)` while moving faster than 0.1 m/s (the model faces +Z at yaw 0). | | `DOF_DEFAULTS` | const | `{ readonly focus: 5; readonly range: 3; readonly bokeh: 1; readonly backdrop: 30; }` | | | `DepthOfFieldControls` | interface | `{ enabled: boolean; focus: { value: number }; range: { value: number }; bokeh: { value: number }; backdrop: { value: number } }` | Opt-in depth of field (photo modes). | | `EngineRenderer` | interface | | | | `EquirectImage` | interface | `{ data: Uint16Array \| Float32Array; width: number; height: number }` | Minimal view of a decoded equirect `DataTexture` image (RGBA, half or 32-bit float). | | `FALLBACK_NOTICE_ID` | const | `"pebble3d-webgl-notice"` | `id` of the notice element, so it is shown at most once per page. | | `FALLBACK_NOTICE_TEXT` | const | | | | `FlyController` | class | `new (camera: PerspectiveCamera, dom: HTMLElement)` | Fly camera: WASD to move, Q/E (or Space/C) down/up, Shift to go fast, drag with a mouse button to look. | | `IDLE_SPEED` | const | `0.1` | Below this XZ speed (m/s) the character is idle and keeps its facing. | | `InstanceRegistry` | class | `new (scene: Scene)` | One `InstancedMesh` per key (geometry kind + size + material params). | | `LoadedSplat` | interface | `{ object: GaussianSplat; count: number; color: SplatColorControls }` | | | `LookSpec` | interface | `{ envIntensity?: number; saturation?: number }` | | | `MaterialSpec` | interface | `{ color: string; roughness: number; metalness: number; emissive?: string }` | | | `MeshSpec` | type | | | | `NO_INTERP` | const | `4` | | | `OrbitController` | class | `new (camera: PerspectiveCamera, dom: HTMLElement)` | | | `PITCH_MAX` | const | `0.3` | | | `PITCH_MIN` | const | `-1.2` | | | `RUN_FRACTION` | const | `0.75` | Walk/run boundary as a fraction of `sprintSpeed`. | | `RenderEntity` | interface | | | | `RenderSettings` | interface | | | | `RenderStats` | interface | `{ fps: number; frameMs: number; drawCalls: number; triangles: number; splats: number; textureMB?: number; backend: 'webgpu'\|'webgl' }` | | | `SLEEPING` | const | `2` | | | `SPLAT_BUDGET` | const | `1500000` | Soft splat budget: a scene above this many splats logs a warning. | | `SPLAT_LAYER` | const | `1` | Splats live on this camera layer (meshes stay on layer 0). | | `SPLAT_LOADERS` | const | `SplatLoaderFactories` | | | `STATE_STRIDE` | const | `8` | State buffer layout: 8 f32 per slot, `px,py,pz,qx,qy,qz,qw,flags`. | | `SplatColorControls` | interface | `{ exposure: { value: number }; saturation: { value: number }; tint: { value: Color } }` | Per-splat colour controls, uniforms so `splatOnly` debug can bypass them at runtime. | | `SplatConfig` | type | `NonNullable` | | | `SplatFormat` | type | `"spz" \| "splat" \| "ksplat" \| "ply"` | | | `SplatLoadError` | class | `new (url: string, cause?: unknown)` | Any failure to produce a splat from `url` (network, parse, unsupported extension). | | `TOON` | const | | Toon style (opt-in, `post.style: "toon"`): cel-banded mesh lighting, ink outlines (see `style/outline.ts`) and a posterised splat grade (see `style/splat-grade.ts`). | | `TOON_DEFAULTS` | const | `ToonSettings` | Defaults of `post.toon` (mirrored by the scene schema). | | `TOON_INK_CONTEXT` | const | `"getToonInk"` | Scene-pass context key under which the pipeline hands `ToonInk` to toon materials. | | `ThirdPersonController` | class | `new (camera: PerspectiveCamera, raycast: ArmRaycast)` | Third-person orbit camera on a spring arm. | | `ToonInk` | interface | `{ edge: Node<"float">; color: Node<"vec3"> }` | What `ToonNodeMaterial` reads from the scene pass context to ink itself. | | `ToonNodeMaterial` | class | | | | `ToonSettings` | interface | | | | `WEBGL_HDR_MAX_RADIANCE` | const | `16384` | WebGL fallback only: the brightest radiance an HDRI texel may keep before PMREM filtering. | | `applyLook` | function | `(root: Object3D, look: LookSpec \| undefined) => void` | Applies `look` to every mesh under `root` (load time, once per glTF + look). | | `applySplatGrade` | function | `(splat: GaussianSplat, g: ToonSettings["splat"]) => void` | Painterly grade of a splat to sit with toon-shaded meshes, per splat (colour stage, so it costs nothing per pixel): the lightness is posterised into `levels` flat values (in a gamma-2 perceptual space) while hue and chroma are kept, saturation is pushed, and a split tone runs from a cool `shadowTint` to a warm `highlightTint`. | | `attachSound` | function | `(object: Object3D, listener: AudioListener, url: string) => Promise` | Loads `url` (cached) and attaches a (non-looping) `PositionalAudio` to `object`. | | `bandOf` | function | `(x: number, n: number) => number` | CPU mirror of `bandsOf` without the antialiasing (tests, docs). | | `createEnvironment` | function | `(renderer: WebGPURenderer, settings: RenderSettings) => Promise` | | | `createPipeline` | function | `(renderer: WebGPURenderer, scene: Scene, camera: PerspectiveCamera, settings: RenderSettings, opts: { splatOnly?: boolean } = {}) => RenderPipeline` | Single-composite design: one scene pass holds meshes and splats (splats depth-test, no depth write). | | `createRenderer` | function | `(canvas: HTMLCanvasElement, settings: RenderSettings, opts: { backend: "webgpu" \| "webgl"; splatOnly?: boolean; transcoderPath?: string; assetBase?: string; webglFallback?: boolean; }) => Promise` | | | `createShadowCatcher` | function | `(floorY: number, size: number) => Mesh` | An invisible floor at `floorY` that only shows the shadows cast onto it (splats neither cast nor receive shadows). | | `createSun` | function | `(settings: RenderSettings, camera: PerspectiveCamera) => { light: DirectionalLight; csm: CSMShadowNode }` | The sun: a DirectionalLight placed along `settings.sun.direction` (scene -> sun), shadowing through a `CSMShadowNode`. | | `defaultAssetBase` | function | `() => string` | The asset base used when `createRenderer` / `createGame` get no `assetBase` option: `VITE_PEBBLE3D_ASSET_BASE` if the app was built with it, else Vite's `BASE_URL` (the `--base` the app was built with, `"/"` by default), else `"/"`. | | `defaultWebglFallback` | function | `(search: string \| undefined = globalThis.location?.search) => boolean` | Whether the opt-in automatic WebGL fallback is on when `createRenderer` gets no `webglFallback` option: the app was built with `VITE_PEBBLE3D_WEBGL_FALLBACK=1`, or the page URL has `?webglFallback=1`. | | `envFromSplat` | function | `(renderer: WebGPURenderer, scene: Scene, splat: GaussianSplat) => RenderTarget` | Image-based lighting from a splat capture: a 256 px cube capture of the scene (splat plus the current background, so the sky above the capture still lights from above) from the splat's world bounding-box centre, PMREM-filtered once. | | `floorProxyViewZ` | function | `(dirViewZ: number, dirWorldY: number, camY: number, floorY: number, backdrop: number) => number` | View-space z (negative, metres) of the floor-plane proxy for a depthless pixel. | | `loadEnvironment` | function | `(renderer: WebGPURenderer, settings: RenderSettings) => Promise` | `outdoor`: `HDRLoader` + `PMREMGenerator` from `settings.hdri`, plus a horizon-coloured haze. | | `loadSplat` | function | `(cfg: SplatConfig, loaders: SplatLoaderFactories = SPLAT_LOADERS) => Promise` | Loads `cfg.url` (loader by extension), wraps it in a `GaussianSplat` with the authored transform on `SPLAT_LAYER`, and linearises its colour. | | `loadSplatGeometry` | function | `(url: string, loaders: SplatLoaderFactories = SPLAT_LOADERS) => Promise` | Loads the splat geometry with the loader for its extension; every failure is a `SplatLoadError`. | | `pickAnimState` | function | `(f: CharacterFrame) => AnimState` | Animation state from the character's sim state. | | `posterize` | function | `(l: number, levels: number) => number` | CPU mirror of the posterise step: perceptual lightness `l` in [0, 1] to the centre of its band. | | `primitiveGeometry` | function | `(primitive: Extract["primitive"], size: [number, number, number]) => BufferGeometry` | | | `readSlot` | function | `(prev: Float32Array, curr: Float32Array, slot: number, alpha: number, outPos: Vector3, outQuat: Quaternion) => boolean` | Writes the interpolated (or NO_INTERP-snapped) transform of `slot` into `outPos`/`outQuat`. | | `resolveAssetUrl` | function | `(url: string, base: string \| undefined) => string` | Prefixes a root-absolute `url` (`/assets/x.glb`) with `base` (`/pebble3d/` gives `/pebble3d/assets/x.glb`). | | `setToonUniforms` | function | `(s: ToonSettings) => void` | Pushes `s` into the global `TOON` uniforms. | | `showFallbackNotice` | function | `(doc: Document \| undefined = globalThis.document) => HTMLElement \| null` | Shows a small dismissible notice (bottom-left, above the game) saying the renderer fell back to WebGL. | | `splatFormatOf` | function | `(url: string) => SplatFormat \| null` | The splat format of `url` from its extension (query and hash ignored), or null. | | `spreadEquirectPeaks` | function | `(img: EquirectImage, cap: number, half: boolean) => { changed: number; converged: boolean }` | Caps every texel of an equirect RGBA image at `cap` (on its brightest channel) without losing energy: the excess of an over-cap texel is scattered to its 3x3 neighbourhood, weighted by texel solid angle (cos latitude), and repeated until nothing exceeds `cap`. | | `springArmDistance` | function | `(desired: number, hitToi: number \| null, padding = 0.2, min = 0.5) => number` | Spring-arm length: the desired distance, pulled in to `hitToi - padding` when the arm's ray hits something closer, never below `min`. | | `stylizeToon` | function | `(root: Object3D) => void` | Swaps every convertible mesh material under `root` for its toon copy (one copy per source material, so sharing is kept). | | `toneMappingOf` | function | `(name: RenderSettings["toneMapping"]) => ToneMapping` | | | `toonInk` | function | `(depth: TextureNode, normal: TextureNode, camera: PerspectiveCamera, pixelRatio: () => number, o: ToonSettings["outline"]) => ToonInk` | Ink-line coverage at the current fragment, from the mesh-only prepass (depth + view normal; splats and transparents never reach it, so the splat gets no lines). | | `toonMaterialFrom` | function | `(src: Material) => Material` | A `ToonNodeMaterial` copy of a standard / physical material (classic or node), copied key by key as WebGPURenderer converts classic materials (value objects cloned, textures and nodes shared). | | `unitTint` | function | `(hex: string) => Color` | `hex` as linear RGB scaled to unit luminance (a pure hue/temperature tint). | | `updateCsmFrustums` | function | `(csm: CSMShadowNode) => void` | Safe to call before the first render: the CSM binds its camera lazily on first build. | ## World (wasm) Source: `packages/sdk/wasm/det/engine_core_det.d.ts` (wasm-bindgen output, committed; rebuilt by `pnpm build:wasm` after Rust changes). "Scratch" is the `SCRATCH_LEN`-float region at `scratchPtr()`. | method | signature | doc | | --- | --- | --- | | `constructor` | `new World(seed: number, gravity_y: number)` | | | `free` | `free(): void` | | | `angularVelocity` | `angularVelocity(id: number): boolean` | Writes `[wx, wy, wz]` to scratch `[16..19)` and returns true, or returns false (scratch untouched) for unknown ids (static bodies read zero). | | `applyImpulse` | `applyImpulse(id: number, ix: number, iy: number, iz: number): boolean` | Adds a linear impulse to a dynamic body (wakes it). Returns false for unknown ids and non-dynamic bodies. | | `applyTorqueImpulse` | `applyTorqueImpulse(id: number, tx: number, ty: number, tz: number): boolean` | Adds a torque impulse to a dynamic body (wakes it). Returns false for unknown ids and non-dynamic bodies. | | `bodyCounts` | `bodyCounts(): Uint32Array` | `[active, sleeping]`. Allocates; call on stats ticks only. | | `characterState` | `characterState(id: number): boolean` | Writes `[grounded 0/1, vx, vz, vy]` to scratch `[8..12)` and returns true, or returns false (scratch untouched) if `id` is not a character. | | `despawn` | `despawn(id: number): boolean` | | | `drainSpawned` | `drainSpawned(): Uint32Array` | Flat `(id, slot, spawnerSimId)` triples. Call only when `spawnedPending() > 0`. | | `linearVelocity` | `linearVelocity(id: number): boolean` | Writes `[vx, vy, vz]` to scratch `[12..15)` and returns true, or returns false (scratch untouched) for unknown ids (static bodies read zero). | | `raycast` | `raycast(ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, max_toi: number, filter: number, exclude_id: number): boolean` | filter: 0 = all, 1 = static-only, 2 = exclude `exclude_id`. On hit writes `[toi, nx, ny, nz, id]` to scratch `[0..5)` and returns true. | | `scratchLen` | `scratchLen(): number` | `SCRATCH_LEN`: floats in the scratch region (the sdk mirrors it and tests the match). | | `scratchPtr` | `scratchPtr(): number` | Byte offset of the fixed `SCRATCH_LEN`-float scratch region. | | `setCharacterInput` | `setCharacterInput(id: number, wx: number, wz: number, jump: boolean, sprint: boolean): void` | World-space XZ direction (clamped to length 1), jump and sprint. No-op for non-characters. | | `setKinematicPose` | `setKinematicPose(id: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number): boolean` | Sets the pose a kinematic body moves to on the next step. Returns false for unknown ids and non-kinematic bodies. | | `setVelocity` | `setVelocity(id: number, vx: number, vy: number, vz: number, wx: number, wy: number, wz: number): boolean` | Sets a dynamic body's linear and angular velocity (wakes it). Returns false for unknown ids and non-dynamic bodies. | | `slotCapacity` | `slotCapacity(): number` | Number of slots (each `STRIDE` = 8 floats) in each state buffer. | | `slotOf` | `slotOf(id: number): number` | Slot index, or -1 if the entity has no slot. | | `spawn` | `spawn(desc_json: string): number` | Parses an `EntityDesc` JSON string and spawns it. Throws with the Rust message on error. | | `spawnedPending` | `spawnedPending(): number` | | | `stateHash` | `stateHash(): string` | FNV-1a 64 state hash as 16 lowercase hex characters. | | `statePtrCurr` | `statePtrCurr(): number` | Byte offset of the curr buffer in `memory.buffer`. Changes when buffers grow. | | `statePtrPrev` | `statePtrPrev(): number` | Byte offset of the prev buffer in `memory.buffer`. Changes when buffers grow. | | `step` | `step(n: number): void` | | | `teleport` | `teleport(id: number, x: number, y: number, z: number): void` | | | `tick` | `tick(): number` | | | `transformOf` | `transformOf(id: number): Float32Array \| undefined` | `[px,py,pz,qx,qy,qz,qw]`, or undefined. Debug/tests only (allocates). | ===== docs/verification.md ===== # Verification How to prove a change works: screenshots with `pnpm shot`, determinism hashes, demo bots, fps benches and the console-error policy. Agents that want the checklist version can start from [`skills/verify-your-work/SKILL.md`](../skills/verify-your-work/SKILL.md). ## `pnpm shot` ```bash pnpm shot --scene showcase --cam hero --backend webgpu --overlay pnpm shot --app rockfall --param demo=1 --param seed=7 --ticks 900 --out artifacts/check --name rockfall-900 ``` It builds the app (default the playground), serves it with `vite preview` on a free port, opens it in Chromium in fixed-tick mode (`?mode=fixed&ticks=`) and waits for `window.__pebble3d.done`. Output: `artifacts/shots/---x.png` plus a `.json` sidecar with `adapterInfo`, `stats`, `stateHash`, `tick`, `game` (the app's `__pebble3d.game` probes, when present) and `console`. Source: `scripts/shot/shot.mjs`. Needs a Chromium for Playwright once: `pnpm exec playwright install chromium`. | Flag | Meaning | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `--scene ` | A file in `apps/playground/scenes/`. Required for the playground (the default app); optional with `--app`. | | `--cam ` | A camera preset, or `controller`. Default: the renderer's (`hero`, else the first preset). | | `--backend webgpu\|webgl` | Default `webgpu`. Fails if that backend is not the one that ran. | | `--size WxH` / `--resize WxH` | Viewport size (default 1280x720) / resize after load (not with `--sequence`). | | `--ticks ` | Sim ticks to run before capture (default 120). | | `--script ` | Scripted player input: `walk-forward`, `walk-into-crates`, `walk-to-bounds`, `walk-side`, `sprint-side`, `jump`, `jump-side` (see `SCRIPTS` in `apps/playground/src/main.ts`). | | `--sequence [:]` | Capture `n` frames, one every `` ticks (default 1), from tick `--ticks`: `-f000.png`... plus `.webp`, an animated WebP (30 fps for every=1, else real time). `--fps ` / `--scale ` / `--no-frames` override the rate, downscale, drop the PNGs. | | `--overlay` | Show the stats overlay in the shot. | | `--splat ` / `--debug splatOnly` | Override the splat / draw only the splat. | | `--allow-console-error "[:count]"` | Permit an expected console error, optionally with an exact count. | | `--no-build` / `--headed` | Skip the build / show the browser. | | `--app ` / `--param key=value` | Capture another app under `apps/` (then `--scene` is optional) / pass extra URL params. | | `--out ` / `--name ` | Output directory (inside `artifacts/`) / file basename. | | `--timeout ` / `--port ` | Per-wait timeout (default 60) / serve the preview on a fixed port. | Exit 1 when: | Condition | Typical fix | | --- | --- | | The requested backend is not the one that ran | WebGPU unavailable: see [troubleshooting.md](troubleshooting.md#backendunavailable-webgpu). | | The adapter is SwiftShader or a fallback adapter (after one headed retry) | Real GPU needed; see [troubleshooting.md](troubleshooting.md#shot-refuses-a-swiftshader-adapter). | | A console warning or error matches neither the allowlist nor `--allow-console-error` | Fix the cause; allowlist only benign lines. | | An `--allow-console-error` count is not met exactly | Adjust the count. | | Any uncaught page error | Always fails; cannot be allowlisted. | | A wait (load, `__pebble3d.done`, each sequence frame) exceeds `--timeout` | The app ignores `mode`/`ticks`, or `main()` threw: read `__pebble3d.error` in the console tail. | Always open the PNG and look at it; exit 0 only means nothing errored. ### Console-error policy - Every capture must exit 0 with an empty `console` array in its sidecar. The showcase games' `bench/capture-final.sh` scripts stop on the first failure. - `scripts/shot/console-allowlist.json` holds benign lines, each with a `pattern`, an optional `type` and a `justification`. It currently lists only Vite HMR `debug` lines, which are never checked. - A one-off expected error goes on the command line: `--allow-console-error "GltfLoadError:1"`. - Only `error` and `warning` messages are checked. `console.info` (for example the playground's "WebGPU unavailable, using the WebGL backend") passes. ## Determinism The engine's `deterministic` build gives a bit-identical state hash across runs and between Node and Chromium (V8). The `fast` build is deterministic only for the same binary on the same machine. | Check | Command | Pass | | --- | --- | --- | | Engine fixture in Node | `node --experimental-strip-types packages/sdk/test/determinism.mjs --expect "$(cat packages/sdk/test/fixtures/det-hash.txt)"` | Prints `{"hash":"2d76d9927e780425"}`, exit 0 | | Same scene in the browser | `pnpm shot --scene det --cam hero --backend webgpu --ticks 1000` | Sidecar below | | Browser equals Node | `node -e "const s=require('./artifacts/shots/det-hero-webgpu-1280x720.json'); const h=require('fs').readFileSync('packages/sdk/test/fixtures/det-hash.txt','utf8').trim(); process.exit(s.stateHash===h && s.tick===1000 ? 0 : 1)"` | Exit 0 | | Chain Reaction levels in Node | `pnpm --filter chain-reaction verify` | `all 6 verified` | | Chain Reaction, browser vs Node | `node apps/chain-reaction/bench/agree.mjs` | Exit 0 (prints `browser and Node agree on all N levels`) | | Game sims in Node | `npx vitest run --project rockfall` (also `ghostline`, `breakpoint`, `chain-reaction`) | Determinism tests load the real wasm, for example `apps/rockfall/test/helpers.ts` (`nodeFactory`) and `apps/ghostline/test/determinism.test.ts` | | An app capture repeats | Run the same `pnpm shot --app ... --ticks ` twice | Same `stateHash` both times | Write your own game-sim determinism test the way `apps/rockfall/test/sim.test.ts` does: load the det wasm bytes with `loadSim("deterministic", bytes)`, run the same seed and input log twice, compare `world.stateHash()`, then change one input and expect a different hash. ## Demo bots Every showcase game has a `?demo=1` autoplayer that plays the full loop with the same input type a player produces. Captures, fps benches and smoke tests drive it. | App | Bot | Useful params with `demo=1` | | --- | --- | --- | | `katana-defense` | `apps/katana-defense/src/game/bot.ts` | `demoWaves=`, `wave=`, `seed=` | | `breakpoint` | `apps/breakpoint/src/game/bot.ts` | `level=` (0-based), `seed=` | | `ghostline` | `apps/ghostline/src/game/bot.ts` | `course=sunfold\|lacquer\|undertow`, `bot=fast\|par\|slow` | | `field-notes` | `apps/field-notes/src/game/bot.ts` | `site=yard\|courtyard`, `seed=` | | `rockfall` | `apps/rockfall/src/game/bot.ts` | `demoWaves=`, `wave=`, `rubble=`, `god=1` | | `chain-reaction` | `apps/chain-reaction/src/demo.ts` | `level=` (1-based) | | `lanternfall` | `apps/lanternfall/src/game/bot.ts` | `seed=` (without it the bot tours keeps), `guards=` | | `ringout` | `apps/ringout/src/game/bot.ts` | `seats=bot,bot,bot,bot`, `bestOf=3\|5\|7`, `seed=` | | `skyrun` | `apps/skyrun/src/game/bot.ts` | `course=dawnsteps\|gale-spires`, `bot=fast\|steady`, `runner=human\|robot` | | `pebble-garden` | `apps/pebble-garden/src/demo.ts` | builds, plays, rewinds and exports a contraption | | `swarm-siege` | `apps/swarm-siege/src/game/bot.ts` | `wave=`, `gold=`, `seed=` | | `drift-drone` | `apps/drift-drone/src/game/bot.ts` | `track=hall-circuit\|needle-and-eaves`, `cam=chase\|fpv` | In a shot: `pnpm shot --app rockfall --param demo=1 --ticks 900`. Each app's URL params are documented at the top of its `src/main.ts`. ## Benches and capture scripts Each fps bench serves the built app with `vite preview`, opens `?demo=1` in realtime and samples `requestAnimationFrame` intervals. Build first: `pnpm --filter build`. | App | fps bench | Capture script (writes) | | --- | --- | --- | | `katana-defense` | `node apps/katana-defense/bench/fps.mjs [seconds=25]` | `bash apps/katana-defense/bench/capture-final.sh` (`artifacts/game/final/`) | | `breakpoint` | `node apps/breakpoint/bench/fps.mjs [seconds=60] [level=0]` | `bash apps/breakpoint/bench/capture-final.sh` (`artifacts/games/breakpoint/`) | | `ghostline` | `node apps/ghostline/bench/fps.mjs [course=sunfold] [seconds=20]` | `bash apps/ghostline/bench/capture-final.sh` (`artifacts/games/ghostline/`) | | `field-notes` | `node apps/field-notes/bench/fps.mjs [seconds=30] [extra query]` | `bash apps/field-notes/bench/capture-final.sh` (`artifacts/games/field-notes/`) | | `rockfall` | `node apps/rockfall/bench/fps.mjs [seconds=20] [full\|empty]` | `bash apps/rockfall/bench/capture-final.sh` (`artifacts/games/rockfall/`) | | `chain-reaction` | `node apps/chain-reaction/bench/fps.mjs [seconds=30]` | `bash apps/chain-reaction/bench/capture-final.sh` (`artifacts/games/chain-reaction/`) | | Setting | Effect | | --- | --- | | `BENCH_VSYNC=1` | Measure under the 60 Hz cap (default uncapped). All benches except rockfall. | | `BENCH_UNCAPPED=1` | Rockfall only: its default is capped; this measures headroom. | | Capture script argument | `bash apps//bench/capture-final.sh ` re-shoots one capture. | Measure fps on an idle GPU. During the parallel game builds, other processes kept the GPU 55-100% busy and benches reported 20-50 fps for games that hold 60 fps on a quiet machine. Check `/sys/class/drm/*/gpu_busy_percent` (Linux, AMD) before trusting a number. Headless (Node) benches: | Command | Measures | | --- | --- | | `node --experimental-strip-types packages/sdk/test/bench.mjs` | Engine ticks per second, both builds, 100 and 500 bodies. | | `pnpm --filter rockfall bench` | Bodies sustained per build within the tick budget. | | `pnpm --filter breakpoint bench:physics` | ms per tick for every level after the first shot. | | `pnpm --filter katana-defense bench:kcc` | Engine character controllers vs the game's JS kinematic path, 40 zombies. | Smoke tests with real input: `node apps/ghostline/bench/smoke.mjs`, `node apps/field-notes/bench/live-smoke.mjs` (after a build). ## Test suites | Command | Covers | | --- | --- | | `pnpm test` | Every vitest project listed in the root `vitest.config.ts` `projects`: sdk, renderer, every game, `scripts` (asset build, docs drift guards). A new app's tests run only after you add it there ([getting-started.md](getting-started.md#tests-in-node)). | | `npx vitest run --project scripts scripts/docs` | Docs: generated files current, scene JSON examples valid, relative links resolve. | | `pnpm typecheck` / `pnpm lint` | tsc in every package / biome. | | `cargo test -p engine-core --features deterministic` and `--no-default-features --features fast` | Rust, both builds. | ===== docs/troubleshooting.md ===== # Troubleshooting Error messages and symptoms seen while building Pebble3D and its showcase games, each with the cause and the fix. | Symptom | Jump to | | --- | --- | | `BackendUnavailable: webgpu (WebGPURenderer fell back to WebGL)` | [BackendUnavailable: webgpu](#backendunavailable-webgpu) | | Outdoor (HDRI) scene renders all black (fog on) or all white (fog off) on `--backend webgl` only | [WebGL outdoor black/white](#webgl-outdoor-scene-is-black-or-white) | | `TypeError: world.setVelocity is not a function` (or `applyImpulse`, `linearVelocity`, ...) | [Stale wasm](#stale-wasm-setvelocity-is-not-a-function) | | `shot: FAIL --out must be inside artifacts/` | [Shot --out rejected](#shot---out-rejected) | | `shot: FAIL software/fallback adapter (SwiftShader) refused` | [SwiftShader adapter](#shot-refuses-a-swiftshader-adapter) | | `determinism mismatch: expected 2d76d9927e780425, got ...` | [Determinism hash mismatch](#determinism-hash-mismatch) | | `shot: FAIL console error not allowlisted: Failed to load resource: ... 404` | [404 in the console](#shot-fails-on-a-404) | | Shot hangs, then times out waiting for `__pebble3d.done` | [Shot timeout](#shot-times-out-waiting-for-__pebble3ddone) | | `TS2352: Conversion of type ... to type ... may be a mistake` on a scene import | [Scene JSON import types](#ts2352-when-passing-an-imported-scene-json) | | fps far below 60 in a bench, or numbers that swing between runs | [GPU contention](#fps-numbers-are-low-or-noisy) | | The game slows to a crawl under heavy physics | [Too many ticks per frame](#heavy-physics-makes-the-game-crawl) | | `fetch-assets` reports a sha256 mismatch or a failed avatar | [Assets](#fetch-assets-hash-mismatch-or-failed-avatar) | | `pnpm docs` does not regenerate the docs | [pnpm docs](#pnpm-docs-does-nothing-useful) | | `scene.schema.json` test fails, or conflicts in a merge | [Schema JSON](#sceneschemajson-is-stale) | | Two screenshots of the same tick differ by a few pixels | [Pixel noise](#two-identical-shots-differ-slightly) | | No per-tick hook or spawn callback in `createGame` | [Custom boot](#creategame-has-no-per-tick-hook) | | A second game on the same page misbehaves | [One game per page](#a-second-game-on-the-same-page) | | `No projects were found ... The filter matched no projects: `, or `No test files found, exiting with code 0` for a new app | [App tests not registered](#a-new-apps-tests-never-run) | | A headless (Node) run's `stateHash` differs from the browser's at the same tick | [Headless hash differs](#headless-hash-differs-from-the-browser) | | Assets, the transcoder or the wasm 404 when the game is served under a sub-path | [Sub-path 404s](#assets-404-under-a-sub-path) | | Dragging or scrolling on the canvas moves a camera your code drives | [Orbit controls fight your camera](#the-orbit-camera-fights-your-camera) | | A bot's or sim's character input is ignored on high-refresh displays; the player walks on a menu | [Player input overwritten](#your-setcharacterinput-is-overwritten) | | A second character slides around without animating or turning | [Characters after the first](#other-characters-do-not-animate) | | A static body was teleported but its mesh stayed put | [Static visuals](#a-static-mesh-does-not-move) | | A ball or wheel rolls forever | [Rolling without damping](#spheres-roll-forever) | | State reads return zeros or stale values; `views.curr.byteLength` is 0 | [Detached views](#state-views-read-zeros-after-a-spawn) | | `raycast` returns false on a world you just built | [Raycast before the first step](#raycasts-miss-on-a-new-world) | | You need collision callbacks | [No contact events](#there-are-no-contact-events) | | A bad scene reports one error at a time | [One scene error](#only-the-first-scene-error-is-reported) | | The sidecar `stateHash` is the same in every capture | [stateHash of the idle world](#the-shot-statehash-never-changes) | | `!important` vanished from a CSS file after a lint fix | [biome --unsafe](#biome---unsafe-removed-important) | | A worker-based sim makes fixed-mode captures flaky or time out | [Worker in fixed mode](#fixed-mode-captures-with-a-worker-sim) | | fps looks fine (or terrible) but was measured headless, on SwiftShader or only on WebGL | [Untrustworthy fps](#fps-from-a-headless-or-webgl-run-is-misleading) | | `SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript parameter property is not supported in strip-only mode` | [Parameter properties in Node](#parameter-properties-fail-in-a-node-script) | | A night or indoor scene is too bright; no point lights in the scene JSON | [Night scenes](#a-night-scene-is-too-bright) | | Draw calls climb fast with each skinned character | [Shadow cascades multiply draws](#draw-calls-climb-with-each-character) | | Flat decals on a splat floor get ink outlines in the toon style | [Decal outlines](#decals-on-a-splat-floor-get-ink-outlines) | | A bench copied from another game reports numbers for the wrong scene, or never connects | [Copied fps bench](#a-copied-fps-bench-measures-the-wrong-thing) | ## BackendUnavailable: webgpu **Symptom:** `BackendUnavailable: webgpu (WebGPURenderer fell back to WebGL)` on the page, in `__pebble3d.error`, or as a `pnpm shot` failure. **Cause:** the browser exposed no usable WebGPU adapter, so three's `WebGPURenderer` fell back to WebGL, and `createRenderer` (`packages/renderer/src/create.ts`) throws when `webgpu` was requested. On Linux, Chromium often ships with WebGPU off; open `chrome://gpu` and look at the WebGPU line to check. **Fix:** - Start Chromium with `chromium --enable-unsafe-webgpu --enable-features=Vulkan --use-angle=vulkan`. `pnpm shot` already passes these (plus `--ignore-gpu-blocklist`). - Or use the WebGL fallback: `?backend=webgl` in the URL, `--backend webgl` for `pnpm shot`. - Or opt in to the automatic fallback: `createGame({ ..., webglFallback: true })` (or `createRenderer`'s `webglFallback`), a build with `VITE_PEBBLE3D_WEBGL_FALLBACK=1`, or `?webglFallback=1` in the URL. The renderer then keeps WebGL on the same canvas and shows a small dismissible notice. It is off by default so a missing WebGPU fails loudly. The public demo builds turn it on. - The playground falls back by itself only when no `backend` param is given (`apps/playground/src/main.ts`, `isBackendUnavailable`). Your own app must do the same if it wants a fallback, and must retry on a fresh canvas, because a canvas keeps its first context type: ```ts const fresh = canvas.cloneNode() as HTMLCanvasElement; canvas.replaceWith(fresh); game = await createGame({ ...opts, canvas: fresh, backend: "webgl" }); ``` ## WebGL outdoor scene is black or white **Symptom:** on the WebGL fallback (`?backend=webgl`, Firefox/Safari), an `outdoor` scene with an HDRI renders almost entirely black with fog on, or blown-out white with fog off. The sky itself may still be visible with bloom off. WebGPU, and the `studio` preset, look fine. **Cause:** `HDRLoader` decodes to half floats, so the sun of a bright HDRI (Poly Haven's `qwantani_noon_puresky_2k.hdr`) is stored as 65504, the half-float maximum. In three 0.187 both backends run the same `PMREMGenerator` with half-float targets, but empirically only the WebGL backend's PMREM overflows to +Inf on these fp16-max peaks (the exact step is unconfirmed). Every IBL-lit fragment then shades to +Inf (white after tone mapping), the range fog's `mix` turns that into NaN (black), and bloom spreads either over the frame. Measured on WebGL with a plain clamp: 32768 renders correctly, 60000 does not. **Fix:** handled in `loadEnvironment` (`packages/renderer/src/defaults/lighting.ts`): on WebGL only, `spreadEquirectPeaks` caps HDRI texels at `WEBGL_HDR_MAX_RADIANCE` (16384, validated on WebGL with spreading) by scattering the excess into neighbouring texels, which conserves the sun's energy, so diffuse IBL matches WebGPU. The same capped HDRI is the WebGL background, so there the sun disc in the sky and in reflections is slightly wider and its peak lower (it still tone-maps to white). Non-finite texels are clamped, not spread. WebGPU loads the HDRI unchanged. If you load your own HDRI into a PMREM on WebGL outside `loadEnvironment`, run it through `spreadEquirectPeaks` first. ## Stale wasm: setVelocity is not a function **Symptom:** `TypeError: world.setVelocity is not a function` (or `applyImpulse`, `linearVelocity`, `applyTorqueImpulse`, `setKinematicPose`), a scene feature that silently does nothing after a merge, or the sdk test `expect(h.world.scratchLen()).toBe(SCRATCH_LEN)` failing. **Cause:** the Rust source in `crates/` changed but the committed wasm in `packages/sdk/wasm/` was not rebuilt, so the JS calls methods the old binary lacks. `pnpm test` reports it as "Rust sources changed since the committed WASM was built" (`scripts/wasm-hash.test.mjs`). **Fix:** `pnpm build:wasm` (Rust 1.94.1, the `wasm32-unknown-unknown` target and `wasm-bindgen-cli` 0.2.130; `scripts/build-wasm.sh` checks both), commit `packages/sdk/wasm/`, then restart the dev server. See [Changing the physics](getting-started.md#changing-the-physics-rust). ## Shot --out rejected **Symptom:** `shot: FAIL --out must be inside artifacts/`. **Cause:** `scripts/shot/shot.mjs` resolves `--out` against the repo root and refuses any directory outside `artifacts/` (gitignored), so shots never land in source folders. **Fix:** `--out artifacts/`, for example `pnpm shot --app rockfall --param demo=1 --out artifacts/rockfall-check`. Omit `--out` for the default `artifacts/shots/`. ## Shot refuses a SwiftShader adapter **Symptom:** `shot: headless got a software adapter; retrying headed`, then `shot: FAIL software/fallback adapter (SwiftShader) refused: {...}`. **Cause:** Chromium ran on its CPU rasteriser (SwiftShader) or a fallback adapter instead of the GPU. Timings and some rendering paths are meaningless there, so the shot refuses it. Headless Chromium reaches the real GPU only with `--use-angle=vulkan`; with a display available the shot retries headed once. **Fix:** - Run on a machine with a GPU and working Vulkan drivers, from a session with `DISPLAY` or `WAYLAND_DISPLAY` set (or pass `--headed`). - An app with its own boot must report real adapter strings on `__pebble3d.adapterInfo`, or the check cannot work. Copy `adapterInfoOf` from `packages/sdk/src/game.ts`, as `apps/rockfall/src/main.ts` does; it reads the unmasked WebGL renderer string so `--backend webgl` on SwiftShader is still caught. ## Determinism hash mismatch **Symptom:** `determinism mismatch: expected 2d76d9927e780425, got ` from `packages/sdk/test/determinism.mjs`, a shot sidecar `stateHash` that differs from the fixture at tick 1000, `pnpm --filter chain-reaction verify` failing a level, or a game's Node determinism test failing. **Cause (check in this order):** 1. Stale wasm (see above): the binary is older or newer than the source. 2. An engine change that is not opt-in: it altered a default, the spawn order, or solver settings. 3. The sim reads `Math.random`, `Date`, wall-clock `dt` or DOM state. 4. The run used the `fast` build. It is deterministic only for the same binary on the same machine; the fixture is for `deterministic`. 5. Realtime mode ran 2+ ticks in one frame while game logic ran once per frame (input applied at a different tick). Fixed mode runs exactly one tick per frame. **Fix:** `pnpm build:wasm`, then rerun the script. If it still differs, make the change opt-in so the defaults reproduce the old state. Move randomness to a seeded generator (`apps/rockfall/src/game/rng.ts`). Never run `determinism.mjs --write` to accept a new hash unless the change is meant to alter default behaviour and that has been agreed. ## Shot fails on a 404 **Symptom:** `shot: FAIL console error not allowlisted: Failed to load resource: the server responded with a status of 404 (Not Found)`. **Cause:** something requested a missing file. Two common ones: - No `` in `index.html`, so the browser asks for `/favicon.ico`. - A missing asset: `pnpm fetch-assets` was not run, or the app does not serve the playground's `public/`. Apps use `appType: "mpa"` in `vite.config.ts` so missing assets are real 404s, not a silent `index.html`. **Fix:** add ``; run `pnpm fetch-assets`; copy `vite.config.ts` from an existing app (`publicDir: "../playground/public"`). Rerun with `--headed` to see which URL failed in the network tab. ## Shot times out waiting for `__pebble3d.done` **Symptom:** the shot waits for the full `--timeout` (default 60 s) and fails on `__pebble3d.done` (or `__pebble3d.ready`). **Cause:** - The app ignores `?mode=fixed&ticks=`, so nothing sets `done`. `createGame` sets it only when it was given `mode: "fixed"` and `stopAtTick`. - A custom boot (no `createGame`) never sets `window.__pebble3d.done`. - `main()` threw before the first frame. **Fix:** pass `mode` and `stopAtTick` from the URL to `createGame` ([getting-started.md](getting-started.md#srcmaints-boot-input-probes)). A custom boot sets `hook.done = true` once `tick >= stopAtTick` in fixed mode (`apps/rockfall/src/main.ts`). Catch boot errors into `window.__pebble3d.error` and `console.error` so the failure is visible. ## TS2352 when passing an imported scene JSON **Symptom:** `error TS2352: Conversion of type '{ version: number; ... }' to type '...' may be a mistake ... Type 'number[]' is not comparable to type '[number, number, number]'.` **Cause:** a JSON import widens `[0, 3, 8]` to `number[]`, which does not match the schema's tuple types. **Fix:** cast through `unknown`; `createGame` validates the scene with zod at runtime anyway: ```ts import sceneJson from "../scenes/court.json"; const scene = sceneJson as unknown as SceneInput; ``` ## fps numbers are low or noisy **Symptom:** a bench reports 20-50 fps, or results swing between runs, for a scene that should hold 60. **Cause:** another process is using the GPU. Other GPU-heavy apps (browsers, video, builds, compositors) can drag fps well below what the scene really holds, so measure on an idle GPU. **Fix:** check `/sys/class/drm/*/gpu_busy_percent` (Linux, AMD) before measuring, close other GPU users, and compare builds back to back in the same window. Use `BENCH_VSYNC=1` for the capped number players see ([verification.md](verification.md#benches-and-capture-scripts)). ## Heavy physics makes the game crawl **Symptom:** with 1,000+ awake bodies each frame gets later and later, or the frame rate collapses. **Cause:** in realtime mode `FixedStepLoop` catches up with up to 5 ticks per frame by default. When one tick costs more than a frame, each frame runs more ticks, which makes the next frame later still. **Fix:** - Cap catch-up: `new FixedStepLoop({ mode, maxTicksPerFrame: 2 })` (`apps/rockfall/src/main.ts`). The game slows down instead of spiralling. - Use the `fast` build when you only need same-machine determinism: `"sim": { "build": "fast" }` halved Breakpoint's tick cost (about 26 ms to 13 ms at 1,300 awake bodies; `apps/breakpoint/scenes/site.json`). - Move the sim to a Web Worker (`apps/breakpoint/src/game/sim.worker.ts`). Bound its message queue and pause on `visibilitychange`, or a hidden tab queues ticks without limit. ## fetch-assets hash mismatch or failed avatar **Symptom:** `pnpm fetch-assets` prints `: sha256 mismatch (expected ..., got ...)`, or reports the human avatar `rocketbox-male-adult-16.glb` as failed. **Cause:** the derived splat hash was verified on one machine only. The avatar build needs the pinned KTX-Software binary, which is linux-x64 only. **Fix:** for the avatar on other platforms, use `/?scene=showcase-robot`. For a hash mismatch, check the source download first; `node scripts/fetch-assets.mjs --update-hashes` rewrites hashes in the manifest, so use it only for assets you are adding. ## `pnpm docs` does nothing useful **Symptom:** `pnpm docs` does not regenerate `docs/`. **Cause:** `docs` is a pnpm builtin command, which shadows a script of that name. **Fix:** `pnpm docs:gen`. `pnpm docs:gen --check` exits 1 when generated files are stale. ## scene.schema.json is stale **Symptom:** the sdk test `scene-schema-json.test.ts` fails, the docs drift test reports `generated docs are current` failing, or two branches conflict in `packages/sdk/scene.schema.json`. **Cause:** `packages/sdk/scene.schema.json` and `docs/scene-reference.md` are generated from `packages/sdk/src/schema.ts`. **Fix:** never hand-merge them. Resolve `schema.ts`, then `pnpm --filter @pebble3d/sdk schema && pnpm docs:gen`. ## Two identical shots differ slightly **Symptom:** two captures of the same tick are not byte-identical. **Cause:** GPU rasterisation noise. Two runs of identical code measured 36 px over a 2% fuzz at about 53 dB PSNR on the showcase scene; screenshots repeat to RMSE < 0.002, not byte for byte. **Fix:** compare `stateHash` and `tick` in the sidecars for logic, and a fuzzy image diff against a measured noise floor for rendering. ## createGame has no per-tick hook **Symptom:** you need code to run exactly once per sim tick, or to see bodies that spawners created at runtime, and `createGame` offers only `onFrame`. **Cause:** `createGame` steps the world itself and consumes `drainSpawned()` for the scene's spawners. There is no `onTick` or `onSpawned` callback yet. **Fix:** for light rules, advance your own sim inside `onFrame` until it reaches `world.tick()` ([getting-started.md](getting-started.md#3-a-minimal-game-app)). For full control, boot like `apps/rockfall/src/main.ts`: `createRenderer` + `loadSim` + `FixedStepLoop`, your own `sim.step(input)` per tick, and your own `window.__pebble3d` hook. Or keep `createGame` for rendering and run your sim in separate worlds from the same wasm module (`engineFrom` in `apps/chain-reaction/src/puzzle/sim.ts`). ## A new app's tests never run **Symptom:** `npx vitest run --project my-app` fails with `No projects were found ... The filter matched no projects: my-app`; `npx vitest run apps/my-app/test` prints `No test files found, exiting with code 0`; `pnpm test` passes without running your tests. **Cause:** the root `vitest.config.ts` lists every project explicitly in `test.projects`; a folder under `apps/` is not picked up by itself. **Fix:** add `apps/my-app/vitest.config.ts` (`defineProject({ test: { name: "my-app", include: ["test/**/*.test.ts"], testTimeout: 60_000 } })`, as `apps/rockfall/vitest.config.ts`) and add `"apps/my-app"` to `projects` in the root `vitest.config.ts`. Details: [getting-started.md](getting-started.md#tests-in-node). ## Headless hash differs from the browser **Symptom:** a Node test reproduces a run, but `world.stateHash()` after n ticks is not the `stateHash` in the `pnpm shot --ticks n` sidecar. **Cause:** usually the order of rules and physics. `createGame` runs `world.step` and then `onFrame`, so rules run after physics each tick; a Node loop that runs `sim.step(input)` before `world.step(1)` shifts tick-keyed rules by one tick. Other causes: a different seed or gravity in `loadSim` (pass `scene.sim.seed` / `scene.sim.gravity`), spawning entries in a different order than `expandScene(scene).sim`, the `fast` build, or JS math that differs between engines. **Fix:** mirror the browser loop exactly: `world.step(1); views.refresh(); bot.next(sim, input); sim.step(input);` per tick for a `createGame` app, or call the sim's own `step()` if the sim owns its world. See [getting-started.md](getting-started.md#tick-order). ## A second game on the same page **Symptom:** you call `createGame` again on the same page (level switch, site change) and the old game is still wired up. **Cause:** `Game.dispose` does not exist yet. `game.stop()` only cancels the frame loop; the renderer, the wasm `World`, the window key listeners, the `ResizeObserver` and `window.__pebble3d` stay. **Fix:** one game per page. Switch levels inside one game (new `World`s, as Chain Reaction does per run) or reload the page with new URL params (Field Notes reloads to change site). ## Assets 404 under a sub-path **Symptom:** served from `/games/x/` instead of `/`, the console shows 404s for `/assets/...`, `/basis/basis_transcoder.js` or a `.wasm`. **Cause:** a URL that bypasses the asset base. The renderer prefixes root-absolute URLs in the scene, in `renderer.loadGltf` and in the transcoder path with the asset base (`createGame`/`createRenderer` `assetBase`, else `VITE_PEBBLE3D_ASSET_BASE`, else Vite's `--base`). Your own `fetch`, `attachSound` and three.js loaders are not prefixed; neither are relative paths. **Fix:** build with `vite build --base /games/x/`, keep asset paths root-absolute, pass hand-loaded URLs through `renderer.assetUrl(url)`, and copy `vite.config.ts` from `apps/rockfall` (it emits `basis/`). Full layout: [cookbook/sub-path-hosting.md](cookbook/sub-path-hosting.md). ## The orbit camera fights your camera **Symptom:** you set `renderer.three.camera` every frame, yet a mouse drag or the wheel still nudges it, or touch scrolling is dead on the canvas. **Cause:** the scene's `camera.controller` defaults to `"orbit"`, which attaches three's `OrbitControls` to the canvas. There is no `"none"` value. Setting `renderer.controller = null` stops its per-frame update but leaves its listeners, which update the camera themselves. **Fix:** `renderer.controller?.dispose(); renderer.controller = null;` after boot, or use `"controller": "thirdPerson"` in a scene without a `character` (no controller is created). See [cookbook/custom-camera.md](cookbook/custom-camera.md). ## Your setCharacterInput is overwritten **Symptom:** your rules call `world.setCharacterInput` for the player character inside the per-tick loop; at 60 Hz it works, on a 120 Hz or 144 Hz display the demo bot stops steering or the player still walks with the keyboard when your rules say stand still. **Cause:** `createGame` sends `game.player.input` (the keyboard) with `setCharacterInput` every frame, including frames that run 0 ticks. On a fast display most frames run no tick, so the rig's value replaces yours before the next `world.step`. **Fix:** re-send your intent at the end of every `onFrame`, after the tick loop (`apps/lanternfall/src/main.ts`, lines 82-91, and `assertInput` in `apps/lanternfall/src/game/sim.ts`, lines 403-420), or drive the player only by writing `game.player.input`. ## Other characters do not animate **Symptom:** the first character animates; the others move but stay in their bind pose and never turn. **Cause:** `createGame` builds a `CharacterView` (animation mixer and facing) only for `game.player`, the first entity with a `character`. **Fix:** for each other character call `game.renderer.attachCharacter(simId, clipMap)` once, then per frame `world.characterState(simId)` and `view.update(frame, dt)` (`apps/lanternfall/src/view/present.ts`, lines 155-160 and 248-260). To make a different character the player, put it first in `entities`. ## A static mesh does not move **Symptom:** `world.teleport` on a `"static"` body moves its collider (things bump into it at the new spot) but its mesh stays where it started. **Cause:** the renderer places a static body's mesh once, on the first `renderer.sync` after it was added, and never reads its slot again. **Fix:** make anything that moves `"kinematic"` and move it with `setKinematicPose` or `teleport`; its visual then follows every frame. Code that inspects or merges static meshes must run after the first frame. ## Spheres roll forever **Symptom:** a ball on flat ground never slows down. **Cause:** Rapier has no rolling resistance, and `angularDamping` and `linearDamping` default to 0. **Fix:** set `"angularDamping"` on rolling bodies (0.25 in Pebble Garden's pebble, `apps/pebble-garden/src/garden/pieces.ts`, lines 156-163). Details: [cookbook/bodies-impulses-velocity.md](cookbook/bodies-impulses-velocity.md). ## State views read zeros after a spawn **Symptom:** after spawning (or when running several worlds), `views.curr` / `views.scratch` read 0 or old values, positions jump to the origin, or a raycast result reads 0. **Cause:** a spawn grew the wasm memory, which detaches every typed array over the old buffer. All worlds from one wasm module share that memory, so a spawn in any world detaches the views of all of them. `createGame` refreshes `game.views` once per frame; a world you create gets no such refresh. **Fix:** call `views.refresh()` after spawning or stepping, and before reading scratch results, and read `views.curr` / `views.scratch` through the views object instead of keeping the arrays (`apps/swarm-siege/src/game/sim.ts`, lines 380-385). See [cookbook/owning-the-world.md](cookbook/owning-the-world.md). ## Raycasts miss on a new world **Symptom:** `world.raycast` returns false on a world you just created and spawned, even straight down onto the floor. **Cause:** queries use the broad phase as of the last `step`; a world that has never stepped has none. **Fix:** `world.step(1)` once after spawning, before the first query, or defer the query work to the first tick (`apps/lanternfall/src/game/sim.ts`, lines 325-329). ## There are no contact events **Symptom:** you look for an `onCollision` callback or a contact list and find none. **Cause:** the engine does not expose Rapier's contact or intersection events. **Fix:** detect contacts in your rules after each step from state you already read: centre distance and closing speed (`apps/ringout/src/game/sim.ts`, lines 341-404), or a velocity change the forces you applied do not explain (`apps/drift-drone/src/game/sim.ts`, lines 407-423 and 441-451). Trigger zones that only test a position need no body at all. Patterns: [cookbook/bodies-impulses-velocity.md](cookbook/bodies-impulses-velocity.md). ## Only the first scene error is reported **Symptom:** fixing one `SceneError` reveals the next, one per run. **Cause:** `parseScene` (and so `createGame`) throws for the first issue only. Also, the cross-field checks (duplicate ids, unknown prefabs, entities with nothing to draw or simulate) run only after every field passes. **Fix:** to list everything, `SceneSchema.safeParse(json)` and print each `error.issues[i]` with `formatPath(issue.path)` ([api-reference.md](api-reference.md#validating-scenes); `apps/pebble-garden/src/garden/validate.ts`, lines 73-81). Expect a second round of cross-field issues once the field errors are fixed. ## The shot stateHash never changes **Symptom:** every `pnpm shot` sidecar has the same `stateHash`, whatever the tick or input. **Cause:** the game runs in worlds it creates itself, while `__pebble3d.stateHash` still reports `createGame`'s world, which holds no moving bodies. **Fix:** override it after `createGame`: `Object.assign(window.__pebble3d ?? {}, { stateHash: () => myWorld.stateHash() })` (`apps/ringout/src/main.ts`, lines 95-99; `apps/pebble-garden/src/main.ts`, lines 182-186). ## biome --unsafe removed !important **Symptom:** after `npx biome check --write --unsafe`, a CSS rule lost its `!important` and a hidden panel shows again. **Cause:** biome's recommended rule `lint/complexity/noImportantStyles` has an unsafe fix that deletes `!important`. `--write` alone only reports it. **Fix:** don't run `--unsafe` over CSS. Where `!important` is needed, keep it with a suppression comment on the line before: `/* biome-ignore lint/complexity/noImportantStyles: */` (`apps/pebble-garden/src/ui/hud.css`, lines 62-65), or raise the selector's specificity instead (`apps/drift-drone/src/game/ui/hud.css`, line 42). ## Fixed-mode captures with a worker sim **Symptom:** with the sim in a Web Worker, `pnpm shot --ticks n` captures a different tick each run, or times out waiting for `__pebble3d.done`. **Cause:** a worker steps on its own clock, so "one tick per frame, stop at n" cannot be enforced across the thread boundary. **Fix:** run the same sim inline on the main thread whenever `mode` is `fixed` and use the worker only in realtime (`apps/swarm-siege/src/main.ts`, line 81 and lines 133-135; `apps/breakpoint/src/main.ts`, line 85). See [cookbook/instanced-crowds-and-perf.md](cookbook/instanced-crowds-and-perf.md). ## fps from a headless or WebGL run is misleading **Symptom:** a game "holds 60 fps" in one measurement and stutters for a player, or a bench reports a few fps on a machine with a good GPU. **Cause:** - Headless Chromium without GPU flags renders WebGL on SwiftShader, a CPU rasteriser. Any fps measured there says nothing about the GPU path. `pnpm shot` refuses that adapter; a hand-written Playwright script or bench does not. - WebGL can be several times slower than WebGPU for the same scene, so a number from one backend does not carry over to the other. Players on Firefox, Safari or a Chromium without WebGPU get WebGL. **Fix:** - Launch Chromium with `--use-angle=vulkan --enable-features=Vulkan --ignore-gpu-blocklist` (plus `--enable-unsafe-webgpu` for WebGPU), as `scripts/shot/shot.mjs` does. - Confirm the renderer string names the real GPU before trusting a number: the sidecar's `adapterInfo`, or in the page `gl.getParameter(gl.getExtension("WEBGL_debug_renderer_info").UNMASKED_RENDERER_WEBGL)` on a WebGL context. "SwiftShader" or "llvmpipe" means software. - Measure both backends (`?backend=webgpu` and `?backend=webgl`) on an idle GPU before calling a game smooth. See [fps numbers are low or noisy](#fps-numbers-are-low-or-noisy). ## Parameter properties fail in a Node script **Symptom:** a headless script or CLI run with `node --experimental-strip-types` (or plain `node` on a version that strips types by default) fails with `SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript parameter property is not supported in strip-only mode`, while vitest and Vite accept the same file. **Cause:** Node's type stripping only removes type annotations; it does not transform TypeScript-only syntax. A constructor parameter property (`constructor(private readonly sim: MySim) {}`) needs a transform, and so do `enum` and `namespace`. vitest and Vite compile TypeScript fully, so the error appears only in the Node path. **Fix:** in code a Node script imports (the sim, the bot, level loaders), declare the field and assign it in the constructor: `private readonly sim: MySim; constructor(sim: MySim) { this.sim = sim; }`. Use `as const` objects instead of `enum`. Or run that code through vitest instead of a bare `node` script. ## A night scene is too bright **Symptom:** a night or interior scene still looks like daylight even with a dim sun, and the scene JSON has no field for point lights or environment strength. **Cause:** the schema's `lighting` has only `sun`; the `studio` and `outdoor` presets also light every mesh with an environment map at full strength, which dominates once the sun is dim. **Fix:** after boot, lower `renderer.three.scene.environmentIntensity` (Lanternfall uses 0.06, Breakpoint 0.42, Chain Reaction 0.55) and add three.js lights to `renderer.three.scene` yourself. Keep a small fixed pool of `PointLight`s with `castShadow = false` and move or re-colour them each frame rather than adding and removing lights, since a change in light count can force material recompiles (`LIGHT_POOL` in `apps/lanternfall/src/view/present.ts`). ## Draw calls climb with each character **Symptom:** a handful of skinned glTF characters adds dozens of draw calls, and fps drops long before the triangle count looks large. **Cause:** every shadow-casting mesh is drawn once in the main pass and once more for each shadow cascade (`CSM_CASCADES`, 3, in `packages/renderer/src/defaults/lighting.ts`). A character made of several skinned meshes multiplies that again. **Fix:** turn off shadows for things that do not need them: `"castShadow": false` on the entity in the scene, or `mesh.castShadow = false` on meshes you add (small props, distant crowds, decals). Merge a character's meshes when the asset allows it, and watch `drawCalls` in `stats()` (or the overlay, toggled with the backtick key) as you add characters. More: [cookbook/instanced-crowds-and-perf.md](cookbook/instanced-crowds-and-perf.md). ## Decals on a splat floor get ink outlines **Symptom:** with `post.style: "toon"`, a flat mesh lying on a Gaussian-splat floor (a puddle, a scorch mark, a target ring) gets a dark ink line around its edge. **Cause:** the outline pass reads a mesh-only depth/normal prepass. The splat floor is not in it, so at the decal's edge the prepass sees a depth step from the decal to empty background and draws ink. There is no per-object outline opt-out. **Fix:** make decals transparent materials (`transparent: true`, even at full opacity): transparent meshes are left out of the prepass and get no lines. See [cookbook/post-and-toon-style.md](cookbook/post-and-toon-style.md). ## A copied fps bench measures the wrong thing **Symptom:** a `bench/fps.mjs` copied from another game times out, measures a title screen, or reports numbers that do not change with your scene. **Cause:** each game's bench hard-codes its own preview port, URL params (seed, wave, level) and the phases it waits for. Rockfall's, for example, uses port 5242 and opens a fixed wave with rubble. **Fix:** after copying, change the port to one your app does not use, the query string to one your `?demo=1` bot understands, and every phase name or probe it polls on `__pebble3d.game`. Build first (`pnpm --filter build`). Benches are listed in [verification.md](verification.md#benches-and-capture-scripts). ===== docs/cookbook/scene-basics.md ===== # Scene basics Goal: a scene file with a floor, walls, static and dynamic props and a camera, that validates the first time. ```json { "version": 1, "environment": { "preset": "studio", "ground": { "size": 30 } }, "bounds": { "min": [-6, -6], "max": [6, 6], "height": 2 }, "lighting": { "sun": { "direction": [0.4, 1, 0.3], "intensity": 3 } }, "camera": { "controller": "orbit", "presets": { "hero": { "position": [0, 6, 12], "target": [0, 1, 0], "fov": 45 } } }, "entities": [ { "id": "table", "mesh": { "primitive": "box", "material": { "color": "#6b4f3a" } }, "body": { "type": "static" }, "transform": { "position": [0, 0.5, 0], "scale": [3, 1, 1.5] } }, { "id": "crate", "mesh": { "primitive": "box" }, "body": { "mass": 2, "friction": 0.7 }, "transform": { "position": [0.4, 2.5, 0], "scale": [0.5, 0.5, 0.5] } }, { "id": "ball", "mesh": { "primitive": "sphere", "material": { "color": "#e8553a", "roughness": 0.3 } }, "body": { "restitution": 0.6 }, "transform": { "position": [-0.6, 3, 0] } }, { "id": "sign", "mesh": { "primitive": "cylinder" }, "transform": { "position": [4, 1, -4], "scale": [0.2, 2, 0.2] } } ] } ``` Load it in the playground: save it as `apps/playground/scenes/.json` and open `/?scene=&cam=hero`, or `pnpm shot --scene --cam hero`. | Gotcha | Detail | | --- | --- | | A mesh without `body` has no physics | `sign` above is visual only: nothing collides with it and raycasts miss it. Add `"body": { "type": "static" }` for a solid prop. | | `body` alone defaults to dynamic | `{}` is a dynamic body with friction 0.5, restitution 0, mass from volume at density 1. | | Primitives are unit-sized | Box 1x1x1, sphere diameter 1, cylinder and capsule diameter x by height y. `transform.scale` is the size in metres, and `collider: "auto"` fits it. | | Rotations are quaternions | `[x, y, z, w]`; 90 degrees about Y is `[0, 0.7071, 0, 0.7071]`. | | Objects are strict | An unknown key (`"colour"`, `"size"`) fails validation with its path, e.g. `SceneError: entities[1].mesh: Unrecognized key: "colour"`. | | Ids are unique | A duplicate `id` is an error; `game.ids.get("crate")` maps it to the sim id. | | `bounds` are invisible | Static walls on the XZ rectangle, from y = 0 to `height`. Their ids are `__bounds.`. | | Static colliders may overlap | Static bodies never collide with each other (Rapier skips fixed-fixed pairs), so a static pad sunk into the floor or two overlapping static boxes cost nothing and push nothing. | | Thin colliders | A 0.02 m static box holds resting bodies fine, but a fast body can pass through a thin collider in one tick: give the fast body `"ccd": true`, or make the collider thicker. A target that rules only test by position (an `inZone` check) needs no `body` at all. | | `environment.ground` vs a floor box | `ground` is an infinite static half-space at `ground.y` (friction 0.5, restitution 0, the body defaults); `size` only sizes the visible plane, so bodies never fall off its edge. A static box floor has edges and its own `friction`/`restitution`. Both are spawned by `expandScene`, so Node and the browser get the same floor either way. | | Static visuals are placed once | The renderer places a `static` body's mesh from the state buffer on the first `renderer.sync` after it is added, then never touches it again (dynamic, kinematic and character visuals follow their slot every frame). `teleport` on a static body moves its collider but not its mesh: anything that moves must be `kinematic`. Code that reads or merges static meshes (baking a level into a few draw calls) must wait until after the first frame, when they have their final transforms. | | Collider limits | `plane` only on static bodies; `trimesh` only on static or kinematic ones. | Every field and default: [scene-reference.md](../scene-reference.md). Editor validation: set `"$schema"` to `packages/sdk/scene.schema.json` relative to the file. See it in: [apps/playground/scenes/studio.json](../../apps/playground/scenes/studio.json) (primitives, materials, prefabs), [apps/chain-reaction/levels/base.json](../../apps/chain-reaction/levels/base.json) (a studio base scene), [apps/lanternfall/src/view/present.ts](../../apps/lanternfall/src/view/present.ts) (merging the static level meshes on the first frame, after their placement, lines 227-241). ===== docs/cookbook/prefabs-and-spawners.md ===== # Prefabs and spawners Goal: define a prop once, place copies of it, and rain more of them in at a fixed rate, deterministically. ```json { "version": 1, "environment": { "preset": "studio", "ground": {} }, "sim": { "seed": 7 }, "prefabs": { "crate": { "mesh": { "primitive": "box", "material": { "color": "#a8743f", "roughness": 0.78 } }, "transform": { "scale": [0.5, 0.5, 0.5] }, "body": { "friction": 0.7 } }, "ball": { "mesh": { "primitive": "sphere", "material": { "color": "#3a7be8" } }, "transform": { "scale": [0.3, 0.3, 0.3] }, "body": { "restitution": 0.5 } } }, "entities": [ { "id": "crate-1", "prefab": "crate", "transform": { "position": [0, 0.25, 0] } }, { "id": "crate-big", "prefab": "crate", "transform": { "position": [1.2, 0.5, 0], "scale": [1, 1, 1] } }, { "id": "rain", "spawner": { "prefab": "ball", "rate": 4, "count": 60, "area": { "min": [-2, 4, -2], "max": [2, 6, 2] } } } ] } ``` How it works: - `prefab` is deep-merged under the entity: entity fields win, objects merge key by key (`crate-big` keeps the prefab's mesh and body and only changes `scale`). - A spawner entity has only `spawner` (plus `id` and optional `transform`). The engine's Rust spawner creates `count` bodies, `rate` per second, uniformly inside `area`, from a seeded generator: `spawner.seed`, else `sim.seed` + the entity's index. - `createGame` drains new bodies each frame (`world.drainSpawned()`, flat `(id, slot, spawnerSimId)` triples) and draws them. Dynamic primitive props, spawned or not, are instanced: one draw call per primitive + size + material. | Gotcha | Detail | | --- | --- | | Spawner entity is bare | A `mesh`, `body` or `character` on the spawner entity itself is an error: put them on the prefab. | | Prefab must have a body | And no `character`; the error is on `entities[i].spawner.prefab`. | | Spawned bodies are not in `game.ids` | Track them from `drainSpawned` in your own loop, or by slot. | | Prefab `position` is ignored for spawns | They land in `area`; the prefab's rotation and scale apply. | | Runtime spawners | `world.spawn('{"spawner":{"template":{...},"rate":..,"count":..,"areaMin":[..],"areaMax":[..],"seed":..}}')` works too, but then you drain and draw the bodies yourself; despawn the spawner entity once it is done. | | Own world, own draining | With a custom boot (no `createGame`), check `world.spawnedPending() > 0` before `drainSpawned()` (it allocates). | See it in: [apps/playground/scenes/showcase.json](../../apps/playground/scenes/showcase.json) (prefabs and the `ball-spawner`), [apps/rockfall/src/game/sim.ts](../../apps/rockfall/src/game/sim.ts) (runtime spawners from wave orders, lines 441-475; draining, lines 595-640), [apps/rockfall/src/game/view/rock-view.ts](../../apps/rockfall/src/game/view/rock-view.ts) (drawing drained bodies, lines 68-101). ===== docs/cookbook/bodies-impulses-velocity.md ===== # Bodies, impulses and velocity Goal: push, launch, spin, move and spawn bodies from code, and read their position and velocity back, without allocating per frame. ```ts import type { Game } from "@pebble3d/sdk/game"; const VEL = 12; // linearVelocity writes [vx, vy, vz] to scratch [12..15) export function setup(game: Game) { const world = game.sim.world; const id = game.ids.get("crate"); if (id === undefined) throw new Error('no "crate" in the scene'); const slot = world.slotOf(id); world.applyImpulse(id, 0, 6, 0); // N·s: delta-v = impulse / mass world.applyTorqueImpulse(id, 0, 0.5, 0); // Spawn at runtime (EntityDescJson, camelCase). No visual is created for it. const rock = world.spawn(JSON.stringify({ position: [0, 4, 0], body: { type: "dynamic", mass: 3, collider: { shape: "sphere", radius: 0.25 } }, })); world.setVelocity(rock, 2, 0, 0, 0, 5, 0); // linear m/s, angular rad/s game.onFrame(() => { const v = game.views; // refreshed by createGame before onFrame const y = v.curr[slot * 8 + 1] as number; const asleep = ((v.curr[slot * 8 + 7] as number) & 2) !== 0; if (world.linearVelocity(id) && !asleep) { const vy = v.scratch[VEL + 1] as number; // fell off the world: snap back (NO_INTERP) with zero velocity if (y < -5 || vy < -30) world.teleport(id, 0, 2, 0); } }); } ``` | Gotcha | Detail | | --- | --- | | Body type matters | `applyImpulse`, `applyTorqueImpulse`, `setVelocity` work on dynamic bodies only; `setKinematicPose` on kinematic only. They return `false` otherwise. | | Mass | Default is collider volume at density 1. Scale impulses by mass for a target speed: `m * (target - v)` (Chain Reaction springs). | | Torque is world-frame | `applyTorqueImpulse(id, tx, ty, tz)` takes a world-space angular impulse (N·m·s), not one in the body's local axes: the change in angular velocity is `I⁻¹ · τ` with the inertia tensor rotated to the body's current orientation. To spin about a body axis, rotate that axis into world space first (from the quaternion in `views.curr`). | | Inertia follows the collider | The inertia tensor is the collider's shape at uniform density. With `mass` set, Rapier keeps the shape's tensor and scales it to that mass, so doubling `mass` halves the spin a torque impulse gives. A 2 x 1 x 0.5 m box of 1 kg yawed 90 degrees, given `applyTorqueImpulse(id, 1, 0, 0)`, spins at 2.4 rad/s (`1 / I_zz`, I_zz = m(2² + 1²)/12); at `mass: 10`, 0.24 rad/s. A sphere's inertia is the same about every axis (`0.4 m r²`), so its frame never matters. | | Spheres roll forever | Rapier has no rolling resistance. A ball rolling on flat ground keeps its speed indefinitely with the default `angularDamping: 0` (a 0.5 m sphere set rolling at 3 m/s still does 3.0 m/s after 10 s). Give rolling bodies `"angularDamping"` (0.25 to 0.6 is typical; 0.5 brought that ball to 0.73 m/s after 10 s) and optionally a little `"linearDamping"`. Damping scales velocity by `1 / (1 + dt · damping)` each tick. | | No contact events | The engine reports no collision or contact events. Detect hits in your rules after each `world.step`, from state you already read: the distance between two bodies dropping below the sum of their radii (and the closing speed along the line of centres), or a velocity change in one tick that gravity and your own impulses do not explain. Keep a per-pair "touching" flag so a contact fires once, not every tick. | | Kinematic pose has no scale | `setKinematicPose` sets position and rotation only; a collider's size is fixed at spawn. To resize a body, `despawn` it and `spawn` a new one with the new collider (and resize its visual yourself); to make it vanish, `despawn` it. | | Views go stale | `spawn` can grow wasm memory. Call `game.views.refresh()` after spawning, before reading `curr` or `scratch` in the same frame. | | Spawned bodies are invisible | `world.spawn` creates physics only. Draw it with your own mesh read from its slot, or through `game.renderer.instances.add(key, geometry, material, slot)`. | | Raycasts lag a tick | A body spawned this tick is not hit by raycasts until after the next `step`. | | Free slots | `despawn(id)` frees the slot (flags read 0) and a later spawn may reuse it; drop your slot index too. | | Determinism | Apply forces inside the tick (before `world.step`), from seeded values only, never from frame time. | Full method list and return values: [api-reference.md](../api-reference.md#body-control). See it in: [apps/chain-reaction/src/puzzle/sim.ts](../../apps/chain-reaction/src/puzzle/sim.ts) (spring and fan impulses, lines 217-260; velocity reads, lines 266-293), [apps/katana-defense/src/game/view/zombie-view.ts](../../apps/katana-defense/src/game/view/zombie-view.ts) (spawn a ragdoll capsule and `setVelocity`, lines 496-537), [apps/field-notes/src/main.ts](../../apps/field-notes/src/main.ts) (`teleport` on restart, lines 158-166), [apps/ringout/src/game/sim.ts](../../apps/ringout/src/game/sim.ts) (rolling torque about the travel axis, lines 210-212; impacts from distance and closing speed, lines 341-404), [apps/drift-drone/src/game/sim.ts](../../apps/drift-drone/src/game/sim.ts) (crashes from the velocity the drone would have had with no contact, lines 407-423 and 441-451), [apps/pebble-garden/src/garden/sim.ts](../../apps/pebble-garden/src/garden/sim.ts) (impact sounds from a one-tick velocity change, lines 240-263), [apps/pebble-garden/src/garden/pieces.ts](../../apps/pebble-garden/src/garden/pieces.ts) (a rolling pebble with `angularDamping`, lines 156-163). ===== docs/cookbook/raycasts.md ===== # Raycasts Goal: ground probes, line-of-sight tests and "what did I hit" queries against the physics world. ```ts import type { Game } from "@pebble3d/sdk/game"; const RAY_ALL = 0; const RAY_STATIC = 1; // ground, bounds, static entities only const RAY_EXCLUDE = 2; // everything but `excludeId` /** Height of the ground under (x, z), or 0 when nothing is below. */ export function groundY(game: Game, x: number, z: number, selfId: number): number { const top = 20; const world = game.sim.world; if (!world.raycast(x, top, z, 0, -1, 0, top + 5, RAY_EXCLUDE, selfId)) return 0; return top - (game.views.scratch[0] as number); // scratch [toi, nx, ny, nz, id] } /** True when a static collider blocks the segment from a to b. */ export function blocked(game: Game, a: number[], b: number[]): boolean { const dx = b[0] - a[0], dy = b[1] - a[1], dz = b[2] - a[2]; const len = Math.hypot(dx, dy, dz); return game.sim.world.raycast(a[0], a[1], a[2], dx, dy, dz, len, RAY_STATIC, 0); } /** Scene id of the first body hit, or null. `byId` is game.ids inverted once at startup. */ export function pick(game: Game, byId: Map, o: number[], d: number[]): string | null { if (!game.sim.world.raycast(o[0], o[1], o[2], d[0], d[1], d[2], 100, RAY_ALL, 0)) return null; return byId.get(game.views.scratch[4] as number) ?? null; } ``` | Gotcha | Detail | | --- | --- | | Results live in scratch | `raycast` returns a boolean; the hit is in `game.views.scratch[0..5)`. Read it before the next query (any query overwrites scratch). | | Direction need not be unit | The engine normalises it, so `toi` is metres and `maxToi` is a distance. | | Exclude the caster | A probe from inside a body hits that body first; use filter 2 with its id. | | Spawned this tick = invisible | Queries see the broad phase as of the last `step`. | | Hit id 1 is usually `__ground` | Generated statics (`__ground`, `__bounds.`) are in `game.ids`. Filter 1 still hits the invisible bounds walls; Field Notes skips them by id for its camera arm. | | Views after spawning | If you spawned this frame, `game.views.refresh()` first; a stale view reads detached memory. | Filters and the scratch layout: [api-reference.md](../api-reference.md#raycasts). See it in: [apps/rockfall/src/game/sim.ts](../../apps/rockfall/src/game/sim.ts) (pickup resting height with filter 2, lines 934-951), [apps/ghostline/src/game/sim.ts](../../apps/ghostline/src/game/sim.ts) (marble ground normal from scratch `[1..4)`, lines 359-391), [apps/field-notes/src/game/present.ts](../../apps/field-notes/src/game/present.ts) (camera arm that ignores the bounds walls, lines 94-105), [apps/rockfall/src/game/view/telegraph-view.ts](../../apps/rockfall/src/game/view/telegraph-view.ts) (landing-ring height under each falling rock, the rock excluded, lines 112-116). ===== docs/cookbook/character-and-camera.md ===== # Character and camera Goal: a walking, jumping player with a third-person camera, eased acceleration and animation clips matched to its speed. ```json { "version": 1, "environment": { "preset": "studio", "ground": {} }, "camera": { "controller": "thirdPerson", "presets": { "hero": { "position": [6, 4, 8], "target": [0, 1, 0] } } }, "entities": [ { "id": "player", "mesh": { "primitive": "capsule", "material": { "color": "#4a8fe0" } }, "body": {}, "character": { "speed": 4, "sprintSpeed": 6.5, "jumpSpeed": 5.5, "accel": 14 }, "transform": { "position": [0, 1, 0], "scale": [0.6, 1.8, 0.6] } }, { "id": "step", "mesh": { "primitive": "box" }, "body": { "type": "static" }, "transform": { "position": [2, 0.15, 0], "scale": [1, 0.3, 1] } } ] } ``` `createGame` turns the first entity with a `character` into `game.player`: WASD/arrows move relative to the camera yaw, Space jumps, Shift sprints, and a click pointer-locks the mouse for the camera. A glTF character instead uses an explicit capsule collider and maps clips, as in `apps/field-notes/scenes/yard.json`: ```json { "gltf": { "url": "/assets/rocketbox-male-adult-16.glb", "animations": { "idle": "Idle", "walk": { "clip": "Walk", "speed": 0.979 }, "run": { "clip": "Run", "speed": 5.649 }, "jump": "Jump", "fall": "Fall" } } } ``` (a fragment: the value of `mesh`; pair it with `"body": { "type": "kinematic", "collider": { "shape": "capsule", "halfHeight": 0.5, "radius": 0.3 } }`). | Gotcha | Detail | | --- | --- | | Body is required | `character` needs a kinematic body with a capsule collider. `"body": {}` defaults to kinematic for a character; `collider: "auto"` on a glTF makes a hull, which is rejected, so give the capsule. | | Capsule auto-fit | On a capsule primitive, `scale.y` must exceed `scale.x` (it is the total height). | | `accel` | m/s² toward the input velocity; 0 (default) is instant. 14 ramps a 4 m/s walk in about 0.3 s. | | Clip `speed` | The clip's authored ground speed; playback rate becomes `speed / authored`, clamped to 0.6-1.6, which stops foot sliding. Walk/run switch at 0.75 x `sprintSpeed`. | | Driving it from code | Write `game.player.input` (`keys.f/b/l/r`, `jump`, `sprint`). It is sent as `setCharacterInput` before your `onFrame` runs, so a value set in the frame at tick t is first used by the step that produces tick t + 2. | | Your own `setCharacterInput` for the player | `createGame` calls `setCharacterInput` for `game.player` from `game.player.input` every frame, **including frames that advance 0 ticks** (any display above 60 Hz, where most frames run no tick). If your rules call `world.setCharacterInput(game.player.simId, ...)` themselves only inside the per-tick loop, the rig overwrites that on the next 0-tick frame and the following `world.step` uses keyboard input instead (a demo bot that stops steering, a player who walks on the title screen). Re-send your intent at the end of every `onFrame`, after the tick loop: it then always wins. Or drive the player only through `game.player.input`. | | Which character is the player | The first entity in `entities` (after prefab expansion) that has a `character`. Reorder the entities to change it; there is no option to pick another or to have none while keeping characters. | | More characters | Only the player gets an animated `CharacterView`. Every other character is still moved by the renderer (its root follows its capsule), but plays no clip and never turns until you call `game.renderer.attachCharacter(simId, clipMap)` once, then each frame `world.characterState(simId)` and `view.update(frame, dt)` with `{ grounded, vx, vz, vy, sprintSpeed }` read from scratch `[8..12)`. `update` also turns the model toward its velocity; set `view.root.rotation` after it to face elsewhere. | | Reading it back | `world.characterState(id)` writes `[grounded, vx, vz, vy]` to scratch `[8..12)` (vz before vy). | | Camera | `game.player.camera` (`ThirdPersonController`): `yaw` (0 looks down -Z), `pitch` (-1.2 to 0.3), `distance`. Its arm ray is static-only. `game.setCamera("hero")` suspends it; `"controller"` resumes it. Your own camera instead: [custom-camera.md](custom-camera.md). | | Moving platforms | Set `"ridePlatforms": true` on the `character` to stand on a kinematic body driven by `world.setKinematicPose` each tick: the character moves (and turns about the platform's origin) exactly with it, and keeps its velocity as momentum after a jump or walking off. Without the flag Rapier's own platform friction lags a tick and a character at rest on a kinematic body can get pinned and fail to walk. The reported `characterState` velocity stays the character's own, relative to the platform. Set the platform's pose before the `world.step` it should apply to. A pose jump over 1 m in one tick counts as a teleport and is not carried. While riding, steps up to `stepHeight` are climbed by a lift-and-set-down cast, which ignores autostep's `min_width`. | | Own character | A character spawned with `world.spawn` (no `createGame` rig) is driven only by your `setCharacterInput` calls each tick. | See it in: [apps/field-notes/scenes/yard.json](../../apps/field-notes/scenes/yard.json) (glTF player with `accel`, lines 65-100), [apps/field-notes/src/main.ts](../../apps/field-notes/src/main.ts) (a sim writing `rig.input` from its own buttons, lines 210-218), [apps/playground/src/main.ts](../../apps/playground/src/main.ts) (scripted input and the jump timing, lines 132-179), [apps/rockfall/src/game/sim.ts](../../apps/rockfall/src/game/sim.ts) (character spawned from JSON and driven per tick, lines 264-287 and 373-415), [apps/lanternfall/src/main.ts](../../apps/lanternfall/src/main.ts) (re-sending the sim's intents after every frame's ticks, lines 82-91) with [apps/lanternfall/src/game/sim.ts](../../apps/lanternfall/src/game/sim.ts) (`assertInput`, lines 403-420), [apps/lanternfall/src/view/present.ts](../../apps/lanternfall/src/view/present.ts) (guards animated with `attachCharacter`, lines 155-160 and 248-260), [apps/skyrun/src/game/sim.ts](../../apps/skyrun/src/game/sim.ts) (a runner with `ridePlatforms` on kinematic movers, lines 169 and 206). ===== docs/cookbook/splat-environments.md ===== # Splat environments Goal: use a Gaussian-splat capture as the world, lit by itself, with mesh shadows on its floor and invisible colliders where its walls are. ```json { "version": 1, "environment": { "preset": "outdoor", "hdri": "/assets/qwantani_noon_puresky_2k.hdr", "fog": false, "splat": { "url": "/assets/knock-community-hall-800k.spz", "position": [0, -1.006, 0], "rotation": [0.99997, -0.0006, 7e-5, -0.0077], "scale": 2.2, "envFromSplat": true, "floorY": 0, "exposure": 0.88, "saturation": 1.1 }, "ground": { "y": 0, "size": 80, "visible": false } }, "bounds": { "min": [-6, 7.2], "max": [12.5, 14.2], "height": 4 }, "post": { "toneMapping": "aces" }, "entities": [ { "id": "planter", "body": { "type": "static", "collider": { "shape": "box", "halfExtents": [0.6, 0.4, 0.6] } }, "transform": { "position": [3, 0.4, 10] } } ] } ``` The splat and HDRI come from `pnpm fetch-assets` (served at `/assets/`). Try it: `pnpm shot --scene showcase --cam hero`. | Gotcha | Detail | | --- | --- | | Splats have no physics | Add an invisible `ground` (`visible: false`) at the capture floor, `bounds` for its edges and body-only static entities (no `mesh`) for furniture. | | Align the floor first | Tune `position`/`rotation`/`scale` until the capture floor sits at y = 0, then set `floorY` to it: the invisible shadow catcher goes there and depth of field uses it for ground splats. Field Notes' `?scout=&pose=...` renders a 1 m grid over the splat for this. | | Splats neither cast nor receive shadows | Only meshes cast, onto the shadow catcher. | | `envFromSplat` | Lights meshes from a cube capture of the splat (once, at load) instead of the HDRI; the background stays. | | Colour | `exposure` and `saturation` compensate the tone mapper; `renderer.splatColor` (`exposure`, `saturation`, `tint`) changes them live, for example a dusk grade. | | Formats | `.spz`, `.ply`, `.splat`, `.ksplat`, picked by extension. | | Budget | Above 1,500,000 splats the renderer logs a `console.warn`, which fails `pnpm shot`. Decimate first (the manifest's `derive` step runs `splat-transform`). | | Missing file | A failed load is reported once as a console error and the game runs without the splat (`showcase-badsplat.json` tests this); `pnpm shot` then fails unless you pass `--allow-console-error`. | See it in: [apps/playground/scenes/showcase.json](../../apps/playground/scenes/showcase.json), [apps/field-notes/scenes/courtyard.json](../../apps/field-notes/scenes/courtyard.json) (an interior capture), [apps/field-notes/src/main.ts](../../apps/field-notes/src/main.ts) (obstacles injected as static boxes, lines 75-98), [apps/field-notes/src/scout.ts](../../apps/field-notes/src/scout.ts) (alignment grid), [apps/katana-defense/src/game/view/dusk.ts](../../apps/katana-defense/src/game/view/dusk.ts) (live `splatColor` grade, lines 136-145). ===== docs/cookbook/post-and-toon-style.md ===== # Post-processing and the toon style Goal: tune exposure, tone mapping, bloom and AO, or switch the whole scene to the opt-in cel-shaded look with ink outlines. ```json { "version": 1, "environment": { "preset": "studio", "ground": {} }, "post": { "exposure": 1, "toneMapping": "aces", "bloom": { "enabled": true, "strength": 0.45, "threshold": 1.4 }, "ao": { "enabled": true, "radius": 0.5 }, "style": "toon", "toon": { "bands": 3, "shadowTone": 0.22, "rim": 0.6, "specular": 0.7, "outline": { "width": 1.5, "color": "#1a1418" }, "splat": { "levels": 3, "saturation": 1.3 } } }, "entities": [ { "id": "ball", "mesh": { "primitive": "sphere", "material": { "color": "#e8553a" } }, "body": {}, "transform": { "position": [0, 2, 0] } } ] } ``` `post.style` defaults to `"pbr"`, which ignores `post.toon`. With `"toon"`, scene entities and their glTFs are converted by the renderer. Objects your code builds are not: ```ts import { ToonNodeMaterial } from "@pebble3d/renderer"; const gltf = await game.renderer.loadGltf(url); game.renderer.stylize(gltf.scene); // once, on the cached scene, before any clone (no-op in pbr) const steel = new ToonNodeMaterial({ metalness: 0.85, roughness: 0.22 }); steel.toonRim = 1.5; // multiplies post.toon.rim for this material steel.toonSpecular = 1.6; // multiplies post.toon.specular ``` | Gotcha | Detail | | --- | --- | | Opt-in | Leave `style` unset for PBR. Existing scenes must not change look, so never flip a default. | | Bloom threshold is HDR luminance | The default 2 catches only highlights and emissives; lower it (1.0-1.4) for a softer glow. | | Outlines come from meshes | The ink pass reads a mesh-only depth/normal prepass: splats and transparent meshes get no lines. | | Splats are graded, not shaded | `toon.splat` posterises the capture's lightness into `levels` and tints shadows/highlights. | | One toon style per page | The toon parameters are page-global uniforms (`TOON`); a second renderer overwrites them. `setToonUniforms(settings)` changes them live. | | Check `renderer.style` | `"toon"` or `"pbr"`; shared code can branch on it. `stylize` is safe to call in either. | | Exposure at runtime | `game.renderer.three.renderer.toneMappingExposure` (Field Notes' photo EV, Ronin Outpost's dusk). | Every field and range: [scene-reference.md](../scene-reference.md#post). Look at the result: `pnpm shot --scene showcase-toon --cam hero`. See it in: [apps/katana-defense/scenes/arena.json](../../apps/katana-defense/scenes/arena.json) (toon post, lines 31-52), [apps/katana-defense/src/main.ts](../../apps/katana-defense/src/main.ts) (`stylize` on cached glTFs, lines 120-127), [apps/katana-defense/src/game/view/katana.ts](../../apps/katana-defense/src/game/view/katana.ts) (`ToonNodeMaterial` with rim and specular multipliers, lines 76-88), [apps/playground/scenes/showcase-toon.json](../../apps/playground/scenes/showcase-toon.json). ===== docs/cookbook/depth-of-field.md ===== # Depth of field Goal: a photo-mode blur with a focus distance you control, that also works on splat captures. Depth of field is a renderer control, not a scene field: `game.renderer.dof` (`DepthOfFieldControls`). It is off by default and costs nothing until first enabled. ```ts // Defaults (DOF_DEFAULTS in @pebble3d/renderer): focus 5, range 3, bokeh 1, backdrop 30. const dof = game.renderer.dof; dof.bokeh.value = 1.1; // bokeh size, unitless dof.backdrop.value = 30; // metres assumed for depthless pixels that miss the floor (sky, far walls) let photoMode = false; window.addEventListener("keydown", (e) => { if (e.code === "KeyF") photoMode = !photoMode; }); game.onFrame(() => { dof.enabled = photoMode; if (!photoMode) return; const focus = distanceToSubject(); // metres along the view direction dof.focus.value = focus; dof.range.value = Math.min(8, Math.max(0.35, focus * 0.42)); // metres to full blur }); ``` | Gotcha | Detail | | --- | --- | | First enable builds the chain | The DOF passes are built the first time `enabled` turns true, so that frame does extra work; enable it once early (as a warm-up) if a hitch matters. Toggling afterwards only swaps the pipeline output. | | Values are uniforms | Set `focus.value`, `range.value`, `bokeh.value`, `backdrop.value`, never replace the objects. | | Focus is view depth | Distance along the camera's forward axis, not the straight-line distance to the subject (they differ off-centre). | | Splats have no depth | A pixel with no mesh depth gets a proxy: where its view ray hits the plane at `environment.splat.floorY`, that distance; otherwise `backdrop`. Set `floorY` correctly or ground splats blur wrongly. | | Transparent meshes blur like the backdrop | Additive glows and particles write no depth, so they take the proxy distance of what is behind them even when they sit in focus. | | Tie `range` to the lens | Field Notes uses `focus * 0.42 * (40 / fovDeg)`, clamped to 0.35-8 m: the blur ramp grows with focus distance and with zoom. | See it in: [apps/field-notes/src/game/present.ts](../../apps/field-notes/src/game/present.ts) (`bokeh`/`backdrop` per site, lines 115-117; enable while the camera is raised and drive focus and range, lines 280-290). The controls and defaults are in [api-reference.md](../api-reference.md) (`DepthOfFieldControls`, `DOF_DEFAULTS`). ===== docs/cookbook/deterministic-game-loop.md ===== # Deterministic game loop: input log, replay, ghosts Goal: game rules that advance once per 60 Hz tick from a logged input, so a run replays bit-exactly, can be verified headless, and can race a ghost. The pattern of Ghostline, Chain Reaction and Breakpoint: the game sim owns its `World`s and steps them itself, and `createGame` only renders. (Rockfall does the same without `createGame`; Ronin Outpost's sim is plain JS with the same loop.) The sim reads one input record per tick and nothing else: no DOM, no `Math.random`, no `Date`, no frame time. ```ts import type { SimHandle } from "@pebble3d/sdk/sim"; import { InputLog, type TickInput } from "./input.ts"; // copy apps/ghostline/src/game/input.ts type World = SimHandle["world"]; const DT = 1 / 60; class MySim { tick = 0; readonly world: World; constructor(host: { create(seed: number, g: number): World }, readonly seed: number) { this.world = host.create(seed, -9.81); // spawn bodies here, from seeded values only } step(i: TickInput): void { /* apply i to bodies */ this.world.step(1); this.tick++; } hash(): string { return this.world.stateHash(); } // 16 hex chars free(): void { this.world.free(); } // every World holds wasm memory } // More worlds from the module createGame loaded (apps/ghostline/src/game/physics.ts). const Ctor = game.sim.world.constructor as new (seed: number, g: number) => World; const host = { create: (s: number, g: number) => new Ctor(s, g) }; const sim = new MySim(host, seed); const ghost = best ? new MySim(host, best.seed) : null; // best: { seed, log: InputLog, hash } const log = new InputLog(); // 3 bytes per tick, grows by doubling const input: TickInput = { x: 0, z: 0, buttons: 0 }, ghostInput = { ...input }; // x, z: int8 let acc = 0; game.onFrame((dt) => { acc += dt; let n = 0; for (; acc >= DT - 1e-9 && n < 5; n++) { acc -= DT; sampleInto(input); // live input or bot.next(input): the same type log.push(input); sim.step(input); if (ghost && ghost.tick < best.log.length) ghost.step(best.log.read(ghost.tick, ghostInput)); } if (n === 5) acc = 0; // fell behind: drop time instead of spiralling present(Math.min(1, acc / DT)); // interpolate visuals between ticks }); /** Replay = a fresh world, the same seed, the same inputs; then compare hashes. */ function verify(seed: number, l: InputLog, expected: string): boolean { const s = new MySim(host, seed); try { for (let t = 0; t < l.length; t++) s.step(l.read(t, ghostInput)); return s.hash() === expected; } finally { s.free(); } } ``` | Gotcha | Detail | | --- | --- | | Tick order | Here the sim owns the world: `step()` applies the input, then calls `world.step(1)` (rules, then physics), and nothing else steps that world. `verify` and any Node test call the same `step()`, so the order matches by construction. This differs from the `createGame`-steps-physics pattern in [getting-started.md](../getting-started.md#tick-order) (physics, then rules in `onFrame`); a headless verifier must copy whichever order the browser path uses, ideally by calling the same function. Do not mix them: a sim that calls `world.step` itself must run on its own world, not on `game.sim.world`, which `createGame` already steps. | | Quantise before logging | Store int8 axes (`Math.round(v * 127)`) and feed the sim the same quantised value live and in replay; a float that differs in the last bit diverges. | | Ghosts re-simulate | A ghost is a second world fed the logged inputs in lockstep, not recorded positions. Fingerprint the course and rules into the record and discard stale ones. | | One hash per run | Save `{ seed, inputs, hash }`; `verify` proves the run. Mix game state into it (score, hp) to catch rule drift. `free()` every world on restart. In fixed mode `dt` is exactly 1/60, so one tick runs per frame. | | The `deterministic` build | Bit-identical across runs and between Node and Chromium; `fast` only for the same binary on the same machine. Your own JS math (`Math.sin`...) can still differ between JS engines: Ghostline reports a diverged ghost instead of trusting it. | See it in: [apps/ghostline/src/game/ghost.ts](../../apps/ghostline/src/game/ghost.ts) (ghost record, re-simulation and `verifyRecord`, lines 136-212), [apps/ghostline/src/game/app.ts](../../apps/ghostline/src/game/app.ts) (live run and ghost per tick, lines 463-477; accumulator, lines 559-577), [apps/ghostline/src/game/input.ts](../../apps/ghostline/src/game/input.ts) (int8 `InputLog`, three bytes per tick, serialised as run-length encoded base64), [apps/rockfall/src/game/input.ts](../../apps/rockfall/src/game/input.ts), [apps/rockfall/src/game/rng.ts](../../apps/rockfall/src/game/rng.ts) (seeded mulberry32), [apps/breakpoint/src/game/replay.ts](../../apps/breakpoint/src/game/replay.ts) (instant replay by re-simulation). Testing it: [verification.md](../verification.md#determinism). ===== docs/cookbook/demo-bot-and-captures.md ===== # Demo bot and captures Goal: a `?demo=1` autoplayer that plays the whole loop, and a script of reproducible screenshots driven by it. ```ts /** `?demo=1` autoplayer. Reads only sim state and writes the same TickInput a player does. */ export class DemoBot { private t = 0; current = "start"; // what it is doing, exposed as a probe constructor(private readonly sim: MySim) {} next(out: TickInput): void { this.t++; out.buttons = 0; out.x = 0; out.z = 0; if (this.sim.phase === "title") { if (this.t > 90) out.buttons = BTN.START; // hold the title for 1.5 s this.current = "title"; return; } const g = this.sim.nearestGoal(); // deterministic choice from sim state out.x = Math.round(Math.sign(g.x - this.sim.px) * 127); out.z = Math.round(Math.sign(g.z - this.sim.pz) * 127); this.current = "seek"; } } // main.ts: one input source per tick, chosen once. const bot = q.get("demo") === "1" ? new DemoBot(sim) : null; // in the tick loop: if (bot) bot.next(input); else live.sample(input); Object.assign(window.__pebble3d ?? {}, { game: { phase: () => sim.phase, bot: () => bot?.current ?? null } }); ``` Capture script (`apps//bench/capture-final.sh`, after `apps/rockfall/bench/capture-final.sh`): ```bash pnpm --filter my-game build >/dev/null shot() { local name=$1; shift node scripts/shot/shot.mjs --app my-game --no-build --out artifacts/games/my-game --name "$name" "$@"; } shot 01-title --ticks 240 shot 02-mid-run --ticks 1800 --param demo=1 --param seed=7 shot 03-loop --ticks 1200 --sequence 90:3 --scale 0.6 --no-frames --param demo=1 --param seed=7 ``` | Gotcha | Detail | | --- | --- | | Same input type as a player | The bot must go through `TickInput`, never poke sim fields, so it tests the real path and its runs replay. | | No randomness of its own | Draw from sim state or a seeded `Rng`. Then a capture at tick n is the same frame every run. | | Fix the seed in fixed mode | Games default to a fixed seed when `mode=fixed` (Rockfall 7, Field Notes 23) and pass `--param seed=` explicitly in scripts. | | Scout ticks headless | Run the same sim in Node, in the browser's tick order, until the event (a goal, the result screen) and note the engine tick: `for (t = 0; t < max && !done(); t++) { world.step(1); views.refresh(); bot.next(sim, input); sim.step(input); }` leaves `world.tick()` at the event tick for a `createGame` app. `--ticks n` captures right after engine tick n, so pass the event tick plus how long the result should be visible (e.g. +30 for 0.5 s). Pin it in a test (`expect(eventTick).toBe(...)`) so a rule change that moves it fails loudly. Loop setup: [getting-started.md](../getting-started.md#tests-in-node). | | Read `mode` and `ticks` | Without them the shot never sees `__pebble3d.done` and times out. | | Mute in fixed mode | Audio stays off for captures (see [audio-sfx.md](audio-sfx.md)). | | Look at every PNG | Exit 0 only means no console errors. | See it in: [apps/rockfall/src/game/bot.ts](../../apps/rockfall/src/game/bot.ts) (threat-scoring dodger), [apps/chain-reaction/src/demo.ts](../../apps/chain-reaction/src/demo.ts) (scripted placement then run), [apps/rockfall/bench/capture-final.sh](../../apps/rockfall/bench/capture-final.sh). Every game's bot: [verification.md](../verification.md#demo-bots). ===== docs/cookbook/instanced-crowds-and-perf.md ===== # Instanced crowds and performance Goal: hundreds of bodies or characters at 60 fps on a laptop GPU. Scene props are instanced for you: every dynamic primitive entity (and every spawned body) with the same primitive, size, material and `castShadow` shares one `InstancedMesh`. For bodies your code spawns, add them to the same registry by slot; `createGame`'s `renderer.sync` moves them every frame: ```ts import { BoxGeometry, Color, MeshStandardNodeMaterial } from "three/webgpu"; const geo = new BoxGeometry(0.5, 0.5, 0.5); const mat = new MeshStandardNodeMaterial({ roughness: 0.8 }); const tint = new Color(); const inst = game.renderer.instances; // InstanceRegistry function addRock(id: number, shade: number): void { const slot = game.sim.world.slotOf(id); inst.add("rock|0", geo, mat, slot, tint.setRGB(shade, shade, shade)); // one draw call per key } function removeRock(id: number, slot: number): void { inst.removeSlot(slot); // before (or right after) world.despawn(id) game.sim.world.despawn(id); } // Tiny things skip the shadow cascades. The mesh is replaced when its group grows // (castShadow carries over): look it up with mesh(key), don't keep the reference. const pebbles = inst.mesh("pebble|0"); if (pebbles) pebbles.castShadow = false; ``` | Technique | Where | | --- | --- | | Skinned crowd: clone every avatar up front (`SkeletonUtils.clone`) into a pool sized for the worst wave; never clone mid-fight. | `apps/katana-defense/src/game/view/zombie-pool.ts` (pool sizes), `zombie-view.ts` (clones) | | Blob shadows: one instanced, depth-write-off quad per zombie instead of shadow-casting skinned meshes. | `apps/katana-defense/src/game/view/zombie-view.ts`, lines 81-99 | | `stylize`/look a cached glTF once, then clone: clones share materials. | `apps/katana-defense/src/main.ts`, lines 120-127 | | Cap catch-up ticks (`maxTicksPerFrame: 2`) so heavy physics slows the game instead of spiralling. | `apps/rockfall/src/main.ts`, lines 324-331 | | `"sim": { "build": "fast" }`: the SIMD Rapier build (Rockfall's fast capture holds 1,800 rocks); deterministic only for the same binary on the same machine. | `apps/breakpoint/scenes/site.json`, `apps/rockfall/src/main.ts` (`?build=fast`) | | Physics in a Web Worker, packed state posted back each tick (transferred buffers, pooled). | `apps/breakpoint/src/game/sim.worker.ts`, lines 24-34 and 55-71 | | Sample `world.bodyCounts()` every 30 frames only: it allocates. | `packages/sdk/src/game.ts` (`BODY_COUNT_INTERVAL`) | | Gotcha | Detail | | --- | --- | | No allocation per frame | Preallocate vectors, typed arrays and event records; reuse the `{ ticks, alpha }` object `FixedStepLoop.advance` returns. | | Instance keys must match | A new key is a new `InstancedMesh` (a new draw call). Vary colour per instance (the 5th argument), not material. | | Workers need an inline path for captures | A worker runs on its own clock, so `?mode=fixed&ticks=n` (one tick per frame, `pnpm shot`) cannot be guaranteed through it. Put the sim behind one host interface with two implementations, a worker host and an inline host that runs the same sim code on the main thread, and pick inline whenever `mode` is `fixed` (and for a `?worker=0` debug switch). Node tests use the inline code too. | | Worker wasm URL | Resolve the `?url` import against the page before posting it: `new URL(wasmUrl, location.href).href`. A worker resolves relative URLs against its own script, so a relative build base would otherwise point it at the wrong folder. See [sub-path-hosting.md](sub-path-hosting.md). | | Budgets | Splats 1,500,000 (warns above); shadow cascades 3, max distance 120 m; DPR capped at 2. | | Measure on an idle GPU | Benches: `node apps//bench/fps.mjs`; see [verification.md](../verification.md#benches-and-capture-scripts). | See it in: [apps/rockfall/src/game/view/rock-view.ts](../../apps/rockfall/src/game/view/rock-view.ts) (spawned rocks into the registry, lines 68-101), [apps/swarm-siege/src/main.ts](../../apps/swarm-siege/src/main.ts) (worker only in realtime, inline otherwise, line 81; absolute wasm URL, lines 109-112; host choice, lines 133-135), [apps/swarm-siege/src/game/host.ts](../../apps/swarm-siege/src/game/host.ts) (`InlineHost` and `WorkerHost` behind one interface, lines 90 and 169-230), [apps/breakpoint/src/main.ts](../../apps/breakpoint/src/main.ts) (the same split, lines 85 and 125-157). ===== docs/cookbook/audio-sfx.md ===== # Audio and sound effects Goal: sound cues driven by sim events, with no autoplay warnings and silent captures. Every showcase game synthesises its sound with WebAudio (no audio files): one `AudioContext`, created on the first pointer or key press, a master gain, and one method per cue, fed from the sim's event queue after each tick. ```ts export class Sfx { private ctx: AudioContext | null = null; private master: GainNode | null = null; constructor(readonly enabled: boolean) { if (!enabled) return; const unlock = (): void => { this.ctx ??= new AudioContext(); // only after a user gesture this.master = this.ctx.createGain(); this.master.gain.value = 0.7; this.master.connect(this.ctx.destination); window.removeEventListener("pointerdown", unlock); window.removeEventListener("keydown", unlock); }; window.addEventListener("pointerdown", unlock); window.addEventListener("keydown", unlock); } /** A short pitched blip; `gain` 0..1. */ blip(freq: number, gain: number): void { const ctx = this.ctx, out = this.master; if (!ctx || !out) return; // not unlocked yet, or disabled const osc = ctx.createOscillator(), g = ctx.createGain(), t = ctx.currentTime; osc.frequency.value = freq; g.gain.setValueAtTime(gain, t); g.gain.exponentialRampToValueAtTime(0.001, t + 0.15); osc.connect(g).connect(out); osc.start(t); osc.stop(t + 0.16); } } const sfx = new Sfx(q.get("mute") !== "1" && mode !== "fixed"); // after sim.step(input): for each event of this tick, e.g. if (ev === EV.HIT) sfx.blip(220, 0.4); ``` | Gotcha | Detail | | --- | --- | | Never create the context at load | Chromium warns "The AudioContext was not allowed to start", and `pnpm shot` fails on any console warning. | | Off in fixed mode | Captures and benches run with sound disabled (`mute || mode === "fixed"` in every game). | | Sound is presentation | Play cues from the event queue after the tick; never let audio state feed back into the sim. | | Rate-limit bursts | Cap voices per frame (Rockfall starts at most 4 impact sounds per rendered frame) or a rockslide clips. | | Noise without `Math.random` | Fill noise buffers from a small LCG, as the games do, so nothing random appears near sim code. | | Positional samples | `attachSound(object, listener, url)` from `@pebble3d/renderer` loads a file (cached) into a three.js `PositionalAudio` on an object; no showcase game uses it. | See it in: [apps/rockfall/src/game/audio/sfx.ts](../../apps/rockfall/src/game/audio/sfx.ts) (gesture unlock, noise buffer, impact limit), [apps/chain-reaction/src/audio/sfx.ts](../../apps/chain-reaction/src/audio/sfx.ts), [apps/rockfall/src/main.ts](../../apps/rockfall/src/main.ts) (`sfx.handle(ev, sim)` per tick, line 377). ===== docs/cookbook/json-levels-and-headless-verify.md ===== # JSON levels and headless verify Goal: levels as data files, each proven solvable by running the real engine sim in Node, with the result pinned by a state hash the browser must reproduce. Chain Reaction's level format (`apps/chain-reaction/level.schema.json`) wraps a partial scene in puzzle metadata. `levels/01-first-drop.json` (a level file, not a scene, so no `"version"`; `hint` omitted): ```json { "$schema": "../level.schema.json", "id": "01-first-drop", "name": "First Drop", "grid": { "cols": 12, "rows": 7, "origin": [-6, 0] }, "ball": { "cell": [1, 6] }, "goal": { "cell": [8, 0] }, "inventory": { "ramp": 4 }, "par": 1, "solution": [{ "part": "ramp", "cell": [1, 3], "dir": "right" }], "scene": { "entities": [ { "id": "slab", "prefab": "block", "transform": { "position": [-2, 0.5, 0], "scale": [8, 1, 1] } }, { "id": "backstop", "prefab": "block", "transform": { "position": [4.5, 1.5, 0], "scale": [3, 3, 1] } } ] }, "expect": { "tick": 213, "hash": "526cbffcde43ae4c" } } ``` `composeLevel` deep-merges `scene` over `levels/base.json` (entities appended), adds the placed parts as prefab entities, then runs `parseScene` and `expandScene` like any scene. `PuzzleSim` spawns the result into a fresh `World` and steps it at 60 Hz. The browser and the CLI share that code. ```bash pnpm --filter chain-reaction verify # all levels: "all 6 verified", exit 0 pnpm --filter chain-reaction verify 3 # one level (number, id or id prefix) pnpm --filter chain-reaction verify --file /abs/my.json # a level outside the campaign pnpm --filter chain-reaction verify 3 --placements '[{"part":"fan","cell":[2,6],"dir":"right"}]' # try a candidate pnpm --filter chain-reaction verify --update # rewrite each level's expect {tick, hash} pnpm --filter chain-reaction verify --json # machine-readable rows node apps/chain-reaction/bench/agree.mjs # browser hashes equal Node's (6/6) ``` The same approach for any game: a Node entry that loads the det wasm bytes (`loadSim("deterministic", readFileSync(...))`), builds the sim from the data file, runs a reference input or solution, and compares `world.stateHash()`. ## Spawn a scene and read state in Node What `createGame` does at boot, without a browser (runs in a vitest test or a `node --experimental-strip-types` script): ```ts import { readFileSync } from "node:fs"; import { expandScene } from "@pebble3d/sdk/expand"; import { parseScene } from "@pebble3d/sdk/schema"; import { loadSim, StateViews } from "@pebble3d/sdk/sim"; const bytes = readFileSync(new URL("../../../packages/sdk/wasm/det/engine_core_det_bg.wasm", import.meta.url)); const scene = parseScene(JSON.parse(readFileSync(new URL("../scenes/court.json", import.meta.url), "utf8"))); const handle = await loadSim("deterministic", bytes, { seed: scene.sim.seed, gravity: scene.sim.gravity }); // x.sim is SimEntry[]: { sceneId, desc }, in spawn order "__ground", "__bounds.", then entities. // desc is the engine's EntityDescJson; spawnScene(entries) calls world.spawn(JSON.stringify(e.desc)) for each. const x = expandScene(scene); const ids = handle.spawnScene(x.sim.filter((e) => !x.pendingHulls.includes(e.sceneId))); // Map sceneId -> sim id const views = new StateViews(handle); // views.curr / views.prev / views.scratch over handle.memory const ball = ids.get("ball") as number; const slot = handle.world.slotOf(ball); // -1 if the entity has no slot for (let t = 0; t < 120; t++) { handle.world.step(1); views.refresh(); // cheap no-op unless buffers moved; always call it after spawning or stepping } const base = slot * 8; // per slot: px, py, pz, qx, qy, qz, qw, flags const pos = [views.curr[base], views.curr[base + 1], views.curr[base + 2]]; const vel = handle.world.linearVelocity(ball) ? [views.scratch[12], views.scratch[13], views.scratch[14]] : null; console.log(pos, vel, handle.world.stateHash(), handle.world.tick()); handle.world.free(); ``` | Gotcha | Detail | | --- | --- | | `SimEntry` | `{ sceneId: string; desc: EntityDescJson }`. `sceneId` is the scene `id` (or `__ground`, `__bounds.minX`...); `desc` is what `World.spawn` parses. Spawning `x.sim` in order gives the same ids and the same `stateHash` as `createGame` (for scenes without auto-hull glTF entities; `createGame` spawns those last, see `game.ts`). | | `environment.ground` is spawned too | It is the first entry (`__ground`): a static infinite half-space at `ground.y` with friction 0.5, restitution 0; `size` only sizes the visible plane. So Node and the browser share the floor; you do not need a box entity for it. | | `pendingHulls` | glTF entities with an auto convex hull have empty `points` until the renderer reads the mesh. Node has no renderer: skip them (above), or give those entities an explicit primitive collider. | | `StateViews(handle)` | Takes a `SimHandle` (only `world` and `memory` are read). Views are byte-offset windows on `memory.buffer`; they go stale when wasm memory grows or the world's buffers grow (spawning), which is what `refresh()` checks. Never keep a raw `Float32Array` across a spawn. | | Velocity and queries | `linearVelocity`, `angularVelocity`, `characterState`, `raycast` write into `views.scratch` and return `false` when there is nothing to write (offsets in [api-reference.md](../api-reference.md#scratch-buffer)). Read the scratch right away; the next query overwrites it. | | Allocating reads | `world.transformOf(id)` returns a fresh `Float32Array` (`[px, py, pz, qx, qy, qz, qw]`) or undefined: fine in a test, not in a per-tick path. | | More worlds | `const World = handle.world.constructor as new (seed: number, g: number) => typeof handle.world;` then `new World(seed, g)`, `new StateViews({ ...handle, world: w2 })`, and `w2.free()` when done. | | Tick order | To match a `createGame` browser run, step first, then run rules: see [getting-started.md](../getting-started.md#tick-order). | | Gotcha | Detail | | --- | --- | | A new level needs `--update` | Write the level and its `solution`, then `verify --update`; commit the `expect` it writes. A later engine or rule change that moves the hash fails `verify` until you check and re-pin it. | | `par` | Must be at least the reference solution's part count, or `verify` fails the level. | | One code path | Keep the sim free of DOM and timing so Node and the browser run identical code (`src/puzzle/sim.ts`). | | Register it | New campaign levels are imported in `src/puzzle/levels.ts`. `--file` checks a loose file; pnpm runs the script in `apps/chain-reaction`, so pass an absolute path or one relative to that directory. | | Schema | After changing `LevelSchema`, `pnpm --filter chain-reaction schema` rewrites `level.schema.json`. | | Base prefabs | The `prefab` names a level uses (`block`, `ball`...) live in `levels/base.json`. | See it in: [apps/chain-reaction/src/cli/verify.ts](../../apps/chain-reaction/src/cli/verify.ts) (lines 99-145), [apps/chain-reaction/src/puzzle/compose.ts](../../apps/chain-reaction/src/puzzle/compose.ts) (`composeLevel`, lines 152-256), [apps/chain-reaction/src/puzzle/level.ts](../../apps/chain-reaction/src/puzzle/level.ts) (`LevelSchema`, lines 38-104), [apps/chain-reaction/src/puzzle/node-engine.ts](../../apps/chain-reaction/src/puzzle/node-engine.ts). ===== docs/cookbook/assets-and-licensing.md ===== # Assets and licensing Goal: add a model, HDRI, splat or texture that every app can load, without committing the file and with its licence recorded. Large assets live in `apps/playground/public/assets/` (gitignored) and are fetched by `pnpm fetch-assets` from `apps/playground/assets.manifest.json`. Add an entry: ```json { "id": "character-robot-expressive", "url": "https://raw.githubusercontent.com/mrdoob/three.js/r170/examples/models/gltf/RobotExpressive/RobotExpressive.glb", "sha256": "047f5e5fb3bb6d378bd1df16ca6137f2a596c99b3a1b5690b4020c05aaf6f319", "license": "CC0 1.0", "attribution": "RobotExpressive by Tomás Laulhé (Quaternius, https://quaternius.com); modifications by Don McCurdy; distributed with three.js r170 examples", "file": "RobotExpressive.glb" } ``` (one element of the manifest's `assets` array; it is not a scene). Then: ```bash pnpm fetch-assets --update-hashes # download what is missing, record every file's sha256 in the manifest pnpm fetch-assets # verify every file; regenerates public/assets/LICENSES.md ``` Reference it from a scene as `"/assets/RobotExpressive.glb"` (`mesh.gltf.url`, `environment.hdri`, `environment.splat.url`). Commit the manifest and `LICENSES.md`, never the asset. | Gotcha | Detail | | --- | --- | | Licences | Only licences that allow commercial use: CC0, CC BY, MIT. CC BY-NC captures were rejected. Put the author, source and every modification in `attribution`. | | Pin the URL | Use a commit- or release-pinned URL (`raw.githubusercontent.com/...//...`) so the sha256 stays valid. | | Hash mismatch | `--update-hashes` trusts whatever is on disk, so review the manifest diff: only your new entry should change. A cached file that does not match is re-fetched; if it still does not, it is deleted and the command fails. See [troubleshooting.md](../troubleshooting.md#fetch-assets-hash-mismatch-or-failed-avatar). | | Derived assets | An entry with `derive` builds the file from `url` (checked against `sourceSha256`) with a pinned tool: `splat-transform` for splats (decimate under the 1.5M budget, convert to `.spz`), `scripts/assets/build-rocketbox.mjs` for the Rocketbox avatars. `sha256` is then the derived file's hash. | | Every app sees them | Apps set `publicDir: "../playground/public"` in `vite.config.ts`, so `/assets/...` resolves in all of them. | | Textures | glTF textures may be KTX2; the renderer's loader handles them with the Basis transcoder served at `/basis/` (copy an app's `vite.config.ts`). Load app-managed models with `game.renderer.loadGltf(url)`: cached per url and counted in `stats().textureMB`. | | Serving under a sub-path | Root-absolute URLs (`/assets/...`, `/basis/`) in the scene, in `renderer.loadGltf` and in the transcoder path are prefixed with the asset base: `createGame({ assetBase })`, else `VITE_PEBBLE3D_ASSET_BASE` at build time, else Vite's `--base`, else `/` (unchanged). `vite build --base /x/` alone works because the public dir is copied under `/x/`; the public site shares one copy with `VITE_PEBBLE3D_ASSET_BASE=/pebble3d/`. For other app-loaded files use `renderer.assetUrl(url)`; `attachSound` does not resolve its URL, so pass it `renderer.assetUrl(url)`. | | No file needed | Procedural geometry (Ronin Outpost's katana, `apps/katana-defense/src/game/view/katana.ts`) and synthesised audio need no manifest entry. | See it in: [apps/playground/assets.manifest.json](../../apps/playground/assets.manifest.json), [apps/playground/public/assets/LICENSES.md](../../apps/playground/public/assets/LICENSES.md), [scripts/fetch-assets.mjs](../../scripts/fetch-assets.mjs), [apps/rockfall/vite.config.ts](../../apps/rockfall/vite.config.ts). ===== docs/cookbook/sub-path-hosting.md ===== # Sub-path hosting Goal: serve a game from a URL like `https://example.com/games/skyrun/` instead of the site root, with every asset, the Basis transcoder and the wasm still loading. Scenes and apps write shared files as root-absolute paths: `/assets/qwantani_noon_puresky_2k.hdr`, `/assets/rocketbox-male-adult-16.glb`, `/basis/`. The renderer prefixes those paths with an **asset base**, so the JSON never changes between a dev server at `/` and a build under a sub-path. ```bash # from apps/: everything (page, wasm, public assets, basis/) under /games/skyrun/ pnpm exec vite build --base /games/skyrun/ ``` That is the whole change for a standalone build. Vite's `--base` (or `base: "/games/skyrun/"` in `vite.config.ts`) sets `import.meta.env.BASE_URL`, the renderer uses it as the asset base, and the build already contains what the prefixed URLs point at: | URL in code | Resolves to | Served from | | --- | --- | --- | | `/assets/x.hdr` (scene `environment.hdri`, `splat.url`, glTF `mesh.gltf.url`, `renderer.loadGltf(url)`) | `/games/skyrun/assets/x.hdr` | `dist/assets/`, copied from the shared `publicDir: "../playground/public"` | | `/basis/` (KTX2 transcoder, `createRenderer`'s `transcoderPath` default) | `/games/skyrun/basis/` | `dist/basis/`, emitted by the `basisTranscoder()` plugin in the copied `vite.config.ts` | | `import detWasmUrl from ".../engine_core_det_bg.wasm?url"` | `/games/skyrun/assets/engine_core_det_bg-.wasm` | Vite rewrites `?url` imports for the base itself | | `new Worker(new URL("./sim.worker.ts", import.meta.url), { type: "module" })` | under the base | Vite bundles the worker | ## Where the base comes from First match wins (`packages/renderer/src/asset-base.ts`, `defaultAssetBase`): 1. `createGame({ assetBase })` or `createRenderer(canvas, settings, { assetBase })`. 2. `VITE_PEBBLE3D_ASSET_BASE`, an env var read at build time: the shared files live somewhere other than the game's own base. 3. Vite's `BASE_URL` (the `--base` the app was built with). 4. `"/"`: every URL is returned unchanged. Default builds and the dev server behave exactly as before. `resolveAssetUrl(url, base)` (exported from `@pebble3d/renderer`) prefixes only root-absolute URLs. Relative URLs (`assets/x.glb`), protocol-relative `//host/x` and URLs with a scheme (`https:`, `data:`, `blob:`) pass through, and a URL that already starts with the base is not prefixed twice. ## Several games sharing one copy of the assets `pnpm build:site` (`scripts/build-site.mjs`) builds every game in `site/src/data/games.json` this way: ```bash VITE_PEBBLE3D_ASSET_BASE=/pebble3d/ VITE_PEBBLE3D_WEBGL_FALLBACK=1 \ pnpm exec vite build --base /pebble3d/play// --outDir site/dist/play/ ``` ```text site/dist/ assets/ apps/playground/public/assets, copied once basis/ the Basis transcoder, kept once (LICENSE.txt added) play// one game: index.html and its hashed bundles and wasm in assets/ ``` The page, its JS and its wasm load from `/pebble3d/play//` (Vite's base); scene assets and the transcoder load from `/pebble3d/assets/` and `/pebble3d/basis/` (the asset base). After each game's build the script deletes that game's copies of the shared public files and of `basis/`, so the large splats and HDRIs exist once. ## What is not resolved for you | You load | Do this | | --- | --- | | A file with your own `fetch`, `Audio`, `TextureLoader`, `HDRLoader` | Pass `renderer.assetUrl("/assets/x.ogg")` (the renderer's resolver with its base). | | A sound through `attachSound` | It does not resolve its URL: `attachSound(..., renderer.assetUrl(url))`. | | A glTF through your own `GLTFLoader` | Use `renderer.loadGltf(url)` instead: resolved, cached per url, KTX2-ready, counted in `stats().textureMB`. | | A wasm URL posted to a Web Worker | Make it absolute first: `new URL(detWasmUrl, location.href).href`. A worker resolves a relative URL against its own script, not the page. | | A link to another page of your site | `import.meta.env.BASE_URL + "other/"`. | Without `createGame`, `createRenderer` applies the same default, so an app that boots itself (Skyrun, Swarm Siege) only needs root-absolute paths and the copied `vite.config.ts`. ## Check it ```bash cd apps/ pnpm exec vite build --base /x/ # into dist/ (gitignored) ls dist # assets/ basis/ favicon.svg index.html pnpm exec vite preview --base /x/ --port 5340 # open http://localhost:5340/x/ ``` A 404 in the network tab names the URL that missed its base: usually a hand-written `fetch("/assets/...")` that should go through `renderer.assetUrl`. | Gotcha | Detail | | --- | --- | | Keep paths root-absolute | Write `/assets/x.glb`, not `assets/x.glb` or `./assets/x.glb`: relative paths are never prefixed and break on pages that are not at the base root. | | Copy `vite.config.ts` | It is what serves `/basis/` in dev and emits `dist/basis/` on build; without it KTX2 textures fail under any base. (`apps/ringout` and `apps/drift-drone` load no KTX2 glTF and leave the plugin out, so their builds have no `basis/`.) | | Don't prefix by hand | Leave paths root-absolute and let the asset base do it. A path you prefixed with `BASE_URL` yourself is wrong as soon as `VITE_PEBBLE3D_ASSET_BASE` points somewhere else. | See it in: [apps/skyrun/src/main.ts](../../apps/skyrun/src/main.ts) (root-absolute HDRI, transcoder and runner glTFs with `createRenderer` and `renderer.loadGltf`, lines 86-115), [apps/swarm-siege/src/main.ts](../../apps/swarm-siege/src/main.ts) (absolute wasm URL for the sim worker, lines 109-112), [scripts/build-site.mjs](../../scripts/build-site.mjs) (the shared-assets layout, lines 76-137), [packages/renderer/src/asset-base.ts](../../packages/renderer/src/asset-base.ts). ===== docs/cookbook/custom-camera.md ===== # Custom camera Goal: drive the camera from your own code (a chase cam, a fixed arena view, a top-down follow) without the built-in orbit controls fighting you for it. ## What the scene's `camera.controller` gives you | `controller` | Created by `createRenderer` | Created by `createGame` | Input it takes | | --- | --- | --- | --- | | `"orbit"` (default) | `OrbitController` (three's `OrbitControls`) on the canvas, as `renderer.controller` | nothing more | Drag rotates, wheel zooms, right-drag pans; sets the canvas's `touch-action: none`. | | `"fly"` | `FlyController`, as `renderer.controller` | nothing more | Keyboard and mouse fly-through. | | `"thirdPerson"` | nothing: `renderer.controller` is `null` | a `ThirdPersonController` for the scene's first `character` (`game.player.camera`), or nothing when there is no character | Click to pointer-lock; mouse moves yaw and pitch. | There is no `"none"` value. Two ways get you a camera nobody else moves: - **Dispose the controller** after boot: `renderer.controller?.dispose(); renderer.controller = null;`. Works with any scene. - **`"controller": "thirdPerson"` in a scene with no `character`**: no controller is ever created. Swarm Siege and Skyrun (which boot with `createRenderer`) do this. Always call `dispose()` before setting `null`. Setting `renderer.controller = null` alone only stops the per-frame `update`; three's `OrbitControls` keeps its pointer and wheel listeners on the canvas, and those call `update()` themselves, so a drag still moves the camera between your writes. ## Drive it every frame ```ts import type { Game } from "@pebble3d/sdk/game"; import { Vector3 } from "three/webgpu"; export function ownCamera(game: Game, targetId: string): void { const r = game.renderer; r.controller?.dispose(); // remove OrbitControls' canvas listeners r.controller = null; const cam = r.three.camera; cam.fov = 55; cam.updateProjectionMatrix(); // after any fov / near / far change const id = game.ids.get(targetId); if (id === undefined) throw new Error(`no "${targetId}" in the scene`); const slot = game.sim.world.slotOf(id); const focus = new Vector3(); const want = new Vector3(); let snap = true; game.onFrame((dt) => { const c = game.views.curr; // refreshed by createGame before onFrame want.set(c[slot * 8] as number, c[slot * 8 + 1] as number, c[slot * 8 + 2] as number); // Frame-rate independent easing; snap on the first frame. focus.lerp(want, snap ? 1 : 1 - Math.exp(-5 * dt)); snap = false; cam.position.set(focus.x, focus.y + 12, focus.z + 9); cam.lookAt(focus); }); } ``` `onFrame` runs after `renderer.sync` (every visual is already at its interpolated pose) and before `renderer.render`, so a camera written there never lags a frame. To follow a visual rather than the raw tick state, read its object: `game.player.view.root.position` for the player character. ## A spring arm without the built-in rig `ThirdPersonController` (from `@pebble3d/renderer`) works on its own: give it the camera and a ray function, call `update(pivot, dt)` each frame, and `connect(canvas)` if the mouse should steer it. ```ts import { ThirdPersonController } from "@pebble3d/renderer"; const STATIC_ONLY = 1; // raycast filter: moving props never pull the arm in const tpc = new ThirdPersonController(camera, (o, d, max) => { if (!world.raycast(o.x, o.y, o.z, d.x, d.y, d.z, max, STATIC_ONLY, 0)) return null; views.refresh(); // re-read scratch: wasm memory may have grown return views.scratch[0] as number; }); tpc.distance = 6.4; tpc.pitch = -0.3; tpc.connect(canvas); // per frame: tpc.update(pivot, dt); yaw 0 looks down -Z ``` | Gotcha | Detail | | --- | --- | | Character movement follows the camera | `createGame` turns WASD into a world direction using `game.player.camera.yaw` when the rig has a third-person camera, else the yaw of `renderer.three.camera`. Owning the camera of a character scene with `"orbit"` plus `dispose()` keeps "W = away from the camera" working. With `"thirdPerson"`, setting `game.player.camera.enabled = false` stops it moving the camera, but movement still uses its (now frozen) yaw. | | Presets and `pnpm shot --cam` | `game.setCamera("hero")` and `__pebble3d.setCamera` apply the preset straight to the camera when there is no controller, but your next `onFrame` overwrites it. Keep a flag and skip your camera code while a preset is active; replace `__pebble3d.setCamera` if the preset path must work in captures. | | Shadow cascades | The sun's cascades are fitted to the camera frustum. `renderer.resize` refits them; after changing `fov`, `near` or `far` yourself, call `updateCsmFrustums(renderer.csm)` (exported from `@pebble3d/renderer`). | | Things parented to the camera | The camera is not in the scene graph by default. `renderer.three.scene.add(camera)` before attaching a viewmodel or HUD mesh to it. | | Camera collision | Cast with filter `1` (static only) as above; a dynamic prop in the ray makes the camera pop in and out. | See it in: [apps/drift-drone/src/game/app.ts](../../apps/drift-drone/src/game/app.ts) (dispose the orbit controller and own the camera, lines 139-145) with [apps/drift-drone/src/game/view/camera-rig.ts](../../apps/drift-drone/src/game/view/camera-rig.ts) (chase cam kept out of walls by a static-only raycast, lines 71-120), [apps/ringout/src/game/app.ts](../../apps/ringout/src/game/app.ts) (lines 114-121), [apps/lanternfall/src/view/present.ts](../../apps/lanternfall/src/view/present.ts) (top-down follow of a character, lines 262-285), [apps/skyrun/src/game/view/camera-rig.ts](../../apps/skyrun/src/game/view/camera-rig.ts) (a standalone `ThirdPersonController`, lines 35-51), [apps/skyrun/src/main.ts](../../apps/skyrun/src/main.ts) (`setCamera` presets next to a game camera, lines 340-347), [apps/swarm-siege/scenes/plateau.json](../../apps/swarm-siege/scenes/plateau.json) (`"thirdPerson"` with no character, line 24). ===== docs/cookbook/owning-the-world.md ===== # Owning the world Goal: keep `createGame` for the renderer, the canvas and the automation hook, but run your game in physics worlds your code creates, steps, draws and throws away (a fresh world per round, a replay world beside the live one, a level editor's Play button). `createGame` loads one wasm module and makes one `World` for the scene. Any number of extra worlds can come from that same module: ```ts import type { Game } from "@pebble3d/sdk/game"; import { type SimHandle, StateViews } from "@pebble3d/sdk/sim"; import { expandScene } from "@pebble3d/sdk/expand"; import { parseScene } from "@pebble3d/sdk/schema"; type World = SimHandle["world"]; export function worldMaker(h: SimHandle): (seed: number, gravity: number) => World { const Ctor = h.world.constructor as new (seed: number, gravity: number) => World; return (seed, gravity) => new Ctor(seed, gravity); } export class Round { readonly world: World; readonly views: StateViews; readonly ids: Map; tick = 0; constructor(game: Game, sceneJson: unknown) { const scene = parseScene(sceneJson); this.world = worldMaker(game.sim)(scene.sim.seed, scene.sim.gravity); this.ids = new Map(); for (const e of expandScene(scene).sim) this.ids.set(e.sceneId, this.world.spawn(JSON.stringify(e.desc))); // StateViews only needs the world and the module's memory. this.views = new StateViews({ ...game.sim, world: this.world }); this.world.step(1); // raycasts see nothing until the first step this.tick = 1; this.views.refresh(); } step(): void { // rules that write forces / kinematic poses go here, then: this.world.step(1); this.tick++; this.views.refresh(); } free(): void { this.world.free(); } } ``` ## Step it from `onFrame` `createGame` keeps stepping its own (now idle) world; your world advances only when you call `step()`. Run it on an accumulator fed by `onFrame`'s `dt`: ```ts const DT = 1 / 60; let acc = 0; game.onFrame((dt) => { acc += dt; let n = 0; while (acc >= DT - 1e-9 && n < 5) { acc -= DT; round.step(); n++; } if (n === 5) acc = 0; // drop the backlog instead of spiralling view.sync(round, Math.min(1, acc / DT)); // alpha for interpolation }); ``` In fixed mode `onFrame`'s `dt` is exactly `1/60` per frame and 0 once `stopAtTick` is reached, so this runs one tick per frame and stops with `createGame`'s world: `pnpm shot --ticks n` still captures your world at tick n (plus the step in the constructor, if you keep it). ## Draw its bodies The renderer only draws `createGame`'s world: `renderer.sync` and `renderer.instances` read `game.views`, whose slots mean nothing for your world. Build your own meshes and place them from your views with `readSlot` (from `@pebble3d/renderer`), which interpolates and honours `NO_INTERP`: ```ts import { primitiveGeometry, readSlot } from "@pebble3d/renderer"; import { Mesh, MeshStandardNodeMaterial, Quaternion, Vector3 } from "three/webgpu"; const _p = new Vector3(); const _q = new Quaternion(); export class RoundView { private readonly items: { mesh: Mesh; slot: number }[] = []; add(game: Game, round: Round, id: string, size: [number, number, number]): void { const mesh = new Mesh(primitiveGeometry("box", size), new MeshStandardNodeMaterial()); mesh.castShadow = true; game.renderer.three.scene.add(mesh); const simId = round.ids.get(id) as number; this.items.push({ mesh, slot: round.world.slotOf(simId) }); } sync(round: Round, alpha: number): void { const { prev, curr } = round.views; for (const it of this.items) { const on = it.slot >= 0 && readSlot(prev, curr, it.slot, alpha, _p, _q); it.mesh.visible = on; // false once the slot is freed if (on) { it.mesh.position.copy(_p); it.mesh.quaternion.copy(_q); } } } } ``` `primitiveGeometry(primitive, size)` builds the same geometry the renderer uses for scene primitives, at the real size. For many identical bodies, one `InstancedMesh` you fill from the slots is cheaper than one mesh each. ## Report your world to automation `pnpm shot` writes `__pebble3d.stateHash()` into the sidecar, and `createGame` installs it for **its** world. Point it at yours, or every capture reports the same idle hash: ```ts Object.assign(window.__pebble3d ?? {}, { stateHash: () => round.world.stateHash(), game: { tick: () => round.tick }, }); ``` | Gotcha | Detail | | --- | --- | | One memory for every world | All worlds from one module share one `WebAssembly.Memory`. A `spawn` in *any* world (createGame's included) can grow it, which detaches every `Float32Array` over the old buffer: views of other worlds read zeros (`byteLength` 0). Call `views.refresh()` after spawning or stepping, and read `views.curr` / `views.scratch` from the object each time instead of keeping the array in a local or a field. | | Scratch after a query | Query results land in the shared scratch region. Read them right after the call, through `views.scratch` after a `refresh()` (cheap: it compares four numbers and returns). | | Raycasts on a new world | A world that has never stepped has an empty query structure: every `raycast` returns false, even onto a static floor. Step once after spawning (as above) before probing. Bodies spawned later are likewise invisible to raycasts until the next step. | | Free what you make | `world.free()` when a round ends; wasm memory is not garbage-collected. | | Same seed, same order | Spawn order and seed decide the state hash; spawning from `expandScene(scene).sim` in order matches `createGame` and Node. | | Keep the scene small | `createGame` still needs a valid scene: an environment and a camera preset are enough. Its world steps every frame, so leave dynamic bodies out of it. | | The camera | The orbit controller is still on the canvas; see [custom-camera.md](custom-camera.md). | | Node | The same `Round` class runs in a test with `loadSim("deterministic", bytes)` as the handle, so the browser and the verifier call one code path. | See it in: [apps/pebble-garden/src/garden/sim.ts](../../apps/pebble-garden/src/garden/sim.ts) (worlds from the loaded module, lines 43-46; spawn from `expandScene` and views, lines 133-186; one tick, lines 221-237) with [apps/pebble-garden/src/view/garden-view.ts](../../apps/pebble-garden/src/view/garden-view.ts) (meshes from `primitiveGeometry`, placed with `readSlot`, lines 165-176), [apps/ringout/src/game/physics.ts](../../apps/ringout/src/game/physics.ts) (world factory and views that re-point after growth, lines 15-70), [apps/ringout/src/game/app.ts](../../apps/ringout/src/game/app.ts) (accumulator in `onFrame`, lines 491-503; alpha, lines 563-569), [apps/ringout/src/main.ts](../../apps/ringout/src/main.ts) (`stateHash` override, lines 95-99), [apps/pebble-garden/src/main.ts](../../apps/pebble-garden/src/main.ts) (lines 182-186), [apps/lanternfall/src/game/sim.ts](../../apps/lanternfall/src/game/sim.ts) (raycast work deferred to the first tick, lines 325-329). ===== skills/make-a-game/SKILL.md ===== --- name: make-a-game description: Use when a developer asks for a game, a game prototype or a playable demo built with Pebble3D (for example "make me a game where...", "build a racing game", "prototype this idea"). Start here before writing any game code. --- # Make a game The front door for every game request in this repo. It fixes the order of work and the check that ends each step. The other skills hold the how; this one holds the sequence. Follow it in order and do not skip ahead to code. Assumptions: you are in a clone of the Pebble3D monorepo, the game becomes a new app in `apps//` like the demos in `apps/`, and the repo is set up (`pnpm i`; no Rust needed, see [docs/getting-started.md](../../docs/getting-started.md)). The working rules for the repo are in [AGENTS.md](../../AGENTS.md). ## The sequence interview → brief → scaffold → build → game feel → art pass → complete loop → verify | Step | Load | Exit check before moving on | | ------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | Interview | [game-interview](../game-interview/SKILL.md) | Every open question is answered, defaulted, or written down as an assumption. | | Brief | [game-interview](../game-interview/SKILL.md) (its last section) | `apps//BRIEF.md` exists and the developer said yes to it (or, non-interactive, its assumptions are marked). | | Scaffold | [start-a-game](../start-a-game/SKILL.md) | `pnpm --filter dev` serves the scene, the first capture shows it (not black), zero console errors, `npx vitest run --project ` runs. | | Build | [engine-pitfalls](../engine-pitfalls/SKILL.md), then [genre-playbooks](../genre-playbooks/SKILL.md) for the closest genre | The core verbs from the brief work with the keyboard, the `?demo=1` bot performs them, and sim tests pass. | | Game feel | [game-feel](../game-feel/SKILL.md) | Every player action has visible and audible feedback; a capture sequence shows it. | | Art pass | [art-direction](../art-direction/SKILL.md) | Captures match the "look" section of the brief; palette, lighting and post are one committed style, not defaults. | | Complete loop | [complete-game-loop](../complete-game-loop/SKILL.md) | Title → play → win or lose → results → restart works by keyboard and by the `?demo=1` bot; README lists controls and URL params. | | Verify | [verify-your-work](../verify-your-work/SKILL.md) | Everything in that skill passes. **`verify-your-work` defines done; never report done without it.** | Load [verify-your-work](../verify-your-work/SKILL.md) early too: run its quick checks (a capture, the console, the tests) at the end of every step from scaffold on, not only at the end. A step whose capture you have not looked at is not finished. Load [engine-pitfalls](../engine-pitfalls/SKILL.md) whenever something renders black, throws, times out in a capture, or behaves differently in Node and the browser. Look up the symptom there and in [docs/troubleshooting.md](../../docs/troubleshooting.md) before debugging from scratch. ## What the developer may skip The developer decides; you do not skip on their behalf. - **Interview**: "just build it", or a request that already answers what the player does, the look, controls, players and scope. You still write `BRIEF.md`, with the defaults listed under assumptions, and show it. - **Developer approval of the brief**: only when they said not to wait. Then proceed on the assumptions and say so in your first progress message. - **Game feel, art pass**: only for an explicitly throwaway prototype ("just the mechanic, grey boxes are fine"). Record the skip in `BRIEF.md` under out of scope. - **Complete loop**: the same rule; a mechanic test may stop at "play". Keep the `?demo=1` bot anyway, because verification drives it. - **Never skippable**: scaffold, build, and verify. A game that was not captured, looked at and tested is not delivered. If the developer changes direction mid-way, update `BRIEF.md` first, then continue from the earliest step the change affects. ## Working habits - One step at a time. Finish its exit check, tell the developer in one or two lines what now works, then load the next skill. - Show, do not describe: when a step changes what is on screen, share the capture with the progress message. - Study before inventing. The demos in `apps/` solve most problems a new game hits; [docs/examples.md](../../docs/examples.md) lists what each one shows, and the cookbook in [docs/cookbook/](../../docs/cookbook/README.md) has the recipes. - Keep the repo invariants from [AGENTS.md](../../AGENTS.md): seeded randomness only in the sim (no `Math.random` or `Date`), no per-frame allocation, no engine changes. If the game needs an engine feature, tell the developer instead of editing `packages/` or `crates/`. - Original work only: never name, copy or imitate an existing commercial game, its characters or its art. - Online multiplayer is not available (the engine has no netcode). Offer local multiplayer on one keyboard or bot opponents, as `apps/ringout` does. ## Reporting done Only after `verify-your-work` passes, report: what was built (link `BRIEF.md`), how to run it (`pnpm --filter dev` and the URL), the controls, the captures you looked at, test results, and any assumption or skip still open. ===== skills/game-interview/SKILL.md ===== --- name: game-interview description: Use when a game request leaves open what the player does, how it should feel or look, the controls, the players or the scope, and you need a short design brief the developer approves before any code is written. --- # Game interview Turn a request ("a game where you bounce enemies off the edge") into `apps//BRIEF.md`, a one-page brief the developer says yes to. The goal is to learn what they picture, not to fill a form. Next: `start-a-game`. ## Rules - **At most six questions, one per message.** Wait for the answer before the next. - **Ask only what the request leaves open.** If they said "racing game with a drone", do not ask what the player does. - **Propose, do not interrogate.** Once you know _why_ they want the game, offer a concrete default and let them correct it: "I'd make it one screen, top-down camera, three lives. Sound right?" beats "How many lives?". - **Biggest unknown first.** Usually the look or what the player does. A good opener restates the request in one sentence, then asks one open question about the vaguest word in it: "When you say very stylized, what do you picture?" - **Show, when the look is their call.** Words fail for visuals; see "Mockups" below. - Never name or suggest imitating an existing commercial game. If the developer names one, ask what they like about it (the feel, the camera, the pace) and write that down instead of the title. - Keep a running list of what you have decided. That list becomes the brief. ## The six topics In rough priority order. Skip any the request or an earlier answer already settles. | Topic | What you need | Default to propose if they shrug | | -------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | What the player does | The core verbs (roll, dash, jump, place, shoot) and the goal of a round | One verb plus one special move, a round that ends in a win or a loss | | The feel | Pace and weight: floaty or heavy, frantic or calm, forgiving or punishing | Responsive and weighty, short rounds, quick restart | | The look | Style, palette, mood, camera; what it should remind them of (in their words) | One committed style suggested by the theme (for example toon with bold outlines) | | Controls, platform | Keyboard, mouse, gamepad, touch; desktop or phone browser | Keyboard on a desktop browser | | Players | Single player, local multiplayer on one keyboard, or online | Single player against bots | | Scope of v1 | What the first playable version contains, and what waits | One arena or level, the full loop (title, play, results, restart) | **Players:** the engine has no online netcode. If they want online play, say so plainly and offer local multiplayer on one keyboard, bot opponents, or both, as `apps/ringout` does ([its README](../../apps/ringout/README.md)). Put online play under out of scope. ## Mockups When the look (or a visual effect) is the developer's call and they cannot describe it, offer to show options instead of asking: 1. Write a throwaway HTML page outside the app (a temp folder is fine) with a few small animated variants side by side: for example four hit-effect styles, three palettes, or two camera angles. Label each with a letter. 2. Open it in their browser and ask which one is closest, or what to mix. 3. If they pick one and want more detail, make a second, more detailed page of that one. 4. When the choice depends on how it looks in the real renderer, do a quick in-engine test: a scene file in `apps/playground/scenes/` captured with `pnpm shot --scene ` (the file name without `.json`; see [docs/getting-started.md](../../docs/getting-started.md)). Delete the test scene afterwards. Keep mockups cheap: minutes, not hours. They decide a direction; they are not the game. ## Non-interactive or "just build it" If you cannot hold a back-and-forth (a headless run, a tool without replies) or the developer says "just build it": 1. If you can send one message and get one reply, ask all your open questions in that single message, each with the default you will use, so they can answer only the ones they care about. 2. If there is no reply, or they said "just build it", use the defaults from the table above (adjusted to whatever the request did say). 3. Write `BRIEF.md` anyway, with every default listed under **Assumptions**, and continue without waiting for approval. Mention the assumptions in your first progress message so the developer can correct them. ## Writing the brief 1. Pick the app name: short, lowercase, hyphenated, original (not a commercial title), and not already a folder in `apps/`. It is also the package name and the `--filter` name. 2. Copy [brief-template.md](brief-template.md) to `apps//BRIEF.md` (create the folder; `start-a-game` fills in the rest). Fill every section in the developer's words where you can. Keep it to one page. 3. Show it to the developer: "Here is the brief. Yes, or what should change?" Edit until they say yes. 4. Exit check: `BRIEF.md` exists, has no empty sections, and is approved (or its assumptions are marked, in the non-interactive case). ===== skills/start-a-game/SKILL.md ===== --- name: start-a-game description: Use when creating a new game app under apps/ in the Pebble3D repo, before writing gameplay code, to scaffold it the way the demos are laid out and prove it boots, captures and runs its tests. --- # Start a game Scaffold `apps//` so it builds, serves, captures and tests like the demos do, before any gameplay exists. `` is the app name from `apps//BRIEF.md`. Next: build the game (`make-a-game` says which skill). The full walkthrough with every file is [docs/getting-started.md](../../docs/getting-started.md) (section "A minimal game app"). This skill is the checklist and the template to copy. ## Template: Ringout Copy the layout of `apps/ringout`, a small, complete game (title, play, results, rematch, bot, captures). Read these before copying: | File | Take from it | | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [package.json](../../apps/ringout/package.json) | Scripts `dev` (with `--port --strictPort`), `build`, `preview`, `test`, `typecheck`; deps `@pebble3d/sdk`, `@pebble3d/renderer` (`workspace:*`) and the pinned `three`. Change `name` and the port. | | [vite.config.ts](../../apps/ringout/vite.config.ts) | `publicDir: "../playground/public"`, `appType: "mpa"`, `server.fs.allow`, the env var for the build base. Rename the env var. If the game loads glTF or KTX2, copy [apps/rockfall/vite.config.ts](../../apps/rockfall/vite.config.ts) instead: it adds the Basis transcoder plugin. | | [index.html](../../apps/ringout/index.html) | ``, a HUD root, the favicon link, the module script. | | [src/main.ts](../../apps/ringout/src/main.ts) | URL params documented in the top comment and parsed strictly; `createGame` with both wasm `?url` imports, `mode`, `backend`, `stopAtTick`; `window.__pebble3d` probes; `main().catch` writing `__pebble3d.error`. | | [README.md](../../apps/ringout/README.md) | Sections: what it is, Run it (commands and a URL param table), Controls, What it shows off, Known issues. | | [bench/capture-final.sh](../../apps/ringout/bench/capture-final.sh) | Build once, then one `pnpm shot` per moment with `--no-build`, a fixed `--port`, `--param demo=1`; stops on the first failure. | Also copy `tsconfig.json` and `vitest.config.ts` from `apps/ringout/` (change the project `name`). Keep game code under `src/game/` (sim, bot, input, UI) and scenes under `scenes/`. Start with the smallest scene that shows something: a ground, a light preset, one player body. ## Checklist 1. **Folder and files.** Create the files above in `apps//`. `BRIEF.md` is already there from `game-interview`; do not overwrite it. 2. **Pick an unused port.** List the ports in use: ```bash grep -rhoE -- '--port[ =][[:digit:]]+' apps/*/package.json apps/*/bench | sort -u ``` Pick a free one for `dev` (keep `--strictPort`, so a clash fails loudly instead of moving), and a different free one for the capture script's `--port`. Ringout uses 5270 for dev and 5271 for captures. Note the default playground dev server uses 5173. 3. **Register the tests.** Add `"apps/"` to the `projects` array in the root `vitest.config.ts`, next to the other apps. Without it the app's tests never run and `--project ` matches nothing. 4. **Demo mode.** Parse `?demo=1` in `src/main.ts` and drive the game with a bot that writes the same input a player produces. At this stage the bot can be trivial (press start, move toward something); it grows with the game. See [docs/cookbook/demo-bot-and-captures.md](../../docs/cookbook/demo-bot-and-captures.md). 5. **Fixed-tick mode.** Read `mode` and `ticks` and pass `stopAtTick`, or every `pnpm shot` times out. 6. **WebGL fallback.** `createGame` already honours `?webglFallback=1` (see [docs/troubleshooting.md](../../docs/troubleshooting.md)): do not pass `webglFallback: false`, and support `?backend=webgl` like Ringout does. Check both URLs load. 7. **Sub-path builds.** Keep asset URLs root-absolute (`/assets/...`) and build URLs in code from `import.meta.env.BASE_URL`, so the game can be hosted under a sub-path: [docs/cookbook/sub-path-hosting.md](../../docs/cookbook/sub-path-hosting.md). 8. **Install.** Run `pnpm install` at the repo root so pnpm links the workspace packages. 9. **A first test.** One Node test in `test/` that loads the scene and steps the sim with the real wasm (pattern in [docs/getting-started.md](../../docs/getting-started.md), "Tests in Node"). ## Exit check All of these, before any gameplay work. The dev server never exits, so start it in the background or a second terminal (not in the same shell before the other commands, which would block), and leave it running while you open the pages: ```bash npx vitest run --project # runs your test (not "No projects were found") pnpm --filter typecheck pnpm shot --app --param demo=1 --ticks 120 --name first pnpm --filter dev & # background; open http://localhost:/ and /?demo=1 ``` - The shot exits 0, its `.json` sidecar has an empty `console` array, and you opened the PNG whose path the shot prints: the scene is visible, not black or empty. - `?webglFallback=1` and `?backend=webgl` load without errors. - `pnpm lint` is clean for the new files. If the shot fails or the frame is black, look up the symptom in [docs/troubleshooting.md](../../docs/troubleshooting.md) (a missing `pnpm i` after a pull is the usual cause). ===== skills/verify-your-work/SKILL.md ===== --- name: verify-your-work description: Use when a Pebble3D game or app change looks finished, at the end of every make-a-game step from scaffold on, or before telling anyone a game works. Defines done: tests, captures, sidecars, looking at every image, both backends. --- # Verify your work This skill is the definition of done. A game is not done because it compiles or because a capture exited 0. It is done when the checks below pass and you have looked at what the player will see. Never report done without it. The reference for every command and flag is [docs/verification.md](../../docs/verification.md). The demo bot and capture script pattern is [docs/cookbook/demo-bot-and-captures.md](../../docs/cookbook/demo-bot-and-captures.md). Any failure: look it up in [docs/troubleshooting.md](../../docs/troubleshooting.md) before debugging from scratch. `` below is the app folder under `apps/`. ## Quick checks (end of every step) Run these at the end of every [make-a-game](../make-a-game/SKILL.md) step from scaffold on. They take a minute and catch most regressions. ```bash npx vitest run --project pnpm shot --app --param demo=1 --ticks 600 --name check ``` 1. The tests pass, and the output shows your test files ran (not "No test files found"). 2. The shot exits 0. Its last line names the backend, adapter, tick and `stateHash`. 3. Open the `.json` sidecar next to the PNG and read it (next section). 4. Open the PNG whose path the shot prints, and look at it (the section after). A step whose capture you have not opened is not finished. ## Read the sidecar Every capture writes a `.json` sidecar beside the PNG. Check each field; a capture that exits 0 can still be wrong. | Field | Pass when | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `console` | An empty array. Never allowlist your own errors to get there; fix them. A warning counts too: fix it, or explain it in the README's known issues with the reason. Never leave one silent. | | `adapterInfo` | `backend` is the one you asked for, and the device names a real GPU, not SwiftShader or llvmpipe. | | `tick` | The tick you asked for with `--ticks`. | | `stateHash` | Different between captures of different moments in a game that moves. The same hash everywhere means the hook reports an idle world: [stateHash never changes](../../docs/troubleshooting.md#the-shot-statehash-never-changes). | | `game` | Your `__pebble3d.game` probes read what the frame should show: the phase (title, playing, results), the bot's current action, score. | Run the same capture twice: the `stateHash` must match. If it does not, the sim is not deterministic: [determinism hash mismatch](../../docs/troubleshooting.md#determinism-hash-mismatch). ## Look at every image Open every PNG (and the animated WebP from a `--sequence`) with your image viewer or file reader. Exit 0 only means nothing errored. For each one, check and write down: - **Not blank.** Not black, not white, not a flat sky with nothing in it. A black or white frame on WebGL only: [WebGL outdoor black/white](../../docs/troubleshooting.md#webgl-outdoor-scene-is-black-or-white). - **The subject is in frame.** The player, the goal and the threat are visible and readable at a glance, not hidden behind scenery or off screen. - **The moment is the one you meant.** The title capture shows the title, the results capture shows results. If not, move the tick (scout it headless, as the cookbook's "Scout ticks headless" row explains). - **The HUD is readable.** Text not clipped or overlapping, contrast against the scene, numbers that make sense. - **It matches the brief.** The palette, lighting and mood in the "look" section of `apps//BRIEF.md`, not engine defaults. - **No rendering faults.** Flickering or z-fighting surfaces, stretched textures, floating or sunken objects, characters in a bind pose. Describe what you saw in one line per image in your report. If you cannot describe it, you did not look. Reading the `.json` sidecar is not looking: the sidecar cannot show a black frame, a clipped HUD or the wrong moment. Every PNG and WebP you captured gets opened and gets its own line, including the ones from the capture script and the WebGL run. ## The full check (before reporting done) All of these pass, in this order. 1. **Unit and sim tests.** `npx vitest run --project `. The app has a determinism test written like `apps/rockfall/test/sim.test.ts`: the same seed and input log run twice give the same `world.stateHash()`, and one changed input gives a different one. 2. **Types and lint.** `pnpm typecheck` and `pnpm lint`. Lint must add no new warnings for your files. 3. **The capture script.** `bash apps//bench/capture-final.sh` exits 0. It covers at least title, mid-play, a win or loss, the results screen and one `--sequence` of the core action, all driven by the `?demo=1` bot. Read every sidecar and look at every image, as above. 4. **The demo bot plays the whole loop.** The captures and the `game` probes show it reaching results and restarting, with the same input type a player produces. 5. **The WebGL path.** WebGPU is not everywhere: Firefox, Safari and many Linux Chromium builds get WebGL. Capture with `--backend webgl` and look at it; it must exit 0 and look like the WebGPU capture. Then load the game with `?webglFallback=1`, headed (the dev server in a browser) or headless (`pnpm shot --app --param webglFallback=1 --param demo=1 --name fallback`), and check it boots and plays with no console errors; do the same for `/?backend=webgl`. `createGame` reads `webglFallback` from the URL by itself; never pass `webglFallback: false`. 6. **Performance, when you claim it.** Build, then run the app's fps bench on an idle GPU, on both backends, in a browser that reached the real GPU. Numbers from a headless run on SwiftShader, or from one backend only, prove nothing: [misleading fps](../../docs/troubleshooting.md#fps-from-a-headless-or-webgl-run-is-misleading) and [low or noisy fps](../../docs/troubleshooting.md#fps-numbers-are-low-or-noisy). The target is 60 fps. 7. **Engine determinism, only if engine code changed.** Games should not change `packages/` or `crates/`. If something did change there, run `pnpm build:wasm` and the determinism script from [AGENTS.md](../../AGENTS.md); it must print `2d76d9927e780425`. 8. **The README.** `apps//README.md` lists how to run it, the controls and every URL param the game reads (including `demo`, `seed`, `mode`, `ticks`, `backend`), and a known-issues section for any console warning you could not fix, each with its reason. ### Exit lines for the full check Each of these is a line you can write truthfully in your report, or the check is not done: - **Every capture opened.** I opened every PNG and WebP I captured (not only the sidecars), and my report has one line per capture saying what it shows. - **WebGL fallback loaded.** I loaded the game with `?webglFallback=1` (headed or headless) and it booted and played with no console errors. - **No silent console messages.** Every console error and warning from every capture and page load is fixed, or listed in the README's known issues with the reason. ## When headless WebGPU has no adapter The right action depends on the symptom. 1. **`software/fallback adapter (SwiftShader) refused`** (often after `shot: headless got a software adapter; retrying headed`). Only this case retries: `pnpm shot` tries once more in a visible window, and only with a display (`DISPLAY` or `WAYLAND_DISPLAY` set). Pass `--headed` to go straight there. Details: [SwiftShader adapter](../../docs/troubleshooting.md#shot-refuses-a-swiftshader-adapter). 2. **`BackendUnavailable: webgpu (WebGPURenderer fell back to WebGL)` or `requested backend webgpu but the page ran webgl`.** The shot does not retry these; headed alone will not help. Open `chrome://gpu` in the same Chromium and read the WebGPU line. On Linux, WebGPU is often off: launch with `--enable-unsafe-webgpu --enable-features=Vulkan --use-angle=vulkan` (`pnpm shot` already does). Details: [BackendUnavailable: webgpu](../../docs/troubleshooting.md#backendunavailable-webgpu). To check the fallback itself rather than WebGPU, capture with `--param webglFallback=1` or `--backend webgl`; that is a WebGL check and does not stand in for the WebGPU capture. 3. **Your own boot must report the adapter.** A custom boot without `createGame` has to fill `__pebble3d.adapterInfo`, or the software check cannot work: [SwiftShader adapter](../../docs/troubleshooting.md#shot-refuses-a-swiftshader-adapter). 4. **No GPU at all** (a container, a remote shell without a display): you cannot verify rendering there. Still run the Node tests, typecheck and lint, then tell the developer plainly that no capture was taken and why, and ask them to run the capture script on a machine with a GPU. Do not switch to WebGL on SwiftShader, allowlist the error, or describe images you did not see. ## Reporting done Report only after the full check passes: - What was built, with a link to `apps//BRIEF.md`. - How to run it: `pnpm --filter dev` and the URL, plus the controls. - Test, typecheck and lint results, as the commands printed them. - The captures you looked at, each with the PNG path the shot printed and your one-line description of it. - Which backends you checked, and fps only if you measured it as above. - Anything skipped or still open, and every assumption from the brief that the developer has not confirmed. If any check failed and you could not fix it, say which one and what you saw. A precise "not done yet" is worth more than a false "done". ===== skills/engine-pitfalls/SKILL.md ===== --- name: engine-pitfalls description: Use when building gameplay with Pebble3D, and whenever something renders black, throws, times out in a capture, or behaves differently in Node and the browser. Known engine traps as "if you see X, do Y", each linked to the full fix. --- # Engine pitfalls Traps that cost the demo builders hours. Read the whole list once before the build step of [make-a-game](../make-a-game/SKILL.md), then come back by symptom. Each line says what to do; the link has the cause and the full fix in [docs/troubleshooting.md](../../docs/troubleshooting.md). Do not debug from scratch before checking here. ## Rendering - **`BackendUnavailable: webgpu`** → the browser has no WebGPU. Open with `?webglFallback=1` or `?backend=webgl`, or launch Chromium with the WebGPU flags; check `chrome://gpu`. [Fix](../../docs/troubleshooting.md#backendunavailable-webgpu) - **Outdoor scene black or white on WebGL only** → load HDRIs through the engine's environment loader, not your own PMREM. [Fix](../../docs/troubleshooting.md#webgl-outdoor-scene-is-black-or-white) - **Your camera drifts when the mouse drags or scrolls** → dispose the default orbit controller after boot and set it to null. [Fix](../../docs/troubleshooting.md#the-orbit-camera-fights-your-camera) - **A second character slides in its bind pose** → only the player gets an animated view; attach the others yourself. Entity order picks the player. [Fix](../../docs/troubleshooting.md#other-characters-do-not-animate) - **A teleported static body's mesh stays put** → anything that moves must be `"kinematic"`. [Fix](../../docs/troubleshooting.md#a-static-mesh-does-not-move) - **Night or interior scene looks like daylight** → lower the scene's `environmentIntensity` and add a fixed pool of three.js point lights; the schema has only a sun. [Fix](../../docs/troubleshooting.md#a-night-scene-is-too-bright) - **Draw calls jump with each character** → shadow casters draw once per cascade; turn shadows off for props, crowds and decals. [Fix](../../docs/troubleshooting.md#draw-calls-climb-with-each-character) - **Toon ink lines around decals on a splat floor** → make the decals transparent materials. [Fix](../../docs/troubleshooting.md#decals-on-a-splat-floor-get-ink-outlines) - **Two captures of the same tick differ by a few pixels** → normal GPU noise; compare `stateHash`, not bytes. [Fix](../../docs/troubleshooting.md#two-identical-shots-differ-slightly) ## Physics and sim - **`world.setVelocity is not a function`, or a feature silently does nothing** → stale wasm after a Rust change: `pnpm build:wasm`, commit `packages/sdk/wasm/`, restart the dev server. [Fix](../../docs/troubleshooting.md#stale-wasm-setvelocity-is-not-a-function) - **Determinism hash mismatch** → stale wasm first, then `Math.random`/`Date`/wall-clock `dt` in the sim, then the `fast` build. [Fix](../../docs/troubleshooting.md#determinism-hash-mismatch) - **Node test hash differs from the browser at the same tick** → mirror the browser tick order exactly: physics step, refresh views, bot, rules. [Fix](../../docs/troubleshooting.md#headless-hash-differs-from-the-browser) - **Bot or rules input ignored on high-refresh displays** → re-send your character input at the end of every frame, after the tick loop. [Fix](../../docs/troubleshooting.md#your-setcharacterinput-is-overwritten) - **Reads return zeros after a spawn** → a spawn detached the views; call `views.refresh()` and read through the views object. [Fix](../../docs/troubleshooting.md#state-views-read-zeros-after-a-spawn) - **Raycast misses on a world you just built** → step once before the first query. [Fix](../../docs/troubleshooting.md#raycasts-miss-on-a-new-world) - **You want collision callbacks** → there are none; detect contacts in your rules from distances and velocities. [Fix](../../docs/troubleshooting.md#there-are-no-contact-events) - **A ball rolls forever** → set `angularDamping` on rolling bodies. [Fix](../../docs/troubleshooting.md#spheres-roll-forever) - **The game crawls under heavy physics** → cap ticks per frame, consider the `fast` build or a worker. [Fix](../../docs/troubleshooting.md#heavy-physics-makes-the-game-crawl) - **You need a per-tick hook or runtime spawns** → `createGame` has neither; advance your own sim in `onFrame` or boot like Rockfall. [Fix](../../docs/troubleshooting.md#creategame-has-no-per-tick-hook) - **Level switch leaves the old game running** → one game per page; new worlds inside it, or reload with new params. [Fix](../../docs/troubleshooting.md#a-second-game-on-the-same-page) - **Scene errors appear one per run** → validate with `SceneSchema.safeParse` and print every issue. [Fix](../../docs/troubleshooting.md#only-the-first-scene-error-is-reported) - **`TS2352` on an imported scene JSON** → cast through `unknown`. [Fix](../../docs/troubleshooting.md#ts2352-when-passing-an-imported-scene-json) ## Assets and hosting - **404 for `/favicon.ico` or an asset fails a capture** → add the favicon link, run `pnpm fetch-assets`, copy a demo's `vite.config.ts`. [Fix](../../docs/troubleshooting.md#shot-fails-on-a-404) - **Assets, transcoder or wasm 404 under a sub-path** → keep URLs root-absolute and pass hand-loaded ones through `renderer.assetUrl`. [Fix](../../docs/troubleshooting.md#assets-404-under-a-sub-path) - **`fetch-assets` hash mismatch or failed avatar** → check the download; the avatar build is linux-x64 only. [Fix](../../docs/troubleshooting.md#fetch-assets-hash-mismatch-or-failed-avatar) ## Captures, benches and toolchain - **Shot times out on `__pebble3d.done`** → read `mode` and `ticks` from the URL and pass `stopAtTick`; catch boot errors into `__pebble3d.error`. [Fix](../../docs/troubleshooting.md#shot-times-out-waiting-for-__pebble3ddone) - **Shot refuses a SwiftShader adapter** → run where a real GPU and a display exist, or `--headed`; a custom boot must report its adapter. [Fix](../../docs/troubleshooting.md#shot-refuses-a-swiftshader-adapter) - **`--out must be inside` the capture folder** → omit `--out`, or keep it under the default capture folder. [Fix](../../docs/troubleshooting.md#shot---out-rejected) - **Sidecar `stateHash` never changes** → point `__pebble3d.stateHash` at the world your game really runs. [Fix](../../docs/troubleshooting.md#the-shot-statehash-never-changes) - **Fixed-mode captures flaky with a worker sim** → run the sim inline in fixed mode, the worker only in realtime. [Fix](../../docs/troubleshooting.md#fixed-mode-captures-with-a-worker-sim) - **fps looks good headless, or only WebGL was measured** → confirm a real GPU renderer string and measure both backends. [Fix](../../docs/troubleshooting.md#fps-from-a-headless-or-webgl-run-is-misleading) - **Low or swinging fps** → another process is using the GPU; measure on an idle one. [Fix](../../docs/troubleshooting.md#fps-numbers-are-low-or-noisy) - **A copied fps bench measures the wrong thing** → change its port, query string and polled phases. [Fix](../../docs/troubleshooting.md#a-copied-fps-bench-measures-the-wrong-thing) - **`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX` in a Node script** → no constructor parameter properties or `enum` in code Node imports. [Fix](../../docs/troubleshooting.md#parameter-properties-fail-in-a-node-script) - **A new app's tests never run** → add its `vitest.config.ts` and register it in the root `projects` list. [Fix](../../docs/troubleshooting.md#a-new-apps-tests-never-run) - **`pnpm docs` does nothing** → it is a pnpm builtin; use `pnpm docs:gen`. [Fix](../../docs/troubleshooting.md#pnpm-docs-does-nothing-useful) - **`scene.schema.json` stale or in a merge conflict** → never hand-merge; regenerate it. [Fix](../../docs/troubleshooting.md#sceneschemajson-is-stale) - **`!important` vanished after a lint fix** → never run biome `--unsafe` over CSS. [Fix](../../docs/troubleshooting.md#biome---unsafe-removed-important) ## Before you invent a workaround The demos in `apps/` hit most of these and solved them; [docs/examples.md](../../docs/examples.md) says which demo shows what, and the cookbook in [docs/cookbook/](../../docs/cookbook/README.md) has the patterns. If the fix needs an engine change, stop and tell the developer instead of editing `packages/` or `crates/`. Then prove the fix with [verify-your-work](../verify-your-work/SKILL.md). ===== skills/game-feel/SKILL.md ===== --- name: game-feel description: Use when a Pebble3D game's core actions work but feel flat, at the game-feel step of make-a-game, or when a hit, jump, dash or win needs more impact. Layers hit-stop, shake, camera punch, trails, particles, decals, buffering, easing and sound, then tunes them by watching capture sequences. --- # Game feel A game whose mechanics work is a tech demo. A game where every press gets an answer you can see and hear, and the big moments land with weight, is a game. This skill is the polish half of the build: it comes after the core verbs work and before the art pass. The values to start from, with the demo file that uses each one, are in [techniques.md](techniques.md). Ronin Outpost (`apps/katana-defense`) is the densest reference: read [present.ts](../../apps/katana-defense/src/game/present.ts), where every sim event becomes feedback. ## The process 1. **Pick the moments.** From the brief, choose the three to five moments that matter most: the hit, the jump, the kill, getting hurt, the win. Write them in `BRIEF.md` under a "feel" heading. Polish these deeply; everything else gets a basic cue. 2. **Give every action an answer.** Before layering, check that every input the player can make produces a visible change and a sound within a tick or two. Missing feedback is the most common reason a game feels broken. 3. **Layer each big moment.** Build the stack below, one layer at a time, capturing after each. 4. **Tune by watching** (the loop at the end). Feel lives in motion; a single frame cannot show it. ## The layers Not every moment needs every layer. A heavy hit takes the full stack; a footstep takes a puff and a tick of sound. | Layer | What it does | Lives in | | ----------------- | ---------------------------------------------------------------------- | ------------ | | Hit-stop | Freezes both sides for a few frames on contact, so the hit reads solid | sim | | Impact frame | One to three frames of high-contrast flash on the heaviest hits | presentation | | Screen shake | Trauma that decays; the offset is trauma squared | presentation | | Camera punch | The lens narrows by a few degrees and springs back | presentation | | Slow motion | Game time drops for the one decisive moment, then eases back | presentation | | Trails | A tapering ribbon behind the striking edge or a fast body | presentation | | Particles | Sparks, chunks and dust that arc with gravity and land | presentation | | Persistent decals | Pools, cracks and rings that stay on the floor after the action | presentation | | Telegraphs | Enemy wind-ups drawn on the ground before the hit | presentation | | Input buffering | A press slightly early still counts; cancel windows chain moves | sim | | Easing | Wind-up, strike, follow-through; exponential approach for cameras | both | | Sound | A cue per action and per hit, scaled by weight | presentation | **A heavy hit reads best as a stack**, in this order on the timeline: the hit-stop freeze, an impact frame, screen shake starting as the freeze ends, a brief camera punch-in, a tapering trail on the striking limb that hangs during the freeze, particles that burst and arc with gravity, and decals that stay on the floor after the particles land. Each layer alone is subtle. Together they sell weight. **Scale by weight.** Light, heavy and finisher hits should differ on every layer: Ronin Outpost's light cuts freeze for fewer frames, shake less and do not punch the camera at all. If everything is maximal, nothing is. **Keep the sim deterministic.** Hit-stop and buffering change gameplay, so they are sim state driven by ticks. Everything else reads the sim's events after the tick and never writes back. No `Math.random` in either: spread particles with offsets from the loop index, and shake with sums of sines. ## Input feel - Buffer presses for a few frames and let a press just after a move ends still chain ([combo.ts](../../apps/katana-defense/src/game/combat/combo.ts)). Presses during hit-stop are buffered too. - Give moves cancel windows so the follow-up starts the moment the current move's commitment ends. - For movement: allow a jump pressed just before landing and just after leaving a ledge. Never drop a tap shorter than one tick ([live-input.ts](../../apps/skyrun/src/game/live-input.ts)). - Camera and character followers ease with `1 - Math.exp(-k * dt)`, never a fixed lerp per frame. Recipes: [custom-camera.md](../../docs/cookbook/custom-camera.md). ## Sound Every action and every hit gets a WebAudio cue fired from the event queue after the tick, louder and lower for heavier events. Unlock the context on the first gesture, cap voices per frame, and keep sound off in fixed mode. The pattern and its gotchas: [audio-sfx.md](../../docs/cookbook/audio-sfx.md). ## Budget Effects cost fill rate, and layered additive effects can cost several times more on the WebGL backend than on WebGPU. Pool every effect (one preallocated `InstancedMesh` per kind, oldest recycled), cap counts, and measure fps on both backends with the effects on screen, as [verify-your-work](../verify-your-work/SKILL.md) describes, before adding more. ## Tune by watching captures Stills can look great while the motion is stiff. Judge feel in a sequence: ```bash pnpm shot --app --param demo=1 --ticks --sequence 90:2 --scale 0.6 --no-frames --name feel-hit ``` `--sequence` writes an animated WebP of the moment (flags: [docs/verification.md](../../docs/verification.md); a real script with sequences: [capture-final.sh](../../apps/ringout/bench/capture-final.sh)). Find the tick of the moment by scouting it headless ([demo-bot-and-captures.md](../../docs/cookbook/demo-bot-and-captures.md)). Then loop: 1. Watch the sequence. For each chosen moment, name what is missing or too much: "the hit has no freeze", "the shake hides the target", "the sparks vanish in place". 2. Change one value, recapture the same tick with the same seed, and compare. 3. Stop when each moment reads at a glance in the sequence and a still from the middle of it still shows what happened (trail, particles in the air, a mark on the floor). ## Exit check - Every player action has a visible and an audible answer. - Each chosen moment has its layer stack, scaled by weight, and a `--sequence` capture that you watched shows it. - Sim tests still pass and the determinism test still holds (feel code did not leak randomness or presentation state into the sim). - The effects are pooled, and fps on both backends with the effects on screen is checked when you claim performance. Next: [art-direction](../art-direction/SKILL.md). ===== skills/art-direction/SKILL.md ===== --- name: art-direction description: Use when a Pebble3D game's look is still engine defaults, at the art-pass step of make-a-game, or when captures look flat, muddy or inconsistent. Commits to one look from the brief (palette, toon or PBR, lighting, post, composition) and judges captures against it over at least two improvement passes. --- # Art direction Default lighting on grey boxes reads as a tech demo, whatever the mechanics. A committed look, one palette, one lighting mood, one rendering style, carried through every object and the HUD, reads as a game. You do not need imported art for it: every demo below builds most of its world from primitives and code. The scene fields for everything here are in [docs/scene-reference.md](../../docs/scene-reference.md); the post and toon recipe is [post-and-toon-style.md](../../docs/cookbook/post-and-toon-style.md). ## Commit to one look Write the look in the "look" section of `apps//BRIEF.md` before touching the scene, in one short paragraph a stranger could check a screenshot against: - **Mood and time of day.** "Dusk on a floating stone arena", "noon in a dusty quarry", "a dark keep lit only by lanterns". - **Palette.** A background family, a ground family and one or two accent colours reserved for what the player must notice: the player, the threat, the goal, pickups. Write the hex values. - **Style.** Toon or PBR (next section), and why it fits. - **Reference.** One or two of the reference captures below that are closest in spirit, and what you take from each. Every later choice is checked against this paragraph. If a choice does not serve it, drop it. ## Toon or PBR | Choose | When | Demo | | ------ | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `toon` | Stylised characters, action, readability over realism; mixing primitives with glTF models | Ronin Outpost: [arena.json](../../apps/katana-defense/scenes/arena.json) | | `pbr` | Materials are the point (stone, metal, glass), physics debris, a moody lit interior | Breakpoint: [site.json](../../apps/breakpoint/scenes/site.json); Ringout: [arena.json](../../apps/ringout/scenes/arena.json) | `post.style: "toon"` bands the lighting, adds a rim and ink outlines. Objects your code builds need `ToonNodeMaterial` or `renderer.stylize`; the recipe has the details. Pick one and apply it everywhere: a toon character on a PBR ground with no outline reads as a mistake. ## Lighting and sky - **Outdoor** (`environment.preset: "outdoor"`): an HDRI sky lights the scene; pick one that matches the time of day, and set the sun direction and colour to agree with it. Breakpoint pairs a clear noon sky with a warm sun. - **Studio** (`"studio"`): a gradient backdrop from `horizon` to `zenith` and range fog of the same colour. Ringout uses a deep violet horizon, a navy zenith and a peach sun: a whole mood from three colours. - **Dark interiors**: low ambient, and the light comes from things in the world (lanterns, emissive pickups), as in Lanternfall. Make sure the player and the threat are always lit. - A low, warm, side-on sun gives long shadows and shape; a sun straight overhead flattens everything. - Fog hides the ground's far edge and separates depth layers. Tint it to the sky. ## Post - **Tone mapping and exposure.** `agx` (the default) is soft and natural; `aces` is punchier and more saturated. Raise exposure until the ground reads, not until whites clip. - **Bloom** only on what should glow: emissives, beams, effects. Lower the threshold for a softer glow, never so low that sunlit ground blooms. - **AO** grounds objects on the floor. Leave it on unless you measured it costing too much. - Runtime changes (a dusk grade over waves, a photo exposure) go through `toneMappingExposure`, as the recipe shows. ## Composition and silhouettes - **Readable at a glance.** In a capture shrunk to thumbnail size, you can still find the player, the threat and the goal. If not, fix value contrast first (light against dark), then colour. - **Silhouettes.** Each kind of actor has a distinct shape: size, proportions, a hat or a weapon. Ringout gives every orb its own team colour and a name plate; Swarm Siege keeps towers pale and the swarm saturated. - **Accent colour is information.** Reserve the brightest, most saturated colours for gameplay (the player, danger, pickups, the HUD's key number). Scenery stays quieter. - **Camera framing.** The default view puts the action in the middle third with space in the direction of travel. Title and results screens can use a slow orbit with the subject off centre, leaving room for text, as Ronin Outpost and Ringout do. ## Stage dressing from primitives An empty plane is the biggest tell of a tech demo. Dress the stage with what the brief's world would contain, built from boxes, cylinders and spheres with distinct materials: walls and crates, posts and rope, rocks, columns, distant silhouettes on the horizon. Vary scale and colour slightly per instance (seeded, never `Math.random` in the sim). Breakpoint's sites are hundreds of boxes; Skyrun's floating islands are simple shapes over a sea of cloud. Dressing should frame the play space, never hide the player. ## The HUD is part of the look Use one type family, the palette's accent for the numbers that matter, a translucent panel colour taken from the scene, and consistent corner placement. The HUD must not cover the action. Compare the HUDs in the Ringout, Skyrun and Swarm Siege captures below. ## Reference captures Committed looks from the demos (the site's 1280x720 WebP captures; how they are made: [site/README.md](../../site/README.md)): | Look | Capture | | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Toon outdoor, ink outlines, a blade trail | [Ronin Outpost, light combo](../../site/public/shots/ronin-outpost/03-light-combo-slash.webp), [dusk wave](../../site/public/shots/ronin-outpost/08-dusk-wave8.webp) | | PBR stone under noon sun, dust and debris | [Breakpoint, impact](../../site/public/shots/breakpoint/03-impact.webp) | | Studio dusk backdrop, team colours, bold HUD | [Ringout, opening clash](../../site/public/shots/ringout/03-opening-clash.webp), [ring drop](../../site/public/shots/ringout/05-ring-drop.webp) | | Dark interior lit by lanterns, a vision cone | [Lanternfall, creep](../../site/public/shots/lanternfall/02-creep.webp) | | Pastel sky, floating islands, soft fog | [Skyrun, spire](../../site/public/shots/skyrun/14-spire.webp) | | Night, neon beams on a dark ground, a saturated swarm | [Swarm Siege, firefight](../../site/public/shots/swarm-siege/05-firefight.webp) | | Racing, motion and speed | [Drift Drone](../../site/public/shots/drift-drone/09-photo-finish.webp), [Ghostline](../../site/public/shots/ghostline/08-ember-glamour.webp) | Open them before you start and name, in the brief, what you take from one or two. ## Judge and improve The art pass is at least two passes, each ending in captures you looked at. 1. Capture the moments from the brief (title, mid-play, the big moment, results) with the `?demo=1` bot, as [verify-your-work](../verify-your-work/SKILL.md) describes. Open every PNG the shot prints. 2. Put each capture next to the look paragraph and the reference you chose. Write down, per capture, the three biggest gaps: "ground is flat grey", "the player disappears against the wall", "bloom washes out the HUD", "the sky does not match the sun". 3. Fix the biggest gaps, recapture the same ticks with the same seed, and compare side by side. 4. Repeat at least once more. Stop when a stranger would describe the capture in the brief's words. Check the WebGL backend too (`--backend webgl`): fog, bloom and the toon pass must look the same there. ## Exit check - The look paragraph in `BRIEF.md` names a palette with hex values, the style, the lighting and a reference capture. - Captures of title, mid-play, the big moment and results match it; no engine-default grey ground or default sky remains unless the brief chose it. - The player, the threat and the goal read in a thumbnail. - At least two judge-and-improve passes, each with captures you opened. Next: [complete-game-loop](../complete-game-loop/SKILL.md). ===== skills/complete-game-loop/SKILL.md ===== --- name: complete-game-loop description: Use when a Pebble3D game plays but has no beginning or end, at the complete-loop step of make-a-game, or before calling a game finished. Adds title, play, results and restart, pause, the HUD, a demo bot that plays the whole loop, a README with controls and sourced numbers, and captures of every screen. --- # Complete game loop A mechanic you can play forever with no start screen, no goal and no ending is a prototype. A game has a title that says what to do, a round that can be won or lost, a results screen that says how you did, and a key that starts again. This skill wraps the core play in that loop and documents it. Template: Ringout (`apps/ringout`) has every piece here at small scale: title with seat setup, countdown, rounds, an instant replay, results, rematch, a bot and a capture script. Read [its README](../../apps/ringout/README.md) and [app.ts](../../apps/ringout/src/game/app.ts) first. ## The phases ``` title → play → (win | lose) → results → restart → play ... ``` - **Phases are sim state.** Keep the phase in the sim and change it with a pure transition function, like Ronin Outpost's `nextPhase` in [phase.ts](../../apps/katana-defense/src/game/phase.ts): title, pre-wave, wave, wave clear, upgrade, victory, game over. A test can then drive the whole loop in Node, and the phase feeds the determinism hash. - **Every play phase has an end.** A win condition and a lose condition from the brief, and if the game could stall, a limit (Ringout ends a round as a draw after a fight-tick limit, `MAX_FIGHT_TICKS` in [constants.ts](../../apps/ringout/src/game/constants.ts)). - **Restart resets everything.** Score, timers, entities, the camera, the HUD and the seeded RNG (from a new or the same seed, as the brief says). A restart that leaks state from the last round is the most common loop bug: test it by playing two rounds in a row in Node and comparing the second round's hash with a fresh first round on the same seed. ## Title screen - The game's name, one line on the goal, the controls in brief, and "press Enter" (or click). The brief's look applies here too: this is the first frame anyone sees. - Put something alive behind it: a slow camera orbit over the arena (Ronin Outpost and Ringout both do), or an attract round played by the bot. Leave room on one side for the text. - Any setup (players, difficulty, match length) lives here with keyboard shortcuts, as on Ringout's title. - A `?title=1` style param that stays on the title helps the capture script. ## Play and the HUD - The HUD shows only what the player needs to decide: the score or progress toward the goal, health or lives, a timer if time matters, and the state of the core verb (a cooldown, a meter, ammo). Ringout's HUD is a DOM overlay ([ui/hud.ts](../../apps/ringout/src/game/ui/hud.ts)); its look follows [art-direction](../art-direction/SKILL.md). - Announce phase changes on screen: the round banner, "Wave clear", a countdown to the next hazard. A toast for big events (a knock-out, a new best). - Show the controls somewhere on first play: a hint bar along the bottom, or the title. - A `hud=0` param hides it for clean captures. ## Pause - Esc (or P) pauses: stop stepping the sim, freeze presentation time, mute or duck sound, and show a small panel with resume, restart and quit to title. In a one-screen local game, Esc may simply return to the title, as Ringout does. - Pause when the tab is hidden too, so time does not pile up: Breakpoint listens for `visibilitychange` ([main.ts](../../apps/breakpoint/src/main.ts)). Clear held keys on window blur, or the player keeps running after alt-tab. - Pause is not sim input in a replayable game: it stops ticks, it is not recorded as a tick. ## Results and restart - Say who won or what the outcome was, in big type, then the numbers that matter for this game: score, time, best, per-player stats (Ringout shows wins, knock-outs, dashes and the hardest hit per seat). Show a personal best if the brief wants replay value. - One key restarts, one returns to the title. Name both on the screen. - **Lock confirm keys briefly** when a results or replay screen appears, so a player still mashing the action key does not skip it. Ringout's `MenuGate` swallows Enter and Space for `LOCK = 0.75` s ([gate.ts](../../apps/ringout/src/game/gate.ts)). - Optional but strong: an instant replay of the decisive moment before results, re-simulated from the input log, as Ringout and Breakpoint do. ## The demo bot plays the whole loop `?demo=1` drives everything through the same input type a player produces: it presses start on the title, plays the round to a win or a loss, waits on results, and restarts. Expose `phase` and the bot's current action as `__pebble3d.game` probes so captures and sidecars show where it is. The pattern: [demo-bot-and-captures.md](../../docs/cookbook/demo-bot-and-captures.md). Pin the ticks of the loop's key moments (first win, results, restart) in a test so a rule change that moves them fails loudly. **The bot must finish the loop on most seeds, not just one.** A bot that loses or stalls on most seeds makes every capture of results, replay and restart luck. Write a Node test that runs the bot headless over a range of seeds, counts the runs that reach the results phase within a tick limit, and asserts that share is a clear majority. A sketch, with your own sim and bot names: ```ts it("the demo bot reaches results on most seeds", () => { let reached = 0; const seeds = Array.from({ length: 20 }, (_, i) => i + 1); for (const seed of seeds) { const sim = makeSim(seed); const bot = makeBot(sim); while (sim.phase !== "results" && sim.tick < MAX_TICKS) sim.step(bot.next()); if (sim.phase === "results") reached++; sim.free(); } expect(reached / seeds.length).toBeGreaterThanOrEqual(0.8); }); ``` If it fails, tune the bot (its aim, timing, which threat it picks), not the game: the rules and numbers in the brief are the player's game, and weakening them so the bot wins changes what you ship. Where the brief wants the bot to show a loss too, assert that separately on a fixed seed. ## README `apps//README.md`, with the sections of [Ringout's README](../../apps/ringout/README.md): 1. **What it is**: the pitch in a paragraph, with the game's key numbers. 2. **Run it**: the install, dev and test commands with the URL, then a table of every URL param the game reads (`demo`, `seed`, `mode`, `ticks`, `backend`, `hud`, `mute`, and the game's own). 3. **Controls**: a table of every input, per screen. Check each line against the input code; a control the README invents is a bug. 4. **What it shows off**: the engine features it exercises, each in a sentence. 5. **Known issues**: what is rough, honestly. **Every number is sourced.** Each number in the README comes from a constant in the code, a test, or a measurement you ran (say how: backend, machine, idle GPU). Ringout's "61 hexagonal basalt columns in 5 rings" is `RINGS = 5` in [constants.ts](../../apps/ringout/src/game/constants.ts). Do not round up, guess fps, or keep a number after the constant changes. ## Captures `apps//bench/capture-final.sh`, after [Ringout's](../../apps/ringout/bench/capture-final.sh): build once, then one shot per moment with `--param demo=1` and a fixed seed, stopping on the first failure. Cover at least the title, mid-play, the big moment, a win or a loss, the results screen and one `--sequence` of the core action. Run it, read every sidecar and open every PNG the shot prints, as [verify-your-work](../verify-your-work/SKILL.md) says. Putting the game on the project site is a separate step, only when the developer asks: [site/README.md](../../site/README.md) lists the entry, the WebP conversion and the claim checks. ## Exit check - Title → play → win or lose → results → restart works by keyboard, and by the `?demo=1` bot with no human input. - The bot test passes: over a range of seeds, a clear majority of `?demo=1` runs reach results. - Pause, tab-hide and Esc behave; restart leaves no state from the last round (tested in Node). - The HUD shows what the player needs, and hides with `hud=0`. - The README lists how to run it, the controls and every URL param, and every number in it has a source. - The capture script covers every screen, and you opened every capture. Next: [verify-your-work](../verify-your-work/SKILL.md), the full check. ===== skills/genre-playbooks/SKILL.md ===== --- name: genre-playbooks description: Use when a Pebble3D game request fits a known genre (racer, platformer, tower defence, physics puzzle, stealth, sandbox, arena brawler, horde action, demolition), at the build step of make-a-game, to reuse the shipped demo that already does that genre well. --- # Genre playbooks Each shipped demo in `apps/` is a worked answer to one genre. A playbook points you at that demo, names the systems the genre needs, the feel points that matter, and the checks that prove the genre works. It does not replace the demo: open it, read its README, and copy its structure before inventing your own. Load this at the build step of [make-a-game](../make-a-game/SKILL.md), after [engine-pitfalls](../engine-pitfalls/SKILL.md). Polish comes later from [game-feel](../game-feel/SKILL.md) and the definition of done from [verify-your-work](../verify-your-work/SKILL.md); the playbooks only add what is specific to the genre. ## Pick the closest playbook Read the brief (`apps//BRIEF.md`) and match the core verb, not the theme. A game about cats racing across rooftops is a platformer or a racer depending on whether the player steers a path or beats a clock. | The player mainly... | Playbook | Demo to study | | ----------------------------------------------------------- | ----------------------------------- | ------------------------------------------- | | Steers a vehicle against a clock or a ghost | [racer](racer.md) | [drift-drone](../../apps/drift-drone) | | Runs and jumps across platforms | [platformer](platformer.md) | [skyrun](../../apps/skyrun) | | Places defences and watches waves hit them | [tower defence](tower-defence.md) | [swarm-siege](../../apps/swarm-siege) | | Sets up parts, then runs a machine | [physics puzzle](physics-puzzle.md) | [chain-reaction](../../apps/chain-reaction) | | Sneaks past watchers to a goal | [stealth](stealth.md) | [lanternfall](../../apps/lanternfall) | | Builds and edits freely with physics | [sandbox](sandbox.md) | [pebble-garden](../../apps/pebble-garden) | | Shoves rivals in a shared arena (local multiplayer or bots) | [arena brawler](arena-brawler.md) | [ringout](../../apps/ringout) | | Fights a crowd of melee enemies in waves | [horde action](horde-action.md) | [katana-defense](../../apps/katana-defense) | | Breaks structures with projectiles | [demolition](demolition.md) | [breakpoint](../../apps/breakpoint) | Games often blend two genres. Pick the one that owns the core verb as the base and borrow single systems from the second (for example, a racer with a tower-defence-style upgrade screen). ## When none fits There is no playbook for fighters, online multiplayer or any genre without a shipped demo. Do not invent one. Use the nearest playbook for structure and the cookbook in [docs/cookbook/](../../docs/cookbook/README.md) for single techniques, and say so: add a line to the assumptions in `BRIEF.md` such as "No playbook for this genre; built on the arena-brawler structure". Tell the developer in your first progress message too. ## How to use a playbook 1. Read the demo README end to end, then the cited source files. 2. Copy the sim/presentation split. The sim is deterministic and seeded; the view only reads it. Every playbook assumes this. 3. Build the genre's core systems first and cover them with sim tests before any art. 4. Before the feel pass, run the genre-specific checks in the playbook. They are in addition to the checks in [verify-your-work](../verify-your-work/SKILL.md), not instead of them. ===== docs/examples.md ===== # Examples map Where each engine feature is used in the showcase games and the playground: feature, file and line range, one-line note. Copy from these; the cookbook ([cookbook/README.md](cookbook/README.md)) explains each pattern. Line ranges were checked against the files when this page was written; if one has drifted, search the file for the named symbol. ## Playground (`apps/playground`) | Feature | File (lines) | Note | | --- | --- | --- | | URL params | `apps/playground/src/main.ts` (8-21) | `scene`, `mode`, `ticks`, `backend`, `cam`, `splat`, `debug`, `script`, `overlay`. | | Load a scene by name | `apps/playground/src/main.ts` (74-91) | `import.meta.glob` over `scenes/*.json`; fills the default HDRI from the asset manifest. | | Scripted player input | `apps/playground/src/main.ts` (112-179) | Writes `game.player.input` and camera yaw; `jumpAtTick` shows the two-tick input latency. | | WebGPU to WebGL fallback | `apps/playground/src/main.ts` (200-212) | Only an implicit backend falls back, on a fresh canvas. | | Stats overlay | `apps/playground/src/main.ts` (215-217) | `mountOverlay(game, undefined, { startVisible })`; backtick toggles. | | Fatal error to `__pebble3d.error` | `apps/playground/src/main.ts` (221-231) | Automation reports the error instead of timing out. | | Scene spawner | `apps/playground/scenes/showcase.json` (361-375) | 60 balls at 4 per second from a prefab. | | Toon style switch | `apps/playground/scenes/showcase-toon.json` (35-39) | `post.style: "toon"` with default `toon` settings. | | Splat level, character, presets | `apps/playground/scenes/showcase.json` | Outdoor splat capture, bounds, third-person character, crates. | ## Chain Reaction (`apps/chain-reaction`): JSON levels, headless verify | Feature | File (lines) | Note | | --- | --- | --- | | `createGame` as renderer only | `apps/chain-reaction/src/main.ts` (79-97) | Empty entity list; puzzle bodies live in per-run worlds from the same module. | | Fixed-step accumulator in `onFrame` | `apps/chain-reaction/src/main.ts` (149-168) | Up to 4 ticks per frame, then drops time; alpha for presentation. | | Probes and `stateHash` override | `apps/chain-reaction/src/main.ts` (170-186) | Shot sidecars report the puzzle world's hash. | | New worlds from a loaded module | `apps/chain-reaction/src/puzzle/sim.ts` (58-65) | `engineFrom(handle)`: `new (world.constructor)(seed, g)`. | | Spawn an expanded scene into a fresh world | `apps/chain-reaction/src/puzzle/sim.ts` (114-133) | `world.spawn(JSON.stringify(e.desc))`, frees the world on failure, own `StateViews`. | | Preallocated event ring | `apps/chain-reaction/src/puzzle/sim.ts` (180-203) | 64 reused records, drained each tick: no per-tick allocation. | | One tick: impulses, step, impacts, goal | `apps/chain-reaction/src/puzzle/sim.ts` (205-324) | Springs and fans as mass-scaled impulses; velocity reads from scratch `[12..15)`. | | Level schema | `apps/chain-reaction/src/puzzle/level.ts` (38-104) | zod `LevelSchema`; `scene` is a partial scene. | | Compose a level into a scene | `apps/chain-reaction/src/puzzle/compose.ts` (152-256) | `deepMerge` over `levels/base.json`, prefab entities, then `parseScene` + `expandScene`. | | Headless verify CLI | `apps/chain-reaction/src/cli/verify.ts` (99-145) | Runs each reference solution, compares `expect.hash`; `--update` rewrites it. | | Wasm in Node | `apps/chain-reaction/src/puzzle/node-engine.ts` (5-14) | `loadSim("deterministic", bytes)`. | | Demo driver | `apps/chain-reaction/src/demo.ts` (4-27) | Places each solution part by part, runs, shows the result; tick-driven. | ## Rockfall (`apps/rockfall`): custom boot, engine spawners, 1,800 bodies | Feature | File (lines) | Note | | --- | --- | --- | | Boot without `createGame` | `apps/rockfall/src/main.ts` (180-199) | `parseScene`, `expandScene`, `loadSim` and `createRenderer` in parallel. | | Hand-installed `__pebble3d` hook | `apps/rockfall/src/main.ts` (274-322) | Everything `pnpm shot` reads, plus `game` probes. | | `FixedStepLoop` with 2 catch-up ticks | `apps/rockfall/src/main.ts` (324-331) | Slows down under load instead of spiralling. | | Per-tick input, log, step, events | `apps/rockfall/src/main.ts` (336-378) | Bot or live input into one `TickInput`, logged, then `sim.step`. | | Sync and render | `apps/rockfall/src/main.ts` (383-398) | `views.refresh()`, `renderer.sync(prev, curr, alpha)`, views, `render`. | | Input log | `apps/rockfall/src/game/input.ts` (8-55) | Quantised axes (1/127) so live play and replay match. | | Seeded RNG | `apps/rockfall/src/game/rng.ts` (1-31) | mulberry32, allocation-free. | | Fresh world per run | `apps/rockfall/src/game/factory.ts` (1-21) | Frees the handle's first world on first use. | | Character from spawn JSON | `apps/rockfall/src/game/sim.ts` (264-287) | Kinematic capsule plus `character`. | | The tick | `apps/rockfall/src/game/sim.ts` (346-371) | Input, director, `world.step(1)`, refresh, drain spawns, read player. | | Driving and reading the character | `apps/rockfall/src/game/sim.ts` (373-415) | `setCharacterInput` per tick; `characterState` grounded flag. | | Runtime spawners | `apps/rockfall/src/game/sim.ts` (418-475) | Spawner JSON per wave order; despawned when finished. | | Draining spawned bodies | `apps/rockfall/src/game/sim.ts` (595-640) | `spawnedPending`/`drainSpawned` triples; seeded tumble via `setVelocity`. | | Raycast with exclude | `apps/rockfall/src/game/sim.ts` (934-951) | Filter 2 skips the player when resting a pickup. | | Game hash | `apps/rockfall/src/game/sim.ts` (216-218) | `stateHash()` plus score, hp, wave, rock count. | | Spawned bodies into the instance registry | `apps/rockfall/src/game/view/rock-view.ts` (68-101) | `instances.add(key, geo, mat, slot, colour)` / `removeSlot`. | | Landing rings | `apps/rockfall/src/game/view/telegraph-view.ts` (112-116) | Ground height under each rock, the rock excluded. | ## Ghostline (`apps/ghostline`): marble time trials, ghosts | Feature | File (lines) | Note | | --- | --- | --- | | Boot | `apps/ghostline/src/main.ts` (84-97) | `createGame` with the course scene; the app runs its own worlds in `onFrame`. | | Worlds from the loaded module | `apps/ghostline/src/game/physics.ts` (5-23) | Refuses the `fast` build. | | Views per world | `apps/ghostline/src/game/physics.ts` (25-70) | Re-points when memory grows (any world's spawn can). | | Int8 input log | `apps/ghostline/src/game/input.ts` (1-58) | 3 bytes per tick; run-length base64 for storage. | | Ghost record and fingerprint | `apps/ghostline/src/game/ghost.ts` (25-67) | Seed, inputs, hash; course and rules fingerprinted. | | Ghost re-simulation and verify | `apps/ghostline/src/game/ghost.ts` (136-212) | Second world in lockstep; `verifyRecord` replays headless. | | Live run and ghost per tick | `apps/ghostline/src/game/app.ts` (463-477) | Logs the input, steps both. | | Accumulator | `apps/ghostline/src/game/app.ts` (559-577) | Up to 5 ticks per frame, alpha for presentation. | | Trimesh track with smooth seams | `apps/ghostline/src/game/sim.ts` (178-196) | Static `trimesh` colliders, `fixInternalEdges: true`. | | Ground probe | `apps/ghostline/src/game/sim.ts` (359-391) | Raycast filter 2 excluding the marble; normal from scratch `[1..4)`. | ## Breakpoint (`apps/breakpoint`): demolition, physics in a worker | Feature | File (lines) | Note | | --- | --- | --- | | Boot and build override | `apps/breakpoint/src/main.ts` (93-102) | `?build=` rewrites `sim.build` before `createGame`. | | Worker or inline sim | `apps/breakpoint/src/main.ts` (118-152) | Worker in realtime; main thread in fixed mode. | | Worker message handling | `apps/breakpoint/src/game/sim.worker.ts` (36-93) | `loadSim` inside the worker; transferable state buffers. | | Buffer pool | `apps/breakpoint/src/game/sim.worker.ts` (24-34) | Reuses packed `Float32Array`s returned by the main thread. | | Worker clock | `apps/breakpoint/src/game/sim.worker.ts` (128-155) | `setTimeout` loop, paused while the tab is hidden. | | Instant replay by re-simulation | `apps/breakpoint/src/game/replay.ts` (5-17) | A shadow world follows the shot log for a bit-exact replay. | | `fast` build | `apps/breakpoint/scenes/site.json` (42-45) | SIMD Rapier. | ## Field Notes (`apps/field-notes`): splat sites, depth of field | Feature | File (lines) | Note | | --- | --- | --- | | Inject colliders into a splat scene | `apps/field-notes/src/main.ts` (75-98) | `bounds` plus body-only static boxes from the site data. | | Static-only occlusion raycast | `apps/field-notes/src/main.ts` (100-105) | Filter 1 for photo line-of-sight. | | Boot with a player rig | `apps/field-notes/src/main.ts` (118-131) | Fails fast if the scene has no character. | | Restart with `teleport` | `apps/field-notes/src/main.ts` (158-166) | New seed, player snapped back, log cleared. | | Ticks from `world.tick()` | `apps/field-notes/src/main.ts` (182-222) | Rules run once per engine tick; the sim's buttons drive `rig.input`. | | Custom camera arm | `apps/field-notes/src/game/present.ts` (88-109) | Replaces the rig camera; the ray ignores `__bounds.*` walls. | | Depth of field setup | `apps/field-notes/src/game/present.ts` (115-117) | `bokeh`, `backdrop` per site. | | Depth of field per frame | `apps/field-notes/src/game/present.ts` (280-290) | Enabled while the camera is raised; focus and range from the lens. | | Character with `accel` | `apps/field-notes/scenes/yard.json` (65-100) | glTF avatar, clip speeds, explicit capsule. | | Splat alignment aid | `apps/field-notes/src/scout.ts` (6-10) | `?scout=&pose=...` draws a 1 m grid over the capture. | ## Ronin Outpost (`apps/katana-defense`): toon horde defence | Feature | File (lines) | Note | | --- | --- | --- | | Inject arena physics | `apps/katana-defense/src/main.ts` (86-104) | Bounds and obstacle boxes added to the scene JSON. | | Stylise cached glTFs | `apps/katana-defense/src/main.ts` (120-127) | `renderer.stylize(gltf.scene)` once, before any clone. | | JS sim loop with input log | `apps/katana-defense/src/main.ts` (187-215) | Accumulator, bot/lab/live input, `sim.step`. | | Probes | `apps/katana-defense/src/main.ts` (217-237) | Phase, wave, kills, hash, rig diagnostics. | | Toon post settings | `apps/katana-defense/scenes/arena.json` (31-52) | Bands, shadow tone, rim, splat grade. | | Hand-made toon material | `apps/katana-defense/src/game/view/katana.ts` (71-88) | `ToonNodeMaterial` with `toonRim`/`toonSpecular`. | | Ragdoll corpse | `apps/katana-defense/src/game/view/zombie-view.ts` (496-537) | Runtime capsule `spawn` plus `setVelocity` spin; avatar hung from its slot. | | Blob shadows | `apps/katana-defense/src/game/view/zombie-view.ts` (81-99) | One instanced quad mesh instead of skinned shadows. | | Pre-cloned skinned pool | `apps/katana-defense/src/game/view/zombie-pool.ts` (4-45) | Clone counts from the worst wave, so no clone mid-fight. | | Two-bone IK | `apps/katana-defense/src/game/view/two-bone-ik.ts` (18-62) | Analytic, allocation-free. | | Live splat grade | `apps/katana-defense/src/game/view/dusk.ts` (136-145) | `renderer.splatColor` exposure, saturation, tint over the dusk cycle. | ## Skyrun (`apps/skyrun`): parkour time trial, riding kinematic movers | Feature | File (lines) | Note | | --- | --- | --- | | Course format as zod-validated JSON | `apps/skyrun/src/game/course.ts` (102-160) | Islands, blocks, stairs, movers, checkpoints, shards, bot route; readable errors. | | Mover poses as a pure function of time | `apps/skyrun/src/game/course.ts` (297-330) | slide (eased ping-pong with rests), spin, orbit. | | Character riding platforms | `apps/skyrun/src/game/sim.ts` (160-169) | `character.ridePlatforms: true` with `accel`, `stepHeight`, `maxSlopeDeg`, `snap`. | | Movers driven before each step | `apps/skyrun/src/game/sim.ts` (201-216) | `setKinematicPose` for the pose reached in this tick's `world.step`. | | Jump buffer on top of the engine's coyote time | `apps/skyrun/src/game/sim.ts` (218-236) | A press 8 ticks before landing still jumps. | | Respawn with `teleport` | `apps/skyrun/src/game/sim.ts` (271-279) | Clears the character's vertical and platform velocity. | | Ghost re-simulated from the input log | `apps/skyrun/src/game/ghost.ts` (92-124) | Second sim in lockstep; a run that does not finish on its recorded tick is hidden. `courseFingerprint` (`course.ts`, 339) discards records from another layout. | | `CharacterView` on an app-managed avatar | `apps/skyrun/src/game/view/runner-view.ts` (125-126) | Cross-faded clips and facing without `createGame`. | | Spring-arm camera on a custom world | `apps/skyrun/src/game/view/camera-rig.ts` (35-48) | `ThirdPersonController` with a static-only ray into the sim's own world. | | Painted sky and matched fog | `apps/skyrun/src/game/view/sky.ts` (55-68) | Replaces `backgroundNode` and `fogNode` after `createRenderer`. | | Sub-path hosting | `apps/skyrun/src/main.ts` (86-93) | Root-absolute `/assets/...` and `/basis/` resolved by the renderer's asset base (`VITE_PEBBLE3D_ASSET_BASE`, else Vite's `BASE_URL`). | ## Lanternfall (`apps/lanternfall`): a generated keep, raycast guards | Feature | File (lines) | Note | | --- | --- | --- | | Total seeded generator | `apps/lanternfall/src/gen/generate.ts` (143-156) | `generateKeep`: a seed that fails validation is regenerated with fresh draws. | | Characters with `accel` in the generated scene | `apps/lanternfall/src/gen/generate.ts` (877-879) | The thief; the guards use the same block with `accel: 10` (970-975). | | Validate, rasterise, flood-fill | `apps/lanternfall/src/gen/generate.ts` (939-949) | `parseScene` on the generated JSON, then a walkability grid and a reachability flood. | | Generated scene into `createGame` | `apps/lanternfall/src/main.ts` (53-67) | `generateKeep(seed)`, an optional `?dumpScene=1`, then the scene object straight into `createGame`. | | Character intents only | `apps/lanternfall/src/game/sim.ts` (377-400) | `setCharacterInput` for every guard and the player each tick. | | Static-only line-of-sight raycast | `apps/lanternfall/src/game/sim.ts` (534-552) | Guard eye to the thief; a hit closer than the target blocks sight. | ## Ringout (`apps/ringout`): sumo with impulses, kinematic movers, replay | Feature | File (lines) | Note | | --- | --- | --- | | Two players on one keyboard | `apps/ringout/src/game/keys.ts` (3-16) | WASD with Space or Left Shift; arrows with Enter, Right Shift, `/` or Numpad 0. | | Torque and impulse drive | `apps/ringout/src/game/sim.ts` (207-213) | `applyImpulse` to steer plus `applyTorqueImpulse` about the rolling axis, capped by speed along the stick. | | Dash | `apps/ringout/src/game/sim.ts` (214-230) | One large impulse with a cooldown, grounded and not staggered. | | Arena turned by kinematic poses | `apps/ringout/src/game/sim.ts` (294-306) | Every column's pose from the arena angle, the shake and the fall, via `setKinematicPose`. | | Velocity reads | `apps/ringout/src/game/sim.ts` (322-331) | `linearVelocity` and `angularVelocity` into the scratch buffer every tick. | | Round hash | `apps/ringout/src/game/sim.ts` (458-478) | Engine `stateHash` plus every rule variable. | | Instant replay and its proof | `apps/ringout/src/game/app.ts` (240-256, 267-283) | Fresh `RoundSim` from the seed, fed the input log; the final hash is compared on screen. | | Independent worlds from one module | `apps/ringout/src/game/physics.ts` (15-23) | New `World`s from the already-loaded deterministic wasm. | ## Pebble Garden (`apps/pebble-garden`): scene JSON editor, play and rewind | Feature | File (lines) | Note | | --- | --- | --- | | Export as tidy scene JSON | `apps/pebble-garden/src/garden/doc.ts` (200-226) | 2-space JSON with number arrays on one line; parses back deep-equal. | | Import with readable errors | `apps/pebble-garden/src/garden/validate.ts` (42-93) | JSON syntax first, then `SceneSchema.safeParse`; every issue with its path and source line. | | Import size caps | `apps/pebble-garden/src/garden/validate.ts` (30-33) | 2 MB of text, entity and dynamic-body limits. | | A fresh world per Play | `apps/pebble-garden/src/garden/sim.ts` (133-151) | `expandScene`, a new deterministic `World`, one `spawn` per entry. | | Kinematic motors | `apps/pebble-garden/src/garden/sim.ts` (220-235) | The pose for the end of the tick from the tick count alone, via `setKinematicPose`. | | Starter gardens and par | `apps/pebble-garden/src/garden/gardens.ts` (30-72) | Three challenges with reference solutions, and the Rock Garden sandbox. | ## Swarm Siege (`apps/swarm-siege`): instancing at scale, sim in a worker | Feature | File (lines) | Note | | --- | --- | --- | | Agent pool size | `apps/swarm-siege/src/game/constants.ts` (4) | `MAX_AGENTS = 32768`. | | One `InstancedMesh` per enemy kind | `apps/swarm-siege/src/game/view/swarm-view.ts` (107-125) | Per-instance glow attribute read by a TSL fresnel-rim emissive node. | | Sim in a module worker | `apps/swarm-siege/src/game/host.ts` (186-193) | `new Worker(new URL("./sim.worker.ts", import.meta.url), { type: "module" })`. | | Placement probe | `apps/swarm-siege/src/game/sim.ts` (378-384) | A downward raycast that must hit only the ground. | | Camera picking | `apps/swarm-siege/src/game/sim.ts` (968-1012) | The cursor ray as an engine raycast: a tower body selects it, the ground gives a build cell. | | Spawner debris | `apps/swarm-siege/src/game/sim.ts` (889-911) | A runtime Rust-side seeded spawner burst of shards. | ## Drift Drone (`apps/drift-drone`): force-driven flight in a splat capture | Feature | File (lines) | Note | | --- | --- | --- | | The drone body | `apps/drift-drone/src/game/sim.ts` (207-216) | A dynamic sphere with CCD. | | Reading `angularVelocity` | `apps/drift-drone/src/game/sim.ts` (249-254) | Into the scratch buffer each tick for the rate loop. | | Rate loop as a torque impulse | `apps/drift-drone/src/game/sim.ts` (384-394) | `applyTorqueImpulse` towards the wanted body rates. | | Thrust and drag | `apps/drift-drone/src/game/sim.ts` (396-405) | One `applyImpulse` along the body's up axis minus quadratic drag. | | Ghost by re-simulation | `apps/drift-drone/src/game/ghost.ts` (145-171) | A second `DroneSim` on its own world, re-fed the record's inputs. | | Static-only camera ray | `apps/drift-drone/src/game/app.ts` (167-176) | The chase camera stays out of the proxy colliders. | | Photo-finish depth of field | `apps/drift-drone/src/game/app.ts` (767-772) | `renderer.dof` focused on the drone's view depth. | ===== README.md ===== # Pebble3D

Five Pebble3D demos played by their demo bots: Swarm Siege, Breakpoint, Ronin Outpost, Drift Drone and Ringout

Play the demos in your browser · Site · Agent skills · Free to use, including commercially, under $50k annual revenue (license)

A browser 3D engine: three.js 0.187 (WebGPU, with a WebGL fallback) for rendering, a Rust/WASM Rapier crate for physics, and Gaussian-splat environments. Scenes are plain JSON, validated by a schema, so an agent can write one without reading engine code. ## Agent skills Ask a coding agent for a game in plain words and it does not start by writing code. The [agent skills](skills/README.md) in `skills/` have it ask at most six short questions (or write down defaults when it cannot ask), write a `BRIEF.md` for you to approve, then build a complete game: title, play, results and restart, with game feel, one committed art direction and a `?demo=1` bot. It verifies the game with tests and screenshots it has looked at before it reports done. Start with [skills/make-a-game/SKILL.md](skills/make-a-game/SKILL.md), which runs the others in this order: interview, brief, scaffold, build, game feel, art pass, complete loop, verify. Claude Code, Cursor and GitHub Copilot discover the copies in `.claude/skills/`; other agents find them through [AGENTS.md](AGENTS.md) and [llms.txt](llms.txt). Overview: https://pebble3d.github.io/pebble3d/build-with-ai/skills/. ## Quickstart Requires Node 22.6 or newer (the Node scripts use `--experimental-strip-types`; the avatar GLB hash was verified on Node 25.2.1, see `.nvmrc`) and pnpm. No Rust: the physics WASM is prebuilt in `packages/sdk/wasm/`. You only need Rust to change the physics crate (see [Changing the physics](docs/getting-started.md#changing-the-physics-rust)). `pnpm shot` also needs a Chromium for Playwright: run `pnpm exec playwright install chromium` once. ```bash pnpm i && pnpm fetch-assets && pnpm dev ``` `pnpm dev` serves the playground with Vite (default port 5173). Open `/?scene=showcase` (a splat scene with a realistic human character). Other scenes: `showcase-robot` (the same scene with the stylised robot), `studio`, `outdoor`, `det`, `showcase-badsplat`. Playground URL params: `scene`, `mode=realtime|fixed`, `ticks`, `backend=webgpu|webgl`, `cam`, `overlay`, `script`, `splat`, `debug=splatOnly`. The stats overlay toggles with the backtick key. ## Docs for humans and LLMs Start with [docs/getting-started.md](docs/getting-started.md), then browse [docs/](docs/) (scene and API reference, cookbook, verification, troubleshooting). Coding agents: read [AGENTS.md](AGENTS.md). LLMs can discover everything from [llms.txt](llms.txt), or load [llms-full.txt](llms-full.txt) in one go. ## Showcase games Original games, each built to show off one strength of the engine. Each one plays a full loop, includes an autoplayer bot (`?demo=1`), and has unit tests. Run `pnpm --filter dev`, then open the port listed below. Each game's README (`apps//README.md`) covers its controls, URL params, numbers and known issues. Play them online at https://pebble3d.github.io/pebble3d/demos/. | Game | App | Port | What it shows off | | -------------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Ronin Outpost | `katana-defense` | 5180 | Toon-shaded ninja katana horde defence: Rocketbox avatars, procedural combat animation with IK, skinned zombie crowds, and the opt-in `post.style: "toon"` | | Breakpoint | `breakpoint` | 5210 | Physics demolition with 838 to 1,344 Rapier bodies per site, run in a Web Worker on the `fast` build, plus a deterministic replay of your best shot | | Ghostline | `ghostline` | 5220 | Marble time trials with ghosts recomputed live from your inputs (not recordings), PBR materials and JSON courses | | Field Notes | `field-notes` | 5231 | Photography in two real Gaussian-splat captures: splat/mesh compositing, a third-person controller, and depth of field | | Rockfall | `rockfall` | 5240 | Survival against waves driven by Rust-side seeded spawners, with up to 1,800 live bodies | | Chain Reaction | `chain-reaction` | 5250 | A contraption puzzle whose levels are JSON scenes; `pnpm --filter chain-reaction verify` replays each solution headless in Node and matches the browser hash | | Lanternfall | `lanternfall` | 5260 | A stealth heist in a keep generated from a seed as schema-valid scene JSON, with raycast guard perception and `accel` characters | | Ringout | `ringout` | 5270 | Local multiplayer sumo: torque and impulse-driven orbs on a collapsing arena of kinematic columns, with an instant replay checked against the live hash | | Skyrun | `skyrun` | 5280 | A parkour time trial: the character controller riding sliding, spinning and orbiting platforms (`ridePlatforms`), with a re-simulated ghost | | Pebble Garden | `pebble-garden` | 5290 | A physics sandbox and level editor: gardens export as schema-valid scene JSON, import with readable errors, and play and rewind exactly | | Swarm Siege | `swarm-siege` | 5300 | Tower defence against thousands of instanced enemies simulated in a Web Worker, with raycast camera picking and spawner debris | | Drift Drone | `drift-drone` | 5310 | An FPV drone flown by thrust and torque impulses through a Gaussian-splat capture, with a re-simulated ghost and a depth-of-field photo finish | Linux Chromium needs WebGPU switched on: `chromium --enable-unsafe-webgpu --enable-features=Vulkan --use-angle=vulkan`. If WebGPU isn't available, `?backend=webgl` uses the WebGL fallback. ## A minimal scene ```json { "version": 1, "environment": { "preset": "studio", "ground": {} }, "prefabs": { "ball": { "mesh": { "primitive": "sphere" }, "body": { "restitution": 0.5 } } }, "entities": [ { "id": "b1", "prefab": "ball", "transform": { "position": [0, 4, 0] } } ] } ``` Save it as `apps/playground/scenes/mine.json` and open `/?scene=mine`. ## For agents [`packages/sdk/scene.schema.json`](packages/sdk/scene.schema.json) is the JSON Schema for scene files (regenerate with `pnpm --filter @pebble3d/sdk schema`). Point `$schema` at it and validate before running. The zod source is `packages/sdk/src/schema.ts`. In a page, `window.__pebble3d` exposes `ready`, `done`, `stats()`, `stateHash()`, `setCamera()`, `player()` and `position()`. ## Screenshots: `pnpm shot` ```bash pnpm shot --scene showcase --cam hero --backend webgpu --overlay ``` It builds the app (default the playground), serves it on a free port, renders in fixed-tick mode in Chromium and writes `artifacts/shots/---x.png` plus a `.json` sidecar (`adapterInfo`, `stats`, `stateHash`, `tick`, console). | Flag | Meaning | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `--scene ` | A file in `apps/playground/scenes/`. Required for the playground (the default app); optional with `--app`. | | `--cam ` | A camera preset, or `controller`. Default: the renderer's (`hero`, else the first preset). | | `--backend webgpu\|webgl` | Default `webgpu`. Fails if that backend is not the one that ran. | | `--size WxH` / `--resize WxH` | Viewport size (default 1280x720) / resize after load (not with `--sequence`). | | `--ticks ` | Sim ticks to run before capture (default 120). | | `--script ` | Scripted player input: `walk-forward`, `walk-into-crates`, `walk-to-bounds`, `walk-side`, `sprint-side`, `jump`, `jump-side` (see `SCRIPTS` in `apps/playground/src/main.ts`). | | `--sequence [:]` | Capture `n` frames, one every `` ticks (default 1), from tick `--ticks`: `-f000.png`... plus `.webp`, an animated WebP (30 fps for every=1, else real time). `--fps ` / `--scale ` / `--no-frames` override the rate, downscale, drop the PNGs. | | `--overlay` | Show the stats overlay in the shot. | | `--splat ` / `--debug splatOnly` | Override the splat / draw only the splat. | | `--allow-console-error "[:count]"` | Permit an expected console error, optionally with an exact count. | | `--no-build` / `--headed` | Skip the build / show the browser. | | `--app ` / `--param key=value` | Capture another app under `apps/` (then `--scene` is optional) / pass extra URL params. | | `--out ` / `--name ` | Output directory (inside `artifacts/`) / file basename. | | `--timeout ` / `--port ` | Per-wait timeout (default 60) / serve the preview on a fixed port. | It exits 1 on any console warning or error not in `scripts/shot/console-allowlist.json` or an `--allow-console-error`, on a missing or software (SwiftShader) adapter, or if a wait (load, `__pebble3d.done`, each sequence frame) exceeds `--timeout` (default 60 s). ## Tests and benchmarks ```bash cargo test -p engine-core --features deterministic cargo test -p engine-core --no-default-features --features fast pnpm -r test && pnpm -r typecheck && pnpm lint node --experimental-strip-types packages/sdk/test/determinism.mjs --expect "$(cat packages/sdk/test/fixtures/det-hash.txt)" pnpm shot --scene det --cam hero --backend webgpu --ticks 1000 node -e "const s=require('./artifacts/shots/det-hero-webgpu-1280x720.json'); const h=require('fs').readFileSync('packages/sdk/test/fixtures/det-hash.txt','utf8').trim(); process.exit(s.stateHash===h && s.tick===1000 ? 0 : 1)" node --experimental-strip-types packages/sdk/test/bench.mjs ``` `engine-core` defaults to the `deterministic` feature (Rapier enhanced-determinism, bit-identical state hash across runs); `fast` is plain Rapier with WASM SIMD. The Node scripts need `--experimental-strip-types` because they import TypeScript sources. Bench (10,000 ticks at 1/60 s, 300 active ticks sampled, real-time multiple of the sim step, one run on an AMD RDNA 3 laptop; numbers vary run to run): | Build | Bodies | Active ticks (x real time) | Full 10k run (x real time) | | ------------- | ------ | -------------------------- | -------------------------- | | deterministic | 100 | 231 | 2890 | | deterministic | 500 | 109 | 1623 | | fast | 100 | 368 | 2817 | | fast | 500 | 149 | 1608 | "Full run" includes the stretch where bodies are asleep. ## Known limitations - One game per page: `Game.dispose` does not exist yet (planned). - Determinism is verified on V8 (Node and Chromium) only. - The derived splat hash was verified on one machine. If `fetch-assets` reports a hash mismatch elsewhere, that is the cause. - The splat is a drone capture, so grass is soft and blurry up close. - On `showcase-robot`, the walk clip's toe dips about 6 cm below the ground plane. - On `showcase-robot`, there is no fall animation clip; falling reuses the jump clip. - On the human, residual foot slip is about 15% at walk and 24% at sprint, inherited from the source clips. - The human avatar (`rocketbox-male-adult-16.glb`) builds only on linux-x64, because the pinned KTX-Software binary is linux-x64 only. On other platforms `pnpm fetch-assets` reports that asset as failed; use `?scene=showcase-robot`. - The overlay's draw calls and triangles count every pass (AO prepass, shadow cascades, bloom, SMAA), not just the main scene. - Screenshots repeat to RMSE < 0.002 (under 0.1% of pixels more than 8/255 off), not byte for byte. - `fps` and `frameMs` are wall-clock. In fixed mode the sim time is not the wall time. ## Assets and credits Large assets are not committed; `pnpm fetch-assets` downloads them per `apps/playground/assets.manifest.json`. Licenses and attribution (Poly Haven HDRI, CC BY 4.0 splat scene, Quaternius robot, and the showcase character: Microsoft Rocketbox `Male_Adult_16`, MIT, Copyright (c) 2020 Microsoft) are in [`apps/playground/public/assets/LICENSES.md`](apps/playground/public/assets/LICENSES.md). The full Rocketbox licence text is in [`Microsoft-Rocketbox-MIT.txt`](apps/playground/public/assets/licenses/Microsoft-Rocketbox-MIT.txt). The Basis transcoder served at `/basis/` is Apache-2.0; its notice ships in `dist/basis/`. ## Roadmap - `packages/mcp-server`: an MCP server for authoring, running and screenshotting scenes. - A headless CLI runner. - Spatial-query and diagnostics APIs for agents. - A full studio HUD beyond the stats overlay (`packages/studio-overlay`). - `scripts/splat-collider`: generate physics geometry from a splat capture. - Tighter fast-build performance at 500 bodies. ## License Pebble3D is source-available under the [Pebble3D Engine License](LICENSE), © 2026 RJV Solutions. - **Free**, including commercial use, for organizations with under **USD $50,000** in annual revenue plus funding (trailing 12 months, counted across the whole organization and its affiliates). - **At or above $50,000**, a paid commercial license from RJV Solutions is required. There is a 60-day grace period after crossing the threshold. - Players of games built with Pebble3D never need a license. - Third-party dependencies and demo assets (three.js MIT, Rapier Apache-2.0, CC BY 4.0 / CC0 assets) keep their own licenses. ===== LICENSE ===== Pebble3D Engine License Version 1.0 Copyright (c) 2026 RJV Solutions. All rights reserved. This license applies to the Pebble3D engine source code, tools and documentation in this repository (the "Software"), except for the third-party components listed in Section 7. 1. Definitions "Licensor" means RJV Solutions. "You" means the individual or legal entity using the Software, together with all of its Affiliates. "Affiliate" means any entity that controls, is controlled by, or is under common control with You. "Control" means ownership of more than 50% of the voting interests of an entity, or the power to direct its management. "Annual Revenue" means the total of: (a) all gross revenue received by You and Your Affiliates from any source, whether or not related to the Software, and (b) all funding raised by You and Your Affiliates, including equity investment, loans, grants and crowdfunding, measured over the most recent trailing twelve (12) months. "Threshold" means fifty thousand United States dollars (USD $50,000). 2. Free License (Annual Revenue under the Threshold) If Your Annual Revenue is less than the Threshold, the Licensor grants You a worldwide, non-exclusive, non-transferable, royalty-free license to use, copy, modify and run the Software, and to distribute the Software and Your modifications of it, including as part of applications, games and other products You create. Commercial use is permitted. 3. Commercial License (Annual Revenue at or above the Threshold) If Your Annual Revenue is equal to or greater than the Threshold, the free license in Section 2 does not apply to You. To use the Software, You must first obtain a separate commercial license from the Licensor, on terms agreed in writing with the Licensor. If Your Annual Revenue first reaches the Threshold while You are using the Software under Section 2, You have sixty (60) days from that date to obtain a commercial license or to stop using the Software. Products You distributed before that date may remain in the hands of their end users. 4. Conditions (a) You must keep this license file and all copyright notices with every copy or substantial portion of the Software You distribute. (b) Anyone who receives the Software from You receives it under this license, and the Annual Revenue conditions apply to them separately. (c) You may not remove or bypass the Annual Revenue conditions by sublicensing the Software under different terms, or by splitting Your business across entities. (d) The Licensor may ask You in writing to confirm that Your Annual Revenue is under the Threshold. You must answer truthfully within thirty (30) days. 5. End Users End users of a game or application You build with the Software do not need their own license to play or use it. 6. Termination If You breach this license and do not fix the breach within thirty (30) days of written notice from the Licensor, Your rights under this license end automatically. Sections 7, 8 and 9 survive termination. 7. Third-Party Components The Software uses or bundles components owned by others, which remain under their own licenses and are not covered by this license, including: - three.js (MIT License) - Rapier physics engine (Apache License 2.0) - other npm and Cargo dependencies, under the licenses stated in their own packages - demo assets downloaded by scripts/fetch-assets.mjs, under the licenses listed in apps/playground/public/assets/LICENSES.md (including CC BY 4.0 and CC0 1.0 works) You must comply with those licenses as well. 8. No Warranty THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 9. Limitation of Liability IN NO EVENT SHALL THE LICENSOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10. Contact For a commercial license, contact RJV Solutions at legal@tempoclub.app.