library reference

Documentation

What exists in each module, and where. For exact signatures and every doc comment, open the generated API. For a first working scene, see Getting started.

A one-line-per-export index of @datamoc/mwg's public API - what exists and where, not how to use it. The published Documentation page is this file rendered as HTML; the full generated API (every parameter, every doc comment) lives beside it at webpage/documentation/api/, with an examples index beside it at webpage/documentation/examples.html listing every @example per module (all from npm run webpage:docs). For why the framework is shaped this way and what it's for, see README's capability spec. For architecture and build commands, see DEVELOPMENT.md. For the order things shipped in and the reasoning behind it, see CLOSED.md; for what's still open, see ROADMAP.md.

Every module is its own barrel: import { X } from '@datamoc/mwg/core' (or the matching subpath for any module below), or import { X } from '@datamoc/mwg' for the root re-export.

Two rendering worlds, and a core that belongs to neither. mwg/two-d is everything drawn through PixiJS (Game, Scene2D, and the render, ui and stage modules beneath it); mwg/3d is everything drawn through Babylon. mwg/core holds what both need and neither renders: the scene lifecycle, SceneStack, input, saves, RNG, signals, achievements.

Which entry points reach a renderer, checked by a test that walks the real import graph (tests/renderer-isolation.test.ts) rather than by good intentions:

renderer-free Pixi Babylon
core, i18n, actors, world, battle, simulation, roguelike, board, audio, music, rpg, ai, mwl, assets/paths two-d (and two-d/render, two-d/ui, two-d/stage), assets three-d (the 3d subpath)

roguelike adds only rot-js, and pixi.js, @babylonjs/core/@babylonjs/loaders and @capacitor/core are optional peer dependencies rather than installed ones, so a project names only the renderer it actually draws with. A Babylon game importing core + 3d pulls in no Pixi at all, and a 2D game importing core + two-d pulls in no Babylon. rpg is renderer-free too: its event interpreter takes an injected DialoguePresenter rather than building a widget, so a 3D game can run map events, dialogue and quests without a 2D renderer anywhere in reach.

MWL presentation

The optional compiler at @datamoc/mwg/mwl/presentation is renderer-free. The runtime at @datamoc/mwg/two-d/presentation imports Pixi and is kept off the root barrel. The browser consumes compiled data, with no MWL parser or network requests.

  • compilePresentation(files, manifest) validates and compiles top-level theme_definition, presentation_context, component_variant, ui_component and scene_definition nodes. It checks named actions/adapters, binding types, assets, reusable-component cycles, duplicate IDs, overrides and token references at build time, with source-file/line diagnostics. The manifest's asset names must be generated files that the game's asset build actually includes.
  • emitPresentationModule(data) emits deterministic TypeScript data, PresentationId (including keyed instance paths) and PresentationSceneId literal types. A game's build script writes this module plus data.messages and data.assets into its existing MWL artifact pipeline. See examples/mwl-presentation/generate.mjs.
  • MwlPresentation(data, sceneId, options) mounts existing Button, Label, Bar, Window, WindowStack and Camera components. get(id), focusId, palette and activeContext expose instances and presentation state. update(dt), resize(width, height), setContext(id) and destroy() drive its lifecycle; handleAction(action) offers modal windows input first. Register destruction with the owning scene's onDestroy; it detaches input, theme, controller and adapter subscriptions.

Declare the TypeScript manifest with values: { name: 'string' | 'number' | 'boolean' }, or { type: 'items', fields: { id: 'string', text: 'string', selected: 'boolean' } } for collections, plus actions, optional adapters and assets name lists. The runtime's options.state() supplies those values; options.actions implements the named callbacks. Repeated-item actions receive the current item, even after reorder. Optional subscribe returns a disposer, and translate resolves authored/gettext text. Asset textures must be loaded before mounting. PresentationAdapter exposes a view plus optional update, resize, restyle and destroy: the runtime destroys the view, while the adapter detaches its own subscriptions. Cleanup continues even if an adapter throws.

Scenes contain scene_camera (zoom, position or fit dimensions), scene_layer (world or screen space, optional generated image or named procedural adapter) and UI trees. ui_mount expands a reusable component at build time. UI trees use ui_container, ui_row (wrapping by default), ui_column, ui_grid (equal grow columns), ui_label, ui_button, ui_bar, ui_window, ui_repeat and ui_adapter. Every node has an id; runtime paths start with the scene ID and join descendant IDs with /. Repeats insert the URI-encoded stable key before their single template child's ID, preserving instances and focus on updates. A reusable component using item fields may declare items_binding so even an unused template can be validated against its collection.

Properties include pixel dimensions, anchors, offsets (x, y), spacing, alpha and semantic color tokens. Bindings use text_binding, title_binding, value_binding, max_binding, color_binding, visible_binding, selected_binding and disabled_binding; item fields use item.field. Buttons name an action, windows may name a close_action, and repeats declare items_binding plus a string/number key. Window close actions should update the controller's visibility binding. Closed windows stay closed until their visibility transitions false then true; reopening creates a fresh window, because existing Window.close() destroys its contents.

Themes require panel, text, accent, success, warning, danger and selection 24-bit color tokens; games may add scenery tokens and choose font/padding metrics. Text/panel contrast must reach 4.5, and danger/selection against panel must reach 3. Contexts choose a theme and may override tokens or authored-node properties using ui_override.target, such as component:controls/toolbar or scene:bridge/decor. Image overrides on scene layers select generated scenery. Precedence is base properties, context overrides, component variant, then ui_state (idle, hover, pressed, disabled, selected, focused). A game's biome schema selects a context; MWG defines no biome rules. Context switches preserve mounted adapters and controller state.

One active presentation owns the existing global UI theme. Destruction restores its prior theme if nobody replaced it meanwhile. Existing widgets also expose local palette updates: Button.setColors (ButtonColors), Window.setColors (WindowColors) and Bar.setBackground, for variants that must follow token changes without remounting.

Conventions

Three rules the whole API follows, so a name means one thing everywhere:

  • advance(turns) moves a clock forward in whole turns or rounds; update(dt) moves one forward in real seconds. TurnClock, Charges, Field, Barrier and AbilityCycle take turns; everything in render, ui, audio and world.EnvironmentClock takes dt. Anything that is not time passing gets its own verb rather than borrowing one of these (QuestLog.advanceStage, BossPhases.check).
  • toJSON() / static fromJSON(defs, data) is how a class saves and reloads. Definitions a game owns (item tables, quest definitions, growth curves, terrain kinds) are supplied fresh as defs rather than written into the save, so rebalancing reaches old saves. Namespace-level state uses exportX/importX free functions instead (Input bindings); Random.Generator keeps getState/setState, which resumes a live stream in place rather than producing a payload.
  • "Nothing to pick" is always null, never -1 or undefined: Random.weighted, Random.element, Random.weightedKey, rollEncounter, rollLoot, rollAffix, pickBuilder.

core

The scene lifecycle, signals, RNG, input, and every save/telemetry/replay primitive - the one module every game imports, whichever renderer it uses, and the only one that depends on no other mwg module and no renderer at all.

  • Scene - one screen of the game, as lifecycle only: create, update(dt), resize, the onSuspend/onResume pair a pushed scene needs, and a destroy that fires once. It owns no display node; two-d.Scene2D adds the Pixi container, and a Babylon game supplies its own.

  • SceneStack - push/pop/replace: suspends the current scene, layers another over or instead of it, and resumes with a result once it pops (minigames, pause menus). Generic over the scene type and typed against the lifecycle above, so it drives a 3D game just as well.

  • SceneComponentHost/SceneComponent - composes a scene out of named sections (map logic, encounter logic, UI wiring), each its own module implementing whichever Scene lifecycle hooks it needs, instead of one scene class accreting every responsibility. A scene owns one host and forwards update/resize/onSuspend/onResume/destroy to it - composition, not a base class, so it works the same whether the scene extends Scene or two-d.Scene2D.

  • Registry - a named lookup registered once and read back by name: register/get/has/ list, throwing on a duplicate or missing name by that name. The dispatch primitive underneath a catalog of factories or handlers (SceneComponentHost uses one internally) - a game still imports and registers each entry itself, no auto-discovery.

  • createHandles/Handles - numeric leases for values a plain-data command cannot carry (callbacks, RNG streams, query closures): put stores a value and returns its id, get resolves it, drop/clear end leases, and with scopes a lease so the drop runs even when the body throws. Ids start at 1 and are never reused.

  • Logger - categories, four severity levels, a filter, and a sink tests can capture, instead of bare console.log/console.error. Three shapes cover what "an event" means here, kept deliberately distinct rather than folded into one bus: a GameEvent is a rule's ordered output - what happened, described after the fact - realised as the generic Event type parameter simulation's SimulationRule/ SimulationRuntimeRule already return, never something a handler reacts to mid-calculation. A Hook (HookRegistry, below) is a point of modification a rule consults while it runs - modifyDamage, "can this creature act this turn" - synchronous, and read back by the same rule that asked. A Signal is a plain notification with no bearing on any rule - sceneChanged, saveCompleted. Reaching for a global bus that several AttackRequested/DamageCalculated/ HpChanged-style events all dispatch onto, each triggering the next, is the shape to avoid: it turns a rule's synchronous, readable logic into a chain no single function owns.

  • Signal - a typed event emitter: one event, one payload, LIFO listeners, and a listener can consume it.

  • HookRegistry/Hook - many events keyed by name, dispatched in registration order, with a source tag so everything one ability or worn item registered comes off in a single offSource call. battle.BattleHooks and roguelike.CombatHooks are both this with their argument types fixed; they were two copies of one class until they were merged.

  • PresentationQueue - plays a batch of simulation events one at a time, at whatever pace play(event) (a tween, a sound, a floating number) says to wait before the next - the presentation-side counterpart to a SimulationRuntime.dispatch()/runScenario() result, kept out of the logical commit that already happened. The same queued/timed shape as two-d.ui. Toast, generalised to any event type and needing no renderer.

  • parseCSV/CsvOptions/CsvColumnType - a header-row CSV into an array of typed row objects, so a content designer edits a spreadsheet instead of a .ts object literal for a table shaped like actors.AffixTable. columns names which fields coerce to 'number'/'boolean'/'list' (semicolon-separated)/'map' (semicolon-separated key=value pairs); an empty cell omits that field entirely, the same as an optional property never set. Takes a raw string with no opinion on how it was loaded, the same boundary i18n.parseFTL already draws.

  • clamp - value restricted to [min, max]. Shared so two-d.render.Camera's bounds clamp and rpg.Collision's tile-edge resolver stop being the same three-line function written twice.

  • parseDialogueLines/DialogueLine - the terse @id text/--alternation dialogue-text parsing engine behind both two-d/stage.parseDialogueText and rpg.parseDialogueText, so the two-speaker state machine lives once instead of twice: each module's own wrapper only renames DialogueLine.speaker onto its own command shape (StageCommand.as versus EventCommand.speaker).

  • parseTwee/TweeCommand/TweeChoice/TweeStory - the Twee-notation parsing engine behind both two-d/stage.importTwee and rpg.importTwee, for the same reason: passages, [[links]] and StoryData/StoryTitle parse once here, and TweeCommand/TweeChoice are structurally compatible with both StoryScript/StageChoice and EventStoryScript/EventChoice, so each module's wrapper needs no per-field conversion.

  • Random (namespace) - seeded RNG: int, float, weighted, element, shuffle and the rest; every "pick one" returns null when there is nothing to pick.

  • Generator - the seeded RNG class Random wraps directly, for a game that wants its own instance.

  • JavaRandom/JavaRandomDraw/JavaRandomOptions - java.util.Random's 48-bit generator bit for bit (nextInt, nextInt(bound), nextLong, nextDouble, nextFloat, nextBoolean), so a game ported from the JVM replays the same seed; onDraw logs every underlying draw for a parity diff against a JVM run. Not for general use, that is Generator.

  • MersenneTwister/MersenneTwisterState - MT19937 with mt_rng's seed/discard/ discardCount bookkeeping, for a port that consumes the reference's raw 32-bit stream; the engine matches the standard test vector, while the int mapping is MWG's own unbiased reduction (C++'s uniform_int_distribution is implementation-defined).

  • RandomStreams - named, independent MT19937 streams over one base seed, so a loot draw and an AI draw never shift each other, with getState/setState for a save and reseed.

  • Input (namespace, so Input.onAction, not a bare onAction import) - named-action input: bind/isDown/justPressed/justReleased over keyboard, bindButton/bindAxis/pollGamepads over a gamepad, bindTouch/pressTouch/releaseTouch/attachSwipe over touch, attachPointer for down/move/drag/up signals with target-relative and (through toWorld) world positions, actionsForKey for rebind-conflict detection, rumble for gamepad haptics. onText carries the character a key press produces (via textFromKey/dispatchText) and onAction the named action a key fires, each with its own programmatic counterpart (dispatchText, dispatchAction) so an on-screen keyboard feeds the same signals a physical key travels; onComposition follows an IME through start/update/end, so a free text field can be built on top.

  • PlayerInput - a per-player scoped Input, for local multiplayer/split-screen.

  • StoredValue/defaultStorage - one JSON value under one storage key (read(fallback)/ write/remove) over the same storage SaveSystem uses: a game's structured progress or best scores without a save slot.

  • FixedStepper - turns the variable Scene.update(dt) into fixed simulation steps (advance(dt, tick), a maxSubsteps cap, alpha for interpolated drawing): the deterministic, refresh-rate-independent loop a physics solver or lockstep game needs.

  • SaveSystem - named, versioned save slots over localStorage (in-memory fallback under file://); a migrations chain, and importExternal as a plug-in point for a foreign save format's own normalize function. load, list and importSlot read every slot through parseInbound plus a { meta: { version, savedAt }, state } shape check: a corrupt or tampered slot loads as null and is left out of list.

  • StateRegistry/StateExtension/StateRestoreDiagnostic - named game-owned state extensions with deep-cloned snapshots and transaction rollback, with independent versions, ordered migrations and explicit handling of extensions absent from a restored save, so custom save data has one atomic boundary.

  • ActionJournal - serializable ordered action and outcome batches with checkpoints, incremental reads, truncation and validated restore for replay, undo and synchronization. Actions and events are copied on append, so both must be plain data.

  • cloneData/uncloneablePath - structuredClone with an error naming the first value that cannot be copied (action.target.reactions.rules[0].when), and that path on its own. The journal and simulation.SimulationRuntime use it, so a command carrying a live actor fails with where and why instead of a bare DataCloneError.

  • scramble/unscramble - light save-data obfuscation, not encryption.

  • SaveSyncClient - pushes/pulls save data to a server the game supplies.

  • LockstepClient - deterministic multiplayer over an injectable WebSocket, tick-driven. Server messages are size-capped (maxMessageBytes, 1 MB) and type-checked; a malformed one is dropped and reported on onProtocolError instead of throwing out of onmessage.

  • stateChecksum/SyncGuard - out-of-sync detection for lockstep: a key-order-stable 32-bit checksum of JSON state, and a guard comparing the checksums two peers compute for each tick, recording the first tick they disagree on.

  • RunHistory - a local record of completed runs (score, cause of death, whatever a game's own summary holds), distinct from SaveSystem's continuable slots.

  • PlayerStats - a lifetime running total folded in one run's summary at a time, distinct from RunHistory's per-run records.

  • encodeShareLink/decodeShareLink/fitShareLink/dropByPriority/bisectShareLink - share links: a short URL whose fragment (#mwg:, never sent to a server) carries an envelope of content type, id@version and a JSON payload, deflated, base64url and ending in a CRC-32 prefix that catches a link a messaging app cut short. The envelope is public and the payload is the game's own, validated by the game on read; reading is bounded (link length, inflated size) and every failure is a reason rather than an exception. maxChars is 2000 by default, up to 4093. fitShareLink takes the first of several candidate payloads, fullest first (dropByPriority builds that ladder from a record), that fits; bisectShareLink keeps the most items of a list that fit. Applying a decoded link after the player confirms is the game's.

  • TelemetryClient - sends usage/error events to a server the game supplies.

  • NewsClient/NewsSeenTracker - a game's own patch-notes/announcement feed, with a seen-tracker so a player is only notified of what's actually new.

  • checkSize/checkNoControlCharacters/sanitizeInboundText/validateSchema/parseInbound - security sanitization of inbound data: an imported save, a network payload, player-typed text. parseInbound is the whole pass in one call (size, control characters, JSON.parse refusing __proto__/constructor/prototype at any depth), and every core reader of JSON it did not just produce uses it: save slots, Collection, stored values, settings, NewsClient and LockstepClient. Under file:// Chromium shares one localStorage between every local page, so a game's own storage is inbound data too.

  • Collection - named, queryable record collections over localStorage (all/get/put/remove/where/clear) - a quest log or bestiary, not a save blob.

  • Recorder/Player/serializeReplay/deserializeReplay - records Input.onAction against Game's own frame counter and replays it deterministically, for testing. Both resume mid-run: Recorder takes fromFrame so a restored run continues its recording where the checkpoint left it, and Player takes fromFrame so playback skips what the restored state already contains. parseReplayEvents validates an already-parsed event array, the half of the check deserializeReplay applies after its own JSON.parse.

  • exportReplayFile/importReplayFile/LastRun/runCheckpoint/resumeRunPlayer - a run made durable (roadmap 396). The file is a versioned, self-describing envelope (format: 'mwg-replay', version, framework, game, optional seed and recordedAt, events), and import refuses another game or another framework build by name, treating the file as inbound data the way a save slot is treated. LastRun keeps the newest recording, one deep and bounded, through the same storage a save slot uses; runCheckpoint(recorder, state) pairs the partial recording with the game state a save already captured, and resumeRunPlayer turns the restored checkpoint back into a mid-run Player. The file:// plumbing rides along: downloadReplayFile is a Blob download (no fetch()), pickReplayFile is the file picker resolving null on cancel, and readReplayFile reads any Blob, headless Node included.

  • Achievements - counters crossing a target unlock a named milestone; drainNew() queues unlocks for a UI to announce. An achievement can name several criteria instead of one counter/target (item 273's sub-achievements, "recruit every unit type"), unlocking only once every criterion is met; subProgress reads them individually.

  • Settings/GameSettings/SettingsOptions/CustomSettingValue - persisted player settings over the same storage SaveSystem uses (in-memory fallback under file://): music and sound-effect levels, master mute, zoom preference, key bindings (applied to Input on load), and a game-defined custom bag for the rest (hints, violence, ...). defaultSettings names the fresh-game values, effectiveMusicVolume/ effectiveSfxVolume read 0 while muted, corrupt storage reads as defaults.

  • Session - counts launches over the same storage SaveSystem uses, for a native wrapper's own rating-prompt timing; never prompts itself.

  • FeedbackClient/HttpTransport/HttpTransportOptions - an injectable HTTPS JSON transport for player-submitted feedback; the game owns the endpoint, consent flow, and server-side storage. Every HttpTransportOptions client (FeedbackClient, NewsClient, SaveSyncClient, TelemetryClient) and LockstepClient refuses an http:/ws: url to anything but localhost/127.0.0.1/[::1] unless allowInsecure: true, and a response body is read up to maxResponseBytes (10 MB), refused as soon as it passes the limit.

  • Spawner - a dt-driven, timed, escalating wave spawner (a horde mode, a survival minigame), distinct from roguelike.Scheduler's turn-order primitive.

  • hexNeighbors/hexDistance/hexLine/hexRange/hexToPixel/pixelToHex with HexShape/HexOrientation/HexOffset - hex grid geometry: cube-based neighbours, lines and ranges, and the pixel projection in both orientations and both offset parities, defaulting to the flat-top odd-q layout this module always had. pixelToHex answers with the nearest cell centre rather than a closed-form inverse per combination, so it cannot disagree with hexToPixel at a hex's edge.

  • weightedFlood/WeightedCell/WeightedFloodOptions - renderer- and rules-neutral Dijkstra flood over any cell topology, with injected costs, blockers, budget and stopping rules.

  • cellInside/cellIndex/cellX/cellY/cellKey/cellFromKey - bounded-grid indexing: the row-major arithmetic and bounds check that roguelike.Level and the board modules used to spell out for themselves, now stated once (the Wesnoth port asked for exactly this, to stop duplicating it in its own systems). cellInside is the shared bounds check and cellIndex is deliberately unchecked arithmetic, so a loop that has already proved its coordinates pays nothing while a module that wants a throw or a -1 keeps that policy in its own method; cellKey/cellFromKey are the 'x,y' spelling for Map/Set membership.

  • NEIGHBOURS4/NEIGHBOURS8/CIRCLE8/euclidean/chebyshev - one frozen offset table per square neighbourhood, shared instead of copied: axial north/east/south/west, the eight surrounding cells in row-major order, and the same ring clockwise from north (the sequence roguelike's neighbourOffsets(8) always returned, now returned as-is from here). euclidean is the straight-line ruler, chebyshev the king-move one (a diagonal costs one step), and manhattan the orthogonal-step count; distance measures with the ruler a DistanceMetric names, so a data-authored rule picks its geometry by name. roguelike's chebyshevDistance delegates to chebyshev.

  • Blob - a spreading volume field over a grid: a per-cell number that spread diffuses a share of into its open 4-neighbours and decays the rest (decay: 1 conserves and only moves volume around). seed adds to a cell, clear zeroes one cell and leaves its neighbours alone, and cellsAbove lists what a game applies its effect on; what a volume means (fire, gas, ooze, water) stays the game's own reading.

  • reducedMotion/setReducedMotion/prefersReducedMotion/watchReducedMotion - the one answer to "should this animate": the OS prefers-reduced-motion preference, overridable per game, with a change subscription for something long-lived that has to stop mid-flight. motionDuration(duration, intent) is the policy built on it, and MotionIntent is the caller's declaration: a decorative motion (the default) collapses, a meaningful one is shortened rather than deleted, because a change that motion conveys stays readable. Tweener, Camera (shake and follow), ScreenEffects, ParticleEmitter and FloatingText consult it. AnimatedSprite deliberately does not: a frame cycle is usually game state.

  • Tweener/Easing/TweenOptions - a generic tween(duration, apply, ease?) plus a small linear/quad/cubic easing-curve set. The third argument also takes { ease, intent, alternate }: alternate is the non-vestibular variant to run instead under reduced motion (a fade where a slide was), and it is ignored while the preference is off.

  • UndoHistory - gameplay-level undo/redo over pushed, reference-held states.

  • LoadQueue - a reusable loading-screen lifecycle: named tasks, aggregate progress, cancellation.

  • EntityRegistry/EntityId - assigns and looks up stable string ids for live objects, so events, saves, AI targets and buffs can name a creature or item without holding it; not an ECS, and distinct from Collection's persisted, queryable records. idOf is what a game passes as roguelike.Scheduler.toJSON's or simulation.SimulationRuntime's actorId.

  • ReactionTable/ReactionRule - declarative when/action rules checked against any state shape (a StatBlock's values, a plain object's own fields), firing edge-triggered so a still-true condition never re-fires; once retires a rule after its first firing. The generic alternative to a branch cascade of if HP < n checks in game code, and works the same for a character or an inanimate object such as an item's durability.

two-d

Everything drawn through PixiJS, and the counterpart to three-d. The barrel re-exports render, ui and stage below, so mwg/two-d is a one-stop 2D import; the granular subpaths (mwg/two-d/render, mwg/two-d/ui, mwg/two-d/stage) are what a game watching its bundle should reach for.

  • Game - owns the Pixi Application, the frame loop, and the current scene; reachable as the singleton Game.current. step(dt) drives one frame by hand, which defeats Chrome's background-tab throttling of requestAnimationFrame. With autoPause (the default) it suspends the loop and silences its audio rig (AudioSuspendRig, an Orchestrator fits) on page hide and resumes both on show, via suspend/resume: the clock parks at 0, the top scene hears onSuspend/onResume, and the player's mute setting is never touched. qualityScaling steps the backing-store ratio down after sustained over-budget frames (and back up only after a much longer streak inside budget) via a QualityScaler over the static fit, off unless given. It draws at the display's devicePixelRatio, reduced to the largest whole number whose backing store fits the device's MAX_TEXTURE_SIZE, with a warning naming the limit when that happens: WebGL clamps a larger request silently, so a device with a small limit renders softer rather than not at all.
  • Scene2D - core.Scene's lifecycle plus the stage container everything this screen draws hangs off, destroyed with the scene. This is what a 2D game extends.

two-d/render

Pixi-backed 2D rendering: sprites, tile maps, camera, animation. All Pixi batcher/high-shader internals are confined to ColorTransformBatcher.ts.

  • ColorTransformBatcher/packColorAdd/packTintAdd/NO_COLOR_ADD - a per-sprite texel × M + A colour transform (multiply and add) in the batch shader.
  • TintedSprite/registerColorTransform - a sprite drawn through the colour-transform batcher; register the extension once via GameOptions.extensions.
  • parseImagePath/imageModifier/colorShiftMatrix/applyImageModifiers/croppedTexture - parses common image suffix modifiers such as ~FL, ~GS, ~SCALE and ~CROP, then applies the supported Pixi presentation changes without mutating shared source textures. channelScaleMatrix (~R/~G/~B) builds the ColorMatrixFilter matrix applyImageModifiers also applies for ~O (opacity) and ~CHAN (channelSwapMatrix - a channel-source swap/constant, not Wesnoth's own per-channel formula language). applyTextureModifiers/ImageTextureProbe cover the modifiers that need real pixel access, a sibling texture, or have to rotate the actual art rather than a sprite transform: ~RC/~PAL (exact palette swap - see recolorTexture below - accepting hex or, via probe.resolveColor, a named colour; parseColorPairs/parsePaletteLists are the argument parsers, the latter reconstructing ~PAL's two comma-separated colour lists since parseImagePath's own comma split does not respect that list boundary), ~BLIT/~MASK (composite/mask against a probe.resolveTexture- resolved sibling texture at an offset - it receives the argument exactly as written, nested modifiers included, not a bare path; maskPixels is ~MASK's renderer-free alpha-multiply core), ~BLEND (blendPixels, an exact per-pixel lerp towards a colour, baked once - not the runtime ColorMatrixFilter approximation blendMatrix still offers on its own) and ~ROTATE (rotatePixels, which rotates the source pixels and expands the surface, unlike a sprite's own rotation; ~ROTATE(degrees) samples nearest-neighbour, exact at quarter turns, and ~ROTATE(degrees,linear) blends the four pixels around each sample point instead - what a non-square angle onto a hex grid needs. parseRotateMode is the second argument's parser, and both modes sample premultiplied so a transparent neighbour contributes coverage and never colour. It is bake-time work: measured, linear costs 2.4 to 4.2 times nearest per image - 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 visibly smooth edge, once, while the texture is built). spriteColorMatrix(sprite, matrix) (item 309) attaches any of the matrix builders above (or blendMatrix, or a game's own) to a sprite as a ColorMatrixFilter, the one remaining case that needed a direct pixi.js import just to construct that one class. applyAllImageModifiers(sprite, parsed, probe?, scale?) (item 310) is the two-step recipe applyImageModifiers's own doc comment names, run for a caller in one call: it bakes applyTextureModifiers's exact pixel-level result into sprite.texture first, then applies the sprite-property/filter modifiers on top, so a ~BLEND/~ROTATE path never silently gets applyImageModifiers's no-op for them.
  • remapPixels/paletteRangeMapping/recolorTexture/withTextureCanvas/PaletteMapping/ PaletteRange/PaletteRemapMode - palette-remap recolouring (team colour by range, not multiply/add): remapPixels is the renderer-free core, 'exact' by default (a pixel is repainted only on an exact match to a from colour, correct for a short specific list like ~RC/~PAL and for a paletteRangeMapping over a reference palette, where the pixels outside it are the ones the art deliberately left alone) or 'nearest' (every opaque pixel repainted by closest match, which a palette covering the whole image wants - the wrong mode for a sparse list, where it silently recolours the entire image). paletteRangeMapping builds a [color_range]-shaped mapping: the reference palette's first colour is its anchor and becomes mid, and every other entry is shaded by its own brightness, darker towards min and brighter towards max, with the floored average and truncated blend a Wesnoth [color_range] team colour is defined in, so a range's shades come out byte for byte as the engine's own. The reference after its anchor needs no order. recolorTexture is the canvas-backed wrapper, built on the shared withTextureCanvas helper applyTextureModifiers above also uses.
  • AnimatedSprite/Animation - frame-sequence sprite animation. A frame may carry its own duration (Wesnoth's image=a.png:120,b.png:80), and an animation may start partway into itself or after a delay (startTime, which is what start_time=-450 on an attack means: begin four and a half frames in, so the hit lines up with the damage frame). A frame may also carry an offset, reported through AnimatedSprite.frameOffset for the caller to add where it positions the sprite, because that position is the caller's (GridMover, a walk tween) and a sprite that overwrote it every frame would undo it every frame.
  • SpriteGroup/isOnScreen (item 369) - animate only what is on screen: update(camera, dt) advances the members inside camera.view (plus margin) and leaves the rest on their current frame, so a crowd of AnimatedSprites (or ParticleEmitters, which satisfy the same SpriteGroupMember shape) costs no CPU off screen. Never freezes anything visible: under a rotated camera the tested box is the over-inclusive one TileMap.cull uses.
  • SpriteSheet - a grid-sliced sprite sheet, or, built with no frame size, one whose frames are its own rect(index, x, y, width, height) declarations: a hand-packed icon atlas, a strip of bar segments, an item whose art is smaller than its cell. A rect is cached under its index like any grid frame, so get/region/name/pick treat the two the same and no site hand-builds a Texture.
  • Camera/createCamera/snapZoom - world-to-screen camera; snapZoom keeps tile edges pixel-aligned at a fractional zoom. Fixed-angle view rotation (item 285): grid picks four quarter turns (square, the default) or six 60-degree steps (hex), setRotationStep/rotate move through them, toScreen/toWorld invert the turn so a click still lands on the cell aimed at, view reports the box around the turned viewport for culling, and uprightRotation is the angle that keeps a label drawn into the world upright. Free rotation (item 286): rotateTo turns to any angle immediately and animateRotationTo eases towards one, shorter way around the turn, sharing the same angle and the same toScreen/toWorld/view math the stepped API uses. shakeScreen(intensity, duration) (item 303) is shake taking screen pixels instead of world units, dividing by the current zoom once so a caller thinking in screen pixels (a convention several engines use for this call) does not have to at every call site.
  • Viewport/splitScreenHalves - a camera scoped to one screen region, for split-screen.
  • createColorBlindnessFilter/COLOR_BLINDNESS_MATRICES - accessibility colour filters.
  • Minimap/newlyRevealed/minimapCellCenter/MinimapMarker - bakes an explored-cell set into a persistent RenderTexture, never redrawing an already-baked cell, and supports several game-owned unit or quest markers.
  • TileMap/EMPTY/tileFrame/tileFrameSheet/tileFrameIndex - tile map rendering: square/hex/isometric/staggered projections, multi-sheet tiles, elevation columns.
  • LayeredSprite - layered character sprites (body/hair/equipment as separate layers).
  • SkeletalSprite/ArticulatedChain/ChainRig (items 399/400) - bones driving drawn parts: the pose math lives in the renderer-free skeleton module (bone tree, keyframed clips, crossfade, priority layers), SkeletalSprite binds a part to a bone by name and update(dt) places it at the bone's world transform, and ArticulatedChain is the follower rule a keyframe cannot express - a serpent's spine whose segments ease toward 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 optional animation (item 311) advances flight frames with the tween's own elapsed time, read back through frame/frameOffset so the caller can apply the frame's offset where it already positions the sprite. Flights owns the live ones: add(sprite | texture, from, to, { speed, tint?, spin? | spinDegrees?, fadeIn?, onArrive? }) returns a handle, update(dt) drives positions and dispatches each arrival exactly once, cancel()/clear() forget without dispatching; caller sprites stay caller-owned while texture-built sprites are parented here and destroyed with their flight. spinDegrees is spin in degrees per second (converted once, so an authored angular speed needs no radian arithmetic at the call site) and fadeIn: 'progress' (or true) eases the sprite's alpha 0 to 1 along the tween's own progress instead of seconds from launch.
  • LightningArc - the position data for a jittered line between two points (a bolt, a tether): points tapers to zero offset at both endpoints, retarget moves either endpoint for a tether following two moving units, and an optional flickerInterval re-rolls the jitter on a timer. Geometry only, drawn by the caller through Shape2D's Graphics. Beam is the drawn one-shot counterpart (a fading line, or a texture strip - repeating by default, or BeamTextureOptions' stretch: true for art that spans the whole beam once, with an anchor placing it across the thickness - additive by default, retarget moving either end, thin narrowing the body as it fades, update reporting expiry once); Beams owns the live ones with add/update/clear and destroys finished beams.
  • SpriteAttachment - ties a second sprite's position to a first one's: follow(x, y) applies an offset, and an optional duration makes update(dt) report done once it elapses, so a permanent shadow and a temporary status icon are the same class with different options. Renderer-neutral like Projectile/LightningArc; z-order and parenting stay the caller's.
  • LiquidLayer/LiquidLayerOptions - an animated liquid surface under a map: one scrolling tiling quad per liquid cell with its own visibility tint (setCellColor), and ripple rings that grow and fade; pure decoration, every child opts out of pointer events.
  • FogLayer/paintFogPixels/FogCell/FogColor/FogLayerOptions - a smooth fog-of-war overlay: a small linear-filtered canvas with resolution pixels per tile, so fog edges blur across cells and one cell can be shaded in parts; paintFogPixels is the same shading as a pure function over an RGBA buffer.
  • TileMap.stampRect copies a block of frames into a layer at a tile position and throws when it does not fit; AutotileSet.mode: 'mixed' reads the MV A4 sheet's alternating rows with the floor table (wall tops) and the wall table (wall faces).
  • Halo/HALO_ANIMATION - the glow around a unit, an aura, a shrine's light: an AnimatedSprite drawn additively (Wesnoth's [halo] blend_mode=add) whose follow(x, y) applies the halo's own offset once instead of in every game that draws one. Z-order stays the caller's, because a halo that belongs behind its unit is added before it and one that belongs in front is added after, and a framework that guessed would be wrong half the time.
  • ParticleEmitter/Particle - a pooled, seeded particle emitter (sparks, dust, rain): burst/start/stop over a pool allocated once at max. Runs the whole simulation with no texture given, which is how it is tested without a renderer. ParticleSpawnArea gives births a local rect or ellipse extent instead of the emitter's single origin. scale and alpha take a ParticleCurve (t over the particle's life) as well as the birth-to-death pair, tint takes a [from, to] range each particle draws its own colour from channel by channel, and flicker wobbles the scale every frame with a seeded draw (dropped under reduced motion). All three draws happen only when used, so an existing emitter's seeded spray is 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.
  • ScreenEffects/ScreenEffectStep - a full-screen colour wash: fadeOut/fadeIn/flash/ setTint, driven by update(dt) returning true on the frame an effect completes. sequence(steps) (item 302) chains fade/hold/flash steps end to end as one call, for the hold-then-fade-back transition the four individual methods cannot express alone; update keeps returning false at every step boundary, true only once the whole sequence finishes.
  • SceneTransition/TransitionOptions/TransitionRunner/TransitionDisposition + transitionDisposition, tileShrink, shrink, pop, grow, slide, iris and dissolve - screen transitions: Game.switchScene(Next, { transition, duration, easing }) photographs the outgoing scene and animates it away (or grows the new one over it), Scene2D.transitionTo(swap, options) does the same for a scene changing its own content, Game.transitioning tells a scene to ignore input, a second transition requested while one plays is ignored unless its options say queue: true or interrupt: true (transitionDisposition is that rule as a plain function), and reduced motion skips it. tileDelays, tileProgress, popScale, openAnimationFrame and resolveEasing are the timing as plain functions.
  • ActorAnimator - an idle/move/action animation state machine with one interruption rule.
  • StatusVisuals - composes every active status effect's colour additively onto a sprite's colorAdd (item 301), instead of one status winning by declaration order; each channel clips at 1 rather than wrapping. Never touches the multiply tint, so a sprite's own identity tint (a team colour) survives underneath. flash(color, strength, duration) layers a one-shot, linearly-decaying pulse (a hit, a heal) on top of whatever is active.
  • SpriteMotion - squash, hop, bob, wobble, spin, shear and flip over any display object's transform through a Tweener (item 404). Effects compose from the rest pose captured at construction, never drift, return a MotionHandle (done, cancel()), and follow setReducedMotion; destroy restores the rest pose, flips included.
  • ClothSprite - a physics Cloth mesh drawn as a textured sprite on the 414 mesh path (item 423): owns the simulation, update(dt) steps it and re-uploads the vertex buffer, the top edge starts pinned, UVs are never rewritten. setWind/pinPoint/ unpinPoint tune it, and it honours setReducedMotion.
  • Spring - a damped 2D chase spring for secondary motion (item 424): the anchor teleports, the bob lags, overshoots and settles through pure arithmetic, O(1) per update, deterministic for a fixed update(dt) sequence. place(target) parks a follower on the bob; honours setReducedMotion. SpringSprite draws the anchor-to-bob line, redrawn by an explicit sync() after stepping.
  • HazeLayer/hazeField/paintHazePixels - an atmospheric haze sheet, never fog of war: translucent drifting weather with soft edges, density and per-plane wind, on a small canvas scaled up with linear filtering. paintHazePixels is the same shading as a pure function over an RGBA buffer, which is how it is tested without a renderer.
  • NeonGlow/glowFalloff/paintGlowPixels - a soft additive halo baked from a shape or mask, with colour, radius, intensity and flicker; a global bloom stays optional.
  • loadTiledMap/TiledMapData/TiledTilesetData/TilesetSheet/LoadedTiledMap - loads Tiled JSON maps into a TileMap: orthogonal, isometric and staggered orientations, multiple tilesets (embedded or external .tsx). Lives here rather than in rpg because what it builds is a TileMap out of SpriteSheets.
  • blobIndex/autotileFrames/BLOB_SHAPES - auto-tiling: the 47-shape "blob tile" reduction of 8-neighbour terrain matches.
  • rpgmAutotileFrame/RpgmAutotileAtlas - renderer-neutral RPG Maker MV autotile atlas geometry: decode one of the four atlas slots, select its four 24px source quadrants for a shape, and describe their 48px output position. RpgmAutotileAtlas caches repeated frame descriptions. RPGM_FLOOR_AUTOTILE_TABLE/RPGM_WALL_AUTOTILE_TABLE are the standard MV shape tables, RPGM_AUTOTILE_SLOT_BASES/RPGM_AUTOTILE_SLOT_COUNTS the family address facts, and rpgmAutotileSlot classifies a raw map id into its family (item 370).
  • TileMap addAutotileLayer over AutotileSet/AutotileCell - a native autotile layer: raw MV ids or XP values route to the set claiming them, and the map assembles each cell's quadrant halves straight from the source sheet (item 370). setAutotileFrame/ getAutotileFrame advance and read the animation frame; setTile/getTile keep working with raw ids. XP_AUTOTILE_PATTERNS/XP_NEIGHBORS_TO_PATTERN are the XP template and neighbourhood tables, xpAutotileRef/xpAutotilePattern decode and compute XP cells, and autotileCellParts/assertAutotileLayout resolve and validate one cell's pieces renderer-free.
  • AutotileSet.tableEdge with rpgmTableEdgeCells over RpgmTableEdgeMap - the front-edge strip the engine draws under an A2 table: rpgmTableEdgeCells finds the cells that get one (table above, none here, no A3/A4 wall on the ground layer) and the set draws its two half-height pieces. TileMap addShadowLayer over ShadowLayerOptions adds the engine's shadow bits (map layer 4) as translucent quarter-tile quads.
  • resolveTerrainGraphics/matchTerrainRule/squareRotate/hexRotate over TerrainRule/ TerrainCondition/TerrainImage/TerrainPlacement/TerrainFlagsAt - a rule-driven [terrain_graphics]-style transition pass for what Autotile's fixed 47-shape table cannot express: flag conditions at arbitrary offsets, one rule placing more than one image (so a piece bigger than one cell is the rule's own data, not something TileMap has to hold), rotations (squareRotate's 4 exact steps or hexRotate's 6) and probability breaking a tie among rules matching at equal specificity. Returns plain placement data.
  • TerrainGraphicsLayer over TerrainGraphicsLayerOptions - the renderer for that data: one Sprite2D per placement, added in layer order (a stable sort, so the rule pass's own row-major walk survives within a layer), each resolved through the asset resolver at the pixel position the caller's project callback reports. setPlacements redraws; z-order against the rest of the scene is the caller's, as it is for Halo.
  • inspectGraphicsCapabilities/detectWebGpu/RENDERING_DECISIONS - checks WebGL/WebGPU/WGSL support and records this project's own rendering-backend decisions.
  • Container2D/Texture2D/Rectangle2D/Rect/TextureRegion/rectOf - the renderer boundary names for common 2D values. The first three work in both type and value positions, so a game can construct a container or use texture and rectangle constants without naming pixi.js. For the rare need the facade does not cover, two-d/pixi-interop re-exports the underlying Pixi classes explicitly.
  • Node2D/Shape2D/Text2D/Sprite2D/TiledSprite/Gradient - bare, MWG-named re-exports of Pixi's Container/Graphics/Text/Sprite/TilingSprite/FillGradient: a plain grouping layer, vector drawing, one-off text, a plain untinted sprite, a repeating/scrolling texture, and a gradient fill/stroke, none of which needed new behaviour, only a name a game can import without naming pixi.js itself. Prefer ui.Label/BitmapLabel over Text2D for anything styled through ui.theme(), and render.TintedSprite over Sprite2D the moment a colour transform is needed.
  • createLayers(parent, names) (item 312) - builds one labeled Node2D per name, attached to parent in the order given and returned keyed by name, so a game's conventionally-ordered layer stack (terrain, units, effects, UI, ...) is one call rather than a dozen hand-wired containers.

two-d/ui

Windows, lists, message boxes, HUD widgets - all themed from one live-swappable Theme.

  • theme/setTheme/defaultTheme/highContrastTheme/themeChanged - the active theme; setTheme fires themeChanged so already-built widgets restyle in place.
  • Label - a themed text wrapper over Pixi Text; stroke/resolution/roundPixels options, useful for text over artwork.
  • parseMarkup/stripMarkup/markupToHtml/escapeHtml over MarkupSpan/MarkupOptions - inline markup (<b>, <i>, <span color='…' size='…'>, <br/>, <img>path</img>, $name, and the five entities) as a renderer-neutral contract: a MarkupSpan is a MarkdownSpan plus the colour, size and image a renderer may use, kept as written because resolving them is the renderer's business. Unknown tags, malformed tags and unset variables stay literal rather than disappearing, and markupToHtml is the escaped HTML fragment for a renderer that speaks HTML text - it now also renders colour and size, as an inline style. MarkupOptions.tags (item 313) names extra tags to treat as styling containers; a run inside one carries its name in MarkupSpan.tag, so a renderer can resolve its style (Pixi's tagStyles) while the parser stays renderer-neutral, and markupToHtml re-emits that tag as a real element for HTMLText. markupAccessibilityText is the proper accessibility projection (an image becomes a caller-described string, not its raw path, which stripMarkup keeps for round-tripping instead). layoutMarkupLines wraps already-parsed spans word by word against a caller-supplied MarkupMeasure, each word measured under its own span's style - wrapping computed after styling, so a bold or larger run wraps where its own wider glyphs actually land - and positionMarkupLines places those already-laid-out lines into PositionedMarkupSpan runs (one x/y per span) under a MarkupLayout's direction/align, so an rtl line flows right to left and alignment defaults to the direction's own edge. Both are backend-neutral: the same spans, measure and maxWidth decide the same line breaks and the same runs whether a caller then draws them through HTMLText or a canvas Text2D pass.
  • MarkupText/MarkupTextOptions - the canvas backend for that contract, the counterpart to RichLabel's HTML text: one Text2D per styled run and one Sprite2D per <img> span, resolved through the asset resolver, so an image is drawn rather than a caller positioning it itself at a layoutMarkupLines offset. It reads direction from the theme and takes maxWidth/lineHeight/align/resolveImage/variables/resolution options, plus tagStyles (item 313): a Pixi TextStyleOptions record keyed by custom tag, applied to each run and used when measuring it, so <quest>...</quest> is styled and wraps under its own font.
  • RichLabel/parseMarkdown/stripMarkdown/sliceSpans - basic inline markdown (**bold**, *italic*, combined ***both***, backslash escapes) through Pixi HTMLText, which is what makes mixed styles inside one string possible at all. parseMarkdown is pure span-splitting (unmatched markers stay literal); stripMarkdown recovers plain text; sliceSpans takes the first N visible characters with styles kept, for progressive reveal without leaking half-shown markers. Costs more than a Label, so this is for descriptions and help bodies, not per-frame numbers. tagStyles (item 313) takes Pixi HTMLTextStyleOptions keyed by custom tag; a registered tag survives escaping as a real element for HTMLText to style, while an unregistered one is still escaped as literal text.
  • startReveal/advanceReveal/completeReveal/revealComplete - the shared progressive-display primitive: one character count behind MessageBox pages (which already revealed this way), Label lines, and RichLabel markdown. Label and RichLabel expose it as showProgressive/updateReveal/completeReveal, driven by the game's own frame loop; MessageBox keeps its confirm-completes-then-advances rule on top unchanged.
  • BitmapLabel/bitmapLabelStyle - bitmap-font-backed text, for a HUD value redrawn every frame where Label's per-string texture re-render would be wasteful.
  • NinePatch - a resizable nine-slice panel.
  • Window - a themed panel container. open({ animation, from }) plays pop, grow, slide or fade (WindowAnimation) and close({ animation }) plays it backwards before closing, both driven by update(dt) and skipped under reduced motion. close() frees the window and its contents and is idempotent; closed is the guard for the caller's reference afterwards (input and place on a closed window are no-ops), and WindowStack.push refuses one with a named error. A window's own area is not clickable, so a click travels to whatever is under it; blocker: true adds the full-viewport layer that swallows clicks and dismisses the window for a click outside it (handleOutsideClick is that decision).
  • WindowStack - keyboard focus goes to the top window only; dims what's underneath; blocker on a window is what stops clicks reaching the map behind it. handleAction(action) is public so a scene with its own key handling can ask the windows first: Input.onAction offers an action to the most recently registered listener first, so a scene that registers after building its stack is asked before the windows are and can swallow a key they need.
  • MessageBox.blocker - whether a click under the box reaches the map behind it; on by default, and since the box is not closable that can only ever swallow clicks rather than dismiss it. blocker: false is for a box the player is meant to click past.
  • ListView - a scrollable, keyboard- and pointer-navigable row list (click, wheel-scroll); multiple checks rows instead of picking one, read back through checkedIndexes.
  • IconGrid - a multi-column icon-grid inventory view; tap-then-tap "drag and drop", frame-driven long-press for a quickslot.
  • TabbedList/ListTab/TabbedListOptions - a renderer-free model for an inventory, journal, shop or codex: caller-supplied tabs and rows (no assumed taxonomy), an optional label, filter and disabled predicate, selection that skips disabled rows, a page derived from the selection rather than tracked beside it, and an openDetail/closeDetail state.
  • Slider/SliderOptions + sliderFraction/sliderValueAt - a draggable knob on a themed track; the two pure functions are the value/track arithmetic (clamping, the step grid, the degenerate range), so a game routing its own input snaps the same way.
  • Checkbox/CheckboxOptions - a ticked-or-not box; a caption is a Label the game places beside it, and onChange fires only when the state moves.
  • RadioGroup/RadioOption/RadioGroupOptions - exactly one choice among several: arrows move the selection and select at once, a tap selects directly, disabled options are skipped.
  • Spinner/SpinnerOptions + spinValue - an up/down numeric stepper; spinValue is the rule (snap to the step, then clamp at the ends or wrap past them).
  • DropdownView/DropdownViewOptions - the widget over a Dropdown model: a button showing the choice that opens a column of Buttons on an opaque backdrop, the highlighted one marked with Button.setSelected. maxVisibleRows makes a long list scroll (wheel, touch, keys, scrollbar) and it opens with the chosen row in view; autoWidth fits the longest label, maxWidth caps that widening, and resize(width) re-lays the button and list in place; handleKey (arrows, Page, Home/End, Enter, Escape) and handleOutsideClick are what the scene forwards from its own input; fitBelow limits the rows to what the viewport leaves under the button.
  • Dropdown/DropdownOption/DropdownOptions - a renderer-free option button: a selected entry, an open list, a highlight that starts on the selection and skips disabled options. setHighlight(i) opens the list on that row, so setHighlight(i); confirm() is a whole programmatic pick.
  • TextModel/TextModelOptions - the editing state behind a text field, fed by core.Input's onText: caret, anchor, selection-replacing edits, a length cap and a mask. Renderer-free. multiline keeps real newlines with row navigation (lineCount, caretLine, lineRange, moveCaretLine holding a sticky goal column); single-line fields strip them on every edit.
  • TextPrompt/TextPromptOptions - a modal single-line text field over a TextModel (a name entry, a save-slot label): typing through onText, caret and edits through left/right/ backspace/delete actions, confirm gated by validate (the error shows and announces assertively, the prompt stays open), cancel giving up. IME compositions preview until they commit, and the message plus validation errors announce through screenReader. The interface example's Name button is the reviewed hosting pattern: push it on a WindowStack and it owns focus, closing and the stack's un-popping by itself. The touch half (roadmap 402): keyboard: UPPERCASE_KEYBOARD (or any KeyboardLayout) hosts one beneath the field and resizes the window to fit it - OnScreenKeyboard, next.
  • OnScreenKeyboard/KeyboardLayout/KeyboardKey + UPPERCASE_KEYBOARD/pressKey/ layoutKeys - pointer-only typing: a layout is rows of keys as plain data (ragged rows fine), each key a caption, the text it types (defaulting to its label), or the named action it fires instead, plus a span in row units for a space bar. The class renders it through the theme's own Button and reports contentHeight so a host can size itself; pressKey is the pure dispatch rule (dispatchText for a typing key, dispatchAction for an action key, the two paths a physical key travels, so no listener can tell a tap from a keystroke) and layoutKeys the rows-to-buttons arithmetic behind it. UPPERCASE_KEYBOARD is the one shipped default: the alphabet over a digit row, then Bksp, caret moves, space, OK, Esc.
  • DataTable/TableColumn/DataTableOptions - a renderer-free columned table: sort by a column (toggling direction), a highlight that skips disabled rows, and a page derived from the highlight.
  • TreeView/TreeNode/TreeRow/TreeViewOptions - a renderer-free collapsible tree, flattened to the rows on screen; collapsing the branch the highlight is inside lands it on the branch.
  • ScrollBox/ScrollBoxOptions/ScrollKey + scrollOffset - a clipped viewport with a themed scrollbar; scrollOffset is the clamping rule the wheel, scrollBy and scrollIntoView all share. touch: true lets a finger drag the content (a drag cancels the tap on the row under it) and coast on release, handleKey scrolls by line, page and to either end, the thumb drags and the track jumps, and autoHeight sizes the viewport to the content up to height. The box owns its hitArea (its viewport, kept current by resize and setContentHeight), so the wheel reaches it without a row under the pointer. update(dt) drives the coasting.
  • ScrollDrag - touch scrolling as plain numbers (start/move/end/step): how far the content follows a finger and how it coasts after release, with no pointer events or clock of its own.
  • ScrollText/ScrollTextOptions - a wrapped Label in a self-sizing ScrollBox: as tall as the text up to maxHeight, scrolling beyond it, re-measured by setText and re-wrapped in place by resize(width).
  • MarqueeLabel/MarqueeLabelOptions + marqueeOffset - one line that stays on one line: a long text slides back and forth in a clipped window (and holds still, cut short, under reduced motion).
  • ellipsize and truncateLines - cut a text to a width or a number of lines, ending in an ellipsis, with the caller supplying the measuring function.
  • flowLayout(items, width, { gap, align }) - left-to-right rows that wrap, returning each item's position and the total height: a toolbar that takes two rows on a phone.
  • Grid/GridSpec/GridTrack + resolveAnchor/anchorAlign with Anchor/AnchorSpec/ LayoutRect - data-driven shell layout (item 263): named anchors placed inside bounds (margin, offset, fill), and columns/rows that are size or grow, so one sidebar plus one content column needs neither side to know the window's width. Pure geometry, renderer-free.
  • Skins with Skin/SkinStates/SkinData/WidgetState - per-widget, per-state looks looked up by name, the counterpart the one global Theme has no room for. A lookup falls back widget state -> widget idle -> wildcard state -> wildcard idle -> {}, and Skins.from reads the plain data a config file would parse into.
  • MessageBox - dialogue text box: paged reveal, choices, ADV/NVL display modes, autoAdvance, and timed {sound:path} markers delivered through onSound. convertText rewrites every page's text, speaker and choice label as the box is built, so a game resolves display-time codes once in the renderer.
  • messageBoxPresenter - wires rpg.EventRunner's dialogue to a MessageBox on a WindowStack, in one argument: present: messageBoxPresenter(this.windows). Takes the same convertText option.
  • VerticalLabel/layoutVertical - vertical writing layout, with CJK glyph rotation.
  • RebindScreen - a keybind-rebinding flow over Input, with an optional conflict hook.
  • SettingsScreen/SettingsCustomRow/SettingsScreenOptions (item 364) - a ready-made settings screen over core.Settings: music/sfx sliders, mute checkbox, zoom slider, one row per custom descriptor (boolean/number/choice), an embedded controls page that writes rebinds back into Settings on exit, and a reset row. cancel on the main page returns false for the caller to close.
  • Button/ButtonSkin/ButtonState - idle/hover/pressed/disabled clickable region, icon and/or text, optional per-button nine-patch skin with per-state tints.
  • Bar - a filled-proportion track (health/mana/XP); flat colour or texture, optional roundUpToPixel so a nonzero value never rounds down to invisible.
  • Meter/MeterOptions (item 368) - a discrete meter: N icons with a value filled, the heart row or star rating to Bar's continuous fill. Fractions clip mid-icon through a mask, so halves need no extra art; flat theme pips by default, a game-supplied filled/empty texture pair (which must come together) otherwise.
  • FloatingText/floatingTextAlpha/floatingTextRise/floatingTextAgeAtLeast - a rising, fading damage/pickup number and its pure motion, opacity and age curves; FloatingTextStack with floatingTextStackLift/floatingTextStackMoves/floatingTextStackLifePenalty and FLOATING_TEXT_STACK_GAP stacks simultaneous pop-ups at one world point without overlap, lifting the lines already there the way Java's FloatingText.push() does.
  • MessageLog/linesToDrop/takeLastEntries/MessageLogEntry/MessageLevel/MessageLogOptions - a player-facing message pane: one coloured block per message (info, positive, negative, warning, highlight) that drops the oldest blocks once the wrapped lines pass a cap; linesToDrop is that budget as a pure function, and lastEntries(n) reads the newest retained entries back as { text, level } records (oldest first) without scraping rendered children.
  • fitWindowZoom/sharpenText - step a window stack's integer zoom down until its content fits the viewport, and re-rasterise every Text under a zoomed container at device ratio times its on-screen scale so it is not magnified 1x text.
  • Toast - a queued, timed pop-up notification (fade in, hold, fade out).
  • Tooltip - a hover explanation over a themed Window: a frame-driven hover delay, and edge-aware placement that flips rather than letting the panel run off screen.
  • TooltipHost/TooltipHostOptions/TooltipTarget - drives one Tooltip from rectangles: a press that rests for longPress seconds shows the text on a touch screen, and a disabled Button (which gets no pointer events) is still explained from its bounds and its tooltip. attach(pointer) wires an Input.attachPointer tracker.
  • HelpScreen - a topic-list-plus-body help/controls screen.
  • StatsScreen - a player-stats display screen.
  • LoadingScreen - a progress-bar loading screen wired to core.LoadQueue.
  • ScreenReader/screenReader - the screen-reader bridge: Window announces its title, MessageBox each page and its choices, and TextPrompt its message and validation errors through a visually hidden aria-live region, and a game's own widgets use the same screenReader.announce(text, { assertive }). No-ops where there is no DOM, so ordinary scene code needs no guard around it.
  • contrastRatio/meetsContrast/relativeLuminance/ContrastLevel - WCAG contrast for a theme palette: the standard luminance and ratio formulas with AA/AAA thresholds, so a game checks its own colours rather than guessing.

two-d/stage

Dialogue scenes: backdrop, characters, a script runner - the visual-novel half.

  • DialogueStage/CharacterDefinition/ShowOptions - backdrop plus character conversation scenes; the speaking character lit, others dimmed.
  • StageScript/StageCommand/StageChoice/StoryScript - a command interpreter; runStory follows a named-passage graph ({goto}, choice jumps); history/showLast for read-only dialogue rollback; skipSeen for auto-advancing already-read lines; ScriptOptions.mode: 'nvl' for the accumulating-block presentation.
  • importTwee/TwineStory - imports Twee-notation Twine stories into StageScript's command format, a thin wrapper around core.parseTwee naming the StoryScript return type. rpg.importTwee is the same wrapper around the same engine, targeting EventStoryScript instead, so a text-only RPG needs no Pixi dependency to import a branching Twee story, and a visual novel that never touches map events needs no rpg dependency either.
  • parseDialogueText/extractDialogueCatalog - a terse line-based dialogue format for straight (non-branching) scenes: @id text names the speaker, an unprefixed line narrates, and - text alternates between the first two speakers established by @id lines (capped at two - a third distinct speaker is refused). A thin wrapper around core.parseDialogueLines, mapping its speaker field onto StageCommand's as. extractDialogueCatalog builds an identity i18n catalog from the resulting commands (or a StoryScript), the same shape MWL's own extractCatalog builds from _("...")-marked strings. rpg.parseDialogueText is the same wrapper around the same engine, targeting EventCommand instead, so a text-only RPG needs no Pixi dependency to use it, and a visual novel that never touches map events needs no rpg dependency either.
  • StoryScreen/StoryScreenOptions with StorySequence/StoryBeat - the between-scenario interlude DialogueStage is not: a full-screen backdrop, title and text advanced by a click. The sequencing (advance/back/goTo/skip/restart, and the current beat's music reported as a signal so the game plays it) lives in the renderer-free StorySequence, and a StoryBeat has the same { text, title, image, music } shape as MwlWorld.story.

assets

The file:// story: a compiled build resolves paths through a data: URI map; dev mode serves them normally. Load once per scene; everything after is synchronous. The compiler side of this (tools/compile-resources.mjs, tools/emit-page.mjs, tools/single-file.mjs) offers independent build options on top of that one story - multi-file vs. single-file output, compression (gzip or brotli, single-file only), WebP image conversion and SVG optimisation (svgo: true, ids and viewBox kept, only when smaller) - documented in DEVELOPMENT.md's "Build options" section and tools.md's tool reference; none of them change what a game calls to load an asset.

Split by renderer specificity: assets/paths.ts resolves paths and needs no renderer, assets/binary.ts caches raw bytes just as renderer-free, assets/loader.ts fetches and decodes textures through Pixi. The assets barrel exposes all three; a game rendering through something else imports @datamoc/mwg/assets/paths or @datamoc/mwg/assets/binary and pays nothing for Pixi, which is how 3d and audio reach the compiled asset map without it.

  • setBase/setAssetMap/isCompiled/paths/has/resolve - dev-vs-compiled path resolution, renderer-free (also its own entry point, @datamoc/mwg/assets/paths). setAssetMap hands these a game's own map directly (item 300), for a game bundled by its own tool rather than tools/compile-resources, and takes priority over window.__MWG_ASSETS__ while set; undefined reverts to it. A value is a URL string, typed bytes (a Blob, or { bytes, type }), or a function returning typed bytes. load() reads typed and lazy values once and mints a blob: URL for them, carrying their MIME type to the texture loader. resolve throws for them until load() has run, and release revokes the minted URL. A missing key throws at load time.
  • load/texture/get/isLoaded/release - load assets by path, read them back synchronously, and free GPU memory once a zone is no longer needed. load(paths, { resolution }) rasterizes a vector source (SVG) at a multiple of its intrinsic size, so a game that zooms into an icon asks for a 2 or 3 instead of shipping a soft bitmap; onProgress is the same LoadQueue seam whether passed alone or in the options. optional loads those paths separately so one missing file never aborts the required batch, calling onMissing for each; texture/get take a fallback returned instead of a throw for a path that never loaded, so a caller stops needing its own try/catch around a missing asset.
  • sanitizeSvg/svgScaleVariants/svgDataUri/splitSvgGroups (item 398) - SVG as inbound data: sanitizeSvg refuses what it cannot prove inert by name (script, foreignObject, event handlers, javascript: and active data: URLs - a gate, never a silent rewrite), svgScaleVariants rasterizes one proven-inert source once per named scale with its resolution hint, and splitSvgGroups loads a group-authored SVG as one 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
    • whenever the resolved src is a compiled build's data: URI (item 308): a data: URI carries no extension of its own for Pixi's resolver to pick a parser from, which otherwise left a game no way to load a compiled asset without building its own {src, parser} descriptor by hand.
  • loadBinary/getBinary/isBinaryLoaded/releaseBinary - the renderer-free counterpart to load/texture/.../release, caching raw ArrayBuffers instead of Pixi textures (also its own entry point, @datamoc/mwg/assets/binary); 3d/models' Vox.parseVox is the direct consumer, taking bytes this now fetches and caches instead of a game doing it by hand.
  • AssetStream/AssetBundle - preloads likely-next bundles with LRU eviction under a byte budget, for progressive loading between scenes.
  • fetchWithByteProgress/ByteProgress/OnByteProgress - real cumulative byte-progress reporting, for a server or desktop host (not file://, which blocks fetch entirely).

audio

  • Sound - a pooled, round-robin one-shot sound effect player. play(gain, pitch) takes an optional pitch as HTMLAudioElement.playbackRate (1 unchanged); there is no matching pan - a plain <audio> element has no pan of its own, the same reason Positional.audioPan only reports a number rather than owning a panner node. suspend cuts in-flight sounds and silences play until resume.
  • onCaption/CaptionEvent - accessibility captions fired alongside a sound cue.
  • Music - crossfading background music. suspend pauses the current and fading tracks and freezes update until resume restarts the current one where it paused. duck glides to an attenuated level until unduck, for dialogue and menus.
  • createAudio/Playable - an injectable audio backend (tests supply a fake in place of new Audio()).
  • Orchestrator/OrchestratorState - maps a named game state ("combat", "boss") to a Music track and crossfade, and fires one-shot cues by event name; re-entering the same state never restarts its track. suspend/resume silence and restore the music and every cue.
  • AudioListener/SoundSource/AudioFalloff - positional audio: a listener the game moves, a Sound placed at a point, and audioGain/audioPan turning distance and heading into a volume and a stereo position. SoundSource.playFor applies the distance gain through Sound.play; panning is reported for a backend that has a panner. Music stays global.
  • XpbdWorld (@datamoc/mwg/physics/xpbd) - a deterministic structure solver (extended position-based dynamics): addNode/addLink (stiffness, tensionOnly cables, strength/ tensionStrength), applyForce, step() on fixed substeps, the load of every link read back (force, smoothed ratio, peakRatio) and onBreak when a link passes its strength; ground (a height or a function of x) holds nodes on a surface with groundFriction. The engine of Pontifex, generalised: bridges, trusses, cranes, anything where the question is which beam fails. XpbdWorld<T>/XpbdLink<T>/XpbdLinkSpec<T> carry game-owned link data without affecting the solver. breakLink(index) dispatches rupture once. linksInBox includes segment crossings; linksNear orders nearby unbroken segments by distance. snapshot() returns positions, velocities, load state and queued forces as detached arrays; hash() compares their exact numeric bits for runs with the same configuration. Payloads and ground callbacks are excluded. The bridge example applies a moving vehicle's weight with applyForce.
  • PhysicsWorld (@datamoc/mwg/physics) - rigid bodies and constraints in plain TypeScript, no engine dependency: addBox/addCircle/addConstraint/remove, update(dt) from Scene.update, onContact, alpha for interpolation. A constraint with maxStretch breaks when pulled that far past its rest length (onBreak, stretchOf). Bodies never spin; angle is a display offset.
  • synthesizeTone/synthesizeSound/playTone/Waveform - a runtime square/triangle/sine/noise/sawtooth waveform synth for a procedural tone or SFX, no sample library; synthesizeSound returns a pooled Sound over the tone.
  • parseMidi/scheduleMidi/midiLoopStart/noteToFrequency/MidiPlayer - a small .mid file player built on synthesizeTone rather than a licensed instrument library: program, bank, controller and pitch-bend events plus the controller-111 loop start, with each scheduled note carrying its channel voice. MidiPlayer.create(file, { humanize }) humanizes first and then schedules, for the same player with a performance behind it.
  • renderMidiToBuffer - renders a parsed .mid file to stereo PCM frames, offline and deterministic: browsers cannot decode MIDI, so the file is synthesized once and plays back like any decoded track, with its controller-111 loop region. An optional game-supplied SoundFont voices real samples; without one the built-in waveform synth plays.
  • renderMidiToBufferAsync - the same render as raw MIDI bytes, run on a worker thread so the seconds a real track costs (2 to 11.8) do not freeze the loading screen. Parse, schedule and voice lookup stay on the caller's thread; the stereo buffers come back transferred rather than copied, and the result is bit-identical to the synchronous render because both call the same function. soundFontBytes takes raw SoundFont 2 data.
  • parseSoundFont - reads SoundFont 2 bytes into layered preset voices (key and velocity ranges, tuning, loops, envelopes, pan, attenuation); the font file itself stays the game's to ship and to license. A SoundFont 3 (compressed samples) is refused by name rather than read as noise: loadSoundFont reads either kind.
  • loadSoundFont - reads a SoundFont 2 or 3 into layered preset voices: a plain font goes straight to parseSoundFont, a SoundFont 3 is decoded first, through webAudioSampleDecoder() in a browser unless { decode } names another decoder. It is what a game calls on the bytes it ships, whichever kind they are.
  • decodeSoundFont - a SoundFont 3 as plain SoundFont 2 bytes: every sample a preset reaches goes through the decoder once (an unreachable one never does), and the loop points a SoundFont 3 states relative to its sample become the absolute ones SoundFont 2 uses. A SoundFont 2 comes back unchanged. The result feeds anything that takes SoundFont 2 bytes, renderMidiToBufferAsync included.
  • encodeSoundFont - the other direction: a SoundFont 2 compressed into a SoundFont 3. Every sample a preset reaches goes through the encoder once, loop points become relative to their sample, the sample type gains the compressed flag and the INFO states version 3. The encoder is yours to give (mwg-soundfonts convert hands it ffmpeg for Vorbis and Opus); flacSampleEncoder writes lossless FLAC with nothing installed.
  • detectSampleCodec/SampleCodec/SAMPLE_CODECS - which codec a compressed sample uses, read from its first bytes: Vorbis and Opus both sit in Ogg pages (told apart by their first packet), FLAC is a native stream. The format itself only flags a sample as compressed, so a reader has to look; an unknown codec is named in the error instead of failing opaquely in a decoder.
  • encodeFlac/decodeFlac/flacSampleEncoder/flacSampleDecoder - a small lossless FLAC codec for one mono 16-bit sample, tested against ffmpeg in both directions. The decoder reads any FLAC stream up to 24 bits (constant, verbatim, fixed and LPC subframes, every stereo mode, left channel kept) and bounds the length and rate a stream claims before allocating.
  • webAudioSampleDecoder/SoundFontSampleDecoder/SoundFontSampleEncoder - the decoder contract (compressed bytes, the sample's own rate and its detected codec in, mono 16-bit frames out, synchronous or not; the encoder is the same contract reversed) and the browser implementation of it over decodeAudioData: each sample decodes in a context created at its own rate, so the browser never resamples it. A Node tool passes a decoder of its own.
  • collectSoundFontUsage - lists the (bank, program) pairs scheduled notes actually request across MIDI files, drums as bank 128, for the compile step to keep.
  • missingSoundFontPrograms - the pairs of a usage list a font does not carry (the bank 0 fallback counts as carried, a drum kit needs that exact kit), on a SoundFont 2 or 3. The build runs it for you: each embedded font's result lists its missing programs and mwg-emit warns.
  • mergeSoundFonts - joins several SoundFont 2 files (or several SoundFont 3 files, the Ogg bytes copied untouched) into one, presets in the order given and the first font winning a shared (bank, program), which is how single-instrument files (the per-program collection mwg-soundfonts fetch reads) become the one file a game ships.
  • subsetSoundFont - writes a smaller valid SoundFont 2 (or 3) file carrying only the used programs, zones and samples copied verbatim and indexes remapped, so a game ships megabytes instead of tens of megabytes with identical voices. The build does this on its own: compileResources (and so emitPage and mwgPage) embeds .mid, .sf2 and .sf3 assets, and subsets every embedded SoundFont to the programs the embedded MIDI files use. soundFont: false embeds the font whole, soundFontUsage names the programs explicitly, and with no shipped MIDI the font embeds whole because the usage is unknowable. A plain .sf2 is then compressed into a SoundFont 3 in Opus (the asset key does not change, and loadSoundFont reads either kind): soundFontCodec picks 'vorbis' or 'flac' instead, or false keeps the SoundFont 2. Opus and Vorbis are encoded by ffmpeg on the developer machine (cached between builds); without it the default keeps the SoundFont 2 and the build says why, while a codec named explicitly fails the build. soundFontBitrate (kbit/s, 6 to 510) sets how much an Opus font keeps and soundFontQuality (-1 smallest to 10 best) does the same for Vorbis; each is ignored by the other codecs, and a measured guide is in tools.md. A .sf3 is embedded as it is. The reference bank in data/microgm-opt.sf2 (2.6 MB, WTFPL, shipped in the npm package for a game to copy into its assets) drops to tens of kilobytes per game this way: measured, piano and drums come to 264 KB, eight essential programs (piano, guitar, bass, strings, brass, flute, synth lead, drums) to 421 KB, sixteen to 585 KB. A program the font lacks plays the font's own piano (preset 0:0) and, only when it has no piano either, the built-in synthesizer; parseSoundFont(data, { missingProgram: 'synth' }) (also on loadSoundFont and renderMidiToBufferAsync) hands those instruments to the synthesizer instead of a piano line, and a bank missing the program or a drum kit still falls back to bank 0 or the standard kit, never to a melodic preset. It is the default bank. A game that wants another picks it from data/soundfont-catalog.json and fetches just its instruments with mwg-soundfonts (see tools.md). A SoundFont 3 stays compressed all the way to the page (FluidR3's piano, guitar and drums: 2.7 MB, against 20 MB decoded to a SoundFont 2), and loadSoundFont decodes it at load, so prefer it over a SoundFont 2 for anything but the smallest banks.
  • createAudioLoader/AudioLoaderOptions - a cached loader for embedded audio and MIDI, shared by all AudioBus lifetimes. MIDI is detected by header and rendered on a worker; other files use decodeAudioData. Options select SoundFont/render settings or a byte source. AudioBus uses this loader by default, so playBgm and playSe accept asset paths with the same volume, pitch and pan fields. BGM/BGS loop; ME/SE play once.
  • MusicPlayer/MusicPlayerOptions/MusicPlayOptions - one loaded AudioBuffer or RenderedMidi, with play, pause, resume, seek, position, volume and an onEnded signal. Call update() each frame to dispatch track completion and choose the next track. toAudioBuffer(context, rendered) copies rendered stereo samples into an AudioBuffer.
  • Channel/AudioBus - buffered WebAudio music: a Channel plays one looping track with volume, pitch, pan, a loop region and a seekable playhead, and an AudioBus wires two of them into independent BGM/BGS loops, ME jingles that suspend and resume the BGM, overlapping SE one-shots, save and replay with playheads, and plain-data snapshots. AudioBus.setMixer(kind, { volume, muted }) scales a whole kind on top of each track's own volume, without changing what snapshots report.
  • MidiSynth/MidiSynthFactory/MidiSynthRequest + registerMidiSynth, unregisterMidiSynth, midiSynthNames, resolveMidiSynth, renderMidiThroughSynth, renderMidiStems, onMidiSynthFallback and INTERNAL_MIDI_ENGINES - the named-engine contract for MIDI: a package registers a synth under a name (retro:mt32), content asks for it by name, and resolution walks the request, then the internal names (gm-soundfont, builtin), firing onMidiSynthFallback whenever another engine voices the file instead. timedMidiMessages is the raw timed message stream a synth is driven by.
  • StreamPlayable/StreamChannel - the streaming half of the Playable contract: seek and currentTime on a synthesised stream, playbackRate by resampling, and a playhead counted in frames, so endless formats (NSF, SID) play without a whole-track render.
  • TrackCache/createBudgetedLoader/BusBudgetPolicy + bufferBytes - bus render budgets: an LRU cache of decoded tracks under a megabyte and entry cap, with maxSeconds, mono or half-rate rendering for ambience through fitToBudget and resampleStereo.
  • DEFAULT_DECODER_LIMITS/decoderLimits/DecodeBudgetError/InstructionBudget + assertInputSize, guardBlockSource and inflateBounded - the decoder guards for untrusted retro formats: input and inflate ceilings, an instruction budget per second of sound, and one named error per breach instead of a hang.
  • SfxBank/SfxSound/SfxArbiter + sfxSeed - data sound effects: synthesised chip effects with a deterministic seed, arbitrated against the se bus by priority, firing captions like a file effect.
  • AudioSettings/AudioSettingsData/AudioRegion/OutputStage + regionPlaybackRate, softenCutoff and dynamicsLimit - the player-facing audio settings in one plain-data object: volume per bus (applied to an AudioBus by applyToBus), the preferred MIDI engine name, PAL or NTSC region (a tune authored for one runs slower or faster on the other, regionPlaybackRate), a faithful or clean output stage, caption display, a dynamics control (a soft limiter, dynamicsLimit) and bright-sound softening (a falling low-pass cutoff, softenCutoff). A CPU and underrun indicator reads AudioCoreHost's stats and onAudioUnderrun. audioSettingsRows gives the rows (soften, dynamics, captions, output stage, region) to pass as SettingsScreen's custom, under the AUDIO_SETTINGS_KEYS custom keys, and AudioSettings.restoreFromCustom reads the answers back.
  • AudioExport/AUDIO_FORMATS/ExportTooLargeError + estimateExportBytes, exportTags and downloadSaver - rendering to a file: the service decides which of WAV, FLAC and Opus this device offers (WAV is written here, FLAC and Opus come from injected ExportEncoders such as the retro-audio package's exportAudio, Opus hidden where opusAvailable() is false), refuses an export over its size limit before spending the time, merges default tags, honours an AbortSignal, and hands the finished Blob to a saver (downloadSaver, a link with the download attribute, unless the platform supplies its own). inWorker runs self-contained encoders on a threads.spawn worker (main thread where none exists). mwg-audio convert writes .flac and .opus through the same service with --encoder (a module, or ffmpeg).
  • webCodecsOpusEncoder/isOpusEncodingAvailable/oggOpus - Opus without a dependency: the encoder an AudioExport takes for opus in a browser (48 kHz, 20 ms blocks into a WebCodecs AudioEncoder, the encoder's own pre-skip, tags), and the Ogg Opus writer under it (OpusHead, OpusTags, CRC-checked pages, a last granule trimmed to the exact length), checked against ffmpeg's decoder. Where there is no AudioEncoder (Node, old WebViews) the game injects another.
  • OutputRecorder + AudioBus.record() - what the bus plays, every kind as the player hears it, recorded into plain stereo frames through a silent script processor (the capture node that exists everywhere, file:// pages included) and bounded by maxSeconds; stop() returns the take for AudioExport.
  • benchEngine/EngineBenchmark - times an engine on up to 16 held voices and reports its share of real time; mwg-audio bench is the command line. The number belongs to the engine and machine it was measured on; over about half of real time, playMidiHosted is the way out.
  • auditEngines/AuditFinding/AuditReport - renders calibration notes through named engines and flags a fallback, a failure, silence, clipping, a DC offset and a pitch that is no harmonic of the note; mwg-audio audit is the command line over it. Screening, not a verdict.
  • playMidiHosted/sendMidiToHost/HostedMidi and reportUnderruns - a MIDI file played through an AudioCoreHost into a StreamChannel (the file's messages queued on the host in one post), and a forwarder that turns onAudioUnderrun into summed, rate-limited audio_underrun telemetry events through any sink with send, TelemetryClient included.
  • waveformEnvelope/channelEnvelopes/WaveformBucket and trackerPattern/trackerNoteName/TrackerRow - the data cores of the audio views: a waveform as per-bucket min/max pairs per channel (what an oscilloscope draws), and a MIDI file as tracker rows, one column per channel on the file's own tick grid. A game draws them with its own widgets; the reduction and the grid live here and are tested as arithmetic.
  • SyxBank/SyxPatch + splitSysex and dx7PatchNames - a .syx bank a player drops: its whole sysex messages, the patch names of every checksummed DX7 32-voice bulk dump in it (another maker's bank names nothing rather than guessing), and an audition that loads a patch into a MidiSynth and renders one note through it for a settings screen. readSyx and SyxBank.skipped say what a tolerant read left out (SyxSkip: bytes before the first message, an unterminated tail, a DX7-shaped bank with a bad checksum, a message that is no DX7 bank) so a mixed or damaged file is used for what is whole and reported for the rest. Each patch has an id of source#message.voice@fingerprint, the identity a save holds: a name alone is shared by many patches. A DX7 patch also carries info (Dx7VoiceInfo: the algorithm, feedback, LFO wave and transposition, read by dx7VoiceInfo from the packed bytes). audit(synth) renders one note of every patch (each selected by a program change after the bank loads) and returns the silent and clipping ones (SyxPatchFinding), so an author knows before publishing.
  • connectWebMidi/requestWebMidiInput/WebMidiConnection - live Web MIDI into a MidiSynth: every input port of a MIDIAccess is wired to the synth (channel messages to event, sysex to sysex, transport dropped), and requestWebMidiInput is the browser entry that returns null where Web MIDI does not exist or was refused.
  • AdaptiveMusic - adaptive tracks: mute and unmute stems of a running track with a fade, and switch between two versions at the same frame position; loopRegionFromFile reads the loop region a file declares as the default. A version loaded with barSeconds accepts quantize: 'bar' (Quantize) on setLevel and switchVersion, so a layer comes in or a scene changes at the next bar line instead of cutting the measure.
  • AudioCoreHost + onAudioUnderrun - the off-main-thread audio host: a synthesis core in a worker behind the same Playable facade, with a main-thread fallback and an underrun signal feeding bounded telemetry. The core is given as a self-contained factory, or as factorySource (the text of an expression that evaluates to the factory) for a core with imports, bundled into one script by the core's own package. start(events) begins a piece in order (reset, messages, then rendering) and prefetch: false keeps a new host from rendering silence first: a modelled instrument that has rendered a second of silence is not a fresh one, and the piece would differ from a direct render. A reset also drops blocks still in flight from before it (each block carries the host's epoch).
  • encodeWav/decodeWav/wavInfo and spectralDistance - WAVE as plain bytes (the mwg-audio tool's convert and compare verbs over the same code), and a spectral distance between two renders for a listening check that can be automated.
  • parseVorbisLoopTags/loopRegionFromTags - read the LOOPSTART/LOOPLENGTH comments an Ogg Vorbis file carries (a bounded walk of the first pages, null on anything malformed) and turn them into the seconds-based LoopRegion a Channel or the bus loader hands back.
  • humanizeMidi/HumanizerFactory/HumanizeRequest/MidiHumanizerEngine - the entry point for a performance that sounds played rather than played back. humanizeMidi(file, options) resolves the tier from the request (a GrooveTemplate in it means the groove tier, anything else the lite one) and returns a new file; HumanizerFactory.create(tier) is for holding one engine across several files. The pass never mutates its input: intensity: 0 reproduces the file exactly, a seed reproduces a run, note durations and every tempo, program, controller and meta event survive, events come back sorted by tick with ties in file order, and nothing lands before tick 0 (a shift that would cross it stops there instead). create('magenta') throws naming what is missing rather than loading: @magenta/music and a PerformanceRNN checkpoint cannot be fetched from a file:// build.
  • LiteHumanizer/GrooveHumanizer/HumanizationOptions/HumanizeStyle/HumanizerTier - the two shipped engines and their options. Tier 1 moves timing and velocity by gaussian noise over a seeded gradient drift, scaled by intensity and by style (jazz wide, classical tight), and holds the kick and the lowest notes to a few milliseconds of their slot; tier 2 applies a template's per-slot offsets and velocities instead, converted through the file's own tempo map when the template was recorded at another tempo (which says so through onWarn rather than staying quiet), plus contextual rules - an accent on a local melody peak, restraint on the beat. initialize() is idempotent on both.
  • subdivisionCount/assertGrooveTemplate/GrooveTemplate/GridSubdivision/GrooveOffset - the units everything else is measured in: how many slots a bar of a signature holds at a grid (subdivisionCount([4, 4], '16n') is 16, [6, 8] at 8n is 6, and a grid that does not tile the bar throws), and the validator for a template's invariants - dense offsets in subdivision order, whole ticks, a power-of-two denominator, a velocity factor between 0 and 1 - run when one is built and when one is imported.
  • GrooveExtractor - a reusable template out of three kinds of evidence, each reduced to the same thing: the median of each slot's deviations, so one flubbed note cannot drag it and a slot nobody played stays on the grid. Mode A matches a played pass against a straight one, note-on to nearest note-on of the same channel and pitch within half a slot; mode B projects a single file onto its own implied grid, which is exactly the residual a quantization would discard; mode C takes an AudioBuffer, detecting attacks by spectral flux (hand-rolled FFT, no analysis dependency) and taking the tempo as an argument because timing means nothing without one, with velocity left at the neutral 1 since a recording carries none.
  • GrooveConverter - a template to and from the two formats that can carry one. JSON is exact; the MIDI encoding is one note per slot behind an anchor a subdivision ahead, with velocity at 1/64 per unit of velocityFactor, so the writer enforces |offset| below the slot and a factor of 1/64 to 127/64 instead of rounding past them, and the file gets its own reader because the round trip needs the tempo, time-signature and name metas that parseMidi deliberately drops. GrooveFormat also names ableton-agr and reaper-groove, both of which throw saying they are not shipped rather than returning a file that resembles one.

music

Generated game music, renderer-free and deterministic. import * as Music from '@datamoc/mwg/music'.

  • composeMusic(scene) - a scene (MusicScene: id, seed, mood, tension, key, bars, voices, optional tempo) becomes a GeneratedMusic: a playable MidiFile, its barSeconds and its measured polyphony. The same scene gives the same notes, since the seeds are mixed the way the data sound effects' are (sfxSeed). voices is kept by writing fewer layers (one voice is the melody alone, two add a bass, three a one-note arpeggio, four drums, more pad notes), so a piece for a 3-voice SID or YM never needs a note cut. The result plays through renderMidiToBuffer, a registered MIDI engine, or AdaptiveMusic.
  • composeStates(base, states) - one piece per game state (exploration, combat, victory) with the same key, tempo and length in bars, so AdaptiveMusic can switch between them on a bar line with barSeconds and quantize: 'bar'.
  • normalizeScene/MUSIC_MOODS/MusicMood - makes a scene safe from a save, a share link or a settings screen (clamps every number, unknown moods become calm), so a scene is plain data a game stores. MUSIC_GENERATOR_VERSION changes when the composer's output for a scene does: a save that keeps scenes keeps the version with them.
  • maxPolyphony(file) - the most notes sounding at once in any MidiFile.

battle

The Pokémon-shaped half of the capability spec: species/stats/party/type-matrix/turn-order. No move, formula, or number belongs here - only the shape.

  • Creature/Species - wraps actors.StatBlock/Progression, not a separate stat system.
  • TypeMatrix - attack-type effectiveness lookup.
  • Party - a roster of creatures.
  • battleOrder/Move/BattleAction - one round's priority-then-speed turn order.
  • checkEvolution/EvolutionRule - level/condition-based species evolution.
  • StatStages - a bounded, symmetric stage ladder over a stat (±max), replacing rather than stacking the modifier for a stat's current stage.
  • chooseMove/chooseSwitch - battle AI built on TypeMatrix.
  • BattleHooks/BattleHook - core.HookRegistry with battle's argument shape: a handler receives the creature plus a shared mutable context, for passive effects, abilities and turn-skipping statuses.
  • Field/FieldCondition - field-wide conditions: weather, terrain, screens; named, optionally timed, ticked down by advance(rounds).
  • AttackPreview/AttackPreviewOptions/AttackFrame/PreviewCombatant - the damage totals and one-frame-per-strike timeline an attack dialog prints and animates, from damage the game's own formula produced (totalDamage, chance-weighted expectedDamage, hits for a rolled outcome, sampleAt on the animation clock). It computes no damage itself.
  • AttackDialog/AttackDialogOptions/StrikeNumbers - the dialog's whole renderer-free state: a UnitSelector to choose the pair, the AttackPreview built from a game-supplied damageFor, and the update(dt)/finished clock that drives the animation.
  • UnitSelector/UnitSelectorOptions/SelectableUnit/SelectorStage - the two-step attack selector: enabled units on the selecting side as candidates, then the enemies canTarget allows as targets; back undoes the attacker choice.
  • Whiteboard/WhiteboardEntry - planned turn orders with one plan per unit, undo/redo (a new plan clears the redo stack) and commit handing the plans back.
  • BattleStats/BattleStatCategory (item 273) - a per-run breakdown by category (recruits, recalls, advances, kills, deaths, damageDealt, damageTaken) and unit type, the shape core.PlayerStats's opaque T cannot give a game for free; record adds to one unit type's count, total/breakdown read a category back summed or per type, and toJSON folds into a core.RunHistory entry or core.PlayerStats total like any other run summary.

board

Board/card/dice games and generic tactics - traditional public-domain rules, no formula borrowed from any licensed game.

  • chess (chess.ts): startingChess/parseFen/positionKey/cloneChess/legalMoves/ applyMove/inCheck/gameResult/sq/squareName - full rules: legality, check/mate/ stalemate, castling, en passant, promotion, FEN in both directions (positions keyed without clocks).

  • engine (Engine.ts): chessGame/chooseMove/search - the chess rules adapter and convenience wrapper over the shared ai.alphaBetaSearch, with material evaluation and depth/node limits. searchAsync scores each root move on a worker thread and combines the scores first-wins, so a depth-3 search stops dropping frames; inside the node 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.

  • bitboards (bitboard.ts): the same rules on twelve 64-bit boards (startingBitboard, bitboardFromChess, bitboardMoves, makeMove/unmakeMove, perft), the mutable board the tournament engine searches. bitboardFromChess bridges from a chess.ts position; the differential tests keep both rule sets in agreement.

  • openings (openings.ts): probeBook looks a position up in a compiled opening book (ECO, name where a known line ends, UCI continuations), parseUciMove reads a UCI move back. The book is a game-side artifact built by tools/compile-openings from vendored CC0 tables, so no table ships with the framework.

  • tourney (tourney.ts): searchTourney/searchTourneyAsync over one self-contained tourneyThink task, so the worker side cannot diverge from the main-thread side: negamax alpha-beta with principal variation search, null-move pruning, late-move reductions, iterative deepening with aspiration windows, a bounded Zobrist transposition table, quiescence over captures and promotions, hash/MVV-LVA/ killer/history ordering, and classical material plus in-house piece-square evaluation. Positions are plain bitboard data and structured-clone straight into workers. TourneyResult.rootScores is populated by an async search with legal root moves and scores from the mover's view, in root order, for near-best selection without a second search. The chess example plays its reply through searchTourneyAsync, with a thinking indicator, a per-move time cap, side and depth choice, a promotion picker and an in-check highlight.

  • tablebase (tablebase.ts): probeTablebase/loadTablebaseEnding/tablebaseId plus the huffEncode/huffDecode codec - WDL outcomes with distance-to-mate for pawnless white-extras-against-lone-king endings, fifty-move-adjudicated against an explicit halfmove clock, generated and verified by tools/build-tablebases and shipped compiled under data/tablebases (3-piece; 4-piece stays a tool run away, full 4-piece tables are tens of megabytes each).

  • classics (Classics.ts): BoardGrid; checkers (startingCheckers/checkersMoves/applyCheckersMove, forced multi-jump captures); go (startingGo/playGo/passGo/goResult/goScore, ko and area scoring); backgammon (startingBackgammon/rollBackgammonDice/backgammonMoves/applyBackgammonMove, bar and bearing off); cards (createDeck/shuffleDeck/deal/trickWinner); solitaire (dealSolitaire/drawSolitaire/moveSolitaireTableau/moveSolitaireToFoundation/ solitaireWon, seeded Klondike); dice (rollDice/rollExpression/DiceCup/scoreDice, Yahtzee-shaped keep-and-reroll scoring).

  • tactics (Tactics.ts): startingTactics/addTacticalUnit/canPlaceTacticalUnit/ tacticalMoves/moveTacticalUnit/setTacticalOverwatch/triggerTacticalOverwatch/ tacticalAttack/endTacticalTurn - squad tactics: action points, cover, overwatch, and zone of control baked into tacticalMoves/move cost.

  • FactionFog/VisionCell - fog of war as a per-faction union of every controlled unit's own vision, with explored memory retained. share puts factions on one map, sight and memory alike, which is Wesnoth's share_vision; nothing shares until asked. sees hands a side's sight out as a predicate for anything that asks what it can see.

  • army (Army.ts): startingArmy/recruit/recall/bankUnit/armyIncome/ applyUpkeep - recruiting/recalling units against a currency total, per-turn income and upkeep, no specific rate baked in.

  • hex skirmish (HexSkirmish.ts): startingSkirmish/setSkirmishTerrain/ canPlaceSkirmishUnit/addSkirmishUnit/skirmishMoves/moveSkirmishUnit/ skirmishAttack/skirmishIncome/endSkirmishTurn - a Wesnoth-style hex army-game rules layer distinct from tactics above: per-terrain movement cost and defence, adjacency-only attacks where a surviving defender always strikes back, capturable villages that grant income and heal whoever owns them, no zone of control.

  • BoardPiece (type, from Classics.ts) - a generic owned/countable/capturable/promotable token distinct from roguelike's Creature-shaped actors; every game above builds on it.

actors

Stat blocks, equipment, inventory, and the numbers layer nearly every other module builds on. This is the shape - a game names its own attributes and formulas.

  • StatBlock/Modifier/DerivedStat - base attributes plus derived stats, combined through ordered modifiers (add → multiply → set). toJSON saves base values only: modifiers are reapplied on load by whatever owns them (equipment, status effects, auras), so saving them too would double every bonus.
  • composeModifiers - the same canonical modifier composition as StatBlock, available to adapters that resolve declarative effect lists without creating a stat block.
  • Progression/powerCurve - levelling from experience against a growth curve; toJSON saves level and experience, the curve being a definition.
  • skillCheck - value-plus-modifiers against a difficulty, one dice roll.
  • SkillPoints - a spendable ledger that raises a stat's base rank, with per-stat caps and a rising cost per rank. toJSON saves only unspent points; the ranks bought are already in the StatBlock's own base values.
  • EquipmentSlots/EquippableItem/SavedEquipment - equip/unequip applies or removes an item's modifiers immediately; an optional locked predicate refuses unequip/swap for cursed/quest gear. toJSON(identify) records slot-to-id, and fromJSON re-equips so every modifier lands back on the StatBlock; a locked item is restored still worn.
  • Inventory/InventoryItem/ItemDefinition/SavedInventory - stacking (by id, and by instanceId when either item sets one), weight, capacity, containers holding their own Inventory. toJSON saves per-item instance state (level, wear, affix, identified, instanceId) while fromJSON(defs, data) takes kind-level fields from the game's item table, so a rebalanced weight reaches an old save.
  • craft/Recipe/Ingredient - resolves a recipe against an Inventory: all-or-nothing, with a capacity-rollback path if the result doesn't fit. An ingredient may match an exact id (or a list of them), a category on the item's definition ("any herb"), or a matches predicate; the allocation is made against a working copy so two flexible ingredients cannot count one stack twice. InventoryItem.category/ItemDefinition carry the kind-level grouping (supplied by the game on load, like stackable and weight).
  • applyStatusEffect/EffectClock/StatusEffectHandle - a StatBlock modifier tied to a TurnClock's automatic expiry; cancel() for early removal.
  • identify/enchant/damageItem/repairItem - identification; enchant/upgrade level (enchant's affixPolicy: 'keep' | 'remove' decides whether an upgrade strips an affix); durability wear and repair, opt-in per item.
  • applyItemStatusEffect - a status effect sourced from an item rather than a spell.
  • Charges/ChargesOptions - a resource regenerating in banked-turn chunks via advance(turns); refund() restores charges directly (a kill or crit), outside that path. toJSON saves the count and the progress banked towards the next, so reloading cannot shorten a recharge.
  • rollLoot/LootEntry/LootTable - rolls whether anything drops, then weight-picks which, the same "roll whether, then which" shape world.rollEncounter shares.
  • Advancement - level-gated tiers granting ledger points, with mutually-exclusive branch/capstone choices.
  • rollAffix/affixOf/applyAffix/removeAffix/copyAffix/matchesContext - named item affixes: weight-picked, applied/removed on InventoryItem.affix, copied between item instances, and matched against a fired trigger's attack kind via AffixDef.kinds.
  • scaledModifiers/LevelScale - level-scaled gear: {stat, op, base, perLevel} resolved to a plain Modifier.
  • assignAppearances/Appearances - per-run appearance shuffling for unidentified items, seeded and fixed for the run.
  • buy/sell/Price/ShopOptions - a currency-StatBlock transaction against an Inventory, all-or-nothing with rollback.
  • canAfford/spend/refund/convertToCharges/ResourceCost - a spendable StatBlock pool (mana, stamina): check, all-or-nothing spend, mirror-image refund (optionally fractional), or convert a spent amount into Charges at a rate.
  • Barrier/BarrierLayer - a layered shield/absorption pool; the most recently added layer drains first, with optional independent per-layer decay ticked by advance(turns).
  • assignTraits/TraitDef/AssignedTrait - per-instance random traits drawn from a shared pool at creation, applied as permanent modifiers.
  • AuraField/AuraDef/AuraParticipant - continuously reapplies a carrier's modifiers to whoever is currently adjacent, diffing rather than reapplying every tick.
  • SupportLedger - a pair-order-independent, thresholded bond/support relationship between two units, growing through proximity or shared battles; toJSON/fromJSON round-trip it.
  • buildEntity/buildEntities/EntityTemplateRow/EntityTemplateCatalog/BuiltEntity - one row of a hero or monster file (typically a core.parseCSV result) into a fully wired entity: a StatBlock of base stats (every non-reserved column), an optional Progression against a named growth curve, a starting item carrying a named starting affix, and a ReactionTable already holding a low-HP rule if the row names a threshold. What each named growth curve/affix/item actually is stays the game's own EntityTemplateCatalog.
  • toEntitySaveState/fromEntitySaveState/EntitySaveState - a BuiltEntity's mutable state (base stat values, level/experience, the carried item) in the same "definitions supplied fresh on load" shape StatBlock/Progression already draw. fromEntitySaveState rebuilds via buildEntity from the same row and catalog, then overlays the saved state on top.

roguelike

FOV, pathfinding, the energy scheduler, level generation, and combat-adjacent primitives - the dungeon-crawl half of the capability spec.

  • Level/WALL/FLOOR/rectCenter/rectsOverlap - the tile grid: terrain kinds, passability/transparency, square or hex shape.
  • generateDungeon/findFreeCell/furthestRoom/DUNGEON_KINDS - procedural dungeon generation.
  • generateDungeonGraph - the same pipeline as generateDungeon, also returning the room graph (corridor edges, backbone then extra loops) and a rejected-placement retry count; DungeonOptions.hooks fires onRoomPlaced/onCorridorCarved as the pipeline runs, the seam a regional generator hangs hand-placed rooms, branches, wells, plants, statues, chasms, doors and traps from.
  • generateCave (item 407) - the cave counterpart: chambers grown as random blobs (jagged the chance a growth step wanders), passages as biased random walks (windiness, width, chance), starts on chamber centres with cleared rings, villageDensity returning picked clear cells as data, and a forced join so a cave is always connected whatever the rolls did. Seeded through the Random stack like the dungeon.
  • generateOverworld (item 410) - a whole realm as plain tile data: seeded elevation and moisture fields classify water, plains, forest, hills, mountains, desert and swamp behind a seaLevel knob; rivers run downhill to the sea, merging when they meet, drowning a lake at a ridge instead of crossing it; settlements place themselves by suitability (buildable ground, water within reach, spaced apart) and join into a road tree that prefers flat ground, water a ford rather than a wall; points of interest carry a leadsTo id for Overworld locations, and every cell carries a coarse region id for encounter tables. The realm invents itself from the seed: no reference game's map data.
  • shape: 'hex' on generateDungeon, generateDungeonGraph, generateCave and generateOverworld lays the same generator out on a hex grid (odd-q offsets, the Level convention): the dungeon and cave Level carry the hex shape, a dungeon corridor leg runs as a hex line, a cave grows its chambers by hex distance and walks passages toward their target in true on-screen distance, and the overworld samples its noise where each hex is drawn and steps rivers and roads across the six edges. The default stays square, byte for byte. generateCave also takes random (a RandomSource, such as a Generator) in place of seed: it draws from, and advances, that stream, leaving the ambient Random stack untouched.
  • RoomBuilder/hallBuilder/eligibleBuilders/pickBuilder - composable room interiors: the generator places and joins rooms, a builder carves each one, picked by weight among those whose size constraints fit. DungeonOptions.builders wires them in; a room no builder fits falls back to a plain hall rather than staying solid rock.
  • FeatureLayer - a floor feature/event layer: named kinds with inspect/interact/ consequence/persistent rules attached to generated cells; definitions supplied fresh on load, only cell-to-kind pairs are save data.
  • rollRoster - a variant-spawn/content-roll API: weighted regular entries, rare additions, per-entry alternative swaps, and a shuffle, in that order; every roll (including an explicitly disabled rare entry's non-roll) is traced for parity tests.
  • candidateCells/cellsNear/selectDistinctCells - deterministic content placement over a Level: candidateCells filters by terrain kind, occupancy and an optional region; cellsNear walks outward by radius for a cluster anchor; selectDistinctCells shuffles and slices a de-duplicated pool, bounded to however many candidates exist rather than throwing. Composes for neighbouring-item clusters, scattered decorations, and single room/branch rewards; nothing is placed until the caller commits, and the returned trace is plain JSON-safe data for DungeonArtifacts.content or a save file.
  • compareDungeonArtifacts/checkDeterminism - a dungeon parity/test harness: diffs a seeded run's room graph, retries, terrain, features and content rolls against a reference or golden fixture, tagging every mismatch 'graph' or 'paint'; checkDeterminism repeats a generation call and confirms every run matches the first.
  • FieldOfView/HeightSight - shadowcast (square) or straight-line (hex) visibility, with Elevation-aware asymmetric cliff sight.
  • Elevation - whole-level height per cell, read by FieldOfView/Pathfinder.
  • Pathfinder/neighbourOffsets - A*(square)/Dijkstra(hex or elevation-aware) pathing, distanceMap/descend/autoExplore, an optional climb limit.
  • Scheduler/Actor/SchedulerSnapshot - energy-cost turn order, the sole authority on logical time; fractional costs, postpone (delaying an actor other than the current one), and toJSON/restore for a deterministic snapshot keyed by a caller-supplied actor id.
  • decideMonsterAI/AIState/AIDecision/Disposition - wander/hunt/flee built on FieldOfView/Pathfinder/Scheduler; peaceful/neutral/hostile disposition, provoked override.
  • Secrets - disguised terrain (secret doors, hidden traps) that passes every passable/transparent check as its disguise until revealed.
  • Doors - open/closed/locked door state; locking is independent of open/closed.
  • chebyshevDistance/traceLine/ballistica/hasLineOfSight/canTarget/resolveArea - targeting and collision paths: range/line-of-sight checks, configurable stopping cells, and single/line/burst/cone area resolution.
  • TargetingController - the input-facing half of targeting: a cursor moved by keyboard (move) or by a caller-resolved pointer cell (moveTo), range and line-of-sight validation with an optional game validate hook, a preview of the shape's cells, and a confirm/cancel result. It returns cells only; the game keeps legality details, damage and drawing.
  • coneCells/chainTargets/knockbackPath - a widening cone spray, a greedy nearest-hop chain, and a shove's path until the first impassable cell.
  • coneSector/ConeSectorOptions - a circular sector aimed at an angle: rays cast every 0.5 degrees across an arc of degrees, each clamped to range and stopped by the first wall, so a wall shadows what is behind it while the rest of the cone reaches. Unlike coneCells, the aim is not snapped to one of the eight directions.
  • resolveAreaOnLevel/hexConeCells - topology-aware area resolution and widening hex cones, complementing the square-grid targeting helpers.
  • rangeMultiplier/areaFalloffMultiplier/RangeBand - a range-band damage multiplier lookup, and a per-target falloff multiplier for an area effect hitting several targets.
  • BossPhases/AbilityCycle - an HP-fraction phase ladder whose check(hpFraction) reports newly entered phases, and a named-cooldown ability rotation (ready/use/advance).
  • CombatHooks/CombatEvent/DamageContext - core.HookRegistry with combat's argument shape (one mutable DamageContext), plus modifyDamage's pre-damage seam.
  • Stealth/StealthOptions - sticky, one-way detection: checkDetection returns true only on the call that first brings an observer within radius.
  • TriggerTracker - a streak counter (combo, kill-streak) that extends within a turn window and restarts once the window lapses.
  • MultiStageAbility/AbilityStage - an ability that unfolds through named, turn-timed stages (windup/active/recovery) once started.
  • Minimap/minimapCellCenter - exploration minimap rendering and overlay coordinates for square and odd-q hex maps.
  • MultiTurnBeam - a deterministic one-front-per-turn beam. The default shape is a straight line; fronts opts into a per-turn front resolver (cone, burst, fork, moving front), blocker is the explicit terrain/none/custom policy with isBlocked as an extra game rule, onCell sees every reached cell, and a save carries the shape name so a reload resumes the same one. Live target lookup, game-owned damage application, cancellation and save/restore as before.
  • BeamBlocker/BeamStep/MultiTurnBeamSave - the blocker policy, one turn's reached cells and damage, and the serialisable front list with its shape identity.

rpg

Tiled map/event data, the map-event interpreter, switches/variables, and grid movement - the classic top-down RPG half.

  • automap/AutomapRule/AutomapTarget/AUTOMAP_EMPTY - Tiled-style automapping: input/output pattern rules applied in order, each rule's matches collected before any write. Takes any grid exposing getTile/setTile (a TileMap satisfies it structurally), so automapping needs no renderer.
  • GameState - switches and variables.
  • activePage/conditionHolds/EventPage/MapEvent - last-matching-page resolution for a map event, re-checked rather than cached.
  • EventRunner/EventCommand/DialoguePresenter/DialogueRequest/EventChoice - a StageScript-shaped command interpreter for map events. Dialogue goes through an injected present function rather than a widget, so the interpreter is renderer-free and a game can drive it from a 3D scene, a DOM overlay, or a test asserting on script order. two-d/ui.messageBoxPresenter is the ready-made 2D implementation. DialogueRequest.portrait is an opaque, renderer-specific value (Texture2D for messageBoxPresenter), kept untyped here so rpg stays renderer-free. EventRunner.runStory/EventStoryScript follow a named- passage graph the same way StageScript.runStory/StoryScript do - a goto command, or a choice's own goto, jumps to a different passage; a plain run() refuses a stray goto rather than silently ignoring it, the same guard StageScript.run applies. EventRunnerOptions.onUnknownCommand hears every command the runner has no handler for (and a goto in a straight run(), which then ends the list instead of throwing), so a game converting foreign event data can make every dropped command loud.
  • importTwee/EventTwineStory - imports Twee-notation Twine stories into EventStoryScript, a thin wrapper around core.parseTwee (the same engine two-d/stage.importTwee wraps for StageCommand/StoryScript instead) naming the EventStoryScript return type, so a text-only RPG can import a branching Twee story without depending on two-d for anything.
  • GridMover/Direction4 - tweened tile-to-tile movement plus a walk-cycle hook. GridMover.jumpBy repositions instantly, with no tween or walk animation, for a move-route "jump" step.
  • MoveRouteRunner/MoveRoute/MoveRouteStep/MoveRouteOptions - drives any GridMover (the player's or an NPC's) through a scripted route over successive update(dt) calls: fixed/random/toward/away directional steps, a turn-in-place step, a jump step, and a wait step, with repeat and skippable policies. Whether a step is passable is asked through the same canMove contract GridMover itself expects of its own caller.
  • FreeMover - continuous (non-grid) position and facing, for action-game movement.
  • MovableSprite - what both movers actually require: x/y, and optionally update/has/ play. A static sprite, a 3D mesh wrapper or a plain test record all satisfy it.
  • aabbOverlap/circleOverlap/circleAabbOverlap/resolveAabbAgainstTiles - 2D collision: shape overlap tests, and an axis-separated sweep against solid tiles.
  • QuestLog/QuestStage/QuestDefinition/QuestMarker - quest stages advanced one at a time by advanceStage, prerequisites, markerFor deriving 'offer'/'turnIn'/'none', and a tracked-quest pointer/location.
  • questsFromRows/QuestStageRow - groups a flat table of stage rows (typically a core.parseCSV result, one row per stage sharing a questId) into QuestDefinitions a QuestLog can define.
  • decodeMarshal/encodeMarshal/RubySymbol - Ruby Marshal 4.8 binary serialization (the container format RPG Maker's own .rxdata saves use).
  • hashDefaultOf/withHashDefault - reads and attaches a Ruby hash's default value, which Marshal carries alongside the entries rather than as one of them.
  • parseDialogueText/extractDialogueCatalog - the terse @id text/--alternation dialogue format targeting EventCommand, a thin wrapper around core.parseDialogueLines (the same engine two-d/stage.parseDialogueText wraps for StageCommand instead), so a text-only RPG (core plus rpg, no renderer at all) can author dialogue without depending on two-d for anything. extractDialogueCatalog builds an identity i18n catalog from the result, the same shape MWL's own extractCatalog builds from _("...")-marked strings.

simulation

TrainingEnvironment adapts game-owned TrainingRules around the existing SimulationRule, with no renderer, DOM, audio or animation loop. reset(seed) returns a TrainingFrame with per-agent observations, rewards, terminated and truncated. step(actions) takes one action index per agent (or null only for an all-masked idle agent), invokes the same rule used during play and returns the next frame. Rewards inspect a cloned pre-transition state, so mutable rules work. The agent roster stays fixed within an episode. maxSteps is required and capped at one million; reaching it truncates an unfinished episode, while rule completion terminates it. Real-time games advance fixed simulation ticks inside their rules; turn-based games advance turns. Neither waits for wall-clock time. A throwing rule can mutate its state, as with runScenario; reset or restore before continuing.

snapshot()/restore() use TrainingSnapshot: versioned environment state, schema, step limit, completion flags, seed and RNG state. TrainingCheckpoint<State, TrainerState> combines that snapshot with the NeuralModel and game-owned optimizer/exploration state. Persist every random stream the trainer uses in trainerState. Train with the same observation schema and action ordering used by the playable game.

runRollouts(environment, model, RolloutOptions) chooses actions from each new observation until completion. Options provide episode seeds, optional seeded softmax sampling and trajectoryLimit (first transitions per episode, zero by default). RolloutEpisode reports steps, cumulative per-agent rewards, completion flags and a bounded array of TrainingTransitions. No command journal or presentation events are retained. Batches accept at most 10000 episodes and 10000 stored transitions.

runRolloutsAsync(TrainingFactory, config, model, options) shards episodes across workers (default four, configurable jobs in 1..64). Each worker keeps its model, environment and inference buffers for the whole shard. Results stay in seed order; signal and per-worker timeout terminate work, and any failure terminates sibling workers. The factory must be self-contained, like threads.spawn, accepting the supplied TrainingEnvironment constructor and structured-cloneable configuration; it cannot close over module imports. Both paths run the same classes and inference code, including in a compiled file:// page. Training algorithms and rewards are game-owned; tools/train-neural.ts shows a seeded evolution optimizer, resumable checkpoint and model export, and examples/neural loads its trained weights.

imitationFromReplay(environment, { actions, events, seed }) turns a persisted run (roadmap 397) into imitation targets: it walks the recorded actions against the same seeded environment they were played on and returns the (observation, action) samples a game's own trainer fits, sourced from how its players played rather than a generated expert. One recorded event is one environment step; the environment must expose exactly one agent (the recorded player - anything else that moves is part of the rule, like the maze chase's ghosts); a recorded action outside the list is a named error, never a silently skipped event.

runSeededEpisode(environment, choose, { seed }) plays one whole run with the AI choosing, from a named seed: the same seed and the same deterministic choose make the same decisions, so runs compare across builds, policies and machines. Unlike runRollouts the chooser is not a NeuralModel - a heuristic, a NeuralPolicy's argmax, or any named function works - and the result records every chosen action and the cumulative rewards, with the environment's maxSteps as the truncation bound.

Headless, deterministic turn/scenario running - for testing and benchmarking without a live game loop.

  • advanceToInput/ScheduledTurns/TurnRules/TurnResult - drives turns forward under a rule set until the next input is due.
  • runScenario/Scenario/ScenarioResult - a bounded, scripted simulation run against a set of expectations.
  • Campaign/CampaignLevel/CampaignLevelResult/CampaignSnapshot - generic level order, result, carry-over, reminder and transition state, with JSON-safe save/restore.
  • runHeadlessScenario/HeadlessScenario/HeadlessScenarioResult - seeded, renderer-free scenario execution returning the final state, ordered events and resumable random state.
  • SimulationRuntime/SimulationContext/SimulationOutcome/SimulationRuntimeRule/ SimulationSnapshot - a facade over one state + one roguelike.Scheduler + one core. Generator, for the interactive half of a turn-based simulation: dispatch runs a single command through the game's rule, threading random/scheduler as context and charging any returned cost; snapshot/restore capture and rebuild the whole triple. Commands, events and (with history) state are journalled through structuredClone, so they must be plain data: name an actor by id, never pass the live object. A dispatch that cannot copy them throws with the offending path and commits nothing. Composes with advanceToInput against the same scheduler for the automatic-actor loop, rather than replacing it.
  • EventPresentation/EventPresentationOptions - the documented pattern tying a SimulationRuntime to a core.PresentationQueue: submit commits a command and starts its events, locked is the animation lock submit refuses under, followUp schedules a secondary actor's commands for after the current batch, cancel drops the rest of the show without rolling the committed turn back, and snapshot/restore deliberately leave the queue out of a save so a load resumes idle.
  • Scheduler/Actor/SchedulerSnapshot - re-exported here from roguelike (its real home), since every SimulationRuntime needs one; a simulation-first game need not import a second module just to construct the class its own runtime is built around.
  • CampaignSave/CampaignSaveState/CampaignSaveParts - one core.SaveSystem slot for a whole campaign: save captures the Campaign snapshot, the game's own world payload and the SimulationRuntime snapshot together, load reads them back migrated, and list/delete are SaveSystem's. The world is opaque, so an MwlWorld, a Level or a game's own scenario object all fit.

skeleton

Skeletal pose math, renderer-free: a bone tree, keyframed clips and layered blending, as pure data and arithmetic so it loads headless and tests without a renderer. Clips are plain JSON-shaped data a game authors itself. import * as Skeleton from '@datamoc/mwg/skeleton'.

  • create(bones) - builds a SkeletonBones from Bones (name, parent, length, origin, rest rotation in degrees, optional limits), throwing by name on a duplicate bone, a cycle, a missing parent or inverted joint limits. boneOrder lists names parents first.
  • resolve(skeleton, pose?) - walks the tree and returns one BoneTransform per bone (world x/y, angle, composed scale, a 2D matrix, and the tipX/tipY the children start from). A Pose is one rotation per bone name; a TransformPose adds per-bone translations and scales.
  • samplePose/sampleTransformPose(clip, time, skeleton?) - a Clip (duration, loop, ascending Keyframes) interpolated at a time: a looping clip wraps, a one-shot holds its last frame. Passing the skeleton validates the result.
  • advancePlayback/createMixer/crossfadeTo/advance/advancePose - a Mixer holds a base Playback plus weighted, prioritised additive Layers. advance(mixer, dt) ticks every playhead, folds in a running crossfade and the layers, and returns rotations; advancePose returns the full TransformPose. mixPoses blends rotation poses by layer priority and weight.
  • validatePose - refuses non-finite rotations and angles outside a bone's limits.
  • solveTwoBoneIK(skeleton, first, second, target, bend?, pose?) - solves a connected two-bone chain toward a world target without stretching; throws for an unreachable target or a second bone with a non-zero origin.

physics

Small deterministic simulations, renderer-free, with no third-party engine. Three entry points: @datamoc/mwg/physics (rigid bodies, cloth, spring) and @datamoc/mwg/physics/xpbd (a structure solver). Everything is plain arithmetic, so a game's headless tests run the same world.

  • PhysicsWorld - rigid circles and axis-aligned boxes (never rotating: angle is a display offset), stepped on a FixedStepper so results do not depend on the display refresh rate. Semi-implicit Euler, impulse contacts with restitution and friction, and distance joints. addBox/addCircle return a plain PhysicsBody (position, velocity, angle, label, isStatic); connect joins two bodies or a body and a world point (ConstraintOptions: stiffness, damping, length, attachment points, and maxStretch to make the joint breakable); remove takes a body or constraint; stretchOf reads a joint's strain; update(dt) runs the fixed steps it covers and returns their count. onContact and onBreak are Signals.
  • XpbdWorld (physics/xpbd) - point masses (addNode, fixed anchors) joined by springs (addLink: stiffness, rest, tensionOnly cables, strength/tensionStrength), solved with extended position-based dynamics and the force in each link read back, so a link breaks at a real load. Fixed steps and no randomness make a replay identical on every machine. step() advances one frame; applyForce pushes a node for one step; ground is a height or a function of x; breaking gates breaking so a structure can settle first; onBreak fires per broken link and peakRatio is a strain gauge. It has no rigid bodies or collisions, which is what PhysicsWorld is for.
  • Cloth - a pinned-point Verlet grid (top row pinned) with structural links only, no allocation per step. indexOf/pointPosition/pointLinks/writePositions read it back; pinPoint/unpinPoint, setWind/setGravity, reset and update(dt) drive it. two-d's ClothSprite draws one as a mesh on the GPU path.
  • Spring - a damped chase spring for secondary motion (hair, hems, panels): setAnchor moves the target, displace shoves the bob, offset/length/settled(tolerance) read the lag, place(target) positions a display object, update(dt) steps it. Under reduced motion it follows SpringOptions.intent (decorative snaps to the anchor).

testing

Test doubles for the seams mwg takes by injection (item 388), so a game's tests and this repository's own share one copy of each. Renderer-free, dependency-free, and off the root barrel: nothing here reaches a shipped game unless a test imports it.

  • createSceneControls (item 408) - named steps a game opts into (enterScenario, finishTurn, advanceDialogue in the Wesnoth port), driven by name from a test or a headless Chrome: the game decides what a step does, the controls only promise that a registered name runs and an unknown one is refused by name.
  • memoryStorage - a SaveStorage held in memory, for SaveSystem, Settings, Collection, PlayerStats and the other stored values; the same class core falls back to where localStorage is missing.
  • exposeForTests(name, object) - publishes inspectable game state under window.__mwg_test__[name] for browser tests; does nothing outside a browser.
  • fakeAudio/fakeAudioWithEnded/FakePlayable - a Playable for Sound/Music's create that counts its plays; the second also has the onended slot a backend reporting track ends has.
  • FakeAudioContext/FakeBuffer/FakeBufferSource/FakeGain/FakeBlockSource - a fake WebAudio graph for the audio tests: sources, gains and buffers a test can inspect, and a block source for a StreamChannel, with no real AudioContext anywhere.
  • FakeRetroPlayer - a MidiSynth double for a retro engine: it records every message it was driven with and renders a flat level while a note is on, so a renderer test reads what was sent and what sounded, with FakeAudioContext.advance() as the clock it moves by hand.
  • FakeSocket - a WebSocketLike for LockstepClient's create: sent, receive(message), receiveRaw(text), close().
  • fakeFetch/FakeFetchCall - a fetch for every HttpTransport client, answering with a Response or a value sent as JSON, recording each call.
  • fakeGamepad - a Gamepad from button values (pressed above 0.5) and axes, for Input and PlayerInput.

threads

Runs a self-contained function on a worker thread, so a blocking computation costs a background thread instead of a dropped frame. mwg's own runtime rather than a dependency: a classic blob worker in the browser, because that is the one shape a double-clicked file:// page accepts (the shipped CSP allows worker-src blob: and new Function, and a module worker loaded from file:// fails CORS whatever the policy says), and node:worker_threads in Node. Off the root barrel like testing: a game that never spawns a worker pays nothing for it, and imports @datamoc/mwg/threads when it wants one.

  • openWorker(source, events) - opens a long-lived worker from a self-contained script (blob worker in a browser, node:worker_threads in Node, null where neither exists) and returns its message link; spawn is the one-task use of it, a service such as the audio core host keeps its worker and talks to it.
  • spawn(fn, args?, options?) - runs fn on a worker and resolves with its value. The task is serialized with Function.prototype.toString, so it must be self-contained: no closures over module scope, no imports, no bound or native functions - everything it needs arrives as args, structured-cloned in. options.transfer moves listed buffers instead, detaching them from the caller's thread. The result returns structured-cloned with every ArrayBuffer inside it transferred rather than copied, since the worker is finished with them. A task that throws, closes over something the worker cannot see, or kills its worker without answering rejects the promise instead of hanging it; options.timeout abandons a task that never returns, and options.signal (an AbortSignal) cancels one on demand. One worker per task, terminated the moment it settles. In Node an unsettled task keeps the process alive, so settle or cancel every task before exit.

headless

The blessed renderer-free entry: every module that loads in bare Node, in one import, with no DOM or WebGL globals. A rule imported through here is headless by construction; anything outside it belongs in presentation, not in the rule.

  • core/simulation/mwl - scenes, saves, RNG, headless scenarios and content tables.
  • i18n/actors/world/battle - messages, stats, maps, encounters and type matchups.
  • roguelike/board/audio/rpg - dungeon generation, board rules, sound/music primitives (inject create, as under plain audio) and map events.
  • ai/testing - decision runners and the shared test doubles.
  • assetPaths/assetBinary - the two renderer-free asset halves (path resolution and byte caching) beside the Pixi-backed assets loader.

Excluded with reasons in src/headless/index.ts: three-d (needs Babylon at import), the Lua runtimes (mwl/pyroeis, ai/lua), and every two-d/* module.

three-d (optional)

Babylon.js-backed 3D, kept fully separate from the 2D default - nothing in core imports this module.

  • Engine3D - owns Babylon's engine, scene, orbit camera, light, resize, and render loop.
  • gridPoint3D/GridCell3D/GridShape3D - square/hex 3D grid cell projection.
  • createTileGrid3D - a thin-instanced 3D tile floor (square or hex) with elevation columns for nonzero cell heights.
  • Character3D - moves an imported mesh or a camera-facing billboard sprite through continuous world coordinates; playAnimation plays a clip an imported model carries.
  • parseVox/createVoxModel3D - MagicaVoxel .vox import, batched by colour.
  • loadModel3D/loadModelContainer3D/isModelContainerLoaded/releaseModelContainer (@datamoc/mwg/3d/models, kept out of the main 3d barrel so a scene that never imports a model pays nothing for the loader) - glTF/GLB import. loadModel3D imports straight into the scene, for one copy; loadModelContainer3D fetches and parses a source once, caches the AssetContainer, and a game calls instantiateModelsToScene() on it for each independent, unaliased copy it wants placed - Babylon's own answer to "load once, place many" without a second network fetch.
  • createHeightmapTerrain3D - a continuous displaced-mesh terrain from a greyscale heightmap image, alongside createTileGrid3D's stepped floors.
  • buildHeightIndex/cellAt/heightAt/resolveCapsuleAgainstGrid - horizontal collision for a moving capsule against createTileGrid3D's stepped grid.

world

Many maps, transitions, persistence, the turn clock, encounter tables - the connective tissue between scenes.

  • World - many maps, each created once and kept alive (or rebuilt fresh per entry when defined persistent: false); unload frees a map's own state.
  • Overworld/Location - named-location lookup.
  • TurnClock/TimedEffect - hunger/poison-style timed effects, ticked on advance.
  • rollEncounter/EncounterTable - rolls whether an encounter fires, then weight-picks which.
  • EnvironmentClock/DayPhase/EnvironmentSnapshot - a continuous day/night-phase and weather clock above any one encounter, driven by update(dt) in real seconds, with change notifications and toJSON/fromJSON.
  • SideTurns/SideTurn/TimeOfDay/TimeArea/Alignment/alignmentBonus - the reference strategy game's outer turn model: sides take turns in order, a round is all of them, and the time-of-day schedule steps on per round. lawfulBonusAt applies a unit's alignment to the current time's lawfulBonus, and a TimeArea overrides the schedule for part of the map, which is what makes the bonus per-hex. toJSON/fromJSON resume the exact position.

i18n

Message tables, plurals, interpolation, and direction - pure logic, no Pixi dependency.

  • Direction/Catalog/MessageValue - the message-table shape: locale, direction, messages, an optional Fluent-parsed or plain-string/plural-form value.
  • setBase/setActive/locale/direction - the active and fallback language, and the direction ui's Theme.direction reads from; reset clears both back to unset.
  • t/tRaw/formatSpec/tokenizeMessage/diffPlaceholders/MessageParams - resolves a key, selecting a plural form via Intl.PluralRules and interpolating {token}s, including dotted paths that walk into nested params ({side.stored.hitpoints} against { side: { stored: { hitpoints: 12 } } }); falls back to the base language, then to the raw key. Placeholders also take Python f-string-style specs ({dmg:03d}, {hp:.1%}, {name:>12}), !s/!r/!a conversions and = debugging, resolved through formatSpec (verified case by case against CPython; an ill-fitting spec stays untouched rather than throwing). tokenizeMessage is the single definition of that placeholder grammar, shared by interpolation and by diffPlaceholders, which compares a reference string against its translation (dropped, added, or reshaped tokens) for tools/i18n-edit to surface. tRaw skips the display-text decoration (typographic spacing, RTL wrapping) for catalog values that are not shown to the player, such as a sound path.
  • parseSoundMarkers/stripSoundMarkers/InlineSoundCue/ParsedSoundText - extracts {sound:path} markers from translated text, returning marker-free display text and each cue's visible-character offset. MessageBox consumes these markers during its reveal; t() and tRaw() preserve them for the presentation layer.
  • typographic - locale-aware curly-apostrophe substitution (French/Italian/Dutch elisions); for French, also a narrow no-break space before ; ! ? : and around « », and a plain no-break space between a numbering word and its number ("Chapitre 3"); for German, a no-break space between a number and its unit ("5 kg") and after a small set of abbreviations ("Nr. 3", "Dr. Müller").
  • nonBreakingUnit - joins a value and a game-defined unit ("pièces d'or", "points de vie") with whichever no-break space French/German typography calls for; the unit's own text is always the game's vocabulary, never MWG's.
  • has - whether a key resolves to something real, in either language.
  • parseFTL/FluentOptions - parses Project Fluent .ftl message resources into the same Catalog/t() surface, with variables, exact and plural variants.
  • parsePo/PoOptions - parses a gettext .po file into the same Catalog/t() surface: msgid/msgstr, msgctxt, msgid_plural with msgstr[N] mapped onto the locale's CLDR categories, the header entry dropped, untranslated entries left out for base fallback - which includes a #, fuzzy one, the way gettext's own tools treat it - and a non-default gettext domain prefixing keys.
  • SemanticMessage/MessageChannel/MessageFormatter/createCatalogFormatter - a typed { type, params } communication intent rendered differently per channel (log/compact/ accessibility/debug/audio) from the same underlying catalog: createCatalogFormatter looks up ${type}.${channel}, falling back to ${type} alone, then formats through t(). A simulation emits the message once; the channel is a presentation choice, not a rule. The audio channel holds a sound path (played game-side through audio's Sound), resolves through tRaw rather than t(), returns '' when no <type>.audio entry exists, and never falls back to a bare type holding a sentence.
  • EntityTextResolver/GrammaticalEntity - type contracts a game uses while building a SemanticMessage's params (resolving an id to display text, or carrying gender/number/ proper-noun metadata for its own catalog's grammar); MWG never calls or interprets either.
  • formatNumber/formatDate/formatList - locale-aware Intl.NumberFormat/ DateTimeFormat/ListFormat wrappers reading the active locale from locale(), for a message that needs more than {token} substitution - a game calls these while building a t()/SemanticMessage param, the same way it resolves an entity id to display text.
  • diffCatalogKeys/validateCatalog/CatalogKeyDiff/CatalogIssue - catalog consistency checks: diffCatalogKeys compares two catalogs' key sets (a base language against a translation); validateCatalog flags empty messages and plural forms missing their other branch within one catalog. Deliberately not a parameter schema validator - a SemanticMessage<TType, TParams>'s own generics already give a game compile-time parameter safety, which is the primary mechanism the source document calls for.
  • validateMessageAudio/AudioIssue - structural checks over <type>.audio sound-cue entries: empty paths and non-string (plural/select) values, which would reduce silently at lookup time rather than selecting per play.
  • EditSession/EditRow/RowFilter/AUDIO_SUFFIX/createEditSession/sessionKeys/ sessionRow/sessionRows/setTargetText/copyFromBase/deleteTargetKey/ setTargetSound/cueKeyFor/sessionCompleteness/swapSession/isAudioKey - the pure session core behind tools/i18n-edit: translatable rows with reference/target text and an effective cue (a channel key shares its semantic family's <type>.audio, one cue per family), completeness ignoring cue keys, and swapping which catalog is the reference. tools/i18n-edit.mjs is the terminal split-screen editor over it, with a --check mode for CI.
  • messageText/levenshteinDistance/findSimilarMessages - content-management over a catalog's actual message text rather than only its key shape: messageText reduces any MessageValue to plain comparable text, levenshteinDistance is the classic edit-distance primitive, and findSimilarMessages surfaces near-duplicate messages worth merging by similarity threshold, most-similar first.
  • catalogUsage/catalogCompleteness/pluralFormCoverage - catalog statistics: catalogUsage compares a catalog's keys against a caller-supplied referenced-keys list (mwg has no view into a game's own source) for used/unused counts; catalogCompleteness is a 0-1 translated fraction built on diffCatalogKeys; pluralFormCoverage tallies which CLDR plural categories a catalog's plural-form messages actually define.
  • mergeCatalogKeys - drops a merged key from one catalog, keeping the surviving key's text untouched; rewriting call sites that used the merged key stays the caller's own job, the same boundary catalogUsage's referencedKeys already draws.

mwl

MWL is the build-time, game-neutral content layer. It uses a WML-inspired syntax for data such as units, items, maps, events, AI hooks, translations, and asset references. The runtime consumes generated data and does not parse .mwl source files in the browser.

  • mwl build - reads one file or a directory of .mwl files in stable path order and emits game-data.ts, i18n.json, and assets.json in one step.

  • mwl build --asset-root public/assets - optionally verifies every extracted asset before emitting the generated files. Missing paths include their MWL source location; without this flag the build stays portable for games that resolve assets elsewhere.

  • contentReport / loadContent / mwl report - counts tags, lists opaque names, reports resources, dependencies and unresolved references, and returns structured load diagnostics for parity checks and CI.

  • validateCatalog/validateCatalogNodes/MwlValidationOptions - semantic checks shared by every game: MWL_DUPLICATE_ID, MWL_UNKNOWN_SLOT, MWL_INCOMPLETE_EFFECT, MWL_INVALID_HOOK/MWL_UNKNOWN_HOOK. MWL_DUPLICATE_ID's tag:id key is scoped by rowIdScope (item 304): 'global' (the default) checks the whole compiled catalog, every source file combined; 'file' folds each node's own source file into the key too, for a game whose id convention is meaningful only within one file and reuses ids across files on purpose

    • a real duplicate within one file still reports.
  • [campaign] - declares game-owned campaign metadata (id, optional name, title, description, and start_scene). Its children are intentionally open so a game can define scenario and progression tags without changing the core MWL schema; metadata is exposed by contentCatalog(game).campaigns.

  • campaignChain - points a [campaign] at simulation.Campaign: first_scenario opens the chain, each [scenario]'s next_scenario is where it goes when it is won, and a scenario that ends the chain ends the campaign. The order is content, the playing stays the game's (run is a callback), and a scenario that decides for itself - a runtime [endlevel] - keeps its decision. The [campaign] schema reads first_scenario, and the catalog exposes each campaign's scenarios.

  • endLevelCarryover/carryoverIntoScenario/MWL_DEFAULT_CARRYOVER_PERCENTAGE with [endlevel] - a scenario's end as the reference models it: a share of the side's gold (80% by default), a bonus on top, that side's surviving units as the recall list, and the next scenario. result=victory ends it won, result=defeat lost, and the arithmetic is the same for both.

  • One side identity (item 277): the id a [side] declares (now a string, so a named side like id=rebels validates) keys world.sides and world.gold, marks a map keep (rebels Kh), and is what unit.side, MwlMessage.side and every side/side_filter filter hold. MwlSideRef is just that id.

  • nodesToObjects/MwlObject - converts compiled nodes to JSON objects using the tag schema: declared numbers and booleans become typed fields, child tags become ordered arrays, and a cardinality.max of 1 selects a single object. Missing optional fields stay absent. Check the returned diagnostics for conversion errors and field collisions. Attributes not listed in MwlTagSchema.required are optional; use number, not number?.

  • readAttributes / readChildren - shared typed readers for compiled nodes. They coerce scalars and lists and return source-located diagnostics instead of silently guessing.

  • MwlNode.attributeLocations / valueLocations - parsed JSON5 nodes retain the exact key and value start for each attribute, and schema diagnostics use those locations when available.

  • MwlValidationOptions.mapBounds - an adapter can supply map dimensions so validateCatalog rejects out-of-bounds integer, list, and range coordinates without embedding a map system in MWG.

  • readTableMap / readTableIndex / tableKey - project typed table rows into a Map, use collision-free native composite keys, and build inverse indexes that retain every matching row.

  • A key="""...""" value (item 317) is the one attribute form that may span lines, and its text is exactly what sits between the delimiters, so wrapped message, objective and option-label text survives a conversion without the whitespace-collapsing workaround it otherwise needs. It carries the _ gettext marker like any other value; text="""done""" is the same form on one line. (A line starting with # is still a comment wherever it appears, so a block cannot carry one at the start of a line.)

  • MWL tables use [table] columns=name:type|... with typed [row] attributes. The compiler validates column shape and values, and contentCatalog(game).tables exposes typed rows. Supported column types match core.parseCSV: string, number, boolean, list, and map, with configurable list and map delimiters. typedRows/MwlTypedRow/ MwlColumnValueType read rows through the declared columns (every field optional, an absent cell omits the key), and emitTableTypes emits one named row interface plus one typed accessor per table for a game's build script to write and import, so a changed column type or a removed column fails type-checking at every use. emitTableTypes(tables, { literalColumns: ['id', 'sprite'] }) also exports sorted, deduplicated readonly value lists and literal unions such as VehiclesSprite from the current string-column values. Regenerate them with the catalog to catch stale game ids.

  • MwlValidationOptions.tableReferences/MwlTableReference (item 362) - declarative cross-table checks, so no game hand-rolls one validator per table: a column declares references: { table, column } or oneOf: [...], and validateCatalog checks every cell once for all tables, reporting MWL_TABLE_REFERENCE with the table, the row, and the offending value. The declarations' contents stay game data; absent or empty cells are skipped and a list cell checks each entry under the table's own delimiter.

  • composeEffects - resolves MWL effects through actors.composeModifiers, so declarative item effects and actor stats use one composition rule.

  • evaluateCondition - evaluates bounded content conditions with comparisons, and/or/not, arithmetic, literals, where bindings, and explicitly supplied pure helpers. There are no loops, assignments, dynamic code loading, or implicit game rules.

  • mwl validate - checks syntax and content structure without generating runtime files.

  • mwl diagnostics / mwl ci - emit stable JSON diagnostics, with ci additionally exposing a boolean valid result and returning a failing process status when errors exist.

  • mwl format / mwl migrate --to 1.0 - expand and emit a deterministic canonical MWL document; migration requires an explicit target and currently normalizes the MWL 1.0 syntax surface.

  • mwl compile/mwl extract-i18n/mwl hooks - lower-level commands for a generated module, translation extraction, or hook manifest when a build pipeline needs separate outputs.

  • parse/compile/validate/extractI18n - the programmatic compiler surface exported from @datamoc/mwg/mwl; games provide their own hook implementations and interpret game-specific effects.

  • The [side] surface Wesnoth's own data writes, and the one key of it with behaviour here (item 252): team_name, user_team_name, share_vision, village_gold, heal, fog, shroud, hidden and flag are read onto MwlWorld.sides as written, yes/no becoming booleans. sideVisionGroups turns team_name and share_vision into the groups FactionFog.share takes, so a scenario's teams see together without every game re-deriving who shares with whom. leader= names either a [unit] id already declared (that unit is the side's leader; nothing is spawned) or a unit type (one leader per free start cell, with that type's stats); a value that is neither is refused by name (item 405).

  • A [side]'s own [victory]/[defeat] children (item 283): a side condition that names no side/side_filter reads as that side's own, its result lands in MwlWorld.sideStatus keyed by the side id, and the aggregate MwlWorld.status ends the scenario as a scenario-wide condition would (a side victory outranking another side's defeat when both fire at once). [win]/[lose] record the side they name too.

  • Public MWL exports - MwlRuntime, MwlSyntaxError, collectHookReferences, compileNodes, compileSources, compileAndEmitSources, emitArtifacts, coerceTableValue, decodeSaveEnvelope, parseTableColumns, contentCatalog, createWorld, decodeSave, effectToModifier, emitHooksDeclaration, emitModule, emitTableTypes, encodeSave, evaluateExpression, execute, extractCatalog, hookTypes, inventoryItem, isGettext, isMwlId, itemDefinition, PACKAGE_TAGS, PACKAGE_ASSET_KINDS, PACKAGE_MEDIA_KINDS, PACKAGE_SCRIPT_ACTIONS, KNOWN_PACKAGE_CAPABILITIES, DEFAULT_PACKAGE_LIMITS, PackageError, PackageFormatError, PackageIntegrityError, PackageLimitError, PackagePathError, PackageConflictError, encodePackage, decodePackage, verifyPackage, loadPackage, mergePackage, compilePackages, packageContent, packageRef, parsePackageRef, parsePackageDocument, checkPackagePath, checkPackagePolicy, checkConditionSyntax, compareVersions, satisfiesVersionRange, requestedCapabilities, detectRomImage, registerRomDigest, generateCredits and sha256Hex (self-contained .mwp content packages: one compressed container with per-entry digests and declared limits, a capability policy the game accepts or refuses, id@version namespaces in saves, and a ROM-image refusal with generated credits; verifyPackage's shared option demands a licence on every synth-patch bank, and its inspectPatch hook lets an instrument's own parser report what only it knows, its warnings (an unrendered wave) never refusing the package and its errors refusing it), parseExpression, parseHookReference, parseMapFile, parseTerrain, parseValue, preprocess, schema01, typedRows, validateCatalogNodes, validateHookReferences, loadContent, and validateWorld.

  • parseMapFile/MwlMapFile (item 284) - reads a Wesnoth-shaped .map: the key=value header is split off and kept, and the comma-separated rows go through the same parseTerrain an inline [map] terrain= uses, overlays (Gg^Vh) and <side> <code> starts included. Header keys are not interpreted here, the same way [terrain_graphics] rules stay content's business.

  • MwlHookDeclaration/validateHookAttributes (item 321) - a hook may declare the attributes its own [hook] calls carry (attributes, typed the way a tag schema types its own, or openAttributes), and validateCatalog's hooks option takes it in place of a bare type:name id, so a typo in one of a command hook's eighteen modes is a compile-time MWL_VALUE rather than a throw mid-scenario. The declaration is the hook's, not the tag's: only [hook] calls are checked, where every attribute but name belongs to the hook. The rule itself is validAttributeValue/attributeTypeDescription, exported because the tag schema and a hook declaration check values the same way rather than two ways that drift.

  • MwlDomainHook/MwlDomainHookRegistry - game-declared hook namespaces such as item-effect:potion-strength use a typed context/input/output boundary. MWG validates and emits the reference shape, while the game owns the domain types, rules, and implementation.

  • HookWorld/Emit (item 319) - the hook boundary's two halves. world.variableAt(path) resolves a nested variable through the same walker [variable] name= reads through, and emit.setVariable(path, value) is its write, so a hook asks for stored_naga.hitpoints and means the same variable content does; writing world.variables directly gets a flat dotted key no reader finds.

  • HookWorld.random/MwlRuntimeOptions.random - a hook draws from the runtime's own seeded core.Generator instead of Math.random(), so a generator/ai/domain hook stays reproducible; the draw position is carried on MwlWorld.random and resumes exactly across save/restore.

  • MwlTraceEvent/MwlRuntimeOptions.onTrace - opt-in lifecycle tracing for event claims, completions, variable writes and runtime errors. MwlHookRegistry.predicate lets an adapter register named, typed filter predicates without putting game-specific semantics in MWG.

  • MwlSaveableHookState / MwlHookRegistry.saveable - a game may explicitly expose JSON-safe hook state; MwlRuntime.save() includes it and restore() hands it back to the same adapter.

  • MwlRuntime.journal / MwlRuntimeAction - public runtime triggers and their trace batches are recorded in order and persisted with the save, providing a replay and diagnostics input without making MWG interpret game-specific commands.

  • validateCatalog also reports MWL_ALIAS_CYCLE for cycles among resolved aliasof references; aliases outside the catalog remain available for game-defined sentinel values.

  • validateSimulationReplay - replays a SimulationRuntime journal from a checkpoint, compares each deterministic event batch, and optionally verifies the final state with a stable checksum.

  • SimulationRuntime accepts an optional history: { actorOf, limit? }; canUndo, canRedo, undo() and redo() restore complete state, scheduler, RNG and journal checkpoints.

  • CanonicalState / CanonicalStateSnapshot - a defensive, JSON-safe root state combined with StateRegistry extensions; snapshots, version migrations, transactions and restores cover all pieces atomically.

  • LockstepClient supports optional command validation, receives a session seed and initial state, and can submit per-tick state checksums; onDesync reports differing peer checksums. createLockstepServer accepts matching seed, initialState and validateInput options.

  • MWL_SCHEMA_01 / MWL_SCHEMA_10 and schema01 / schema10 identify the supported MWL vocabularies; mwl migrate --to 1.0 updates the document version without changing its data. Schema 1.0 additionally enforces declared required attributes and child cardinalities.

  • ScriptHost and createExpressionScriptHost - the game-owned boundary for executable content. The expression host is the statement-free default. The main mwl entry point exports its types without loading a scripting VM. Projects that opt in to the optional @datamoc/pyroeis dependency can import createPyroeisScriptHost from @datamoc/mwg/mwl/pyroeis. It provides Lua 5.4 evaluation, chunks, named function calls, JSON-shaped context values, and mwg_emit(name, payload) events. The adapter opens only the sandbox-safe standard libraries (base, coroutine, math, string, table, utf8): io, os, debug and package with its require are never constructed, identically in Node and the browser, the base library's load, loadfile and dofile are removed, and chunks compile in text mode only, so a binary \x1bLua dump is rejected. It replaces math.random with seeded deterministic random, and enforces an instruction budget and a memoryLimit (bytes of string and buffer data one call may allocate, 32 MB by default, parsing included), since one .. or string.rep instruction can allocate without bound. Scripts get local x <const>, local x <close> (with __close, run on a normal exit, break, return and error, and unwound by a limit error too) and coroutine.close, from fork 0.3.0; a __close cannot yield. The byte budget is the VM's per-call allocation limit (limits.totalAllocation on PyroeisVm), so a script's own pcall sees the standard not enough memory while the host still rejects the call. getmetatable("") returns false. Globals persist between calls on one host, so mutually untrusted scripts need a host each. Lua VM state is not save data: reload scripts from the game's entry point.

  • createPyroeisRuntime (the same optional mwl/pyroeis subpath) returns a PyroeisRuntime for games that need synchronous API responses, live state and resumable handlers. It keeps the smaller ScriptHost contract intact. defineFunction(path, callback) exposes a host function with arguments and a result, and get/set use dotted global paths made of identifiers. run executes text and returns its first result; call accepts a path or a PyroeisReference. reference(path) retains a Lua table or function's identity, including callbacks registered by Lua; dispose references when finished, or dispose the entire runtime. PyroeisValue includes plain values, arrays, objects, Maps, BigInts, binary strings as Uint8Arrays and owned references. Ordinary tables are copied on read; contiguous sequences become arrays. Bound tables retain their references even inside lists. Nil maps to null; assigning it removes a Lua table entry. Lua VM state and references are not JSON save data. createTable(PyroeisTableBinding) creates a live proxy: get and optional set run on ordinary indexed reads/writes, with optional keys for pairs and length for #. Nested bindings can return other proxy references, allowing a game to expose a side list, each side's resources, a variable namespace or an entity lookup. Its metatable is hidden; Lua rawget/rawset still bypass bindings, so callbacks must enforce game rules themselves. PyroeisRuntimeOptions.modules snapshots exact module IDs and embedded source strings. Lua require caches the first result with Lua identity; dofile reruns a source and returns all results. A game can alias game.require = require without copying a loader. Unknown IDs, cyclic loads and binary chunks are rejected. No filesystem, fetch or XHR is involved; io, os, debug, package, load and loadfile stay absent. Closing a suspended module load clears its loading marker. defineYieldingFunction returns request values to the host; a PyroeisCoroutine created by coroutine(pathOrReference) exposes status, resume(args) and close(). It can also adopt a thread created by Lua, including one already suspended by the script; each thread has one host controller. Each resume returns { done, values }, with scene answers supplied as the next resume's arguments. Close handlers run on explicit closure or runtime disposal; failed handlers retain their error until closure. Instruction and string/buffer allocation budgets cover compilation, modules, host-side indexing and coroutine resumes. Nested host calls share the current budget; a later top-level call/resume gets a fresh budget. Optional timeLimit bounds wall-clock time, including callbacks, but cannot preempt host JavaScript. Randomness is seeded; bounded math.random intervals require safe integers. Total JavaScript heap and some native operations remain outside these bounds.

  • luaToJs(source, { format?, header? }) (same subpath) translates Lua to readable JavaScript without running it and returns { code, warnings, exports, freeGlobals }. Metatables, coroutines, general goto and some patterns stay as TODO(lua2js) comments with a matching warning; invalid Lua throws LuaSyntaxError. Pyroeis's runtime numeric compile is not used: it is skipped whenever execution limits are on.

MwlRuntime exposes fireEvent(id) for named event execution. Event conditions compare numeric variables numerically, set_variable accepts the bounded MWL expression syntax, filters can match a unit id, unit_at can constrain a side, and both moveto events and unit filters take coordinates as comma-separated lists or inclusive ranges (x=1,2,4-5). A set_variable (either spelling, [set_variable] or [command] name="set_variable") may declare what its own value= means with mode=literal|number|expression: literal keeps the text exactly as written, number parses it and refuses anything else, expression evaluates it and treats a missing variable as an error. Without a mode the value is inferred from its shape ($name copies a variable, a finite number is a number, operator characters or a numeric variable's name evaluate), which is what hand-authored content relies on and what a compiler target cannot, since a literal such as Raise Walking Corpse (8 Gold) would be read as an expression. path= is that same write with a target built from variables (zombies[$index].allow_recruit, or $target for a variable holding a path), expanded before the path is walked; a reference that names nothing throws rather than leaving an empty segment. name=/target= stay literal (a $ there is not a reference today, so it is not read as one now), which keeps every existing write meaning exactly what it did. Top-level say commands execute normally. Dialogue choices are delivered in MwlMessage.choices and answered with answerDialogue; pending choices are included in save data. Commands after a dialogue in the same event run immediately, before the answer, so deferred follow-up commands belong in the selected choice event.

The WML action vocabulary (item 250) is on the same event surface. fire_event runs another event by id. store_unit writes matching units into a world variable, unstore_unit and recall write them back (recall can move one to a chosen hex and side), modify_unit changes what its [set] names and heal_unit adds amount (or sets hp). A unit carries its own name, role/function and can_recruit leader flag: [unit] sets them, a side's own leader is can_recruit, and unitMatchesFilter reads all three, so [filter] role=courier, name=Kalenz and can_recruit=yes select on them ([store_unit] and the save keep them too). set_terrain changes one map cell, capture_village records ownership in MwlWorld.villages, and clear_shroud records the hexes a side has uncovered in MwlWorld.clearedShroud; the fog itself stays a game layer. At scenario level, [role] fills MwlWorld.roles and stamps the role onto the units it matches, [object] lands in MwlWorld.objects, and [story] in MwlWorld.story as data (rendering a story screen is its own item), all kept in the save. [item] is deliberately not among them: the tag already means an inventory item definition here, so WML's map-placement shape would have collided with it.

Typical build-time usage:

npm run mwl -- build content/ -o generated/

The executable mwl-content example shows the full path: authored content, generated catalog and manifests, then a small game reading the result at runtime. A Wesnoth adapter can convert native .cfg files to the same MWL input model before invoking this build step.

mwl/pyroeis

The optional Lua 5.4 entry point, @datamoc/mwg/mwl/pyroeis, kept off the mwl barrel so the Pyroeis VM (the optional @datamoc/pyroeis dependency) loads only when a game imports it. The mwl section above describes its behaviour in full; the exports are:

  • createPyroeisScriptHost(options?) - a sandboxed ScriptHost (PyroeisScriptHostOptions: instructionLimit, memoryLimit, seed). Only the base, coroutine, math, string, table and utf8 libraries are opened, load is removed, math.random is seeded, and every call is bounded; globals persist per host.
  • createPyroeisRuntime(options?) - a PyroeisRuntime for synchronous host calls and live state: run, call, get/set on dotted paths, reference, defineFunction, defineYieldingFunction, createTable (live proxy tables), coroutine and dispose. Types: PyroeisValue, PyroeisReference, PyroeisCoroutine, PyroeisTableBinding, PyroeisRuntimeOptions.
  • luaToJs(source, options?) - translates Lua to readable JavaScript without running it (LuaToJsOptions/LuaToJsResult are re-exported).

ai

Renderer-free decision runners. The game owns perception, navigation, combat rules and goals; these modules provide the execution boundary, deterministic choice support, explicit actions, serialisable state, diagnostics and budgets.

  • NeuralPolicy over NeuralModel/DenseLayer: dependency-free dense inference, ReLU hidden layers and linear output scores, with flat row-major weights and an explicit observationVersion. Construction validates dimensions and finite values before copying the weights; limits are 32 layers, 4096 neurons per layer and one million parameters. predict(input, output?) reuses activation buffers and can write into a caller-owned Float64Array. exportModel() returns a plain-data copy suitable for bundling in a local-file game. selectAction(NeuralObservation, random?) masks illegal actions, chooses the first best score on ties and returns null when all actions are masked. A seeded random callback enables stable-softmax sampling. behavior(id, actions, observe, sample?) maps the same policy into JavaScriptAI, using its seeded random callback when sampling. predictBatchAsync(inputs, { signal?, timeout? }) runs a whole inference batch on one worker. The caller owns stale-result rejection if a scene or position changes while awaiting it. Tiny predictions are usually cheaper synchronously; measure batches before offloading them.

  • JavaScriptAI - registers named behaviours, checks them in declaration order, and returns a JSON-shaped action or an idle decision. A behaviour receives perception, mutable plain state, seeded random(), emit() and a cooperative checkpoint() for cancellation and step or wall-clock budgets. JavaScript cannot interrupt a synchronous function that never checks its checkpoint, so long-running behaviours must cooperate.

  • Suggester - the suggestion mode (roadmap 397): the same decision call a game makes for the AI, pointed at a hint UI instead of the world, throttled by a frame-count budget (every, never wall clock) so a hint does not tax the frame budget. The first update decides immediately, throttled updates return null while latest keeps the previous suggestion, an idle decision is a suggestion the UI reads (decision.action === null), and clear drops it. The decider must not mutate game state to compute a suggestion; what the player does with one is the game's.

  • alphaBetaSearch/AlphaBetaGame - deterministic minimax with alpha-beta pruning over a game-owned immutable-state adapter. The adapter supplies legal moves, transitions, terminal detection, current player and evaluation from the root player's perspective. depth, maxNodes, cancellation and node diagnostics bound the search; the same primitive works for a local actor and for a top-level controller such as a chess master. rootSplits/firstWins are the root-split halves of an off-thread search: the split pairs each root move with its child in game order, and first-wins reduces scored moves so ties keep the earlier move.

  • personalScoreView/sideScoreView/scoreWith over ScoreSubject/ScoreView/ ScorePersonality - the numbers a mind that weighs outcomes needs, for the case where a search is the wrong tool. The game owns what anything is worth (scoreOf), the framework owns how a view is assembled (own, allies and enemies kept apart, plus a seen count), and the mind owns what it cares about: a personality is weights, so a selfish scout and a loyal one are content rather than two AI implementations. Both scopes read through the same code and differ only in the visibility set they are handed, a unit's own sight or FactionFog.sees(side). ScoreSubject also carries an optional type, role/function, can_recruit leader flag and name, and subjectsWhere/ScoreSubjectFilter select a world on any of them, so a mind finds "the enemy leader" ({ side: 'red', can_recruit: true }) without re-deriving it from ids.

  • The heuristic AI (item 269): Aspects/AspectValues/AspectValue - the named tuning knobs (aggression, caution, keep_away, recruitment_pattern, ...) with typed readers and no built-in values, since the numbers are content; Difficulty/DifficultyLevel - named levels as aspect overrides on a base set; Goals/Goal/GoalKind - per-unit orders a stage's weigh reads; RecruitmentPattern - a side's recruit order, cycled, with a fallback. HeuristicAI runs candidate actions through HeuristicStages in order, the first whose when passes scoring every HeuristicCandidate and taking the best (earlier candidate on a tie); a candidate may carry the acting unit's own type/role/can_recruit/name for a custom weigh to read. defaultWeigh is each factor times the aspect of the same name with keepAwayScore for a candidate's distance; goalScore is what a custom weigh adds for a goal.

  • AIDecision/AIDecisionInput/AIAction - the shared contract for perception, explicit action objects, status (action, idle, cancelled, or budget-exceeded), emitted diagnostics and state snapshots.

  • AICancelledError/AIBudgetExceededError - the cooperative control-flow errors used by a JavaScript behaviour when it observes cancellation or exceeds its configured budget.

  • exportState/importState - versioned, JSON-shaped agent state. Function closures, VM state and arbitrary object graphs never become save data.

  • LuaAI/createLuaAI from @datamoc/mwg/ai/lua - optional Lua 5.4 provider with the same action and state envelope. A Lua function receives (perception, state) and returns an action table or { action, state, events }. It uses the existing optional Pyroeis host, which removes filesystem, process, module-loading, clock and debug access, supplies seeded random, and enforces an instruction budget.

  • AIAgentDefinition/AIBehavior - JavaScript registrations; Lua registrations instead provide a source chunk and an entry function name. Both remain game-owned content and do not include any reference game's code or data.

MWL [ai] profiles describe the boundary without embedding executable game rules: scope is actor or controller, provider is javascript or lua, algorithm can be rules or alpha_beta, and depth, max_nodes, player, moves, apply, terminal and evaluate identify search limits and game-owned operations. A game resolves those names to JavaScript behaviours or Lua functions and supplies the actual state, legal moves and evaluation.

Skeleton extensions (417-421)

  • skeleton.solveTwoBoneIK(skeleton, first, second, target, bend, pose) solves a connected two-bone chain in world coordinates. bend is +1 or -1; positive bends clockwise on screen. Positive finite lengths and a zero origin on the second bone are required. Unreachable targets throw with the chain names. Rest rotations and rotated ancestors are supported.
  • Bone.limits: { min, max } bounds the absolute local rotation in degrees, including rest rotation. skeleton.validatePose checks an authored pose; samplePose and sampleTransformPose accept an optional skeleton for validation. Mixers and resolve validate automatically. Use a nonnegative or nonpositive interval to constrain bend direction.
  • Keyframe.translations and Keyframe.scales map bone names to { x, y } channels. skeleton.sampleTransformPose and skeleton.advancePose return a TransformPose, with rotations, translations and scales. Missing channels interpolate toward zero translation or unit scale. Looping, reverse playback, holding, priority layers and crossfades share the rotation timeline. Legacy samplePose and advance return rotations only.
  • SkeletalSprite.apply accepts either rotation poses or TransformPose; its mixer uses advancePose automatically. setDiagnostics(true) explicitly enables bone lines, pivot crosses, joint circles and tips. Omit it in release builds; disabled rigs allocate no overlay.
  • assets.loadSvgParts(sourceOrPath, { resolution, groups }) returns borrowed textures keyed by top-level SVG group name. It preserves the full SVG canvas, group attributes, shared defs and styles. Repeated loads reuse textures; resolutions have separate cache entries. Compiled asset paths decode directly from data URIs under file://. Unknown groups and invalid resolutions throw by name. releaseSvgParts(parts) unloads them once no sprite uses them.
  • node tools/check-skeleton-extensions-browser.mjs [local-vehicle.svg] builds a classic local-file page, verifies WebGL rendering, texture reuse, resolution isolation and diagnostic cleanup, and writes screenshots under benchmark-results/skeleton-extensions/. The default vehicle is generated; passing a local consumer SVG embeds it only into ignored scratch output.

Deformation, articulated SVG loading and asset filtering (414-416)

  • PinnedDeform / DeformableSprite expose pinned control points. dragVertex, nudgeVertex and resetVertices change GPU vertex positions without changing UVs or rotating the sprite. dragVertices([{ index, x, y }, ...]) validates a batch before applying it and uploads once; the pure PinnedDeform.dragMany performs the same batch operation without a renderer.
  • loadSvgSkeleton(sourceOrPath, { skeleton, bindings?, pivots?, resolution?, mixer? }) returns { sprite, textures }. sprite is a SkeletalSprite with named SVG groups already bound. By default matching groups bind in SVG document order. Explicit bindings provide draw order, group-to-bone mapping and optional pivot/rest-angle overrides. Pivots come from data-pivot-x and data-pivot-y (root SVG user coordinates), or a pivots map keyed by group id. Missing pivots, groups, bones and duplicate bindings fail by name. Separately bound descendants are removed from parent textures; ancestor transforms, shared styles and defs survive. Artwork is normalized against each bone's rest angle so poses rotate the correct limbs about their pivots. Browser DOMParser/XMLSerializer are required. Compiled paths work under file://. Destroy the sprite with { children: true }, then call releaseSvgParts(textures) when all users are done.
  • mwgPage({ assetFiles: ['hero.svg', 'music/theme.ogg'] }) embeds only those asset-folder paths. Omit assetFiles to keep all supported assets; [] embeds none. Unknown or unsupported named entries fail before replacing compiled asset scripts. Both emitPage and compileResources accept the same option. credits.json generates CREDITS.txt when selected, or with no filter.
  • Browser checks: node tools/check-sprite-deform-browser.mjs [local-bird.svg] and node tools/check-svg-skeleton-browser.mjs [local-character.svg] [local-manifest.json] build local-file WebGL pages and save rest/posed screenshots under benchmark-results/. Defaults use generated art; consumer inputs remain in ignored scratch output only.