threedog 2.1.0 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/core/assets/Animator.js +1 -1
  3. package/core/audio/Audio.js +55 -8
  4. package/core/audio/audioReverb.js +2 -2
  5. package/core/base/Random.js +1 -1
  6. package/core/base/errorCodes.js +1 -1
  7. package/core/engine/Loading.js +3 -1
  8. package/core/engine/copies.js +1 -1
  9. package/core/engine/loop.js +1 -0
  10. package/core/input/Input.js +3 -3
  11. package/core/inspect/InspectPerf.js +1 -1
  12. package/core/inspect/describeText.js +3 -2
  13. package/core/inspect/metadata.generated.js +76 -24
  14. package/core/ops/holds.js +1 -1
  15. package/core/ops/sharedPoint.js +6 -1
  16. package/core/saves/Saves.js +24 -12
  17. package/core/saves/saveVersions.js +15 -0
  18. package/core/scene/Rays.js +1 -1
  19. package/core/scene/Views.js +20 -1
  20. package/core/scene/canvasBox.js +9 -0
  21. package/core/scene/sceneMethods.js +2 -1
  22. package/core/threads/Jobs.js +1 -1
  23. package/docs/AI.md +2 -2
  24. package/docs/API.md +2 -2
  25. package/docs/COMMANDS.md +4 -3
  26. package/docs/api/audio.md +1 -0
  27. package/docs/api/music.md +2 -2
  28. package/docs/api/saves.md +2 -1
  29. package/docs/api/settings.md +0 -2
  30. package/docs/recipes/02-npc.md +1 -1
  31. package/docs/recipes/03-items-pickups.md +4 -5
  32. package/docs/recipes/06-clock-events.md +2 -6
  33. package/docs/recipes/07-flow-scenes-pause.md +1 -1
  34. package/docs/recipes/08-weather-sky.md +2 -4
  35. package/docs/recipes/09-materials-lights-models.md +2 -2
  36. package/docs/recipes/14-custom-module.md +4 -1
  37. package/docs/recipes/15-perf.md +9 -5
  38. package/docs/recipes/16-dev-bridge.md +46 -36
  39. package/docs/recipes/20-content-actions-save.md +1 -0
  40. package/docs/recipes/21-camera.md +3 -4
  41. package/docs/recipes/26-ui-parts.md +3 -2
  42. package/docs/recipes/31-audio.md +19 -3
  43. package/docs/recipes/44-water-weather-hooks.md +1 -1
  44. package/docs/recipes/52-around-the-picture.md +1 -1
  45. package/docs/recipes/55-mods-time-wrap.md +5 -1
  46. package/docs/recipes/56-webgpu-tsl.md +5 -7
  47. package/docs/recipes/58-input.md +4 -1
  48. package/docs/recipes/60-judge-the-picture.md +5 -5
  49. package/llms.txt +1 -1
  50. package/modules/camera/common.js +1 -1
  51. package/modules/collision/Collision.js +1 -1
  52. package/modules/debug/DebugPanel.js +1 -1
  53. package/modules/gameplay/Dialogue.js +1 -1
  54. package/modules/gameplay/Interactions.js +1 -1
  55. package/modules/gameplay/Inventory.js +1 -1
  56. package/modules/gameplay/Quests.js +1 -1
  57. package/modules/hud/parts.js +1 -1
  58. package/modules/music/Music.js +35 -3
  59. package/modules/particles/Particles.js +1 -1
  60. package/modules/rigid/RigidBodies.js +1 -1
  61. package/modules/settings/Settings.js +22 -16
  62. package/modules/settings/sections.js +1 -1
  63. package/modules/swarm/Swarm.js +1 -1
  64. package/modules/timeline/Timeline.js +1 -1
  65. package/modules/timeline/letterbox.js +1 -1
  66. package/package.json +1 -1
  67. package/render/PostFX.js +7 -1
  68. package/render/fx/detail.tsl.js +3 -0
  69. package/types/core.d.ts +2 -0
  70. package/types/gameplay.d.ts +6 -7
  71. package/types/generated/core/audio/Audio.d.ts +10 -0
  72. package/types/generated/core/saves/Saves.d.ts +6 -1
  73. package/types/generated/modules/music/Music.d.ts +4 -13
  74. package/ui/Focus.js +1 -1
  75. package/ui/Parts.js +19 -7
  76. package/ui/defaults.js +1 -1
  77. package/ui/theme.js +14 -8
@@ -15,10 +15,8 @@ What this machine can carry: `threedog stress` (COMMANDS.md) prints where 16.7 /
15
15
  (`✗` with the next call; your `engine.budget` limits, else a desktop 60 fps reference, not enforced). Plain three.js: `renderer.info`. Textures: `engine.inspect.materials()`.
16
16
  - **Which materials cost**: `engine.debug.view('shaderCost')` colors materials green -> red by compiled program cost (gray = not compiled yet);
17
17
  `engine.debug.view('overdraw')` shows pixels drawn many times over. `'off'` restores. Real GPU timings: `threedog capture` (Spector.js) or the browser's GPU profiler.
18
- - **Other view modes**: `debug.view('triggers')` shows hidden zones (`triggers({ debugColor, debugOpacity })` colors them); modules add their own (`engine.debug.defineView(name, { what, apply })`);
19
- `engine.debug.viewModes()` lists them.
20
- - **F3 panel** (`engine.debug.panel`; `debug()` module, dev builds, null without it; action `debugPanel`): frame rate, CPU ms, draw calls, triangles,
21
- chunks, vegetation instances, time of day; with a budget set, over-limit items and startup time.
18
+ - **F3 panel** (`engine.debug.panel`; `debug()` module, dev builds, null without it; action `debugPanel`).
19
+ - **Other view modes**: `debug.view('triggers')` shows hidden zones; modules add their own with `engine.debug.defineView(name, { what, apply })`.
22
20
  - **Text**: `engine.describe().perf` =
23
21
  `{ fps, cpuMs, cpuFrames, cpu, apply, drawCalls, triangles, pixelRatio, gpuMemory, budget, notice, startup, stream, batching, jobs, commits, chunks?, vegetation? }`
24
22
  (`cpuMs`: median of `cpuFrames` frames, as in `inspect.perf()` and F3; `cpu`: last frame by phase);
@@ -36,6 +34,12 @@ What this machine can carry: `threedog stress` (COMMANDS.md) prints where 16.7 /
36
34
  splits it into parts that add up to it: `script` (page open until `createEngine`), `construct`, `setup` (game code until `start()`), `init` (saves,
37
35
  renderer, module init), `preload`, `world` (nearby builds), `compile` (shaders + hidden warm-up frame), `draw`. `inspect.perf().text` prints the line.
38
36
 
37
+ ## 1b. Counts and `snap` do not change while the loop is halted (a stale frame)
38
+ A halted loop (pause, `threedog step`, a test) keeps the counts and picture of the last frame drawn; `engine.step(1 / 60)` draws a new one.
39
+
40
+ ## 1c. Paint a procedural texture (an async canvas texture helper) without blocking the main thread: slice it with `engine.jobs`
41
+ `engine.jobs.add(function* () { for (let y = 0; y < h; y++) { paintRow(y); yield; } })`: `yield` once per row; the queue packs as many steps into a frame as its time budget (`budgetMs`) allows, so no row count to guess.
42
+
39
43
  ## 2. Set a budget (so going over reports itself)
40
44
  Off by default and costs nothing. Only the categories given are checked; `gpuMemoryMB` is three's own byte count (WebGPU only, not driver VRAM):
41
45
  ```js
@@ -69,7 +73,7 @@ Browsers round time to 0.1 ms. `onFrame/onFixed` are not timed; to time one, mak
69
73
  |---|---|
70
74
  | Many draw calls | Use `vegetation` / InstancedMesh for repeated objects; install `hlod()` for a block of buildings; share geometry and materials between copies of a model (`assets.model` shares by default) |
71
75
  | Expensive shadows | `engine.shadows.budget(light, { every: 3 })` (update every 3 frames), reduce `light.shadow.mapSize` / the box's `extent`; filter `renderer.shadowMap.type`: Basic cheapest, PCF default, VSM softest and dearest (switching recompiles); vegetation `shadowRing` (default 1) is how many chunk rings cast (culled per camera: a shadow box or cascade draws only chunks inside it), `engine.vegetation.setShadowRing('tree', 0)` while playing; grass-scale species: `castShadow: false` (`content check` hints) |
72
- | Stutter while walking | Put generation work in `engine.jobs.add(function* () { ...; yield; })` or `engine.stream.add`; chunk upload budget `engine.terrain.applyBudgetMs` |
76
+ | Stutter while walking | Slice generation work with `engine.jobs` (1c) or put it in `engine.stream.add`; chunk upload budget `engine.terrain.applyBudgetMs` |
73
77
  | Slow start | Look at which is slowest in `engine.startup.modules`; `npm run bake` for large models; preload only the necessary assets |
74
78
  | Slow physics | Keep dynamic rigid bodies within a few hundred (the `rigidBodies` budget); `rigid({ terrainRing: 1 })` |
75
79
  | Too much loaded at once | Each `engine.stream` source loads its own surroundings: remove sources you no longer need, give a far camera `physics: false` and a `radius`, use `detail: 'simple'` for a distant view (recipe 18 section 10) |
@@ -3,7 +3,7 @@
3
3
  > **Covers:** driving the running game from the terminal: describe, step, press, state, scenarios, snapshots, MCP.
4
4
  > **Use when:** checking a change without a screenshot or a browser script.
5
5
  > **Shortest:** `threedog describe -w my-game`.
6
- > **Sections:** 1 Usage · 2 Notes · 2b A scripted playthrough · 3 Windows / PowerShell · 3b Speed, a session · 4 Let describe see · 5 Safety · 6 Reuse in scenario · 7 Describe snapshots instead · 8 Errors carry a · 9 Reusable scenarios · 10 MCP server Claude · 11 When something happens
6
+ > **Sections:** 1 Usage · 2 Notes · 2b A scripted playthrough · 3 Windows / PowerShell · 3b Speed, a session · 4 Let describe see · 5 Safety · 6 Reuse in scenario · 7 Describe snapshots instead · 8 Errors carry a · 9 Reusable scenarios · 10 MCP server Claude · 11 When something happens · 12 Expectations
7
7
 
8
8
  After changing code, ask the running game instead of writing a playwright script or taking a screenshot: look, advance time, press keys, change state. Output is a few English lines.
9
9
 
@@ -24,36 +24,44 @@ Every command and its options are in `../COMMANDS.md`. What each does to the gam
24
24
  |---|---|---|
25
25
  | `step`, `press`, `hold`, `skip`, and `scenario` / `verify`, which use them | `op`, `state` (only its `wait=` moves the clock), `js` | `describe`, `ops`, `inspect`, `pick`, `explain`, `errors`, `loading`, `snap`, `snap-describe` |
26
26
 
27
- - `describe` is one line: position, time and weather, nearby, quest. `describe player.position` or any dotted path of `engine.describe()` reads one item (`--max characters`). `describe --full` is the state as text in at most 30 lines (`engine.describeText()`: nearest things, the game's `describe.add` sections, one line per module, engine tables as one count line, how to expand); `--all` is large, prefer a path. In code: `engine.describe('picture')`, `describe({ only: ['picture', 'shared'] })`. `describe render` lists how the picture is set; it informs and never warns.
27
+ - `describe` is one line: position, time and weather, nearby, quest. `describe player.position` or any dotted path of `engine.describe()` reads one item (`--max characters`). `describe --full` is the state as text in at most 30 lines; `--all` is large, prefer a path. In code: `engine.describe('picture')`, `describe({ only: ['picture', 'shared'] })`.
28
28
  - `step 2` is deterministic; a real-time page is halted first.
29
29
  - `press interact` takes an action name or key (`KeyE`, `e`, `Escape`). **It advances game time**: 0.1 s held + one rendered frame of 1/60 s, about 0.117 s; shorten the hold with `--for 0.02` when timing matters.
30
30
  - `op shop.buy shop=trader item=medkit n=2` runs as source `bridge`. Values follow the op's `args` shape (`n=2` a number, `position=3,0,-2` an array). **Change state with this, not `js`**: `js` writes skip the op log.
31
31
  - `ops` lists every offer checked with `can`; `inspect [id | x,z]` adds what is around, with reasons (recipes/23-ops.md section 8); `explain op ...` / `explain quest ...` says why one cannot run or where a quest is stuck (`--full` adds the last attempt and events around it).
32
- - `state view=gate` or `state view=0,5,12,0,1,0,50` (a pose: position, target, fov) places the camera for the next `snap`.
33
- - `state time=18:30 weather=rain pos=40,-20` sets the scene like URL parameters (`engine.applyState`). A weather name must be in the game's table (`describe weather`; `weather({ types: presets.weather.temperate })`, which `--open-world` games start with): what could not be applied fails with the reason and exit 1.
34
- - `js "engine.calendar.timeOfDay"`: `engine` is available directly and `await` works inside; multi-line statements need their own `return` (`js "const p = engine.player.position; return p.x + p.z"`). Long scripts: `js --file script.js`.
35
32
  - `scenario barter` runs `tests/scenarios/barter.json` (recipes/23-ops.md section 7), prints failed checks and leaves the loop halted.
36
33
 
34
+ ## 1b. `state` from the CLI (`time=17:40 weather=rain`) and a multi-line `js` script
35
+ - `state view=gate` or `state view=0,5,12,0,1,0,50` (a pose: position, target, fov) places the camera for the next `snap`.
36
+ - `state time=18:30 weather=rain pos=40,-20` sets the scene like URL parameters (`engine.applyState`); `state` takes only key=value words (`time= weather= pos= wait= cutscene= save= state= view=`), not `--time`. A weather name must be in the game's table (`describe weather`; `weather({ types: presets.weather.temperate })`, which `--open-world` games start with): what could not be applied fails with the reason and exit 1.
37
+ - `js "engine.calendar.timeOfDay"`: `engine` is available directly and `await` works inside; it prints the value of one expression (a trailing `;` or `// comment` is fine); a multi-line script prints only what it returns, so it needs its own `return` (`js "const p = engine.player.position; return p.x + p.z"`). Long scripts: `js --file script.js`.
38
+
37
39
  ## 2. Notes
38
- - **Smallest scenario** (`tests/scenarios/coins.json` <!-- r18-ignore-line -->, then `threedog verify coins` or `scenario coins`; `verify` with no file says "Have: none"):
39
- `{ "name": "coins", "url": "/", "state": { "pos": "6,4" }, "steps": [ { "step": 1 }, { "expect": { "inventory.items.coin": 1 } } ] }`
40
- - **Position formats**: `pos=x,z` (state, shot, `applyState`) is two numbers on the ground plane, and the height is looked up; an op argument such as `position=3,0,-2` is `x,y,z`. Both are meters, north is -z. `describe` reports the player as `{ x, y, z }` (`describe player.position`).
41
- - **Teleport the player**: `threedog state "pos=40,-20"`, or `await engine.applyState({ pos: '40,-20' })` in a test or `js` (both wait for the ground to load). A bare
42
- `player.placeAt` outside an op prints the ops-guard warning. `step 1` after it collects `auto` pickups.
40
+ - **Position formats**: `pos=x,z` (state, shot, `applyState`) is two numbers on the ground plane, and the height is looked up; an op argument such as `position=3,0,-2` is `x,y,z`. Both are meters, north is -z.
41
+ - **Teleport the player** with `state "pos=40,-20"` or `await engine.applyState({ pos: '40,-20' })` (both wait for the ground); a bare `player.placeAt` outside an op prints the ops-guard warning. `step 1` after it collects `auto` pickups.
43
42
  - **Ops with a reach** (`interaction.use`, `pickup.take`) check the player's distance as a key press would, also from the bridge: put the player next
44
43
  to the thing first (`threedog state "pos=x,z"`), then `threedog op interaction.use id=gate`. A `tooFar` result carries `facts: { distance, radius, at }`.
45
44
  - **`shot` always starts a fresh game** (`?save=slot1` loads one); after playing use `snap name`. Every shot prints the picture numbers and hints (recipes/35 "Picture check after every shot").
46
45
  - **`step` / `press` halt the real page's loop**; resume with `threedog resume` when done (they halt as owner `threedog`, so nothing of the game's is touched). A headless page only advances on step anyway.
47
- - **Run state** is printed after `step` / `press` / `skip` / `resume` and by `threedog status`: `running`, `title-frozen` (title screen waiting for start), `halted` (loop stopped by the bridge, a test or a headless page), `frozen(by owners)` (every `freeze` owner, e.g. `ui-inventory` or `page`) or `loading`. The same object is `engine.runState` and `describe().time.run`: `{ state, owners, blockedBy }`, where `blockedBy` lists what keeps input from driving the game (opaque input contexts such as `win-settings`, `ui-title`, `dialogue`, `cutscene`, plus `error` and `loading`); the bridge and the MCP tools copy it as-is.
46
+ - **Run state** is printed after `step` / `press` / `skip` / `resume` and by `threedog status`: `running`, `title-frozen` (title screen waiting for start), `halted` (loop stopped by the bridge, a test or a headless page), `frozen(by owners)` (every `freeze` owner, e.g. `ui-inventory` or `page`) or `loading`. The same object is `engine.runState` and `describe().time.run`: `{ state, owners, blockedBy }`, where `blockedBy` lists what keeps input from driving the game (opaque input contexts, `error`, `loading`).
48
47
  - **Who holds what**: `describe().holds` lists every holder in one place: `halt / freeze / camera / debugView` as `[{ owner, at }]` (`at` = game clock time of the take, `engine.clock.now`), `input` (pushed contexts `[{ context, owner, pass }]`), `gates` (`input.gate` owners by action) and `stacks` (every other `engine.mod` quantity), so a stuck pause, jump or camera has a name.
49
48
  - **`snap` on a real page captures only the canvas** (not the HTML UI); on a headless page it captures the whole page. To see UI state use `describe`
50
49
  (`ui.windows`, dialogue).
51
- - **Keys go through `engine.input` like a real keyboard**: action names are translated to keyboard keys (gamepad buttons are ignored); when a window
52
- locks input, menu-type actions (`pressedRaw`) are still received.
53
- - **In your own page scripts and tests use `engine.input.simulate(action, down = true)`** (the same path as `press`): `engine.input.simulate('jump'); engine.step(1 / 60); engine.input.simulate('jump', false)`.
54
50
  - `describe` by default gives only the 3 nearest things and the first quest; for detail use a path (`quests.active`, `nearby`, `world`) or `--full`.
51
+
52
+ ## 2a. Hold a button down in a headless shot or test (`engine.input.simulate`)
53
+ - **In page scripts and tests use `engine.input.simulate(action, down = true)`** (like `press`): `engine.input.simulate('jump'); engine.step(1 / 60); engine.input.simulate('jump', false)`.
54
+ - **Hold across a picture**: `threedog js "engine.input.simulate('moveForward', true)"`, `threedog step 1`, `threedog snap`; release with `false`.
55
+ - After changing the viewport on a headless page, `step` once before reading sizes (`step()` picks the new size up).
56
+
57
+ ## 2c. Start the game from the command line: leave the title screen (`state play=1`, `--play`), open the page with URL parameters (`--page`)
58
+ - **Start clean.** Enter on a title picks Continue when a save exists, so a rerun by keys plays the last autosave. `state fresh=1` deletes the saves and
59
+ goes back to the title, `play=1` starts the run; `?fresh&play` does the same in a URL. `session.newGame()` alone leaves the title open.
60
+ - `snap --play` and `shot --play` leave the title first; `--page "/?play&time=17:40"` opens that URL (kept on reload).
55
61
  - Several pages: `--page /<page>.html` picks the path; `-w name` picks the workspace.
56
- - Another port (`npm run dev -- my-game --port 5000`) is found through `.threedog/dev.json`.
62
+
63
+ ## 2d. Import a game module inside a test page (`window.game`)
64
+ - A test page runs the bundled game, so `import('/game/x.js')` is a 404: use `window.game` or `engine` (set next to `window.engine = engine`).
57
65
  - Never ready: the dev server attaches `window.engine` itself, but a bundled build (npm test) needs `window.engine = engine;` before `await engine.start()`; the timeout error says which is missing.
58
66
 
59
67
  ## 2b. A scripted playthrough, and three kinds of check
@@ -73,15 +81,12 @@ The same steps as a file: `tests/scenarios/<name>.json` with `{ "press": … }`,
73
81
 
74
82
  **Script the failures, not only the win.** Every end state gets a scenario: lose, die and respawn, retry, reload mid-run (`threedog reload` between bridge commands; a scenario file has no reload step). Read `ops never run` in the `verify` report (rules no script reached), then check what the player stands in after the failure: a closed-off respawn point, a hit landing after the blow that should end contact, a timer or lock left from the last attempt.
75
83
 
76
- Playing a game through from a script, the five things that cost the most time:
77
- - **Start clean.** Enter on a title picks Continue when a save exists, so a rerun by keys plays the last autosave. `state fresh=1` deletes the saves and
78
- goes back to the title, `play=1` starts the run; `?fresh&play` does the same in a URL. `session.newGame()` alone leaves the title open.
84
+ Playing a game through from a script, the four things that cost the most time:
79
85
  - **Advance time yourself.** On a headless page the clock moves only on `step`, `press` and `hold`, so `await player.walkTo(spot)` never returns. Start it,
80
86
  step, then await: `const w = engine.player.walkTo(spot); step(5); return await w`. A `js` script whose page clock stands still for 20 s ends with that reason.
81
87
  - **Continue finishes after `press` returns.** The load is async, so the first lines of `press` on a title still say `windows open title`; the `Changed:` line and the next command show it closed. A load that waits on frames needs a `step` on a halted page.
82
88
  - **Read why it was refused.** `interaction.use` fails with `inputLocked` and `facts: { by }` (`title`, `dialogue`, `settings`...), `tooFar` with the distance.
83
- - **Press real keys when input is the question**: the title menu, whether a key reaches the action, a hold. For rules use `op` and `state`: faster and exact.
84
- Neither tells you how the game feels or sounds, and a headless picture falls back to software WebGL2 where no hardware GPU is reachable (the `shot` / `snap` line says): report those as not verified.
89
+ - **Press real keys when input is the question** (title menu, a hold); rules go through `op` and `state`. Neither shows how the game feels or sounds, and a headless picture is software WebGL2 where no hardware GPU is reachable (the `shot` / `snap` line says): report those as not verified.
85
90
 
86
91
  ## 3. Windows / PowerShell notes
87
92
  - **Quote commas**: PowerShell splits `pos=1,-8` into two arguments and the coordinates become NaN. Write `threedog state "pos=1,-8"` (the bridge
@@ -89,11 +94,10 @@ Playing a game through from a script, the five things that cost the most time:
89
94
  - Wrap the whole `js` expression in **double quotes** and use single quotes for strings inside: `threedog js "engine.vars.counter('score')"`.
90
95
  PowerShell expands `$variables` inside double quotes; to pass `$` literally wrap the whole thing in single quotes.
91
96
  - **Write a command on a single line** (a multi-line here-string to a native command often returns nothing): separate statements with semicolons, or use `threedog js --file script.js`.
92
- - Some terminal sandboxes (Bash) block commands containing the word `eval`: use `js`, not `eval`.
93
97
 
94
98
  ## 3b. Speed, a session, and checks in one call
95
99
 
96
- The bin called directly is the fastest route (COMMANDS.md, first lines); `threedog session` saves a little more per command. Commands behave identically with or without it.
100
+ The bin called directly is the fastest route (COMMANDS.md, first lines); `threedog session` saves a little more per command.
97
101
 
98
102
  - `threedog js --file steps.js`: the whole test in one file, one round trip. Inside: `assert(cond, msg)`, `expect(v).toBe(x)` (also `toEqual`, `toBeCloseTo(x, tol)`, `toBeGreaterThan`), `step(seconds)`, `log(...)`, and `engine`. It prints the failures and one summary line, exit code 1 on failure:
99
103
 
@@ -104,6 +108,10 @@ step(1);
104
108
  expect(engine.time.tick).toBeGreaterThan(before, 'time advanced');
105
109
  ```
106
110
 
111
+ ## 3c. Several agents building at the same time: one worktree or folder each
112
+ - Each agent uses its own worktree / folder (`-w name`); a tool build is private to its run, so it cannot break another session's page.
113
+ - Another port (`npm run dev -- my-game --port 5000`) is found through `.threedog/dev.json`.
114
+
107
115
  ## 4. Let describe see the game's own state
108
116
  A game's own state (score, number of targets, crops) is not in `describe` by default. **Small games use this**: register it in one line, no module needed:
109
117
  ```js
@@ -117,9 +125,7 @@ The bridge exists only in the dev server (`apply: 'serve'`); built and preview o
117
125
  be localhost, and anything carrying an Origin (sent from a web page) is rejected.
118
126
 
119
127
  ## 6. Reuse in scenario tests
120
- The bridge commands are built on one small driver, `{ evaluate(src, arg), screenshot(), reload?() }`. The dev bridge's driver forwards the three to
121
- the dev server. For your own tests, `import { pageDriver, runScenario } from '@threedog/tools/scenario'` (the public entry; the command runner behind
122
- the bridge is internal) gives the same driver for a Playwright `page` and runs a scenario file through it.
128
+ The bridge commands are built on one small driver, `{ evaluate(src, arg), screenshot(), reload?() }`. For your own tests, `import { pageDriver, runScenario } from '@threedog/tools/scenario'` gives the same driver for a Playwright `page` and runs a scenario file through it.
123
129
 
124
130
  ## 7. Describe snapshots instead of screenshots
125
131
  A baseline is the gameplay part of `engine.describe()` saved as JSON (`<workspace>/tests/snapshots/<name>.describe.json`, commit it). `perf`, `loading`, `picture.writers` and the clock counters `time.tick` / `time.real` / `time.ambient` are dropped; numbers compare within a tolerance (default 0.5); a list of things with an `id` or `name` is compared by that key, so a
@@ -129,8 +135,6 @@ reordered `nearby` is not a change. A difference comes out as text, e.g. `player
129
135
  threedog snap-describe save market-noon --only player,quests,nearby # write / overwrite the baseline
130
136
  threedog snap-describe diff market-noon --only player,quests,nearby # compare the running page with it (exit code 1 if different)
131
137
  ```
132
- Options: `--only a,b.c` (compare just these fields; dotted paths allowed), `--ignore x.y` (extra fields to skip), `--tolerance 1`. Use the same
133
- `--only` for save and diff.
134
138
 
135
139
  In a test, one line (the page must already be in the state to freeze; use `engine.haltLoop()` and `engine.step()` first):
136
140
  ```
@@ -139,22 +143,19 @@ await expectDescribe({ check, ev }, 'market-noon', { only: ['player', 'quests',
139
143
  ```
140
144
  Update after an intended change: `threedog test <name> --update-snapshots` or `threedog snap-describe save <name>`, and review the JSON diff before committing.
141
145
 
142
- ## 8. Errors carry a code, a fix and a doc page
146
+ ## 8. Show the latest errors: they carry a code, a fix and a doc page
143
147
  Every error and warning the engine raises carries a stable **code**: `err.code`, `err.fix` (what to do) and `err.docs` (pages to read), and its message
144
- ends with `[code]` (e.g. `clock.every(seconds): ... [clock-interval]`), so logs show it too. Messages the engine does not write (JavaScript's
145
- `Cannot read properties of undefined`, `... is not a function`, a frozen definition, a browser resource 404) get the code of the hint whose pattern matches. Dev text adds `Code: …`
146
- (when the message has no tag), `Possible cause: …` and `Read: recipes/…, api/…`. The same data shows in `engine.error`
147
- (`{ where, message, code, fix, docs }`), the first line of `describeText()`, `.threedog/errors.log` and `threedog errors`. A code never changes meaning.
148
+ ends with `[code]` (e.g. `clock.every(seconds): ... [clock-interval]`), so logs show it too. Messages the engine does not write (JavaScript's `... is not a function`, a browser 404) get the code of the hint whose pattern matches. The same data shows in `engine.error`
149
+ (`{ where, message, code, fix, docs }`), the first line of `describeText()`, `.threedog/errors.log` and `threedog errors` (`errors latest 3` = the last 3). A code never changes meaning.
148
150
 
149
151
  ## 9. Reusable scenarios
150
152
  `engine.applyState({ time, weather, pos, ... })` (also URL parameters) sets up a scenario in one call; `engine.defineState(name, params)` names a
151
153
  combination so tests and scenarios reuse it.
152
154
 
153
155
  ## 10. MCP server: Claude Code, Cursor and other MCP clients
154
- `threedog mcp` runs the dev bridge as an MCP server over stdio. Each command becomes a tool (`play`, `status`, `describe`, `step`, `press`, `hold`, `skip`, `state`, `ops`,
155
- `op`, `catalog`, `inspect`, `scene`, `pick`, `thing`, `explain`, `errors`, `loading`, `snap`, `snap_describe`, `picture_palette`, `picture_compare`, `scenario`, `verify`, `reload`, `resume`, and the static `how`, `check`, `art_list` and `lib_list`) and returns the same text as the
156
- command line (every default answer fits in about 4 KB; a `data` payload over 3 KB keeps its small fields and names `threedog <cmd> --json` for the rest); `snap` also returns the PNG as an image, 480 px wide by default (`size` for more; the full file is saved). `picture_palette` and `picture_compare` need no game (recipe 35). It finds the dev server through `.threedog/dev.json` like the CLI; with none running, call the `play` tool (it starts the server and waits for the bridge)
157
- (or start `npm run dev` yourself; a tool call without a server answers with that fix). It is only a local client of the bridge and opens no port; every check in section 5 still applies. As
156
+ `threedog mcp` runs the dev bridge as an MCP server over stdio. Each command becomes a tool of the same name (`play`, `status`, `describe`, `step`, `snap`, `snap_describe`, `scene`, `reload`, `how`, `check`, `catalog`, `art_list`, `lib_list`...) and returns the same text as the
157
+ command line (every default answer fits in about 4 KB; a bigger `data` payload names `threedog <cmd> --json`); `snap` also returns the PNG as an image, 480 px wide by default (`size` for more; the full file is saved). `picture_palette` and `picture_compare` need no game (recipe 35). It finds the dev server through `.threedog/dev.json` like the CLI; with none running, call the `play` tool (it starts the server and waits for the bridge)
158
+ (or `npm run dev`; a call without a server says so). It is only a local client of the bridge and opens no port; every check in section 5 still applies. As
158
159
  with the command line, the `op` and `step` tools change the current session and its saves; the level itself changes only by editing content files.
159
160
 
160
161
  Claude Code (in the game folder; in the engine repository add `-w name` after `mcp`):
@@ -184,3 +185,12 @@ Tools: MCP, or `node node_modules/@threedog/tools/bin/threedog.mjs <cmd>` (`COMM
184
185
  - Models made in code -> hot swap, `threedog gallery --shots` (recipe 05 §2c); another game's art -> `threedog art copy`.
185
186
  - Verifying a change -> `describeText()` for logic, shots for the picture, `threedog verify <scenario>` (read "not proven").
186
187
  - Saves or time skips broken -> `checkSave`, `checkSkip`.
188
+ - This must stay so (a range, with the reason) -> `threedog expect` (section 12).
189
+
190
+ ## 12. Expectations: keep a number or threshold in range, with the reason (a guard so a value does not change again)
191
+ ```sh
192
+ threedog expect shot.dark --max 0.35 --point night-view --why "path lost at 0.5"
193
+ threedog expect economy.gold --min 0 --why "negative = price ran twice"
194
+ threedog expect loading.failed.length --is 0 --why "a missing model hid the item"
195
+ ```
196
+ A `describe()` path (`shot.*` needs `--point`); `threedog shot --point night-view` and `threedog test` check it: **holds**, **fails** (reason printed), **missing** (no such path) or **unmeasured** (another renderer's `shot.*`, listed). Snapshots (7) compare a whole run, scenarios (6) drive a play, `Picture intent` states a look; this keeps one number and why. The same value and point again edits it, showing the old reason; `expect drop` removes it.
@@ -160,6 +160,7 @@ if (engine.saves.check('auto') === null) await engine.session.load('auto'); //
160
160
  record id, not the mesh, and look it up again on `save:loaded`: `engine.world.get(id)` for the record, `engine.world.view(id)` for its model
161
161
  now (null while not built or far away).
162
162
  - Main menu: show "Continue" only when `engine.saves.check(slot) === null`; "New game" is `await engine.session.newGame()`.
163
+ - Start screen rows: mark the part with the numbers `summary: true` (`saves.define('hero', { save, load, summary: true })`); `saves.list()` rows then carry `summary.hero`, read from the stored save and migrated, `{}` if none is marked.
163
164
  - During development, to jump straight into a save: URL `?save=slot1` (`threedog state` also understands `save=`).
164
165
  - In tests, `engine.saves.save('x'); await engine.saves.flush();` writes before reading back.
165
166
 
@@ -49,7 +49,7 @@ engine.cameraRig.shoulder = -0.7; // switch shoulders at any time (plain proper
49
49
  engine.cameraRig.frame(enemy.root); // lock-on: turn to "behind the player, looking at the enemy"; frame(null) lets go
50
50
  ```
51
51
  - **`shoulder`**: meters the aim point (and so the camera) moves to the right along `right()`; negative = left, 0 = centered (default).
52
- - **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases, and `engine.page.releaseLock()` releases from code without opening the pause menu. Not on phones. If the browser refuses the lock the camera falls back to dragging; `describe().camera.pointerLock` has `state` (`off` / `unsupported` / `waiting-click` / `requesting` / `locked` / `refused`), `covered` (what sits on the canvas centre and eats the click), `cameraOverride` (a takeover blocks locking) and `lastFailure { reason, agoSec }`; the text line shows the same.
52
+ - **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases, and `engine.page.releaseLock()` releases from code without opening the pause menu. Not on phones. If the browser refuses the lock the camera falls back to dragging; `describe().camera.pointerLock` says why it is not locked (`state`, `covered`, `lastFailure`).
53
53
  The press that locks is swallowed (no `Mouse0`, no click) so it cannot attack or fire; `swallowLockClick: false` delivers it.
54
54
  Leave it off when the mouse buttons are for UI or clicking the ground.
55
55
  - **`yaw` is which side of the player the camera is on**: `camera = focus + (sin yaw, cos yaw) * distance`, looking along `forward() = -(sin yaw, cos yaw)`; prefer `frame(target)` to computing it.
@@ -138,9 +138,8 @@ function steer(player, input, dt) { // called once per fixed step while the inp
138
138
  current target and its own rules, such as "let go beyond 20 m" or "target died, pick the next".
139
139
  - The engine already calls `player.animate(dt)` every frame; a module with its own loop over characters must skip the player, or the walk cycle runs
140
140
  twice as fast.
141
- - Test without a keyboard: `engine.input.simulate('lockOn'); engine.step(1 / 60); engine.input.simulate('lockOn', false)`.
142
141
 
143
- ## 6. Orthographic view, and taking the camera over yourself
142
+ ## 6. Orthographic view, and taking the camera over yourself (a title background camera)
144
143
 
145
144
  **Orthographic (isometric / 2.5D) with the built-in rigs.** `projection: 'orthographic'` plus `size` (world units of view height) on the fixed and follow cameras.
146
145
  The default stays perspective. On resize the view height stays `size` and the width follows the aspect.
@@ -167,7 +166,7 @@ A `setCamera` before play (boot code, or with the title up) is the camera every
167
166
  - Limits: on the follow camera the mouse wheel changes `size` (clamped to the `minDistance`/`maxDistance` ratio of the starting `distance`).
168
167
  The `fov` slider in the settings menu has no effect. Cascaded shadows, `dof` and `outline` handle orthographic depth; a custom post pass that assumes perspective depth must do the same.
169
168
 
170
- **Placing the camera yourself (cutscene, photo mode, your own rig).** Take it with `engine.takeCamera(owner, { focus })`; the camera module leaves the camera alone until you `remove()` the handle.
169
+ **Placing the camera yourself (cutscene, photo mode, your own rig).** Take it with `engine.takeCamera(owner, { focus })`; the camera module leaves the camera alone until you `remove()` the handle. A camera script of yours steps aside the same way while `engine.cameraOverride` is set; otherwise `shot --cam` / `--view` fails with "the game's camera code moved the camera away from the requested view".
171
170
  Several holders can take it (a cutscene, then a named view on top): the latest is in charge, and removing it hands the camera back to the previous one, not to nobody.
172
171
 
173
172
  ```js fragment
@@ -167,12 +167,13 @@ engine.events.on('session:start', () => results.toggle(false)); // a new run or
167
167
  results.toggle(true); // when the run ends; results.refresh() after the data changes
168
168
  ```
169
169
 
170
- ## 5. Title screen and "back to title"
170
+ ## 5. Title screen: your own title part (the title text, a background camera) and "back to title"
171
171
  ```js
172
172
  createEngine({ canvas, ui: { title: { title: 'My Game', items: ['continue', 'start', { label: 'Credits', run: e => showCredits() }] } } });
173
173
  engine.events.on('ui:close', id => { if (id === 'title') startIntro(); }); // the player left the title screen
174
174
  engine.ui.open('title'); // show it again (the settings 'game' tab has a "Back to title" button)
175
175
  ```
176
+ A custom title part gets the title text and items in `show({ title, items })` (section 2); its backdrop is the theme's `loadingBg`, or hold the camera with `engine.takeCamera` and move it in `engine.onFrame` (recipe 21).
176
177
  While the title is open gameplay is frozen, input is locked, and Esc goes to it (the settings menu does not open).
177
178
 
178
179
  **A custom item closes the title itself.** The built-in `continue` / `start` call `e.ui.close('title')` after loading; yours does not, so `flow` can reach `playing` with the title still on top, no warning. End every item that leaves the title with `e.ui.close('title')`:
@@ -193,7 +194,7 @@ const still = await engine.photo.trace({ samples: 128 }); // still.pathTraced.u
193
194
  ```
194
195
  HUD text follows the engine locale (`createEngine({ locale })`, default `'auto'` = the browser language): a game written in English sets `locale: 'en'`, or distance labels read `50 米` on a Chinese browser.
195
196
 
196
- ## 6. Settings menu: only the tabs the game needs, quality options that turn off your pass
197
+ ## 6. Settings menu: add a row with a label (`settings.define`), only the tabs the game needs, quality options that turn off your pass
197
198
  ```js
198
199
  engine.use(settings({ sections: ['game', 'graphics', 'audio', 'controls', 'camera'] })); // default: graphics, audio, controls, language, saves
199
200
  // optional built-ins by name: 'game' (resume / load / back to title), 'camera' (sensitivity, invert Y, field of view; re-applied on 'camera:change')
@@ -37,8 +37,8 @@ Code may hold functions (a `volume: e => ...`); the same config as data goes in
37
37
 
38
38
  ## 2. Buses and sounds by name
39
39
  Buses are real Web Audio `GainNode`s: `master`, `music`, `sfx`, `ambience`, `ui`, plus the game's own (`levels: { voice: 1 }` or
40
- `engine.audio.addBus('voice')`). `engine.audio.setVolume('music', 0.3)` sets one; `engine.audio.buses.sfx` is the node to connect your own nodes to, and `buses.master` (also `audio.master`) is the total. `buses` is empty until audio
41
- unlocks on the player's first click or key: build your own nodes on the `audio:ready` event. A name that is no bus warns once and gives `master`, so the sound still plays.
40
+ `engine.audio.addBus('voice')`). `engine.audio.setVolume('music', 0.3)` sets one; `buses.sfx` is the node to connect to, and `buses.master` is the total. `buses` is empty until audio
41
+ unlocks on the player's first click or key: build your own nodes on the `audio:ready` event. A name that is no bus warns once and gives `master`.
42
42
 
43
43
  ```js fragment
44
44
  engine.audio.sfx('door'); // plays on its bus (default sfx)
@@ -57,6 +57,12 @@ until the rules load again, instead of refetching.
57
57
 
58
58
  A synth with default params is `{ build: synthFn, params }` in the manifest.
59
59
 
60
+ ### 2a. Your node on a bus
61
+ `audio.addNode(bus, ctx => node)` puts your node after the bus's volume and duck, before master and the reverb send (`'master'`: before the speakers).
62
+ ```js fragment
63
+ engine.audio.addNode('sfx', ctx => Object.assign(ctx.createBiquadFilter(), { type: 'lowpass' })); // underwater: only effects go dull
64
+ ```
65
+
60
66
  ## 3. Ambience: sounds by place (a rule table)
61
67
  Drips in a cave, a river near water, birds by day: one rule each, no per-frame code, naming a sound, when and how loud. A rule with `every` is a one-shot at random gaps; without, a loop that fades in and out (and stops
62
68
  when silent, so idle rules cost nothing).
@@ -90,6 +96,16 @@ The same `when` keys as ambience. Tracks cross-fade (`fade`, default 2 s); a new
90
96
  `engine.music.override('boss')` picks by hand; `override(null)` hands back to the rules. `engine.music.stinger('win')` plays a short piece over the music.
91
97
  Decoded music is large (about 21 MB a stereo minute): `assets.release(name)` and `assets.trim()` (a level change calls it) free it, the longest-unused long sounds go by themselves over a memory budget, playing sounds play on, a freed sound loads again when played; effects under 10 s stay cached, and `preload: true` keeps a track.
92
98
 
99
+ ### 4a. Music made by code
100
+ `{ generate({ ctx, output, start, end }) }` instead of `url` / `stems` (code only) runs per play: connect to `output`, start at `start`; `end()` finishes it
101
+ (a stinger must call it, or the music stays dipped); a returned `{ stop(at) }` hears the fade-out.
102
+ ```js fragment
103
+ engine.music.define('drone', { generate({ ctx, output, start }) {
104
+ const o = ctx.createOscillator(); o.connect(output); o.start(start); // layer by engine.music.intensity
105
+ return { stop: at => o.stop(at) };
106
+ } });
107
+ ```
108
+
93
109
  ## 5. Footsteps by surface
94
110
  The player's footstep rhythm follows its speed (one step per foot landing). Each step plays the sound named by `footsteps[groundType]`, else
95
111
  `footsteps.default`, else `footstep`. The ground type is the terrain's `groundType` or, in a Blender level, the material name (or `groundType` custom
@@ -101,7 +117,7 @@ const d = engine.audio.duck({ music: 0.3, ambience: 0.5 }, { fade: 0.3 }); // l
101
117
  engine.events.once('dialogue:end', () => d.remove()); // restore
102
118
  ```
103
119
  Ducks stack (levels multiply) and never touch the player's volume setting. `music({ duckDialogue: 0.35 })` ducks the music bus during dialogue for
104
- you; it is off by default (whether talking lowers the music is the game's choice).
120
+ you; it is off by default.
105
121
 
106
122
  ## 7. Settings
107
123
  The default settings menu has a volume slider per bus, the game's own buses included, saved with the other settings. A game bus's label is the text
@@ -19,7 +19,7 @@ For an AI that wants water or weather particles to look a way the defaults do no
19
19
  none of `depthColor`, `foam`, `surface` keeps the plain shader and pays nothing. Four exits: a material write, a
20
20
  uniform, a GLSL function you replace, or your own material.
21
21
 
22
- ## Water: material and uniforms
22
+ ## Water: material and uniforms (sea, lake or river around an island: `engine.water`)
23
23
  `engine.water.material` is shared by every water mesh and is a `MeshLambertMaterial` by default: color, opacity and anything else three.js has on it are
24
24
  plain writes. Lambert has no highlight; for `shininess` / `specular` set your own Phong material (below). `engine.water.uniforms` are `{ value }` objects:
25
25
  `uWave` multiplies the wave function (0 = flat), `uWaveScale` scales the world position fed to it, `uWaveSpeed` the time; all three default to 1. `uFresnel` (default 0.5, 0 = off) blends grazing angles toward the fog color, or the sky's horizon with no fog.
@@ -53,7 +53,7 @@ in**: game code and the game's `plugins/` folder (a file that exports the Pass o
53
53
  effect has a name, a handle and a row in `describe().slots` and `describe().render.post`. It returns `{ name, enabled, set(params), remove() }`, and
54
54
  `engine.post.get(name)` returns the same handle. A wrong shape throws with nothing added.
55
55
 
56
- `x` is a plain three.js Pass (WebGL), a TSL node function `(input, ctx) => node` (WebGPU), or an effect `{ name, create, node, fuse, slot, order, params, update, needsDepth, needsBuffers, backend, skipOnLowTier, facts }`: both renderers when it gives `create` and `node`, or a `fuse`. `create(ctx) => pass` returns any three.js postprocessing Pass, built the first time the effect is on, and `update?(pass, params)` applies new params (on WebGPU `node`: recipe 56). Optional: `needsBuffers` (extra scene outputs, WebGPU), `backend: 'webgpu'` (the WebGL2 backend cannot run it), `skipOnLowTier` (held on `engine.tier` 'low'), `facts` (a line in `describe().render.post`).
56
+ `x` is a plain three.js Pass (WebGL), a TSL node function `(input, ctx) => node` (WebGPU), or an effect `{ name, create, node, fuse, slot, order, params, update, needsDepth, needsBuffers, backend, skipOnLowTier, facts }`: both renderers when it gives `create` and `node`, or a `fuse`. `create(ctx) => pass` returns any three.js postprocessing Pass, built the first time the effect is on, and `update?(pass, params)` applies new params (on WebGPU `node`: recipe 56). Optional: `needsBuffers` (extra scene outputs, WebGPU), `backend: 'webgpu'` (the WebGL2 backend cannot run it), `skipOnLowTier` (held on `engine.tier` 'low'), `facts: () => object` (a function; what it returns is shown in `describe().render.post`).
57
57
 
58
58
  **An extra render inside your own effect** (a mask pass, a depth of selected objects): draw it in `ctx.borrowRenderer(renderer, () => { renderer.setRenderTarget(myTarget); renderer.render(scene, camera); }, { scene, camera })`. The render target, viewport, scissor, clear color, tone mapping and the scene's override material, background and fog come back afterwards, also when the draw throws; targets and materials stay the effect's to dispose. `clean: true` (WebGPU) starts from three's reset state for a quad inside a node frame. Restoring by hand and forgetting one makes the next effect draw into your target.
59
59
 
@@ -28,7 +28,7 @@ What to remember:
28
28
  it. You never pick a layer by hand unless you want to: game code and game modules write `'game'` (the default); effects pass `layer: 'effect'`.
29
29
  - **`mul` / `add` to cooperate, `set` to decide.** Any number of owners can multiply and add. Two owners `set` the same value on the same layer is
30
30
  an error (in development and release alike) that names both lines and gives three copyable fixes; copy one. The earlier value stays.
31
- - **`replaces` to swap an engine part** that `provides` a slot; a second provider without it is the error `shared-taken`. What the old part issued goes with it: read `engine.<slot>` where you use it, and keep the issuer beside any handle so you can compare (`if (from !== engine.rigid) { from = engine.rigid; crate = from.addBox(mesh); }`). Version numbers count per module, so they cannot tell two modules apart. The engine's own props, NPCs, pickups, cars and movers do this; a rider leaves a rigid car when rigid goes. `world` is the exception: it owns every record, so install your world before the modules that need it; once they are installed, or after `start()`, `replaces: 'world'` and `unuse('world')` are refused (`module-replaces`, `module-unuse`). A factory that gives two modules goes in whole: `engine.use(terrain(o), { replaces: 'terrain' })` swaps its drawing part too. A module of your own wraps `world.present`, `world.simulate`, `rays.addProvider`, `input.touchButton` and `assets.onSwap` in `ctx.track(...)`, so they leave with it.
31
+ - **`replaces` to swap an engine part** that `provides` a slot; a second provider without it is the error `shared-taken`. What the old part issued goes with it: read `engine.<slot>` where you use it, and keep the issuer beside any handle so you can compare (`if (from !== engine.rigid) { from = engine.rigid; crate = from.addBox(mesh); }`). Version numbers count per module, so they cannot tell two modules apart. `world` is the exception: it owns every record, so install your world before the modules that need it; once they are installed, or after `start()`, `replaces: 'world'` and `unuse('world')` are refused (`module-replaces`, `module-unuse`). A factory that gives two modules goes in whole: `engine.use(terrain(o), { replaces: 'terrain' })` swaps its drawing part too. A module of your own wraps what it registers in `ctx.track(...)` (recipe 14), so it leaves with it.
32
32
  - Every handle ends with `h.remove()` (`engine.mod`, `ctx.mod`, `input.gate`, `wrap`, `freeze`, `takeCamera`); it drops only your own entry.
33
33
 
34
34
  Only things several parties write are shared values (time speeds, holders, move stats, input gates, shadow and post parameters); your own
@@ -70,6 +70,10 @@ engine.wrap(engine.inventory, 'add', (next, id, n = 1, o) => // a weight rule o
70
70
  `engine.stacks.define(name, { important: true })` keeps a point on that line even at its base and before the cap, for the few values a reader must always see.
71
71
  - Saved: `engine` to `effect` entries. Not saved: `settings` (the settings module re-applies the player's choices), `system`, `debug`.
72
72
 
73
+ ## A stale handle after loading a save; an additive stat that reads 1 with no `base`
74
+ - A point reads its `base` (default 1) while nothing is set: write `engine.stacks.define(name, { base: 0 })` for an additive stat.
75
+ - A loaded save rewrites each entry in place, so an old handle's `remove()` still works; with none, `engine.mod` again with the same owner and `remove()` that.
76
+
73
77
  ## Picture points follow the same rule
74
78
  `shadows.enabled`, `post.<name>.enabled`, `sky.tint`, `sky.flash` and `ground.cover` are shared points like the rest.
75
79
  `sky.tint`, `ground.cover` (blend by amount) and `sky.flash` (adds) are written with `engine.mod`.
@@ -51,10 +51,10 @@ A node material is lit, shadowed and fogged by three like its plain twin; you re
51
51
 
52
52
  Node names come from `three/tsl` (`Object.keys(await import('three/tsl'))` lists them, `node_modules/three/src/nodes/` has the source). Noise: `mx_noise_float`, `mx_fractal_noise_float` (MaterialX, also `_vec3`), or `noise` / `hash` below.
53
53
 
54
- ## The engine's values as nodes: `uniforms(engine)`
54
+ ## The engine's values as nodes: `uniforms(engine)`, a uniform of your own that changes every frame (`setGroup`)
55
55
  `uniforms(engine)` returns `engine.uniforms` as TSL nodes with the same names: `uTime`, `uWind`, `uWeatherCloud`, `uSunDir`, `uSunColor`, `uDaylight`
56
56
  (0 at night, 1 at noon), `uTimeOfDay`, `uFoliageTint`, `uGroundTint` ... (the list: `uniforms` in [the engine API](../api/engine.md)). The node reads the
57
- engine's value each render: no per-frame code.
57
+ engine's value each render: no per-frame code. A value of your own that changes every frame: `uniform(x).setGroup(renderGroup)`, because the default `objectGroup` re-uploads it for every draw.
58
58
  ```js
59
59
  import * as THREE from 'three';
60
60
  import { MeshStandardNodeMaterial } from 'three/webgpu';
@@ -69,7 +69,7 @@ lantern.emissiveNode = color(0xffa040).mul(night.mul(glow)).mul(sin(u.uTime.mul(
69
69
  engine.add(new THREE.Mesh(new THREE.OctahedronGeometry(0.3), lantern));
70
70
  ```
71
71
 
72
- ## The engine's shader functions: `threedog/tsl`
72
+ ## The engine's shader functions: `threedog/tsl` (`detailBump`: a bumped normal from a procedural height, where `bumpMap` needs a texture)
73
73
  Each is a TSL `Fn` with the same arguments and meaning as its GLSL twin in recipe 43, reading the same `engine.uniforms`; full signatures are
74
74
  in the package's `types/tsl.d.ts`. Call them on nodes, put the result where it belongs:
75
75
 
@@ -145,9 +145,10 @@ engine.add(new THREE.Mesh(new THREE.DodecahedronGeometry(1), rock));
145
145
  ## Half-transparent surfaces differ from plain WebGL, fog does not
146
146
  Fog is mixed in linear space before tone mapping on every path (WebGPU, WebGL with an effect on, and WebGL straight to the canvas, where the engine's `fog-linear` patch moves three's fog mix before the tone curve), so fog does not change colour when the first post effect turns on. Half-transparent and additive surfaces still differ: WebGL straight to the canvas blends them in display values after tone mapping; WebGPU, and WebGL with any `engine.post` effect on, blend in linear and tone-map once. They shift a little on the straight WebGL path (more in dim scenes), and the first post effect can move them there. This is three.js's own model, not a fault in your scene.
147
147
 
148
- ## Sky and fog hooks
148
+ ## Sky and fog hooks: replace the fog function (`fogNode`)
149
149
  The engine's sky dome has a node version; nothing changes in how you set it (recipe 08). The GLSL hooks (`engine.sky.clouds`, `engine.sky.layer`
150
150
  clouds and layers) take `{ glsl, tsl }` on this route: see 52's [tsl forms](52-around-the-picture.md#tsl-forms).
151
+ Replace the fog function with `scene.fogNode = fog(color, factor)`; the dome's horizon fog band reads that colour only from a `THREE.Color`, `color(..)` or `uniform(Color)`.
151
152
  A sky of your own: three's `SkyMesh` (`three/addons/objects/SkyMesh.js`) through `engine.sky.replace`.
152
153
 
153
154
  ## Post effects as nodes
@@ -227,9 +228,6 @@ emissive lines; a storybook is soft ramp edges (`rampTexture(ramp, soften)`) wit
227
228
  - Look at the picture in gray. Do the shapes still separate? Color cannot rescue forms that have the same value.
228
229
  - Cover the object you just changed. If the rest of the frame tells you the same story about light, the style is holding; if one material looks lit by another sun, its answers differ.
229
230
  - Is every shade in the frame leaning the same way? A cast shadow and a turned-away side that disagree read as two renderers.
230
- - A flat look with soft or stair-stepped shadow edges: the shadow map is showing. Raise its resolution for the area in view, or soften the ramp a little.
231
- - Count what the picture really holds (common colors, saturation, light-dark spread): a palette look with many stray colors has something running after the `lut`.
232
- - Put an effect in the stage that matches what it reads: a grade for finished colors goes after the tone curve, a glow before it.
233
231
 
234
232
  ## Dropping a mesh whose material lives on
235
233
  Nothing to do: WebGPURenderer keeps a record of every mesh it drew while the material stays in use, so the engine frees the records of meshes 4 to 8 seconds out of every Scene (`webgpu-record-sweep` in `THREE.md`). Adding one back rebuilds it.
@@ -80,4 +80,7 @@ const p2 = engine.characters.addPlayer({ id: 'two', input: two, control: 'camera
80
80
 
81
81
  The seat's pad leaves `engine.input` and answers the game's pad bindings on this seat alone, so `bind('jump', ['PadA'])` works for it as written. A seat's keys are its own list: keep them out of the first player's bindings. Two seats on one pad or key, or one seat on two players, throw `input-seat`.
82
82
 
83
- `engine.player` stays the first player; `p2` has its own world record, saved with the world, and `removePlayer('two')` takes it away. There is one screen and one camera. Footstep sounds and NPCs giving way cover every player. A seat with its own `interact` key uses what its player stands by, as that player (`seat.actor`, set by `addPlayer`; `ctx.actor` in the op). The prompt shows `engine.actor`'s choice alone, and one hold runs at a time. A trigger zone hears every player when its `who` names them.
83
+ `engine.player` stays the first player; `p2` has its own world record, saved with the world, and `removePlayer('two')` takes it away. There is one screen and one camera. A seat with its own `interact` key uses what its player stands by, as that player (`seat.actor`, set by `addPlayer`; `ctx.actor` in the op). The prompt shows `engine.actor`'s choice alone, and one hold runs at a time. A trigger zone hears every player when its `who` names them.
84
+
85
+ ## 7. Read a key while the world is frozen: a menu's own keys (`pressedRaw`, `toggleOnKey`)
86
+ A menu reads its keys with `engine.input.pressedRaw(action)` in an `engine.onFrame` hook (it ignores input contexts). To open and close a window on one key, call `toggleOnKey(engine, win, 'menu')` there once per frame.
@@ -12,8 +12,8 @@ time of day, so every row says what to look for instead.
12
12
 
13
13
  Where the rest lives (one home each): calls, parameters and who writes what: [recipe 52](52-around-the-picture.md); the plain three.js way: [THREE.md](../THREE.md); whole-picture questions and the numbers each shot prints: [recipe 35](35-picture-from-reference.md) "Picture questions" and "Picture check after every shot"; a whole picture: `picture/` code ([62](62-picture-code.md), materials and lights [09](09-materials-lights-models.md)).
14
14
 
15
- ## How to judge, in one loop
16
- Change one knob, take a shot (`threedog shot`, or `threedog snap` on a running page), compare with the one before, keep or undo. Shoot the
15
+ ## How to judge, in one loop: a shot that waits for background work and holds a key
16
+ Change one knob, take a shot (`threedog shot`, or `threedog snap` on a running page), compare with the one before, keep or undo. A shot waits for `isReady` work (a decor chunk, a texture job; recipe 05 section 3), holds a key with `engine.input.simulate` (recipe 16), and needs a camera script to step aside for `--cam` (recipe 21). Shoot the
17
17
  times and weathers the game really shows (`threedog shot --time`), not only noon. A knob is right when the difference you wanted is visible
18
18
  and nothing else got worse; when you cannot say what difference a knob should make, leave it at the style's value.
19
19
 
@@ -26,18 +26,18 @@ shadow. `threedog examples pull sun-and-key-light` shows three routes side by si
26
26
 
27
27
  | Knob | What it changes on screen | It is right when | How (details) |
28
28
  |---|---|---|---|
29
- | Sky gradient, horizon | the color from the top of the sky down to where it meets the ground | the horizon band and the fog agree where they meet; the top-to-horizon change matches the hour and mood; no visible seam | `engine.sky.top`, `engine.sky.horizon` ([08 §3](08-weather-sky.md#3-changing-sky-colors-sun-stars-the-day-and-night-sky)); own shader: share `engine.uniforms.uSkyHorizon` / `uSkyTop` ([08](08-weather-sky.md#sky-color-for-my-shader-horizon-color-zenith-color)); own sky: `engine.sky.replace(mySky)` |
29
+ | Sky gradient, horizon | the color from the top of the sky down to where it meets the ground | the horizon band and the fog agree where they meet; the top-to-horizon change matches the hour and mood; no visible seam | `engine.sky.top`, `engine.sky.horizon` ([08 §3](08-weather-sky.md#3-change-the-sky-colors-sun-glow-usunglow-stars-and-the-horizon-fog-band-the-day-and-night-sky)); own shader: share `engine.uniforms.uSkyHorizon` / `uSkyTop` ([08](08-weather-sky.md#sky-color-for-my-shader-horizon-color-zenith-color)); own sky: `engine.sky.replace(mySky)` |
30
30
  | Fog near / far | how fast distant things fade | the play space stays clear, the far edge of the world dissolves instead of ending in a line, landmarks you want seen still read | `engine.scene.fog = new THREE.Fog(color, near, far)` ([34 Fog](34-environment-lighting.md#fog-plain-threejs-signals-your-own-math)) |
31
31
  | Fog color vs sky | whether the distance melts into the sky or into its own haze | distant hills fade toward the sky behind them; a fog color of its own is a choice you can name (smoke, mist, a dream) | `scene.fog.color`, your `picture/` code reads `uSkyHorizon` ([34 Fog](34-environment-lighting.md#fog-plain-threejs-signals-your-own-math)) |
32
32
  | Exposure | overall brightness after lighting | the brightest things you care about keep detail and the darkest still read; a night is dark because the lights are, not because exposure hides it | `engine.renderer.toneMappingExposure` ([34 Exposure](34-environment-lighting.md#exposure-and-the-tone-curve)) |
33
33
  | Tone mapping curve | how highlights roll off and how saturated bright colors stay | bright colors keep their hue where the style wants color, highlights soften where it wants film; flat-color styles may want almost no curve | `engine.renderer.toneMapping = THREE.AgXToneMapping` (or ACESFilmic, Neutral, No) ([52 Who writes it](52-around-the-picture.md#who-writes-it-the-ownership-table)) |
34
34
  | Sun direction | where shadows fall and which faces are lit | shapes read from the camera (lit side and shaded side both visible), shadows point somewhere useful, the hour looks like the hour | time of day (`engine.calendar`, [06](06-clock-events.md)); sun path: `engine.sky.orbit.tilt`; the lights do not move on their own: aim yours from `engine.uniforms.uSunDir` ([62](62-picture-code.md)) |
35
35
  | Sun color, intensity | the key light: color and strength of lit faces | lit and shaded sides separate; whites under the sun are the white the style wants (warm, neutral, cool) | your `picture/` code writes the light ([62](62-picture-code.md)) |
36
- | Ambient / hemisphere, environment | the fill: how bright and what color the shaded side is | shadows are as deep as the style wants and still show shape; up-facing and down-facing faces differ; metals have something to reflect | your `picture/` code writes the hemisphere light and `scene.environment`, `scene.environmentIntensity` ([34](34-environment-lighting.md), [08 brightness](08-weather-sky.md#3-changing-sky-colors-sun-stars-the-day-and-night-sky)) |
36
+ | Ambient / hemisphere, environment | the fill: how bright and what color the shaded side is | shadows are as deep as the style wants and still show shape; up-facing and down-facing faces differ; metals have something to reflect | your `picture/` code writes the hemisphere light and `scene.environment`, `scene.environmentIntensity` ([34](34-environment-lighting.md), [08 brightness](08-weather-sky.md#3-change-the-sky-colors-sun-glow-usunglow-stars-and-the-horizon-fog-band-the-day-and-night-sky)) |
37
37
  | Shadow softness | hard or blurred shadow edges | edges match the light (crisp under a clear sun, soft under cloud or for a gentle style); no stair-steps or speckle | `renderer.shadowMap.type`, `light.shadow.radius` ([45](45-cascaded-shadows.md)) |
38
38
  | Shadow distance, detail | how far shadows reach and how sharp small ones are | the area the player looks at has shadows; small props keep theirs; objects touch the ground (no gap under a foot) | `engine.shadows.box(sun, { extent })`, `engine.shadows.cascades(sun, { count, maxFar })`, `light.shadow.bias`, `mapSize` ([45](45-cascaded-shadows.md)) |
39
39
  | Bloom | light bleeding around bright pixels | the bright things you meant (sun, lamps, magic) glow and nothing else does; the picture does not turn milky | `engine.post.add(bloom())` from `@threedog/post-effects`, or three's `UnrealBloomPass` through `engine.post.add(pass)` ([52 Post chain](52-around-the-picture.md#post-effect-chain-your-own-pass-extra-render-passes)) |
40
- | Light glow / halo | lamps, windows, signs that read as lit | a glowing object keeps its hue at the center (it is not a white block), has a halo where bloom is on, and lights its surroundings if it should | `material.emissive`, `engine.uniforms.uNight` ([09 §1b](09-materials-lights-models.md#night-glow-emissive-that-follows-daylight)); many lamps: `lightPool` ([09 §1b](09-materials-lights-models.md#1b-lights-and-stalls)) |
40
+ | Light glow / halo | lamps, windows, signs that read as lit | a glowing object keeps its hue at the center (it is not a white block), has a halo where bloom is on, and lights its surroundings if it should | `material.emissive`, `engine.uniforms.uNight` ([09 §1b](09-materials-lights-models.md#night-glow-emissive-that-follows-daylight)); many lamps: `lightPool` ([09 §1b](09-materials-lights-models.md#1b-lights-and-stalls-street-lamps-lightpool)) |
41
41
  | Water, sea | color with depth, waves, foam, what it reflects | shallow and deep read differently, the far sea meets the sky without a seam, foam sits where waves break | `engine.water.shader({ depthColor, foam })`, `engine.water.uniforms.uWave` ([44](44-water-weather-hooks.md)); own: three/addons `Water`, a `ShaderMaterial` ([44 own material](44-water-weather-hooks.md#water-your-own-material-reflections-refraction)) |
42
42
  | Wet ground | streets and stone after rain | wet is darker and glossier together, gloss shows reflections of something bright, puddles have soft edges | no engine picture: read `engine.uniforms.uRain`, then write `material.color`, `material.roughness` ([08 §7](08-weather-sky.md#7-wet-roads-and-puddles-after-rain)) |
43
43
  | Color grading | contrast, saturation and warm / cool shift of the whole frame | the frame has the mood you named; skin, foliage and the player's colors still read | `engine.post.add(lut())` from `@threedog/post-effects`, or `new LUTPass({ lut })` ([52 Post chain](52-around-the-picture.md#post-effect-chain-your-own-pass-extra-render-passes)) |
package/llms.txt CHANGED
@@ -65,7 +65,7 @@ The rest of this file maps tasks to recipe sections.
65
65
  - Many lights (torches); windows, signs at night: docs/recipes/09-materials-lights-models.md §1b
66
66
  - Picture from a reference; judge: docs/recipes/35-picture-from-reference.md §"The loop", 60-judge-the-picture.md
67
67
  - Reuse effects, models of old games: docs/recipes/05-props-bake.md
68
- - Sound, music, ambience: docs/recipes/31-audio.md
68
+ - Sound, music, ambience, bus nodes: docs/recipes/31-audio.md
69
69
 
70
70
  ## Rules, state, time
71
71
 
@@ -331,4 +331,4 @@ export const CAMERA_STRINGS = {
331
331
  en: { 'camera.rotateLeft': 'Rotate view left', 'camera.rotateRight': 'Rotate view right' },
332
332
  };
333
333
 
334
- export const handRolled = [{ kind: 'follow', seen: 'a camera follow of its own', use: 'followCamera() or openWorld({ camera }): collision, smoothing and switching are handled; a shot of your own: engine.takeCamera(owner) (recipe 21)', quiet: /\b(?:follow|firstPerson|fixed|rts)Camera\(|\bopenWorld\(|\b(engine|e|eng|ctx)\.(takeCamera|cameraRig|setCamera)\b/, code: /\bcamera\.position\.(?:lerp|copy|set)\s*\(/, raw: /player|hero|target|character|avatar/i, near: [{ re: /\bonFrame\b|\bonRender\b|\bonFixed\b|requestAnimationFrame|\bupdate\b|\btick\b|\banimate\b/, lines: 12 }] }];
334
+ export const handRolled = [{ kind: 'follow', docRef: 'recipes/21-camera.md', seen: 'a camera follow of its own', use: 'followCamera() or openWorld({ camera }): collision, smoothing and switching are handled; a shot of your own: engine.takeCamera(owner)', quiet: /\b(?:follow|firstPerson|fixed|rts)Camera\(|\bopenWorld\(|\b(engine|e|eng|ctx)\.(takeCamera|cameraRig|setCamera)\b/, code: /\bcamera\.position\.(?:lerp|copy|set)\s*\(/, raw: /player|hero|target|character|avatar/i, near: [{ re: /\bonFrame\b|\bonRender\b|\bonFixed\b|requestAnimationFrame|\bupdate\b|\btick\b|\banimate\b/, lines: 12 }] }];
@@ -348,4 +348,4 @@ export function collision(opts = {}) {
348
348
  } };
349
349
  }
350
350
 
351
- export const handRolled = [{ kind: 'collision', seen: 'a hand-written box overlap', use: 'engine.collision.addBox / addCircle for walls and props (movement, rays and physics read them); engine.collision.walkable to ask', quiet: /\b(engine|e|eng|ctx)\.collision\b/, code: /Math\.abs\([^)]*\)\s*<=?[^&|;]*&&\s*Math\.abs\([^)]*\)\s*<=?|[<>]=?\s*[\w.]*\bmin[XYZ]?\b[^;]*&&[^;]*[<>]=?\s*[\w.]*\bmax[XYZ]?\b/i }];
351
+ export const handRolled = [{ kind: 'collision', seen: 'a hand-written box overlap', use: 'engine.collision.addBox / addCircle for walls and props (movement, rays and physics read them); engine.collision.walkable to ask', quiet: /\b(engine|e|eng|ctx)\.collision\b/, notRaw: /Math\.abs\([^)]*\)\s*<=?\s*\.?\d/, code: /Math\.abs\([^)]*\w\s*-\s*[\w.(][^)]*\)\s*<=?[^&|;]*&&\s*Math\.abs\([^)]*\w\s*-\s*[\w.(][^)]*\)\s*<=?|[<>]=?\s*[\w.]*\bmin[XYZ]?\b[^;]*&&[^;]*[<>]=?\s*[\w.]*\bmax[XYZ]?\b/i }];
@@ -18,7 +18,7 @@ export class DebugPanel {
18
18
  el.className = 'threedog-debug'; el.hidden = !open; // collapsed by default so it does not cover the game HUD
19
19
  el.innerHTML = `<style>
20
20
  .threedog-debug{position:fixed;top:calc(12px + env(safe-area-inset-top,0px));left:max(12px,env(safe-area-inset-left,0px));width:min(290px,calc(100% - 24px));max-height:calc(100% - 24px);overflow:auto;
21
- background:rgba(17,23,20,.82);color:#e9ece0;border:1px solid rgba(226,232,214,.14);border-radius:10px;font:12px/1.5 system-ui,"PingFang SC","Microsoft YaHei",sans-serif;z-index:10;backdrop-filter:blur(8px)}
21
+ background:rgba(17,23,20,.82);color:#e9ece0;border:1px solid rgba(226,232,214,.14);border-radius:10px;font:12px/1.5 system-ui,"PingFang SC","Microsoft YaHei",sans-serif;z-index:var(--threedog-z-debug,10);backdrop-filter:blur(8px)}
22
22
  .threedog-debug .g{display:grid;grid-template-columns:repeat(3,1fr);gap:6px 10px;padding:10px 12px}
23
23
  .threedog-debug .s b{display:block;font:600 15px ui-monospace,Menlo,Consolas,monospace;font-variant-numeric:tabular-nums}
24
24
  .threedog-debug .s span{color:#a2ad9b;font-size:11px}
@@ -347,4 +347,4 @@ export function dialogue(opts = {}) {
347
347
  };
348
348
  }
349
349
 
350
- export const handRolled = [{ kind: 'dialogue', seen: 'a dialogue box of its own', use: 'engine.dialogue.define(speaker, nodes) and the dialogue part: typing on game time, choices, input lock (recipe 02, recipe 26)', quiet: /\b(engine|e|eng|ctx)\.dialogue\b|\bdialogue\(\s*[{)]/, code: /\b(createElement|innerHTML|className|classList|getElementById|querySelector|\.id)\b/, raw: /(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)[^,;{}]*(?:dialog(?:ue)?|speech|subtitle|textbox|conversation)|(?:dialog(?:ue)?|speech|subtitle|textbox|conversation)[^,;{}]*(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)/i }];
350
+ export const handRolled = [{ kind: 'dialogue', docRef: 'recipes/02-npc.md', seen: 'a dialogue box of its own', use: 'engine.dialogue.define(speaker, nodes) and the dialogue part: typing on game time, choices, input lock', quiet: /\b(engine|e|eng|ctx)\.dialogue\b|\bdialogue\(\s*[{)]/, code: /\b(createElement|innerHTML|className|classList|getElementById|querySelector|\.id)\b/, raw: /(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)[^,;{}]*(?:dialog(?:ue)?|speech|subtitle|textbox|conversation)|(?:dialog(?:ue)?|speech|subtitle|textbox|conversation)[^,;{}]*(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)/i }];
@@ -497,4 +497,4 @@ function defineUse(e, ctx, i) {
497
497
  // Why this detection: hand-written interaction often compares Math.hypot(...) < RULES.cartReach next to engine.input.pressed('mine') and engine.hud.hint; a check limited to numeric thresholds and E / interact words missed it.
498
498
  // Two signals needed: a distance comparison (threshold may be a name or a number) plus a nearby player-facing hud.hint, or an E key itself.
499
499
  // Not matched: arbitrary action names or keys: pressed('attack' / 'use') && distanceTo(enemy) < weapon.range is combat reach; toast is a result, not a prompt (it caused a false report on a falling-rock handler).
500
- export const handRolled = [{ kind: 'reach', seen: 'a hand-made reach check for interacting', use: 'engine.interactions.add(target, { ... }): prompt, range and the interact action are handled (recipe 20)', quiet: /\b(engine|e|eng|ctx)\.interactions\b/, code: /(?:\bdistanceTo(?:Squared)?\(|\bMath\.hypot\(|\bdist(?:ance)?\w*)[^;]*<=?\s*[\w.]/, near: [{ re: /KeyE|['"]e['"]|press e\b|\.hud\.hint\(/i, lines: 3, on: 'raw' }] }];
500
+ export const handRolled = [{ kind: 'reach', docRef: 'recipes/03-items-pickups.md', seen: 'a hand-made reach check for interacting', use: 'engine.interactions.add(target, { ... }): prompt, range and the interact action are handled', quiet: /\b(engine|e|eng|ctx)\.interactions\b/, code: /(?:\bdistanceTo(?:Squared)?\(|\bMath\.hypot\(|\bdist(?:ance)?\w*)[^;]*<=?\s*[\w.]/, near: [{ re: /KeyE|['"]e['"]|press e\b|\.hud\.hint\(/i, lines: 6, on: 'raw' }] }];
@@ -264,4 +264,4 @@ export function inventory(opts = {}) {
264
264
  // (2) within 3 lines it is compared to a named capacity limit (< RULES.capacity, >= this.maxSlots, > limit): refusing to add when full is what a bag is.
265
265
  // Numeric literal limits do not count (in a falling-block game `if (bag.length < 7) bag.push(...)` is one round of pieces); count / weight alone do not count (ammo, gravity).
266
266
  // Known limit: (2) is tied to (1) by adjacency, not by the same name, since a regex cannot match names across lines; remaining false positives go in the known list.
267
- export const handRolled = [{ kind: 'inventory', seen: 'a hand-made inventory (items kept in your own array / object)', use: 'the inventory module: engine.use(inventory()), engine.inventory.add / remove / has (counts, containers, events, saved with the game)', quiet: /\b(engine|e|eng)\.inventory\b|\binventory\(\s*[{)]/, code: /\b(?:inventory|backpack|bag|pockets|inv)(?:Items|Slots|List|Contents|Data|Map|Counts?|s)?\s*(?:[=:]\s*\(?\s*(?:\[\s*\]|\{\s*\}|new Map\b|new Set\b)|\.(?:push|splice|unshift|reduce)\()/i, near: [{ re: /[<>]=?\s*(?:[\w$]+\.)*(?:capacity|cap|max\w*|slots?|limit)\w*\b(?!\s*\()/i, lines: 3, on: 'code' }], tags: false }];
267
+ export const handRolled = [{ kind: 'inventory', seen: 'a hand-made inventory (items kept in your own array / object)', use: 'the inventory module: engine.use(inventory()), engine.inventory.add / remove / has (counts, containers, events, saved with the game)', quiet: /\b(engine|e|eng)\.inventory\b|\binventory\(\s*[{)]/, code: /\b(?:inventory|backpack|bag|pockets|inv)(?:Items|Slots|List|Contents|Data|Map|Counts?|s)?\s*(?:[=:]\s*\(?\s*(?:\[\s*\]|\{\s*\}|new Map\b|new Set\b)|\.(?:push|splice|unshift|reduce)\()/i, near: [{ re: /[<>]=?\s*(?:[\w$]+\.)*[\w$]*(?:capacity|cap|max|slots?|limit)\w*\b(?!\s*\()|\b(?:sell|price|gold|coins?|shop)\w*/i, lines: 6, on: 'code' }], tags: false }];
@@ -357,4 +357,4 @@ export function quests(opts = {}) {
357
357
  };
358
358
  }
359
359
 
360
- export const handRolled = [{ kind: 'quests', seen: 'a quest list of its own', use: 'engine.quests (quests()): steps, rewards, markers and the log, saved with the game (recipe 04)', quiet: /\b(engine|e|eng|ctx)\.quests\b|\bquests\(\s*[{)]/, code: /(?:\b(?:const|let|var)\s+|\bthis\.)(?:quests?|questLog|missions?|objectives?)(?:List|Log|Data|s)?\s*=\s*(?:\[\s*\]|\{\s*\}|new Map\b)/i }];
360
+ export const handRolled = [{ kind: 'quests', docRef: 'recipes/04-quests.md §1', seen: 'a quest list of its own', use: 'engine.quests (quests()): steps, rewards, markers and the log, saved with the game', quiet: /\b(engine|e|eng|ctx)\.quests\b|\bquests\(\s*[{)]/, code: /(?:\b(?:const|let|var)\s+|\bthis\.)(?:quests?|questLog|missions?|objectives?)(?:List|Log|Data|s)?\s*=\s*(?:\[\s*\]|\{\s*\}|new Map\b)/i }];