墨kazokuai.dev

kit 0.8.0, contract 1, Sumi pass 8 (2026-10-06). This is kit/KIT.src.md. kit/KIT.md is this text plus an API

Generated from the kit's types and kit/KIT.src.md, so it can't drift from the code; it is the AI's prompt for every build as well as this page. Download KIT.md.

The kit

Status: kit 0.8.0, contract 1, Sumi pass 8 (2026-10-06). This is kit/KIT.src.md. kit/KIT.md is this text plus an API section, a Scripting API section, a Scene data section and a Cast data section that scripts/kit-doc.mjs generates from kit/host-api's, kit/packs/shooter/api.ts's, kit/packs/scene/api.ts's and kit/engine's types and doc comments and the data in kit/packs; it also writes kit/packs/shooter/api.d.ts and kit/packs/scene/api.d.ts, the declarations a level's module is checked against. Edit this file, never KIT.md: a test fails when KIT.md or either api.d.ts is stale (brief R12). Pass 15 adds the 3D path section, generated from kit/engine3d and kit/host-api/rim.ts (D148–D154).

The method

Ink and light is silhouettes, outlines and light as events. Everything is a silhouette filled with ink, edged with a neon outline, and lit by the glow that outline throws. There are no textures, no sprites and no shading inside a shape — but one: a scene pack's backdrop, a picture the scene is drawn over, shown whole as it was drawn (below). Light is something that happens — outline bloom, trails, sparks, a hit's flash, a light that bends across a rock as it tumbles, a boss whose outline pulses with its health — and all the richness comes from it. Light is never visibility, except by one look option: a scene whose reveal is lantern shows its picture only inside a lantern's light. If a shape needs detail inside it, it gets a second silhouette, not a texture. Every entity is a signed-distance shape on one instanced quad: a circle, a capsule, a polygon of up to 8 points, or a polygon with one circle or capsule in union. The renderer evaluates the shape per pixel: ink inside, an outline at the edge, a glow beyond it. The outline's hue says what a thing is. The player wears the member's hue, enemy classes wear class hues, and nothing hostile wears the player's hue. Readable first: brighter is more dangerous or more valuable.

Two renderers

The kit has two: the 2D renderer (kit/engine, everything above and below this section) and, since pass 15, the 3D path (kit/engine3d, its own section at the end). A pack declares which one it uses, and a package carries only that one: a 2D package's bytes hold none of the 3D path, and the 3D path imports nothing of the 2D renderer but its pure arithmetic (the hue, the four curves). The method holds in both — ink, outlines in hues, light as events — and in 3D it is ink bodies with a fresnel rim in the character's hue, an outline, bloom from what glows, and props drawn as light (D149). The 3D path's budgets are its own (the local tier: a desktop at 1920 × 1080, D153); the ones below are the 2D renderer's.

Budgets (ink & light §3; a look never changes them)

What a package is

A package is a static bundle with a manifest, played by a host in a sandboxed iframe over the contract (spec/SPEC.md, contract 1). A package built with this kit:

The engine (kit/engine)

Packs

shooter (kit/packs/shooter): Kaos's

The rules are Kaos (game.ts): title → each level's waves → an asteroid field → its boss (three phases) → level clear, and after the last level "cleared"; or game over. It has lives, a score with a wave-clear multiplier, six powerups and bombs. step(dt, input) runs at 240 Hz and draw(batch, alpha, dt, palette) fills the frame. It is pure: no DOM.

A game is a project: its cast cards and one level script per level (the Scripting API below). The build bundles the pack's runtime (runtime.tsx: the canvas, the HUD, the title, pause, game-over, clear and cleared cards, the save) with the scripts; project.ts turns each script's defineLevel into the rules' level data, every id checked against the cast.

The rules' level data, which a script becomes:

interface Group { class: 'dart' | 'drone' | 'wall'; count: number; pattern: 'line' | 'v' | 'sine' | 'pincer'; delay: number }
type Wave = Group[];
interface Field { duration: number; density: number; sizes: [large, medium, small] }
interface Level { n: number; waves: Wave[]; field: Field; boss: 'l1' | 'l2' | 'l3' }

scene (kit/packs/scene): first person, point and click

A scene game is a project whose chapters are data, not scripts (D82): each chapter is its scenes — a backdrop with a portrait crop, a light, hotspots with what each verb does to them, exits and death cards — and the build writes the chapter's module (export default defineChapter({...})) from that data and bundles it with the pack's runtime (runtime.tsx). No model writes a scene chapter's code; a model may propose its data, which the kit's own chapterProblems holds to the rules below (the Scene data section is generated from them).

combat (kit/packs/combat): turn by turn, every move a light

Combat is data too (D91): an encounter is a node of a scene chapter beside its scenes — an exit or a go leads to it like a scene — with its foes, its backdrop (the room's, or a picture of its own), the intro the log opens with, a playlist, whether the party may flee, what a win does (effects; a go takes the party on) and the death card a lose shows. A card brings its four numbers (the Stats tab: HP · ATK · DEF · speed) and its moves to a fight; an enemy or a boss also brings its weights (how often it picks each move) and a taunt (one of its barks, said on its first turn). No model writes a fight's code; Build proposes data — moves for the cards that lack them, the foes' weights, the intro and the lose card's words — which lands drafted. The Combat data section is generated from the rules below, and rules.json (printed there) holds the constants.

Kaos

Kaos is no longer a folder in the kit (Sumi pass 6): it is a Sumi project, the house's example — its cast as cards, its three levels as scripts against this API (server/examples/kaos), built by the same bundler as any project. The built-in Kaos package is its release build.

Not in the kit

API (generated)

Generated by scripts/kit-doc.mjs from kit/host-api/index.ts, kit/host-api/theme.ts, kit/engine/state.ts: the game's side of the contract, which every package bundles, and the world state its save carries. Import them as import { host, checkpoint } from '<kit>/host-api' and import { load, setFlag } from '<kit>/engine/state'. The host's listener is live from the moment the bundle runs.

CONTRACT (const)

The contract this kit speaks. A host says which contract it speaks in hello; the kit expects 1.

const CONTRACT = 1;

SAVE_MAX (const)

The most a save may be: 65,536 bytes of UTF-8 (SPEC §4). A bigger save is not sent.

const SAVE_MAX = 65536;

LABEL_MAX (const)

The most a score's label may be: 24 characters (SPEC §4). A longer one is cut.

const LABEL_MAX = 24;

SAVE_DEBOUNCE_MS (const)

How long a world state waits before it is sent: the last one in a second goes.

const SAVE_DEBOUNCE_MS = 1000;

Mode (type)

The host's theme mode.

type Mode = 'dark' | 'light';

ThemeTokens (interface)

The ten theme tokens, all always present, as CSS values (SPEC §4, the Theme).

interface ThemeTokens {
  /** The page. */
  bg: string;
  /** A card on the page. */
  bg2: string;
  /** A divider. */
  line: string;
  /** Text. */
  fg: string;
  /** Secondary text. */
  dim: string;
  /** The host's accent. */
  accent: string;
  /** The sans font stack. A package has only the fonts it ships. */
  sans: string;
  /** The mono font stack. */
  mono: string;
  /** The lightness every member hue is drawn at in this mode, e.g. "76%". */
  hueL: string;
  /** The chroma every member hue is drawn at in this mode, e.g. "0.15". */
  hueC: string;
}

Theme (interface)

The host's theme: for the package's chrome (its HUD, menus, cards). The world is the game's own.

interface Theme {
  mode: Mode;
  tokens: ThemeTokens;
}

Aspect (type)

A shape the host gives the game: taller than wide, or wider than tall.

type Aspect = 'portrait' | 'wide';

InputKind (type)

What the game can be played with on this device.

type InputKind = 'touch' | 'keys' | 'pad';

Member (interface)

The player, as the host tells it: a hue (0–359) and a display name. The member's id never crosses.

interface Member {
  hue: number;
  name: string;
}

Hello (interface)

The host's first message, once, after the frame loads.

interface Hello {
  /** The contract the host speaks. */
  contract: number;
  theme: Theme;
  member: Member;
  /** The shape the host gives the game now. */
  aspect: Aspect;
  /** The manifest's inputs the host offers on this device. */
  inputs: InputKind[];
  /** The member's last save for this package, or null. */
  save: string | null;
  /** The host's sound is off at the start. */
  muted: boolean;
}

HostEvents (interface)

What the host can tell the game, by event.

interface HostEvents {
  /** The first message: the theme, the member, the aspect, the inputs, the save, the mute. */
  hello: Hello;
  /** The host's theme changed. */
  theme: Theme;
  /** The host changed the shape it gives the game. */
  aspect: Aspect;
  /** The game is out of sight or under the host's UI: stop time and sound. */
  pause: undefined;
  /** Back: carry on from where pause stopped. */
  resume: undefined;
  /** The host's sound went off (true) or on (false). */
  mute: boolean;
}

Host (interface)

The game's side of the contract.

interface Host {
  /** The hello, once it has come (null before). */
  readonly hello: Hello | null;
  /** The theme now: hello's, then each theme message's. */
  readonly theme: Theme | null;
  /** The host's mute now. */
  readonly muted: boolean;
  /**
   * Listen for one of the host's messages; returns a function that stops listening. A hello that has already come is
   * handed to a late `hello` listener at once, so a game can subscribe after the bundle has started.
   */
  on<K extends keyof HostEvents>(type: K, fn: (value: HostEvents[K]) => void): () => void;
  /** The game has taken hello in and can be shown. Sent once; before hello it does nothing. */
  ready(): boolean;
  /**
   * Keep the game's state. A world state (engine/state) is serialized and sent a second after the last call (the
   * debounce), or at once before a pause or an exit. A string is the game's own blob, sent at once (debounce it
   * yourself: at a checkpoint, never every frame). Only after ready and only when it is at most SAVE_MAX bytes as
   * UTF-8; false when it won't be sent.
   */
  save(state: WorldState | string): boolean;
  /** Save a world state now, with no debounce: the packs call it at their checkpoints (a scene, a level, a fight). */
  checkpoint(state: WorldState): boolean;
  /**
   * The member's last save, as hello handed it (null when there is none): the listener is called once, at hello, or at
   * once when hello has already come. Read it with engine/state's load().
   */
  onSave(fn: (blob: string | null) => void): () => void;
  /**
   * A run ended: its score, a whole number ≥ 0, and an optional short label ("Level 3", cut to LABEL_MAX). Sent only
   * after ready; false when it wasn't (not a whole number, below 0, or too soon).
   */
  score(value: number, label?: string): boolean;
  /** Ask the host to play a playlist by name, or (null) to stop the music. Sent only after ready. */
  music(playlist: string | null): boolean;
  /** The player left the game: the host closes it. Sent any time after hello. */
  exit(): boolean;
}

parseTheme (function)

A Theme as SPEC §4 says it is, or null.

function parseTheme(v: unknown): Theme | null;

parseHello (function)

A hello as SPEC §4 says it is, or null.

function parseHello(d: Record<string, unknown>): Hello | null;

HostWindow (interface)

The window a host-api lives in, as far as it uses one (tests hand in a fake).

interface HostWindow {
  readonly parent: unknown;
  addEventListener(type: 'message', fn: (e: { source: unknown; data: unknown }) => void): void;
}

createHost (function)

Make the game's side of the contract on a window. Packages use the ready-made host below; this exists for tests and for a page that hosts itself.

function createHost(win: HostWindow, opts: { post?: (msg: object) => void; root?: HTMLElement | null; log?: (msg: string) => void } = {}): Host;

host (const)

The package's host. Importing the kit starts listening at once, so the hello the host sends at the frame's load event is never missed. Outside a frame (a page opened on its own) it waits for a hello that never comes.

const host: Host;

checkpoint (const)

Save a world state now (the packs call it at their checkpoints): host.checkpoint on the package's host.

const checkpoint = (state: WorldState): boolean => host.checkpoint(state);

THEME_VARS (const)

The CSS variables the shim writes, by Theme token. --hue is the member's colour in the host's mode.

const THEME_VARS = {
  bg: '--bg',
  bg2: '--bg2',
  line: '--line',
  fg: '--fg',
  dim: '--dim',
  accent: '--accent',
  sans: '--sans',
  mono: '--mono',
  hueL: '--hue-l',
  hueC: '--hue-c',
} as const;

memberColor (function)

The member's colour in this theme, drawn as the host draws it (the theme's hueL and hueC); null if they don't parse.

function memberColor(theme: Theme, hue: number): string | null;

applyTheme (function)

Write a Theme onto root (the documentElement): every token as its variable, data-theme as the mode, and, given the member's hue, --hue as their colour in this mode.

function applyTheme(theme: Theme, root: HTMLElement, hue?: number): void;

STATE_MAX (const)

The most the serialized state may be: 60 KB of UTF-8, under the contract's 64 KB save (SPEC §4).

const STATE_MAX = 60 * 1024;

STATE_WARN (const)

The size warnIfLarge() warns at: three quarters of STATE_MAX.

const STATE_WARN = 45 * 1024;

STATE_FORMAT (const)

The blob's own format, so the shape itself can change later.

const STATE_FORMAT = 1;

FlagValue (type)

A flag's value.

type FlagValue = boolean | number | string;

Json (type)

Any JSON value (a pack's custom object holds these).

type Json = null | boolean | number | string | Json[] | { [k: string]: Json };

PartyMember (interface)

One member of the party: an id (a cast card's), hit points and stats (ATK, DEF, speed, …).

interface PartyMember {
  id: string;
  hp: number;
  stats: Record<string, number>;
  /** Fields a newer kit wrote that this one doesn't know, kept as they were. */
  keep?: Record<string, unknown>;
}

Location (interface)

Where the player is: a level (shooter, overhead) or a scene (scene pack), and a room within it.

interface Location {
  level?: number;
  scene?: string;
  room?: string;
  keep?: Record<string, unknown>;
}

WorldState (interface)

The world state: what the scripts read, what Story shows as "what the game knows", what the save carries.

interface WorldState {
  /** The version of the package that wrote it (the manifest's version). */
  version: string;
  flags: Record<string, FlagValue>;
  inventory: string[];
  party: PartyMember[];
  location: Location;
  /** A small open object for a pack's own state. */
  custom: Record<string, Json>;
  /** Fields a newer kit wrote that this one doesn't know, kept as they were. */
  keep?: Record<string, unknown>;
}

StateTooLarge (class)

The state would be over STATE_MAX: the change is refused and the state is unchanged.

class StateTooLarge extends Error {
  constructor(readonly bytes: number);
}

createState (function)

A fresh state for a package version.

function createState(version: string): WorldState;

serialize (function)

The state as the save's blob: short keys, no whitespace. Throws StateTooLarge over STATE_MAX.

function serialize(s: WorldState): string;

sizeOf (function)

The serialized size in bytes, whatever it is (no guard).

function sizeOf(s: WorldState): number;

load (function)

Read a save's blob into a state, migrating forward. null, empty, or anything that isn't a world state gives a fresh one (at opts.version, else "0.0.0"); a field this kit doesn't know is kept, a missing one defaulted, renames applied.

function load(blob: string | null, opts: LoadOptions = {}): WorldState;

writtenBy (function)

The version a blob says wrote it, or null for a blob that isn't a world state.

function writtenBy(blob: string | null): string | null;

change (function)

Change the state through fn, all or nothing: when the result would serialize past STATE_MAX, StateTooLarge is thrown and the state is exactly as it was.

function change(s: WorldState, fn: (draft: WorldState) => void): WorldState;

setFlag (const)

Set a flag (refused past STATE_MAX).

const setFlag = (s: WorldState, name: string, value: FlagValue) => change(s, (d) => void (d.flags[name] = value));

clearFlag (const)

Clear a flag.

const clearFlag = (s: WorldState, name: string) => change(s, (d) => void delete d.flags[name]);

addItem (const)

Add an item, once (refused past STATE_MAX).

const addItem = (s: WorldState, item: string) => change(s, (d) => void (d.inventory.includes(item) || d.inventory.push(item)));

removeItem (const)

Take an item out.

const removeItem = (s: WorldState, item: string) => change(s, (d) => void (d.inventory = d.inventory.filter((x) => x !== item)));

setLocation (const)

Move the player.

const setLocation = (s: WorldState, at: Location) => change(s, (d) => void (d.location = { ...at, ...(d.location.keep ? { keep: d.location.keep } : {}) }));

warnIfLarge (function)

The build's check (R47): a warning line when the state, as given, serializes to more than STATE_WARN bytes, or null. The build calls it with the largest state a project's sheets allow (every flag set to its longest value).

function warnIfLarge(s: WorldState): string | null;

Scripting API (generated)

Generated by scripts/kit-doc.mjs from kit/packs/shooter/api.ts; its declarations are kit/packs/shooter/api.d.ts. A level script is one TypeScript module that imports only from '@sumi/kit' (this API: any other import is a build error) and exports default defineLevel({...}). It names its cast by the cards' ids, which the build declares, so a wrong id or the wrong kind of card is a type error. A card's behaviour (how it moves, what it fires, its hitbox) is the pack's, chosen on the card: a script places and times things and never defines a behaviour. Hooks see the world state (ctx.state, the kit's state module) and may set flags and items, add a group now, drop an item now and show a line.

Pattern (type)

How a group comes in. line: across the width at once; v: a V, apex first; sine: one after another down the middle, each a step along a sine; pincer: half from each side, alternating, closing in from the upper edges. x positions are shares of the field's width (wide fields are wider, never taller); heights and times are the same at every width.

type Pattern = 'line' | 'v' | 'sine' | 'pincer';

PATTERNS (const)

The patterns, in order.

const PATTERNS: readonly Pattern[];

ProjectCast (interface)

The project's cards by id and kind. The build declares them (declare module '@sumi/kit' { interface ProjectCast {…} }), so a wrong id is a type error.

interface ProjectCast {}

EnemyId (type)

An enemy card's id: its behaviour (dart, drone or wall) and its numbers are the card's.

type EnemyId = IdsOf<'enemy'>;

BossId (type)

A boss card's id: its behaviour (boss-core, boss-blades or boss-crown) is the card's.

type BossId = IdsOf<'boss'>;

ItemId (type)

An item card's id: its behaviour is one of the six powerups.

type ItemId = IdsOf<'item'>;

Group (interface)

A group of one enemy card.

interface Group {
  cast: EnemyId;
  /** How many, for a field 390 wide (1–40; a wider field gets × (W / 390)^0.7). */
  count: number;
  pattern: Pattern;
  /** Seconds after the wave starts (0–60). */
  delay: number;
}

GroupOptions (interface)

When a group comes in, after its wave starts.

interface GroupOptions {
  /** Seconds after the wave starts (default 0). */
  at?: number;
}

Wave (interface)

A wave: its groups, which come in at their delays. The next wave starts 1.6 s after every enemy of this one is gone (destroyed or off the field).

interface Wave {
  groups: Group[];
  /** What the wave is for, in a line (the sheet's note; the game never shows it). */
  note?: string;
}

Field (interface)

The asteroid field after the waves: rocks for seconds, density a second (× the level's rock density and the field's width), large / medium / small in the shares sizes (summing to 1). A large rock splits into two medium, a medium into two small.

interface Field {
  seconds: number;
  density: number;
  sizes: [number, number, number];
}

Boss (interface)

The level's boss: its card, and a name for each of its three phases (at 100%, 60% and 30% of its health; a crown splits in two at its card's split share). The names label the frame grid and the playtest notes.

interface Boss {
  cast: BossId;
  phases: string[];
}

Dials (interface)

The level's speeds over its cards' own numbers (each 0.25–4). None: the pack's curve for level n, enemy speed 1 + 0.15(n − 1), shot speed 1 + 0.1(n − 1), rock density 1 + 0.2(n − 1).

interface Dials {
  enemySpeed?: number;
  shotSpeed?: number;
  rockDensity?: number;
}

World (interface)

The world state as a hook reads it: the kit's state module's (KIT.md, engine/state.ts), saved at each level's clear.

interface World {
  /** The version of the package that wrote it. */
  readonly version: string;
  readonly flags: Readonly<Record<string, boolean | number | string>>;
  /** Item ids. */
  readonly inventory: readonly string[];
  readonly location: { readonly level?: number; readonly scene?: string; readonly room?: string };
}

LevelContext (interface)

What a hook can do: read and change the world state (saved at each level's clear), add a group now, drop an item now, and show a line at the foot of the frame. A change past the state's 60 KB is refused (it throws).

interface LevelContext {
  /** The level's number in the project. */
  readonly level: number;
  /** The current wave's index, 0-based. */
  readonly wave: number;
  /** The world state, read-only here: change it with the calls below. */
  readonly state: World;
  setFlag(name: string, value: boolean | number | string): void;
  getFlag(name: string): boolean | number | string | undefined;
  addItem(id: string): void;
  hasItem(id: string): boolean;
  /** A group, now: its members come in as its pattern places them, from this moment, as part of the current wave. */
  spawn(group: Group): void;
  /** An item card's powerup, dropped now at the share `x` (0–1) of the field's width, near the top. */
  pickup(item: ItemId, x?: number): void;
  /** A line at the foot of the frame for a few seconds. */
  toast(text: string): void;
}

LevelDef (interface)

A level, as its script defines it.

interface LevelDef {
  /** The level's title (the sheet's). */
  title?: string;
  /** The waves, in order (1–12). */
  waves: Wave[];
  /** The asteroid field after the waves; null or none: none, straight to the boss. */
  field?: Field | null;
  /** The boss; null or none: the level clears once the waves (and the field) are done. */
  boss?: Boss | null;
  /** What drops, in order, round and round, counted over the whole run: walls drop one when they split, a boss one at
   * each new phase (and at level 3's split). None: the project's item cards, in their order. */
  pickups?: ItemId[];
  /** The level's item: the one its sheet teaches (it should be in `pickups`). */
  item?: ItemId | null;
  /** The playlist the host plays under this level (none: the game's). */
  music?: string | null;
  dials?: Dials;
  /** When the level starts, before its first wave. */
  onStart?(ctx: LevelContext): void;
  /** When a wave starts (0-based). */
  onWave?(ctx: LevelContext, wave: number): void;
  /** When the boss enters a new phase (2 or 3), with that phase's name. */
  onBossPhase?(ctx: LevelContext, phase: number, name: string): void;
  /** When the level is clear, before the clear card (the world state is saved just after). */
  onClear?(ctx: LevelContext): void;
}

LevelModule (interface)

What defineLevel returns: the module's default export.

interface LevelModule {
  readonly kind: 'shooter-level';
  readonly def: LevelDef;
}

LevelError (class)

A level script that can't be played: each problem names where it is ("waves.1.groups.0.count: 1–40").

class LevelError extends Error {
  constructor(readonly problems: string[]);
}

levelProblems (function)

What's wrong with a level's definition (none: it can be played). The ids are checked against the cast when the game starts.

function levelProblems(def: LevelDef): string[];

defineLevel (function)

A level: the module's default export (export default defineLevel({...})). Throws LevelError when it can't be played.

function defineLevel(def: LevelDef): LevelModule;

wave (function)

A wave of these groups.

function wave(...groups: Group[]): Wave;

group (function)

A group: count of the enemy card cast, placed by pattern, at seconds into its wave.

function group(cast: EnemyId, count: number, pattern: Pattern, opts: GroupOptions = {}): Group;

line (const)

A line of count across the width, at once.

const line = (cast: EnemyId, count: number, opts?: GroupOptions): Group => group(cast, count, 'line', opts);

v (const)

A V of count, apex in the middle and first.

const v = (cast: EnemyId, count: number, opts?: GroupOptions): Group => group(cast, count, 'v', opts);

sine (const)

count one after another down the middle, 0.45 s apart, each further along a sine.

const sine = (cast: EnemyId, count: number, opts?: GroupOptions): Group => group(cast, count, 'sine', opts);

pincer (const)

count from both sides, alternating, 0.28 s apart, closing in from the upper edges.

const pincer = (cast: EnemyId, count: number, opts?: GroupOptions): Group => group(cast, count, 'pincer', opts);

field (function)

The asteroid field: seconds long, density rocks a second, the shares of large, medium and small.

function field(seconds: number, density = 1.1, sizes: [number, number, number] = [0.4, 0.35, 0.25]): Field;

boss (function)

The boss card cast, its phases named.

function boss(cast: BossId, ...phases: string[]): Boss;

pickups (function)

The drop order: these item cards, round and round.

function pickups(...items: ItemId[]): ItemId[];

Scene data (generated)

Generated by scripts/kit-doc.mjs from kit/packs/scene/api.ts; its declarations are kit/packs/scene/api.d.ts. A scene chapter is this data (D82): the build writes its module, export default defineChapter({...}), importing only '@sumi/kit' (this API), and the game boots it through chapterProblems, the rules below. A point is in the wide backdrop's unit coordinates (1600 × 900); items and cards are the cast's ids; scene ids are the project's, one chapter's each.

VERBS (const)

The seven verbs, in the row's order (R22). No parser: a verb, then the thing.

const VERBS = ['look', 'take', 'use', 'open', 'go', 'talk', 'hit'] as const;

Verb (type)

A verb.

type Verb = (typeof VERBS)[number];

FlagValue (type)

A flag's value (the world state's).

type FlagValue = boolean | number | string;

Pt (type)

A point in unit coordinates of the wide backdrop: [0, 0] its top-left, [1, 1] its bottom-right (1600 × 900).

type Pt = [number, number];

BACKDROP (const)

The backdrop's size: every scene's one image is 1600 × 900 (R49); a hotspot's points and the crop are shares of it.

const BACKDROP = { w: 1600, h: 900 } as const;

Lit (type)

How a scene's backdrop is revealed — a look option, the maker's (pass 13, D132): full, the whole picture as drawn (the default); lantern, only inside a flickering light at the scene's lantern point, ink outside it. Light is never visibility otherwise: a light that follows the pointer is gone, and an effect's light is an event (light sets this option for a scene).

type Lit = 'full' | 'lantern';

LITS (const)

The reveals, the default first.

const LITS: readonly Lit[];

asLit (const)

A reveal as an older Sumi wrote it: before pass 13 a scene was lit (now full) or followed the pointer (cursor, gone: full). Anything but lantern is full.

const asLit = (v: unknown): Lit => (v === 'lantern' ? 'lantern' : 'full');

When (interface)

A condition: every field given must hold. flag with is (default true; is: false also holds when the flag was never set), has an item in the inventory — for Use, the item in hand — and lacks an item not in it.

interface When {
  flag?: string;
  is?: FlagValue;
  has?: string;
  lacks?: string;
}

STATS (const)

The party's numbers a stat effect changes (D92: no XP in v1 — a reward is an item or a stat): hp heals or hurts (never below 1 outside a fight, never past hp_max), hp_max raises or lowers the most HP (and the HP with it), atk, def and speed the card's own numbers.

const STATS = ['hp', 'hp_max', 'atk', 'def', 'speed'] as const;

Stat (type)

A party number.

type Stat = (typeof STATS)[number];

Effect (type)

What a response does, in order: say a line, give or remove an item (an item card's id), set a flag, go to a scene or an encounter, die with a death card, light — an event — sets a scene's reveal (this one's when scene is left out), and stat: the party's stat by by (±1–99).

type Effect =
  | { do: 'say'; text: string }
  | { do: 'give'; item: string }
  | { do: 'remove'; item: string }
  | { do: 'set'; flag: string; value: FlagValue }
  | { do: 'go'; scene: string }
  | { do: 'die'; card: string }
  | { do: 'light'; lit: Lit; scene?: string }
  | { do: 'stat'; stat: Stat; by: number };

EFFECTS (const)

The effects, by name.

const EFFECTS = ['say', 'give', 'remove', 'set', 'go', 'die', 'light', 'stat'] as const;

Response (interface)

One answer to a verb: shown when its when holds — the first that holds answers — with its text, then its effects.

interface Response {
  when?: When;
  text: string;
  effects: Effect[];
}

Hotspot (interface)

A thing in a scene: a polygon of 3 to 8 points over the backdrop, a name, and what each verb does to it. A verb with no response that holds gets the pack's default line (the player card's barks when it has any, else the pack's table). card: the cast card it is (an enemy to Talk to), drawn in its hue when lit.

interface Hotspot {
  id: string;
  name: string;
  points: Pt[];
  card?: string | null;
  responses: Partial<Record<Verb, Response[]>>;
}

Edge (type)

An edge of the frame an exit can leave by.

type Edge = 'left' | 'right' | 'up' | 'down';

EDGES (const)

The edges.

const EDGES: readonly Edge[];

Exit (interface)

A way out: Go on its hotspot (via a hotspot's id) or its edge (via an edge) takes the player to a scene or an encounter, when its when holds. An exit is tried before the hotspot's Go responses; the first that holds is taken.

interface Exit {
  to: string;
  via: string;
  when?: When;
}

DeathCard (interface)

A death: its card's text over ink, and Try again (back to where the scene was entered).

interface DeathCard {
  id: string;
  text: string;
}

Crop (interface)

The portrait crop (R49): a 9:16 rectangle of the wide backdrop, in its unit coordinates, that a portrait screen shows.

interface Crop {
  x: number;
  y: number;
  w: number;
  h: number;
}

Scene (interface)

A scene: its backdrop (an image id, or null before there is one), the portrait crop, its reveal (full unless the maker chose lantern) and the lantern's radius (in backdrop pixels) and point, the playlist under it, what happens when it's entered, its hotspots, exits and death cards.

interface Scene {
  id: string;
  title: string;
  backdrop: string | null;
  crop: Crop;
  lit: Lit;
  light_radius: number;
  lantern: Pt | null;
  music: string | null;
  on_enter: Effect[];
  hotspots: Hotspot[];
  exits: Exit[];
  death_cards: DeathCard[];
}

EncounterBackdrop (type)

An encounter's backdrop (R24, R49): a scene's — the room it happens in, by the scene's id — or a picture of its own, by an image id (shipped as scenes/<encounter id>.webp).

type EncounterBackdrop = { scene: string } | { image: string };

Foe (interface)

A foe in an encounter: an enemy or a boss card, and how many of it (more than one fan out on the field).

interface Foe {
  cast_id: string;
  count: number;
}

Encounter (interface)

An encounter (the combat pack, D91): a node of the chapter, reached by an exit or a go like a scene. Its backdrop, the foes, the intro the log opens with, its playlist, whether the party may flee (back to the scene it came from, HP as it stands), what a win does (effects; a go takes the party on, else back to the scene it came from), and the death card a lose shows (one of the chapter's: Try again goes back to the moment before the encounter, HP as it was).

interface Encounter {
  id: string;
  title: string;
  backdrop: EncounterBackdrop;
  enemies: Foe[];
  intro: string;
  music: string | null;
  flee: boolean;
  win: Effect[];
  lose: string;
}

Chapter (interface)

A scene chapter: its number and title, its scenes, the one the player enters first, and its encounters.

interface Chapter {
  n: number;
  title: string;
  start: string;
  scenes: Scene[];
  encounters?: Encounter[];
}

ChapterModule (interface)

What a chapter's module exports: export default defineChapter({...}).

interface ChapterModule {
  kind: 'scene-chapter';
  chapter: Chapter;
}

ProjectCast (interface)

The project's cards by id and kind. The build declares them (declare module '@sumi/kit' { interface ProjectCast {…} }); a chapter's items and cards are checked against the cast when the game starts.

interface ProjectCast {}

defineChapter (function)

A chapter's module (the build writes it from the chapter's data).

function defineChapter(chapter: Chapter): ChapterModule;

LIMITS (const)

The limits a chapter is held to.

const LIMITS = {
  scenes: 40,
  hotspots: 24,
  points: 8,
  exits: 12,
  deathCards: 8,
  responses: 6,
  effects: 8,
  text: 600,
  title: 60,
  radius: [60, 900],
  encounters: 12,
  foes: 4,
  stat: 99,
} as const;

ID (const)

An id: a scene's, a hotspot's, a death card's — lower case, a letter first, up to 32.

const ID = /^[a-z][a-z0-9_-]{0,31}$/;

FLAG (const)

A flag's name (the Lines tab's rule).

const FLAG = /^[a-z][a-z0-9_]{0,31}$/;

DEFAULT_CROP (const)

The crop when the maker hasn't set one: the centre 9:16 slice of the wide image, its full height.

const DEFAULT_CROP: Crop;

cropAspectOk (function)

The crop's shape: 9:16 in backdrop pixels, within 1%.

function cropAspectOk(c: Crop): boolean;

fitCrop (function)

A crop moved and sized to fit: 9:16, inside the image, at least a quarter of its height.

function fitCrop(c: Crop): Crop;

inPolygon (function)

The point is inside the polygon (even-odd).

function inPolygon(p: Pt, poly: readonly Pt[]): boolean;

centreOf (function)

A polygon's centre (the mean of its points).

function centreOf(poly: readonly Pt[]): Pt;

outsideCrop (function)

A hotspot lies wholly outside the crop: no point of it inside, and the crop's centre not inside it — a portrait screen never shows it (the validator warns, and fails a portrait-only game).

function outsideCrop(points: readonly Pt[], c: Crop): boolean;

ChapterContext (interface)

What a chapter may name outside itself: the cast (an item, a card) and the other chapters' scenes and encounters.

interface ChapterContext {
  cast?: readonly { id: string; kind: string }[];
  /** scene ids of the project's other chapters (an exit or a go may cross into one) */
  scenes?: readonly string[];
  /** encounter ids of the project's other chapters (an exit or a go may lead to one) */
  encounters?: readonly string[];
}

encounterIn (function)

The encounter by its id, from any of these chapters, or null.

function encounterIn(chapters: readonly Chapter[], id: string): Encounter | null;

chapterProblems (function)

Why a chapter's data isn't one the pack can play, as lines ("scenes.1.hotspots.0.points: 3 to 8 points"); none: it is. The shape (every field, its limits, no unknown field), the ids (unique in the chapter, the exits' and effects' targets there), the crop (9:16 inside the image) and the cast it names. A backdrop not made yet is no problem here: the validator says so.

function chapterProblems(v: unknown, ctx: ChapterContext = {}): string[];

Combat data (generated)

Generated by scripts/kit-doc.mjs from kit/packs/combat/api.ts (its declarations are kit/packs/combat/api.d.ts) and kit/packs/combat/rules.json, printed as it is. A card's moves, weights and taunt are this data, on its Stats tab beside its four numbers; an encounter is the Scene data's Encounter. The fight's rules read rules.json (D94): the hit's terms and its least, Guard's share, when a foe heals, the order's ties, simulate's player. Every move is a light (MoveLight), drawn in the mover's hue.

MOVE_KINDS (const)

What a move does: attack hits one foe; guard halves the next hit the mover takes; heal gives the mover back power HP (an enemy heals only when under half); item spends its cost item and heals power; flee leaves the fight (the player: back to the scene before it, if the encounter allows; an enemy: off the field).

const MOVE_KINDS = ['attack', 'guard', 'heal', 'item', 'flee'] as const;

MoveKind (type)

A move's kind.

type MoveKind = (typeof MOVE_KINDS)[number];

LIGHT_KINDS (const)

How a move is drawn (D93: every move is a light, in the mover's hue): arc, a light that flies from the mover to the target; burst, a flash at the target; ring, rings round the mover; none, only the outline's flash on a hit.

const LIGHT_KINDS = ['arc', 'burst', 'ring', 'none'] as const;

MoveLight (type)

A move's light.

type MoveLight = (typeof LIGHT_KINDS)[number];

MoveCost (interface)

What a move costs (D101): the item card it needs carried, and whether playing it spends the item (spend: true: the item leaves the inventory when the move plays — a last arrow, a torch that burns out; false: it only has to be carried — the torch enables the Flare). An item move always has a cost.

interface MoveCost {
  item: string;
  spend: boolean;
}

Move (interface)

One move on a card's Stats tab. cost: the item it needs and whether it spends it (null: none) — a move with a cost is in the menu only while its item is carried. power: an attack's own share of the hit, a heal's HP. note: the log's words when it plays ("the Lantern-eater recoils from the light").

interface Move {
  id: string;
  name: string;
  kind: MoveKind;
  cost: MoveCost | null;
  light: MoveLight;
  power: number;
  note: string;
}

Weight (interface)

How often an enemy or a boss picks a move: its id and a weight (the chance is the weight over the sum of the weights of the moves it may pick now). A move with no weight, or weight 0, is never picked.

interface Weight {
  move: string;
  weight: number;
}

CombatStats (interface)

A card's four numbers (the Stats tab): HP, attack, defence and speed (the turn order: the fastest first).

interface CombatStats {
  hp: number;
  atk: number;
  def: number;
  speed: number;
}

CombatCard (interface)

A card as a fight reads it: the cast card's id, kind and name, its numbers, its moves and (an enemy's or a boss's) weights, and its taunt — the id of one of its Lines of kind bark, shown in the log on its first turn.

interface CombatCard {
  id: string;
  kind: 'player' | 'enemy' | 'boss' | 'item';
  name: string;
  stats?: CombatStats;
  moves?: Move[];
  weights?: Weight[];
  taunt?: string | null;
  lines?: { id?: string; kind: string; text: string }[];
}

COMBAT_LIMITS (const)

The limits a card's combat data is held to.

const COMBAT_LIMITS = {
  moves: 8,
  power: [0, 99],
  weight: [0, 99],
  name: 30,
  note: 120,
} as const;

MOVE_ID (const)

A move's id: lower case, a letter first, up to 24.

const MOVE_ID = /^[a-z][a-z0-9_-]{0,23}$/;

combatProblems (function)

Why a card's combat data — its moves, weights and taunt — isn't one the pack can fight with, as lines ("moves.1.cost: no card torch in the cast"); none: it is. The shape (every field, its limits, no unknown field), the ids (unique on the card), a cost that is an item card, an item move that has one, weights that name the card's moves, and a taunt that is one of the card's barks. items: the cast's item cards' ids (left out: a cost isn't checked).

function combatProblems(card: Pick<CombatCard, 'moves' | 'weights' | 'taunt' | 'lines'>, ctx: { items?: readonly string[] } = {}): string[];

weightOf (function)

The weight a card gives a move (0 when none).

function weightOf(card: Pick<CombatCard, 'weights'>, move: string): number;

fightProblem (function)

Why a card can't take its side in a fight, or null: a foe (an enemy or a boss) needs its numbers and at least one attack move with a weight; the player needs its numbers and at least one attack move.

function fightProblem(card: CombatCard, side: 'party' | 'foe'): string | null;

kit/packs/combat/rules.json

{
  "note": "The combat pack's constants (DESIGN.md D94): a later ruling tunes them here, without code. kit/packs/combat/rules.ts is the one place they are read.",
  "damage": {
    "note": "A hit is the sum of each term times its weight, then at least min: max(min, power·power + atk·atk + def·def). With these weights, max(1, power + ATK − DEF).",
    "power": 1,
    "atk": 1,
    "def": -1,
    "min": 1
  },
  "guard": {
    "note": "Guard: the guarder's next hit taken is this share of itself, rounded down, never below damage.min; it lasts until that hit.",
    "factor": 0.5
  },
  "heal": {
    "note": "An enemy's heal move is in its choice only under this share of its HP; a heal never goes past the HP it started with.",
    "enemy_below": 0.5
  },
  "order": {
    "note": "Turn order: speed, the fastest first; on a tie the party goes first, then the encounter's order.",
    "ties": "party_first"
  },
  "greedy": {
    "note": "Simulate's player (D95): Item when under item_below of its HP and one is carried; Guard when the enemies could kill it before its next turn; else the move and target that deal the most.",
    "item_below": 0.3333
  },
  "simulate": {
    "note": "Simulate runs this many fights, each under a fresh seed, and gives up on a fight after max_rounds.",
    "runs": 200,
    "max_rounds": 60
  }
}

Cast data (generated)

Generated by scripts/kit-doc.mjs from kit/engine/cast.ts, kit/engine/anim.ts, kit/engine/voice.ts, kit/engine/effects.ts, kit/engine/looks.ts and the data in kit/packs they read, printed as it is. A cast card is this data: the Cast room's preview draws it with the renderer, and a build hands it to a level's script (import { drawShape, localPoly } from '<kit>/engine/cast', import { poseAt } from '<kit>/engine/anim'). A behaviour is chosen from its pack's list and given numbers; its code is the pack's.

Shape grammar

UnitPt (type)

A point in the card's unit square: x from 0 (left) to 1 (right), y from 0 (top) to 1 (bottom). (0.5, 0.5) is the shape's centre, where it turns and scales.

type UnitPt = [number, number];

UnionCircle (interface)

A circle in union with the polygon: its centre and radius, in the unit square.

interface UnionCircle {
  kind: 'circle';
  x: number;
  y: number;
  /** 0.02–0.5 */
  r: number;
}

UnionCapsule (interface)

A capsule in union with the polygon: its centre, radius, half length along its axis, and how far the axis is turned from vertical, in degrees.

interface UnionCapsule {
  kind: 'capsule';
  x: number;
  y: number;
  /** 0.02–0.5 */
  r: number;
  /** half the length of the straight part, 0–0.5 */
  h: number;
  /** −180–180 degrees; 0 is vertical */
  rot: number;
}

Union (type)

A circle or a capsule in union.

type Union = UnionCircle | UnionCapsule;

CastShape (interface)

The shape grammar: a cast card's silhouette.

interface CastShape {
  points: UnitPt[];
  mirror_x: boolean;
  unions: Union[];
  morph?: UnitPt[] | null;
}

SHAPE_MAX_POINTS (const)

At most this many points drawn (the renderer's shape table holds 8 a row).

const SHAPE_MAX_POINTS = 8;

SHAPE_MAX_UNIONS (const)

At most this many circles or capsules in union.

const SHAPE_MAX_UNIONS = 2;

AXIS_EPS (const)

Within this of x = 0.5, a mirrored shape's point is on the axis.

const AXIS_EPS = 1e-3;

NO_SHAPE (const)

An empty card: no shape yet.

const NO_SHAPE: CastShape;

drawnPoints (function)

The polygon as drawn: the points, or with mirror_x the half and its mirror (the axis's points once). axis says which points are on the axis (by default, those within AXIS_EPS of it); a morph's frame takes its points'.

function drawnPoints(points: readonly UnitPt[], mirror: boolean, axis?: readonly boolean[]): UnitPt[];

shapeProblems (function)

What's wrong with a shape, as short lines (none: it's a shape the kit can draw).

function shapeProblems(s: unknown): string[];

localPoly (function)

The drawn polygon in the renderer's local frame (centred on the unit square's middle, one unit across), with the morph m (0–1) of the way to the morph target. Null when there are fewer than 3 points.

function localPoly(s: CastShape, m = 0): Pt[] | null;

unionSub (function)

A union as the renderer's sub-shape, in the local frame.

function unionSub(u: Union): Sub;

drawShape (function)

Draw a card's shape: the polygon (with the first union joined), the second union beneath it. row is the shape table's row for the polygon (a script gets one from ShapeTable.id(localPoly(shape))); size is how many world units the unit square spans. A shape with no polygon is its unions: the first is the body and the second joins it, one outline round both (pass 6: Kaos's drone, a circle with a capsule across it). Returns the instances pushed.

function drawShape(batch: InstanceBatch, row: number | null, s: CastShape, x: number, y: number, rot: number, size: number, look: Look): number;

Animation

ANIM_STATES (const)

A card's states. idle and move loop; attack, hit and death play once and hold their last pose.

const ANIM_STATES = ['idle', 'move', 'attack', 'hit', 'death'] as const;

LOOPING (const)

Which states loop.

const LOOPING: Record<AnimState, boolean>;

TRACKS (const)

The tracks a state can key: rotate (degrees), scale (× the card's size), offset ([x, y] in card sizes), glow (× the card's glow) and morph (0–1 of the way to the shape's morph target).

const TRACKS = ['rotate', 'scale', 'offset', 'glow', 'morph'] as const;

TRACK_RANGES (const)

Each track's range; a value outside it is refused.

const TRACK_RANGES: Record<TrackName, readonly [number, number]> = {
  rotate: [-360, 360],
  scale: [0.1, 4],
  offset: [-1, 1],
  glow: [0, 4],
  morph: [0, 1],
};

CURVES (const)

The four curves (R45): how a keyframe's value arrives at it, as a function from the segment's progress (0–1) to the share of the change made (0 at 0, 1 at 1). A keyframe's curve shapes the segment that ends on it.

const CURVES = {
  /** An overshooting entrance: past the value, then back onto it (peaks about 10% over). */
  snap: (t: number) => {
    const s = 1.70158;
    const u = t - 1;
    return 1 + (s + 1) * u * u * u + s * u * u;
  },
  /** Decelerating: fast at first, easing onto the value; never past it. */
  settle: (t: number) => 1 - (1 - t) ** 3,
  /** Accelerating out: slow at first, leaving fast. */
  exit: (t: number) => t ** 3,
  /** Linear: the same speed all the way (a turn that keeps turning). */
  spin: (t: number) => t,
} as const;

Curve (type)

A curve's name.

type Curve = keyof typeof CURVES;

CURVE_NAMES (const)

The curves' names, in the order the editor offers them.

const CURVE_NAMES = Object.keys(CURVES) as Curve[];

Keyframe (interface)

One keyframe: its time in the state's loop (ms), its value (offset's is [x, y]) and the curve it arrives on.

interface Keyframe {
  t: number;
  v: number | [number, number];
  curve: Curve;
}

AnimEvent (interface)

An effect fired at a time in the loop: one of the effects' names, in the card's hue or in hue (0–359).

interface AnimEvent {
  t: number;
  effect: string;
  hue?: number;
}

StateAnim (interface)

One state: its length, its tracks (each a list of keyframes in time order) and its events.

interface StateAnim {
  /** 100–10,000 ms */
  loop_ms: number;
  tracks: Partial<Record<TrackName, Keyframe[]>>;
  events: AnimEvent[];
}

CastAnim (type)

A card's animation: any of the five states. A state with no keys rests.

type CastAnim = Partial<Record<AnimState, StateAnim>>;

Pose (interface)

Where a card is at a moment: turned (degrees), scaled, offset (card sizes), its glow (×) and morph (0–1).

interface Pose {
  rotate: number;
  scale: number;
  offset: [number, number];
  glow: number;
  morph: number;
}

REST (const)

The pose with nothing keyed.

const REST: Pose;

MAX_KEYS (const)

At most this many keyframes on a track.

const MAX_KEYS = 16;

MAX_EVENTS (const)

At most this many events in a state.

const MAX_EVENTS = 8;

trackValue (function)

A track's value at ms into the loop. Before the first key it holds the first key's value; between two keys the second key's curve shapes the way; after the last key a looping state goes on round to the first key (on its curve), and a state that plays once holds the last.

function trackValue(keys: readonly Keyframe[], ms: number, loopMs: number, looping: boolean): Keyframe['v'] | null;

loopTime (function)

The time in the state's loop for ms since it started: wrapped when it loops, held at the end when it doesn't.

function loopTime(state: Pick<StateAnim, 'loop_ms'>, ms: number, looping: boolean): number;

poseAt (function)

The pose ms after the state started.

function poseAt(state: StateAnim | undefined, ms: number, looping: boolean): Pose;

eventsBetween (function)

The events whose time falls after fromMs and at or before toMs since the state started (both in the state's own clock, unwrapped), each once per pass round the loop.

function eventsBetween(state: StateAnim | undefined, fromMs: number, toMs: number, looping: boolean): AnimEvent[];

animProblems (function)

What's wrong with a card's animation, as short lines (none: the animator can play it).

function animProblems(a: unknown): string[];

Voice

Wave (type)

The waveform: an oscillator, or noise through a band-pass at the pitch.

type Wave = 'sine' | 'square' | 'saw' | 'triangle' | 'noise';

WAVES (const)

The waveforms, in the order the Voice tab offers them.

const WAVES: readonly Wave[];

Envelope (interface)

The envelope, in seconds (a attack, d decay, r release) and the sustain's level (s, 0–1 of the peak).

interface Envelope {
  a: number;
  d: number;
  s: number;
  r: number;
}

CastVoice (interface)

A voice: the waveform at pitch_hz, bent by pitch_env semitones (up when positive) over length_ms, shaped by the envelope; the release follows the length.

interface CastVoice {
  wave: Wave;
  pitch_hz: number;
  envelope: Envelope;
  pitch_env: number;
  length_ms: number;
}

VOICE_RANGES (const)

Each number's range, inclusive: pitch 40–4,000 Hz, ±24 semitones of bend, 30–3,000 ms, the envelope in seconds.

const VOICE_RANGES = {
  pitch_hz: [40, 4000],
  pitch_env: [-24, 24],
  length_ms: [30, 3000],
  a: [0, 1],
  d: [0, 2],
  s: [0, 1],
  r: [0, 2],
} as const;

VOICE_PRESETS (const)

The presets, by name (kit/packs/voices.json): chirp, thud, hiss, bell, growl.

const VOICE_PRESETS: Record<string, CastVoice>;

voiceProblems (function)

What's wrong with a voice, as short lines (none: the synth can play it).

function voiceProblems(v: unknown): string[];

VoiceTimes (interface)

When a voice's parts end, in seconds from its start.

interface VoiceTimes {
  attack: number;
  decay: number;
  /** the release starts at the voice's length */
  release: number;
  end: number;
}

voiceTimes (function)

When a voice's parts end: the attack, the decay, the release's start, the end.

function voiceTimes(v: CastVoice): VoiceTimes;

endPitch (const)

The pitch at the end of the voice: pitch_hz bent by pitch_env semitones, kept in range.

const endPitch = (v: CastVoice) => Math.min(VOICE_RANGES.pitch_hz[1], Math.max(VOICE_RANGES.pitch_hz[0], v.pitch_hz * 2 ** (v.pitch_env / 12)));

kit/packs/voices.json

{
  "chirp": { "wave": "sine", "pitch_hz": 1400, "envelope": { "a": 0.005, "d": 0.08, "s": 0.25, "r": 0.06 }, "pitch_env": 7, "length_ms": 110 },
  "thud": { "wave": "sine", "pitch_hz": 80, "envelope": { "a": 0.002, "d": 0.16, "s": 0, "r": 0.1 }, "pitch_env": -12, "length_ms": 200 },
  "hiss": { "wave": "noise", "pitch_hz": 3200, "envelope": { "a": 0.03, "d": 0.2, "s": 0.35, "r": 0.2 }, "pitch_env": 0, "length_ms": 420 },
  "bell": { "wave": "triangle", "pitch_hz": 880, "envelope": { "a": 0.002, "d": 0.9, "s": 0, "r": 0.7 }, "pitch_env": 0, "length_ms": 1100 },
  "growl": { "wave": "saw", "pitch_hz": 90, "envelope": { "a": 0.05, "d": 0.3, "s": 0.6, "r": 0.25 }, "pitch_env": -5, "length_ms": 650 }
}

Effects

EffectPreset (interface)

A preset as kit/packs/effects.json writes it: its label, its default rate (a second) and the most it may be.

interface EffectPreset {
  label: string;
  rate: number;
  max: number;
}

EFFECTS (const)

The presets, by name (kit/packs/effects.json).

const EFFECTS: Record<string, EffectPreset>;

EFFECT_NAMES (const)

The presets' names: none, dust, sparks, trail, rings.

const EFFECT_NAMES: string[];

Emitter (interface)

Where an effect plays: the card's centre and size (world units), and how fast it's moving (world units a second).

interface Emitter {
  x: number;
  y: number;
  size: number;
  vx: number;
  vy: number;
}

MAX_RINGS (const)

At most this many rings at once.

const MAX_RINGS = 8;

Effects (class)

A card's effects: a steady emitter (run) and bursts (burst), with the rings it keeps.

class Effects {
  /** Seeded or not, the presets jitter with this. */
  rand: () => number;
  /** The preset `name` at `rate` a second for `dt` seconds (clamped to the preset's max). */
  run(name: string, rate: number, dt: number, at: Emitter, color: RGB, sink: ParticleSink): void;
  /** One burst of the preset (an animation event): a handful of what it emits steadily. */
  burst(name: string, at: Emitter, color: RGB, sink: ParticleSink): void;
  /** Age the rings and push the live ones (outline-only circles that grow and fade). Returns the instances pushed. */
  draw(batch: InstanceBatch, dt: number): number;
  clear(): void;
}

kit/packs/effects.json

{
  "none": { "label": "none", "rate": 0, "max": 0 },
  "dust": { "label": "dust motes", "rate": 2, "max": 12 },
  "sparks": { "label": "sparks", "rate": 6, "max": 30 },
  "trail": { "label": "trail", "rate": 20, "max": 60 },
  "rings": { "label": "rings", "rate": 0.8, "max": 4 }
}

Looks

LookName (type)

The looks a pitch chooses from.

type LookName = 'ink' | 'paper' | 'neon';

LookRecipe (interface)

A look's recipe:

interface LookRecipe {
  label: string;
  line: string;
  background: 'ink' | 'bg';
  fill: number;
  light: number;
  bloom: number;
  glow: number;
  tonemap: boolean;
  grain: number;
  vignette: number;
  halftone: number;
  fringe: number;
}

LOOKS (const)

The recipes, by name (kit/packs/looks.json). Ink is the default and is the engine as it was before looks.

const LOOKS: Record<LookName, LookRecipe>;

lookRecipe (const)

A look's recipe by name; anything else is Ink.

const lookRecipe = (name: string | null | undefined): LookRecipe => (name && name in LOOKS ? LOOKS[name as LookName] : LOOKS.ink);

kit/packs/looks.json

{
  "ink": {
    "label": "Ink",
    "line": "silhouettes in ink, neon outlines, bloom",
    "background": "ink",
    "fill": 0,
    "light": 1,
    "bloom": 1,
    "glow": 1,
    "tonemap": true,
    "grain": 0,
    "vignette": 0.45,
    "halftone": 0,
    "fringe": 0
  },
  "paper": {
    "label": "Paper",
    "line": "flat fills on the theme's paper, no bloom; grain and a vignette",
    "background": "bg",
    "fill": 0.22,
    "light": 0,
    "bloom": 0,
    "glow": 0,
    "tonemap": false,
    "grain": 0.05,
    "vignette": 0.3,
    "halftone": 0,
    "fringe": 0
  },
  "neon": {
    "label": "Neon",
    "line": "heavy bloom and a chromatic fringe at the edges",
    "background": "ink",
    "fill": 0,
    "light": 1.15,
    "bloom": 1.8,
    "glow": 1.35,
    "tonemap": true,
    "grain": 0,
    "vignette": 0.5,
    "halftone": 0,
    "fringe": 2.2
  }
}

Behaviours

kit/packs/shooter/behaviours.json

{
  "pack": "shooter",
  "note": "Kaos's behaviours as extracted (docs/KIT_SURVEY.md §2, kit/packs/shooter): the three classes, the three bosses and the six powerups. A card picks one and sets its numbers; the code is the pack's. size: the world units a card's unit square spans in play; light: the class's OKLCH lightness and chroma, at which the card's hue is drawn (pass 6).",
  "behaviours": [
    {
      "id": "dart",
      "label": "dart · comes in, turns and dives",
      "kinds": ["enemy"],
      "line": "Enters in a line, a V or a pincer, then dives at the column the player was in when it turned.",
      "size": 24,
      "light": [0.701, 0.253],
      "params": [
        {"key": "speed", "label": "Speed", "min": 60, "max": 240, "step": 10, "default": 120, "unit": "/s"},
        {"key": "dive_after", "label": "Dive after", "min": 0.4, "max": 3, "step": 0.1, "default": 2.4, "unit": "s"},
        {"key": "hp", "label": "Hearts", "min": 1, "max": 8, "step": 1, "default": 1, "unit": ""}
      ]
    },
    {
      "id": "drone",
      "label": "drone · hovers in a sine and aims",
      "kinds": ["enemy"],
      "line": "Drops to a hover line, sweeps side to side in a sine and fires a shot aimed at the player; leaves after a while.",
      "size": 38,
      "light": [0.69, 0.2],
      "params": [
        {"key": "speed", "label": "Speed", "min": 40, "max": 180, "step": 10, "default": 90, "unit": "/s"},
        {"key": "fire_every", "label": "Fires every", "min": 0.8, "max": 6, "step": 0.1, "default": 2.4, "unit": "s"},
        {"key": "leave_after", "label": "Leaves after", "min": 4, "max": 30, "step": 1, "default": 14, "unit": "s"},
        {"key": "hp", "label": "Hearts", "min": 1, "max": 12, "step": 1, "default": 4, "unit": ""}
      ]
    },
    {
      "id": "wall",
      "label": "wall · slow, splits at half health",
      "kinds": ["enemy"],
      "line": "Drifts down slowly and splits along its seam at half health into two halves that turn apart.",
      "size": 100,
      "light": [0.801, 0.14],
      "params": [
        {"key": "speed", "label": "Speed", "min": 16, "max": 80, "step": 4, "default": 32, "unit": "/s"},
        {"key": "split_at", "label": "Splits at", "min": 0.2, "max": 0.8, "step": 0.05, "default": 0.5, "unit": "of hp"},
        {"key": "hp", "label": "Hearts", "min": 4, "max": 40, "step": 1, "default": 16, "unit": ""}
      ]
    },
    {
      "id": "boss-core",
      "label": "boss · a turning core (level 1)",
      "kinds": ["boss"],
      "line": "Three phases; a core turns inside the hull and fires aimed bursts that come faster as it weakens.",
      "size": 210,
      "light": [0.652, 0.236],
      "params": [
        {"key": "hp", "label": "Hit points", "min": 120, "max": 1200, "step": 20, "default": 420, "unit": ""},
        {"key": "burst_every", "label": "Sweeps every", "min": 0.8, "max": 4, "step": 0.1, "default": 2.4, "unit": "s"}
      ]
    },
    {
      "id": "boss-blades",
      "label": "boss · two blade arms that spiral (level 2)",
      "kinds": ["boss"],
      "line": "Three phases; two arms sweep round and fire from their tips, outward, as two spirals.",
      "size": 144,
      "light": [0.652, 0.236],
      "params": [
        {"key": "hp", "label": "Hit points", "min": 160, "max": 1400, "step": 20, "default": 560, "unit": ""},
        {"key": "turn", "label": "Arm turn", "min": 0.6, "max": 4, "step": 0.1, "default": 1.9, "unit": "rad/s"}
      ]
    },
    {
      "id": "boss-crown",
      "label": "boss · a crown that splits in two (level 3)",
      "kinds": ["boss"],
      "line": "Three phases; at the split it breaks into two halves that take turns to charge.",
      "size": 220,
      "light": [0.652, 0.236],
      "params": [
        {"key": "hp", "label": "Hit points", "min": 200, "max": 1600, "step": 20, "default": 720, "unit": ""},
        {"key": "split_at", "label": "Splits at", "min": 0.1, "max": 0.6, "step": 0.05, "default": 0.3, "unit": "of hp"}
      ]
    },
    {"id": "spread", "label": "powerup · spread", "kinds": ["item"], "line": "The shot fans out, up to five.", "params": [{"key": "steps", "label": "Up to", "min": 1, "max": 5, "step": 1, "default": 5, "unit": "shots"}], "size": 20, "light": [0.755, 0.126]},
    {"id": "rapid", "label": "powerup · rapid", "kinds": ["item"], "line": "Fires faster.", "params": [{"key": "rate", "label": "Rate", "min": 1.1, "max": 2.5, "step": 0.1, "default": 1.6, "unit": "×"}], "size": 20, "light": [0.755, 0.126]},
    {"id": "shield", "label": "powerup · shield", "kinds": ["item"], "line": "One hit taken for free.", "params": [{"key": "hits", "label": "Hits", "min": 1, "max": 1, "step": 1, "default": 1, "unit": ""}], "size": 20, "light": [0.755, 0.126]},
    {"id": "pierce", "label": "powerup · pierce", "kinds": ["item"], "line": "A shot goes through one target.", "params": [{"key": "through", "label": "Through", "min": 1, "max": 3, "step": 1, "default": 1, "unit": ""}], "size": 20, "light": [0.755, 0.126]},
    {"id": "speed", "label": "powerup · speed", "kinds": ["item"], "line": "Moves faster.", "params": [{"key": "rate", "label": "Rate", "min": 1.1, "max": 2, "step": 0.1, "default": 1.3, "unit": "×"}], "size": 20, "light": [0.755, 0.126]},
    {"id": "bomb", "label": "powerup · bomb", "kinds": ["item"], "line": "Stores a bomb that clears the field (up to three).", "params": [{"key": "max", "label": "Hold up to", "min": 1, "max": 5, "step": 1, "default": 3, "unit": ""}], "size": 20, "light": [0.755, 0.126]}
  ]
}

kit/packs/scene/behaviours.json

{ "pack": "scene", "pass": 8, "note": "A scene game's cards need no behaviour: the player carries the light, an item is carried and used by its id, and an enemy is a hotspot's card, answering Talk with its barks.", "behaviours": [] }

kit/packs/combat/behaviours.json

{ "pack": "combat", "pass": 9, "note": "The combat pack's behaviours arrive with the pack (pass 9).", "behaviours": [] }

3D path (generated)

Generated by scripts/kit-doc.mjs from kit/engine3d/budgets.ts, kit/engine3d/index.ts, kit/engine3d/renderer.ts, kit/engine3d/stage.ts, kit/engine3d/camera.ts, kit/engine3d/loader.ts, kit/engine3d/animator.ts, kit/host-api/rim.ts, kit/engine3d/look.ts, kit/engine3d/scaler.ts, kit/engine3d/tier.ts and kit/engine3d/stages/torii-ground.json, printed as it is. The kit's second renderer (D148): three.js (WebGPU first, WebGL2 where WebGPU isn't offered), beside the 2D renderer and never inside it. A pack declares which renderer it uses and a package carries only that one; a 3D pack imports <kit>/engine3d (one entry, createStage3D) and drives the rim through host.rim (<kit>/host-api/rim). The look is ink (D149): bodies in ink, a fresnel rim in the character's hue, an outline, bloom from what glows, props drawn as light; the theme changes the stage and the HUD only. Characters are assets (D154): a glb's bytes — a skin, its clips, props on named bones — carried inside the package's script. Until contract 2 carries a tier, a 3D build is a dev build, played on a desktop.

What the 3D path does not have

kit/engine3d/budgets.ts

RendererKind (type)

The renderer a pack declares (D148): the 2D kit's instanced SDF renderer, or this one. A package carries only its own.

type RendererKind = '2d' | '3d';

BONE_BUDGET (const)

The most bones a character's skin may have (D145: the vroid body). A heavier rig is refused at load.

const BONE_BUDGET = 22;

TRIANGLE_BUDGET (const)

The most triangles a character's body may have (Tatara's ink recipe makes ≤ 30k). A heavier mesh is refused at load.

const TRIANGLE_BUDGET = 30_000;

PROP_TRIANGLE_BUDGET (const)

The most triangles a prop may have (D143).

const PROP_TRIANGLE_BUDGET = 2_000;

LIGHT_BUDGET (const)

The most point lights a stage may light (D149): the stage's lanterns and any the pack adds, together.

const LIGHT_BUDGET = 4;

CHARACTER_BUDGET (const)

The most characters on a stage at once.

const CHARACTER_BUDGET = 6;

LOCAL_TIER (const)

The local tier's ruler (D153): the desktop at 1920×1080, judged at 8.3 ms a frame (a 120 Hz display), never looser than 16.6 ms (60 Hz). Placeholders until the desktop GPU's reading rules them (docs/reports/pass-15.md has the readings).

const LOCAL_TIER = { width: 1920, height: 1080, budgetMs: 8.3, floorMs: 16.6 } as const;

STAGE_ASPECT (const)

The stage's shape: a 3D pack is wide-first; portrait letterboxes the stage at this aspect (D148, task 2).

const STAGE_ASPECT = 16 / 9;

ABSENT (const)

What the 3D path does not have, by design: a script that needs one of these needs a ruling first.

const ABSENT = [
  'no free camera: the stage camera is fixed (three-quarter framing, or the boss framing a pack requests); the right stick is never the camera’s',
  'no shadows: the body is ink, lit by the lanterns and drawn by its rim and outline',
  'no textures in the ink look: a character is a mesh, a rig and clips; a material or texture in the glTF is ignored',
  'no image loads at run time and no fetch: assets arrive as bytes in the package’s own script (the contract’s connect-src is none)',
  `no more than ${LIGHT_BUDGET} point lights, ${BONE_BUDGET} bones a character, ${TRIANGLE_BUDGET.toLocaleString('en-US')} triangles a body, ${CHARACTER_BUDGET} characters`,
  'no physics, no ragdolls, no IK: poses come from clips and keyed procedural layers',
  'no phone browser: a 3D build plays on the local tier (a desktop) and says so on a phone',
  'no cel or animated looks yet (D151 reserves them); the ink look is the one recipe',
] as const;

kit/engine3d/index.ts

StageOptions (interface)

How a stage starts: its data (the default stage unless given), the theme's mode, the aspect, the renderer's options.

interface StageOptions extends BootOptions {
  stage?: StageData;
  mode?: Mode;
  aspect?: Aspect;
  /** Step the scaler from the frames' times (true unless false: a test or a bench holds a level with `quality`). */
  autoScale?: boolean;
}

StageCharacter (interface)

A character on the stage: what was loaded, its animator and its look.

interface StageCharacter extends Character {
  animator: Animator;
  look: CharacterLook;
}

Readout3D (interface)

The budget readout (the corner's chip): the backend, the frame's time, its draw calls and the scaler's step.

interface Readout3D {
  backend: Backend;
  gpu: string;
  /** A GPU-synced frame time, ms (one frame in 30 waits for the GPU), smoothed; null until the first. */
  ms: number | null;
  /** The last frame's CPU time, ms (the update and the submit). */
  cpuMs: number;
  /** Draw calls in the last frame, every pass counted. */
  draws: number;
  /** The scaler's level (0: full) and what its last step did. */
  level: number;
  step: string;
  /** The drawing buffer, pixels. */
  width: number;
  height: number;
}

Stage3D (interface)

A stage.

interface Stage3D {
  readonly backend: Backend;
  readonly gpu: string;
  readonly scaler: Scaler3D;
  readonly characters: ReadonlyMap<string, StageCharacter>;
  /** The framing now. */
  readonly framing: FramingName;
  /** The stage's clock, seconds: rims and their presets run on it; tick advances it. Setting it moves no animator. */
  time: number;
  /** Load a character from its glb's bytes and stand it at a place (a name in the stage's places, or a ground point). */
  addCharacter(bytes: ArrayBuffer | Uint8Array, opts: CharacterOptions & { place?: string | GroundPt }): Promise<StageCharacter>;
  /** Play one of a character's clips (a crossfade from what plays). */
  play(name: string, clip: string, opts?: PlayOptions): void;
  /** Add a procedural layer to a character's bones; returns its remover. */
  layer(name: string, layer: BoneLayer): () => void;
  /** Turn character `a` to face character `b`. */
  face(a: string, b: string): void;
  /** The theme's mode: the stage's night or paper (the body never changes, D146). */
  setMode(mode: Mode): void;
  /** Cut to a framing: the stage's, or the boss's (D150). */
  frame(f: FramingName): void;
  /** The aspect the host gives: wide fills the view, portrait letterboxes the stage. */
  setAspect(aspect: Aspect): void;
  /** The view's size in CSS pixels: the canvas is placed and sized inside it (see `rect`). */
  resize(w: number, h: number): void;
  /** Where the stage draws in the view, CSS pixels. */
  rect(): Rect;
  /** The outline's thickness in pixels (1.6 unless set; 0 draws none — what a test compares against). */
  outline(px: number): void;
  /** Hold the scaler at a level (0–5) and stop it stepping by itself; null lets it step again. */
  quality(level: number | null): void;
  /** Advance every animator and rim by dt seconds, feed the scaler, and draw. */
  tick(dt: number): void;
  /** Draw the frame as it is. */
  render(): void;
  /** Wait for the GPU to finish what was submitted. */
  gpuDone(): Promise<void>;
  /** The GPU's time for the passes drawn since the last call, ms (null unless booted with `timestamps`). */
  gpuTime(): Promise<number | null>;
  readout(): Readout3D;
}

kit/engine3d/renderer.ts

Backend (type)

The backend a stage draws with.

type Backend = 'webgpu' | 'webgl2';

Booted (interface)

A booted renderer: three's, its backend and the GPU it named.

interface Booted {
  renderer: WebGPURenderer;
  backend: Backend;
  gpu: string;
  /** Wait until the GPU has finished what was submitted (a frame time that includes the GPU's). */
  gpuDone(): Promise<void>;
  /** The GPU's time for the passes drawn since the last call, ms; null without timestamps. */
  gpuTime(): Promise<number | null>;
}

BootOptions (interface)

Boot options: force WebGL2 (the tests' SwiftShader runs), the device-pixel ratio, antialiasing, GPU timestamps.

interface BootOptions {
  forceWebGL?: boolean;
  pixelRatio?: number;
  antialias?: boolean;
  /** Time each frame's passes on the GPU (timestamp queries, where the GPU has them): the bench's, never a game's. */
  timestamps?: boolean;
}

kit/engine3d/stage.ts

GroundPt (type)

A point on the ground: [x, z] in metres (a character is 1.75 m tall); +x right, +z toward the camera.

type GroundPt = [number, number];

WorldPt (type)

A point in the world: [x, y, z] in metres.

type WorldPt = [number, number, number];

StagePiece (type)

One piece of a stage.

type StagePiece =
  /** The ground plane, `size` metres square, centred: lit by the lanterns at night, the page itself on paper. */
  | { kind: 'ground'; size: number }
  /** The playing field's three-quarter grid: `rows` lines across and `rails` toward the back, inside the field. */
  | { kind: 'grid'; rows: number; rails: number }
  /** A torii's silhouette at a ground point, scaled (1: 5.6 m tall); never hazed, drawn lighter than the night. */
  | { kind: 'torii'; at: GroundPt; scale: number }
  /** A lantern at a world point: a glowing box and a point light of `light` candela-ish (34 is the plate's). */
  | { kind: 'lantern'; at: WorldPt; light: number }
  /** Haze over the stage (exponential fog), its density by theme; the body is never hazed (D146). */
  | { kind: 'haze'; dark: number; light: number };

StageData (interface)

A stage: its name, the playing field's rectangle on the ground, its pieces and where characters stand.

interface StageData {
  name: string;
  /** The field: x from–to and z from–to (back to front), metres. */
  field: { x: [number, number]; z: [number, number] };
  pieces: StagePiece[];
  /** Named places on the ground: `player` and `foe` at least. */
  places: Record<string, GroundPt>;
}

DEFAULT_STAGE (const)

The duel view's stage (stages/torii-ground.json): a 14 × 10.5 m field, two torii far back, two lanterns, haze.

const DEFAULT_STAGE = TORII_GROUND as unknown as StageData;

stageProblems (function)

What's wrong with a stage, as short lines (none: the 3D path can build it).

function stageProblems(s: unknown): string[];

stageLights (const)

How many point lights a stage lights (its lanterns).

const stageLights = (s: StageData): number => s.pieces.filter((p) => p.kind === 'lantern').length;

kit/engine3d/camera.ts

Framing (interface)

A framing: the vertical field of view (degrees), where the camera stands and the point it looks at.

interface Framing {
  fov: number;
  eye: WorldPt;
  look: WorldPt;
}

FramingName (type)

The framings a pack may ask for: the stage's three-quarter view, and the boss's wider, lower one.

type FramingName = 'stage' | 'boss';

FRAMINGS (const)

The framings (the plate's stage camera, and its boss variant: 8° wider, the eye 1.6 m lower, looking up a little).

const FRAMINGS: Readonly<Record<FramingName, Framing>> = {
  stage: { fov: 30, eye: [0.3, 3.7, 13.2], look: [0.3, 1.55, -2.6] },
  boss: { fov: 38, eye: [0.3, 2.1, 12.4], look: [0.6, 2.2, -2.6] },
};

Rect (interface)

A rectangle in CSS pixels.

interface Rect {
  x: number;
  y: number;
  w: number;
  h: number;
}

fitStage (function)

Where the stage draws in a view of w × h: wide fills it; portrait letterboxes a 16:9 band across the full width, centred, the bars ink. The HUD sits over the stage's rectangle and never scales with the scaler.

function fitStage(w: number, h: number, aspect: 'portrait' | 'wide'): Rect;

kit/engine3d/loader.ts

Role (type)

A character's role on the stage: whose hue its rim is drawn in (the member's for the player, the class's for a foe).

type Role = 'player' | 'foe' | 'boss';

CharacterOptions (interface)

What a stage needs to know to place a character.

interface CharacterOptions {
  /** Its name on the stage, unique: the rim, the animator and the pack call it by this. */
  name: string;
  /** Its hue, 0–359: the member's (the player) or its class's (a foe), drawn at the dark constants on ink (D149). */
  hue: number;
  role: Role;
  /** Its height on the stage in metres (1.75 unless given). */
  height?: number;
}

PropSpec (interface)

A prop's spec (D143): its kind, the bone it rides, the clips it's drawn in and those it's hidden in.

interface PropSpec {
  kind: string;
  bone: string;
  shown_in: string[];
  hidden_in: string[];
}

Prop (interface)

A prop on a character: its mesh (a child of its bone) and its spec.

interface Prop {
  mesh: Mesh;
  spec: PropSpec;
}

Character (interface)

A loaded character: its holder on the stage (place and face it by this), its model, body meshes, props and clips.

interface Character {
  options: Required<CharacterOptions>;
  holder: Group;
  model: Object3D;
  body: Mesh[];
  props: Prop[];
  clips: AnimationClip[];
  /** The skin's bones by name. */
  bones: Map<string, Object3D>;
  /** The body's triangles. */
  triangles: number;
}

AssetRefused (class)

Refused at load: the line says what was over or missing.

class AssetRefused extends Error {}
}

attachProp (function)

Put a prop on a named bone of a character (re-parented, keeping its world pose), held to the prop budget.

function attachProp(c: Pick<Character, 'bones' | 'props' | 'options'>, mesh: Mesh, spec: PropSpec): Prop;

faceToward (function)

Turn a character's holder to face a point on the ground.

function faceToward(c: Pick<Character, 'holder'>, x: number, z: number): void;

kit/engine3d/animator.ts

BONE_CHANNELS (const)

A bone channel a layer keys: a turn about x, y or z (degrees), an offset along x, y or z (character heights), a scale.

const BONE_CHANNELS = ['turn_x', 'turn_y', 'turn_z', 'offset_x', 'offset_y', 'offset_z', 'scale'] as const;

CHANNEL_RANGES (const)

Each channel's range; a key outside it is refused (the 2D tracks' ranges: rotate, offset, scale).

const CHANNEL_RANGES: Record<BoneChannel, readonly [number, number]> = {
  turn_x: [-360, 360],
  turn_y: [-360, 360],
  turn_z: [-360, 360],
  offset_x: [-1, 1],
  offset_y: [-1, 1],
  offset_z: [-1, 1],
  scale: [0.1, 4],
};

BoneLayer (interface)

A procedural layer: one bone's channel, keyed like a 2D track (a number a key; the curve shapes the way to it).

interface BoneLayer {
  bone: string;
  channel: BoneChannel;
  /** 100–10,000 ms */
  loop_ms: number;
  looping: boolean;
  keys: Keyframe[];
}

PlayOptions (interface)

How a clip is played: the crossfade in from what played (s), its speed (×), and whether it loops.

interface PlayOptions {
  fade?: number;
  speed?: number;
  loop?: boolean;
  /** A clip that plays once fades back to this one at its end (idle unless given; null holds the last pose). */
  then?: string | null;
}

DEFAULT_FADE (const)

The crossfade when none is given, seconds (the plate's).

const DEFAULT_FADE = 0.12;

layerProblems (function)

What's wrong with a layer, as short lines (none: the animator can play it).

function layerProblems(l: unknown, bones?: ReadonlySet<string>): string[];

Animator (class)

A character's animator.

class Animator {
  readonly mixer: AnimationMixer;
  readonly actions;
  readonly layers: BoneLayer[];
  /** The clip playing now (the one fading in), or null. */
  current: string | null;
  constructor(private readonly c: Pick<Character, 'model' | 'clips' | 'props' | 'bones' | 'options'>);
  /** Each clip's weight now (0–1). */
  weights(): Record<string, number>;
  /** Play a clip, crossfading from whatever plays. A clip already playing keeps its time unless it played once and ended. */
  play(name: string, opts: PlayOptions = {}): void;
  /** The clip's speed (×) from now. */
  speed(name: string, x: number): void;
  /** Add a procedural layer (checked); returns a function that removes it. */
  addLayer(layer: BoneLayer): () => void;
  /** Advance by dt seconds: the fade, the clips, a finished clip back to `then`, then the layers and the props. */
  update(dt: number): void;
  /**
   * Hold a still pose (a plate's frame, a test's): `clip` at `t` seconds, crossfaded from idle as play would have it —
   * its weight rising over the fade at the start and falling over it at the end — with idle at `idleT` under it.
   * Nothing advances: the next update carries on from here.
   */
  pose(clip: string, t: number, idleT = t): void;
  /** How far each prop is drawn (0–1): the weight of the clips that show it and don't hide it. */
  drawn(p: Prop): number;
}

kit/host-api/rim.ts

RIM_DEFAULT (const)

A character's rim when nothing has set it: pass 14's look.

const RIM_DEFAULT = 0.5;

RimEnvelope (type)

A rim preset's envelope: a pulse (attack, hold, a quadratic decay back to the base) or a hold (a level with a waver).

type RimEnvelope =
  | { kind: 'pulse'; label: string; peak: number; attack: number; hold: number; decay: number; bloom: number }
  | { kind: 'hold'; label: string; level: number; wave: number; period: number; bloom: number };

RIM_PRESETS (const)

The four presets (D147): their times in seconds; bloom is what each adds to the bloom's strength at its peak.

const RIM_PRESETS = {
  parry_pulse: { kind: 'pulse', label: 'parry pulse', peak: 1.0, attack: 0.03, hold: 0.05, decay: 0.32, bloom: 0.4 },
  stance_break_bloom: { kind: 'pulse', label: 'stance-break bloom', peak: 1.0, attack: 0.08, hold: 0.3, decay: 0.9, bloom: 1.6 },
  low_health_dim: { kind: 'hold', label: 'low-health dim', level: 0.15, wave: 0.06, period: 1.8, bloom: 0 },
  powered: { kind: 'hold', label: 'powered', level: 0.9, wave: 0.05, period: 0.6, bloom: 0.5 },
} as const satisfies Record<string, RimEnvelope>;

RimPreset (type)

A preset's name.

type RimPreset = keyof typeof RIM_PRESETS;

RIM_PRESET_NAMES (const)

The presets' names, in the order a preview offers them.

const RIM_PRESET_NAMES = Object.keys(RIM_PRESETS) as RimPreset[];

RimValue (interface)

A rim at a moment: its intensity (0–1), the bloom it adds, and (a pulse) whether it has finished.

interface RimValue {
  intensity: number;
  bloom: number;
  done: boolean;
}

clampRim (function)

A value as a rim intensity: clamped to 0–1; not a number is the default.

function clampRim(v: unknown): number;

rimEnvelope (function)

The rim t seconds after name was called on a character whose base is base.

function rimEnvelope(name: RimPreset, base: number, t: number): RimValue;

Rim (class)

One character's rim: a base and at most one running preset, on the caller's clock (seconds).

class Rim {
  base;
  preset: RimPreset | null;
  at;
  set(v: number): number;
  call(name: RimPreset, at: number): void;
  clear(): void;
  /** The rim at `now`; a finished pulse clears itself. */
  value(now: number): RimValue;
}

RimWho (type)

Who a rim call is for: a character's name on the stage, or player (the stage's player character).

type RimWho = string;

RimControl (interface)

The pack's rim control, as host.rim: set a base, call a preset, clear it; who is player unless named.

interface RimControl {
  /** Set the base intensity (0–1, clamped) of `who`'s rim; returns what it became. */
  (value: number, who?: RimWho): number;
  /** Start a preset on `who`'s rim now (a pulse ends by itself; a hold stays until `clear`). */
  preset(name: RimPreset, who?: RimWho): void;
  /** End `who`'s preset: back to its base. */
  clear(who?: RimWho): void;
  /** `who`'s rim at `now` (seconds on the stage's clock): what the 3D path draws. */
  value(who: RimWho, now: number): RimValue;
}

rim (const)

The rim control host.rim is: one registry per package.

const rim: RimControl = Object.assign((value: number, who: RimWho = 'player') => rimOf(who).set(value), {
  preset: (name: RimPreset, who: RimWho = 'player') => rimOf(who).call(name, clock()),
  clear: (who: RimWho = 'player') => rimOf(who).clear(),
  value: (who: RimWho, now: number) => rimOf(who).value(now),
});

setRimClock (function)

The stage's clock for presets (tests and the bench drive it).

function setRimClock(fn: () => number): void;

aliasRim (function)

Let alias (e.g. player) stand for a character's name: the stage calls it for its player character.

function aliasRim(alias: string, name: string): void;

resetRims (function)

Every rim back to the default with no preset, and no alias (a new run).

function resetRims(): void;

Host3D (type)

The package's host with its rim: the same host object, with rim installed when the 3D path is in the bundle.

type Host3D = Host & { rim: RimControl };

host3d (const)

The package's host, typed with rim (the same object as host-api's host).

const host3d = host as Host3D;

kit/engine3d/look.ts

INK (const)

The body's ink, both themes (D146).

const INK = '#07070b';

RIM_L (const)

D15's dark constants: a rim and an outline sit on ink in both themes, so they are drawn at these.

const RIM_L = 0.76;

rimColor (function)

A hue at the rim's constants, as a linear colour.

function rimColor(hue: number): Color;

STAGE_THEMES (const)

The stage's colours by theme (the plate's): only the stage and the HUD change with it.

const STAGE_THEMES = {
  dark: { bg: '#07070b', fog: '#0d0f17', ground: '#050608', paper: false, grid: '#20242f', edge: '#2f3545', torii: '#2a2d3a' },
  light: { bg: '#f3f4f7', fog: '#eef0f4', ground: '#eceef3', paper: true, grid: '#d3d7df', edge: '#a9afbb', torii: '#e1e4ea' },
} as const;

CharacterLook (interface)

A character's materials and the uniforms the stage drives each frame.

interface CharacterLook {
  body: MeshStandardNodeMaterial;
  prop: MeshStandardNodeMaterial;
  hue: UniformNode<Color>;
  rim: UniformNode<number>;
  prop_light: UniformNode<number>;
}

rimWidth (const)

The rim's width (0–1: the plate's 0.4).

const rimWidth = uniform(0.4);

characterLook (function)

A character's look: ink lit by the lanterns with its rim in its hue; its props as light.

function characterLook(hue: number, rimDefault: number): CharacterLook;

BuiltStage (interface)

A stage built from its data: its group, its lights, and how to show it in a theme or without haze.

interface BuiltStage {
  group: Group;
  lights: PointLight[];
  setMode(mode: Mode): void;
  setHaze(on: boolean): void;
}

buildStage (function)

Build a stage's pieces (stage.ts) into the scene; its colours follow the theme.

function buildStage(scene: Scene, data: StageData): BuiltStage;

Post (interface)

The post: the scene with its emissive target, bloom from that target, an outline per character, composed by theme.

interface Post {
  pipeline: RenderPipeline;
  bloom: BloomNode;
  outlines: Map<string, OutlineNode>;
  /** Compose for a theme, with an outline for every character in the map (one made for each newly added). */
  compose(mode: Mode): void;
  /** Bloom's resolution (0.5, 0.25) and the outline's down-sampling (1, 2): the scaler's steps. */
  setQuality(bloomScale: number, outlineRatio: number): void;
  /** The outline's thickness, pixels (the plate's 1.6). */
  edge: UniformNode<number>;
}

BLOOM_STRENGTH (const)

The bloom's strength with no preset lifting it (the plate's).

const BLOOM_STRENGTH = 1.0;

makePost (function)

Make the post for a scene, a camera and the characters (each its holder and its hue uniform).

function makePost(renderer: WebGPURenderer, scene: Scene, camera: Camera, characters: Map<string, { holder: Object3D; look: CharacterLook }>): Post;

kit/engine3d/scaler.ts

Quality3D (interface)

What a level draws at.

interface Quality3D {
  /** The 3D canvas's resolution against the CSS size × the device's pixels (1, 0.75, 0.5). */
  renderScale: number;
  /** Bloom's resolution against the frame (0.5, 0.25). */
  bloomScale: number;
  /** The outline's down-sampling (1: full resolution, 2: half). */
  outlineRatio: number;
  /** Haze on. */
  haze: boolean;
}

STEPS_3D (const)

What each step down does, in order (level n has the first n applied).

const STEPS_3D = ['render scale 1.0 → 0.75', 'render scale 0.75 → 0.5', 'bloom ½ → ¼ resolution', 'outline full → ½ resolution', 'haze off'] as const;

quality3dAt (function)

The quality at a level (0: full).

function quality3dAt(level: number): Quality3D;

budget3dFor (const)

The budget for a display: 8.3 ms at 120 Hz (faster than 90 Hz), the 16.6 ms floor at 60 (D153).

const budget3dFor = (periodMs: number): number => (periodMs < 11 ? LOCAL_TIER.budgetMs : LOCAL_TIER.floorMs);

Frame3D (interface)

One frame's numbers: its CPU time, its GPU-synced time (null when not sampled), and the gap since the last frame.

interface Frame3D {
  cpuMs: number;
  gpuMs: number | null;
  gapMs: number;
}

Step3D (interface)

A step taken: when, from and to which level, what changed, and the numbers it was taken on.

interface Step3D {
  at: number;
  from: number;
  to: number;
  what: string;
  avgMs: number;
  budgetMs: number;
}

Scaler3D (class)

The scaler: feed it a frame each frame; read level and apply quality3dAt(level).

class Scaler3D {
  level;
  readonly log: Step3D[];
  /** A forced budget in ms (a test's), or null to follow the display. */
  override: number | null;
  /** The display's refresh period as measured, ms (the median of the last 15 gaps; 16.7 until then). */
  period(): number;
  /** The budget now, ms. */
  budget(): number;
  /** The average cost over the window so far, ms. */
  average(): number;
  /** One frame; `now` in seconds. Returns the step taken, if any. */
  feed(f: Frame3D, now: number): Step3D | null;
  /** Go to a level now (the preview's and the bench's), with an empty window. */
  force(level: number, now = 0): Step3D | null;
  /** Back to full quality with an empty window. */
  reset(): void;
}

kit/engine3d/tier.ts

PHONE_REFUSAL (const)

What a phone sees in place of a 3D stage.

const PHONE_REFUSAL = 'This one plays on a desktop, not in a phone browser.';

DeviceLike (interface)

The device as far as the tier asks: a coarse pointer (a finger), the screen's shorter side in CSS pixels, the UA.

interface DeviceLike {
  coarse: boolean;
  shortSide: number;
  userAgent: string;
}

thisDevice (function)

The device this page runs on.

function thisDevice(): DeviceLike;

PHONE_UA (const)

A phone's user agent (web/src/play/tier.ts has the same: a test holds the two the same).

const PHONE_UA = /\b(iPhone|iPod)\b|Android.+Mobile|Mobile Safari|\bMobi\b/;

isPhone (function)

A phone: a phone's user agent, or a finger for a pointer on a screen under 768 CSS pixels on its short side.

function isPhone(d: DeviceLike): boolean;

tierRefusal (function)

The line a 3D stage shows instead of itself on this device, or null when it plays here.

function tierRefusal(d: DeviceLike = thisDevice()): string | null;

kit/engine3d/stages/torii-ground.json

{
  "name": "torii-ground",
  "field": { "x": [-7, 7], "z": [-6, 4.5] },
  "pieces": [
    { "kind": "ground", "size": 80 },
    { "kind": "grid", "rows": 5, "rails": 7 },
    { "kind": "torii", "at": [-6.6, -16], "scale": 1 },
    { "kind": "torii", "at": [6.4, -18], "scale": 1 },
    { "kind": "lantern", "at": [-5.6, 3.0, -9], "light": 34 },
    { "kind": "lantern", "at": [5.8, 3.3, -10.5], "light": 34 },
    { "kind": "haze", "dark": 0.022, "light": 0.03 }
  ],
  "places": { "player": [-1.55, 1.2], "foe": [1.35, -0.9], "boss": [1.2, -1.6] }
}