@datamoc/mw_games 0.40.0 → 0.41.0

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 (90) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/REFERENCE.md +2115 -0
  3. package/api-surface.json +48 -0
  4. package/data/microgm-opt.PROVENANCE.md +3 -0
  5. package/data/soundfont-catalog.json +183 -0
  6. package/dist/ai/index.d.ts +10 -0
  7. package/dist/ai/index.d.ts.map +1 -1
  8. package/dist/ai/index.js.map +1 -1
  9. package/dist/ai/lua.d.ts +6 -0
  10. package/dist/ai/lua.d.ts.map +1 -1
  11. package/dist/ai/lua.js.map +1 -1
  12. package/dist/audio/SampleDecoder.d.ts +41 -0
  13. package/dist/audio/SampleDecoder.d.ts.map +1 -0
  14. package/dist/audio/SampleDecoder.js +70 -0
  15. package/dist/audio/SampleDecoder.js.map +1 -0
  16. package/dist/audio/SoundFont.d.ts +59 -0
  17. package/dist/audio/SoundFont.d.ts.map +1 -1
  18. package/dist/audio/SoundFont.js +248 -2
  19. package/dist/audio/SoundFont.js.map +1 -1
  20. package/dist/audio/index.d.ts +3 -1
  21. package/dist/audio/index.d.ts.map +1 -1
  22. package/dist/audio/index.js +2 -1
  23. package/dist/audio/index.js.map +1 -1
  24. package/dist/mw_games.global.js +11 -11
  25. package/dist/mwl/presentation.d.ts +16 -0
  26. package/dist/mwl/presentation.d.ts.map +1 -1
  27. package/dist/mwl/presentation.js.map +1 -1
  28. package/dist/mwl/pyroeis-runtime.d.ts +7 -0
  29. package/dist/mwl/pyroeis-runtime.d.ts.map +1 -1
  30. package/dist/mwl/pyroeis-runtime.js.map +1 -1
  31. package/dist/mwl/pyroeis.d.ts +3 -0
  32. package/dist/mwl/pyroeis.d.ts.map +1 -1
  33. package/dist/mwl/pyroeis.js.map +1 -1
  34. package/dist/physics/PhysicsWorld.d.ts +3 -0
  35. package/dist/physics/PhysicsWorld.d.ts.map +1 -1
  36. package/dist/physics/PhysicsWorld.js.map +1 -1
  37. package/dist/physics/XpbdWorld.d.ts +11 -0
  38. package/dist/physics/XpbdWorld.d.ts.map +1 -1
  39. package/dist/physics/XpbdWorld.js.map +1 -1
  40. package/dist/physics/cloth/index.d.ts +20 -19
  41. package/dist/physics/cloth/index.d.ts.map +1 -1
  42. package/dist/physics/cloth/index.js +19 -0
  43. package/dist/physics/cloth/index.js.map +1 -1
  44. package/dist/physics/spring/index.d.ts +19 -18
  45. package/dist/physics/spring/index.d.ts.map +1 -1
  46. package/dist/physics/spring/index.js +23 -0
  47. package/dist/physics/spring/index.js.map +1 -1
  48. package/dist/three-d/Character3D.d.ts +8 -7
  49. package/dist/three-d/Character3D.d.ts.map +1 -1
  50. package/dist/three-d/Character3D.js +7 -0
  51. package/dist/three-d/Character3D.js.map +1 -1
  52. package/dist/three-d/Collision3D.d.ts +4 -0
  53. package/dist/three-d/Collision3D.d.ts.map +1 -1
  54. package/dist/three-d/Collision3D.js.map +1 -1
  55. package/dist/three-d/Engine3D.d.ts +2 -0
  56. package/dist/three-d/Engine3D.d.ts.map +1 -1
  57. package/dist/three-d/Engine3D.js.map +1 -1
  58. package/dist/three-d/Grid.d.ts +5 -0
  59. package/dist/three-d/Grid.d.ts.map +1 -1
  60. package/dist/three-d/Grid.js.map +1 -1
  61. package/dist/three-d/Heightmap.d.ts +3 -0
  62. package/dist/three-d/Heightmap.d.ts.map +1 -1
  63. package/dist/three-d/Heightmap.js.map +1 -1
  64. package/dist/three-d/TileGrid3D.d.ts +6 -0
  65. package/dist/three-d/TileGrid3D.d.ts.map +1 -1
  66. package/dist/three-d/TileGrid3D.js.map +1 -1
  67. package/dist/three-d/Vox.d.ts +7 -0
  68. package/dist/three-d/Vox.d.ts.map +1 -1
  69. package/dist/three-d/Vox.js.map +1 -1
  70. package/dist/two-d/presentation/MwlPresentation.d.ts +7 -0
  71. package/dist/two-d/presentation/MwlPresentation.d.ts.map +1 -1
  72. package/dist/two-d/presentation/MwlPresentation.js.map +1 -1
  73. package/dist/version.d.ts +1 -1
  74. package/dist/version.js +1 -1
  75. package/package.json +16 -1
  76. package/sbom.cdx.json +139 -139
  77. package/tools/benchmark-browser.mjs +6 -0
  78. package/tools/bundle-size.mjs +4 -0
  79. package/tools/compile-resources.mjs +3 -2
  80. package/tools/init.mjs +3 -1
  81. package/tools/make-example-assets.mjs +4 -0
  82. package/tools/multiplayer-server.mjs +4 -0
  83. package/tools/mwl.mjs +7 -0
  84. package/tools/play-uci.mjs +4 -0
  85. package/tools/sbom.mjs +4 -0
  86. package/tools/soundfonts.d.mts +79 -0
  87. package/tools/soundfonts.mjs +301 -0
  88. package/tools/verify-scenarios.mjs +6 -2
  89. package/tools/vite.mjs +1 -1
  90. package/tools.md +216 -0
package/REFERENCE.md ADDED
@@ -0,0 +1,2115 @@
1
+ # mwg reference
2
+
3
+ A one-line-per-export index of `@datamoc/mw_games`'s public API - what exists and where,
4
+ not how to use it. The published Documentation page is this file rendered as HTML; the
5
+ full generated API (every parameter, every doc comment) lives beside it at
6
+ `webpage/documentation/api/` (both from `npm run webpage:docs`). For *why* the framework
7
+ is shaped this way and what it's for, see `README.md`'s capability spec. For architecture
8
+ and build commands, see `DEVELOPMENT.md`. For the order things shipped in and the reasoning
9
+ behind it, see `CLOSED.md`; for what's still open, see `ROADMAP.md`.
10
+
11
+ Every module is its own barrel: `import { X } from '@datamoc/mw_games/core'` (or the
12
+ matching subpath for any module below), or `import { X } from '@datamoc/mw_games'` for the
13
+ root re-export.
14
+
15
+ **Two rendering worlds, and a core that belongs to neither.** `mwg/two-d` is everything drawn
16
+ through PixiJS (`Game`, `Scene2D`, and the `render`, `ui` and `stage` modules beneath it);
17
+ `mwg/3d` is everything drawn through Babylon. `mwg/core` holds what both need and neither
18
+ renders: the scene lifecycle, `SceneStack`, input, saves, RNG, signals, achievements.
19
+
20
+ **Which entry points reach a renderer**, checked by a test that walks the real import graph
21
+ (`tests/renderer-isolation.test.ts`) rather than by good intentions:
22
+
23
+ | renderer-free | Pixi | Babylon |
24
+ | --- | --- | --- |
25
+ | `core`, `i18n`, `actors`, `world`, `battle`, `simulation`, `roguelike`, `board`, `audio`, `rpg`, `ai`, `mwl`, `assets/paths` | `two-d` (and `two-d/render`, `two-d/ui`, `two-d/stage`), `assets` | `three-d` (the `3d` subpath) |
26
+
27
+ `roguelike` adds only `rot-js`, and `pixi.js`, `@babylonjs/core`/`@babylonjs/loaders` and
28
+ `@capacitor/core` are optional peer dependencies rather than installed ones, so a project names
29
+ only the renderer it actually draws with. A Babylon game importing `core` + `3d` pulls in no Pixi
30
+ at all, and a 2D game importing `core` + `two-d` pulls in no Babylon. `rpg` is renderer-free too:
31
+ its event interpreter takes an injected `DialoguePresenter` rather than building a widget, so
32
+ a 3D game can run map events, dialogue and quests without a 2D renderer anywhere in reach.
33
+
34
+ ## MWL presentation
35
+
36
+ The optional compiler at `@datamoc/mw_games/mwl/presentation` is renderer-free. The
37
+ runtime at `@datamoc/mw_games/two-d/presentation` imports Pixi and is kept off the root
38
+ barrel. The browser consumes compiled data, with no MWL parser or network requests.
39
+
40
+ - `compilePresentation(files, manifest)` validates and compiles top-level
41
+ `theme_definition`, `presentation_context`, `component_variant`, `ui_component` and
42
+ `scene_definition` nodes. It checks named actions/adapters, binding types, assets,
43
+ reusable-component cycles, duplicate IDs, overrides and token references at build time,
44
+ with source-file/line diagnostics. The manifest's asset names must be generated files
45
+ that the game's asset build actually includes.
46
+ - `emitPresentationModule(data)` emits deterministic TypeScript data, `PresentationId`
47
+ (including keyed instance paths) and `PresentationSceneId` literal types. A game's build
48
+ script writes this module plus `data.messages` and `data.assets` into its existing MWL
49
+ artifact pipeline. See `examples/mwl-presentation/generate.mjs`.
50
+ - `MwlPresentation(data, sceneId, options)` mounts existing `Button`, `Label`, `Bar`,
51
+ `Window`, `WindowStack` and `Camera` components. `get(id)`, `focusId`, `palette` and
52
+ `activeContext` expose instances and presentation state. `update(dt)`, `resize(width,
53
+ height)`, `setContext(id)` and `destroy()` drive its lifecycle; `handleAction(action)`
54
+ offers modal windows input first. Register destruction with the owning scene's
55
+ `onDestroy`; it detaches input, theme, controller and adapter subscriptions.
56
+
57
+ Declare the TypeScript manifest with `values: { name: 'string' | 'number' | 'boolean' }`,
58
+ or `{ type: 'items', fields: { id: 'string', text: 'string', selected: 'boolean' } }` for
59
+ collections, plus `actions`, optional `adapters` and `assets` name lists. The runtime's
60
+ `options.state()` supplies those values; `options.actions` implements the named callbacks.
61
+ Repeated-item actions receive the current item, even after reorder. Optional `subscribe`
62
+ returns a disposer, and `translate` resolves authored/gettext text. Asset textures must
63
+ be loaded before mounting. `PresentationAdapter` exposes a view plus optional `update`,
64
+ `resize`, `restyle` and `destroy`: the runtime destroys the view, while the adapter
65
+ detaches its own subscriptions. Cleanup continues even if an adapter throws.
66
+
67
+ Scenes contain `scene_camera` (zoom, position or fit dimensions), `scene_layer` (world or
68
+ screen space, optional generated image or named procedural adapter) and UI trees.
69
+ `ui_mount` expands a reusable component at build time. UI trees use `ui_container`,
70
+ `ui_row` (wrapping by default), `ui_column`, `ui_grid` (equal grow columns), `ui_label`,
71
+ `ui_button`, `ui_bar`, `ui_window`, `ui_repeat` and `ui_adapter`. Every node has an `id`;
72
+ runtime paths start with the scene ID and join descendant IDs with `/`. Repeats insert
73
+ the URI-encoded stable key before their single template child's ID, preserving instances
74
+ and focus on updates. A reusable component using item fields may declare `items_binding`
75
+ so even an unused template can be validated against its collection.
76
+
77
+ Properties include pixel dimensions, anchors, offsets (`x`, `y`), spacing, alpha and
78
+ semantic color tokens. Bindings use `text_binding`, `title_binding`, `value_binding`,
79
+ `max_binding`, `color_binding`, `visible_binding`, `selected_binding` and
80
+ `disabled_binding`; item fields use `item.field`. Buttons name an `action`, windows may
81
+ name a `close_action`, and repeats declare `items_binding` plus a string/number `key`.
82
+ Window close actions should update the controller's visibility binding. Closed windows
83
+ stay closed until their visibility transitions false then true; reopening creates a
84
+ fresh window, because existing `Window.close()` destroys its contents.
85
+
86
+ Themes require `panel`, `text`, `accent`, `success`, `warning`, `danger` and `selection`
87
+ 24-bit color tokens; games may add scenery tokens and choose font/padding metrics.
88
+ Text/panel contrast must reach 4.5, and danger/selection against panel must reach 3.
89
+ Contexts choose a theme and may override tokens or authored-node properties using
90
+ `ui_override.target`, such as `component:controls/toolbar` or `scene:bridge/decor`.
91
+ Image overrides on scene layers select generated scenery. Precedence is base properties,
92
+ context overrides, component variant, then `ui_state` (`idle`, `hover`, `pressed`,
93
+ `disabled`, `selected`, `focused`). A game's biome schema selects a context; MWG defines
94
+ no biome rules. Context switches preserve mounted adapters and controller state.
95
+
96
+ One active presentation owns the existing global UI theme. Destruction restores its prior
97
+ theme if nobody replaced it meanwhile. Existing widgets also expose local palette updates:
98
+ `Button.setColors` (`ButtonColors`), `Window.setColors` (`WindowColors`) and
99
+ `Bar.setBackground`, for variants that must follow token changes without remounting.
100
+
101
+ ## Conventions
102
+
103
+ Three rules the whole API follows, so a name means one thing everywhere:
104
+
105
+ - **`advance(turns)` moves a clock forward in whole turns or rounds; `update(dt)` moves one
106
+ forward in real seconds.** `TurnClock`, `Charges`, `Field`, `Barrier` and `AbilityCycle`
107
+ take turns; everything in `render`, `ui`, `audio` and `world.EnvironmentClock` takes `dt`.
108
+ Anything that is not time passing gets its own verb rather than borrowing one of these
109
+ (`QuestLog.advanceStage`, `BossPhases.check`).
110
+ - **`toJSON()` / `static fromJSON(defs, data)` is how a class saves and reloads.** Definitions
111
+ a game owns (item tables, quest definitions, growth curves, terrain kinds) are supplied
112
+ fresh as `defs` rather than written into the save, so rebalancing reaches old saves.
113
+ Namespace-level state uses `exportX`/`importX` free functions instead (`Input` bindings);
114
+ `Random.Generator` keeps `getState`/`setState`, which resumes a live stream in place rather
115
+ than producing a payload.
116
+ - **"Nothing to pick" is always `null`**, never `-1` or `undefined`: `Random.weighted`,
117
+ `Random.element`, `Random.weightedKey`, `rollEncounter`, `rollLoot`, `rollAffix`,
118
+ `pickBuilder`.
119
+
120
+ ## Contents
121
+
122
+ [core](#core) · [two-d](#two-d) · [render](#two-drender) · [ui](#two-dui) · [stage](#two-dstage) ·
123
+ [assets](#assets) · [audio](#audio) · [battle](#battle) · [board](#board) ·
124
+ [actors](#actors) · [roguelike](#roguelike) · [rpg](#rpg) · [simulation](#simulation) ·
125
+ [three-d](#three-d-optional) · [world](#world) · [i18n](#i18n) · [mwl](#mwl) · [mwl/pyroeis](#mwlpyroeis) ·
126
+ [skeleton](#skeleton) · [physics](#physics) · [ai](#ai) ·
127
+ [testing](#testing) · [threads](#threads) · [headless](#headless)
128
+
129
+ ## `core`
130
+
131
+ The scene lifecycle, signals, RNG, input, and every save/telemetry/replay primitive - the one
132
+ module every game imports, whichever renderer it uses, and the only one that depends on no
133
+ other `mwg` module and no renderer at all.
134
+
135
+ - `Scene` - one screen of the game, as lifecycle only: `create`, `update(dt)`, `resize`, the
136
+ `onSuspend`/`onResume` pair a pushed scene needs, and a `destroy` that fires once. It owns
137
+ no display node; `two-d.Scene2D` adds the Pixi container, and a Babylon game supplies its own.
138
+ - `SceneStack` - `push`/`pop`/`replace`: suspends the current scene, layers another over or
139
+ instead of it, and resumes with a result once it pops (minigames, pause menus). Generic over
140
+ the scene type and typed against the lifecycle above, so it drives a 3D game just as well.
141
+ - `SceneComponentHost`/`SceneComponent` - composes a scene out of named sections (map logic,
142
+ encounter logic, UI wiring), each its own module implementing whichever `Scene` lifecycle
143
+ hooks it needs, instead of one scene class accreting every responsibility. A scene owns one
144
+ host and forwards `update`/`resize`/`onSuspend`/`onResume`/`destroy` to it - composition, not
145
+ a base class, so it works the same whether the scene extends `Scene` or `two-d.Scene2D`.
146
+ - `Registry` - a named lookup registered once and read back by name: `register`/`get`/`has`/
147
+ `list`, throwing on a duplicate or missing name by that name. The dispatch primitive
148
+ underneath a catalog of factories or handlers (`SceneComponentHost` uses one internally) -
149
+ a game still imports and registers each entry itself, no auto-discovery.
150
+ - `createHandles`/`Handles` - numeric leases for values a plain-data command cannot carry
151
+ (callbacks, RNG streams, query closures): `put` stores a value and returns its id, `get`
152
+ resolves it, `drop`/`clear` end leases, and `with` scopes a lease so the drop runs even
153
+ when the body throws. Ids start at 1 and are never reused.
154
+ - `Logger` - categories, four severity levels, a filter, and a sink tests can capture,
155
+ instead of bare `console.log`/`console.error`.
156
+ Three shapes cover what "an event" means here, kept deliberately distinct rather than folded
157
+ into one bus: a **GameEvent** is a rule's ordered *output* - what happened, described after the
158
+ fact - realised as the generic `Event` type parameter `simulation`'s `SimulationRule`/
159
+ `SimulationRuntimeRule` already return, never something a handler reacts to mid-calculation. A
160
+ **Hook** (`HookRegistry`, below) is a point of *modification* a rule consults while it runs -
161
+ `modifyDamage`, "can this creature act this turn" - synchronous, and read back by the same rule
162
+ that asked. A **Signal** is a plain *notification* with no bearing on any rule - `sceneChanged`,
163
+ `saveCompleted`. Reaching for a global bus that several `AttackRequested`/`DamageCalculated`/
164
+ `HpChanged`-style events all dispatch onto, each triggering the next, is the shape to avoid: it
165
+ turns a rule's synchronous, readable logic into a chain no single function owns.
166
+
167
+ - `Signal` - a typed event emitter: one event, one payload, LIFO listeners, and a listener
168
+ can consume it.
169
+ - `HookRegistry`/`Hook` - many events keyed by name, dispatched in registration order, with a
170
+ `source` tag so everything one ability or worn item registered comes off in a single
171
+ `offSource` call. `battle.BattleHooks` and `roguelike.CombatHooks` are both this with their
172
+ argument types fixed; they were two copies of one class until they were merged.
173
+ - `PresentationQueue` - plays a batch of simulation events one at a time, at whatever pace
174
+ `play(event)` (a tween, a sound, a floating number) says to wait before the next - the
175
+ presentation-side counterpart to a `SimulationRuntime.dispatch()`/`runScenario()` result, kept
176
+ out of the logical commit that already happened. The same queued/timed shape as `two-d.ui.
177
+ Toast`, generalised to any event type and needing no renderer.
178
+ - `parseCSV`/`CsvOptions`/`CsvColumnType` - a header-row CSV into an array of typed row
179
+ objects, so a content designer edits a spreadsheet instead of a `.ts` object literal for a
180
+ table shaped like `actors.AffixTable`. `columns` names which fields coerce to
181
+ `'number'`/`'boolean'`/`'list'` (semicolon-separated)/`'map'` (semicolon-separated
182
+ `key=value` pairs); an empty cell omits that field entirely, the same as an optional
183
+ property never set. Takes a raw string with no opinion on how it was loaded, the same
184
+ boundary `i18n.parseFTL` already draws.
185
+ - `clamp` - `value` restricted to `[min, max]`. Shared so `two-d.render.Camera`'s bounds
186
+ clamp and `rpg.Collision`'s tile-edge resolver stop being the same three-line function
187
+ written twice.
188
+ - `parseDialogueLines`/`DialogueLine` - the terse `@id text`/`-`-alternation dialogue-text
189
+ parsing engine behind both `two-d/stage.parseDialogueText` and `rpg.parseDialogueText`, so
190
+ the two-speaker state machine lives once instead of twice: each module's own wrapper only
191
+ renames `DialogueLine.speaker` onto its own command shape (`StageCommand.as` versus
192
+ `EventCommand.speaker`).
193
+ - `parseTwee`/`TweeCommand`/`TweeChoice`/`TweeStory` - the Twee-notation parsing engine
194
+ behind both `two-d/stage.importTwee` and `rpg.importTwee`, for the same reason: passages,
195
+ `[[links]]` and `StoryData`/`StoryTitle` parse once here, and `TweeCommand`/`TweeChoice`
196
+ are structurally compatible with both `StoryScript`/`StageChoice` and
197
+ `EventStoryScript`/`EventChoice`, so each module's wrapper needs no per-field conversion.
198
+ - `Random` (namespace) - seeded RNG: `int`, `float`, `weighted`, `element`, `shuffle` and the
199
+ rest; every "pick one" returns `null` when there is nothing to pick.
200
+ - `Generator` - the seeded RNG class `Random` wraps directly, for a game that wants its own instance.
201
+ - `JavaRandom`/`JavaRandomDraw`/`JavaRandomOptions` - `java.util.Random`'s 48-bit generator bit for bit
202
+ (`nextInt`, `nextInt(bound)`, `nextLong`, `nextDouble`, `nextFloat`, `nextBoolean`), so a
203
+ game ported from the JVM replays the same seed; `onDraw` logs every underlying draw for a
204
+ parity diff against a JVM run. Not for general use, that is `Generator`.
205
+ - `MersenneTwister`/`MersenneTwisterState` - MT19937 with `mt_rng`'s `seed`/`discard`/
206
+ `discardCount` bookkeeping, for a port that consumes the reference's raw 32-bit stream; the
207
+ engine matches the standard test vector, while the int mapping is MWG's own unbiased
208
+ reduction (C++'s `uniform_int_distribution` is implementation-defined).
209
+ - `RandomStreams` - named, independent MT19937 streams over one base seed, so a loot draw and
210
+ an AI draw never shift each other, with `getState`/`setState` for a save and `reseed`.
211
+ - `Input` (namespace, so `Input.onAction`, not a bare `onAction` import) - named-action input: `bind`/`isDown`/`justPressed`/`justReleased`
212
+ over keyboard, `bindButton`/`bindAxis`/`pollGamepads` over a gamepad,
213
+ `bindTouch`/`pressTouch`/`releaseTouch`/`attachSwipe` over touch, `attachPointer` for
214
+ down/move/drag/up signals with target-relative and (through `toWorld`) world positions, `actionsForKey` for
215
+ rebind-conflict detection, `rumble` for gamepad haptics. `onText` carries the character a
216
+ key press produces (via `textFromKey`/`dispatchText`) and `onAction` the named action a
217
+ key fires, each with its own programmatic counterpart (`dispatchText`,
218
+ `dispatchAction`) so an on-screen keyboard feeds the same signals a physical key
219
+ travels; `onComposition` follows an IME through `start`/`update`/`end`, so a free text
220
+ field can be built on top.
221
+ - `PlayerInput` - a per-player scoped `Input`, for local multiplayer/split-screen.
222
+ - `StoredValue`/`defaultStorage` - one JSON value under one storage key (`read(fallback)`/
223
+ `write`/`remove`) over the same storage `SaveSystem` uses: a game's structured progress or
224
+ best scores without a save slot.
225
+ - `FixedStepper` - turns the variable `Scene.update(dt)` into fixed simulation steps
226
+ (`advance(dt, tick)`, a `maxSubsteps` cap, `alpha` for interpolated drawing): the deterministic,
227
+ refresh-rate-independent loop a physics solver or lockstep game needs.
228
+ - `SaveSystem` - named, versioned save slots over `localStorage` (in-memory fallback under
229
+ `file://`); a `migrations` chain, and `importExternal` as a plug-in point for a foreign
230
+ save format's own `normalize` function. `load`, `list` and `importSlot` read every slot
231
+ through `parseInbound` plus a `{ meta: { version, savedAt }, state }` shape check: a
232
+ corrupt or tampered slot loads as `null` and is left out of `list`.
233
+ - `StateRegistry`/`StateExtension`/`StateRestoreDiagnostic` - named game-owned state extensions with deep-cloned
234
+ snapshots and transaction rollback, with independent versions, ordered migrations and
235
+ explicit handling of extensions absent from a restored save, so custom save data has one
236
+ atomic boundary.
237
+ - `ActionJournal` - serializable ordered action and outcome batches with checkpoints,
238
+ incremental reads, truncation and validated restore for replay, undo and synchronization.
239
+ Actions and events are copied on `append`, so both must be plain data.
240
+ - `cloneData`/`uncloneablePath` - `structuredClone` with an error naming the first value that
241
+ cannot be copied (`action.target.reactions.rules[0].when`), and that path on its own. The
242
+ journal and `simulation.SimulationRuntime` use it, so a command carrying a live actor fails
243
+ with where and why instead of a bare `DataCloneError`.
244
+ - `scramble`/`unscramble` - light save-data obfuscation, not encryption.
245
+ - `SaveSyncClient` - pushes/pulls save data to a server the game supplies.
246
+ - `LockstepClient` - deterministic multiplayer over an injectable WebSocket, tick-driven.
247
+ Server messages are size-capped (`maxMessageBytes`, 1 MB) and type-checked; a malformed one
248
+ is dropped and reported on `onProtocolError` instead of throwing out of `onmessage`.
249
+ - `stateChecksum`/`SyncGuard` - out-of-sync detection for lockstep: a key-order-stable 32-bit
250
+ checksum of JSON state, and a guard comparing the checksums two peers compute for each tick,
251
+ recording the first tick they disagree on.
252
+ - `RunHistory` - a local record of completed runs (score, cause of death, whatever a game's
253
+ own `summary` holds), distinct from `SaveSystem`'s continuable slots.
254
+ - `PlayerStats` - a lifetime running total folded in one run's summary at a time, distinct
255
+ from `RunHistory`'s per-run records.
256
+ - `TelemetryClient` - sends usage/error events to a server the game supplies.
257
+ - `NewsClient`/`NewsSeenTracker` - a game's own patch-notes/announcement feed, with a
258
+ seen-tracker so a player is only notified of what's actually new.
259
+ - `checkSize`/`checkNoControlCharacters`/`sanitizeInboundText`/`validateSchema`/`parseInbound` -
260
+ security sanitization of inbound data: an imported save, a network payload, player-typed
261
+ text. `parseInbound` is the whole pass in one call (size, control characters, `JSON.parse`
262
+ refusing `__proto__`/`constructor`/`prototype` at any depth), and every `core` reader of
263
+ JSON it did not just produce uses it: save slots, `Collection`, stored values, settings,
264
+ `NewsClient` and `LockstepClient`. Under `file://` Chromium shares one `localStorage`
265
+ between every local page, so a game's own storage is inbound data too.
266
+ - `Collection` - named, queryable record collections over `localStorage`
267
+ (`all`/`get`/`put`/`remove`/`where`/`clear`) - a quest log or bestiary, not a save blob.
268
+ - `Recorder`/`Player`/`serializeReplay`/`deserializeReplay` - records `Input.onAction`
269
+ against `Game`'s own frame counter and replays it deterministically, for testing.
270
+ Both resume mid-run: `Recorder` takes `fromFrame` so a restored run continues its
271
+ recording where the checkpoint left it, and `Player` takes `fromFrame` so playback
272
+ skips what the restored state already contains. `parseReplayEvents` validates an
273
+ already-parsed event array, the half of the check `deserializeReplay` applies after
274
+ its own `JSON.parse`.
275
+ - `exportReplayFile`/`importReplayFile`/`LastRun`/`runCheckpoint`/`resumeRunPlayer` -
276
+ a run made durable (roadmap 396). The file is a versioned, self-describing envelope
277
+ (`format: 'mwg-replay'`, `version`, `framework`, `game`, optional `seed` and
278
+ `recordedAt`, `events`), and import refuses another game or another framework build
279
+ by name, treating the file as inbound data the way a save slot is treated.
280
+ `LastRun` keeps the newest recording, one deep and bounded, through the same storage
281
+ a save slot uses; `runCheckpoint(recorder, state)` pairs the partial recording with
282
+ the game state a save already captured, and `resumeRunPlayer` turns the restored
283
+ checkpoint back into a mid-run `Player`. The `file://` plumbing rides along:
284
+ `downloadReplayFile` is a Blob download (no `fetch()`), `pickReplayFile` is the file
285
+ picker resolving null on cancel, and `readReplayFile` reads any `Blob`, headless
286
+ Node included.
287
+ - `Achievements` - counters crossing a target unlock a named milestone; `drainNew()`
288
+ queues unlocks for a UI to announce. An achievement can name several `criteria`
289
+ instead of one `counter`/`target` (item 273's sub-achievements, "recruit every unit
290
+ type"), unlocking only once every criterion is met; `subProgress` reads them individually.
291
+ - `Settings`/`GameSettings`/`SettingsOptions`/`CustomSettingValue` - persisted player
292
+ settings over the same storage `SaveSystem` uses (in-memory fallback under `file://`):
293
+ music and sound-effect levels, master mute, zoom preference, key bindings (applied to
294
+ `Input` on load), and a game-defined `custom` bag for the rest (`hints`, `violence`,
295
+ ...). `defaultSettings` names the fresh-game values, `effectiveMusicVolume`/
296
+ `effectiveSfxVolume` read 0 while muted, corrupt storage reads as defaults.
297
+ - `Session` - counts launches over the same storage `SaveSystem` uses, for a native
298
+ wrapper's own rating-prompt timing; never prompts itself.
299
+ - `FeedbackClient`/`HttpTransport`/`HttpTransportOptions` - an injectable HTTPS JSON transport for
300
+ player-submitted feedback; the game owns the endpoint, consent flow, and server-side storage.
301
+ Every `HttpTransportOptions` client (`FeedbackClient`, `NewsClient`, `SaveSyncClient`,
302
+ `TelemetryClient`) and `LockstepClient` refuses an `http:`/`ws:` url to anything but
303
+ `localhost`/`127.0.0.1`/`[::1]` unless `allowInsecure: true`, and a response body is read up
304
+ to `maxResponseBytes` (10 MB), refused as soon as it passes the limit.
305
+ - `Spawner` - a `dt`-driven, timed, escalating wave spawner (a horde mode, a survival
306
+ minigame), distinct from `roguelike.Scheduler`'s turn-order primitive.
307
+ - `hexNeighbors`/`hexDistance`/`hexLine`/`hexRange`/`hexToPixel`/`pixelToHex` with
308
+ `HexShape`/`HexOrientation`/`HexOffset` - hex grid geometry: cube-based neighbours, lines and
309
+ ranges, and the pixel projection in both orientations and both offset parities, defaulting to the
310
+ flat-top odd-q layout this module always had. `pixelToHex` answers with the nearest cell centre
311
+ rather than a closed-form inverse per combination, so it cannot disagree with `hexToPixel` at a
312
+ hex's edge.
313
+ - `weightedFlood`/`WeightedCell`/`WeightedFloodOptions` - renderer- and rules-neutral Dijkstra
314
+ flood over any cell topology, with injected costs, blockers, budget and stopping rules.
315
+ - `cellInside`/`cellIndex`/`cellX`/`cellY`/`cellKey`/`cellFromKey` - bounded-grid indexing:
316
+ the row-major arithmetic and bounds check that `roguelike.Level` and the `board` modules used
317
+ to spell out for themselves, now stated once (the Wesnoth port asked for exactly this, to stop
318
+ duplicating it in its own systems). `cellInside` is the shared bounds check and `cellIndex` is
319
+ deliberately *unchecked* arithmetic, so a loop that has already proved its coordinates pays
320
+ nothing while a module that wants a throw or a `-1` keeps that policy in its own method;
321
+ `cellKey`/`cellFromKey` are the `'x,y'` spelling for `Map`/`Set` membership.
322
+ - `NEIGHBOURS4`/`NEIGHBOURS8`/`CIRCLE8`/`euclidean`/`chebyshev` - one frozen offset table per square
323
+ neighbourhood, shared instead of copied: axial north/east/south/west, the eight
324
+ surrounding cells in row-major order, and the same ring clockwise from north (the
325
+ sequence `roguelike`'s `neighbourOffsets(8)` always returned, now returned as-is from
326
+ here). `euclidean` is the straight-line ruler, `chebyshev` the king-move one (a
327
+ diagonal costs one step), and `manhattan` the orthogonal-step count; `distance` measures
328
+ with the ruler a `DistanceMetric` names, so a data-authored rule picks its geometry by
329
+ name. `roguelike`'s `chebyshevDistance` delegates to `chebyshev`.
330
+ - `Blob` - a spreading volume field over a grid: a per-cell number that `spread` diffuses a
331
+ share of into its open 4-neighbours and decays the rest (`decay: 1` conserves and only
332
+ moves volume around). `seed` adds to a cell, `clear` zeroes one cell and leaves its
333
+ neighbours alone, and `cellsAbove` lists what a game applies its effect on; what a volume
334
+ means (fire, gas, ooze, water) stays the game's own reading.
335
+ - `reducedMotion`/`setReducedMotion`/`prefersReducedMotion`/`watchReducedMotion` - the one
336
+ answer to "should this animate": the OS `prefers-reduced-motion` preference, overridable per
337
+ game, with a change subscription for something long-lived that has to stop mid-flight.
338
+ `motionDuration(duration, intent)` is the policy built on it, and `MotionIntent` is the
339
+ caller's declaration: a `decorative` motion (the default) collapses, a `meaningful` one is
340
+ shortened rather than deleted, because a change that motion conveys stays readable. `Tweener`,
341
+ `Camera` (shake and follow), `ScreenEffects`, `ParticleEmitter` and `FloatingText` consult it.
342
+ `AnimatedSprite` deliberately does not: a frame cycle is usually game state.
343
+ - `Tweener`/`Easing`/`TweenOptions` - a generic `tween(duration, apply, ease?)` plus a small
344
+ linear/quad/cubic easing-curve set. The third argument also takes `{ ease, intent, alternate }`:
345
+ `alternate` is the non-vestibular variant to run instead under reduced motion (a fade where a
346
+ slide was), and it is ignored while the preference is off.
347
+ - `UndoHistory` - gameplay-level undo/redo over pushed, reference-held states.
348
+ - `LoadQueue` - a reusable loading-screen lifecycle: named tasks, aggregate progress,
349
+ cancellation.
350
+ - `EntityRegistry`/`EntityId` - assigns and looks up stable string ids for live objects, so
351
+ events, saves, AI targets and buffs can name a creature or item without holding it; not an
352
+ ECS, and distinct from `Collection`'s persisted, queryable records. `idOf` is what a game
353
+ passes as `roguelike.Scheduler.toJSON`'s or `simulation.SimulationRuntime`'s `actorId`.
354
+ - `ReactionTable`/`ReactionRule` - declarative `when`/`action` rules checked against any
355
+ state shape (a `StatBlock`'s values, a plain object's own fields), firing edge-triggered
356
+ so a still-true condition never re-fires; `once` retires a rule after its first firing. The
357
+ generic alternative to a branch cascade of `if HP < n` checks in game code, and works the
358
+ same for a character or an inanimate object such as an item's durability.
359
+
360
+ ## `two-d`
361
+
362
+ Everything drawn through PixiJS, and the counterpart to `three-d`. The barrel re-exports
363
+ `render`, `ui` and `stage` below, so `mwg/two-d` is a one-stop 2D import; the granular
364
+ subpaths (`mwg/two-d/render`, `mwg/two-d/ui`, `mwg/two-d/stage`) are what a game watching its
365
+ bundle should reach for.
366
+
367
+ - `Game` - owns the Pixi `Application`, the frame loop, and the current scene; reachable as
368
+ the singleton `Game.current`. `step(dt)` drives one frame by hand, which defeats Chrome's
369
+ background-tab throttling of `requestAnimationFrame`. With `autoPause` (the default) it
370
+ suspends the loop and silences its `audio` rig (`AudioSuspendRig`, an `Orchestrator`
371
+ fits) on page hide and resumes both on show, via `suspend`/`resume`: the clock parks at
372
+ 0, the top scene hears `onSuspend`/`onResume`, and the player's mute setting is never
373
+ touched. `qualityScaling` steps the backing-store ratio down after sustained
374
+ over-budget frames (and back up only after a much longer streak inside budget) via a
375
+ `QualityScaler` over the static fit, off unless given. It draws at the display's
376
+ `devicePixelRatio`, reduced to the largest whole number whose backing store fits the device's
377
+ `MAX_TEXTURE_SIZE`, with a warning naming the limit when that happens: WebGL clamps a larger
378
+ request silently, so a device with a small limit renders softer rather than not at all.
379
+ - `Scene2D` - `core.Scene`'s lifecycle plus the `stage` container everything this screen draws
380
+ hangs off, destroyed with the scene. This is what a 2D game extends.
381
+
382
+ ### `two-d/render`
383
+
384
+ Pixi-backed 2D rendering: sprites, tile maps, camera, animation. All Pixi
385
+ batcher/high-shader internals are confined to `ColorTransformBatcher.ts`.
386
+
387
+ - `ColorTransformBatcher`/`packColorAdd`/`packTintAdd`/`NO_COLOR_ADD` - a per-sprite
388
+ `texel × M + A` colour transform (multiply *and* add) in the batch shader.
389
+ - `TintedSprite`/`registerColorTransform` - a sprite drawn through the colour-transform
390
+ batcher; register the extension once via `GameOptions.extensions`.
391
+ - `parseImagePath`/`imageModifier`/`colorShiftMatrix`/`applyImageModifiers`/`croppedTexture` - parses common
392
+ image suffix modifiers such as `~FL`, `~GS`, `~SCALE` and `~CROP`, then applies the supported
393
+ Pixi presentation changes without mutating shared source textures. `channelScaleMatrix`
394
+ (`~R`/`~G`/`~B`) builds the `ColorMatrixFilter` matrix `applyImageModifiers` also applies for
395
+ `~O` (opacity) and `~CHAN` (`channelSwapMatrix` - a channel-source swap/constant, not
396
+ Wesnoth's own per-channel formula language). `applyTextureModifiers`/`ImageTextureProbe`
397
+ cover the modifiers that need real pixel access, a sibling texture, or have to rotate the
398
+ actual art rather than a sprite transform: `~RC`/`~PAL` (exact palette swap - see
399
+ `recolorTexture` below - accepting hex or, via `probe.resolveColor`, a named colour;
400
+ `parseColorPairs`/`parsePaletteLists` are the argument parsers, the latter reconstructing
401
+ `~PAL`'s two comma-separated colour lists since `parseImagePath`'s own comma split does not
402
+ respect that list boundary), `~BLIT`/`~MASK` (composite/mask against a `probe.resolveTexture`-
403
+ resolved sibling texture at an offset - it receives the argument exactly as written, nested
404
+ modifiers included, not a bare path; `maskPixels` is `~MASK`'s renderer-free alpha-multiply
405
+ core), `~BLEND` (`blendPixels`, an exact per-pixel lerp towards a colour, baked once - not the
406
+ runtime `ColorMatrixFilter` approximation `blendMatrix` still offers on its own) and `~ROTATE`
407
+ (`rotatePixels`, which rotates the source pixels and expands the surface, unlike a sprite's own
408
+ `rotation`; `~ROTATE(degrees)` samples nearest-neighbour, exact at quarter turns, and
409
+ `~ROTATE(degrees,linear)` blends the four pixels around each sample point instead - what a
410
+ non-square angle onto a hex grid needs. `parseRotateMode` is the second argument's parser, and
411
+ both modes sample premultiplied so a transparent neighbour contributes coverage and never
412
+ colour. It is bake-time work: measured, `linear` costs 2.4 to 4.2 times `nearest` per image -
413
+ 0.45 ms against 0.12 ms for a 64x64 tile at 60 degrees, 3.6 ms against 1.5 ms at 256x256 - for a
414
+ visibly smooth edge, once, while the texture is built).
415
+ `spriteColorMatrix(sprite, matrix)` (item 309) attaches any of the matrix
416
+ builders above (or `blendMatrix`, or a game's own) to a sprite as a `ColorMatrixFilter`, the
417
+ one remaining case that needed a direct `pixi.js` import just to construct that one class.
418
+ `applyAllImageModifiers(sprite, parsed, probe?, scale?)` (item 310) is the two-step recipe
419
+ `applyImageModifiers`'s own doc comment names, run for a caller in one call: it bakes
420
+ `applyTextureModifiers`'s exact pixel-level result into `sprite.texture` first, then applies
421
+ the sprite-property/filter modifiers on top, so a `~BLEND`/`~ROTATE` path never silently gets
422
+ `applyImageModifiers`'s no-op for them.
423
+ - `remapPixels`/`paletteRangeMapping`/`recolorTexture`/`withTextureCanvas`/`PaletteMapping`/
424
+ `PaletteRange`/`PaletteRemapMode` - palette-remap recolouring (team colour by range, not
425
+ multiply/add): `remapPixels` is the renderer-free core, `'exact'` by default (a pixel is
426
+ repainted only on an exact match to a `from` colour, correct for a short specific list like
427
+ `~RC`/`~PAL` and for a `paletteRangeMapping` over a reference palette, where the pixels outside
428
+ it are the ones the art deliberately left alone) or `'nearest'` (every opaque pixel repainted by
429
+ closest match, which a palette covering the whole image wants - the wrong mode for a sparse
430
+ list, where it silently recolours the entire image). `paletteRangeMapping` builds a
431
+ `[color_range]`-shaped mapping: the reference palette's *first* colour is its anchor and becomes
432
+ `mid`, and every other entry is shaded by its own brightness, darker towards `min` and brighter
433
+ towards `max`, with the floored average and truncated blend a Wesnoth `[color_range]` team
434
+ colour is defined in, so a range's shades come out byte for byte as the engine's own. The
435
+ reference after its anchor needs no order. `recolorTexture` is the canvas-backed wrapper, built
436
+ on the shared `withTextureCanvas` helper `applyTextureModifiers` above also uses.
437
+ - `AnimatedSprite`/`Animation` - frame-sequence sprite animation. A frame may carry its own
438
+ duration (Wesnoth's `image=a.png:120,b.png:80`), and an animation may start partway into itself
439
+ or after a delay (`startTime`, which is what `start_time=-450` on an attack means: begin four and
440
+ a half frames in, so the hit lines up with the damage frame). A frame may also carry an offset,
441
+ reported through `AnimatedSprite.frameOffset` for the caller to add where it positions the sprite,
442
+ because that position is the caller's (`GridMover`, a walk tween) and a sprite that overwrote it
443
+ every frame would undo it every frame.
444
+ - `SpriteGroup`/`isOnScreen` (item 369) - animate only what is on screen: `update(camera, dt)`
445
+ advances the members inside `camera.view` (plus `margin`) and leaves the rest on their current
446
+ frame, so a crowd of `AnimatedSprite`s (or `ParticleEmitter`s, which satisfy the same
447
+ `SpriteGroupMember` shape) costs no CPU off screen. Never freezes anything visible: under a
448
+ rotated camera the tested box is the over-inclusive one `TileMap.cull` uses.
449
+ - `SpriteSheet` - a grid-sliced sprite sheet, or, built with no frame size, one whose frames are
450
+ its own `rect(index, x, y, width, height)` declarations: a hand-packed icon atlas, a strip of bar
451
+ segments, an item whose art is smaller than its cell. A rect is cached under its index like any
452
+ grid frame, so `get`/`region`/`name`/`pick` treat the two the same and no site hand-builds a
453
+ `Texture`.
454
+ - `Camera`/`createCamera`/`snapZoom` - world-to-screen camera; `snapZoom` keeps tile edges
455
+ pixel-aligned at a fractional zoom. Fixed-angle view rotation (item 285): `grid` picks four
456
+ quarter turns (square, the default) or six 60-degree steps (hex), `setRotationStep`/`rotate`
457
+ move through them, `toScreen`/`toWorld` invert the turn so a click still lands on the cell aimed
458
+ at, `view` reports the box around the turned viewport for culling, and `uprightRotation` is the
459
+ angle that keeps a label drawn into the world upright. Free rotation (item 286): `rotateTo` turns
460
+ to any angle immediately and `animateRotationTo` eases towards one, shorter way around the turn,
461
+ sharing the same angle and the same `toScreen`/`toWorld`/`view` math the stepped API uses.
462
+ `shakeScreen(intensity, duration)` (item 303) is `shake` taking screen pixels instead of world
463
+ units, dividing by the current `zoom` once so a caller thinking in screen pixels (a convention
464
+ several engines use for this call) does not have to at every call site.
465
+ - `Viewport`/`splitScreenHalves` - a camera scoped to one screen region, for split-screen.
466
+ - `createColorBlindnessFilter`/`COLOR_BLINDNESS_MATRICES` - accessibility colour filters.
467
+ - `Minimap`/`newlyRevealed`/`minimapCellCenter`/`MinimapMarker` - bakes an explored-cell set
468
+ into a persistent `RenderTexture`, never redrawing an already-baked cell, and supports
469
+ several game-owned unit or quest markers.
470
+ - `TileMap`/`EMPTY`/`tileFrame`/`tileFrameSheet`/`tileFrameIndex` - tile map rendering:
471
+ square/hex/isometric/staggered projections, multi-sheet tiles, elevation columns.
472
+ - `LayeredSprite` - layered character sprites (body/hair/equipment as separate layers).
473
+ - `SkeletalSprite`/`ArticulatedChain`/`ChainRig` (items 399/400) - bones driving drawn
474
+ parts: the pose math lives in the renderer-free `skeleton` module (bone tree, keyframed
475
+ clips, crossfade, priority layers), `SkeletalSprite` binds a part to a bone by name and
476
+ `update(dt)` places it at the bone's world transform, and `ArticulatedChain` is the
477
+ follower rule a keyframe cannot express - a serpent's spine whose segments ease toward
478
+ their parent's previous position within per-segment rotation limits.- `Projectile` - tweens a sprite in a straight line for a thrown/shot visual flourish; an
479
+ optional `animation` (item 311) advances flight frames with the tween's own elapsed time, read
480
+ back through `frame`/`frameOffset` so the caller can apply the frame's offset where it already
481
+ positions the sprite. `Flights` owns the live ones: `add(sprite | texture, from, to,
482
+ { speed, tint?, spin? | spinDegrees?, fadeIn?, onArrive? })` returns a handle, `update(dt)` drives
483
+ positions and dispatches each arrival exactly once, `cancel()`/`clear()` forget without
484
+ dispatching; caller sprites stay caller-owned while texture-built sprites are parented
485
+ here and destroyed with their flight. `spinDegrees` is `spin` in degrees per second
486
+ (converted once, so an authored angular speed needs no radian arithmetic at the call
487
+ site) and `fadeIn: 'progress'` (or `true`) eases the sprite's alpha 0 to 1 along the
488
+ tween's own progress instead of seconds from launch.
489
+ - `LightningArc` - the position data for a jittered line between two points (a bolt, a tether):
490
+ `points` tapers to zero offset at both endpoints, `retarget` moves either endpoint for a
491
+ tether following two moving units, and an optional `flickerInterval` re-rolls the jitter on a
492
+ timer. Geometry only, drawn by the caller through `Shape2D`'s `Graphics`. `Beam` is the
493
+ drawn one-shot counterpart (a fading line, or a texture strip - repeating by default,
494
+ or `BeamTextureOptions`' `stretch: true` for art that spans the whole beam once, with an
495
+ `anchor` placing it across the thickness - additive by default, `retarget` moving
496
+ either end, `thin` narrowing the body as it fades, `update` reporting expiry once);
497
+ `Beams` owns the live ones with `add`/`update`/`clear` and destroys finished beams.
498
+ - `SpriteAttachment` - ties a second sprite's position to a first one's: `follow(x, y)` applies
499
+ an offset, and an optional `duration` makes `update(dt)` report `done` once it elapses, so a
500
+ permanent shadow and a temporary status icon are the same class with different options.
501
+ Renderer-neutral like `Projectile`/`LightningArc`; z-order and parenting stay the caller's.
502
+ - `LiquidLayer`/`LiquidLayerOptions` - an animated liquid surface under a map: one scrolling
503
+ tiling quad per liquid cell with its own visibility tint (`setCellColor`), and `ripple` rings
504
+ that grow and fade; pure decoration, every child opts out of pointer events.
505
+ - `FogLayer`/`paintFogPixels`/`FogCell`/`FogColor`/`FogLayerOptions` - a smooth fog-of-war
506
+ overlay: a small linear-filtered canvas with `resolution` pixels per tile, so fog edges blur
507
+ across cells and one cell can be shaded in parts; `paintFogPixels` is the same shading as a
508
+ pure function over an RGBA buffer.
509
+ - `TileMap.stampRect` copies a block of frames into a layer at a tile position and throws when
510
+ it does not fit; `AutotileSet.mode: 'mixed'` reads the MV A4 sheet's alternating rows with the
511
+ floor table (wall tops) and the wall table (wall faces).
512
+ - `Halo`/`HALO_ANIMATION` - the glow around a unit, an aura, a shrine's light: an `AnimatedSprite`
513
+ drawn additively (Wesnoth's `[halo] blend_mode=add`) whose `follow(x, y)` applies the halo's own
514
+ offset once instead of in every game that draws one. Z-order stays the caller's, because a halo
515
+ that belongs behind its unit is added before it and one that belongs in front is added after, and
516
+ a framework that guessed would be wrong half the time.
517
+ - `ParticleEmitter`/`Particle` - a pooled, seeded particle emitter (sparks, dust, rain):
518
+ `burst`/`start`/`stop` over a pool allocated once at `max`. Runs the whole simulation with
519
+ no `texture` given, which is how it is tested without a renderer. `ParticleSpawnArea` gives
520
+ births a local `rect` or `ellipse` extent instead of the emitter's single origin. `scale` and
521
+ `alpha` take a `ParticleCurve` (`t` over the particle's life) as well as the birth-to-death
522
+ pair, `tint` takes a `[from, to]` range each particle draws its own colour from channel by
523
+ channel, and `flicker` wobbles the scale every frame with a seeded draw (dropped under reduced
524
+ motion). All three draws happen only when used, so an existing emitter's seeded spray is
525
+ unchanged. `attach(target)` follows a display object or position thunk on every tick (with `offsetX`/`offsetY`, an `enabled` callback gating tick emission, a `visible` callback hiding the whole spray (fog-of-war gates) while the simulation steps on behind the invisibility, and auto-detach for destroyed targets); `detach()` keeps the last position.
526
+ - `ScreenEffects`/`ScreenEffectStep` - a full-screen colour wash: `fadeOut`/`fadeIn`/`flash`/
527
+ `setTint`, driven by `update(dt)` returning true on the frame an effect completes.
528
+ `sequence(steps)` (item 302) chains fade/hold/flash steps end to end as one call, for the
529
+ hold-then-fade-back transition the four individual methods cannot express alone; `update`
530
+ keeps returning false at every step boundary, true only once the whole sequence finishes.
531
+ - `ActorAnimator` - an idle/move/action animation state machine with one interruption rule.
532
+ - `StatusVisuals` - composes every active status effect's colour additively onto a sprite's
533
+ `colorAdd` (item 301), instead of one status winning by declaration order; each channel clips
534
+ at 1 rather than wrapping. Never touches the multiply `tint`, so a sprite's own identity
535
+ tint (a team colour) survives underneath. `flash(color, strength, duration)` layers a
536
+ one-shot, linearly-decaying pulse (a hit, a heal) on top of whatever is active.
537
+ - `SpriteMotion` - squash, hop, bob, wobble, spin, shear and flip over any display object's
538
+ transform through a `Tweener` (item 404). Effects compose from the rest pose captured at
539
+ construction, never drift, return a `MotionHandle` (`done`, `cancel()`), and follow
540
+ `setReducedMotion`; `destroy` restores the rest pose, flips included.
541
+ - `ClothSprite` - a `physics` `Cloth` mesh drawn as a textured sprite on the 414 mesh
542
+ path (item 423): owns the simulation, `update(dt)` steps it and re-uploads the vertex
543
+ buffer, the top edge starts pinned, UVs are never rewritten. `setWind`/`pinPoint`/
544
+ `unpinPoint` tune it, and it honours `setReducedMotion`.
545
+ - `Spring` - a damped 2D chase spring for secondary motion (item 424): the anchor
546
+ teleports, the bob lags, overshoots and settles through pure arithmetic, O(1) per
547
+ update, deterministic for a fixed `update(dt)` sequence. `place(target)` parks a
548
+ follower on the bob; honours `setReducedMotion`. `SpringSprite` draws the
549
+ anchor-to-bob line, redrawn by an explicit `sync()` after stepping.
550
+ - `HazeLayer`/`hazeField`/`paintHazePixels` - an atmospheric haze sheet, never fog of war:
551
+ translucent drifting weather with soft edges, density and per-plane wind, on a small
552
+ canvas scaled up with linear filtering. `paintHazePixels` is the same shading as a pure
553
+ function over an RGBA buffer, which is how it is tested without a renderer.
554
+ - `NeonGlow`/`glowFalloff`/`paintGlowPixels` - a soft additive halo baked from a shape or
555
+ mask, with colour, radius, intensity and flicker; a global bloom stays optional.
556
+ - `loadTiledMap`/`TiledMapData`/`TiledTilesetData`/`TilesetSheet`/`LoadedTiledMap` - loads
557
+ Tiled JSON maps into a `TileMap`: orthogonal, isometric and staggered orientations, multiple
558
+ tilesets (embedded or external `.tsx`). Lives here rather than in `rpg` because what it
559
+ builds is a `TileMap` out of `SpriteSheet`s.
560
+ - `blobIndex`/`autotileFrames`/`BLOB_SHAPES` - auto-tiling: the 47-shape "blob tile"
561
+ reduction of 8-neighbour terrain matches.
562
+ - `rpgmAutotileFrame`/`RpgmAutotileAtlas` - renderer-neutral RPG Maker MV autotile atlas
563
+ geometry: decode one of the four atlas slots, select its four 24px source quadrants for a
564
+ shape, and describe their 48px output position. `RpgmAutotileAtlas` caches repeated frame
565
+ descriptions. `RPGM_FLOOR_AUTOTILE_TABLE`/`RPGM_WALL_AUTOTILE_TABLE` are the standard MV
566
+ shape tables, `RPGM_AUTOTILE_SLOT_BASES`/`RPGM_AUTOTILE_SLOT_COUNTS` the family address
567
+ facts, and `rpgmAutotileSlot` classifies a raw map id into its family (item 370).
568
+ - `TileMap` `addAutotileLayer` over `AutotileSet`/`AutotileCell` - a native autotile layer:
569
+ raw MV ids or XP values route to the set claiming them, and the map assembles each
570
+ cell's quadrant halves straight from the source sheet (item 370). `setAutotileFrame`/
571
+ `getAutotileFrame` advance and read the animation frame; `setTile`/`getTile` keep
572
+ working with raw ids. `XP_AUTOTILE_PATTERNS`/`XP_NEIGHBORS_TO_PATTERN` are the XP
573
+ template and neighbourhood tables, `xpAutotileRef`/`xpAutotilePattern` decode and
574
+ compute XP cells, and `autotileCellParts`/`assertAutotileLayout` resolve and validate
575
+ one cell's pieces renderer-free.
576
+ - `AutotileSet.tableEdge` with `rpgmTableEdgeCells` over `RpgmTableEdgeMap` - the front-edge strip
577
+ the engine draws under an A2 table: `rpgmTableEdgeCells` finds the cells that get one (table
578
+ above, none here, no A3/A4 wall on the ground layer) and the set draws its two half-height
579
+ pieces. `TileMap` `addShadowLayer` over `ShadowLayerOptions` adds the engine's shadow bits
580
+ (map layer 4) as translucent quarter-tile quads.
581
+ - `resolveTerrainGraphics`/`matchTerrainRule`/`squareRotate`/`hexRotate` over `TerrainRule`/
582
+ `TerrainCondition`/`TerrainImage`/`TerrainPlacement`/`TerrainFlagsAt` - a rule-driven
583
+ `[terrain_graphics]`-style transition pass for what `Autotile`'s fixed 47-shape table cannot
584
+ express: flag conditions at arbitrary offsets, one rule placing more than one image (so a
585
+ piece bigger than one cell is the rule's own data, not something `TileMap` has to hold),
586
+ `rotations` (`squareRotate`'s 4 exact steps or `hexRotate`'s 6) and `probability` breaking a
587
+ tie among rules matching at equal specificity. Returns plain placement data.
588
+ - `TerrainGraphicsLayer` over `TerrainGraphicsLayerOptions` - the renderer for that data: one
589
+ `Sprite2D` per placement, added in `layer` order (a stable sort, so the rule pass's own
590
+ row-major walk survives within a layer), each resolved through the asset resolver at the pixel
591
+ position the caller's `project` callback reports. `setPlacements` redraws; z-order against the
592
+ rest of the scene is the caller's, as it is for `Halo`.
593
+ - `inspectGraphicsCapabilities`/`detectWebGpu`/`RENDERING_DECISIONS` - checks
594
+ WebGL/WebGPU/WGSL support and records this project's own rendering-backend decisions.
595
+ - `Container2D`/`Texture2D`/`Rectangle2D`/`Rect`/`TextureRegion`/`rectOf` - the renderer
596
+ boundary names for common 2D values. The first three work in both type and value positions,
597
+ so a game can construct a container or use texture and rectangle constants without naming
598
+ `pixi.js`. For the rare need the facade does not cover, `two-d/pixi-interop` re-exports the
599
+ underlying Pixi classes explicitly.
600
+ - `Node2D`/`Shape2D`/`Text2D`/`Sprite2D`/`TiledSprite`/`Gradient` - bare, MWG-named
601
+ re-exports of Pixi's `Container`/`Graphics`/`Text`/`Sprite`/`TilingSprite`/`FillGradient`:
602
+ a plain grouping layer, vector drawing, one-off text, a plain untinted sprite, a
603
+ repeating/scrolling texture, and a gradient fill/stroke, none of which needed new
604
+ behaviour, only a name a game can import without naming `pixi.js` itself. Prefer
605
+ `ui.Label`/`BitmapLabel` over `Text2D` for anything styled through `ui.theme()`, and
606
+ `render.TintedSprite` over `Sprite2D` the moment a colour transform is needed.
607
+ - `createLayers(parent, names)` (item 312) - builds one labeled `Node2D` per name, attached to
608
+ `parent` in the order given and returned keyed by name, so a game's conventionally-ordered
609
+ layer stack (terrain, units, effects, UI, ...) is one call rather than a dozen hand-wired
610
+ containers.
611
+
612
+ ### `two-d/ui`
613
+
614
+ Windows, lists, message boxes, HUD widgets - all themed from one live-swappable `Theme`.
615
+
616
+ - `theme`/`setTheme`/`defaultTheme`/`highContrastTheme`/`themeChanged` - the active theme;
617
+ `setTheme` fires `themeChanged` so already-built widgets restyle in place.
618
+ - `Label` - a themed text wrapper over Pixi `Text`; `stroke`/`resolution`/`roundPixels`
619
+ options, useful for text over artwork.
620
+ - `parseMarkup`/`stripMarkup`/`markupToHtml`/`escapeHtml` over `MarkupSpan`/`MarkupOptions` - inline
621
+ markup (`<b>`, `<i>`, `<span color='…' size='…'>`, `<br/>`, `<img>path</img>`, `$name`, and the
622
+ five entities) as a renderer-neutral contract: a `MarkupSpan` is a `MarkdownSpan` plus the colour,
623
+ size and image a renderer may use, kept as written because resolving them is the renderer's
624
+ business. Unknown tags, malformed tags and unset variables stay literal rather than disappearing,
625
+ and `markupToHtml` is the escaped HTML fragment for a renderer that speaks HTML text - it now
626
+ also renders colour and size, as an inline style. `MarkupOptions.tags` (item 313) names extra
627
+ tags to treat as styling containers; a run inside one carries its name in `MarkupSpan.tag`, so a
628
+ renderer can resolve its style (Pixi's `tagStyles`) while the parser stays renderer-neutral, and
629
+ `markupToHtml` re-emits that tag as a real element for `HTMLText`. `markupAccessibilityText` is the proper
630
+ accessibility projection (an image becomes a caller-described string, not its raw path, which
631
+ `stripMarkup` keeps for round-tripping instead). `layoutMarkupLines` wraps already-parsed spans
632
+ word by word against a caller-supplied `MarkupMeasure`, each word measured under its own
633
+ span's style - wrapping computed *after* styling, so a bold or larger run wraps where its own
634
+ wider glyphs actually land - and `positionMarkupLines` places those already-laid-out lines into
635
+ `PositionedMarkupSpan` runs (one `x`/`y` per span) under a `MarkupLayout`'s `direction`/`align`,
636
+ so an `rtl` line flows right to left and alignment defaults to the direction's own edge. Both
637
+ are backend-neutral: the same spans, `measure` and `maxWidth` decide the same line breaks and
638
+ the same runs whether a caller then draws them through `HTMLText` or a canvas `Text2D` pass.
639
+ - `MarkupText`/`MarkupTextOptions` - the canvas backend for that contract, the counterpart to
640
+ `RichLabel`'s HTML text: one `Text2D` per styled run and one `Sprite2D` per `<img>` span,
641
+ resolved through the asset resolver, so an image is drawn rather than a caller positioning it
642
+ itself at a `layoutMarkupLines` offset. It reads `direction` from the theme and takes
643
+ `maxWidth`/`lineHeight`/`align`/`resolveImage`/`variables`/`resolution` options, plus
644
+ `tagStyles` (item 313): a Pixi `TextStyleOptions` record keyed by custom tag, applied to each
645
+ run and used when measuring it, so `<quest>...</quest>` is styled and wraps under its own font.
646
+ - `RichLabel`/`parseMarkdown`/`stripMarkdown`/`sliceSpans` - basic inline markdown (`**bold**`,
647
+ `*italic*`, combined `***both***`, backslash escapes) through Pixi `HTMLText`, which is
648
+ what makes mixed styles inside one string possible at all. `parseMarkdown` is pure
649
+ span-splitting (unmatched markers stay literal); `stripMarkdown` recovers plain text;
650
+ `sliceSpans` takes the first N visible characters with styles kept, for progressive
651
+ reveal without leaking half-shown markers. Costs more than a `Label`, so this is for
652
+ descriptions and help bodies, not per-frame numbers. `tagStyles` (item 313) takes Pixi
653
+ `HTMLTextStyleOptions` keyed by custom tag; a registered tag survives escaping as a real element
654
+ for `HTMLText` to style, while an unregistered one is still escaped as literal text.
655
+ - `startReveal`/`advanceReveal`/`completeReveal`/`revealComplete` - the shared
656
+ progressive-display primitive: one character count behind `MessageBox` pages (which
657
+ already revealed this way), `Label` lines, and `RichLabel` markdown. `Label` and
658
+ `RichLabel` expose it as `showProgressive`/`updateReveal`/`completeReveal`, driven by
659
+ the game's own frame loop; `MessageBox` keeps its confirm-completes-then-advances rule
660
+ on top unchanged.
661
+ - `BitmapLabel`/`bitmapLabelStyle` - bitmap-font-backed text, for a HUD value redrawn
662
+ every frame where `Label`'s per-string texture re-render would be wasteful.
663
+ - `NinePatch` - a resizable nine-slice panel.
664
+ - `Window` - a themed panel container. `close()` frees the window and its contents and is
665
+ idempotent; `closed` is the guard for the caller's reference afterwards (input and `place` on a
666
+ closed window are no-ops), and `WindowStack.push` refuses one with a named error. A window's own
667
+ area is not clickable, so a click travels to whatever is under it; `blocker: true` adds the
668
+ full-viewport layer that swallows clicks and dismisses the window for a click outside it
669
+ (`handleOutsideClick` is that decision).
670
+ - `WindowStack` - keyboard focus goes to the top window only; dims what's underneath; `blocker` on
671
+ a window is what stops clicks reaching the map behind it. `handleAction(action)` is public so a
672
+ scene with its own key handling can ask the windows first: `Input.onAction` offers an action to
673
+ the most recently registered listener first, so a scene that registers after building its stack
674
+ is asked before the windows are and can swallow a key they need.
675
+ - `MessageBox.blocker` - whether a click under the box reaches the map behind it; on by default,
676
+ and since the box is not closable that can only ever swallow clicks rather than dismiss it.
677
+ `blocker: false` is for a box the player is meant to click past.
678
+ - `ListView` - a scrollable, keyboard- and pointer-navigable row list (click, wheel-scroll);
679
+ `multiple` checks rows instead of picking one, read back through `checkedIndexes`.
680
+ - `IconGrid` - a multi-column icon-grid inventory view; tap-then-tap "drag and drop",
681
+ frame-driven long-press for a quickslot.
682
+ - `TabbedList`/`ListTab`/`TabbedListOptions` - a renderer-free model for an inventory, journal,
683
+ shop or codex: caller-supplied tabs and rows (no assumed taxonomy), an optional label,
684
+ filter and disabled predicate, selection that skips disabled rows, a page derived from the
685
+ selection rather than tracked beside it, and an `openDetail`/`closeDetail` state.
686
+ - `Slider`/`SliderOptions` + `sliderFraction`/`sliderValueAt` - a draggable knob on a themed track;
687
+ the two pure functions are the value/track arithmetic (clamping, the step grid, the degenerate
688
+ range), so a game routing its own input snaps the same way.
689
+ - `Checkbox`/`CheckboxOptions` - a ticked-or-not box; a caption is a `Label` the game places beside
690
+ it, and `onChange` fires only when the state moves.
691
+ - `RadioGroup`/`RadioOption`/`RadioGroupOptions` - exactly one choice among several: arrows
692
+ move the selection and select at once, a tap selects directly, disabled options are skipped.
693
+ - `Spinner`/`SpinnerOptions` + `spinValue` - an up/down numeric stepper; `spinValue` is the rule
694
+ (snap to the step, then clamp at the ends or wrap past them).
695
+ - `DropdownView`/`DropdownViewOptions` - the widget over a `Dropdown` model: a button showing the choice
696
+ that opens a column of `Button`s, the chosen one marked with `Button.setSelected`.
697
+ - `Dropdown`/`DropdownOption`/`DropdownOptions` - a renderer-free option button: a selected entry,
698
+ an open list, a highlight that starts on the selection and skips disabled options.
699
+ - `TextModel`/`TextModelOptions` - the editing state behind a text field, fed by `core.Input`'s
700
+ `onText`: caret, anchor, selection-replacing edits, a length cap and a mask. Renderer-free.
701
+ `multiline` keeps real newlines with row navigation (`lineCount`, `caretLine`, `lineRange`,
702
+ `moveCaretLine` holding a sticky goal column); single-line fields strip them on every edit.
703
+ - `TextPrompt`/`TextPromptOptions` - a modal single-line text field over a `TextModel` (a name
704
+ entry, a save-slot label): typing through `onText`, caret and edits through `left`/`right`/
705
+ `backspace`/`delete` actions, `confirm` gated by `validate` (the error shows and announces
706
+ assertively, the prompt stays open), `cancel` giving up. IME compositions preview until
707
+ they commit, and the message plus validation errors announce through `screenReader`.
708
+ The interface example's Name button is the reviewed hosting pattern: push it on a
709
+ `WindowStack` and it owns focus, closing and the stack's un-popping by itself.
710
+ The touch half (roadmap 402): `keyboard: UPPERCASE_KEYBOARD` (or any `KeyboardLayout`)
711
+ hosts one beneath the field and resizes the window to fit it - `OnScreenKeyboard`,
712
+ next.
713
+ - `OnScreenKeyboard`/`KeyboardLayout`/`KeyboardKey` + `UPPERCASE_KEYBOARD`/`pressKey`/
714
+ `layoutKeys` - pointer-only typing: a layout is rows of keys as plain data (ragged rows
715
+ fine), each key a caption, the `text` it types (defaulting to its label), or the named
716
+ `action` it fires instead, plus a `span` in row units for a space bar. The class renders
717
+ it through the theme's own `Button` and reports `contentHeight` so a host can size
718
+ itself; `pressKey` is the pure dispatch rule (`dispatchText` for a typing key,
719
+ `dispatchAction` for an action key, the two paths a physical key travels, so no
720
+ listener can tell a tap from a keystroke) and `layoutKeys` the rows-to-buttons
721
+ arithmetic behind it. `UPPERCASE_KEYBOARD` is the one shipped default: the alphabet
722
+ over a digit row, then `Bksp`, caret moves, space, `OK`, `Esc`.
723
+ - `DataTable`/`TableColumn`/`DataTableOptions` - a renderer-free columned table: sort by a column
724
+ (toggling direction), a highlight that skips disabled rows, and a page derived from the
725
+ highlight.
726
+ - `TreeView`/`TreeNode`/`TreeRow`/`TreeViewOptions` - a renderer-free collapsible tree, flattened to
727
+ the rows on screen; collapsing the branch the highlight is inside lands it on the branch.
728
+ - `ScrollBox`/`ScrollBoxOptions` + `scrollOffset` - a clipped viewport with a themed scrollbar;
729
+ `scrollOffset` is the clamping rule the wheel, `scrollBy` and `scrollIntoView` all share.
730
+ - `flowLayout(items, width, { gap, align })` - left-to-right rows that wrap, returning each item's
731
+ position and the total height: a toolbar that takes two rows on a phone.
732
+ - `Grid`/`GridSpec`/`GridTrack` + `resolveAnchor`/`anchorAlign` with `Anchor`/`AnchorSpec`/
733
+ `LayoutRect` - data-driven shell layout (item 263): named anchors placed inside bounds (margin,
734
+ offset, fill), and columns/rows that are `size` or `grow`, so one sidebar plus one content column
735
+ needs neither side to know the window's width. Pure geometry, renderer-free.
736
+ - `Skins` with `Skin`/`SkinStates`/`SkinData`/`WidgetState` - per-widget, per-state looks looked up
737
+ by name, the counterpart the one global `Theme` has no room for. A lookup falls back widget state
738
+ -> widget idle -> wildcard state -> wildcard idle -> `{}`, and `Skins.from` reads the plain data a
739
+ config file would parse into.
740
+ - `MessageBox` - dialogue text box: paged reveal, choices, ADV/NVL display modes,
741
+ `autoAdvance`, and timed `{sound:path}` markers delivered through `onSound`.
742
+ - `messageBoxPresenter` - wires `rpg.EventRunner`'s dialogue to a `MessageBox` on a
743
+ `WindowStack`, in one argument: `present: messageBoxPresenter(this.windows)`.
744
+ - `VerticalLabel`/`layoutVertical` - vertical writing layout, with CJK glyph rotation.
745
+ - `RebindScreen` - a keybind-rebinding flow over `Input`, with an optional conflict hook.
746
+ - `SettingsScreen`/`SettingsCustomRow`/`SettingsScreenOptions` (item 364) - a ready-made
747
+ settings screen over `core.Settings`: music/sfx sliders, mute checkbox, zoom slider,
748
+ one row per `custom` descriptor (boolean/number/choice), an embedded controls page
749
+ that writes rebinds back into `Settings` on exit, and a reset row. `cancel` on the
750
+ main page returns false for the caller to close.
751
+ - `Button`/`ButtonSkin`/`ButtonState` - idle/hover/pressed/disabled clickable region, icon
752
+ and/or text, optional per-button nine-patch skin with per-state tints.
753
+ - `Bar` - a filled-proportion track (health/mana/XP); flat colour or texture, optional
754
+ `roundUpToPixel` so a nonzero value never rounds down to invisible.
755
+ - `Meter`/`MeterOptions` (item 368) - a discrete meter: N icons with a value filled, the
756
+ heart row or star rating to `Bar`'s continuous fill. Fractions clip mid-icon through a
757
+ mask, so halves need no extra art; flat theme pips by default, a game-supplied
758
+ filled/empty texture pair (which must come together) otherwise.
759
+ - `FloatingText`/`floatingTextAlpha`/`floatingTextRise`/`floatingTextAgeAtLeast` - a rising, fading
760
+ damage/pickup number and its pure motion, opacity and age curves; `FloatingTextStack` with
761
+ `floatingTextStackLift`/`floatingTextStackMoves`/`floatingTextStackLifePenalty` and
762
+ `FLOATING_TEXT_STACK_GAP` stacks simultaneous pop-ups at one world point without overlap, lifting
763
+ the lines already there the way Java's `FloatingText.push()` does.
764
+ - `MessageLog`/`linesToDrop`/`takeLastEntries`/`MessageLogEntry`/`MessageLevel`/`MessageLogOptions` - a player-facing message pane:
765
+ one coloured block per message (info, positive, negative, warning, highlight) that drops the
766
+ oldest blocks once the wrapped lines pass a cap; `linesToDrop` is that budget as a pure function,
767
+ and `lastEntries(n)` reads the newest retained entries back as `{ text, level }` records
768
+ (oldest first) without scraping rendered children.
769
+ - `fitWindowZoom`/`sharpenText` - step a window stack's integer zoom down until its content fits
770
+ the viewport, and re-rasterise every `Text` under a zoomed container at device ratio times its
771
+ on-screen scale so it is not magnified 1x text.
772
+ - `Toast` - a queued, timed pop-up notification (fade in, hold, fade out).
773
+ - `Tooltip` - a hover explanation over a themed `Window`: a frame-driven hover delay, and
774
+ edge-aware placement that flips rather than letting the panel run off screen.
775
+ - `HelpScreen` - a topic-list-plus-body help/controls screen.
776
+ - `StatsScreen` - a player-stats display screen.
777
+ - `LoadingScreen` - a progress-bar loading screen wired to `core.LoadQueue`.
778
+ - `ScreenReader`/`screenReader` - the screen-reader bridge: `Window` announces its title,
779
+ `MessageBox` each page and its choices, and `TextPrompt` its message and validation errors
780
+ through a visually hidden `aria-live` region, and a game's own widgets use the same
781
+ `screenReader.announce(text, { assertive })`. No-ops where there is no DOM, so ordinary
782
+ scene code needs no guard around it.
783
+ - `contrastRatio`/`meetsContrast`/`relativeLuminance`/`ContrastLevel` - WCAG contrast for a
784
+ `theme` palette: the standard luminance and ratio formulas with AA/AAA thresholds, so a
785
+ game checks its own colours rather than guessing.
786
+
787
+ ### `two-d/stage`
788
+
789
+ Dialogue scenes: backdrop, characters, a script runner - the visual-novel half.
790
+
791
+ - `DialogueStage`/`CharacterDefinition`/`ShowOptions` - backdrop plus character
792
+ conversation scenes; the speaking character lit, others dimmed.
793
+ - `StageScript`/`StageCommand`/`StageChoice`/`StoryScript` - a command interpreter;
794
+ `runStory` follows a named-passage graph (`{goto}`, choice jumps); `history`/`showLast`
795
+ for read-only dialogue rollback; `skipSeen` for auto-advancing already-read lines;
796
+ `ScriptOptions.mode: 'nvl'` for the accumulating-block presentation.
797
+ - `importTwee`/`TwineStory` - imports Twee-notation Twine stories into `StageScript`'s
798
+ command format, a thin wrapper around `core.parseTwee` naming the `StoryScript` return
799
+ type. `rpg.importTwee` is the same wrapper around the same engine, targeting
800
+ `EventStoryScript` instead, so a text-only RPG needs no Pixi dependency to import a
801
+ branching Twee story, and a visual novel that never touches map events needs no `rpg`
802
+ dependency either.
803
+ - `parseDialogueText`/`extractDialogueCatalog` - a terse line-based dialogue format for
804
+ straight (non-branching) scenes: `@id text` names the speaker, an unprefixed line
805
+ narrates, and `- text` alternates between the first two speakers established by `@id`
806
+ lines (capped at two - a third distinct speaker is refused). A thin wrapper around
807
+ `core.parseDialogueLines`, mapping its `speaker` field onto `StageCommand`'s `as`.
808
+ `extractDialogueCatalog` builds an identity `i18n` catalog from the resulting commands
809
+ (or a `StoryScript`), the same shape MWL's own `extractCatalog` builds from
810
+ `_("...")`-marked strings. `rpg.parseDialogueText` is the same wrapper around the same
811
+ engine, targeting `EventCommand` instead, so a text-only RPG needs no Pixi dependency to
812
+ use it, and a visual novel that never touches map events needs no `rpg` dependency either.
813
+ - `StoryScreen`/`StoryScreenOptions` with `StorySequence`/`StoryBeat` - the between-scenario
814
+ interlude `DialogueStage` is not: a full-screen backdrop, title and text advanced by a click. The
815
+ sequencing (advance/back/`goTo`/`skip`/`restart`, and the current beat's `music` reported as a
816
+ signal so the game plays it) lives in the renderer-free `StorySequence`, and a `StoryBeat` has
817
+ the same `{ text, title, image, music }` shape as `MwlWorld.story`.
818
+
819
+ ## `assets`
820
+
821
+ The `file://` story: a compiled build resolves paths through a `data:` URI map; dev mode
822
+ serves them normally. Load once per scene; everything after is synchronous. The compiler side
823
+ of this (`tools/compile-resources.mjs`, `tools/emit-page.mjs`, `tools/single-file.mjs`) offers
824
+ independent build options on top of that one story - multi-file vs. single-file output,
825
+ compression (gzip or brotli, single-file only), and WebP image conversion - documented in
826
+ `DEVELOPMENT.md`'s "Build options" section and `tools.md`'s tool reference; none of them
827
+ change what a game calls to load an asset.
828
+
829
+ Split by renderer specificity: `assets/paths.ts` resolves paths and needs no renderer,
830
+ `assets/binary.ts` caches raw bytes just as renderer-free, `assets/loader.ts` fetches and
831
+ decodes *textures* through Pixi. The `assets` barrel exposes all three; a game rendering
832
+ through something else imports `@datamoc/mw_games/assets/paths` or
833
+ `@datamoc/mw_games/assets/binary` and pays nothing for Pixi, which is how `3d` and `audio`
834
+ reach the compiled asset map without it.
835
+
836
+ - `setBase`/`setAssetMap`/`isCompiled`/`paths`/`has`/`resolve` - dev-vs-compiled path
837
+ resolution, renderer-free (also its own entry point, `@datamoc/mw_games/assets/paths`).
838
+ `setAssetMap` hands these a game's own path-to-URI map directly (item 300), for a game
839
+ bundled by its own tool rather than `tools/compile-resources`, and takes priority over
840
+ `window.__MWG_ASSETS__` while set; `undefined` reverts to it.
841
+ - `load`/`texture`/`get`/`isLoaded`/`release` - load assets by path, read them back
842
+ synchronously, and free GPU memory once a zone is no longer needed. `load(paths,
843
+ { resolution })` rasterizes a vector source (SVG) at a multiple of its intrinsic size, so a
844
+ game that zooms into an icon asks for a `2` or `3` instead of shipping a soft bitmap;
845
+ `onProgress` is the same `LoadQueue` seam whether passed alone or in the options. `optional`
846
+ loads those paths separately so one missing file never aborts the required batch, calling
847
+ `onMissing` for each; `texture`/`get` take a `fallback` returned instead of a throw for a
848
+ path that never loaded, so a caller stops needing its own try/catch around a missing asset.
849
+ - `sanitizeSvg`/`svgScaleVariants`/`svgDataUri`/`splitSvgGroups` (item 398) - SVG as
850
+ inbound data: `sanitizeSvg` refuses what it cannot prove inert by name (script,
851
+ `foreignObject`, event handlers, `javascript:` and active `data:` URLs - a gate, never
852
+ a silent rewrite), `svgScaleVariants` rasterizes one proven-inert source once per named
853
+ scale with its resolution hint, and `splitSvgGroups` loads a group-authored SVG as one
854
+ standalone part per top-level `<g id=...` group, the authoring form for an SVG puppet. `load` also supplies Pixi's `Assets.add` a `format` hint - the original path's own extension
855
+ - whenever the resolved `src` is a compiled build's `data:` URI (item 308): a `data:` URI
856
+ carries no extension of its own for Pixi's resolver to pick a parser from, which otherwise
857
+ left a game no way to load a compiled asset without building its own `{src, parser}`
858
+ descriptor by hand.
859
+ - `loadBinary`/`getBinary`/`isBinaryLoaded`/`releaseBinary` - the renderer-free counterpart
860
+ to `load`/`texture`/.../`release`, caching raw `ArrayBuffer`s instead of Pixi textures
861
+ (also its own entry point, `@datamoc/mw_games/assets/binary`); `3d/models`' `Vox.parseVox`
862
+ is the direct consumer, taking bytes this now fetches and caches instead of a game doing
863
+ it by hand.
864
+ - `AssetStream`/`AssetBundle` - preloads likely-next bundles with LRU eviction under a
865
+ byte budget, for progressive loading between scenes.
866
+ - `fetchWithByteProgress`/`ByteProgress`/`OnByteProgress` - real cumulative byte-progress
867
+ reporting, for a server or desktop host (not `file://`, which blocks `fetch` entirely).
868
+
869
+ ## `audio`
870
+
871
+ - `Sound` - a pooled, round-robin one-shot sound effect player. `play(gain, pitch)` takes an
872
+ optional pitch as `HTMLAudioElement.playbackRate` (1 unchanged); there is no matching `pan` -
873
+ a plain `<audio>` element has no pan of its own, the same reason `Positional.audioPan` only
874
+ reports a number rather than owning a panner node. `suspend` cuts in-flight sounds and
875
+ silences `play` until `resume`.
876
+ - `onCaption`/`CaptionEvent` - accessibility captions fired alongside a sound cue.
877
+ - `Music` - crossfading background music. `suspend` pauses the current and fading tracks
878
+ and freezes `update` until `resume` restarts the current one where it paused. `duck`
879
+ glides to an attenuated level until `unduck`, for dialogue and menus.
880
+ - `createAudio`/`Playable` - an injectable audio backend (tests supply a fake in place of `new Audio()`).
881
+ - `Orchestrator`/`OrchestratorState` - maps a named game state ("combat", "boss") to a
882
+ `Music` track and crossfade, and fires one-shot cues by event name; re-entering the same
883
+ state never restarts its track. `suspend`/`resume` silence and restore the music and
884
+ every cue.
885
+ - `AudioListener`/`SoundSource`/`AudioFalloff` - positional audio: a listener the game moves,
886
+ a `Sound` placed at a point, and `audioGain`/`audioPan` turning distance and heading into a
887
+ volume and a stereo position. `SoundSource.playFor` applies the distance gain through
888
+ `Sound.play`; panning is reported for a backend that has a panner. `Music` stays global.
889
+ - `XpbdWorld` (`@datamoc/mw_games/physics/xpbd`) - a deterministic structure solver
890
+ (extended position-based dynamics): `addNode`/`addLink` (stiffness, `tensionOnly` cables, `strength`/
891
+ `tensionStrength`), `applyForce`, `step()` on fixed substeps, the load of every link read back
892
+ (`force`, smoothed `ratio`, `peakRatio`) and `onBreak` when a link passes its strength; `ground` (a height or a function of x) holds nodes
893
+ on a surface with `groundFriction`. The engine of
894
+ Pontifex, generalised: bridges, trusses, cranes, anything where the question is which beam fails.
895
+ - `PhysicsWorld` (`@datamoc/mw_games/physics`) - rigid bodies and constraints in plain TypeScript, no engine
896
+ dependency: `addBox`/`addCircle`/`addConstraint`/`remove`, `update(dt)` from
897
+ `Scene.update`, `onContact`, `alpha` for interpolation. A constraint with `maxStretch` breaks when pulled
898
+ that far past its rest length (`onBreak`, `stretchOf`). Bodies never spin; `angle` is a display offset.
899
+ - `synthesizeTone`/`synthesizeSound`/`playTone`/`Waveform` - a runtime square/triangle/sine/noise
900
+ waveform synth for a procedural tone or SFX, no sample library; `synthesizeSound` returns a
901
+ pooled `Sound` over the tone.
902
+ - `parseMidi`/`scheduleMidi`/`midiLoopStart`/`noteToFrequency`/`MidiPlayer` - a small `.mid` file player
903
+ built on `synthesizeTone` rather than a licensed instrument library: program, bank,
904
+ controller and pitch-bend events plus the controller-111 loop start, with each
905
+ scheduled note carrying its channel voice. `MidiPlayer.create(file, { humanize })`
906
+ humanizes first and then schedules, for the same player with a performance behind it.
907
+ - `renderMidiToBuffer` - renders a parsed `.mid` file to stereo PCM frames, offline and
908
+ deterministic: browsers cannot decode MIDI, so the file is synthesized once and plays
909
+ back like any decoded track, with its controller-111 loop region. An optional game-supplied
910
+ `SoundFont` voices real samples; without one the built-in waveform synth plays.
911
+ - `renderMidiToBufferAsync` - the same render as raw MIDI bytes, run on a worker thread so
912
+ the seconds a real track costs (2 to 11.8) do not freeze the loading screen. Parse,
913
+ schedule and voice lookup stay on the caller's thread; the stereo buffers come back
914
+ transferred rather than copied, and the result is bit-identical to the synchronous
915
+ render because both call the same function. `soundFontBytes` takes raw SoundFont 2 data.
916
+ - `parseSoundFont` - reads SoundFont 2 bytes into layered preset voices (key and velocity
917
+ ranges, tuning, loops, envelopes, pan, attenuation); the font file itself stays the
918
+ game's to ship and to license. A SoundFont 3 (Ogg Vorbis samples) is refused by name
919
+ rather than read as noise: `loadSoundFont` reads either kind.
920
+ - `loadSoundFont` - reads a SoundFont 2 or 3 into layered preset voices: a plain font goes
921
+ straight to `parseSoundFont`, a SoundFont 3 is decoded first, through
922
+ `webAudioSampleDecoder()` in a browser unless `{ decode }` names another decoder. It
923
+ is what a game calls on the bytes it ships, whichever kind they are.
924
+ - `decodeSoundFont` - a SoundFont 3 as plain SoundFont 2 bytes: every sample a preset reaches
925
+ goes through the decoder once (an unreachable one never does), and the loop points a
926
+ SoundFont 3 states relative to its sample become the absolute ones SoundFont 2 uses. A
927
+ SoundFont 2 comes back unchanged. The result feeds anything that takes SoundFont 2 bytes,
928
+ `renderMidiToBufferAsync` included.
929
+ - `webAudioSampleDecoder`/`SoundFontSampleDecoder` - the decoder contract (Ogg bytes and the
930
+ sample's own rate in, mono 16-bit frames out, synchronous or not) and the browser
931
+ implementation of it over `decodeAudioData`: each sample decodes in a context created at its
932
+ own rate, so the browser never resamples it. A Node tool passes a decoder of its own.
933
+ - `collectSoundFontUsage` - lists the (bank, program) pairs scheduled notes actually
934
+ request across MIDI files, drums as bank 128, for the compile step to keep.
935
+ - `mergeSoundFonts` - joins several SoundFont 2 files (or several SoundFont 3 files, the
936
+ Ogg bytes copied untouched) into one, presets in the order given and the first font winning
937
+ a shared (bank, program), which is how single-instrument files (the per-program collection
938
+ `mwg-soundfonts fetch` reads) become the one file a game ships.
939
+ - `subsetSoundFont` - writes a smaller valid SoundFont 2 (or 3) file carrying only the used
940
+ programs, zones and samples copied verbatim and indexes remapped, so a game ships
941
+ megabytes instead of tens of megabytes with identical voices. The build does this
942
+ on its own: `compileResources` (and so `emitPage` and `mwgPage`) embeds `.mid`,
943
+ `.sf2` and `.sf3` assets, and subsets every embedded SoundFont to the programs the embedded
944
+ MIDI files use. `soundFont: false` embeds the font whole, `soundFontUsage` names
945
+ the programs explicitly, and with no shipped MIDI the font embeds whole because
946
+ the usage is unknowable. The reference bank in `data/microgm-opt.sf2` (2.6 MB,
947
+ WTFPL, shipped in the npm package for a game to copy into its assets) drops to
948
+ tens of kilobytes per game this way. It is the default bank. A game that wants another
949
+ picks it from `data/soundfont-catalog.json` and fetches just its instruments with
950
+ `mwg-soundfonts` (see [tools.md](tools.md)). A SoundFont 3 stays compressed all the way to
951
+ the page (FluidR3's piano, guitar and drums: 2.7 MB, against 20 MB decoded to a SoundFont 2),
952
+ and `loadSoundFont` decodes it at load, so prefer it over a SoundFont 2 for anything but the
953
+ smallest banks.
954
+ - `Channel`/`AudioBus` - buffered WebAudio music: a `Channel` plays one looping track with
955
+ volume, pitch, pan, a loop region and a seekable playhead, and an `AudioBus` wires two of
956
+ them into independent BGM/BGS loops, ME jingles that suspend and resume the BGM,
957
+ overlapping SE one-shots, save and replay with playheads, and plain-data snapshots.
958
+ `AudioBus.setMixer(kind, { volume, muted })` scales a whole kind on top of each track's
959
+ own volume, without changing what snapshots report.
960
+ - `parseVorbisLoopTags`/`loopRegionFromTags` - read the `LOOPSTART`/`LOOPLENGTH` comments an
961
+ Ogg Vorbis file carries (a bounded walk of the first pages, null on anything malformed) and
962
+ turn them into the seconds-based `LoopRegion` a `Channel` or the bus loader hands back.
963
+ - `humanizeMidi`/`HumanizerFactory`/`HumanizeRequest`/`MidiHumanizerEngine` - the entry point
964
+ for a performance that sounds played rather than played back. `humanizeMidi(file, options)`
965
+ resolves the tier from the request (a `GrooveTemplate` in it means the groove tier, anything
966
+ else the lite one) and returns a new file; `HumanizerFactory.create(tier)` is for holding one
967
+ engine across several files. The pass never mutates its input: `intensity: 0` reproduces the
968
+ file exactly, a `seed` reproduces a run, note durations and every tempo, program, controller
969
+ and meta event survive, events come back sorted by tick with ties in file order, and nothing
970
+ lands before tick 0 (a shift that would cross it stops there instead). `create('magenta')`
971
+ throws naming what is missing rather than loading: `@magenta/music` and a PerformanceRNN
972
+ checkpoint cannot be fetched from a `file://` build.
973
+ - `LiteHumanizer`/`GrooveHumanizer`/`HumanizationOptions`/`HumanizeStyle`/`HumanizerTier` - the
974
+ two shipped engines and their options. Tier 1 moves timing and velocity by gaussian noise
975
+ over a seeded gradient drift, scaled by `intensity` and by `style` (jazz wide, classical
976
+ tight), and holds the kick and the lowest notes to a few milliseconds of their slot; tier 2
977
+ applies a template's per-slot offsets and velocities instead, converted through the file's
978
+ own tempo map when the template was recorded at another tempo (which says so through
979
+ `onWarn` rather than staying quiet), plus contextual rules - an accent on a local melody
980
+ peak, restraint on the beat. `initialize()` is idempotent on both.
981
+ - `subdivisionCount`/`assertGrooveTemplate`/`GrooveTemplate`/`GridSubdivision`/`GrooveOffset` -
982
+ the units everything else is measured in: how many slots a bar of a signature holds at a
983
+ grid (`subdivisionCount([4, 4], '16n')` is 16, `[6, 8]` at `8n` is 6, and a grid that does
984
+ not tile the bar throws), and the validator for a template's invariants - dense offsets in
985
+ subdivision order, whole ticks, a power-of-two denominator, a velocity factor between 0 and
986
+ 1 - run when one is built and when one is imported.
987
+ - `GrooveExtractor` - a reusable template out of three kinds of evidence, each reduced to the
988
+ same thing: the median of each slot's deviations, so one flubbed note cannot drag it and a
989
+ slot nobody played stays on the grid. Mode A matches a played pass against a straight one,
990
+ note-on to nearest note-on of the same channel and pitch within half a slot; mode B projects
991
+ a single file onto its own implied grid, which is exactly the residual a quantization would
992
+ discard; mode C takes an `AudioBuffer`, detecting attacks by spectral flux (hand-rolled FFT,
993
+ no analysis dependency) and taking the tempo as an argument because timing means nothing
994
+ without one, with velocity left at the neutral 1 since a recording carries none.
995
+ - `GrooveConverter` - a template to and from the two formats that can carry one. JSON is
996
+ exact; the MIDI encoding is one note per slot behind an anchor a subdivision ahead, with
997
+ velocity at 1/64 per unit of `velocityFactor`, so the writer enforces `|offset|` below the
998
+ slot and a factor of 1/64 to 127/64 instead of rounding past them, and the file gets its own
999
+ reader because the round trip needs the tempo, time-signature and name metas that `parseMidi`
1000
+ deliberately drops. `GrooveFormat` also names `ableton-agr` and `reaper-groove`, both of
1001
+ which throw saying they are not shipped rather than returning a file that resembles one.
1002
+
1003
+ ## `battle`
1004
+
1005
+ The Pokémon-shaped half of the capability spec: species/stats/party/type-matrix/turn-order.
1006
+ No move, formula, or number belongs here - only the shape.
1007
+
1008
+ - `Creature`/`Species` - wraps `actors.StatBlock`/`Progression`, not a separate stat system.
1009
+ - `TypeMatrix` - attack-type effectiveness lookup.
1010
+ - `Party` - a roster of creatures.
1011
+ - `battleOrder`/`Move`/`BattleAction` - one round's priority-then-speed turn order.
1012
+ - `checkEvolution`/`EvolutionRule` - level/condition-based species evolution.
1013
+ - `StatStages` - a bounded, symmetric stage ladder over a stat (±`max`), replacing rather
1014
+ than stacking the modifier for a stat's current stage.
1015
+ - `chooseMove`/`chooseSwitch` - battle AI built on `TypeMatrix`.
1016
+ - `BattleHooks`/`BattleHook` - `core.HookRegistry` with battle's argument shape: a handler
1017
+ receives the creature plus a shared mutable `context`, for passive effects, abilities and
1018
+ turn-skipping statuses.
1019
+ - `Field`/`FieldCondition` - field-wide conditions: weather, terrain, screens; named,
1020
+ optionally timed, ticked down by `advance(rounds)`.
1021
+ - `AttackPreview`/`AttackPreviewOptions`/`AttackFrame`/`PreviewCombatant` - the damage totals and
1022
+ one-frame-per-strike timeline an attack dialog prints and animates, from damage the game's own
1023
+ formula produced (`totalDamage`, chance-weighted `expectedDamage`, `hits` for a rolled outcome,
1024
+ `sampleAt` on the animation clock). It computes no damage itself.
1025
+ - `AttackDialog`/`AttackDialogOptions`/`StrikeNumbers` - the dialog's whole renderer-free state: a
1026
+ `UnitSelector` to choose the pair, the `AttackPreview` built from a game-supplied `damageFor`, and
1027
+ the `update(dt)`/`finished` clock that drives the animation.
1028
+ - `UnitSelector`/`UnitSelectorOptions`/`SelectableUnit`/`SelectorStage` - the two-step attack
1029
+ selector: enabled units on the selecting side as candidates, then the enemies `canTarget` allows
1030
+ as targets; `back` undoes the attacker choice.
1031
+ - `Whiteboard`/`WhiteboardEntry` - planned turn orders with one plan per unit, `undo`/`redo` (a new
1032
+ plan clears the redo stack) and `commit` handing the plans back.
1033
+ - `BattleStats`/`BattleStatCategory` (item 273) - a per-run breakdown by category (`recruits`,
1034
+ `recalls`, `advances`, `kills`, `deaths`, `damageDealt`, `damageTaken`) and unit type, the shape
1035
+ `core.PlayerStats`'s opaque `T` cannot give a game for free; `record` adds to one unit type's
1036
+ count, `total`/`breakdown` read a category back summed or per type, and `toJSON` folds into a
1037
+ `core.RunHistory` entry or `core.PlayerStats` total like any other run summary.
1038
+
1039
+ ## `board`
1040
+
1041
+ Board/card/dice games and generic tactics - traditional public-domain rules, no formula
1042
+ borrowed from any licensed game.
1043
+
1044
+ - **chess** (`chess.ts`): `startingChess`/`parseFen`/`positionKey`/`cloneChess`/`legalMoves`/
1045
+ `applyMove`/`inCheck`/`gameResult`/`sq`/`squareName` - full rules: legality, check/mate/
1046
+ stalemate, castling, en passant, promotion, FEN in both directions (positions keyed
1047
+ without clocks).
1048
+ - **engine** (`Engine.ts`): `chessGame`/`chooseMove`/`search` - the chess rules adapter and
1049
+ convenience wrapper over the shared `ai.alphaBetaSearch`, with material evaluation and
1050
+ depth/node limits. `searchAsync` scores each root move on a worker thread and combines
1051
+ the scores first-wins, so a depth-3 search stops dropping frames; inside the node
1052
+ budget it chooses exactly the move `search` would. The minigame path keeps this small search and never pays for the tournament module below. `searchAsync` combines root-move scores first-wins.
1053
+
1054
+ - **bitboards** (`bitboard.ts`): the same rules on twelve 64-bit boards
1055
+ (`startingBitboard`, `bitboardFromChess`, `bitboardMoves`, `makeMove`/`unmakeMove`,
1056
+ `perft`), the mutable board the tournament engine searches. `bitboardFromChess`
1057
+ bridges from a `chess.ts` position; the differential tests keep both rule sets in
1058
+ agreement.
1059
+ - **openings** (`openings.ts`): `probeBook` looks a position up in a compiled opening
1060
+ book (ECO, name where a known line ends, UCI continuations), `parseUciMove` reads a
1061
+ UCI move back. The book is a game-side artifact built by `tools/compile-openings`
1062
+ from vendored CC0 tables, so no table ships with the framework.
1063
+ - **tourney** (`tourney.ts`): `searchTourney`/`searchTourneyAsync` over one
1064
+ self-contained `tourneyThink` task, so the worker side cannot diverge from the
1065
+ main-thread side: negamax alpha-beta with principal variation search, null-move
1066
+ pruning, late-move reductions, iterative deepening with aspiration windows, a bounded
1067
+ Zobrist transposition table, quiescence over captures and promotions, hash/MVV-LVA/
1068
+ killer/history ordering, and classical material plus in-house piece-square evaluation.
1069
+ Positions are plain bitboard data and structured-clone straight into workers.
1070
+ `TourneyResult.rootScores` is populated by an async search with legal root moves and
1071
+ scores from the mover's view, in root order, for near-best selection without a
1072
+ second search. The
1073
+ chess example plays its reply through `searchTourneyAsync`, with a thinking indicator,
1074
+ a per-move time cap, side and depth choice, a promotion picker and an in-check
1075
+ highlight.
1076
+ - **tablebase** (`tablebase.ts`): `probeTablebase`/`loadTablebaseEnding`/`tablebaseId`
1077
+ plus the `huffEncode`/`huffDecode` codec - WDL outcomes with distance-to-mate for
1078
+ pawnless white-extras-against-lone-king endings, fifty-move-adjudicated against an
1079
+ explicit halfmove clock, generated and verified by `tools/build-tablebases` and
1080
+ shipped compiled under `data/tablebases` (3-piece; 4-piece stays a tool run away,
1081
+ full 4-piece tables are tens of megabytes each).
1082
+ - **classics** (`Classics.ts`): `BoardGrid`; checkers
1083
+ (`startingCheckers`/`checkersMoves`/`applyCheckersMove`, forced multi-jump captures); go
1084
+ (`startingGo`/`playGo`/`passGo`/`goResult`/`goScore`, ko and area scoring); backgammon
1085
+ (`startingBackgammon`/`rollBackgammonDice`/`backgammonMoves`/`applyBackgammonMove`, bar
1086
+ and bearing off); cards (`createDeck`/`shuffleDeck`/`deal`/`trickWinner`); solitaire
1087
+ (`dealSolitaire`/`drawSolitaire`/`moveSolitaireTableau`/`moveSolitaireToFoundation`/
1088
+ `solitaireWon`, seeded Klondike); dice (`rollDice`/`rollExpression`/`DiceCup`/`scoreDice`,
1089
+ Yahtzee-shaped keep-and-reroll scoring).
1090
+ - **tactics** (`Tactics.ts`): `startingTactics`/`addTacticalUnit`/`canPlaceTacticalUnit`/
1091
+ `tacticalMoves`/`moveTacticalUnit`/`setTacticalOverwatch`/`triggerTacticalOverwatch`/
1092
+ `tacticalAttack`/`endTacticalTurn` - squad tactics: action points, cover, overwatch, and
1093
+ zone of control baked into `tacticalMoves`/move cost.
1094
+ - `FactionFog`/`VisionCell` - fog of war as a per-faction union of every controlled unit's
1095
+ own vision, with explored memory retained. `share` puts factions on one map, sight and memory
1096
+ alike, which is Wesnoth's `share_vision`; nothing shares until asked. `sees` hands a side's sight
1097
+ out as a predicate for anything that asks what it can see.
1098
+ - **army** (`Army.ts`): `startingArmy`/`recruit`/`recall`/`bankUnit`/`armyIncome`/
1099
+ `applyUpkeep` - recruiting/recalling units against a currency total, per-turn income and
1100
+ upkeep, no specific rate baked in.
1101
+ - **hex skirmish** (`HexSkirmish.ts`): `startingSkirmish`/`setSkirmishTerrain`/
1102
+ `canPlaceSkirmishUnit`/`addSkirmishUnit`/`skirmishMoves`/`moveSkirmishUnit`/
1103
+ `skirmishAttack`/`skirmishIncome`/`endSkirmishTurn` - a Wesnoth-style hex army-game rules
1104
+ layer distinct from `tactics` above: per-terrain movement cost and defence, adjacency-only
1105
+ attacks where a surviving defender always strikes back, capturable villages that grant
1106
+ income and heal whoever owns them, no zone of control.
1107
+ - `BoardPiece` (type, from `Classics.ts`) - a generic owned/countable/capturable/promotable
1108
+ token distinct from `roguelike`'s `Creature`-shaped actors; every game above builds on it.
1109
+
1110
+ ## `actors`
1111
+
1112
+ Stat blocks, equipment, inventory, and the numbers layer nearly every other module builds
1113
+ on. This is the *shape* - a game names its own attributes and formulas.
1114
+
1115
+ - `StatBlock`/`Modifier`/`DerivedStat` - base attributes plus derived stats, combined
1116
+ through ordered modifiers (add → multiply → set). `toJSON` saves base values only:
1117
+ modifiers are reapplied on load by whatever owns them (equipment, status effects, auras),
1118
+ so saving them too would double every bonus.
1119
+ - `composeModifiers` - the same canonical modifier composition as `StatBlock`, available to
1120
+ adapters that resolve declarative effect lists without creating a stat block.
1121
+ - `Progression`/`powerCurve` - levelling from experience against a growth curve; `toJSON`
1122
+ saves level and experience, the curve being a definition.
1123
+ - `skillCheck` - value-plus-modifiers against a difficulty, one dice roll.
1124
+ - `SkillPoints` - a spendable ledger that raises a stat's base rank, with per-stat caps and
1125
+ a rising cost per rank. `toJSON` saves only unspent points; the ranks bought are already
1126
+ in the `StatBlock`'s own base values.
1127
+ - `EquipmentSlots`/`EquippableItem`/`SavedEquipment` - equip/unequip applies or removes an
1128
+ item's modifiers immediately; an optional `locked` predicate refuses unequip/swap for
1129
+ cursed/quest gear. `toJSON(identify)` records slot-to-id, and `fromJSON` re-equips so every
1130
+ modifier lands back on the `StatBlock`; a locked item is restored still worn.
1131
+ - `Inventory`/`InventoryItem`/`ItemDefinition`/`SavedInventory` - stacking (by id, and by
1132
+ `instanceId` when either item sets one), weight, capacity, containers holding their own
1133
+ `Inventory`. `toJSON` saves per-item instance state (level, wear, affix, identified,
1134
+ `instanceId`) while `fromJSON(defs, data)` takes kind-level fields from the game's item
1135
+ table, so a rebalanced weight reaches an old save.
1136
+ - `craft`/`Recipe`/`Ingredient` - resolves a recipe against an `Inventory`: all-or-nothing, with a
1137
+ capacity-rollback path if the result doesn't fit. An ingredient may match an exact `id` (or a
1138
+ list of them), a `category` on the item's definition ("any herb"), or a `matches` predicate; the
1139
+ allocation is made against a working copy so two flexible ingredients cannot count one stack
1140
+ twice. `InventoryItem.category`/`ItemDefinition` carry the kind-level grouping (supplied by the
1141
+ game on load, like `stackable` and `weight`).
1142
+ - `applyStatusEffect`/`EffectClock`/`StatusEffectHandle` - a `StatBlock` modifier tied to a
1143
+ `TurnClock`'s automatic expiry; `cancel()` for early removal.
1144
+ - `identify`/`enchant`/`damageItem`/`repairItem` - identification; enchant/upgrade level
1145
+ (`enchant`'s `affixPolicy: 'keep' | 'remove'` decides whether an upgrade strips an
1146
+ affix); durability wear and repair, opt-in per item.
1147
+ - `applyItemStatusEffect` - a status effect sourced from an item rather than a spell.
1148
+ - `Charges`/`ChargesOptions` - a resource regenerating in banked-turn chunks via
1149
+ `advance(turns)`; `refund()` restores charges directly (a kill or crit), outside that path.
1150
+ `toJSON` saves the count *and* the progress banked towards the next, so reloading cannot
1151
+ shorten a recharge.
1152
+ - `rollLoot`/`LootEntry`/`LootTable` - rolls whether anything drops, then weight-picks
1153
+ which, the same "roll whether, then which" shape `world.rollEncounter` shares.
1154
+ - `Advancement` - level-gated tiers granting ledger points, with mutually-exclusive
1155
+ branch/capstone choices.
1156
+ - `rollAffix`/`affixOf`/`applyAffix`/`removeAffix`/`copyAffix`/`matchesContext` - named
1157
+ item affixes: weight-picked, applied/removed on `InventoryItem.affix`, copied between
1158
+ item instances, and matched against a fired trigger's attack `kind` via `AffixDef.kinds`.
1159
+ - `scaledModifiers`/`LevelScale` - level-scaled gear: `{stat, op, base, perLevel}` resolved
1160
+ to a plain `Modifier`.
1161
+ - `assignAppearances`/`Appearances` - per-run appearance shuffling for unidentified items,
1162
+ seeded and fixed for the run.
1163
+ - `buy`/`sell`/`Price`/`ShopOptions` - a currency-`StatBlock` transaction against an
1164
+ `Inventory`, all-or-nothing with rollback.
1165
+ - `canAfford`/`spend`/`refund`/`convertToCharges`/`ResourceCost` - a spendable `StatBlock`
1166
+ pool (mana, stamina): check, all-or-nothing spend, mirror-image refund (optionally
1167
+ fractional), or convert a spent amount into `Charges` at a rate.
1168
+ - `Barrier`/`BarrierLayer` - a layered shield/absorption pool; the most recently added
1169
+ layer drains first, with optional independent per-layer decay ticked by `advance(turns)`.
1170
+ - `assignTraits`/`TraitDef`/`AssignedTrait` - per-instance random traits drawn from a
1171
+ shared pool at creation, applied as permanent modifiers.
1172
+ - `AuraField`/`AuraDef`/`AuraParticipant` - continuously reapplies a carrier's modifiers to
1173
+ whoever is currently adjacent, diffing rather than reapplying every tick.
1174
+ - `SupportLedger` - a pair-order-independent, thresholded bond/support relationship between
1175
+ two units, growing through proximity or shared battles; `toJSON`/`fromJSON` round-trip it.
1176
+ - `buildEntity`/`buildEntities`/`EntityTemplateRow`/`EntityTemplateCatalog`/`BuiltEntity` - one
1177
+ row of a hero or monster file (typically a `core.parseCSV` result) into a fully wired
1178
+ entity: a `StatBlock` of base stats (every non-reserved column), an optional `Progression`
1179
+ against a named growth curve, a starting item carrying a named starting affix, and a
1180
+ `ReactionTable` already holding a low-HP rule if the row names a threshold. What each named
1181
+ growth curve/affix/item actually is stays the game's own `EntityTemplateCatalog`.
1182
+ - `toEntitySaveState`/`fromEntitySaveState`/`EntitySaveState` - a `BuiltEntity`'s mutable state
1183
+ (base stat values, level/experience, the carried item) in the same "definitions supplied
1184
+ fresh on load" shape `StatBlock`/`Progression` already draw. `fromEntitySaveState` rebuilds
1185
+ via `buildEntity` from the same row and catalog, then overlays the saved state on top.
1186
+
1187
+ ## `roguelike`
1188
+
1189
+ FOV, pathfinding, the energy scheduler, level generation, and combat-adjacent primitives -
1190
+ the dungeon-crawl half of the capability spec.
1191
+
1192
+ - `Level`/`WALL`/`FLOOR`/`rectCenter`/`rectsOverlap` - the tile grid: terrain kinds,
1193
+ passability/transparency, square or hex `shape`.
1194
+ - `generateDungeon`/`findFreeCell`/`furthestRoom`/`DUNGEON_KINDS` - procedural dungeon
1195
+ generation.
1196
+ - `generateDungeonGraph` - the same pipeline as `generateDungeon`, also returning the room
1197
+ graph (corridor edges, backbone then extra loops) and a rejected-placement retry count;
1198
+ `DungeonOptions.hooks` fires `onRoomPlaced`/`onCorridorCarved` as the pipeline runs, the
1199
+ seam a regional generator hangs hand-placed rooms, branches, wells, plants, statues,
1200
+ chasms, doors and traps from.
1201
+ - `generateCave` (item 407) - the cave counterpart: chambers grown as random blobs
1202
+ (`jagged` the chance a growth step wanders), passages as biased random walks
1203
+ (`windiness`, `width`, `chance`), starts on chamber centres with cleared rings,
1204
+ `villageDensity` returning picked clear cells as data, and a forced join so a cave is
1205
+ always connected whatever the rolls did. Seeded through the `Random` stack like the
1206
+ dungeon.
1207
+ - `generateOverworld` (item 410) - a whole realm as plain tile data: seeded elevation and
1208
+ moisture fields classify water, plains, forest, hills, mountains, desert and swamp behind
1209
+ a `seaLevel` knob; rivers run downhill to the sea, merging when they meet, drowning a
1210
+ lake at a ridge instead of crossing it; settlements place themselves by suitability
1211
+ (buildable ground, water within reach, spaced apart) and join into a road tree that
1212
+ prefers flat ground, water a ford rather than a wall; points of interest carry a
1213
+ `leadsTo` id for `Overworld` locations, and every cell carries a coarse region id for
1214
+ encounter tables. The realm invents itself from the seed: no reference game's map data.
1215
+ - `shape: 'hex'` on `generateDungeon`, `generateDungeonGraph`, `generateCave` and
1216
+ `generateOverworld` lays the same generator out on a hex grid (odd-q offsets, the `Level`
1217
+ convention): the dungeon and cave `Level` carry the hex shape, a dungeon corridor leg runs
1218
+ as a hex line, a cave grows its chambers by hex distance and walks passages toward their
1219
+ target in true on-screen distance, and the overworld samples its noise where each hex is
1220
+ drawn and steps rivers and roads across the six edges. The default stays square, byte for
1221
+ byte. `generateCave` also takes `random` (a `RandomSource`, such as a `Generator`) in place
1222
+ of `seed`: it draws from, and advances, that stream, leaving the ambient `Random` stack
1223
+ untouched.
1224
+ - `RoomBuilder`/`hallBuilder`/`eligibleBuilders`/`pickBuilder` - composable room interiors:
1225
+ the generator places and joins rooms, a builder carves each one, picked by weight among
1226
+ those whose size constraints fit. `DungeonOptions.builders` wires them in; a room no
1227
+ builder fits falls back to a plain hall rather than staying solid rock.
1228
+ - `FeatureLayer` - a floor feature/event layer: named kinds with `inspect`/`interact`/
1229
+ `consequence`/`persistent` rules attached to generated cells; definitions supplied fresh
1230
+ on load, only cell-to-kind pairs are save data.
1231
+ - `rollRoster` - a variant-spawn/content-roll API: weighted regular entries, rare additions,
1232
+ per-entry alternative swaps, and a shuffle, in that order; every roll (including an
1233
+ explicitly disabled rare entry's non-roll) is traced for parity tests.
1234
+ - `candidateCells`/`cellsNear`/`selectDistinctCells` - deterministic content placement over a
1235
+ `Level`: `candidateCells` filters by terrain kind, occupancy and an optional region;
1236
+ `cellsNear` walks outward by radius for a cluster anchor; `selectDistinctCells` shuffles and
1237
+ slices a de-duplicated pool, bounded to however many candidates exist rather than throwing.
1238
+ Composes for neighbouring-item clusters, scattered decorations, and single room/branch
1239
+ rewards; nothing is placed until the caller commits, and the returned trace is plain
1240
+ JSON-safe data for `DungeonArtifacts.content` or a save file.
1241
+ - `compareDungeonArtifacts`/`checkDeterminism` - a dungeon parity/test harness: diffs a
1242
+ seeded run's room graph, retries, terrain, features and content rolls against a reference
1243
+ or golden fixture, tagging every mismatch `'graph'` or `'paint'`; `checkDeterminism` repeats
1244
+ a generation call and confirms every run matches the first.
1245
+ - `FieldOfView`/`HeightSight` - shadowcast (square) or straight-line (hex) visibility, with
1246
+ `Elevation`-aware asymmetric cliff sight.
1247
+ - `Elevation` - whole-level height per cell, read by `FieldOfView`/`Pathfinder`.
1248
+ - `Pathfinder`/`neighbourOffsets` - A*(square)/Dijkstra(hex or elevation-aware) pathing,
1249
+ `distanceMap`/`descend`/`autoExplore`, an optional climb limit.
1250
+ - `Scheduler`/`Actor`/`SchedulerSnapshot` - energy-cost turn order, the sole authority on
1251
+ logical time; fractional costs, `postpone` (delaying an actor other than the current one),
1252
+ and `toJSON`/`restore` for a deterministic snapshot keyed by a caller-supplied actor id.
1253
+ - `decideMonsterAI`/`AIState`/`AIDecision`/`Disposition` - wander/hunt/flee built on
1254
+ `FieldOfView`/`Pathfinder`/`Scheduler`; peaceful/neutral/hostile disposition, provoked
1255
+ override.
1256
+ - `Secrets` - disguised terrain (secret doors, hidden traps) that passes every
1257
+ passable/transparent check as its disguise until revealed.
1258
+ - `Doors` - open/closed/locked door state; locking is independent of open/closed.
1259
+ - `chebyshevDistance`/`traceLine`/`ballistica`/`hasLineOfSight`/`canTarget`/`resolveArea` -
1260
+ targeting and collision paths: range/line-of-sight checks, configurable stopping cells,
1261
+ and single/line/burst/cone area resolution.
1262
+ - `TargetingController` - the input-facing half of targeting: a cursor moved by keyboard
1263
+ (`move`) or by a caller-resolved pointer cell (`moveTo`), range and line-of-sight
1264
+ validation with an optional game `validate` hook, a `preview` of the shape's cells, and a
1265
+ `confirm`/`cancel` result. It returns cells only; the game keeps legality details, damage
1266
+ and drawing.
1267
+ - `coneCells`/`chainTargets`/`knockbackPath` - a widening cone spray, a greedy nearest-hop
1268
+ chain, and a shove's path until the first impassable cell.
1269
+ - `coneSector`/`ConeSectorOptions` - a circular sector aimed at an angle: rays cast every 0.5
1270
+ degrees across an arc of `degrees`, each clamped to `range` and stopped by the first wall, so a
1271
+ wall shadows what is behind it while the rest of the cone reaches. Unlike `coneCells`, the aim
1272
+ is not snapped to one of the eight directions.
1273
+ - `resolveAreaOnLevel`/`hexConeCells` - topology-aware area resolution and widening hex cones,
1274
+ complementing the square-grid targeting helpers.
1275
+ - `rangeMultiplier`/`areaFalloffMultiplier`/`RangeBand` - a range-band damage multiplier
1276
+ lookup, and a per-target falloff multiplier for an area effect hitting several targets.
1277
+ - `BossPhases`/`AbilityCycle` - an HP-fraction phase ladder whose `check(hpFraction)` reports
1278
+ newly entered phases, and a named-cooldown ability rotation (`ready`/`use`/`advance`).
1279
+ - `CombatHooks`/`CombatEvent`/`DamageContext` - `core.HookRegistry` with combat's argument
1280
+ shape (one mutable `DamageContext`), plus `modifyDamage`'s pre-damage seam.
1281
+ - `Stealth`/`StealthOptions` - sticky, one-way detection: `checkDetection` returns true
1282
+ only on the call that first brings an observer within radius.
1283
+ - `TriggerTracker` - a streak counter (combo, kill-streak) that extends within a turn
1284
+ window and restarts once the window lapses.
1285
+ - `MultiStageAbility`/`AbilityStage` - an ability that unfolds through named, turn-timed
1286
+ stages (windup/active/recovery) once started.
1287
+ - `Minimap`/`minimapCellCenter` - exploration minimap rendering and overlay coordinates for
1288
+ square and odd-q hex maps.
1289
+ - `MultiTurnBeam` - a deterministic one-front-per-turn beam. The default shape is a straight line;
1290
+ `fronts` opts into a per-turn front resolver (cone, burst, fork, moving front), `blocker` is the
1291
+ explicit terrain/`none`/custom policy with `isBlocked` as an extra game rule, `onCell` sees every
1292
+ reached cell, and a save carries the shape name so a reload resumes the same one. Live target
1293
+ lookup, game-owned damage application, cancellation and save/restore as before.
1294
+ - `BeamBlocker`/`BeamStep`/`MultiTurnBeamSave` - the blocker policy, one turn's reached cells and
1295
+ damage, and the serialisable front list with its shape identity.
1296
+
1297
+ ## `rpg`
1298
+
1299
+ Tiled map/event data, the map-event interpreter, switches/variables, and grid movement -
1300
+ the classic top-down RPG half.
1301
+
1302
+ - `automap`/`AutomapRule`/`AutomapTarget`/`AUTOMAP_EMPTY` - Tiled-style automapping:
1303
+ `input`/`output` pattern rules applied in order, each rule's matches collected before any
1304
+ write. Takes any grid exposing `getTile`/`setTile` (a `TileMap` satisfies it structurally),
1305
+ so automapping needs no renderer.
1306
+ - `GameState` - switches and variables.
1307
+ - `activePage`/`conditionHolds`/`EventPage`/`MapEvent` - last-matching-page resolution for
1308
+ a map event, re-checked rather than cached.
1309
+ - `EventRunner`/`EventCommand`/`DialoguePresenter`/`DialogueRequest`/`EventChoice` - a
1310
+ `StageScript`-shaped command interpreter for map events. Dialogue goes through an injected
1311
+ `present` function rather than a widget, so the interpreter is renderer-free and a game can
1312
+ drive it from a 3D scene, a DOM overlay, or a test asserting on script order.
1313
+ `two-d/ui.messageBoxPresenter` is the ready-made 2D implementation. `DialogueRequest.portrait`
1314
+ is an opaque, renderer-specific value (`Texture2D` for `messageBoxPresenter`), kept untyped
1315
+ here so `rpg` stays renderer-free. `EventRunner.runStory`/`EventStoryScript` follow a named-
1316
+ passage graph the same way `StageScript.runStory`/`StoryScript` do - a `goto` command, or a
1317
+ choice's own `goto`, jumps to a different passage; a plain `run()` refuses a stray `goto`
1318
+ rather than silently ignoring it, the same guard `StageScript.run` applies.
1319
+ `EventRunnerOptions.onUnknownCommand` hears every command the runner has no handler for (and a
1320
+ `goto` in a straight `run()`, which then ends the list instead of throwing), so a game converting
1321
+ foreign event data can make every dropped command loud.
1322
+ - `importTwee`/`EventTwineStory` - imports Twee-notation Twine stories into `EventStoryScript`,
1323
+ a thin wrapper around `core.parseTwee` (the same engine `two-d/stage.importTwee` wraps for
1324
+ `StageCommand`/`StoryScript` instead) naming the `EventStoryScript` return type, so a
1325
+ text-only RPG can import a branching Twee story without depending on `two-d` for anything.
1326
+ - `GridMover`/`Direction4` - tweened tile-to-tile movement plus a walk-cycle hook.
1327
+ `GridMover.jumpBy` repositions instantly, with no tween or walk animation, for a move-route
1328
+ "jump" step.
1329
+ - `MoveRouteRunner`/`MoveRoute`/`MoveRouteStep`/`MoveRouteOptions` - drives any `GridMover`
1330
+ (the player's or an NPC's) through a scripted route over successive `update(dt)` calls:
1331
+ fixed/random/toward/away directional steps, a turn-in-place step, a jump step, and a wait
1332
+ step, with `repeat` and `skippable` policies. Whether a step is passable is asked through the
1333
+ same `canMove` contract `GridMover` itself expects of its own caller.
1334
+ - `FreeMover` - continuous (non-grid) position and facing, for action-game movement.
1335
+ - `MovableSprite` - what both movers actually require: `x`/`y`, and optionally `update`/`has`/
1336
+ `play`. A static sprite, a 3D mesh wrapper or a plain test record all satisfy it.
1337
+ - `aabbOverlap`/`circleOverlap`/`circleAabbOverlap`/`resolveAabbAgainstTiles` - 2D
1338
+ collision: shape overlap tests, and an axis-separated sweep against solid tiles.
1339
+ - `QuestLog`/`QuestStage`/`QuestDefinition`/`QuestMarker` - quest stages advanced one at a
1340
+ time by `advanceStage`, prerequisites, `markerFor` deriving `'offer'`/`'turnIn'`/`'none'`,
1341
+ and a tracked-quest pointer/location.
1342
+ - `questsFromRows`/`QuestStageRow` - groups a flat table of stage rows (typically a
1343
+ `core.parseCSV` result, one row per stage sharing a `questId`) into `QuestDefinition`s a
1344
+ `QuestLog` can `define`.
1345
+ - `decodeMarshal`/`encodeMarshal`/`RubySymbol` - Ruby `Marshal` 4.8 binary serialization
1346
+ (the container format RPG Maker's own `.rxdata` saves use).
1347
+ - `hashDefaultOf`/`withHashDefault` - reads and attaches a Ruby hash's default value, which
1348
+ `Marshal` carries alongside the entries rather than as one of them.
1349
+ - `parseDialogueText`/`extractDialogueCatalog` - the terse `@id text`/`-`-alternation dialogue
1350
+ format targeting `EventCommand`, a thin wrapper around `core.parseDialogueLines` (the same
1351
+ engine `two-d/stage.parseDialogueText` wraps for `StageCommand` instead), so a text-only
1352
+ RPG (`core` plus `rpg`, no renderer at all) can author dialogue without depending on
1353
+ `two-d` for anything. `extractDialogueCatalog` builds an identity `i18n` catalog from the
1354
+ result, the same shape MWL's own `extractCatalog` builds from `_("...")`-marked strings.
1355
+
1356
+ ## `simulation`
1357
+
1358
+ `TrainingEnvironment` adapts game-owned `TrainingRules` around the existing
1359
+ `SimulationRule`, with no renderer, DOM, audio or animation loop. `reset(seed)`
1360
+ returns a `TrainingFrame` with per-agent observations, rewards, `terminated` and
1361
+ `truncated`. `step(actions)` takes one action index per agent (or `null` only for
1362
+ an all-masked idle agent), invokes the same rule used during play and returns the
1363
+ next frame. Rewards inspect a cloned pre-transition state, so mutable rules work.
1364
+ The agent roster stays fixed within an episode. `maxSteps` is required and capped
1365
+ at one million; reaching it truncates an unfinished episode, while rule completion
1366
+ terminates it. Real-time games advance fixed simulation ticks inside their rules;
1367
+ turn-based games advance turns. Neither waits for wall-clock time. A throwing
1368
+ rule can mutate its state, as with `runScenario`; reset or restore before continuing.
1369
+
1370
+ `snapshot()`/`restore()` use `TrainingSnapshot`: versioned environment state, schema,
1371
+ step limit, completion flags, seed and RNG state. `TrainingCheckpoint<State, TrainerState>`
1372
+ combines that snapshot with the `NeuralModel` and game-owned optimizer/exploration
1373
+ state. Persist every random stream the trainer uses in `trainerState`. Train with
1374
+ the same observation schema and action ordering used by the playable game.
1375
+
1376
+ `runRollouts(environment, model, RolloutOptions)` chooses actions from each new
1377
+ observation until completion. Options provide episode seeds, optional seeded
1378
+ softmax sampling and `trajectoryLimit` (first transitions per episode, zero by
1379
+ default). `RolloutEpisode` reports steps, cumulative per-agent rewards, completion
1380
+ flags and a bounded array of `TrainingTransition`s. No command journal or presentation
1381
+ events are retained. Batches accept at most 10000 episodes and 10000 stored transitions.
1382
+
1383
+ `runRolloutsAsync(TrainingFactory, config, model, options)` shards episodes across
1384
+ workers (default four, configurable `jobs` in 1..64). Each worker keeps its model,
1385
+ environment and inference buffers for the whole shard. Results stay in seed order;
1386
+ `signal` and per-worker `timeout` terminate work, and any failure terminates sibling
1387
+ workers. The factory must be self-contained, like `threads.spawn`, accepting the
1388
+ supplied `TrainingEnvironment` constructor and structured-cloneable configuration;
1389
+ it cannot close over module imports. Both paths run the same classes and inference
1390
+ code, including in a compiled `file://` page. Training algorithms and rewards are
1391
+ game-owned; `tools/train-neural.ts` shows a seeded evolution optimizer, resumable
1392
+ checkpoint and model export, and `examples/neural` loads its trained weights.
1393
+
1394
+ `imitationFromReplay(environment, { actions, events, seed })` turns a persisted run
1395
+ (roadmap 397) into imitation targets: it walks the recorded actions against the
1396
+ same seeded environment they were played on and returns the `(observation, action)`
1397
+ samples a game's own trainer fits, sourced from how its players played rather than a
1398
+ generated expert. One recorded event is one environment step; the environment must
1399
+ expose exactly one agent (the recorded player - anything else that moves is part of
1400
+ the rule, like the maze chase's ghosts); a recorded action outside the list is a
1401
+ named error, never a silently skipped event.
1402
+
1403
+ `runSeededEpisode(environment, choose, { seed })` plays one whole run with the AI
1404
+ choosing, from a named seed: the same seed and the same deterministic `choose` make
1405
+ the same decisions, so runs compare across builds, policies and machines. Unlike
1406
+ `runRollouts` the chooser is not a `NeuralModel` - a heuristic, a `NeuralPolicy`'s
1407
+ argmax, or any named function works - and the result records every chosen action and
1408
+ the cumulative rewards, with the environment's `maxSteps` as the truncation bound.
1409
+
1410
+ Headless, deterministic turn/scenario running - for testing and benchmarking without a
1411
+ live game loop.
1412
+
1413
+ - `advanceToInput`/`ScheduledTurns`/`TurnRules`/`TurnResult` - drives turns forward under a
1414
+ rule set until the next input is due.
1415
+ - `runScenario`/`Scenario`/`ScenarioResult` - a bounded, scripted simulation run against a
1416
+ set of expectations.
1417
+ - `Campaign`/`CampaignLevel`/`CampaignLevelResult`/`CampaignSnapshot` - generic level order,
1418
+ result, carry-over, reminder and transition state, with JSON-safe save/restore.
1419
+ - `runHeadlessScenario`/`HeadlessScenario`/`HeadlessScenarioResult` - seeded, renderer-free
1420
+ scenario execution returning the final state, ordered events and resumable random state.
1421
+ - `SimulationRuntime`/`SimulationContext`/`SimulationOutcome`/`SimulationRuntimeRule`/
1422
+ `SimulationSnapshot` - a facade over one state + one `roguelike.Scheduler` + one `core.
1423
+ Generator`, for the interactive half of a turn-based simulation: `dispatch` runs a single
1424
+ command through the game's rule, threading `random`/`scheduler` as context and charging any
1425
+ returned cost; `snapshot`/`restore` capture and rebuild the whole triple. Commands, events and
1426
+ (with `history`) state are journalled through `structuredClone`, so they must be plain data:
1427
+ name an actor by id, never pass the live object. A `dispatch` that cannot copy them throws
1428
+ with the offending path and commits nothing. Composes with
1429
+ `advanceToInput` against the same scheduler for the automatic-actor loop, rather than
1430
+ replacing it.
1431
+ - `EventPresentation`/`EventPresentationOptions` - the documented pattern tying a
1432
+ `SimulationRuntime` to a `core.PresentationQueue`: `submit` commits a command and starts its
1433
+ events, `locked` is the animation lock `submit` refuses under, `followUp` schedules a
1434
+ secondary actor's commands for after the current batch, `cancel` drops the rest of the show
1435
+ without rolling the committed turn back, and `snapshot`/`restore` deliberately leave the
1436
+ queue out of a save so a load resumes idle.
1437
+ - `Scheduler`/`Actor`/`SchedulerSnapshot` - re-exported here from `roguelike` (its real home),
1438
+ since every `SimulationRuntime` needs one; a simulation-first game need not import a second
1439
+ module just to construct the class its own runtime is built around.
1440
+ - `CampaignSave`/`CampaignSaveState`/`CampaignSaveParts` - one `core.SaveSystem` slot for a whole
1441
+ campaign: `save` captures the `Campaign` snapshot, the game's own world payload and the
1442
+ `SimulationRuntime` snapshot together, `load` reads them back migrated, and `list`/`delete` are
1443
+ `SaveSystem`'s. The world is opaque, so an `MwlWorld`, a `Level` or a game's own scenario object
1444
+ all fit.
1445
+
1446
+ ## `skeleton`
1447
+
1448
+ Skeletal pose math, renderer-free: a bone tree, keyframed clips and layered blending, as
1449
+ pure data and arithmetic so it loads headless and tests without a renderer. Clips are plain
1450
+ JSON-shaped data a game authors itself. `import * as Skeleton from '@datamoc/mw_games/skeleton'`.
1451
+
1452
+ - `create(bones)` - builds a `SkeletonBones` from `Bone`s (`name`, `parent`, `length`,
1453
+ `origin`, `rest` `rotation` in degrees, optional `limits`), throwing by name on a duplicate
1454
+ bone, a cycle, a missing parent or inverted joint limits. `boneOrder` lists names parents
1455
+ first.
1456
+ - `resolve(skeleton, pose?)` - walks the tree and returns one `BoneTransform` per bone (world
1457
+ `x`/`y`, `angle`, composed scale, a 2D `matrix`, and the `tipX`/`tipY` the children start
1458
+ from). A `Pose` is one rotation per bone name; a `TransformPose` adds per-bone translations
1459
+ and scales.
1460
+ - `samplePose`/`sampleTransformPose(clip, time, skeleton?)` - a `Clip` (`duration`, `loop`,
1461
+ ascending `Keyframe`s) interpolated at a time: a looping clip wraps, a one-shot holds its
1462
+ last frame. Passing the skeleton validates the result.
1463
+ - `advancePlayback`/`createMixer`/`crossfadeTo`/`advance`/`advancePose` - a `Mixer` holds a base
1464
+ `Playback` plus weighted, prioritised additive `Layer`s. `advance(mixer, dt)` ticks every
1465
+ playhead, folds in a running crossfade and the layers, and returns rotations;
1466
+ `advancePose` returns the full `TransformPose`. `mixPoses` blends rotation poses by layer
1467
+ priority and weight.
1468
+ - `validatePose` - refuses non-finite rotations and angles outside a bone's `limits`.
1469
+ - `solveTwoBoneIK(skeleton, first, second, target, bend?, pose?)` - solves a connected
1470
+ two-bone chain toward a world target without stretching; throws for an unreachable target
1471
+ or a second bone with a non-zero origin.
1472
+
1473
+ ## `physics`
1474
+
1475
+ Small deterministic simulations, renderer-free, with no third-party engine. Three entry
1476
+ points: `@datamoc/mw_games/physics` (rigid bodies, cloth, spring) and
1477
+ `@datamoc/mw_games/physics/xpbd` (a structure solver). Everything is plain arithmetic, so a
1478
+ game's headless tests run the same world.
1479
+
1480
+ - `PhysicsWorld` - rigid circles and axis-aligned boxes (never rotating: `angle` is a display
1481
+ offset), stepped on a `FixedStepper` so results do not depend on the display refresh rate.
1482
+ Semi-implicit Euler, impulse contacts with restitution and friction, and distance joints.
1483
+ `addBox`/`addCircle` return a plain `PhysicsBody` (`position`, `velocity`, `angle`, `label`,
1484
+ `isStatic`); `connect` joins two bodies or a body and a world point
1485
+ (`ConstraintOptions`: `stiffness`, `damping`, `length`, attachment points, and `maxStretch`
1486
+ to make the joint breakable); `remove` takes a body or constraint; `stretchOf` reads a
1487
+ joint's strain; `update(dt)` runs the fixed steps it covers and returns their count.
1488
+ `onContact` and `onBreak` are `Signal`s.
1489
+ - `XpbdWorld` (`physics/xpbd`) - point masses (`addNode`, `fixed` anchors) joined by springs
1490
+ (`addLink`: `stiffness`, `rest`, `tensionOnly` cables, `strength`/`tensionStrength`),
1491
+ solved with extended position-based dynamics and the force in each link read back, so a link
1492
+ breaks at a real load. Fixed steps and no randomness make a replay identical on every
1493
+ machine. `step()` advances one frame; `applyForce` pushes a node for one step; `ground` is a
1494
+ height or a function of x; `breaking` gates breaking so a structure can settle first;
1495
+ `onBreak` fires per broken link and `peakRatio` is a strain gauge. It has no rigid bodies or
1496
+ collisions, which is what `PhysicsWorld` is for.
1497
+ - `Cloth` - a pinned-point Verlet grid (top row pinned) with structural links only, no
1498
+ allocation per step. `indexOf`/`pointPosition`/`pointLinks`/`writePositions` read it back;
1499
+ `pinPoint`/`unpinPoint`, `setWind`/`setGravity`, `reset` and `update(dt)` drive it.
1500
+ `two-d`'s `ClothSprite` draws one as a mesh on the GPU path.
1501
+ - `Spring` - a damped chase spring for secondary motion (hair, hems, panels): `setAnchor`
1502
+ moves the target, `displace` shoves the bob, `offset`/`length`/`settled(tolerance)` read the
1503
+ lag, `place(target)` positions a display object, `update(dt)` steps it. Under reduced motion
1504
+ it follows `SpringOptions.intent` (`decorative` snaps to the anchor).
1505
+
1506
+ ## `testing`
1507
+
1508
+ Test doubles for the seams mwg takes by injection (item 388), so a game's tests and this
1509
+ repository's own share one copy of each. Renderer-free, dependency-free, and off the root barrel:
1510
+ nothing here reaches a shipped game unless a test imports it.
1511
+ - `createSceneControls` (item 408) - named steps a game opts into (`enterScenario`,
1512
+ `finishTurn`, `advanceDialogue` in the Wesnoth port), driven by name from a test or a
1513
+ headless Chrome: the game decides what a step does, the controls only promise that a
1514
+ registered name runs and an unknown one is refused by name.
1515
+ - `memoryStorage` - a `SaveStorage` held in memory, for `SaveSystem`, `Settings`, `Collection`,
1516
+ `PlayerStats` and the other stored values; the same class `core` falls back to where
1517
+ `localStorage` is missing.
1518
+ - `fakeAudio`/`fakeAudioWithEnded`/`FakePlayable` - a `Playable` for `Sound`/`Music`'s `create`
1519
+ that counts its plays; the second also has the `onended` slot a backend reporting track ends
1520
+ has.
1521
+ - `FakeSocket` - a `WebSocketLike` for `LockstepClient`'s `create`: `sent`, `receive(message)`,
1522
+ `receiveRaw(text)`, `close()`.
1523
+ - `fakeFetch`/`FakeFetchCall` - a `fetch` for every `HttpTransport` client, answering with a
1524
+ `Response` or a value sent as JSON, recording each call.
1525
+ - `fakeGamepad` - a `Gamepad` from button values (pressed above 0.5) and axes, for `Input` and
1526
+ `PlayerInput`.
1527
+
1528
+ ## `threads`
1529
+
1530
+ Runs a self-contained function on a worker thread, so a blocking computation costs a
1531
+ background thread instead of a dropped frame. mwg's own runtime rather than a dependency:
1532
+ a classic blob worker in the browser, because that is the one shape a double-clicked
1533
+ `file://` page accepts (the shipped CSP allows `worker-src blob:` and `new Function`, and
1534
+ a module worker loaded from `file://` fails CORS whatever the policy says), and
1535
+ `node:worker_threads` in Node. Off the root barrel like `testing`: a game that never
1536
+ spawns a worker pays nothing for it, and imports `@datamoc/mw_games/threads` when it
1537
+ wants one.
1538
+
1539
+ - `spawn(fn, args?, options?)` - runs `fn` on a worker and resolves with its value. The
1540
+ task is serialized with `Function.prototype.toString`, so it must be self-contained:
1541
+ no closures over module scope, no imports, no bound or native functions - everything it
1542
+ needs arrives as `args`, structured-cloned in. `options.transfer` moves listed buffers
1543
+ instead, detaching them from the caller's thread. The result returns structured-cloned
1544
+ with every `ArrayBuffer` inside it transferred rather than copied, since the worker is
1545
+ finished with them. A task that throws, closes over something the worker cannot see, or
1546
+ kills its worker without answering rejects the promise instead of hanging it;
1547
+ `options.timeout` abandons a task that never returns, and `options.signal` (an
1548
+ `AbortSignal`) cancels one on demand. One worker per task, terminated the moment it
1549
+ settles. In Node an unsettled task keeps the process alive, so settle or cancel every
1550
+ task before exit.
1551
+
1552
+ ## `headless`
1553
+
1554
+ The blessed renderer-free entry: every module that loads in bare Node, in one import,
1555
+ with no DOM or WebGL globals. A rule imported through here is headless by construction;
1556
+ anything outside it belongs in presentation, not in the rule.
1557
+
1558
+ - `core`/`simulation`/`mwl` - scenes, saves, RNG, headless scenarios and content tables.
1559
+ - `i18n`/`actors`/`world`/`battle` - messages, stats, maps, encounters and type matchups.
1560
+ - `roguelike`/`board`/`audio`/`rpg` - dungeon generation, board rules, sound/music
1561
+ primitives (inject `create`, as under plain `audio`) and map events.
1562
+ - `ai`/`testing` - decision runners and the shared test doubles.
1563
+ - `assetPaths`/`assetBinary` - the two renderer-free asset halves (path resolution and
1564
+ byte caching) beside the Pixi-backed `assets` loader.
1565
+
1566
+ Excluded with reasons in `src/headless/index.ts`: `three-d` (needs Babylon at import),
1567
+ the Lua runtimes (`mwl/pyroeis`, `ai/lua`), and every `two-d/*` module.
1568
+
1569
+ ## `three-d` (optional)
1570
+
1571
+ Babylon.js-backed 3D, kept fully separate from the 2D default - nothing in `core` imports
1572
+ this module.
1573
+
1574
+ - `Engine3D` - owns Babylon's engine, scene, orbit camera, light, resize, and render loop.
1575
+ - `gridPoint3D`/`GridCell3D`/`GridShape3D` - square/hex 3D grid cell projection.
1576
+ - `createTileGrid3D` - a thin-instanced 3D tile floor (square or hex) with elevation
1577
+ columns for nonzero cell heights.
1578
+ - `Character3D` - moves an imported mesh or a camera-facing billboard sprite through
1579
+ continuous world coordinates; `playAnimation` plays a clip an imported model carries.
1580
+ - `parseVox`/`createVoxModel3D` - MagicaVoxel `.vox` import, batched by colour.
1581
+ - `loadModel3D`/`loadModelContainer3D`/`isModelContainerLoaded`/`releaseModelContainer`
1582
+ (`@datamoc/mw_games/3d/models`, kept out of the main `3d` barrel so a scene that never
1583
+ imports a model pays nothing for the loader) - glTF/GLB import. `loadModel3D` imports
1584
+ straight into the scene, for one copy; `loadModelContainer3D` fetches and parses a source
1585
+ once, caches the `AssetContainer`, and a game calls `instantiateModelsToScene()` on it for
1586
+ each independent, unaliased copy it wants placed - Babylon's own answer to "load once,
1587
+ place many" without a second network fetch.
1588
+ - `createHeightmapTerrain3D` - a continuous displaced-mesh terrain from a greyscale
1589
+ heightmap image, alongside `createTileGrid3D`'s stepped floors.
1590
+ - `buildHeightIndex`/`cellAt`/`heightAt`/`resolveCapsuleAgainstGrid` - horizontal collision
1591
+ for a moving capsule against `createTileGrid3D`'s stepped grid.
1592
+
1593
+ ## `world`
1594
+
1595
+ Many maps, transitions, persistence, the turn clock, encounter tables - the connective
1596
+ tissue between scenes.
1597
+
1598
+ - `World` - many maps, each created once and kept alive (or rebuilt fresh per entry when
1599
+ defined `persistent: false`); `unload` frees a map's own state.
1600
+ - `Overworld`/`Location` - named-location lookup.
1601
+ - `TurnClock`/`TimedEffect` - hunger/poison-style timed effects, ticked on `advance`.
1602
+ - `rollEncounter`/`EncounterTable` - rolls whether an encounter fires, then weight-picks
1603
+ which.
1604
+ - `EnvironmentClock`/`DayPhase`/`EnvironmentSnapshot` - a continuous day/night-phase and
1605
+ weather clock above any one encounter, driven by `update(dt)` in real seconds, with change
1606
+ notifications and `toJSON`/`fromJSON`.
1607
+ - `SideTurns`/`SideTurn`/`TimeOfDay`/`TimeArea`/`Alignment`/`alignmentBonus` - the reference
1608
+ strategy game's outer turn model: sides take turns in order, a round is all of them, and the
1609
+ time-of-day schedule steps on per round. `lawfulBonusAt` applies a unit's alignment to the
1610
+ current time's `lawfulBonus`, and a `TimeArea` overrides the schedule for part of the map,
1611
+ which is what makes the bonus per-hex. `toJSON`/`fromJSON` resume the exact position.
1612
+
1613
+ ## `i18n`
1614
+
1615
+ Message tables, plurals, interpolation, and direction - pure logic, no Pixi dependency.
1616
+
1617
+ - `Direction`/`Catalog`/`MessageValue` - the message-table shape: locale, direction,
1618
+ messages, an optional Fluent-parsed or plain-string/plural-form value.
1619
+ - `setBase`/`setActive`/`locale`/`direction` - the active and fallback language, and the
1620
+ direction `ui`'s `Theme.direction` reads from; `reset` clears both back to unset.
1621
+ - `t`/`tRaw`/`formatSpec`/`tokenizeMessage`/`diffPlaceholders`/`MessageParams` - resolves a key, selecting a plural form via `Intl.PluralRules` and
1622
+ interpolating `{token}`s, including dotted paths that walk into nested params
1623
+ (`{side.stored.hitpoints}` against `{ side: { stored: { hitpoints: 12 } } }`); falls back to the
1624
+ base language, then to the raw key. Placeholders
1625
+ also take Python f-string-style specs (`{dmg:03d}`, `{hp:.1%}`, `{name:>12}`), `!s`/`!r`/`!a`
1626
+ conversions and `=` debugging, resolved through `formatSpec` (verified case by case against
1627
+ CPython; an ill-fitting spec stays untouched rather than throwing). `tokenizeMessage` is
1628
+ the single definition of that placeholder grammar, shared by interpolation and by
1629
+ `diffPlaceholders`, which compares a reference string against its translation (dropped,
1630
+ added, or reshaped tokens) for `tools/i18n-edit` to surface. `tRaw`
1631
+ skips the display-text decoration (typographic spacing, RTL wrapping) for catalog values
1632
+ that are not shown to the player, such as a sound path.
1633
+ - `parseSoundMarkers`/`stripSoundMarkers`/`InlineSoundCue`/`ParsedSoundText` - extracts
1634
+ `{sound:path}` markers from translated text, returning marker-free display text and each
1635
+ cue's visible-character offset. `MessageBox` consumes these markers during its reveal;
1636
+ `t()` and `tRaw()` preserve them for the presentation layer.
1637
+ - `typographic` - locale-aware curly-apostrophe substitution (French/Italian/Dutch elisions);
1638
+ for French, also a narrow no-break space before `; ! ? :` and around `« »`, and a plain
1639
+ no-break space between a numbering word and its number ("Chapitre 3"); for German, a
1640
+ no-break space between a number and its unit ("5 kg") and after a small set of
1641
+ abbreviations ("Nr. 3", "Dr. Müller").
1642
+ - `nonBreakingUnit` - joins a value and a game-defined unit ("pièces d'or", "points de vie")
1643
+ with whichever no-break space French/German typography calls for; the unit's own text is
1644
+ always the game's vocabulary, never MWG's.
1645
+ - `has` - whether a key resolves to something real, in either language.
1646
+ - `parseFTL`/`FluentOptions` - parses Project Fluent `.ftl` message resources into the same
1647
+ `Catalog`/`t()` surface, with variables, exact and plural variants.
1648
+ - `parsePo`/`PoOptions` - parses a gettext `.po` file into the same `Catalog`/`t()` surface:
1649
+ `msgid`/`msgstr`, `msgctxt`, `msgid_plural` with `msgstr[N]` mapped onto the locale's CLDR
1650
+ categories, the header entry dropped, untranslated entries left out for base fallback - which
1651
+ includes a `#, fuzzy` one, the way gettext's own tools treat it - and a non-default gettext
1652
+ `domain` prefixing keys.
1653
+ - `SemanticMessage`/`MessageChannel`/`MessageFormatter`/`createCatalogFormatter` - a typed
1654
+ `{ type, params }` communication intent rendered differently per channel (log/compact/
1655
+ accessibility/debug/audio) from the same underlying catalog: `createCatalogFormatter` looks up
1656
+ `${type}.${channel}`, falling back to `${type}` alone, then formats through `t()`. A
1657
+ simulation emits the message once; the channel is a presentation choice, not a rule. The
1658
+ `audio` channel holds a sound path (played game-side through `audio`'s `Sound`), resolves
1659
+ through `tRaw` rather than `t()`, returns `''` when no `<type>.audio` entry exists, and
1660
+ never falls back to a bare type holding a sentence.
1661
+ - `EntityTextResolver`/`GrammaticalEntity` - type contracts a game uses while building a
1662
+ `SemanticMessage`'s params (resolving an id to display text, or carrying gender/number/
1663
+ proper-noun metadata for its own catalog's grammar); MWG never calls or interprets either.
1664
+ - `formatNumber`/`formatDate`/`formatList` - locale-aware `Intl.NumberFormat`/
1665
+ `DateTimeFormat`/`ListFormat` wrappers reading the active locale from `locale()`, for a
1666
+ message that needs more than `{token}` substitution - a game calls these while building a
1667
+ `t()`/`SemanticMessage` param, the same way it resolves an entity id to display text.
1668
+ - `diffCatalogKeys`/`validateCatalog`/`CatalogKeyDiff`/`CatalogIssue` - catalog consistency
1669
+ checks: `diffCatalogKeys` compares two catalogs' key sets (a base language against a
1670
+ translation); `validateCatalog` flags empty messages and plural forms missing their
1671
+ `other` branch within one catalog. Deliberately not a parameter schema validator - a
1672
+ `SemanticMessage<TType, TParams>`'s own generics already give a game compile-time
1673
+ parameter safety, which is the primary mechanism the source document calls for.
1674
+ - `validateMessageAudio`/`AudioIssue` - structural checks over `<type>.audio` sound-cue
1675
+ entries: empty paths and non-string (plural/select) values, which would reduce silently
1676
+ at lookup time rather than selecting per play.
1677
+ - `EditSession`/`EditRow`/`RowFilter`/`AUDIO_SUFFIX`/`createEditSession`/`sessionKeys`/
1678
+ `sessionRow`/`sessionRows`/`setTargetText`/`copyFromBase`/`deleteTargetKey`/
1679
+ `setTargetSound`/`cueKeyFor`/`sessionCompleteness`/`swapSession`/`isAudioKey` - the pure
1680
+ session core behind `tools/i18n-edit`: translatable rows with reference/target text and
1681
+ an effective cue (a channel key shares its semantic family's `<type>.audio`, one cue per
1682
+ family), completeness ignoring cue keys, and swapping which catalog is the reference.
1683
+ `tools/i18n-edit.mjs` is the terminal split-screen editor over it, with a `--check`
1684
+ mode for CI.
1685
+ - `messageText`/`levenshteinDistance`/`findSimilarMessages` - content-management over a
1686
+ catalog's actual message text rather than only its key shape: `messageText` reduces any
1687
+ `MessageValue` to plain comparable text, `levenshteinDistance` is the classic edit-distance
1688
+ primitive, and `findSimilarMessages` surfaces near-duplicate messages worth merging by
1689
+ similarity threshold, most-similar first.
1690
+ - `catalogUsage`/`catalogCompleteness`/`pluralFormCoverage` - catalog statistics:
1691
+ `catalogUsage` compares a catalog's keys against a caller-supplied referenced-keys list
1692
+ (mwg has no view into a game's own source) for used/unused counts; `catalogCompleteness`
1693
+ is a 0-1 translated fraction built on `diffCatalogKeys`; `pluralFormCoverage` tallies which
1694
+ CLDR plural categories a catalog's plural-form messages actually define.
1695
+ - `mergeCatalogKeys` - drops a merged key from one catalog, keeping the surviving key's text
1696
+ untouched; rewriting call sites that used the merged key stays the caller's own job, the
1697
+ same boundary `catalogUsage`'s `referencedKeys` already draws.
1698
+
1699
+ ## `mwl`
1700
+
1701
+ MWL is the build-time, game-neutral content layer. It uses a WML-inspired syntax for data
1702
+ such as units, items, maps, events, AI hooks, translations, and asset references. The runtime
1703
+ consumes generated data and does not parse `.mwl` source files in the browser.
1704
+
1705
+ - `mwl build` - reads one file or a directory of `.mwl` files in stable path order and emits
1706
+ `game-data.ts`, `i18n.json`, and `assets.json` in one step.
1707
+ - `mwl build --asset-root public/assets` - optionally verifies every extracted asset before
1708
+ emitting the generated files. Missing paths include their MWL source location; without this
1709
+ flag the build stays portable for games that resolve assets elsewhere.
1710
+ - `contentReport` / `loadContent` / `mwl report` - counts tags, lists opaque names, reports
1711
+ resources, dependencies and unresolved references, and returns structured load diagnostics
1712
+ for parity checks and CI.
1713
+ - `validateCatalog`/`validateCatalogNodes`/`MwlValidationOptions` - semantic checks shared by
1714
+ every game: `MWL_DUPLICATE_ID`, `MWL_UNKNOWN_SLOT`, `MWL_INCOMPLETE_EFFECT`,
1715
+ `MWL_INVALID_HOOK`/`MWL_UNKNOWN_HOOK`. `MWL_DUPLICATE_ID`'s `tag:id` key is scoped by
1716
+ `rowIdScope` (item 304): `'global'` (the default) checks the whole compiled catalog, every
1717
+ source file combined; `'file'` folds each node's own source file into the key too, for a game
1718
+ whose id convention is meaningful only within one file and reuses ids across files on purpose
1719
+ - a real duplicate within one file still reports.
1720
+ - `[campaign]` - declares game-owned campaign metadata (`id`, optional `name`, `title`,
1721
+ `description`, and `start_scene`). Its children are intentionally open so a game can define
1722
+ scenario and progression tags without changing the core MWL schema; metadata is exposed by
1723
+ `contentCatalog(game).campaigns`.
1724
+ - `campaignChain` - points a `[campaign]` at `simulation.Campaign`: `first_scenario` opens the chain,
1725
+ each `[scenario]`'s `next_scenario` is where it goes when it is won, and a scenario that ends the
1726
+ chain ends the campaign. The order is content, the playing stays the game's (`run` is a callback),
1727
+ and a scenario that decides for itself - a runtime `[endlevel]` - keeps its decision. The
1728
+ `[campaign]` schema reads `first_scenario`, and the catalog exposes each campaign's `scenarios`.
1729
+ - `endLevelCarryover`/`carryoverIntoScenario`/`MWL_DEFAULT_CARRYOVER_PERCENTAGE` with `[endlevel]` -
1730
+ a scenario's end as the reference models it: a share of the side's gold (80% by default), a bonus
1731
+ on top, that side's surviving units as the recall list, and the next scenario. `result=victory`
1732
+ ends it won, `result=defeat` lost, and the arithmetic is the same for both.
1733
+ - One side identity (item 277): the `id` a `[side]` declares (now a `string`, so a named side like
1734
+ `id=rebels` validates) keys `world.sides` and `world.gold`, marks a map keep (`rebels Kh`), and
1735
+ is what `unit.side`, `MwlMessage.side` and every `side`/`side_filter` filter hold. `MwlSideRef`
1736
+ is just that id.
1737
+ - `readAttributes` / `readChildren` - shared typed readers for compiled nodes. They coerce
1738
+ scalars and lists and return source-located diagnostics instead of silently guessing.
1739
+ - `MwlNode.attributeLocations` / `valueLocations` - parsed JSON5 nodes retain the exact key and
1740
+ value start for each attribute, and schema diagnostics use those locations when available.
1741
+ - `MwlValidationOptions.mapBounds` - an adapter can supply map dimensions so `validateCatalog`
1742
+ rejects out-of-bounds integer, list, and range coordinates without embedding a map system in MWG.
1743
+ - `readTableMap` / `readTableIndex` / `tableKey` - project typed table rows into a `Map`, use
1744
+ collision-free native composite keys, and build inverse indexes that retain every matching row.
1745
+ - A `key="""..."""` value (item 317) is the one attribute form that may span lines, and its text
1746
+ is exactly what sits between the delimiters, so wrapped message, objective and option-label
1747
+ text survives a conversion without the whitespace-collapsing workaround it otherwise needs. It
1748
+ carries the `_` gettext marker like any other value; `text="""done"""` is the same form on one
1749
+ line. (A line starting with `#` is still a comment wherever it appears, so a block cannot
1750
+ carry one at the start of a line.)
1751
+ - MWL tables use `[table] columns=name:type|...` with typed `[row]` attributes. The compiler
1752
+ validates column shape and values, and `contentCatalog(game).tables` exposes typed rows.
1753
+ Supported column types match `core.parseCSV`: `string`, `number`, `boolean`, `list`, and
1754
+ `map`, with configurable list and map delimiters. `typedRows`/`MwlTypedRow`/
1755
+ `MwlColumnValueType` read rows through the declared columns (every field optional, an
1756
+ absent cell omits the key), and `emitTableTypes` emits one named row interface plus one
1757
+ typed accessor per table for a game's build script to write and import, so a changed
1758
+ column type or a removed column fails type-checking at every use.
1759
+ - `MwlValidationOptions.tableReferences`/`MwlTableReference` (item 362) - declarative
1760
+ cross-table checks, so no game hand-rolls one validator per table: a column declares
1761
+ `references: { table, column }` or `oneOf: [...]`, and `validateCatalog` checks every cell
1762
+ once for all tables, reporting `MWL_TABLE_REFERENCE` with the table, the row, and the
1763
+ offending value. The declarations' contents stay game data; absent or empty cells are
1764
+ skipped and a `list` cell checks each entry under the table's own delimiter.
1765
+ - `composeEffects` - resolves MWL effects through `actors.composeModifiers`, so declarative
1766
+ item effects and actor stats use one composition rule.
1767
+ - `evaluateCondition` - evaluates bounded content conditions with comparisons, `and`/`or`/`not`,
1768
+ arithmetic, literals, `where` bindings, and explicitly supplied pure helpers. There are no loops, assignments,
1769
+ dynamic code loading, or implicit game rules.
1770
+ - `mwl validate` - checks syntax and content structure without generating runtime files.
1771
+ - `mwl diagnostics` / `mwl ci` - emit stable JSON diagnostics, with `ci` additionally exposing
1772
+ a boolean `valid` result and returning a failing process status when errors exist.
1773
+ - `mwl format` / `mwl migrate --to 1.0` - expand and emit a deterministic canonical MWL document;
1774
+ migration requires an explicit target and currently normalizes the MWL 1.0 syntax surface.
1775
+ - `mwl compile`/`mwl extract-i18n`/`mwl hooks` - lower-level commands for a generated module,
1776
+ translation extraction, or hook manifest when a build pipeline needs separate outputs.
1777
+ - `parse`/`compile`/`validate`/`extractI18n` - the programmatic compiler surface exported from
1778
+ `@datamoc/mw_games/mwl`; games provide their own hook implementations and interpret
1779
+ game-specific effects.
1780
+ - The `[side]` surface Wesnoth's own data writes, and the one key of it with behaviour here (item
1781
+ 252): `team_name`, `user_team_name`, `share_vision`, `village_gold`, `heal`, `fog`, `shroud`,
1782
+ `hidden` and `flag` are read onto `MwlWorld.sides` as written, `yes`/`no` becoming booleans.
1783
+ `sideVisionGroups` turns `team_name` and `share_vision` into the groups `FactionFog.share` takes,
1784
+ so a scenario's teams see together without every game re-deriving who shares with whom.
1785
+ `leader=` names either a `[unit]` id already declared (that unit is the side's leader; nothing
1786
+ is spawned) or a unit type (one leader per free start cell, with that type's stats); a value
1787
+ that is neither is refused by name (item 405).
1788
+ - A `[side]`'s own `[victory]`/`[defeat]` children (item 283): a side condition that names no
1789
+ `side`/`side_filter` reads as that side's own, its result lands in `MwlWorld.sideStatus` keyed by
1790
+ the side id, and the aggregate `MwlWorld.status` ends the scenario as a scenario-wide condition
1791
+ would (a side victory outranking another side's defeat when both fire at once). `[win]`/`[lose]`
1792
+ record the side they name too.
1793
+ - Public MWL exports - `MwlRuntime`, `MwlSyntaxError`, `collectHookReferences`, `compileNodes`,
1794
+ `compileSources`, `compileAndEmitSources`, `emitArtifacts`, `coerceTableValue`, `decodeSaveEnvelope`,
1795
+ `parseTableColumns`, `contentCatalog`, `createWorld`, `decodeSave`, `effectToModifier`,
1796
+ `emitHooksDeclaration`, `emitModule`, `emitTableTypes`, `encodeSave`, `evaluateExpression`,
1797
+ `execute`,
1798
+ `extractCatalog`, `hookTypes`, `inventoryItem`, `isGettext`, `isMwlId`, `itemDefinition`,
1799
+ `parseExpression`, `parseHookReference`, `parseMapFile`, `parseTerrain`, `parseValue`, `preprocess`,
1800
+ `schema01`, `typedRows`, `validateCatalogNodes`, `validateHookReferences`, `loadContent`, and `validateWorld`.
1801
+ - `parseMapFile`/`MwlMapFile` (item 284) - reads a Wesnoth-shaped `.map`: the `key=value` header
1802
+ is split off and kept, and the comma-separated rows go through the same `parseTerrain` an inline
1803
+ `[map] terrain=` uses, overlays (`Gg^Vh`) and `<side> <code>` starts included. Header keys are
1804
+ not interpreted here, the same way `[terrain_graphics]` rules stay content's business.
1805
+ - `MwlHookDeclaration`/`validateHookAttributes` (item 321) - a hook may declare the attributes its
1806
+ own `[hook]` calls carry (`attributes`, typed the way a tag schema types its own, or
1807
+ `openAttributes`), and `validateCatalog`'s `hooks` option takes it in place of a bare
1808
+ `type:name` id, so a typo in one of a command hook's eighteen modes is a compile-time
1809
+ `MWL_VALUE` rather than a throw mid-scenario. The declaration is the hook's, not the tag's:
1810
+ only `[hook]` calls are checked, where every attribute but `name` belongs to the hook. The
1811
+ rule itself is `validAttributeValue`/`attributeTypeDescription`, exported because the tag
1812
+ schema and a hook declaration check values the same way rather than two ways that drift.
1813
+ - `MwlDomainHook`/`MwlDomainHookRegistry` - game-declared hook namespaces such as
1814
+ `item-effect:potion-strength` use a typed context/input/output boundary. MWG validates and
1815
+ emits the reference shape, while the game owns the domain types, rules, and implementation.
1816
+ - `HookWorld`/`Emit` (item 319) - the hook boundary's two halves. `world.variableAt(path)`
1817
+ resolves a nested variable through the same walker `[variable] name=` reads through, and
1818
+ `emit.setVariable(path, value)` is its write, so a hook asks for `stored_naga.hitpoints` and
1819
+ means the same variable content does; writing `world.variables` directly gets a flat dotted
1820
+ key no reader finds.
1821
+ - `HookWorld.random`/`MwlRuntimeOptions.random` - a hook draws from the runtime's own seeded
1822
+ `core.Generator` instead of `Math.random()`, so a `generator`/`ai`/domain hook stays reproducible;
1823
+ the draw position is carried on `MwlWorld.random` and resumes exactly across save/restore.
1824
+ - `MwlTraceEvent`/`MwlRuntimeOptions.onTrace` - opt-in lifecycle tracing for event claims,
1825
+ completions, variable writes and runtime errors. `MwlHookRegistry.predicate` lets an adapter
1826
+ register named, typed filter predicates without putting game-specific semantics in MWG.
1827
+ - `MwlSaveableHookState` / `MwlHookRegistry.saveable` - a game may explicitly expose JSON-safe
1828
+ hook state; `MwlRuntime.save()` includes it and `restore()` hands it back to the same adapter.
1829
+ - `MwlRuntime.journal` / `MwlRuntimeAction` - public runtime triggers and their trace batches are
1830
+ recorded in order and persisted with the save, providing a replay and diagnostics input without
1831
+ making MWG interpret game-specific commands.
1832
+ - `validateCatalog` also reports `MWL_ALIAS_CYCLE` for cycles among resolved `aliasof` references;
1833
+ aliases outside the catalog remain available for game-defined sentinel values.
1834
+ - `validateSimulationReplay` - replays a `SimulationRuntime` journal from a checkpoint, compares
1835
+ each deterministic event batch, and optionally verifies the final state with a stable checksum.
1836
+ - `SimulationRuntime` accepts an optional `history: { actorOf, limit? }`; `canUndo`, `canRedo`,
1837
+ `undo()` and `redo()` restore complete state, scheduler, RNG and journal checkpoints.
1838
+ - `CanonicalState` / `CanonicalStateSnapshot` - a defensive, JSON-safe root state combined with
1839
+ `StateRegistry` extensions; snapshots, version migrations, transactions and restores cover all
1840
+ pieces atomically.
1841
+ - `LockstepClient` supports optional command validation, receives a session seed and initial
1842
+ state, and can submit per-tick state checksums; `onDesync` reports differing peer checksums.
1843
+ `createLockstepServer` accepts matching `seed`, `initialState` and `validateInput` options.
1844
+ - `MWL_SCHEMA_01` / `MWL_SCHEMA_10` and `schema01` / `schema10` identify the supported MWL
1845
+ vocabularies; `mwl migrate --to 1.0` updates the document version without changing its data.
1846
+ Schema 1.0 additionally enforces declared required attributes and child cardinalities.
1847
+ - `ScriptHost` and `createExpressionScriptHost` - the game-owned boundary for executable content.
1848
+ The expression host is the statement-free default. The main `mwl` entry point
1849
+ exports its types without loading a scripting VM. Projects that opt in to the optional
1850
+ `@datamoc/pyroeis` dependency can import `createPyroeisScriptHost` from `@datamoc/mw_games/mwl/pyroeis`.
1851
+ It provides Lua 5.4 evaluation, chunks, named function calls, JSON-shaped context values, and
1852
+ `mwg_emit(name, payload)` events. The adapter opens only the sandbox-safe standard libraries
1853
+ (base, coroutine, math, string, table, utf8): `io`, `os`, `debug` and `package` with its
1854
+ `require` are never constructed, identically in Node and the browser, the base library's `load`,
1855
+ `loadfile` and `dofile` are removed, and chunks compile in text mode only, so a binary
1856
+ `\x1bLua` dump is rejected. It replaces `math.random` with seeded deterministic random, and
1857
+ enforces an
1858
+ instruction budget and a `memoryLimit` (bytes of string and buffer data one call may
1859
+ allocate, 32 MB by default, parsing included), since one `..` or `string.rep` instruction
1860
+ can allocate without bound. Scripts get `local x <const>`, `local x <close>` (with `__close`,
1861
+ run on a normal exit, `break`, `return` and error, and unwound by a limit error too) and
1862
+ `coroutine.close`, from fork 0.3.0; a `__close` cannot yield. The byte budget is the VM's
1863
+ per-call allocation limit (`limits.totalAllocation` on `PyroeisVm`), so a script's own `pcall`
1864
+ sees the standard `not enough memory`
1865
+ while the host still rejects the call. `getmetatable("")` returns `false`. Globals persist between calls on one host, so
1866
+ mutually untrusted scripts need a host each. Lua VM state is not save data: reload scripts
1867
+ from the game's entry point.
1868
+
1869
+ - `createPyroeisRuntime` (the same optional `mwl/pyroeis` subpath) returns a
1870
+ `PyroeisRuntime` for games that need synchronous API responses, live state and
1871
+ resumable handlers. It keeps the smaller `ScriptHost` contract intact.
1872
+ `defineFunction(path, callback)` exposes a host function with arguments and a
1873
+ result, and `get`/`set` use dotted global paths made of identifiers. `run` executes
1874
+ text and returns its first result; `call` accepts a path or a `PyroeisReference`.
1875
+ `reference(path)` retains a Lua table or function's identity, including callbacks
1876
+ registered by Lua; dispose references when finished, or dispose the entire runtime.
1877
+ `PyroeisValue` includes plain values, arrays, objects, Maps, BigInts, binary strings
1878
+ as Uint8Arrays and owned references. Ordinary tables are copied on read; contiguous
1879
+ sequences become arrays. Bound tables retain their references even inside lists.
1880
+ Nil maps to null; assigning it removes a Lua table entry. Lua VM state and references
1881
+ are not JSON save data.
1882
+ `createTable(PyroeisTableBinding)` creates a live proxy: `get` and optional `set`
1883
+ run on ordinary indexed reads/writes, with optional `keys` for `pairs` and `length`
1884
+ for `#`. Nested bindings can return other proxy references, allowing a game to expose
1885
+ a side list, each side's resources, a variable namespace or an entity lookup.
1886
+ Its metatable is hidden; Lua `rawget`/`rawset` still bypass bindings, so callbacks
1887
+ must enforce game rules themselves.
1888
+ `PyroeisRuntimeOptions.modules` snapshots exact module IDs and embedded source
1889
+ strings. Lua `require` caches the first result with Lua identity; `dofile` reruns
1890
+ a source and returns all results. A game can alias `game.require = require` without
1891
+ copying a loader. Unknown IDs, cyclic loads and binary chunks are rejected.
1892
+ No filesystem, fetch or XHR is involved; `io`, `os`, `debug`, `package`, `load` and
1893
+ `loadfile` stay absent. Closing a suspended module load clears its loading marker.
1894
+ `defineYieldingFunction` returns request values to the host; a
1895
+ `PyroeisCoroutine` created by `coroutine(pathOrReference)` exposes `status`,
1896
+ `resume(args)` and `close()`. It can also adopt a thread created by Lua, including
1897
+ one already suspended by the script; each thread has one host controller.
1898
+ Each resume returns `{ done, values }`, with scene
1899
+ answers supplied as the next resume's arguments. Close handlers run on explicit
1900
+ closure or runtime disposal; failed handlers retain their error until closure.
1901
+ Instruction and string/buffer allocation budgets cover compilation, modules,
1902
+ host-side indexing and coroutine resumes. Nested host calls share the current
1903
+ budget; a later top-level call/resume gets a fresh budget. Optional `timeLimit`
1904
+ bounds wall-clock time, including callbacks, but cannot preempt host JavaScript.
1905
+ Randomness is seeded; bounded `math.random` intervals require safe integers.
1906
+ Total JavaScript heap and some native operations remain outside these bounds.
1907
+ - `luaToJs(source, { format?, header? })` (same subpath) translates Lua to readable
1908
+ JavaScript without running it and returns `{ code, warnings, exports, freeGlobals }`.
1909
+ Metatables, coroutines, general `goto` and some patterns stay as `TODO(lua2js)`
1910
+ comments with a matching warning; invalid Lua throws `LuaSyntaxError`. Pyroeis's
1911
+ runtime numeric `compile` is not used: it is skipped whenever execution limits are on.
1912
+
1913
+ `MwlRuntime` exposes `fireEvent(id)` for named event execution. Event conditions compare
1914
+ numeric variables numerically, `set_variable` accepts the bounded MWL expression syntax,
1915
+ filters can match a unit id, `unit_at` can constrain a side, and both moveto events and unit
1916
+ filters take coordinates as comma-separated lists or inclusive ranges (`x=1,2,4-5`). A
1917
+ `set_variable` (either spelling, `[set_variable]` or `[command] name="set_variable"`) may
1918
+ declare what its own `value=` means with `mode=literal|number|expression`: `literal` keeps the
1919
+ text exactly as written, `number` parses it and refuses anything else, `expression` evaluates
1920
+ it and treats a missing variable as an error. Without a mode the value is inferred from its
1921
+ shape (`$name` copies a variable, a finite number is a number, operator characters or a
1922
+ numeric variable's name evaluate), which is what hand-authored content relies on and what a
1923
+ compiler target cannot, since a literal such as `Raise Walking Corpse (8 Gold)` would be read
1924
+ as an expression. `path=` is that same write with a target built from variables
1925
+ (`zombies[$index].allow_recruit`, or `$target` for a variable holding a path), expanded before
1926
+ the path is walked; a reference that names nothing throws rather than leaving an empty segment.
1927
+ `name=`/`target=` stay literal (a `$` there is not a reference today, so it is not read as one
1928
+ now), which keeps every existing write meaning exactly what it did. Top-level
1929
+ `say` commands execute normally. Dialogue choices are
1930
+ delivered in `MwlMessage.choices` and answered with `answerDialogue`; pending choices are
1931
+ included in save data. Commands after a dialogue in the same event run immediately, before
1932
+ the answer, so deferred follow-up commands belong in the selected choice event.
1933
+
1934
+ The WML action vocabulary (item 250) is on the same event surface. `fire_event` runs another event
1935
+ by id. `store_unit` writes matching units into a world variable, `unstore_unit` and `recall` write
1936
+ them back (recall can move one to a chosen hex and side), `modify_unit` changes what its `[set]`
1937
+ names and `heal_unit` adds `amount` (or sets `hp`). A unit carries its own `name`, `role`/function
1938
+ and `can_recruit` leader flag: `[unit]` sets them, a side's own leader is `can_recruit`, and
1939
+ `unitMatchesFilter` reads all three, so `[filter] role=courier`, `name=Kalenz` and
1940
+ `can_recruit=yes` select on them (`[store_unit]` and the save keep them too). `set_terrain` changes
1941
+ one map cell, `capture_village` records ownership in `MwlWorld.villages`, and `clear_shroud`
1942
+ records the hexes a side has uncovered in `MwlWorld.clearedShroud`; the fog itself stays a game
1943
+ layer. At scenario level, `[role]` fills `MwlWorld.roles` and stamps the role onto the units it
1944
+ matches, `[object]` lands in `MwlWorld.objects`, and `[story]` in `MwlWorld.story` as data
1945
+ (rendering a story screen is its own item), all kept in the save. `[item]` is deliberately not
1946
+ among them: the tag already means an inventory item definition here, so WML's map-placement shape
1947
+ would have collided with it.
1948
+
1949
+ Typical build-time usage:
1950
+
1951
+ ```sh
1952
+ npm run mwl -- build content/ -o generated/
1953
+ ```
1954
+
1955
+ The executable [`mwl-content` example](../examples/view.html?ex=mwl-content) shows the full
1956
+ path: authored content, generated catalog and manifests, then a small game reading the result
1957
+ at runtime. A Wesnoth adapter can convert native `.cfg` files to the same MWL input model
1958
+ before invoking this build step.
1959
+
1960
+ ## `mwl/pyroeis`
1961
+
1962
+ The optional Lua 5.4 entry point, `@datamoc/mw_games/mwl/pyroeis`, kept off the `mwl` barrel
1963
+ so the Pyroeis VM (the optional `@datamoc/pyroeis` dependency) loads only when a game imports
1964
+ it. The `mwl` section above describes its behaviour in full; the exports are:
1965
+
1966
+ - `createPyroeisScriptHost(options?)` - a sandboxed `ScriptHost` (`PyroeisScriptHostOptions`:
1967
+ `instructionLimit`, `memoryLimit`, `seed`). Only the base, coroutine, math, string, table and
1968
+ utf8 libraries are opened, `load` is removed, `math.random` is seeded, and every call is
1969
+ bounded; globals persist per host.
1970
+ - `createPyroeisRuntime(options?)` - a `PyroeisRuntime` for synchronous host calls and live
1971
+ state: `run`, `call`, `get`/`set` on dotted paths, `reference`, `defineFunction`,
1972
+ `defineYieldingFunction`, `createTable` (live proxy tables), `coroutine` and `dispose`.
1973
+ Types: `PyroeisValue`, `PyroeisReference`, `PyroeisCoroutine`, `PyroeisTableBinding`,
1974
+ `PyroeisRuntimeOptions`.
1975
+ - `luaToJs(source, options?)` - translates Lua to readable JavaScript without running it
1976
+ (`LuaToJsOptions`/`LuaToJsResult` are re-exported).
1977
+
1978
+ ## `ai`
1979
+
1980
+ Renderer-free decision runners. The game owns perception, navigation, combat rules and
1981
+ goals; these modules provide the execution boundary, deterministic choice support, explicit
1982
+ actions, serialisable state, diagnostics and budgets.
1983
+
1984
+ - `NeuralPolicy` over `NeuralModel`/`DenseLayer`: dependency-free dense inference,
1985
+ ReLU hidden layers and linear output scores, with flat row-major weights and an
1986
+ explicit `observationVersion`. Construction validates dimensions and finite values
1987
+ before copying the weights; limits are 32 layers, 4096 neurons per layer and one
1988
+ million parameters. `predict(input, output?)` reuses activation buffers and can
1989
+ write into a caller-owned `Float64Array`. `exportModel()` returns a plain-data copy
1990
+ suitable for bundling in a local-file game.
1991
+ `selectAction(NeuralObservation, random?)` masks illegal actions, chooses the first
1992
+ best score on ties and returns `null` when all actions are masked. A seeded random
1993
+ callback enables stable-softmax sampling. `behavior(id, actions, observe, sample?)`
1994
+ maps the same policy into `JavaScriptAI`, using its seeded random callback when
1995
+ sampling. `predictBatchAsync(inputs, { signal?, timeout? })` runs a whole inference
1996
+ batch on one worker. The caller owns stale-result rejection if a scene or position
1997
+ changes while awaiting it. Tiny predictions are usually cheaper synchronously;
1998
+ measure batches before offloading them.
1999
+
2000
+ - `JavaScriptAI` - registers named behaviours, checks them in declaration order, and returns
2001
+ a JSON-shaped action or an idle decision. A behaviour receives perception, mutable plain
2002
+ state, seeded `random()`, `emit()` and a cooperative `checkpoint()` for cancellation and
2003
+ step or wall-clock budgets. JavaScript cannot interrupt a synchronous function that never
2004
+ checks its checkpoint, so long-running behaviours must cooperate.
2005
+ - `Suggester` - the suggestion mode (roadmap 397): the same decision call a game makes
2006
+ for the AI, pointed at a hint UI instead of the world, throttled by a frame-count
2007
+ budget (`every`, never wall clock) so a hint does not tax the frame budget. The
2008
+ first `update` decides immediately, throttled updates return null while `latest`
2009
+ keeps the previous suggestion, an `idle` decision is a suggestion the UI reads
2010
+ (`decision.action === null`), and `clear` drops it. The decider must not mutate
2011
+ game state to compute a suggestion; what the player does with one is the game's.
2012
+ - `alphaBetaSearch`/`AlphaBetaGame` - deterministic minimax with alpha-beta pruning over a
2013
+ game-owned immutable-state adapter. The adapter supplies legal moves, transitions, terminal
2014
+ detection, current player and evaluation from the root player's perspective. `depth`,
2015
+ `maxNodes`, cancellation and node diagnostics bound the search; the same primitive works
2016
+ for a local actor and for a top-level controller such as a chess master.
2017
+ `rootSplits`/`firstWins` are the root-split halves of an off-thread search: the split
2018
+ pairs each root move with its child in game order, and first-wins reduces scored moves
2019
+ so ties keep the earlier move.
2020
+ - `personalScoreView`/`sideScoreView`/`scoreWith` over `ScoreSubject`/`ScoreView`/
2021
+ `ScorePersonality` - the numbers a mind that weighs outcomes needs, for the case where a search
2022
+ is the wrong tool. The game owns what anything is worth (`scoreOf`), the framework owns how a
2023
+ view is assembled (own, allies and enemies kept apart, plus a `seen` count), and the mind owns
2024
+ what it cares about: a personality is weights, so a selfish scout and a loyal one are content
2025
+ rather than two AI implementations. Both scopes read through the same code and differ only in
2026
+ the visibility set they are handed, a unit's own sight or `FactionFog.sees(side)`. `ScoreSubject`
2027
+ also carries an optional `type`, `role`/function, `can_recruit` leader flag and `name`, and
2028
+ `subjectsWhere`/`ScoreSubjectFilter` select a world on any of them, so a mind finds "the enemy
2029
+ leader" (`{ side: 'red', can_recruit: true }`) without re-deriving it from ids.
2030
+
2031
+ - The heuristic AI (item 269): `Aspects`/`AspectValues`/`AspectValue` - the named tuning knobs
2032
+ (`aggression`, `caution`, `keep_away`, `recruitment_pattern`, ...) with typed readers and no
2033
+ built-in values, since the numbers are content; `Difficulty`/`DifficultyLevel` - named levels as
2034
+ aspect overrides on a base set; `Goals`/`Goal`/`GoalKind` - per-unit orders a stage's `weigh`
2035
+ reads; `RecruitmentPattern` - a side's recruit order, cycled, with a fallback. `HeuristicAI`
2036
+ runs candidate actions through `HeuristicStage`s in order, the first whose `when` passes scoring
2037
+ every `HeuristicCandidate` and taking the best (earlier candidate on a tie); a candidate may carry
2038
+ the acting unit's own `type`/`role`/`can_recruit`/`name` for a custom `weigh` to read.
2039
+ `defaultWeigh` is each factor times the aspect of the same name with `keepAwayScore` for a
2040
+ candidate's `distance`; `goalScore` is what a custom `weigh` adds for a goal.
2041
+ - `AIDecision`/`AIDecisionInput`/`AIAction` - the shared contract for perception, explicit
2042
+ action objects, status (`action`, `idle`, `cancelled`, or `budget-exceeded`), emitted
2043
+ diagnostics and state snapshots.
2044
+ - `AICancelledError`/`AIBudgetExceededError` - the cooperative control-flow errors used by
2045
+ a JavaScript behaviour when it observes cancellation or exceeds its configured budget.
2046
+ - `exportState`/`importState` - versioned, JSON-shaped agent state. Function closures, VM
2047
+ state and arbitrary object graphs never become save data.
2048
+ - `LuaAI`/`createLuaAI` from `@datamoc/mw_games/ai/lua` - optional Lua 5.4 provider with the same
2049
+ action and state envelope. A Lua function receives `(perception, state)` and returns an action
2050
+ table or `{ action, state, events }`. It uses the existing optional Pyroeis host, which
2051
+ removes filesystem, process, module-loading, clock and debug access, supplies seeded random,
2052
+ and enforces an instruction budget.
2053
+ - `AIAgentDefinition`/`AIBehavior` - JavaScript registrations; Lua registrations instead
2054
+ provide a source chunk and an entry function name. Both remain game-owned content and
2055
+ do not include any reference game's code or data.
2056
+
2057
+ MWL `[ai]` profiles describe the boundary without embedding executable game rules: `scope`
2058
+ is `actor` or `controller`, `provider` is `javascript` or `lua`, `algorithm` can be
2059
+ `rules` or `alpha_beta`, and `depth`, `max_nodes`, `player`, `moves`, `apply`, `terminal`
2060
+ and `evaluate` identify search limits and game-owned operations. A game resolves those names
2061
+ to JavaScript behaviours or Lua functions and supplies the actual state, legal moves and
2062
+ evaluation.
2063
+
2064
+ ### Skeleton extensions (417-421)
2065
+
2066
+ - `skeleton.solveTwoBoneIK(skeleton, first, second, target, bend, pose)` solves a connected
2067
+ two-bone chain in world coordinates. `bend` is +1 or -1; positive bends clockwise on screen.
2068
+ Positive finite lengths and a zero origin on the second bone are required. Unreachable
2069
+ targets throw with the chain names. Rest rotations and rotated ancestors are supported.
2070
+ - `Bone.limits: { min, max }` bounds the absolute local rotation in degrees, including rest
2071
+ rotation. `skeleton.validatePose` checks an authored pose; `samplePose` and
2072
+ `sampleTransformPose` accept an optional skeleton for validation. Mixers and `resolve`
2073
+ validate automatically. Use a nonnegative or nonpositive interval to constrain bend direction.
2074
+ - `Keyframe.translations` and `Keyframe.scales` map bone names to `{ x, y }` channels.
2075
+ `skeleton.sampleTransformPose` and `skeleton.advancePose` return a `TransformPose`, with
2076
+ `rotations`, `translations` and `scales`. Missing channels interpolate toward zero translation
2077
+ or unit scale. Looping, reverse playback, holding, priority layers and crossfades share the
2078
+ rotation timeline. Legacy `samplePose` and `advance` return rotations only.
2079
+ - `SkeletalSprite.apply` accepts either rotation poses or `TransformPose`; its mixer uses
2080
+ `advancePose` automatically. `setDiagnostics(true)` explicitly enables bone lines, pivot
2081
+ crosses, joint circles and tips. Omit it in release builds; disabled rigs allocate no overlay.
2082
+ - `assets.loadSvgParts(sourceOrPath, { resolution, groups })` returns borrowed textures keyed
2083
+ by top-level SVG group name. It preserves the full SVG canvas, group attributes, shared defs
2084
+ and styles. Repeated loads reuse textures; resolutions have separate cache entries. Compiled
2085
+ asset paths decode directly from data URIs under `file://`. Unknown groups and invalid
2086
+ resolutions throw by name. `releaseSvgParts(parts)` unloads them once no sprite uses them.
2087
+ - `node tools/check-skeleton-extensions-browser.mjs [local-vehicle.svg]` builds a classic
2088
+ local-file page, verifies WebGL rendering, texture reuse, resolution isolation and diagnostic
2089
+ cleanup, and writes screenshots under `benchmark-results/skeleton-extensions/`. The default
2090
+ vehicle is generated; passing a local consumer SVG embeds it only into ignored scratch output.
2091
+
2092
+ ### Deformation, articulated SVG loading and asset filtering (414-416)
2093
+
2094
+ - `PinnedDeform` / `DeformableSprite` expose pinned control points. `dragVertex`, `nudgeVertex`
2095
+ and `resetVertices` change GPU vertex positions without changing UVs or rotating the sprite.
2096
+ `dragVertices([{ index, x, y }, ...])` validates a batch before applying it and uploads once;
2097
+ the pure `PinnedDeform.dragMany` performs the same batch operation without a renderer.
2098
+ - `loadSvgSkeleton(sourceOrPath, { skeleton, bindings?, pivots?, resolution?, mixer? })` returns
2099
+ `{ sprite, textures }`. `sprite` is a `SkeletalSprite` with named SVG groups already bound.
2100
+ By default matching groups bind in SVG document order. Explicit `bindings` provide draw order,
2101
+ group-to-bone mapping and optional pivot/rest-angle overrides. Pivots come from `data-pivot-x`
2102
+ and `data-pivot-y` (root SVG user coordinates), or a `pivots` map keyed by group id. Missing
2103
+ pivots, groups, bones and duplicate bindings fail by name. Separately bound descendants are
2104
+ removed from parent textures; ancestor transforms, shared styles and defs survive. Artwork is
2105
+ normalized against each bone's rest angle so poses rotate the correct limbs about their pivots.
2106
+ Browser DOMParser/XMLSerializer are required. Compiled paths work under `file://`. Destroy the
2107
+ sprite with `{ children: true }`, then call `releaseSvgParts(textures)` when all users are done.
2108
+ - `mwgPage({ assetFiles: ['hero.svg', 'music/theme.ogg'] })` embeds only those asset-folder paths.
2109
+ Omit `assetFiles` to keep all supported assets; `[]` embeds none. Unknown or unsupported named
2110
+ entries fail before replacing compiled asset scripts. Both `emitPage` and `compileResources`
2111
+ accept the same option. `credits.json` generates `CREDITS.txt` when selected, or with no filter.
2112
+ - Browser checks: `node tools/check-sprite-deform-browser.mjs [local-bird.svg]` and
2113
+ `node tools/check-svg-skeleton-browser.mjs [local-character.svg] [local-manifest.json]` build
2114
+ local-file WebGL pages and save rest/posed screenshots under `benchmark-results/`. Defaults
2115
+ use generated art; consumer inputs remain in ignored scratch output only.