# Ludrel > An AI-first framework for 2D browser games written in TypeScript. A game is a folder of JSON documents (manifest, > scenes, levels, prefabs, synth audio) validated by JSON Schemas, plus optional code "behaviors". AI tools (MCP server > `apps/mcp`) can create games from templates, edit data with validation, run games headless with assertions and > take screenshots. ## AI guide How to make and change Ludrel games with the AI tools (MCP server `apps/mcp`, or the built-in assistant). The tools work on game folders under `games/`; every edit is validated, and games run headless so a change can be proved before anyone plays it. ## AI guide: The loop 1. **Look.** `list_games`, then `get_project_tree` and `read_file` for `game/game.json`, the scene you will change, and the prefabs involved. For levels, read `game/levels/legend.json` (the map characters). 2. **Change data first.** Prefer the specific tools: `update_prefab` (merge component values), `upsert_prefab`, `upsert_scene`, `add_entity`, `build_level` (new levels), `read_level` + `edit_level` (change existing levels). Use `write_file` for anything else, including code in `src/`. An invalid document is refused with exact JSON pointers, and nothing is written; fix and retry. 3. **Validate.** `validate` (add `typecheck: true` after editing code). Fix every error. 4. **Prove it.** `run_headless` with scripted `inputs` and `expect` assertions, e.g. "after 2 s holding right, `player.Transform.x > 100`" or "event `pickup:gem` happened". Results include errors, event counts, named entities (position, velocity, health) and scene state. 5. **Look again** (optional, slower). `capture_screenshot` shows a scene after scripted input. Start a new game with `create_game_from_template` (template `platformer`), which creates `games/`. ## AI guide: How a game is organised - `game/game.json`: display size, input actions (`moveX`, `jump`, `down`, `pause`, `uiUp`...), UI theme, assets (images, sprite sheets with animations, bitmap fonts, `synth` audio), prefab list, scene list, entry scene. - `game/scenes/.json`: level, camera, background, music, `systems` (code behaviors), `hud`, `menu`, `rules`. - `game/levels/.json`: tilemap. Build new ones with `build_level` from text rows instead of writing tile arrays. To change one, `read_level` (layers drawn as text, objects with tile positions, gids per tileset) and then `edit_level` with operations: `ground` (auto-tiled terrain by cells or `rect`), `paint`/`fill`/`floodFill` (gids), `place`/`move`/`update`/`remove` objects, `resize`, layer operations. They apply all or nothing and the result is validated. Creators make the same edits in the editor's visual level view. - `game/prefabs/.json`: entity templates; `components` by name (see the component reference), `tags`, optional `extends` (another prefab whose components are merged under these). - `game/audio/*.json`: synthesized sound effects (`kind: "sound"`) and songs (`kind: "song"`). - `src/behaviors.ts`: code. Every exported function is a behavior that scenes can list in `systems`. ## AI guide: Gameplay without code Built-in components (always active): `PlatformerController` (run, jump, `maxJumps`, `enabled`), `Health`, `ContactDamage` (`stompable`), `Patrol` (walkers turn at walls and ledges), `Hover` (flyers: `rangeX`, `rangeY`, `period`), `Pickup` (emits `pickup:`, can `heal`), `Checkpoint`, `Lifetime`, `PlatformerAnimator`, `Trigger`, plus physics (`Body`, `Collider`) and visuals (`Sprite`, `SpriteAnimation`, `Rect`, `Text`, `ParticleEmitter`). Rules connect events to actions in a scene: - Events: `scene:start`, `controller:jump`, `pickup:`, `enemy:stomped`, `enemy:defeated`, `:hurt`, `:died`, `:respawned`, `checkpoint:reached`, `trigger:` (from `Trigger` components or level trigger objects), `input:` (an input action was pressed), `app:hidden` (page lost focus), and anything a behavior emits. - Actions: `goToScene` (fades), `pushScene`, `popScene`, `restartScene`, `addToCounter` (`amount` or `from` a binding; `scope` `scene` or `session`), `setCounter`, `playSound`, `playMusic`, `stopMusic`, `cameraShake`, `emit`, `respawn`, `setComponent` (change fields of a named entity), `banner`, `toggleSetting`, `saveGame`. Any action takes `delayMs`. Bindings read values for HUD labels, menu labels, banners and assertions: `game.` (scene state, e.g. `game.coins`, `game.coinTotal`), `session.` (kept across scenes), `settings.sound`, and `..` for named entities (e.g. `player.Health.hp`). Labels use `{binding}`; HUD labels also take `{value}`. ## AI guide: Conventions and pitfalls - Names: ids are lowercase with dashes (`level-2`); components are PascalCase; input actions camelCase. - The player must be named `player` (level legend `P`, or `id` on the spawn) for cameras, HUD and rules. - Spawn positions are the top-left of the entity's sprite; colliders are offset inside it. - A new scene must be listed in `game.json` (`upsert_scene` does that) and reachable (`goToScene` from another scene's rule or menu). - Simulation is deterministic: never use `Math.random` in behaviors; use the `GameRng` resource. - Use the documented binding paths. If `run_headless` reports a binding as `undefined`, the entity is not named or the scene state key was never set. - Keep changes small and validate after each one; `run_headless` costs a fraction of a second. ## Top-down games Phase 5a added these (ADR 0024). Start from the template: `pnpm create-game my-game --template topdown`. In the platform editor, use **Start from the top-down template**. Everything below is data, validated like every other document, so creators, content packs and AI tools can write it. ## Top-down games: Movement - `TopDownController` moves an entity in eight directions from two axis actions (`moveX`, `moveY`). List `topDownController` in the scene's `systems`. - `TopDownAnimator` plays `walk-` / `idle-` animations, with facing `down`, `up`, `left` or `right`. - Set gravity to zero in `game.json`: `"physics": { "gravity": { "x": 0, "y": 0 } }`. ## Top-down games: Worlds (large maps) A scene can have `"world": "world.json"` instead of a `level`. A **world** document lists a grid of chunks, and each chunk is an ordinary level of `chunkWidth × chunkHeight` tiles. Chunk levels work in the level editor, the AI level tools and packs. Chunks within `streamRadius` of the camera's target are loaded; the others unload. Two things to know: - Objects removed while their chunk was loaded (collected, defeated) stay gone. - Cells of unloaded chunks count as solid, so nothing walks into them. ## Top-down games: NPC brains An NPC has a `Brain` component naming a brain document (`game/ai/.json`, listed in `game.json` `brains`). **A state machine.** Each state has an `activity` or a behaviour `tree`. - Activities: `idle`, `moveTo`, `wander`, `follow`, `flee`, `wait`, `say` (a speech bubble) and `do` (rule actions). - A transition fires on an event (`on`), a condition (`if`), time in the state (`after`), or when the activity finishes (`done`). **A behaviour tree.** - Composites: `sequence`, `selector`, `parallel`. - Decorators: `inverter`, `succeeder`, `repeat`, `cooldown`. - Leaves: `condition`, and `action` with any activity. NPCs walk around walls with A* over tile collision. Brains are deterministic (seeded randomness, fixed step). ## Top-down games: Talking, dialogue and quests - **`Interactable`**: pressing `interact` near it emits `talked:` and opens its `dialogue`. It shows `prompt` while the player is in range. - **Dialogues** (`game/dialogues/*.json`): nodes have a speaker, text, `do` actions and `choices`. `branches` jump to another node when a condition holds. The built-in dialogue box pauses play; `uiUp`/`uiDown` pick a choice and `uiConfirm` continues. - **Quests** (`game/quests/*.json`): steps complete in order, on an event (`when.event`, counted) or a condition (`when.if`). Each step can run `do` actions, and the last one runs `rewards`. Progress emits `quest:started:`, `quest:step:` and `quest:done:`. The `quest` HUD widget shows the current step. - **Actions**: `startDialogue`, `startQuest`, `giveItem`, `takeItem`, `useItem` and `setLanguage`. ## Top-down games: Conditions These are used by rules (`if`), dialogue choices and branches, quest steps, and brains: - `{ "value": "session.coins", "op": ">=", "than": 3 }` - `{ "hasItem": "key", "count": 1 }` - `{ "quest": "cave", "is": "active", "step": "find" }` - `{ "near": "player", "within": 48 }` (brains only) - `{ "chance": 0.5 }` - `{ "all": [...] }`, `{ "any": [...] }`, `{ "not": {...} }` ## Top-down games: Items Items are listed in `game.json` `items`, each with: - a name; - an icon (and frame); - `stackable` and `max`; - `use` actions, and `consumable` for items used up by `useItem`. A `Pickup` with `"item": ""` adds the item when collected. Bindings: - `items.`: how many the player carries; - `quest.`: the quest's state; `quest..step`: its current step. Inventory and quests live in the session, and `saveGame` saves them. ## Top-down games: Languages `game/locales/.json` are string tables, listed in `game.json` `localization`. Any text field may say `@key`; inline `{ "en": ..., "fr": ... }` maps still work. The player's language comes from the browser. `setLanguage` (a code, or `next` to cycle) changes it and remembers it; `settings.language` binds it. Missing keys fall back to the default language. Bitmap fonts draw lowercase with capitals; the template's font has accented capitals for French. See the recipe `recipes/npc-quest.md` and `templates/topdown`. ## Arcade games and phones Phase 5b added these (ADR 0025). Start from the template with `pnpm create-game my-shooter --template arcade`, or use **Start from the arcade template** in the platform editor. ## Arcade games and phones: Arcade kit **Waves.** A scene's `waves` spawn groups of a prefab over time, entering from just above the view: - `at`: seconds after the scene starts. - `count` and `every`: how many, and the seconds between them. - `x`: a fraction of the view's width, so it works at any screen width. - `formation`: `column`, `line`, `v` or `random`. - `components`: overrides for the spawned prefab. `wave:` is emitted when a wave starts, and `waves:done` once every wave has spawned and none of their entities is left. **Components:** - `Mover`: moves by itself; no Body needed. - `line`: at (`vx`, `vy`). - `sine` and `zigzag`: sway sideways by `amplitude` every `period` seconds. - `dive`: drifts for `delay` seconds, then speeds toward where the player was. - `Shooter`: fires `bullet` prefabs `rate` times a second. - When: automatically, or while `action` is held. - Aim: `up`, `down`, or at the `player`. - Spread: `count` bullets over `spread` degrees. - `Projectile`: a bullet; it hurts the first entity with `Health` and `targetTag` that it touches, then disappears. - `Score`: adds `points` to a session counter (`score`) when its entity's `Health` reaches 0, with an explosion. - `Offscreen`: removes entities that leave the view. - `KeepInView`: keeps the player on screen. - `TopDownController`: steers a ship in eight directions (the top-down controller). **Best scores.** `recordBest` keeps the player's best value (`{ "value": "session.score", "key": "score" }`, or `lower: true` for times). It is saved with the player's saves: platform cloud saves when signed in, the browser otherwise. Bind it as `best.score`. **Backgrounds.** A parallax layer with `drift` scrolls by itself, for starfields and clouds. ## Arcade games and phones: Touch controls On phones and tablets (or with `?touch` in the URL), games get on-screen controls. Without a `touch` section in `game.json`, they are made from the input actions: - `moveX` and `moveY` give a floating joystick; - `moveX` alone gives ◀ ▶ buttons; - `jump`, `fire`, `interact`, `action`, `attack`, `dash` and `bomb` give buttons; - `pause` gives a small corner button. The controls hide while a menu is up, so taps reach the menu. In dialogue, choices can be tapped. To choose the layout yourself: ```json "touch": { "move": { "type": "joystick", "x": "moveX", "y": "moveY", "side": "left", "floating": true, "size": 110 }, "buttons": [{ "action": "fire", "label": "B", "side": "right" }], "pause": "pause" } ``` `"enabled": false` turns them off (for games played by tapping menus only). ## Arcade games and phones: Phones and screen shapes With `"display": { "width": 180, "height": 320, "scaleMode": "expand", "minWidth": 180, "maxWidth": 420 }`, the view keeps its height and widens or narrows to the screen's shape. The camera shows more or less world, and the HUD and menus anchor to the real edges, following rotations and resizes. Without a follow target, the camera centres on the design area (`width` × `height`), so extra width appears on both sides. `"orientation": "portrait"` (or `landscape`) shows a "rotate your device" hint on phones held the other way. ## 3D games Phase 5c added 3D (ADR 0026). Start from the template with `pnpm create-game my-island --template island`, or use **Start from the 3D template** in the platform editor. ## 3D games: Turning it on In `game.json`: - `"display": { "mode": "3d", ... }` - `"physics": { "engine": "rapier3d", "gravity3d": { "x": 0, "y": -20, "z": 0 } }` With these, the game loads: - Three.js, for rendering; - deterministic Rapier, for physics. Both come as a separate chunk that 2D games never download. The 2D renderer stays on top as a transparent layer, so HUD widgets, menus, banners, the dialogue box and touch controls work as in 2D. Units are metres, and y is up. ## 3D games: Levels A scene names a 3D level with `"level3d": "levels3d/island.json"`. 3D levels live in `game/levels3d/`, and contain: - `pieces`: blocks such as `box`, `ramp`, `cylinder` and `sphere`. Each has a `position` (its centre), a `size`, an optional `rotation` (degrees), a `color`, and `collides`. A ramp rises from height 0 at its -x side to `size.y` at its +x side. - `objects`: prefab `spawn`s with a position, `trigger` boxes that emit `trigger:`, and named `point`s. - `lights` (default: soft ambient light plus a sun with shadows) and `sky` (colour and fog). - `killY`: entities that fall below it emit `:fell`. Answer with `respawn`, which returns them to where they started. AI tools: `read_level3d` and `edit_level3d`. ## 3D games: Components **Placement and drawing:** - `Transform3D`: position, rotation in degrees, and scale. - `Mesh`: a primitive shape and colour. - `Model`: a glTF model, declared as an asset of type `model` (`.glb`), with an `animation` clip playing. - `Light3D`: a light. - `Camera3D`: a camera that follows a `target` at a set `distance` and `height` (turned with the `cameraX` axis), or stays fixed. - `Spin3D`: turns and bobs an entity, for collectibles. **Physics:** - `Collider3D`: box, sphere, capsule, cylinder or ramp. Set `sensor` for trigger zones, with `event`, `filterTag` and `once`. - `RigidBody3D`: `dynamic`, `fixed` or `kinematic`. An entity with only a `Collider3D` gets a fixed body. - `Mover3D`: moves a kinematic body back and forth (and spins it). Characters standing on it ride along. **Characters:** - `CharacterController3D`: walks relative to the camera, climbs slopes and steps, and jumps with coyote time and buffering. It emits `:jumped` and `:landed`. - `CharacterAnimator3D`: plays the model's `idle`, `run`, `jump` and `fall` clips. A `Pickup` with a sensor `Collider3D` is collected when touched, as in 2D. Each scene's state gets `Total`, the number of pickups of each kind. ## 3D games: Models The template's models are written as `.glb` from code (`templates/island/tools/gltf.ts`): flat-shaded boxes, cylinders and gems, a node tree, and rotation animations. Models made in other tools work too, as long as they are `.glb` files or `.gltf` files with embedded buffers. ## 3D games: Limitations - No visual 3D level editor yet: edit 3D levels as JSON or with the AI tools, and check them in the preview. - 3D screenshots need a browser; headless runs simulate physics without drawing. - Content packs cannot add 3D levels yet. ## Leaderboards and achievements Phase 6a added these (ADR 0027). The arcade template (`--template arcade`) uses all of them. ## Leaderboards and achievements: Declaring them In `game.json`: ```json "leaderboards": [{ "key": "score", "name": "@board.score", "order": "higher", "min": 0, "max": 20000 }], "achievements": [ { "key": "first-hit", "name": "@ach.first", "description": "@ach.first.about", "icon": "sprite.items", "iconFrame": 5 }, { "key": "secret", "name": "Secret", "hidden": true } ] ``` - `order`: `higher` is better for scores; use `lower` for times (with `"format": "time"`). - `min` and `max` bound what a fair run can reach. Scores outside them are refused. - `hidden` achievements show as "???" until a player unlocks them. - Names may be `@keys` from the game's string tables. The platform shows them in the default language. ## Leaderboards and achievements: Sending them Use rule actions: - `{ "action": "submitScore", "board": "score", "value": "session.score" }` - `{ "action": "unlockAchievement", "achievement": "first-hit" }` On the platform, they go through the play bridge for signed-in players. Signed-out players can play, but nothing is kept. Each player keeps their best score per board, and each achievement once. ## Leaderboards and achievements: How scores are checked Game code runs in the player's browser, so a score could be faked. Every run's inputs are recorded: the seed, plus every change of an input action by scene and tick. A score is sent together with that recording. The top 50 entries of each board are checked by replaying the recording headless in the sandbox. Because the simulation is deterministic, the replay must submit the same score to the same board, or the entry is rejected. Boards mark checked entries with ✓. What this needs from a game: - gameplay that is deterministic: randomness from `GameRng`, never `Math.random`; gameplay in `fixed` systems; - a score submitted by a rule (or code) during the run, not typed in from outside. Players can submit 30 scores and 60 achievement unlocks per hour per game. The game's owner (and moderators) can remove an entry. ## Leaderboards and achievements: Profiles `/u/` shows: - a generated avatar (no uploads); - the games and packs the player published; - their achievements; - their best checked leaderboard places. There is no free-text bio. A private profile (set on `/account`) is hidden from others, and the player's name shows as "A player" on boards. ## Content packs Players and creators can extend a game they did not make, if its owner allows it (ADR 0015, ADR 0023). ## Content packs: What the game's owner decides In `game/game.json`: ```json "permissions": { "expansions": { "allowed": true, "contentTypes": ["levels", "prefabs", "assets"], "menu": true }, "remix": "remix" } ``` - `expansions.allowed`: people may make content packs for this game. `contentTypes` limits what packs may contain (scenes are always allowed). `menu: false` removes the automatic **Expansions** item from the title menu; open the `packs:menu` scene from your own menu or a rule instead. - `remix`: `none` (no copies), `fork` (private copies with credit, which cannot be published) or `remix` (copies may be published as new games, with credit). The platform reads these from the game's **live** release. ## Content packs: Making a pack 1. On the game's page, choose **Make a pack**, then give it a title and an address. The address is also the pack's `id`. 2. The editor opens on the pack's files, under `pack/`: - `pack.json` - `levels/`, `scenes/` and `prefabs/` - `assets/` (PNG, WebP, OGG, MP3, WAV, WOFF2) - `audio/` (synth sounds) You start with a copy of the game's first level and its scene. 3. Edit levels in the visual level editor. The game's tilesets and prefabs are there to use; they are read from its live release, and you can read them but not change them. **Play here** previews the game with your pack inside it. 4. **Release** checks the pack against the game's live release (every document, and every reference to a prefab, scene or level). The release then waits in the owner's queue. A pack is data and media only: no code (ADR 0015). Packs can use everything the game exposes as data: its prefabs, built-in components, rule actions, HUD and menus. ### Ids Use plain ids in a pack. When a pack is loaded, every id it defines becomes `:`: scenes, levels, prefabs, items, asset keys and the asset bundle. References inside the pack find the pack's own ids first, then the game's. So a pack can: - place the game's `coin` prefab; - extend the game's `player`; - send the player back to the game's `title` scene. It can never replace the game's own content. One more rule applies to component data: a string value that equals an id the pack defines counts as a reference to it. `pack.json` example: ```json { "schemaVersion": "0.1", "id": "ice-caves", "version": "1.0.0", "title": "Ice Caves", "authors": [{ "name": "Pat" }], "target": { "gameId": "platformer", "gameVersion": ">=0.1.0" }, "contents": { "start": ["cave-1"], "levels": [{ "id": "cave-1", "path": "levels/cave-1.json" }], "scenes": [{ "id": "cave-1", "path": "scenes/cave-1.json" }], "prefabs": [{ "id": "ice-spike", "path": "prefabs/ice-spike.json" }], "assets": [{ "key": "ice.tiles", "type": "image", "src": "assets/ice-tiles.png", "mediaType": "image/png" }] } } ``` `target.gameId` is the game's manifest `id`. `contents.start` lists the scenes the Expansions menu offers; it defaults to the first scene. ## Content packs: Review and play - **Review.** The game's owner sees submitted versions on the game's management page, under **Pack queue**. They can **Try it**, then approve or reject it. A rejection can include a note, which the creator sees on their pack's page. The newest approved version is the one players get. - **Players opt in.** On the game page, **Expansions** lists the approved packs. Each pack can be turned on or off; the choice is saved to the player's account, or kept in the browser for guests. Turned-on packs show up in the game's title menu under **Expansions**. If a pack fails to load or breaks the game, the game starts without packs. - **Moderation.** Packs can be reported like games, and moderators can take them down. ## Content packs: Forks and remixes **Fork** (or **Remix**) on a game's page copies the game's live release into a new game of yours. Its history and drafts are not copied. The new game: - records where it came from: `lineage` in `game.json` and an attribution line on its page; - links back to the original. A fork, made when the original allows only `fork`, stays private. A remix can be published. ## Getting started Requirements: Node.js 24+ (26 used in development) and pnpm 12 (`npm i -g pnpm`). ```bash pnpm install pnpm dev # Sprout, the sample game, with hot reload → http://localhost:5173 pnpm dev:demo # the Phase 1a test scene (also on :5173; run one at a time) ``` Open `http://localhost:5173/?debug` to start with the debug overlay open (toggle it with the backquote key). In the 1a demo, the sprite stress test is at `/?bench=sprites&n=2000`. Sprout's controls, file layout and tools are described in [games/sprout/README.md](../games/sprout/README.md). ## Getting started: Commands | Command | What it does | | --- | --- | | `pnpm dev` | Sprout dev server with hot reload (code: page reload; JSON data: swapped in place) | | `pnpm dev:demo` | The 1a demo instead | | `pnpm test` | Unit and headless game tests (Vitest), including a bot that plays all of Sprout | | `pnpm test:e2e` | Builds both games for production and plays them in headless Chromium (Playwright): keyboard, gamepad, level 1 completed. First time: `pnpm exec playwright install chromium` | | `pnpm lint` / `pnpm format` | Biome check / fix | | `pnpm typecheck` | TypeScript strict across all packages | | `pnpm bench` | ECS benchmark (fails if 5k entities exceed the 4 ms simulation budget) | | `pnpm size` | Builds both games, checks bundle-size budgets and that no Zod reached a production bundle | | `pnpm docs:api` | Generates the API reference into `docs/api/` (Markdown) | | `pnpm schemas` | Regenerates JSON Schemas from the Zod definitions | | `pnpm docs:llms` | Regenerates the AI docs and references (`--check` fails if they are stale) | | `pnpm create-game ` | Creates `games/` from a template | | `pnpm mcp` | Starts the MCP server on stdio (clients usually start it themselves) | | `pnpm evals` | AI success tests (see below; the default runner is free) | | `pnpm platform:dev` | The platform locally without Docker (http://localhost:3000) | | `pnpm platform:up` | The platform in Docker (`docker compose up --build`) | | `pnpm platform publish ` | Publish a game folder to a running platform (needs `PLATFORM_TOKEN`) | | `pnpm verify` | Everything above in sequence (except evals with a model) | ## Getting started: How a game is put together A game is a folder of JSON documents plus optional TypeScript (see `games/sprout/game`): ```text game.json manifest: display, input actions, UI theme, asset bundles, scenes, permissions scenes/*.json scene: level, camera, background, music, systems, HUD, menu, rules levels/*.json tilemap: tilesets with per-tile collision, tile layers, object layers prefabs/*.json entity templates: component values by component name assets/* images (PNG/SVG), bitmap fonts audio/*.json synthesized sounds and songs (or recorded files with the `audio` asset type) ``` ### Gameplay without code Built-in components cover a typical platformer: `PlatformerController`, `Health`, `ContactDamage` (set `stompable`), `Patrol` (walkers), `Hover` (flyers), `Pickup`, `Checkpoint`, `Lifetime` and `PlatformerAnimator`. Scenes connect events to actions with **rules**: ```json "rules": [ { "on": "pickup:coin", "do": [{ "action": "addToCounter", "counter": "coins", "amount": 1 }, { "action": "playSound", "sound": "sfx.coin" }] }, { "on": "player:died", "do": [{ "action": "respawn", "entity": "player", "delayMs": 1300 }] }, { "on": "input:pause", "do": [{ "action": "pushScene", "scene": "pause" }] } ] ``` Events include `scene:start`, `controller:jump`, `pickup:`, `enemy:stomped`, `:hurt`, `:died`, `checkpoint:reached`, `trigger:`, `input:` and `app:hidden`. Actions: `goToScene` (fades), `pushScene`, `popScene`, `restartScene`, `addToCounter`, `setCounter`, `playSound`, `playMusic`, `stopMusic`, `cameraShake`, `emit`, `respawn`, `setComponent`, `banner`, `toggleSetting`, `saveGame`; any action takes `delayMs`. HUD entries (`text`, `counter`, `icon`, `hearts`, `bar`, `timer`) and menu labels read values with bindings: `{game.coins}` (scene state), `{session.coins}` (across scenes), `{settings.sound}`, `{player.Health.hp}`. ### Production builds `vite build` with the `platformData` plugin validates every document (a mistake fails the build with its JSON pointer) and bundles normalized documents, so games load them without the validator and without Zod (ADR 0016). Every document has a JSON Schema (`packages/schema/json`), so editors autocomplete and the framework reports mistakes with exact paths, e.g. `levels/test-level.json#/layers/0/data — Expected 1200 cells, got 1199`. Code is the escape hatch: a game registers *behaviors* by name and scenes list them in `systems`: ```ts import { defineSystem, ParticleEmitter, startGame, type BehaviorFactory } from '@ludrel/framework'; const jumpDust: BehaviorFactory = () => defineSystem({ name: 'jumpDust', phase: 'fixed', setup(world) { world.events.on('controller:jump', (payload) => { const { entity } = payload as { entity: number }; const emitter = world.tryGet(entity, ParticleEmitter); if (emitter) emitter.burst += 8; }); }, run() {}, }); await startGame({ files, parent, behaviors: { jumpDust } }); ``` ## Getting started: The platform `pnpm platform:dev` runs the whole platform locally without Docker (catalog, accounts, publishing, sandboxed player, moderation) at http://localhost:3000; `pnpm platform:up` runs it in Docker. See [platform.md](platform.md). ## Getting started: Make games with AI The MCP server (`apps/mcp`) gives any MCP client the same tools the built-in assistant will use: create a game from a template, read and edit its files with validation, build levels from text, validate, run headless with assertions, capture screenshots and search the docs. Start with [the AI guide](guides/ai-guide.md); the generated AI docs are [`docs/llms.txt`](llms.txt) and [`docs/llms-full.txt`](llms-full.txt) (`pnpm docs:llms` regenerates them). - **Claude Code**: the repository's `.mcp.json` registers the server as `platform`; approve it when Claude Code asks. - **Other clients** (e.g. Claude Desktop): add a stdio server with the command `/node_modules/.bin/tsx` and the arguments `/apps/mcp/src/main.ts --root `. New games without AI: ```bash pnpm create-game my-game --title "My Game" pnpm --filter @ludrel/my-game dev ``` ### Evals (is the AI tooling good enough?) `pnpm evals` runs scripted tasks (add a double-jump power-up, add a second level, replace bees with a bat) on a fresh game and grades the result automatically. Runners: | Runner | Cost | What runs the task | | --- | --- | --- | | `--runner reference` (default) | free | each task's reference solution, through the same tools; proves the graders | | `--runner api` | API tokens | a fresh Claude session through `@ludrel/ai` (needs `ANTHROPIC_API_KEY` in your environment or an `ant auth login` profile) | | `--runner claude-code` | your Claude plan | `claude -p` restricted to this repository's MCP tools (needs the Claude Code CLI) | Add `--task ` for one task and `--keep` to inspect the game afterwards. Reports go to `.cache/evals/`. ## Getting started: Try hot reload With `pnpm dev` running, edit a prefab in `games/sprout/game/prefabs/` (e.g. the player's `PlatformerController.jumpSpeed` or a mushroom's `Patrol.speed`) or a scene's rules. The scene rebuilds in place and the player keeps its position. Save an invalid change (e.g. delete a number from `data`) and the overlay shows why it was rejected while the game keeps running. ## Getting started: Testing a game headless ```ts import { runHeadless } from '@ludrel/testing'; const r = await runHeadless({ gameDir: 'games/sprout/game', ticks: 300, inputs: [{ tick: 0, action: 'moveX', value: 1 }], watchEvents: ['player:died'], }); expect(r.errors).toEqual([]); ``` Same seed + same inputs = same result, so these tests are reliable — and the Phase 2 MCP `run_headless` tool will use this runner. ## Platformer template Start a game from this with `pnpm create-game ` (or the `create_game_from_template` AI tool). - `game/` holds the data: `game.json` (manifest), `scenes/` (title, level-1, pause, ending), `levels/` (`legend.json` maps map characters to tiles and prefabs), `prefabs/`, `audio/` (synth sounds and music), `assets/`. - `src/behaviors.ts` holds game-specific behaviors: every exported function can be listed in a scene's `systems`. - `src/bot.ts` is a simple bot used by `src/game.test.ts` to prove the level can be finished. Art and audio are original and come from the Sprout sample (`games/sprout`). ## Sprout sample A little sprout hops home across a sunny meadow and a ridge at dusk. Two levels, two enemy types, coins, hearts, checkpoints, a title screen, pause menu and ending, music and sound effects, keyboard, gamepad and mouse. ```bash pnpm dev # from the repo root → http://localhost:5173 ``` Useful URLs: `/?debug` (debug overlay), `/?scene=ridge` (jump to a scene), `/?bot` (exposes the test bot). ## Sprout sample: Controls | Action | Keyboard | Gamepad | | --- | --- | --- | | Move | ← → / A D | left stick, d-pad | | Jump (hold for higher) | Space, Z, W, ↑ | A | | Drop through a plank | ↓ + jump | d-pad down + A | | Pause / resume | Esc, P | Start (B also resumes) | | Menus | ↑ ↓ + Enter/Space, or the mouse | d-pad + A | ## Sprout sample: How it is made Almost everything is data, validated against the schemas in `packages/schema/json`: ```text game/game.json manifest: display, input actions, UI theme, assets, scenes game/scenes/ title, meadow, ridge, pause (overlay), ending: HUD, menus, rules game/prefabs/ player, coin, heart, mushroom, bee, checkpoint, goal game/levels/ generated by tools/levels.ts from ASCII segments game/assets/ generated by tools/art.ts (PNG) game/audio/ sound effects and songs as synth data (ADR 0017) src/behaviors.ts the only game code: a dust puff when jumping src/bot.ts a reactive bot used by tests ``` Regenerate art or levels after editing the tools: ```bash pnpm --filter @ludrel/sprout art # add `-- --preview out.png` for a zoomed contact sheet pnpm --filter @ludrel/sprout levels ``` Level maps use one character per tile, e.g. `#` ground (auto grass/dirt/edges), `/ \` slopes, `=` one-way plank, `^` spikes, `$` coin, `M` mushroom, `Q` bee, `C` checkpoint, `G` goal. The full legend is at the top of `tools/levels.ts`. ## Sprout sample: Credits and licence All art, music and sound effects are original, made for this project in code (pixel grids, procedural terrain and the built-in synthesizer). No third-party assets are used. ## Recipe: Write a code behavior When data is not enough, write a behavior: a system factory exported from `src/behaviors.ts`. Every exported function there is registered by name; list it in a scene's `systems` to run it. This one pulls nearby coins toward the player (a "magnet"), in the `fixed` phase so it stays deterministic: ```ts import { type BehaviorFactory, defineSystem, Pickup, Transform } from '@ludrel/framework'; /** Pulls coins within 40 px toward the player. */ export const coinMagnet: BehaviorFactory = () => defineSystem({ name: 'coinMagnet', phase: 'fixed', run(world, { dt }) { const player = world.named('player'); if (player === undefined) return; const p = world.get(player, Transform); world.query({ with: [Pickup, Transform] }).each((_e, pickup, t) => { if (pickup.kind !== 'coin') return; const dx = p.x - t.x; const dy = p.y - t.y; const d = Math.hypot(dx, dy); if (d > 40 || d < 1) return; t.x += (dx / d) * 120 * dt; t.y += (dy / d) * 120 * dt; }); }, }); ``` Scene: `"systems": ["platformerController", "platformerHazards", "coinMagnet"]`. Behaviors run before physics. After editing code, run `validate` with `typecheck: true`, then `run_headless`. Rules of thumb: read input through the `Input` resource, randomness through the `GameRng` resource (never `Math.random`), emit events with `world.events.enqueue('name', payload)` so rules can react, and keep component data plain JSON. ## Recipe: Add a new collectible Gems worth counting separately from coins: a prefab with `Pickup`, a rule that counts it, and a HUD counter. Prefab `game/prefabs/gem.json` (reuses the coin art, tinted): ```json prefab { "schemaVersion": "0.1", "id": "gem", "components": { "Transform": {}, "Sprite": { "texture": "sprite.items", "frame": 0, "tint": "#7fe3ff", "z": 15 }, "SpriteAnimation": { "animation": "spin" }, "Collider": { "w": 8, "h": 10, "offsetX": 4, "offsetY": 3, "trigger": true, "layer": "pickup", "mask": ["player"] }, "Pickup": { "kind": "gem", "effectColor": "#7fe3ff" } } } ``` Scene rules (add to the level scene's `rules`): ```json rules [ { "on": "pickup:gem", "do": [ { "action": "addToCounter", "counter": "gems", "amount": 1 }, { "action": "playSound", "sound": "sfx.coin" } ] } ] ``` HUD entry (add to the scene's `hud`); `gemTotal` is set automatically from the gems in the level: ```json hud [{ "widget": "counter", "anchor": "top", "label": "GEMS {value}/{game.gemTotal}", "bind": "game.gems" }] ``` Then place gems with `add_entity` or a legend character, and check with `run_headless`: `expect: [{ "event": "pickup:gem" }]`. ## Recipe: Add enemies Enemies are prefabs with `ContactDamage` plus a movement component. A spiky walker that cannot be stomped (jump over it): ```json prefab { "schemaVersion": "0.1", "id": "spiky", "tags": ["enemy"], "components": { "Transform": {}, "Sprite": { "texture": "sprite.enemies", "frame": 0, "tint": "#b0a0ff", "anchorX": 0.5, "offsetX": 8, "z": 18 }, "SpriteAnimation": { "animation": "walk" }, "Body": { "maxFallSpeed": 500 }, "Collider": { "w": 12, "h": 11, "offsetX": 2, "offsetY": 5, "layer": "enemy", "mask": ["player"] }, "Patrol": { "speed": 45, "turnAtLedges": true }, "ContactDamage": { "amount": 1, "stompable": false } } } ``` A bat that swoops in a wide sine wave (`Hover` moves the Transform; no `Body` needed): ```json prefab { "schemaVersion": "0.1", "id": "bat", "extends": "bee", "components": { "Sprite": { "tint": "#8a6db0" }, "Hover": { "rangeX": 48, "rangeY": 20, "period": 4, "bobPeriod": 2 } } } ``` `extends` merges the parent prefab's components under these, so the bat keeps the bee's collider and damage. Stomps emit `enemy:stomped`; reward them with a rule. ## Recipe: Make a new level Levels are built from text rows with `build_level`; the characters come from `game/levels/legend.json`. In the platformer template: `#` ground, `/` `\` slopes, `=` one-way plank, `^` spikes, `X` block, `P` player, `$` coin, `H` heart, `M` mushroom, `Q` bee, `C` checkpoint, `G` goal (2 tiles tall), and decorations (`,` `r` `y` `B`...). ```json build_level { "id": "level-2", "name": "Level 2", "rows": [ "..............................", "..............$$$.............", ".............=====............", "..P....$$...........M....G....", "######..####^^################", "######..######################" ] } ``` Rules for rows: all the same length (otherwise the tool reports e.g. `Row 5 is 34 characters wide; row 0 is 30`), the player on solid ground, gaps at most 4 tiles wide and steps at most 3 tiles high (jump height is about 4 tiles). Columns 6–7 above are a pit (falling in costs a life); `^` spikes hurt and bounce the player. Then make a scene for it: copy the level-1 scene with `id: "level-2"` and `level: "levels/level-2.json"` (`upsert_scene`), and point level 1's goal rule at it: `{ "action": "goToScene", "scene": "level-2", "delayMs": 2800 }`. Check that the level can be finished by holding right and jumping at the right moments with `run_headless`, or at least that `player.Transform.x` increases and no errors appear. ## Recipe: A 3D level: ground, a ramp, a moving platform, gems and a goal Needs a game with `"display": { "mode": "3d" }`. The level goes in `game/levels3d/`, and a scene points at it with `"level3d"`. Blocks are `pieces`, with `position` at the centre and sizes in metres (y is up). Everything else is a prefab placed as an object: ```json level3d { "schemaVersion": "0.1", "id": "meadow", "killY": -4, "sky": { "color": "#8fd0ff", "fog": { "color": "#bfe6ff", "near": 30, "far": 90 } }, "pieces": [ { "id": "ground", "shape": "box", "position": { "x": 0, "y": -0.5, "z": 0 }, "size": { "x": 24, "y": 1, "z": 24 }, "color": "#6cbf5a" }, { "id": "ledge", "shape": "box", "position": { "x": 8, "y": 1, "z": 0 }, "size": { "x": 6, "y": 2, "z": 6 }, "color": "#8a9a5b" }, { "id": "ramp", "shape": "ramp", "position": { "x": 3, "y": 1, "z": 0 }, "size": { "x": 4, "y": 2, "z": 3 }, "color": "#a6b36a" } ], "objects": [ { "kind": "spawn", "id": "player", "prefab": "runner", "position": { "x": 0, "y": 1, "z": -6 } }, { "kind": "spawn", "prefab": "gem", "position": { "x": 8, "y": 2.9, "z": 0 } }, { "kind": "spawn", "prefab": "lift", "position": { "x": -5, "y": 0.25, "z": 4 } }, { "kind": "trigger", "position": { "x": 0, "y": 1, "z": 10 }, "size": { "x": 3, "y": 2, "z": 3 }, "event": "goal", "filterTag": "player" } ] } ``` The moving platform (`lift`): a kinematic block that rises 3.6 m and back every 6 seconds. Characters on it ride along. ```json prefab { "schemaVersion": "0.1", "id": "lift", "components": { "Transform3D": {}, "Mesh": { "shape": "box", "w": 2.5, "h": 0.5, "d": 2.5, "color": "#c9a46b" }, "Collider3D": { "w": 2.5, "h": 0.5, "d": 2.5 }, "Mover3D": { "y": 3.6, "period": 6 } } } ``` A gem that spins and is collected when touched (`pickup:gem`): ```json prefab { "schemaVersion": "0.1", "id": "gem", "components": { "Transform3D": {}, "Mesh": { "shape": "sphere", "w": 0.5, "color": "#4fd1ff" }, "Collider3D": { "shape": "sphere", "w": 1, "sensor": true }, "Pickup": { "kind": "gem" }, "Spin3D": { "speed": 120 } } } ``` Rules: count gems, bring the player back after a fall, and finish at the goal: ```json rules [ { "on": "pickup:gem", "do": [{ "action": "addToCounter", "counter": "gems", "amount": 1 }] }, { "on": "player:fell", "do": [{ "action": "respawn", "entity": "player", "delayMs": 600 }] }, { "on": "trigger:goal", "do": [{ "action": "goToScene", "scene": "win" }] } ] ``` ## Recipe: Menus and HUD A scene `menu` is a vertical list navigated with `uiUp`/`uiDown`/`uiConfirm` (keyboard, gamepad) or the mouse (`uiClick`); `back` runs on `uiBack`. Labels can show bindings. ```json menu { "anchor": "center", "items": [ { "label": "PLAY", "do": [{ "action": "goToScene", "scene": "level-1" }] }, { "label": "SOUND: {settings.sound}", "do": [{ "action": "toggleSetting", "setting": "sound" }] } ], "back": [{ "action": "popScene" }] } ``` HUD widgets: `text`, `counter`, `icon` (sprite + value), `hearts` (full/empty frames up to `max`), `bar`, `timer`. ```json hud [ { "widget": "hearts", "anchor": "top-left", "bind": "player.Health.hp", "max": "player.Health.max", "icon": "ui.icons", "frames": [0, 1] }, { "widget": "icon", "anchor": "top-right", "icon": "ui.icons", "frames": [2], "bind": "game.coins", "label": "{value}/{game.coinTotal}" }, { "widget": "timer", "anchor": "top", "label": "TIME " } ] ``` A pause menu is an `overlay` scene opened with `{ "on": "input:pause", "do": [{ "action": "pushScene", "scene": "pause" }] }`; the scene below freezes until `popScene`. ## Recipe: A talking NPC with a quest (top-down) Needs a game with an `interact` input action and the `topDownController` behavior (the top-down template has both). Four pieces of data: the NPC prefab, its brain, its dialogue and the quest. List the files in `game.json` (`brains`, `dialogues`, `quests`) and the item in `items`. The NPC walks around, stops to chat when talked to (`talked:` is emitted with the entity's name), and offers a quest. Its `Interactable` opens the dialogue when the player presses `interact` nearby: ```json prefab { "schemaVersion": "0.1", "id": "baker", "components": { "Transform": {}, "Sprite": { "texture": "sprite.villager", "frame": 0, "z": 20 }, "SpriteAnimation": { "animation": "idle-down" }, "TopDownAnimator": {}, "Body": { "gravityScale": 0 }, "Collider": { "w": 10, "h": 6, "offsetX": 3, "offsetY": 10, "layer": "npc", "mask": ["world"] }, "Brain": { "brain": "baker" }, "Interactable": { "dialogue": "baker", "prompt": "@prompt.talk" } } } ``` The brain (`game/ai/baker.json`): a state machine. States run an activity (`idle`, `wander`, `moveTo`, `follow`, `flee`, `wait`, `say`, `do`) or a behaviour `tree`; transitions fire on an event (`on`), a condition (`if`), time (`after`) or the activity finishing (`done`): ```json brain { "schemaVersion": "0.1", "id": "baker", "speed": 30, "machine": { "initial": "wander", "states": { "wander": { "activity": { "act": "wander", "radius": 40, "pause": 2 }, "transitions": [{ "to": "chat", "on": "talked:baker" }] }, "chat": { "activity": { "act": "idle" }, "transitions": [{ "to": "wander", "after": 4 }] } } } } ``` A shy animal is a behaviour tree: flee when the player is near, else wander. ```json brain { "schemaVersion": "0.1", "id": "cat", "tree": { "type": "selector", "children": [ { "type": "sequence", "children": [ { "type": "condition", "if": { "near": "player", "within": 48 } }, { "type": "action", "action": { "act": "flee", "from": "player", "distance": 96 } } ] }, { "type": "action", "action": { "act": "wander", "radius": 40 } } ] } } ``` The dialogue (`game/dialogues/baker.json`). `branches` jump elsewhere when a condition holds, so the same NPC says the right thing at each stage of the quest; choices can have conditions and actions: ```json dialogue { "schemaVersion": "0.1", "id": "baker", "start": "hi", "speakers": { "baker": { "name": "Baker" } }, "nodes": { "hi": { "speaker": "baker", "text": "Could you bring me some flour?", "branches": [ { "if": { "quest": "flour", "is": "done" }, "next": "thanks" }, { "if": { "hasItem": "flour" }, "next": "give" } ], "choices": [ { "text": "Sure.", "do": [{ "action": "startQuest", "quest": "flour" }] }, { "text": "Not now." } ] }, "give": { "speaker": "baker", "text": "Perfect, thank you!", "do": [ { "action": "takeItem", "item": "flour" }, { "action": "emit", "event": "gave:flour" } ] }, "thanks": { "speaker": "baker", "text": "Fresh bread soon!" } } } ``` The quest (`game/quests/flour.json`): steps complete in order, on an event or when a condition holds. The `quest` HUD widget shows the current step. ```json quest { "schemaVersion": "0.1", "id": "flour", "title": "Flour for the baker", "steps": [ { "id": "find", "text": "Find a bag of flour", "when": { "if": { "hasItem": "flour" } } }, { "id": "bring", "text": "Bring it to the baker", "when": { "event": "gave:flour" } } ], "rewards": [{ "action": "giveItem", "item": "bread" }] } ``` The flour itself is a prefab with `"Pickup": { "kind": "flour", "item": "flour" }`. Check everything with `validate`, then `run_headless`. ## Recipe: Add a power-up (double jump) A pickup whose rule changes the player's controller. No code needed. ```json prefab { "schemaVersion": "0.1", "id": "feather", "components": { "Transform": {}, "Sprite": { "texture": "sprite.items", "frame": 4, "tint": "#c8f0ff", "z": 15 }, "Collider": { "w": 10, "h": 10, "offsetX": 3, "offsetY": 3, "trigger": true, "layer": "pickup", "mask": ["player"] }, "Pickup": { "kind": "feather", "effectColor": "#c8f0ff" }, "Hover": { "rangeX": 0, "rangeY": 2, "bobPeriod": 1 } } } ``` ```json rules [ { "on": "pickup:feather", "do": [ { "action": "setComponent", "entity": "player", "component": "PlatformerController", "values": { "maxJumps": 2 } }, { "action": "banner", "text": "DOUBLE JUMP!", "durationMs": 1200, "size": 8 }, { "action": "playSound", "sound": "sfx.checkpoint" } ] } ] ``` Prove it: run the level, touch the feather, then press jump twice in the air and count jumps: `watch: ["controller:jump"]` should report 2 jumps for one take-off. ## Recipe: Add sounds and music Sounds and songs are synth data in `game/audio/` (asset type `synth`), rendered when the game loads. A sound effect, `game/audio/zap.json`: ```json synth { "kind": "sound", "wave": "square", "duty": 0.25, "frequency": 880, "slideTo": 220, "duration": 0.2, "volume": 0.3, "vibrato": { "rate": 20, "depth": 0.5 } } ``` Register it in `game.json` under an asset bundle and play it from a rule: ```json rules [{ "on": "enemy:stomped", "do": [{ "action": "playSound", "sound": "sfx.zap" }] }] ``` with the asset entry `{ "key": "sfx.zap", "type": "synth", "src": "audio/zap.json", "bus": "sfx" }`. A song: tracks of space-separated steps (`C4`, `F#3`, `.` rest, `-` hold), patterns played in `sequence`, and a drum line (`k` kick, `s` snare, `h` hi-hat). All tracks should have the same number of steps. ```json synth { "kind": "song", "bpm": 120, "tracks": [ { "instrument": { "wave": "square", "duty": 0.25, "volume": 0.2 }, "patterns": { "A": "C5 - E5 - G5 - E5 -", "B": "D5 - F5 - A5 - - -" }, "sequence": ["A", "B"] }, { "instrument": { "wave": "triangle", "volume": 0.5 }, "patterns": { "A": "C3 . . . G2 . . .", "B": "D3 . . . A2 . . ." }, "sequence": ["A", "B"] }, { "drums": true, "patterns": { "D": "k . h . s . h ." }, "sequence": ["D", "D"] } ] } ``` Play it with the scene's `music` (`{ "track": "music.theme" }`) or a `playMusic` action. ## Recipe: Waves of enemies (arcade) Enemies that sway down the screen, worth points, removed when shot down or when they leave the view. They hurt the player on contact (`ContactDamage`) and need the tag your bullets target: ```json prefab { "schemaVersion": "0.1", "id": "drone", "tags": ["enemy"], "components": { "Transform": {}, "Sprite": { "texture": "sprite.drone", "frame": 0, "z": 15 }, "Collider": { "w": 12, "h": 10, "offsetX": 2, "offsetY": 3, "trigger": true, "layer": "enemy", "mask": ["player", "shot"] }, "Health": { "hp": 1, "max": 1, "invulnerableTime": 0.08, "knockback": 0 }, "ContactDamage": { "amount": 1, "stompable": false }, "Mover": { "pattern": "sine", "vy": 40, "amplitude": 24, "period": 2 }, "Score": { "points": 10 }, "Offscreen": { "margin": 24 } } } ``` The player's bullet (its `Shooter` has `"bullet": "laser"`): ```json prefab { "schemaVersion": "0.1", "id": "laser", "components": { "Transform": {}, "Sprite": { "texture": "sprite.items", "frame": 0, "z": 12 }, "Collider": { "w": 4, "h": 8, "trigger": true, "layer": "shot", "mask": ["enemy"] }, "Projectile": { "damage": 1, "targetTag": "enemy" }, "Offscreen": { "margin": 8 } } } ``` The scene's `waves`: five drones in a column, then six side by side, then a fan of divers: ```json waves [ { "at": 1, "prefab": "drone", "count": 5, "every": 0.5, "x": 0.5 }, { "at": 5, "prefab": "drone", "count": 6, "every": 0.05, "x": 0.5, "formation": "line", "spacing": 24 }, { "at": 9, "prefab": "drone", "count": 5, "formation": "v", "spacing": 18, "components": { "Mover": { "pattern": "dive", "delay": 1.2 } } } ] ``` When every wave is cleared, keep the best score and show the end: ```json rules [ { "on": "waves:done", "do": [ { "action": "recordBest", "value": "session.score", "key": "score" }, { "action": "goToScene", "scene": "victory", "delayMs": 1500 } ] } ] ``` On phones, a top-down ship gets a floating joystick by itself; to choose the layout, add to `game.json`: ```json touch { "move": { "type": "joystick", "x": "moveX", "y": "moveY" }, "buttons": [], "pause": "pause" } ``` Every component that game data can use, by name, with its default values. Put them in prefab or entity `components` objects; omitted fields keep their defaults. Generated from the source (`pnpm docs:llms`). ## Component Body A moving body. Velocity is in pixels per second; the physics system integrates it every fixed step and resolves collisions. Contact flags (`onFloor`...) are outputs, recomputed every step. Example: world.add(player, Body, { maxFallSpeed: 600 }); if (input.pressed('jump') && world.get(player, Body).onFloor) world.get(player, Body).vy = -380; | Field | Default | Notes | | --- | --- | --- | | `vx` | `0` | | | `vy` | `0` | | | `gravityScale` | `1` | Multiplier on world gravity (0 = floats). | | `maxFallSpeed` | `900` | Terminal downward speed (px/s). | | `dragX` | `0` | Horizontal deceleration toward 0 when no other system sets vx (px/s²). 0 = none. | | `collideTiles` | `true` | Collide with tiles. | | `collideWorldBounds` | `true` | Keep inside the tilemap's left/right/top edges. | | `dropThrough` | `false` | Fall through one-way platforms this step (set by controllers for "down + jump"). | | `onFloor` | `false` | | | `onCeiling` | `false` | | | `onWallLeft` | `false` | | | `onWallRight` | `false` | | | `onSlope` | `false` | | Package: `@ludrel/physics-arcade` ## Component Brain An NPC driven by a brain document (`game/ai/.json`): a state machine or a behaviour tree. | Field | Default | Notes | | --- | --- | --- | | `brain` | `""` | | | `speed` | `0` | Walking speed override (0 = the brain's `speed`). | Package: `@ludrel/framework` ## Component Checkpoint Touching it makes it the respawn point (emits `checkpoint:reached` once) and plays its `activeAnimation`. | Field | Default | Notes | | --- | --- | --- | | `targetTag` | `"player"` | | | `activeAnimation` | `"active"` | | | `active` | `false` | Output. | Package: `@ludrel/framework` ## Component Collider Axis-aligned collision box relative to the entity's Transform. Without a Body it is static: `solid` statics block bodies like tiles, `oneWay` ones only from above, and `trigger` colliders only report overlaps. Layers: `layer` is this collider's layer name; `mask` lists layers it interacts with (`*` = all). To change a mask at runtime assign a new array (masks are cached per array). Example: world.add(coin, Collider, { w: 8, h: 8, offsetX: 4, offsetY: 4, layer: 'pickup', mask: ['player'], trigger: true }); | Field | Default | Notes | | --- | --- | --- | | `w` | `16` | | | `h` | `16` | | | `offsetX` | `0` | | | `offsetY` | `0` | | | `layer` | `"default"` | | | `mask` | `["*"]` | | | `trigger` | `false` | | | `solid` | `false` | | | `oneWay` | `false` | | Package: `@ludrel/physics-arcade` ## Component ContactDamage Hurts entities with `targetTag` on contact. If `stompable`, landing on top defeats this entity instead (emits `enemy:stomped`) and bounces the stomper. Example: (prefab JSON) "ContactDamage": { "amount": 1, "stompable": true } | Field | Default | Notes | | --- | --- | --- | | `amount` | `1` | | | `targetTag` | `"player"` | | | `stompable` | `true` | | | `bounce` | `240` | Upward speed given to the stomper (px/s). | Package: `@ludrel/framework` ## Component Health Hit points with a short invulnerability after each hit. At 0 the entity dies: `:died` is emitted and a controlled entity (PlatformerController) pops up and falls off screen until `respawn` revives it. Example: (prefab JSON) "Health": { "hp": 3, "max": 3 } | Field | Default | Notes | | --- | --- | --- | | `hp` | `3` | | | `max` | `3` | | | `invulnerableTime` | `1.2` | Seconds of invulnerability after a hit (the sprite blinks). | | `knockback` | `150` | Speed of the knockback after a hit (px/s). | | `invulnerable` | `0` | Output: seconds of invulnerability left. | | `dead` | `false` | Output: true from death until respawn. | Package: `@ludrel/framework` ## Component Hover Floats around its starting point (flying enemies, moving pickups). Moves the Transform; no Body needed. | Field | Default | Notes | | --- | --- | --- | | `rangeX` | `32` | Horizontal travel each side of the start (px). | | `rangeY` | `6` | Vertical bobbing each side of the start (px). | | `period` | `3` | Seconds for one horizontal round trip. | | `bobPeriod` | `1` | Seconds for one bob. | | `phase` | `0` | Starting offset in the cycle (0..1), so neighbours don't move in sync. | Package: `@ludrel/framework` ## Component Interactable Something the player can talk to or use: pressing the `interact` action nearby starts `dialogue` (if any) and emits `talked:` and `event` (if any). Shows `prompt` above it while the player is in range. | Field | Default | Notes | | --- | --- | --- | | `dialogue` | `""` | | | `event` | `""` | | | `range` | `24` | | | `prompt` | `""` | | | `targetTag` | `"player"` | Tag of who can interact. | Package: `@ludrel/framework` ## Component KeepInView | Field | Default | Notes | | --- | --- | --- | | `margin` | `2` | | ## Component Lifetime Despawns the entity after `seconds` (effects, banners, defeated enemies). | Field | Default | Notes | | --- | --- | --- | | `seconds` | `1` | | Package: `@ludrel/framework` ## Component Mover Moves an entity by itself (Transform, no Body needed): `line` at (vx, vy); `sine` and `zigzag` sway sideways by `amplitude` every `period` seconds while moving at (vx, vy); `dive` drifts for `delay` seconds, then speeds toward where the player was. | Field | Default | Notes | | --- | --- | --- | | `pattern` | `"line"` | | | `vx` | `0` | | | `vy` | `40` | | | `amplitude` | `24` | | | `period` | `2` | | | `delay` | `1` | | | `speed` | `140` | Speed of a dive (px/s). | | `time` | `0` | Output: seconds since it started moving. | Package: `@ludrel/framework` ## Component Name | Field | Default | Notes | | --- | --- | --- | | `value` | `""` | | ## Component NetPlayer Marks an entity as an online player's: its controls read that player's inputs (ADR 0027). | Field | Default | Notes | | --- | --- | --- | | `index` | `0` | | | `name` | `""` | Output: the player's name (their handle), set when the match starts. | Package: `@ludrel/input` ## Component Offscreen | Field | Default | Notes | | --- | --- | --- | | `margin` | `32` | | ## Component Parallax A repeating background image that scrolls at a fraction of the camera's speed. Needs no Transform. Example: world.add(world.spawn(), Parallax, { texture: 'bg.hills', scrollX: 0.3, offsetY: 40, z: -10 }); | Field | Default | Notes | | --- | --- | --- | | `texture` | `""` | | | `scrollX` | `0.5` | 0 = fixed to the screen, 1 = moves with the world. | | `scrollY` | `0` | | | `repeatX` | `true` | | | `repeatY` | `false` | | | `offsetX` | `0` | | | `offsetY` | `0` | | | `alpha` | `1` | | | `visible` | `true` | | | `z` | `0` | | Package: `@ludrel/render-2d` ## Component ParticleEmitter | Field | Default | Notes | | --- | --- | --- | | `texture` | `""` | | | `color` | `"#ffffff"` | | | `size` | `2` | | | `rate` | `20` | | | `burst` | `0` | | | `emitting` | `true` | | | `lifetime` | `[0.4,0.8]` | | | `speed` | `[20,60]` | | | `angle` | `[0,360]` | | | `gravity` | `0` | | | `scale` | `[1,0]` | | | `alpha` | `[1,0]` | | | `maxParticles` | `200` | | | `offsetX` | `0` | | | `offsetY` | `0` | | | `z` | `0` | | ## Component Patrol Walks back and forth, turning at walls and (optionally) ledges. Needs a Body. | Field | Default | Notes | | --- | --- | --- | | `speed` | `30` | | | `direction` | `-1` | -1 = left, 1 = right. | | `turnAtLedges` | `true` | | Package: `@ludrel/framework` ## Component Pickup Collected when an entity with `targetTag` touches it: emits `pickup:` (count it with rules), heals by `heal`, bursts a few particles and disappears. The scene state gets `Total` (pickups of that kind at scene start), handy for "Coins 3/20". | Field | Default | Notes | | --- | --- | --- | | `kind` | `"coin"` | | | `targetTag` | `"player"` | | | `heal` | `0` | | | `item` | `""` | An item (manifest `items`) the collector gets. | | `effectColor` | `"#ffe066"` | Particle colour of the collect effect (empty = none). | Package: `@ludrel/framework` ## Component PlatformerAnimator | Field | Default | Notes | | --- | --- | --- | | `idle` | `"idle"` | | | `run` | `"run"` | | | `jump` | `"jump"` | | | `fall` | `"fall"` | | | `hurt` | `"hurt"` | | ## Component PlatformerController Side-scroller controls: run with acceleration, variable-height jump, coyote time, jump buffering, optional multi-jump, and drop through one-way platforms with down + jump. Reads input actions by name. Example: (prefab JSON) "PlatformerController": { "speed": 110, "jumpSpeed": 320, "maxJumps": 2 } | Field | Default | Notes | | --- | --- | --- | | `enabled` | `true` | When false the controller leaves the body alone (cutscenes, death, level clear). | | `moveAction` | `"moveX"` | | | `jumpAction` | `"jump"` | | | `downAction` | `"down"` | Optional action for dropping through one-way platforms (with jump). | | `speed` | `110` | Max horizontal speed (px/s). | | `acceleration` | `1400` | | | `deceleration` | `1800` | | | `airControl` | `0.65` | Fraction of acceleration available in the air. | | `jumpSpeed` | `320` | | | `jumpCut` | `0.45` | Upward speed is multiplied by this when jump is released early (shorter hops). | | `coyoteTime` | `0.1` | Seconds after leaving a ledge during which jumping still works. | | `jumpBuffer` | `0.12` | Seconds a jump press is remembered before landing. | | `maxJumps` | `1` | | | `facing` | `1` | Output: 1 = facing right, -1 = left. | | `state` | `"idle"` | Output: idle | run | jump | fall. | Package: `@ludrel/framework` ## Component Projectile A bullet: hurts the first entity with Health and `targetTag` it touches, then disappears. | Field | Default | Notes | | --- | --- | --- | | `damage` | `1` | | | `targetTag` | `"enemy"` | | Package: `@ludrel/framework` ## Component Rect A solid coloured rectangle — handy for prototypes, placeholder art and UI. | Field | Default | Notes | | --- | --- | --- | | `w` | `16` | | | `h` | `16` | | | `color` | `"#ffffff"` | | | `offsetX` | `0` | | | `offsetY` | `0` | | | `alpha` | `1` | | | `visible` | `true` | | | `z` | `0` | | | `space` | `"world"` | `screen` keeps it fixed on screen (HUD panels, dimmers). | Package: `@ludrel/render-2d` ## Component Score Adds `points` to a counter (`session.score` by default) when the entity is defeated (its Health reaches 0). | Field | Default | Notes | | --- | --- | --- | | `points` | `100` | | | `counter` | `"score"` | | | `effectColor` | `"#ffb347"` | Particle colour of the explosion (empty = none). | | `sound` | `""` | | Package: `@ludrel/framework` ## Component Shooter Fires `bullet` prefabs: automatically, or while `action` is held. `direction` is `up`, `down` or `player` (aimed); `count` bullets fan out over `spread` degrees. | Field | Default | Notes | | --- | --- | --- | | `bullet` | `""` | | | `rate` | `4` | Shots per second. | | `action` | `""` | Input action that fires while held; empty = fires by itself. | | `speed` | `200` | | | `direction` | `"up"` | | | `count` | `1` | | | `spread` | `0` | | | `offsetX` | `0` | | | `offsetY` | `0` | | | `sound` | `""` | | | `delay` | `0` | Seconds before the first automatic shot (enemies wait a little after appearing). | | `enabled` | `true` | | | `cooldown` | `0` | Output: seconds until it can fire again. | Package: `@ludrel/framework` ## Component Sprite Draws a texture (or one frame of a sprite sheet) at the entity's Transform. Use `anchorX/anchorY` 0.5 for sprites that flip, so they flip around their center. Example: world.add(player, Sprite, { texture: 'player.sheet', frame: 0, anchorX: 0.5, anchorY: 1 }); | Field | Default | Notes | | --- | --- | --- | | `texture` | `""` | Asset key of an image, tileset or sprite sheet. | | `frame` | `-1` | Frame index for sprite sheets; -1 draws the whole texture. | | `anchorX` | `0` | | | `anchorY` | `0` | | | `offsetX` | `0` | | | `offsetY` | `0` | | | `flipX` | `false` | | | `flipY` | `false` | | | `tint` | `"#ffffff"` | | | `alpha` | `1` | | | `visible` | `true` | | | `z` | `0` | Draw order within the layer; higher is in front. | | `space` | `"world"` | `screen` keeps it fixed on screen (HUD icons). | Package: `@ludrel/render-2d` ## Component SpriteAnimation Plays a named animation from the sprite sheet used by the entity's Sprite (animations are declared in the manifest's asset entry). Set `animation` to switch; time restarts automatically. Example: world.get(player, SpriteAnimation).animation = body.onFloor ? 'run' : 'jump'; | Field | Default | Notes | | --- | --- | --- | | `animation` | `""` | | | `speed` | `1` | | | `playing` | `true` | | | `finished` | `false` | Output: true when a non-looping animation reached its last frame. | Package: `@ludrel/render-2d` ## Component Tags | Field | Default | Notes | | --- | --- | --- | | `values` | `[]` | | ## Component Text Text at the entity's Transform. `space: 'screen'` keeps it fixed on screen (HUD). If `font` is the key of a loaded bitmap font (asset type `font`), the text is drawn with it, scaled by the whole number nearest to `size / glyph height` (crisp pixel text); otherwise `font` is a CSS font family. Example: world.add(e, Text, { text: 'Coins 3', font: 'font.main', size: 8, shadow: '#000000' }); | Field | Default | Notes | | --- | --- | --- | | `text` | `""` | | | `size` | `12` | | | `color` | `"#ffffff"` | | | `align` | `"left"` | | | `font` | `"monospace"` | | | `shadow` | `""` | Bitmap fonts only: drop-shadow colour (empty = none). | | `space` | `"screen"` | | | `alpha` | `1` | | | `visible` | `true` | | | `z` | `100` | | Package: `@ludrel/render-2d` ## Component TopDownAnimator Picks the sprite animation for top-down characters (players and NPCs): `-` while moving, else `-` (facing is `down`, `up`, `left` or `right`). With `directional: false` it plays `` or `` and flips the sprite to face left. | Field | Default | Notes | | --- | --- | --- | | `idle` | `"idle"` | | | `walk` | `"walk"` | | | `directional` | `true` | | | `facing` | `"down"` | Output, also set from movement for NPCs. | Package: `@ludrel/framework` ## Component TopDownController Eight-way movement from two axis actions (top-down games). Faces the way it last moved. | Field | Default | Notes | | --- | --- | --- | | `enabled` | `true` | | | `moveXAction` | `"moveX"` | | | `moveYAction` | `"moveY"` | | | `speed` | `80` | | | `acceleration` | `900` | | | `facing` | `"down"` | Output: `down`, `up`, `left` or `right`. | Package: `@ludrel/framework` ## Component Transform Position (pixels, world space), rotation (radians) and scale of an entity. Physics, rendering and cameras all read this component. Example: world.add(player, Transform, { x: 32, y: 80 }); | Field | Default | Notes | | --- | --- | --- | | `x` | `0` | | | `y` | `0` | | | `rotation` | `0` | | | `scaleX` | `1` | | | `scaleY` | `1` | | Package: `@ludrel/core` ## Component Transform3D Position (metres; y is up), rotation (degrees around x, y, z) and scale of a 3D entity. 3D physics, rendering and cameras read it. Example: world.add(gem, Transform3D, { x: 2, y: 1, z: -4 }); | Field | Default | Notes | | --- | --- | --- | | `x` | `0` | | | `y` | `0` | | | `z` | `0` | | | `rx` | `0` | | | `ry` | `0` | | | `rz` | `0` | | | `sx` | `1` | | | `sy` | `1` | | | `sz` | `1` | | Package: `@ludrel/core` ## Component Trigger A zone that emits `trigger:` on the world's event bus when a matching entity enters it. Created from level `trigger` objects. | Field | Default | Notes | | --- | --- | --- | | `event` | `""` | | | `filterTag` | `""` | Only entities with this tag fire it (empty = any body). | | `once` | `false` | | Package: `@ludrel/framework` Top-level fields of each game document (full JSON Schemas: `packages/schema/json/`), then every action that scene rules and menu items can run. Generated from the Zod schemas (`pnpm docs:llms`). ## Document manifest Root document of a game (game.json). | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `id` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `title` | string \| object | yes | | Plain string, or a map of locale → string. | | `description` | string \| object | | | Plain string, or a map of locale → string. | | `version` | string | yes | | Semantic version, e.g. 1.4.0. | | `engine` | object | yes | | Framework version range. | | `genre` | "platformer" \| "top-down" \| "arcade" \| "puzzle" \| "racing" \| "shooter" \| " | | | | | `tags` | string[] | | | | | `authors` | object[] | | | | | `defaultLocale` | string | | `"en"` | | | `display` | object | yes | | | | `simulation` | object | | | | | `physics` | object | | | | | `input` | object | yes | | | | `ui` | object | | | Game-wide look of text and menus. | | `assets` | object | | | Asset bundles by id. | | `prefabs` | string[] | | | Paths to prefab JSON files. | | `items` | object[] | | | Things players can carry (inventory). | | `dialogues` | string[] | | | Paths to dialogue files. | | `quests` | string[] | | | Paths to quest files. | | `brains` | string[] | | | Paths to NPC brain files (state machines, behaviour trees). | | `localization` | object | | | String tables: '@key' in any text field shows the player's language. | | `scenes` | object[] | yes | | | | `entryScene` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `behaviors` | string[] | | | Code behaviours/systems this game registers and lets data reference. | | `touch` | object | | | On-screen controls for touch screens (shown on phones and tablets, or with '?touch'). | | `multiplayer` | object | | | Online play (ADR 0027): rooms of signed-in players; every browser steps the same match in lockstep. | | `leaderboards` | object[] | | | Boards the platform keeps (best score per player); a game submits with 'submitScore'. | | `achievements` | object[] | | | Achievements the platform shows on profiles; a game unlocks them with 'unlockAchievement'. | | `permissions` | object | | | Publisher's per-game choices for community extensions. | | `monetization` | object | | | Reserved for the monetization phase. | | `lineage` | object | | | Set by the platform on fork/remix. Read-only for creators. | ## Document scene A scene: level, entities, systems, camera, background, music, HUD and rules. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `id` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `kind` | "gameplay" \| "menu" \| "cutscene" \| "overlay" | | `"gameplay"` | | | `bundles` | string[] | | | Asset bundle ids to load before the scene starts. | | `level` | string | | | Level file to load into this scene. | | `level3d` | string | | | 3D games: a level3d file (pieces, objects, lights). | | `world` | string | | | Or a world file: chunk levels streamed around the camera (instead of `level`). | | `camera` | object | | | | | `background` | object | | | | | `music` | object | | | | | `entities` | object[] | | | | | `systems` | string[] | | | Registered system names to run in this scene, in order. | | `hud` | object[] | | | | | `menu` | object | | | A vertical menu navigated with the 'uiUp', 'uiDown' and 'uiConfirm' actions, mouse or touch. | | `rules` | object[] | | | Declarative event → action rules. | | `waves` | object[] | | | Arcade waves: timed groups entering from above the view. Emits 'wave:' and 'waves:done'. | | `properties` | object | | | Free-form key/value properties. Values are primitives only. | ## Document level A tile-based level. Global tile id (gid) 0 means empty; tileset firstGid offsets map gids to tiles (Tiled-compatible). | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `id` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `name` | string \| object | | | Plain string, or a map of locale → string. | | `orientation` | "orthogonal" | | `"orthogonal"` | | | `tileWidth` | integer | yes | | | | `tileHeight` | integer | yes | | | | `width` | integer | yes | | Width in tiles. | | `height` | integer | yes | | Height in tiles. | | `backgroundColor` | string | | | CSS hex colour. | | `tilesets` | object[] | yes | | | | `layers` | object \| object[] | yes | | | | `properties` | object | | | Free-form key/value properties. Values are primitives only. | ## Document prefab Entity template: a named bag of component values. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `id` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `extends` | string | | | Parent prefab; its components are merged under these. | | `components` | object | yes | | Component name → component data, e.g. { "Transform": { "x": 0, "y": 0 } }. | | `tags` | string[] | | | | ## Document content-pack Community expansion: data and media only, never code. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `id` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `version` | string | yes | | Semantic version, e.g. 1.4.0. | | `title` | string \| object | yes | | Plain string, or a map of locale → string. | | `description` | string \| object | | | Plain string, or a map of locale → string. | | `authors` | object[] | yes | | | | `license` | string | | | SPDX license identifier or expression, or 'proprietary'. | | `target` | object | yes | | | | `dependencies` | object[] | | | | | `contents` | object | yes | | | | `pricing` | object \| object | | | Reserved for the monetization phase; only 'free' is accepted until then. | ## Document synth ### synth kind "sound" | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | | | Major.minor version of the document schema. Loaders migrate older versions. | | `kind` | "sound" | yes | | | | `wave` | "square" \| "triangle" \| "sine" \| "saw" \| "noise" | | `"square"` | | | `duty` | number | | `0.5` | Square wave pulse width. | | `volume` | number | | `0.5` | | | `attack` | number | | `0.005` | Seconds to reach full volume. | | `decayPower` | number | | `1` | Fade-out curve after the attack: 1 = linear, 2+ = quick fall-off (plucky). | | `lowpass` | number | | | One-pole low-pass cutoff in Hz (softens noise). | | `duration` | number | yes | | | | `frequency` | number | yes | | Start pitch in Hz. | | `slideTo` | number | | | End pitch in Hz (exponential slide). | | `arpeggio` | object | | | Steps the pitch through these intervals (e.g. [0, 4, 7, 12] for a major arpeggio). | | `vibrato` | object | | | Pitch wobble: rate in Hz, depth in semitones. | ### synth kind "song" | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | | | Major.minor version of the document schema. Loaders migrate older versions. | | `kind` | "song" | yes | | | | `bpm` | number | yes | | | | `stepsPerBeat` | integer | | `4` | | | `volume` | number | | `0.6` | | | `tracks` | object[] | yes | | | ## Document world A large map made of chunk levels on a grid, streamed around the camera. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `id` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `tileWidth` | integer | yes | | | | `tileHeight` | integer | yes | | | | `chunkWidth` | integer | yes | | Width of every chunk level, in tiles. | | `chunkHeight` | integer | yes | | Height of every chunk level, in tiles. | | `streamRadius` | integer | | `1` | Chunks loaded around the camera in each direction (1 = a 3×3 block). | | `backgroundColor` | string | | | CSS hex colour. | | `chunks` | object[] | yes | | | ## Document dialogue A conversation: nodes of lines with optional choices, conditions and actions. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `id` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `start` | string | yes | | First node. | | `speakers` | object | | | | | `nodes` | object | yes | | | ## Document quest A quest: steps completed in order by events or conditions. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `id` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `title` | string \| object | yes | | Plain string, or a map of locale → string. | | `description` | string \| object | | | Plain string, or a map of locale → string. | | `steps` | object[] | yes | | | | `rewards` | object \| object \| object \| object \| object \| object \| object \| object \| | | | Actions when the last step completes. | ## Document brain How an NPC behaves: a state machine (states may run behaviour trees) or a behaviour tree. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `id` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `speed` | number | | `40` | Default walking speed, pixels per second. | | `machine` | object | | | A state machine. | | `tree` | any | | | A behaviour tree, ticked every step (when there is no machine). | ## Document locale Strings of one language (game/locales/.json). | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `language` | string | yes | | | | `name` | string | | | The language's own name, e.g. 'Français'. | | `strings` | object | yes | | Text by key; games write '@key' in any text field. | ## Document level3d A 3D level: primitive pieces (boxes, ramps, cylinders, spheres), objects (prefabs, triggers, points), lights and sky. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `schemaVersion` | string | yes | | Major.minor version of the document schema. Loaders migrate older versions. | | `id` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `name` | string | | | | | `sky` | object | | | | | `lights` | object[] | | | Default: a soft ambient light and a sun with shadows. | | `killY` | number | | | Entities below this height emit ':fell' (falling off the world). | | `pieces` | object[] | | `[]` | | | `objects` | object \| object \| object[] | | `[]` | | ## Rule and menu actions Each action is an object with `action` plus the fields below. Every action also accepts `delayMs` (milliseconds, counted in fixed steps). ## Action restartScene ## Action goToScene Leaves every scene on the stack (gameplay and overlays) and starts another. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `scene` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `transition` | "none" \| "fade" | | | Default 'fade'. | ## Action pushScene Opens a scene on top (pause menu); the one below freezes. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `scene` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | ## Action popScene Closes the top scene (resume). ## Action playSound | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `sound` | string | yes | | Asset key used at runtime, e.g. 'player.sheet'. | | `volume` | number | | | | ## Action playMusic | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `track` | string | yes | | Asset key used at runtime, e.g. 'player.sheet'. | | `crossfadeMs` | integer | | | | ## Action stopMusic | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `fadeMs` | integer | | | | ## Action addToCounter | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `counter` | string | yes | | | | `amount` | number | | | | | `from` | string | | | Add a bound value instead of 'amount', e.g. 'game.coins'. | | `scope` | "scene" \| "session" | | `"scene"` | 'scene' state resets with the scene; 'session' state lasts until the game is closed (and is saved). | ## Action setCounter | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `counter` | string | yes | | | | `value` | number | yes | | | | `scope` | "scene" \| "session" | | `"scene"` | 'scene' state resets with the scene; 'session' state lasts until the game is closed (and is saved). | ## Action cameraShake | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `intensity` | number | | | | | `durationMs` | integer | | | | ## Action emit | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `event` | string | yes | | | ## Action saveGame Saves session state to the autosave slot. ## Action respawn Revives an entity at the last checkpoint (or where it started) with full health. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `entity` | string | yes | | | ## Action setComponent Changes component fields of a named entity, e.g. disable a controller. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `entity` | string | yes | | | | `component` | string | yes | | | | `values` | object | yes | | | ## Action banner Shows a centered message for a while. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `text` | string \| object | yes | | May include {bindings}, e.g. "Coins {game.coins}". | | `durationMs` | integer | | `2000` | | | `size` | integer | | | | ## Action toggleSetting | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `setting` | "sound" \| "music" | yes | | | ## Action recordBest Keeps the player's best value (saved; cloud saves on the platform). | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `value` | string | yes | | Value path to keep the best of, e.g. 'session.score'. | | `key` | string | yes | | Saved as the player's best; bind it as 'best.'. | | `lower` | boolean | | `false` | Lower is better (times). | ## Action submitScore Sends a score to the platform's leaderboard (signed-in players; checked by replaying the run). | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `board` | string | yes | | A leaderboard key from game.json 'leaderboards'. | | `value` | string | yes | | Value path, e.g. 'session.score'. | ## Action unlockAchievement Unlocks an achievement from game.json 'achievements' (once per player). | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `achievement` | string | yes | | | ## Action startDialogue Opens a dialogue (pauses play). | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `dialogue` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | ## Action giveItem | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `item` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `count` | integer | | `1` | | ## Action takeItem | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `item` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | | `count` | integer | | `1` | | ## Action useItem Runs the item's 'use' actions. | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `item` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | ## Action startQuest | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `quest` | string | yes | | Stable identifier: lowercase letters, digits, '-', '_' or '.', 1–64 chars. | ## Action setLanguage | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `language` | string | yes | | A language code, or 'next' to cycle. | ## API @ludrel/audio - `Audio` (const) — Resource key for the game's audio engine. - `AudioEngine` (class) — Web Audio mixer: sound effects and music on volume buses, music crossfades, and the browser "unlock on first gesture" dance. Without an `AudioContext` (headless, tests) it stays silent but keeps the same API, so game code never needs to check. - `audioPlugin` (function) — Installs audio: an {@link AudioEngine} as the {@link Audio} resource, asset loaders for `audio` (decodes files) and `synth` (renders sound/song data, see `renderSound`), and unlock-on-first-gesture. - `BusName` (type) — Mixer buses. Every sound plays on one; all feed `master`. - `noteFrequency` (function) — Frequency in Hz of a note name such as `A4` (440 Hz), `C#3` or `Eb5`. - `PlayOptions` (interface) - `renderSong` (function) — Renders a song to one seamless loop of mono samples at {@link SYNTH_SAMPLE_RATE}. Notes ringing past the end wrap to the start, so `loop: true` playback has no gap. - `renderSound` (function) — Renders a sound effect to mono samples at {@link SYNTH_SAMPLE_RATE}. - `SoundHandle` (interface) — Controls a playing sound. - `SYNTH_SAMPLE_RATE` (const) — Sample rate used for synthesized audio (chip sounds need no more). - `SynthSongData` (interface) - `SynthSoundData` (interface) — Tone settings shared by sounds and song instruments (defaults applied by the schema). - `SynthTone` (interface) — Tone settings shared by sounds and song instruments (defaults applied by the schema). - `SynthWave` (type) — A tiny chip synthesizer: renders sound effects and songs described as data (see the `synth` schema in `@ludrel/schema`) into sample buffers. Pure functions, deterministic output (seeded noise), so renders can be tested and cached. ## API @ludrel/camera - `Camera` (const) — Resource key for the scene's main camera. - `Camera2D` (class) — A 2D camera with follow, dead zone, smoothing, look-ahead, bounds and trauma-based shake. Stored as the {@link Camera} resource; {@link cameraSystem} updates it every frame. - `Camera2DOptions` (interface) - `cameraSystem` (function) — Render-phase system that updates the {@link Camera} resource (uses interpolated positions for smoothness). - `CameraView` (interface) — What the renderer needs: top-left of the visible world rectangle and zoom. ## API @ludrel/core - `addComponentsFromData` (function) — Adds components to an entity from JSON-style data (`{ "Transform": { "x": 1 } }`), looking types up by name and validating against each component's schema when it has one. Unknown components and invalid data are reported, not thrown, so a bad level shows an error instead of crashing the game. - `approach` (function) — Moves `current` toward `target` by at most `maxDelta`. - `AssetDescriptor` (interface) — Describes one asset to load. Matches the manifest's asset entries; extra fields are passed to loaders. - `AssetLoader` (interface) — Loads one asset type. Registered by packages: render-2d (images, sprite sheets), audio (sounds)... - `AssetManager` (class) — Loads, caches and reference-counts assets. Assets are grouped into bundles (from the manifest) and loaded per scene; a key is fetched once no matter how many bundles use it. - `Assets` (const) — Resource: the game's {@link AssetManager}. - `captureTransforms` (function) — Records every Transform before a fixed step so rendering can interpolate. Called by the game loop. - `clamp` (function) - `ComponentDataIssue` (interface) — Issue found while creating components from JSON data. - `componentNames` (function) — Names of all registered component types. - `ComponentType` (interface) — A component type: a name, default values and an optional schema for validating JSON data. - `ComponentValue` (type) — Value type of a component type. - `createGame` (function) — Creates a {@link Game}. - `damp` (function) — Frame-rate independent smoothing: like `lerp(a, b, t)` per frame at 60 fps, for any `dt` (seconds). - `defineComponent` (function) — Defines a component. Component data must be plain, JSON-serializable data so it can be saved, inspected, edited by an AI and loaded from scene/level files by name. - `defineResource` (function) - `defineSystem` (function) — Identity helper that gives systems full type inference and a documented shape. - `Entity` (type) — An entity is a numeric id. Ids are never reused within a world. - `EventBus` (class) — Typed publish/subscribe event bus. Declare known events in the type parameter; any other string event is still allowed with an `unknown` payload (scene rules use free-form names like `trigger:goal`). - `FixedStepLoop` (class) — Fixed-timestep loop with render interpolation ("fix your timestep"). Simulation is deterministic: it depends only on the number of ticks, never on the display refresh rate. - `FrameTime` (interface) — Timing passed to systems. - `Game` (class) — The game: owns the loop, the scene stack, game-wide resources, events, RNG, assets and saves. - `GameErrorEvent` (interface) — Error raised by a system or plugin; the system is disabled and the error reported. - `GameEvents` (interface) — Events the game itself emits on {@link Game.events}. - `GameOptions` (interface) - `GameResource` (const) — Resource: the running {@link Game} (scene changes, plugins) — available in every world. - `GameRng` (const) — Resource: the game's seeded {@link Rng}. Use it (or a fork) for all gameplay randomness. - `getComponentType` (function) — Looks up a component type by name (used when loading JSON documents). - `interpolatedTransform` (function) — Position between the previous and current fixed step, for smooth rendering at any refresh rate. `alpha` comes from the loop (0 = previous step, 1 = current step). - `lerp` (function) - `Listener` (type) — Listener for an event payload. - `LoaderContext` (interface) — Context passed to loaders. - `LocalSaveStorage` (class) — Stores saves in `localStorage` under a per-game prefix. - `LoopCallbacks` (interface) — Callbacks driven by the loop. - `LoopOptions` (interface) — Options for {@link FixedStepLoop}. - `LoopStats` (interface) — Rolling performance numbers, shown by the debug overlay. - `MemorySaveStorage` (class) — Keeps saves in memory (tests, headless runs). - `Name` (const) — Component storing an entity's unique name within a world (scene/level ids). - `Plugin` (interface) — A plugin hooks a subsystem (input, audio, renderer, devtools...) into the game loop. - `previousPosition` (function) — Position at the start of the current fixed step (before this step's movement). - `ProgressCallback` (type) — Progress callback: `loaded` of `total` assets in the batch. - `Query` (class) — A live set of entities matching a filter; kept up to date as components change. - `QueryFilter` (interface) — Filter for {@link World.query}. - `ResourceKey` (interface) — Typed key for a world resource (a singleton service or state, e.g. input or the camera). - `Rng` (class) — Deterministic seeded random number generator (sfc32). The same seed always yields the same sequence, which makes replays, headless tests and procedural generation reproducible. Never use `Math.random` in gameplay code. - `RngState` (type) — Serializable generator state, for saves and replays. - `SaveEnvelope` (interface) — On-disk envelope of a save. - `SaveManager` (class) — Versioned save/load. When the save format changes, bump `version` and provide `migrate` so old saves still load. - `SaveStorage` (interface) — Where saves are stored. Local implementations now; a platform (cloud) implementation in Phase 3. - `Scene` (class) — A scene: one world plus the systems that run on it. Scenes form a stack (gameplay, pause menu on top...). Only the top scene updates unless `updateWhenCovered` is set; covered scenes still render unless `renderWhenCovered` is false. - `SceneDefinition` (interface) — Describes how to build a scene. `setup` adds entities and systems; it may be async (to load assets). - `snapTransform` (function) — Call after teleporting an entity so rendering doesn't interpolate across the jump. - `StandardSchema` (interface) — Minimal Standard Schema (https://standardschema.dev) interface, so Zod/Valibot schemas plug in without a runtime dependency. - `System` (interface) — A system: logic that runs over the world every step or frame. - `SystemPhase` (type) — When a system runs: - `fixed`: every simulation step with constant `dt` — gameplay, physics, AI. Deterministic. - `update`: once per displayed frame with variable `dt` — cosmetic animation, UI. - `render`: once per frame after `update`, with interpolation `alpha` — drawing, camera. - `Tags` (const) — Component storing free-form tags such as `player` or `enemy`. - `Transform` (const) — Position (pixels, world space), rotation (radians) and scale of an entity. Physics, rendering and cameras all read this component. - `Transform3D` (const) — Position (metres; y is up), rotation (degrees around x, y, z) and scale of a 3D entity. 3D physics, rendering and cameras read it. - `Vec2` (interface) — A 2D vector. - `World` (class) — Holds entities, their components and resources. Each scene owns one world. - `WorldSnapshot` (interface) — A snapshot of all serializable component data, for saves, the inspector and AI tools. ## API @ludrel/devtools - `connectHotReload` (function) — Applies data hot-reload events from `platformDataHotReload` (in `@ludrel/devtools/vite`) to a running game. - `debugOverlay` (function) — Developer overlay: FPS and timing, scene stack, entity counts, hitboxes (colliders, solid and slope tiles), an entity inspector with live JSON editing, pause/step, and an error panel that also shows rejected hot reloads. - `DebugOverlayOptions` (interface) - `HotContext` (interface) — Minimal shape of Vite's `import.meta.hot`. ## API @ludrel/framework - `ActionRunner` (class) — Runs declarative actions (scene rules, menu items) for one scene. Delays are counted in fixed ticks so runs stay deterministic. Call {@link ActionRunner.tick} once per fixed step. - `announceQuest` (function) — Runs a quest change's actions, emits `quest::` and shows a banner. - `applyPacks` (function) — Merges content packs into a game's files (as given to `startGame({ files })`), with namespacing: every id a pack defines (scenes, levels, prefabs, items, asset keys) becomes `:`, and the pack's references resolve to its own ids first, otherwise to the base game's, so packs use `player`, `coin` or `title` as they are. Packs never replace base content. String values inside component data that equal an id the pack defines are rewritten too. - `arcadeSystem` (function) — Movement patterns, shooting, bullets hitting things, score for defeated enemies, cleanup of what leaves the view, and drifting backgrounds. One system so the order is fixed: move, shoot, hit, score, clean up. - `BehaviorContext` (interface) — Context given to behavior factories. - `BehaviorFactory` (type) — Creates a system for a scene. Behaviors are referenced by name from scene `systems` lists. - `Brain` (const) — An NPC driven by a brain document (`game/ai/.json`): a state machine or a behaviour tree. - `builtinBehaviors` (const) — Built-in behaviors available to every game by name. Games add their own via `startGame({ behaviors })`. - `burst` (function) — Spawns a short particle burst (collect sparkles, dust). - `captureFrame` (function) — A picture of the game's next drawn frame, as a JPEG data URL: every canvas under `root` composed into one image, scaled to fit 1280×720. Used by the platform's thumbnail capture (the play bridge's `capture`, ADR 0029). Rejects when the game draws no frame in time (for example, while it is stopped). - `CaptureOptions` (interface) — Where the game draws, and how to make the picture (tests pass fakes). - `Checkpoint` (const) — Touching it makes it the respawn point (emits `checkpoint:reached` once) and plays its `activeAnimation`. - `ChunkMember` (const) — Marks entities that belong to a loaded chunk (its tile views and the objects it spawned). Runtime-only. - `conditionContext` (function) — Conditions as seen from a scene (and optionally from one entity, for `near`). - `ContactDamage` (const) — Hurts entities with `targetTag` on contact. If `stompable`, landing on top defeats this entity instead (emits `enemy:stomped`) and bounces the stomper. - `CurrentScene` (const) — Resource: the scene that owns a world (lets systems read and write `scene.state`). - `defaultTouchLayout` (function) — The touch layout a game gets without a `touch` section: a joystick for two move axes (`moveX` + `moveY`), ◀ ▶ for one (`moveX`), buttons for `jump`, `fire`, `interact`, `action`, `attack`, `dash` and `bomb` when the game has them, and the pause button. - `defeat` (function) — Knocks out an enemy: no more contact, flips over, falls and despawns. Emits `enemy:defeated`. - `DIALOGUE_SCENE` (const) — The built-in overlay scene that shows dialogue (pushed by the `startDialogue` action). - `dialogueBoxSystem` (function) — Draws the open dialogue at the bottom of the screen; `uiConfirm` continues or picks, `uiUp`/`uiDown` choose. - `DialogueRunner` (class) — Steps through a dialogue document. `start` and `choose`/`advance` return the actions to run (node `do`, choice `do`); the view is undefined once the dialogue has ended. - `dialogueSceneDoc` (const) — Its (generated) scene document. - `DocumentValidator` (type) — Validates (and normalizes: migrations, defaults) one document. `schemaValidator` from `@ludrel/framework/validate` is the standard one; it pulls in Zod, so production builds leave it out and load documents that were validated and normalized at build time (ADR 0016). - `driftSystem` (function) — Moves parallax layers by themselves (scene `background.parallax[].drift`, px per second): starfields, clouds. - `enemyMovementSystem` (function) — Patrol and Hover movement (before physics). - `fadePlugin` (function) — Installs screen fades (used by scene transitions). Needs the render plugin installed first. - `FadePlugin` (interface) — Screen fades drawn on an overlay layer above every scene. - `fetchPacks` (function) — Downloads approved packs from the play server: `/pack.json` and the JSON files it lists. Packs that fail to load are skipped (reported through `onError`), so the game still starts. - `formatProjectIssues` (function) - `formatValue` (function) — Formats a bound value for display (`undefined` → empty, `true` → `on`). - `GameProject` (interface) — A game's documents: the manifest plus scenes, levels and prefabs, keyed by path relative to the game root. - `GameRuntime` (interface) — A running game plus the operations tools need (scene switching, hot reload). - `GameSettings` (interface) — Player settings, saved between visits. - `GoToSceneOptions` (interface) — Options for {@link RuntimeServices.goToScene}. - `Health` (const) — Hit points with a short invulnerability after each hit. At 0 the entity dies: `:died` is emitted and a controlled entity (PlatformerController) pops up and falls off screen until `respawn` revives it. - `Hover` (const) — Floats around its starting point (flying enemies, moving pickups). Moves the Transform; no Body needed. - `hudSystem` (function) - `hurt` (function) — Damages an entity with {@link Health}, unless it is dead or invulnerable. Knocks it away from `fromX`. Emits `:hurt`, and `:died` (via {@link kill}) at 0 hp. - `InputRecorder` (class) — Records input changes per scene and tick (installed by `startGame`). - `Interactable` (const) — Something the player can talk to or use: pressing the `interact` action nearby starts `dialogue` (if any) and emits `talked:` and `event` (if any). Shows `prompt` above it while the player is in range. - `interactionSystem` (function) — Contact damage and stomping, pickups and checkpoints (after physics, using its overlaps). - `interactSystem` (function) — Pressing `interact` near an {@link Interactable} starts its dialogue and emits `talked:`. - `interpolate` (function) — Replaces `{path}` placeholders with bound values. - `KeepInView` (const) — Keeps the entity inside the view, `margin` pixels from the edges (the player's ship). - `kill` (function) — Kills an entity with Health: emits `:died`; a controlled entity pops up and falls off screen. - `LevelMap` (const) — Resource: the tilemap of the scene's level (if it has one). - `Lifetime` (const) — Despawns the entity after `seconds` (effects, banners, defeated enemies). - `LoadedPack` (interface) — A content pack ready to merge: its `pack.json` document and its JSON files by path relative to the pack root. - `loadProject` (function) — Builds and validates a project from raw JSON files (e.g. Vite's `import.meta.glob(..., { eager: true })` or files read from disk). Checks every document and every cross-reference: scene → level, prefab ids, entry scene, `extends` chains, follow-camera targets. - `LoadProjectOptions` (interface) — Options for {@link loadProject}. - `LOBBY_SCENE` (const) — The built-in overlay scene showing the lobby (pushed when the player joins a room). - `lobbySceneDoc` (const) - `lobbySystem` (function) — The lobby screen: who is in the room, and the host starts the match with confirm (or a tap). - `localized` (function) — Picks a localized string (`{ en: '...', fr: '...' }`) or returns a plain string. - `measureText` (function) — Pixel size of a string in the theme font at `size` (bitmap fonts scale by whole numbers). - `menuSystem` (function) — A vertical menu from a scene document's `menu`: navigate with `uiUp`/`uiDown` (keys, d-pad, stick), confirm with `uiConfirm`, point and click with `uiClick` (mouse/touch), and `uiBack` runs `menu.back`. Item labels may contain `{bindings}` (e.g. `Sound: {settings.sound}`). - `Mover` (const) — Moves an entity by itself (Transform, no Body needed): `line` at (vx, vy); `sine` and `zigzag` sway sideways by `amplitude` every `period` seconds while moving at (vx, vy); `dive` drifts for `delay` seconds, then speeds toward where the player was. - `normalizeFiles` (function) — Converts a Vite glob result (`{ '../game/scenes/a.json': {...} }`) into paths relative to the game root. - `normalizePath` (function) — Normalizes a file path to be relative to the game root (`./game/scenes/a.json` → `scenes/a.json`). - `npcSystem` (function) — Runs {@link Brain} entities: their brain decides, and they walk with A* around walls. - `NullInputSource` (class) — Input source that reports nothing (headless runs drive input with `InputManager.setOverride`). - `ObjectSpawner` (type) — Spawns a level object at a world position (the scene loader's spawner). - `Offscreen` (const) — Removes the entity once it is `margin` pixels outside the view (bullets, enemies that flew past). - `OnlinePlugin` (class) — Drives online matches: updates every player's inputs each fixed step (installed by `startGame`). - `OnlineState` (interface) — Online state, for the lobby and HUD bindings (`online.players`, `online.you`). - `OpenDialogue` (interface) — An open dialogue: the runner and where its actions run (the scene that started it). - `orientationHint` (function) — Shows a "rotate your device" hint on touch screens held the other way than the game's `display.orientation` (`landscape` or `portrait`). Installed by `startGame` for games that set an orientation. - `PACK_MENU_SCENE` (const) — The generated menu scene listing each enabled pack's start scenes. Open it with `pushScene`. - `PackIssue` (interface) — A problem found while merging a pack (the file is the pack-relative path). - `packScoped` (function) — The id a pack's own `id` becomes once merged: `:`. - `Patrol` (const) — Walks back and forth, turning at walls and (optionally) ledges. Needs a Body. - `Pickup` (const) — Collected when an entity with `targetTag` touches it: emits `pickup:` (count it with rules), heals by `heal`, bursts a few particles and disappears. The scene state gets `Total` (pickups of that kind at scene start), handy for "Coins 3/20". - `PlatformerAnimator` (const) — Picks the Sprite animation from the PlatformerController state and flips the sprite to face the movement. Values are animation names in the entity's sprite sheet. - `platformerController` (const) — Side-scroller movement for entities with {@link PlatformerController}, Body and Transform. Runs before physics. - `PlatformerController` (const) — Side-scroller controls: run with acceleration, variable-height jump, coyote time, jump buffering, optional multi-jump, and drop through one-way platforms with down + jump. Reads input actions by name. - `platformerHazards` (const) — Hazard tiles and falling out of the level for controlled entities. With {@link Health}, a hazard tile deals 1 damage and bounces the entity up, and falling out kills it (`:died`). Without Health, either emits `:died` once (e.g. `player:died`). - `PlatformHooks` (interface) — What the hosting platform does with scores and achievements (the play bridge in published games). - `PrefabSpawner` (type) — Spawner type used by the scene loader (prefab, position, extra components). - `Projectile` (const) — A bullet: hurts the first entity with Health and `targetTag` it touches, then disappears. - `ProjectIssue` (interface) — Validation problems in a project, grouped by file. - `ProjectValidationError` (class) — Thrown when a project has errors; `issues` lists every problem (formatted in `message`). - `questSystem` (function) — Feeds events and conditions to the quest log, runs quest actions and announces progress. - `readBinding` (function) — Reads a value path: - `game.coins`: the scene's state - `session.coins`: state that outlives scenes - `settings.sound`: a player setting (`on`/`off`) - `items.apple`: how many apples the player carries - `best.score`: the player's best for a key (`recordBest`) - `quest.cave`: `inactive`, `active` or `done`; `quest.cave.step`: the current step's id - `settings.language`: the player's language code - `player.Health.hp`: a field of a named entity's component - `replayRun` (function) — Replays a recording into a running game (normally headless, started with the recording's seed): before each fixed step, the inputs recorded for that scene and tick are applied. Stops when `until()` is true or the recording ends (plus `extraTicks`). Returns the ticks played. - `resolvePrefab` (function) — Resolves a prefab's components through its `extends` chain (parents first, children override per field). - `Respawn3D` (const) — Resource: respawns a named 3D entity at its checkpoint or start (set by 3D scenes; used by `respawn`). - `respawnPoint` (function) — Where `respawn` puts a named entity: the last checkpoint, else where it started. - `revive` (function) — Brings a dead entity back with full health at a position (collider bottom-center at `x`, `bottom`), with a moment of invulnerability. Emits `:respawned`. - `rulesSystem` (function) — Runs a scene document's `rules`: each rule listens for an event and runs actions. Besides world events (`player:died`, `trigger:goal`, `pickup:coin`...), rules can listen for `input:` (an input action was pressed) and `app:hidden` (the page lost focus, e.g. to auto-pause). - `RunRecording` (interface) — A run's input recording (ADR 0027): the seed and every change of an input action's value, by scene sequence number and fixed tick within that scene, so time spent loading between scenes cannot shift a replay. Pointer positions are kept while an action is held (menu taps). - `Runtime` (const) — Resource: runtime services (see {@link RuntimeServices}). - `RuntimeServices` (interface) - `sceneFromDocument` (function) — Builds a scene definition from the scene document `id` (read from the current project at setup time). - `SceneLoaderContext` (interface) — Internals the scene loader needs from the runtime. - `Score` (const) — Adds `points` to a counter (`session.score` by default) when the entity is defeated (its Health reaches 0). - `seatPlayers` (function) — At a match scene's start: names its players and removes the seats nobody took. - `Shooter` (const) — Fires `bullet` prefabs: automatically, or while `action` is held. `direction` is `up`, `down` or `player` (aimed); `count` bullets fan out over `spread` degrees. - `spawnPrefab` (function) — Spawns an entity from a prefab with optional per-instance overrides. Problems (unknown components, invalid values) are reported through `onIssue` instead of throwing. - `splitBundledPacks` (function) — Takes packs bundled with a game out of its files: each `packs//pack.json` and the files next to it become a {@link LoadedPack} (editor previews of a pack bundle it this way). The documents must already be normalized. - `startGame` (function) — Starts a data-driven game: validates every document, installs input, audio and rendering, registers asset bundles and enters the manifest's entry scene. - `StartGameOptions` (interface) - `stateHash` (function) — A state hash of a world: gameplay components only (transforms rounded to avoid printing noise). - `statusSystem` (function) — Invulnerability timers and blinking, {@link Lifetime} despawns, and {@link PlatformerAnimator}. - `streamFocus` (function) — Where streaming centres: the named entity (camera target), else the camera's view centre. - `teleport` (function) — Teleports an entity and resets its velocity (no interpolation streak). - `textIn` (function) — Text in the player's language for a scene: `@key` string-table entries and `{ en, fr }` maps (ADR 0024). - `TopDownAnimator` (const) — Picks the sprite animation for top-down characters (players and NPCs): `-` while moving, else `-` (facing is `down`, `up`, `left` or `right`). With `directional: false` it plays `` or `` and flips the sprite to face left. - `topDownController` (const) — Behavior `topDownController`: moves {@link TopDownController} entities from input and animates them. - `TopDownController` (const) — Eight-way movement from two axis actions (top-down games). Faces the way it last moved. - `touchControls` (function) — On-screen controls for touch screens, from the game's touch layout (ADR 0025): a virtual joystick (floating or fixed) or ◀ ▶ buttons for movement, action buttons and a pause button. They write into the input system like a gamepad, so games need no code for them. Shown only on touch screens (or with `?touch`); hidden while `active()` is false. - `TouchControlsOptions` (interface) - `TouchLayout` (type) — A touch layout: the manifest's `touch` section, filled in (see {@link defaultTouchLayout}). - `TouchLayoutResource` (const) — Resource: the game's touch layout (set by `startGame` from the manifest). - `Trigger` (const) — A zone that emits `trigger:` on the world's event bus when a matching entity enters it. Created from level `trigger` objects. - `triggerSystem` (function) — Turns physics overlaps with {@link Trigger} entities into `trigger:` events. - `UiTheme` (interface) — Game-wide text and menu look (from the manifest's `ui`, with defaults). - `ViewSize` (interface) — The view size (live: it changes in the `expand` scale mode). - `wavesSystem` (function) — Runs a scene's `waves`: at `at` seconds, spawns `count` of `prefab` every `every` seconds, entering from above the view at `x` (fractions of the view width) in a `line`, `column`, `v` or `random` formation. Emits `wave:` when a wave starts and `waves:done` once every wave has spawned and none of their entities is left. - `WorldStream` (const) — Resource: the streamed world of the scene (scenes with `world` instead of `level`). - `worldStreamSystem` (function) — Keeps the chunks around the camera's target (or the camera) loaded: adds their tile views and spawns their objects when they load, removes them when they unload. Objects that were removed while their chunk was loaded (collected, defeated) stay gone for the rest of the scene. Runs first in the fixed step, so physics sees the chunks the player is in. - `wrapText` (function) — Splits text into lines of at most `max` characters (on spaces where possible). ## API @ludrel/input - `ActionDefinition` (interface) — An action definition from the game manifest's `input.actions`. - `BrowserInputOptions` (interface) — Options for the browser input source. - `BrowserInputSource` (class) — Reads keyboard, mouse and the Gamepad API in the browser. - `Input` (const) — Resource key for the game's input manager. - `inputFor` (function) — The inputs an entity listens to: its online player's (when it has a {@link NetPlayer} and a match is on), otherwise the local {@link Input}. - `InputManager` (class) — Turns raw keyboard/mouse/gamepad state into named actions from the manifest. Gameplay code reads actions only, so players can remap controls and AI-generated code never hard-codes keys. - `inputPlugin` (function) — Installs input: creates an {@link InputManager}, stores it as the {@link Input} resource and evaluates actions before every fixed step. - `InputSource` (interface) — Raw device state. Implemented for the browser below; tests can supply their own. - `NetPlayer` (const) — Marks an entity as an online player's: its controls read that player's inputs (ADR 0027). - `PAD_AXES` (const) — Standard Gamepad API axis indices by name. - `PAD_BUTTONS` (const) — Standard Gamepad API button indices by name. - `parseBinding` (function) — Parses and validates a binding string; throws with a helpful message if invalid. - `PlayerInputs` (const) — Resource: one input manager per player of an online match (driven by the server's frames). ## API @ludrel/physics-arcade - `ArcadePhysics` (const) — Resource key for the scene's physics world. - `ArcadePhysicsOptions` (interface) - `arcadePhysicsSystem` (function) — Fixed-step system that runs arcade physics on the scene's {@link ArcadePhysics} resource. - `ArcadePhysicsWorld` (class) — Deterministic arcade physics: AABB bodies against tiles (solid, one-way, slopes) and static colliders, plus overlap/trigger events, raycasts and box queries. Store it as the {@link ArcadePhysics} resource and add {@link arcadePhysicsSystem} to a scene. - `Body` (const) — A moving body. Velocity is in pixels per second; the physics system integrates it every fixed step and resolves collisions. Contact flags (`onFloor`...) are outputs, recomputed every step. - `BodyData` (type) - `Collider` (const) — Axis-aligned collision box relative to the entity's Transform. Without a Body it is static: `solid` statics block bodies like tiles, `oneWay` ones only from above, and `trigger` colliders only report overlaps. - `ColliderData` (type) - `OverlapEvent` (interface) — Overlap pair event payload: `physics:enter` / `physics:exit` on the world's event bus. - `RayHit` (interface) — Result of a raycast. - `slopeSurface` (function) — Surface height (offset from the tile's top, 0..th) of a slope at local x (0..tw). - `TileCollisionSource` (interface) — Anything that can answer "what collision is at this tile?" — e.g. `Tilemap` from `@ludrel/world`. ## API @ludrel/render-2d - `addTilemapViews` (function) — Spawns one entity per tile layer of a tilemap, drawn in order (z = layer index * 10 + baseZ). - `BackendInitOptions` (interface) - `BitmapFont` (interface) — Fixed-grid pixel font: glyphs laid out left-to-right, top-to-bottom in one image, in the order of `chars`. Loaded from manifest assets of type `font` (`frame` = glyph cell, `chars` = characters in order). - `BitmapTextNode` (interface) — Text drawn with a {@link BitmapFont}, scaled by a whole number so pixels stay crisp. - `browserImageDecoder` (const) — Browser decoder: `createImageBitmap` for raster images, an `` element for SVG. - `DebugDraw` (interface) — Debug drawing, cleared every frame (used by the debug overlay for hitboxes and rays). - `DecodedImage` (type) — Decoded image: a browser image source, or just a size (headless). - `FrameRect` (interface) — Pixel rectangle inside a texture. - `ImageDecoder` (type) — Turns fetched bytes into an image the backend can upload. - `LayerId` (type) - `layoutBitmapText` (function) — Glyph positions for bitmap text (unscaled pixels), shared by backends and tests. - `NodeId` (type) — The renderer-agnostic drawing interface. Game code never talks to it directly: ECS components (Sprite, Rect, TilemapView, Parallax, ParticleEmitter, Text) are turned into nodes by the render system. Implementations: {@link PixiBackend} (WebGL) and {@link StubBackend} (headless). - `NodeKind` (type) - `NodeProps` (type) - `Parallax` (const) — A repeating background image that scrolls at a fraction of the camera's speed. Needs no Transform. - `ParticleEmitter` (const) — Emits short-lived particles (dust, sparks, pickups). Purely visual; simulated per frame. - `ParticlesNode` (interface) — Particles simulated by the particle system, drawn as tinted textured or square quads. - `PixiBackend` (class) — WebGL backend built on PixiJS. This is the only file in the framework that imports PixiJS (ADR 0004). Our loop drives rendering: PixiJS's ticker is never used. - `readImageSize` (function) — Reads width/height from PNG or SVG bytes without decoding pixels (headless runs). - `Rect` (const) — A solid coloured rectangle — handy for prototypes, placeholder art and UI. - `RectNode` (interface) - `registerImageLoaders` (function) — Registers `image`, `tileset`, `spritesheet` and `font` (bitmap font) loaders that upload textures to the backend. - `RenderBackend` (interface) - `Renderer` (const) — Resource: the game's render backend. - `RenderLayer` (const) — Resource: the render layer assigned to a scene's world. - `renderPlugin` (function) - `RenderPluginOptions` (interface) - `renderSystem` (function) — Render-phase system that mirrors visual components into the render backend: creates, updates and destroys nodes, interpolates positions, applies the scene camera and simulates particles. - `sheetFrame` (function) — Frame rectangle for a sprite sheet frame index. - `sizeOnlyImageDecoder` (const) — Headless decoder returning sizes only. - `Space` (type) — `world` nodes move with the camera; `screen` nodes stay fixed (HUD); `background` is behind world (parallax). - `Sprite` (const) — Draws a texture (or one frame of a sprite sheet) at the entity's Transform. Use `anchorX/anchorY` 0.5 for sprites that flip, so they flip around their center. - `SpriteAnimation` (const) — Plays a named animation from the sprite sheet used by the entity's Sprite (animations are declared in the manifest's asset entry). Set `animation` to switch; time restarts automatically. - `spriteAnimationSystem` (function) — Fixed-step system advancing {@link SpriteAnimation}s (fixed so gameplay that waits for an animation stays deterministic). - `SpriteNode` (interface) - `SpriteSheet` (interface) — Sprite sheet metadata, stored in the asset manager under the sheet's key. - `StubBackend` (class) — Headless backend: draws nothing, records everything. Used by tests, the headless runner and the MCP `run_headless` tool, where it lets assertions like "the coin sprite is visible" work without a GPU. - `StubNode` (interface) — A node as recorded by the stub, with its last transform. - `Text` (const) — Text at the entity's Transform. `space: 'screen'` keeps it fixed on screen (HUD). If `font` is the key of a loaded bitmap font (asset type `font`), the text is drawn with it, scaled by the whole number nearest to `size / glyph height` (crisp pixel text); otherwise `font` is a CSS font family. - `TextNode` (interface) - `TileLayerSource` (interface) — What a tile layer needs to be drawn. `Tilemap` from `@ludrel/world` satisfies it. - `TilemapNode` (interface) — Tiles of one layer, drawn in chunks and culled to the view. - `TilemapView` (const) — Draws one tile layer of a tilemap (see `Tilemap` in `@ludrel/world`). Runtime-only. - `TilingNode` (interface) — A repeating image filling the screen, scrolled by the camera times a factor (parallax backgrounds). - `Viewport` (const) — Resource: the view size in game pixels, kept up to date when the `expand` scale mode resizes it. - `ViewTransform` (interface) ## API @ludrel/schema - `actionNameSchema` (const) - `AssetEntry` (type) - `assetEntrySchema` (const) - `assetKeySchema` (const) — Key used to look up a loaded asset, e.g. `player.sheet`. - `assetPathSchema` (const) — Relative path inside a game or pack: no URL scheme, no leading slash, no `..` segment. - `authorSchema` (const) - `BehaviorNode` (type) - `behaviorNodeSchema` (const) - `bindingSchema` (const) — Input binding string, e.g. `key:Space`, `key:ArrowLeft+ArrowRight` (axis from two keys), `mouse:0`, `pad:a`, `pad:leftStickX`, `pad:dpadX`, `pad:leftStickX-` (half axis as a button). - `Brain` (type) - `brainSchema` (const) - `CameraConfig` (type) - `cameraConfigSchema` (const) - `checkSynth` (function) — Semantic checks for synth files: valid step tokens, known pattern ids, matching track lengths. - `colorSchema` (const) — CSS hex colour: `#rgb`, `#rrggbb` or `#rrggbbaa`. - `ComponentsData` (type) - `componentsSchema` (const) — Component name → component data. Component data is validated in a second pass against the component's own registered schema (see `@ludrel/core` `defineComponent`). - `Condition` (type) — A condition on game state, used by rules, dialogue choices, quests and NPC brains. - `conditionSchema` (const) - `ContentPack` (type) - `ContentPackInput` (type) - `contentPackSchema` (const) - `CURRENT_SCHEMA_VERSION` (const) — Current schema version written into new documents (`major.minor`). - `decodeTileData` (function) — Expands a tile layer's `data` into one gid per cell (row-major). - `Dialogue` (type) - `dialogueSchema` (const) - `DocumentKind` (type) - `documentSchemas` (const) — Every document kind with a schema. - `DocumentTypes` (interface) - `encodeTileDataRle` (function) — Compresses gids into RLE pairs `[count, gid, ...]`. - `entityIdSchema` (const) — Entity id inside a scene or level (case-sensitive, used by cameras and rules). - `formatIssues` (function) — Formats issues one per line, for logs and AI tool output. - `GameManifest` (type) - `GameManifestInput` (type) - `gameManifestSchema` (const) - `idSchema` (const) — Stable identifier: lowercase letters, digits, `-`, `_` or `.`, 1–64 chars. `:` names an id from a content pack (the pack loader writes these; `:` is reserved for it). - `InputActionDefinition` (type) - `inputActionSchema` (const) - `Item` (type) - `itemSchema` (const) - `Level` (type) - `Level3d` (type) - `Level3dInput` (type) - `Level3dObject` (type) - `level3dObjectSchema` (const) - `level3dSchema` (const) - `LevelInput` (type) - `LevelObject` (type) - `levelObjectSchema` (const) - `levelSchema` (const) - `Locale` (type) - `localeSchema` (const) - `LocalizedText` (type) - `localizedTextSchema` (const) — Plain string, or a map of BCP 47 locale → string. - `migrateDocument` (function) — Brings a raw document up to {@link CURRENT_SCHEMA_VERSION} by applying migrations in order. Call before {@link validateDocument}. Returns the document unchanged when already current. - `Migration` (interface) — Upgrades a document from one schema version to the next. - `moneySchema` (const) — Money in minor units. Reserved until the monetization phase. - `NpcActivity` (type) - `npcActivitySchema` (const) — What an NPC does over time (a behaviour tree leaf, or a state's ongoing activity). - `ObjectLayer` (type) - `objectLayerSchema` (const) - `packMediaTypeSchema` (const) — Media types a pack may contain. Scripts, HTML and SVG are never allowed. - `patternSteps` (function) — Steps of a pattern string. - `permissionsSchema` (const) - `Piece` (type) - `pieceSchema` (const) - `plainIdSchema` (const) — An id without a pack prefix: what games and packs define themselves. - `pointObjectSchema` (const) - `Prefab` (type) - `PrefabInput` (type) - `prefabSchema` (const) - `Properties` (type) - `propertiesSchema` (const) — Free-form designer properties; primitive values only. - `Quest` (type) - `questSchema` (const) - `Rect` (type) - `rectSchema` (const) - `RuleAction` (type) - `ruleActionSchema` (const) — Declarative actions for scene rules and menu items. - `Scene` (type) - `SceneEntity` (type) - `sceneEntitySchema` (const) - `SceneInput` (type) - `sceneSchema` (const) - `schemaVersionSchema` (const) — `major.minor` version of the document schema. - `semverRangeSchema` (const) — npm-style semver range such as `^1.2.0`. - `semverSchema` (const) — Semantic version such as `1.4.0`. - `Size` (type) - `sizeSchema` (const) - `SongTrack` (type) - `songTrackSchema` (const) — One instrument line of a song. - `spawnObjectSchema` (const) - `spdxLicenseSchema` (const) - `Synth` (type) - `synthSchema` (const) — A synth asset file: a sound effect or a song. - `SynthSong` (type) - `synthSongSchema` (const) — A chiptune song as data: tracks of note patterns played in sequence, rendered to a looping buffer when loaded. - `SynthSound` (type) - `synthSoundSchema` (const) — A sound effect described by numbers instead of a recording (sfxr-style). Rendered to audio when loaded, so it weighs a few hundred bytes and AI tools can tweak it field by field. - `TileCollision` (type) - `tileCollisionSchema` (const) — Arcade collision shape of a tile. Slopes are named by rise direction and steepness. - `TileLayer` (type) - `tileLayerSchema` (const) - `Tileset` (type) - `tilesetSchema` (const) - `touchSchema` (const) — On-screen controls for touch screens; without this section they are made from the input actions. - `triggerObjectSchema` (const) - `validateDocument` (function) — Validates a document against its schema, then runs semantic checks that JSON Schema cannot express (tile data length, gid ranges, unique ids, references). Defaults are applied to the returned value. - `ValidationIssue` (interface) — One problem found in a document. `path` is a JSON pointer such as `/layers/0/data`. - `ValidationResult` (type) - `Vec2` (type) - `vec2Schema` (const) - `Vec3` (type) - `vec3Schema` (const) — A point or size in 3D (metres; y is up). - `Wave` (type) - `waveSchema` (const) — Oscillator shapes of the built-in chip synthesizer. - `WorldDocument` (type) - `WorldDocumentInput` (type) - `worldSchema` (const) ## API @ludrel/testing - `fileFetch` (const) — `fetch` that serves `file:` URLs from disk (asset loading in Node). - `HeadlessOptions` (interface) - `HeadlessResult` (interface) — Result of {@link runHeadless}. - `readGameFiles` (function) — Reads every `.json` file under a game directory into a path → JSON map. - `runHeadless` (function) — Runs a game headless for a number of ticks with scripted input and collects logs, errors and events. The same seed and script always give the same result — this is what tests and the MCP `run_headless` tool use. - `ScriptedInput` (interface) — One scripted input change: at `tick`, set `action` to `value` (null releases it). - `startHeadless` (function) — Starts a game without a browser (stub renderer, no audio, scripted input). Documents are validated with the schema validator unless `validate` is given. ## API @ludrel/world - `findPath` (function) — A* over a tile grid. Returns the tiles from `from` (excluded) to `to` (included), `[]` when already there, or `undefined` when there is no path within the budget. Deterministic: ties break the same way every time. - `LoadedChunk` (interface) — A loaded chunk of a world. - `PathGrid` (interface) — What {@link findPath} needs from a map (a `Tilemap` or a `WorldMap`). - `PathOptions` (interface) - `PlacedObject` (type) — A level object with the id of the layer it came from. - `TILE_COLLISIONS` (const) — Collision kinds by numeric code (index), for compact storage. - `TileChangeListener` (type) — Called when a tile changes (renderers redraw, physics caches update). - `TileLayerRuntime` (interface) — A tile layer at runtime: decoded gids in a typed array. - `Tilemap` (class) — Runtime tilemap built from a level document: tile lookups, combined collision grid, objects. Implements the collision source interface used by `@ludrel/physics-arcade`. - `WorldMap` (class) — A large map made of chunk levels on a grid (a `world` document), streamed around a point. Implements the tile collision source of `@ludrel/physics-arcade` in world tile coordinates: cells of chunks that are not loaded, or that have no level, count as solid so nothing walks or falls into them.