Skip to content

G. API Cheat Sheets ​

The APIs you'll reach for most as you build a game with MVT and this book's libraries, arranged by what you're trying to do rather than by package. Each entry says when you'd use the API, and gives its signature, its import line and the chapter that teaches it. The playground shows the same sheets beside your code, and so does each experiment online.

Related: MVT on One Page · Glossary · Troubleshooting

Each sheet covers one job, such as noticing a change or playing a sound, whichever library its APIs come from. The signatures, and the first sentence of each description, are read from the libraries' own declarations as the book is built, so they always match the code. The libraries' doc comments say more, and so does the chapter that each entry links to.

In this book

The sheets cover the @mvtjs libraries, the playground's playground module and the audio90 sound chips, and the parts of Pixi, PixiJS 3D, three.js and GSAP that the book's examples use. MVT itself needs none of them. The view tick API, such as setRefresh, is exported by each renderer's package: @mvtjs/pixi, @mvtjs/html, @mvtjs/three and @mvtjs/pixi-3d. The sheets show the import from @mvtjs/pixi, so import it from your own renderer's package instead. In the playground, press Cheat sheet, or F1, to open the sheets over the run, beside your code. In an experiment, press View code, then Cheat sheet.

G.1 Defining a Project in the Playground ​

What your main.ts exports, and what the playground passes to your start function.

G.1.1 Defining the project ​

definePixiProjectStart a project that draws in 2D with Pixi. start adds your views to the stage, and returns your model.

definePixiProject(options: PixiProjectOptions): PixiProject
export const project = definePixiProject({
    width: 400,
    height: 300,
    start: ({ stage }) => {
        const model = createBallModel();
        stage.addChild(BallView({ model }));
        return model;
    },
});

import { definePixiProject } from 'playground'; · Chapter 3, A First Game

defineHtmlProjectStart a project built from HTML elements, such as a form or a board of buttons. start appends your views to root.

defineHtmlProject(options: HtmlProjectOptions): HtmlProject
export const project = defineHtmlProject({
    start: ({ root }) => {
        const model = createCounterModel();
        root.append(CounterView({ model }));
        return model;
    },
});

import { defineHtmlProject } from 'playground';

defineThreeProjectStart a 3D project drawn with three.js. start adds your views to the scene, which the camera looks at from 5 units back.

defineThreeProject(options: ThreeProjectOptions): ThreeProject
export const project = defineThreeProject({
    width: 400,
    height: 300,
    start: ({ scene }) => {
        const model = createSpinnerModel();
        scene.add(SpinnerView({ model }));
        return model;
    },
});

import { defineThreeProject } from 'playground';

G.1.2 What start is passed, and what it returns ​

PixiStartOptionsSee what a Pixi project's start is passed: the stage for your views, the sound chip, and the project's size.

interface PixiStartOptions {
    stage: Container<ContainerChild>;
    sound: Audio80;
    width: number;
    height: number;
}

import { PixiStartOptions } from 'playground';

HtmlStartOptionsSee what an HTML project's start is passed: the root element for your views, the sound chip, and the size.

interface HtmlStartOptions {
    root: HTMLElement;
    sound: Audio80;
    width: number;
    height: number;
}

import { HtmlStartOptions } from 'playground';

ThreeStartOptionsSee what a three.js project's start is passed: the scene and camera, the sound chip, and the size.

interface ThreeStartOptions {
    scene: Scene<Object3DEventMap>;
    camera: PerspectiveCamera;
    sound: Audio80;
    width: number;
    height: number;
}

import { ThreeStartOptions } from 'playground';

TickedReturn your model from start. Each tick, the playground calls its update(deltaMs), then updates and refreshes your views.

interface Ticked {
    update: (deltaMs: number) => void;
}

import { Ticked } from 'playground'; · Chapter 5, The Tick

G.1.3 Checking your own code ​

assertStop with a clear message when something that must be true isn't, such as a precondition of a model's action.

assert(condition: unknown, message: string | (() => string)): void
assert(lives > 0, () => `No lives left to lose: ${lives}`);

import { assert } from '@mvtjs/utils'; · Chapter 31, Design by Contract (DbC)

G.2 The View Tick API ​

How a view writes the model's state every tick, and moves its own presentation state on. Import these from your renderer's package.

G.2.1 A view tick by tick ​

setRefreshGive a view a refresh method, which writes the model's state to the view's display objects every tick.

setRefresh(view: View, refresh: RefreshMethod | undefined): void
const view = new Container();
const ball = new Graphics().circle(0, 0, 10).fill(0xffcc00);
view.addChild(ball);
setRefresh(view, () => {
    ball.position.set(bindings.x(), bindings.y());
});
return view;

import { setRefresh } from '@mvtjs/pixi'; · Chapter 7, Views

setUpdateGive a view an update method, which moves the view's own presentation state on by deltaMs, such as a flash that fades.

setUpdate(view: View, update: UpdateMethod | undefined): void
let flashMs = 0;
setUpdate(view, (deltaMs) => {
    flashMs = Math.max(0, flashMs - deltaMs);
});
setRefresh(view, () => {
    flash.alpha = flashMs / FLASH_MS;
});

import { setUpdate } from '@mvtjs/pixi'; · Chapter 11, Presentation State

SKIP_DESCENDANTSReturn it from an update or refresh method to skip the view's children this tick, such as while the view is hidden.

const SKIP_DESCENDANTS: unique symbol
setRefresh(view, () => {
    view.visible = bindings.isShown();
    if (!view.visible) return SKIP_DESCENDANTS;
});

import { SKIP_DESCENDANTS } from '@mvtjs/pixi'; · Chapter 7, Views

G.2.2 Running the views yourself ​

updateViewCall every update method in a tree of views. The playground calls it for you each tick, so you need it only in a loop of your own.

updateView(view: View, deltaMs: number): void

import { updateView } from '@mvtjs/pixi'; · Chapter 7, Views

refreshViewCall every refresh method in a tree of views, parents before children. The playground calls it for you each tick.

refreshView(view: View): void

import { refreshView } from '@mvtjs/pixi'; · Chapter 7, Views

hasUpdateCheck whether a view has an update method, such as in a test.

hasUpdate(view: View): boolean

import { hasUpdate } from '@mvtjs/pixi';

hasRefreshCheck whether a view has a refresh method, such as in a test.

hasRefresh(view: View): boolean

import { hasRefresh } from '@mvtjs/pixi';

advanceTimeMove models and views on by some milliseconds in a test, a tick at a time, as the ticker would.

advanceTime(ms: number, ...items: readonly Advanceable[]): Promise<void>
const model = createShipModel();
const view = ShipView({ model });
await advanceTime(500, model, view);

import { advanceTime } from '@mvtjs/pixi'; · Chapter 15, Testing Models

G.3 Watching for Changes ​

How a view does something only when a value changes, rather than every tick: play a sound, rebuild some text, or redraw a shape.

G.3.1 Reactions and computed values ​

createReactionDo something once, at the moment a value changes, such as playing a sound as the score goes up. Call the reaction every tick.

createReaction(options: {
    watch: () => T;
    when?: T | ((current: T, previous: T) => boolean);
    react: (current: T, previous: T) => void;
}): () => void
const playChimeWhenScoreRises = createReaction({
    watch: () => model.score,
    when: increased,
    react: () => sound.play(CHIME),
});
setRefresh(view, playChimeWhenScoreRises);

import { createReaction } from '@mvtjs/utils'; · Chapter 9, Noticing Changes

createComputedMake a value, such as a label's text, only when what it's made from changes. Read it by calling it.

createComputed(options: {
    watch: () => T;
    compute: (current: T) => R;
}): Computed<R>
const scoreText = createComputed({
    watch: () => model.score,
    compute: (score) => `Score: ${score}`,
});
setRefresh(view, () => {
    label.text = scoreText();
});

import { createComputed } from '@mvtjs/utils'; · Chapter 9, Noticing Changes

watchRead several values at once, and see which have changed since you last polled. Poll it every tick.

watch(getters: (() => T) | Record<string, () => unknown>): Watcher
const watcher = watch({
    lives: () => model.lives,
    level: () => model.level,
});
setRefresh(view, () => {
    const { lives, level } = watcher.poll();
    if (lives.changed) drawLives(lives.current);
    if (level.changed) drawLevel(level.current);
});

import { watch } from '@mvtjs/utils'; · Chapter 9, Noticing Changes

G.3.2 Conditions for when ​

increasedPass it as a reaction's when, to react only as a number goes up, such as a count of shots fired.

increased<T>(current: T, previous: T): boolean

import { increased } from '@mvtjs/utils'; · Chapter 9, Noticing Changes

decreasedPass it as a reaction's when, to react only as a number goes down, such as the lives left.

decreased<T>(current: T, previous: T): boolean

import { decreased } from '@mvtjs/utils'; · Chapter 9, Noticing Changes

changedFromPass it as a reaction's when, to react only as a value leaves the one you name, such as a phase leaving 'playing'.

changedFrom<T>(value: NoInfer<T>): (current: T, previous: T) => boolean
const playJingleWhenGameEnds = createReaction({
    watch: () => model.phase,
    when: changedFrom('playing'),
    react: () => sound.play(GAME_OVER),
});

import { changedFrom } from '@mvtjs/utils'; · Chapter 9, Noticing Changes

G.4 JSX for Pixi ​

Views written as JSX, for Pixi. Start a .tsx file with /** @jsxImportSource @mvtjs/pixi */.

G.4.1 Elements ​

<container>Group other elements, and move, fade, turn or scale them together. Every element takes these attributes.

<container x={...} y={...} alpha={...} rotation={...} scale={...}>
<container x={() => model.x} y={() => model.y}>
    <graphics ref={drawShip} />
</container>

<graphics>Draw shapes. Draw them once in ref, then move, scale or tint the element, rather than drawing again every tick.

<graphics ref={(g: Graphics) => void} tint={...}>
<graphics
    ref={(g) => g.circle(0, 0, 10).fill(0xffffff)}
    tint={() => (model.isHurt ? 0xff4040 : 0xffffff)}
/>

<text>Show text, such as a score. Make the text with createComputed, so it changes only when the score does.

<text text={...} style={{ fill, fontSize, ... }} anchor={...}>
<text
    text={scoreText}
    style={{ fill: 0xffffff, fontSize: 18 }}
    anchor={0.5}
/>

<sprite>Show a texture, such as one you made by drawing a Graphics.

<sprite texture={...} tint={...} anchor={...} width={...} height={...}>

onPointerTapReport a click or tap on an element. Pixi has onPointerDown, onPointerUp, onPointerMove and the rest too.

onPointerTap={(event: FederatedPointerEvent) => void}
<graphics ref={drawButton} onPointerTap={() => model.startNewRun()} />

G.4.2 Attributes of every element ​

Getters for values that changePass a getter, () => value, for a value that changes. The view reads it every tick. Pass a plain value for one that never changes.

attribute={value}
attribute={() => value}

Chapter 12, Writing Views in JSX

visibleShow or hide an element as the model changes. While it's hidden, its children aren't refreshed at all.

visible={() => boolean}

Chapter 12, Writing Views in JSX

refDo something to an element once it's made, such as drawing shapes, which an attribute can't do.

ref={(element) => void}

Chapter 12, Writing Views in JSX

onRefreshRun your own code on an element in its refresh step, every tick, for output that attributes can't write.

onRefresh={(element) => void}

Chapter 12, Writing Views in JSX

onUpdateMove a view's own presentation state on, every tick, such as a timer for a flash that fades.

onUpdate={(deltaMs: number) => void}

Chapter 11, Presentation State

onDestroyedRelease something as the element is destroyed, such as a listener on window.

onDestroyed={(element) => void}

Chapter 7, Views

ownsFree the resources that the view made for the element, such as a texture or a 3D shape, when the element is destroyed.

owns={[texture, geometry, ...]}

Chapter 7, Views

G.4.3 Lists and switches ​

ListShow a view for each item in an array, such as each enemy. The item is a getter, since an item view may show other items over time.

<List items={() => readonly T[]}>{(item: () => T, index: number) => view}</List>
<List items={() => model.enemies}>
    {(enemy) => (
        <EnemyView x={() => enemy().x} y={() => enemy().y} />
    )}
</List>

import { List } from '@mvtjs/pixi'; · Chapter 14, Lists and Switches

SwitchShow one of several views, such as a title screen or the game, whichever <Match> matches first.

<Switch>{<Match> elements}</Switch>
<Switch>
    <Match when={() => model.phase === 'title'}>
        <TitleView />
    </Match>
    <Match else>
        <GameView model={model} />
    </Match>
</Switch>

import { Switch } from '@mvtjs/pixi'; · Chapter 14, Lists and Switches

MatchGive a <Switch> a branch, shown while its when is true, or as the last branch, else.

<Match when={() => boolean}>
<Match else>

import { Match } from '@mvtjs/pixi'; · Chapter 14, Lists and Switches

G.5 JSX for HTML ​

Views written as JSX, for HTML elements. Start a .tsx file with /** @jsxImportSource @mvtjs/html */.

G.5.1 Elements ​

<div> and the other tagsBuild the page from elements. Change how one looks as the model changes with class. Its style is set once.

<div class={...} text={...} style="..." title={...}>
<div class={() => (model.isWon ? 'board won' : 'board')}>
    <span class="score" text={scoreText} />
</div>

textPut text in an element. It's the only way to: JSX text between tags isn't supported, so an element with text has no children.

text={string | (() => string)}

onClickReport a click. There's onInput, onChange, onKeyDown, onPointerDown and the rest too.

onClick={(event: MouseEvent) => void}
<button type="button" text="Reset" onClick={() => model.reset()} />

<input>Take the player's input, and show the model's value in the field as it changes.

<input type="..." value={...} checked={...} disabled={...} onInput={...}>
<input
    type="range"
    valueAsNumber={() => model.speed}
    onInput={(e) => {
        model.speed = (e.target as HTMLInputElement).valueAsNumber;
    }}
/>

data- and aria- attributesSet an element's data-* and aria-* attributes, for your CSS and for screen readers.

data-name={...}
aria-label={...}

G.5.2 Attributes of every element ​

Getters for values that changePass a getter, () => value, for a value that changes. The view reads it every tick. Pass a plain value for one that never changes.

attribute={value}
attribute={() => value}

Chapter 12, Writing Views in JSX

visibleShow or hide an element as the model changes. While it's hidden, its children aren't refreshed at all.

visible={() => boolean}

Chapter 12, Writing Views in JSX

refDo something to an element once it's made, such as drawing shapes, which an attribute can't do.

ref={(element) => void}

Chapter 12, Writing Views in JSX

onRefreshRun your own code on an element in its refresh step, every tick, for output that attributes can't write.

onRefresh={(element) => void}

Chapter 12, Writing Views in JSX

onUpdateMove a view's own presentation state on, every tick, such as a timer for a flash that fades.

onUpdate={(deltaMs: number) => void}

Chapter 11, Presentation State

onDestroyedRelease something as the element is destroyed, such as a listener on window.

onDestroyed={(element) => void}

Chapter 7, Views

ownsFree the resources that the view made for the element, such as a texture or a 3D shape, when the element is destroyed.

owns={[texture, geometry, ...]}

Chapter 7, Views

G.5.3 Lists and switches ​

ListShow an element for each item in an array, such as each row of a table. The item is a getter.

<List items={() => readonly T[]}>{(item: () => T, index: number) => view}</List>
<ul>
    <List items={() => model.scores}>
        {(score) => <li text={() => score().name} />}
    </List>
</ul>

import { List } from '@mvtjs/html'; · Chapter 14, Lists and Switches

SwitchShow one of several views, whichever <Match> matches first.

<Switch>{<Match> elements}</Switch>
<Switch>
    <Match when={() => model.phase === 'title'}>
        <TitleView />
    </Match>
    <Match else>
        <GameView model={model} />
    </Match>
</Switch>

import { Switch } from '@mvtjs/html'; · Chapter 14, Lists and Switches

MatchGive a <Switch> a branch, shown while its when is true, or as the last branch, else.

<Match when={() => boolean}>
<Match else>

import { Match } from '@mvtjs/html'; · Chapter 14, Lists and Switches

MVT_GROUP_CSSAdd this CSS rule to your page when a <List> or <Switch> sits in a grid or a flexbox, so the element that holds its children doesn't change the layout.

const MVT_GROUP_CSS: "mvt-group:not([hidden]){display:contents}"
const style = document.createElement('style');
style.textContent = MVT_GROUP_CSS;
document.head.append(style);

import { MVT_GROUP_CSS } from '@mvtjs/html';

G.6 JSX for three.js ​

Views written as JSX, for three.js. Start a .tsx file with /** @jsxImportSource @mvtjs/three */.

G.6.1 Elements ​

<group>Group other objects, and move, turn or scale them together. Every element takes these attributes.

<group x={...} y={...} z={...} rotationX={...} rotationY={...} rotationZ={...} scale={...}>
<group x={() => model.x} rotationY={() => model.heading}>
    <mesh geometry={HULL} material={METAL} />
</group>

<mesh>Show a shape. Make each geometry and material once, outside the view, and share them between meshes.

<mesh geometry={...} material={...}>
const BOX = new BoxGeometry(1, 1, 1);
const RED = new MeshStandardMaterial({ color: 0xff4040 });

<mesh geometry={BOX} material={RED} y={() => model.height} />

<ambientLight>, <directionalLight> and <pointLight>Light the scene, so a MeshStandardMaterial shows. A MeshNormalMaterial needs no light.

<directionalLight color={...} intensity={...} x={...} y={...} z={...}>
<ambientLight intensity={0.4} />
<directionalLight x={3} y={5} z={4} intensity={1.2} />

onClickReport a click on an object, or on any object inside a group. It needs a pointer picker, made once in start.

onClick={(event: PointerPickEvent) => void}

createPointerPickerMake pointer events reach your objects' onClick and onPointerDown attributes. In the playground, the scene's canvas is the page's only one.

createPointerPicker(options: PointerPickerOptions): PointerPicker
createPointerPicker({
    domElement: document.querySelector('canvas')!,
    camera: () => camera,
    scene,
});

import { createPointerPicker } from '@mvtjs/three';

G.6.2 Attributes of every element ​

Getters for values that changePass a getter, () => value, for a value that changes. The view reads it every tick. Pass a plain value for one that never changes.

attribute={value}
attribute={() => value}

Chapter 12, Writing Views in JSX

visibleShow or hide an element as the model changes. While it's hidden, its children aren't refreshed at all.

visible={() => boolean}

Chapter 12, Writing Views in JSX

refDo something to an element once it's made, such as drawing shapes, which an attribute can't do.

ref={(element) => void}

Chapter 12, Writing Views in JSX

onRefreshRun your own code on an element in its refresh step, every tick, for output that attributes can't write.

onRefresh={(element) => void}

Chapter 12, Writing Views in JSX

onUpdateMove a view's own presentation state on, every tick, such as a timer for a flash that fades.

onUpdate={(deltaMs: number) => void}

Chapter 11, Presentation State

onDestroyedRelease something as the element is destroyed, such as a listener on window.

onDestroyed={(element) => void}

Chapter 7, Views

ownsFree the resources that the view made for the element, such as a texture or a 3D shape, when the element is destroyed.

owns={[texture, geometry, ...]}

Chapter 7, Views

G.6.3 Lists and switches ​

ListShow an object for each item in an array, such as each asteroid. The item is a getter.

<List items={() => readonly T[]}>{(item: () => T, index: number) => view}</List>
<List items={() => model.rocks}>
    {(rock) => (
        <mesh geometry={ROCK} material={STONE} x={() => rock().x} />
    )}
</List>

import { List } from '@mvtjs/three'; · Chapter 14, Lists and Switches

SwitchShow one of several views, whichever <Match> matches first.

<Switch>{<Match> elements}</Switch>

import { Switch } from '@mvtjs/three'; · Chapter 14, Lists and Switches

MatchGive a <Switch> a branch, shown while its when is true, or as the last branch, else.

<Match when={() => boolean}>
<Match else>

import { Match } from '@mvtjs/three'; · Chapter 14, Lists and Switches

G.7 JSX for PixiJS 3D ​

Views of 3D scenes written as JSX, for PixiJS 3D on a Pixi stage. Start a .tsx file with /** @jsxImportSource @mvtjs/pixi-3d */.

G.7.1 2D and 3D together ​

Scene3DViewShow a 3D scene on the Pixi stage, drawn from the first <camera> in it. 2D views added after it draw on top.

Scene3DView(bindings: Scene3DViewBindings): View3D<Container3D>
stage.addChild(Scene3DView({
    scene: CrateSceneView({ progress: () => model.progress }),
    width: 400,
    height: 300,
    background: 0x1d2433,
}));

import { Scene3DView } from '@mvtjs/pixi-3d';

ScreenViewShow a 2D view on a screen in the scene, such as a scoreboard over a track. The screen shows the view from the first frame.

ScreenView(bindings: ScreenViewBindings): Mesh3D
<ScreenView content={ScoreView({ score: () => model.score })}
    contentWidth={256} contentHeight={64} width={4} height={1} />

import { ScreenView } from '@mvtjs/pixi-3d';

ScreenAnchorViewPlace a 2D view over a point in the scene, such as a name tag over a car. It stays sharp, and draws over the scene.

ScreenAnchorView(bindings: ScreenAnchorViewBindings): Container<ContainerChild>

import { ScreenAnchorView } from '@mvtjs/pixi-3d';

G.7.2 Elements ​

<group>Group other nodes, and move, turn or scale them together. Every element takes these attributes. Rotations are in radians.

<group x={...} y={...} z={...} rotationX={...} rotationY={...} rotationZ={...} scale={...}>
<group x={() => model.x} rotationY={() => model.heading}>
    <mesh geometry={hull} material={metal} />
</group>

<mesh>Show a shape. Make each geometry and material once, in a variable, and list them in owns on the view's root element.

<mesh geometry={...} material={...} castShadow={...} receiveShadow={...}>
const box = new CubeGeometry({ width: 1, height: 1, depth: 1 });
const red = new Material3D({ baseColor: 0xff4040 });

<group owns={[box, red]}>
    <mesh geometry={box} material={red} y={() => model.height} />
</group>

<camera>Set where the scene is seen from. Write lookAt after the position, since attributes are applied in order. Keep one camera, outside any <Switch> or <List>, and move it.

<camera x={...} y={...} z={...} lookAt={...} fov={...}>
<camera y={2} z={6} lookAt={{ x: 0, y: 0, z: 0 }} />

<ambientLight>, <directionalLight>, <pointLight> and <spotLight>Light the scene, so a Material3D shows. A directional or spot light can cast shadows.

<directionalLight color={...} intensity={...} castShadow={...} shadow={...} lookAt={...}>
<ambientLight intensity={0.4} />
<directionalLight intensity={2.5} castShadow={true} x={-3} y={5} z={4} lookAt={{ x: 0, y: 0, z: 0 }} />

<sprite3d>Show a picture in the scene, which walls in front of it can hide. With billboardMode='spherical', it always faces the camera.

<sprite3d texture={...} width={...} height={...} billboardMode={...}>

<model>Show a 3D model loaded from a glTF file, posed at a moment in one of its animation clips. The pose changes only when clipTimeMs does.

<model source={...} clip={...} clipTimeMs={...}>

onPointerTapReport a tap on a node, or on any node inside a group. hitVolume='geometry' tests each triangle, not the box around it.

onPointerTap={(event: Pointer3DEvent) => void}

G.7.3 Particles, and freeing without JSX ​

ParticlesViewShow particles, such as sparks or smoke. They move only as your views update, and start from a seed, so a run repeats exactly.

ParticlesView(bindings: ParticlesViewBindings): ParticleSystem3D<readonly ShaderBit[]>
<ParticlesView
    options={{ emitRate: 0, life: [0.4, 0.8], speed: [2, 6], color: 0xffaa33 }}
    isEmitting={false}
    bursts={() => model.explosions}
/>

import { ParticlesView } from '@mvtjs/pixi-3d';

ownResourcesFree a view's geometries, materials and textures when its node is destroyed, as owns does, in a view written without JSX.

ownResources<N>(node: N, resources: readonly OwnedResource[]): N

import { ownResources } from '@mvtjs/pixi-3d';

G.7.4 Attributes of every element ​

Getters for values that changePass a getter, () => value, for a value that changes. The view reads it every tick. Pass a plain value for one that never changes.

attribute={value}
attribute={() => value}

Chapter 12, Writing Views in JSX

visibleShow or hide an element as the model changes. While it's hidden, its children aren't refreshed at all.

visible={() => boolean}

Chapter 12, Writing Views in JSX

refDo something to an element once it's made, such as drawing shapes, which an attribute can't do.

ref={(element) => void}

Chapter 12, Writing Views in JSX

onRefreshRun your own code on an element in its refresh step, every tick, for output that attributes can't write.

onRefresh={(element) => void}

Chapter 12, Writing Views in JSX

onUpdateMove a view's own presentation state on, every tick, such as a timer for a flash that fades.

onUpdate={(deltaMs: number) => void}

Chapter 11, Presentation State

onDestroyedRelease something as the element is destroyed, such as a listener on window.

onDestroyed={(element) => void}

Chapter 7, Views

ownsFree the resources that the view made for the element, such as a texture or a 3D shape, when the element is destroyed.

owns={[texture, geometry, ...]}

Chapter 7, Views

G.7.5 Lists and switches ​

ListShow a node for each item in an array, such as each asteroid. The item is a getter.

<List items={() => readonly T[]}>{(item: () => T, index: number) => view}</List>

import { List } from '@mvtjs/pixi-3d'; · Chapter 14, Lists and Switches

SwitchShow one of several views, whichever <Match> matches first.

<Switch>{<Match> elements}</Switch>

import { Switch } from '@mvtjs/pixi-3d'; · Chapter 14, Lists and Switches

MatchGive a <Switch> a branch, shown while its when is true, or as the last branch, else.

<Match when={() => boolean}>
<Match else>

import { Match } from '@mvtjs/pixi-3d'; · Chapter 14, Lists and Switches

G.8 Time and Motion Helpers ​

Helpers for a view's own presentation state, such as a glow that eases in or a flash that fades. Each has an update(deltaMs), which you call from the view's update step.

G.8.1 Tweens ​

createBooleanTweenEase a number between two values as a true-or-false state changes, such as a glow that fades in while a shield is up.

createBooleanTween(options: BooleanTweenOptions): BooleanTween
const glow = createBooleanTween({
    getSource: () => model.isShielded,
    offValue: 0,
    onValue: 1,
    onDurationMs: 300,
    offDurationMs: 600,
});
setUpdate(view, glow.update);
setRefresh(view, () => {
    shield.alpha = glow.value;
});

import { createBooleanTween } from '@mvtjs/utils'; · Chapter 18, Growing a Complex View

createEdgeTweenPlay a short tween each time a state turns true, such as a flash that fades as the player is hurt.

createEdgeTween(options: EdgeTweenOptions): EdgeTween
const flash = createEdgeTween({
    getSource: () => model.isHurt,
    triggerValue: 1,
    restValue: 0,
    durationMs: 400,
});
setUpdate(view, flash.update);

import { createEdgeTween } from '@mvtjs/utils'; · Chapter 18, Growing a Complex View

G.8.2 Beats and sequences ​

createMetronomeCount beats at a tempo you can change as you go, such as a heartbeat that quickens as fewer enemies are left.

createMetronome(): Metronome
const beat = createMetronome();
setUpdate(view, (deltaMs) => {
    beat.periodMs = 200 + 40 * model.enemiesLeft;
    beat.update(deltaMs);
});

import { createMetronome } from '@mvtjs/utils'; · Chapter 18, Growing a Complex View

createRepeaterCall a function from a model at a steady rate, such as firing while the trigger is held.

createRepeater(options: RepeaterOptions): Repeater
const autoFire = createRepeater({
    periodMs: () => (model.isAutoFiring ? 200 : 0),
    onRepeat: () => model.fire(),
});
// In the model's update: autoFire.update(deltaMs);

import { createRepeater } from '@mvtjs/utils'; · Chapter 6, Time and Phases

createSequenceTime several overlapping steps of an effect, such as a flash, a shake and a burst of dust, from one start().

createSequence(steps: readonly StepDef[]): Sequence
const celebration = createSequence([
    { name: 'flash', startMs: 0, durationMs: 100 },
    { name: 'shake', startMs: 50, durationMs: 400 },
] as const);
setUpdate(view, celebration.update);
// Later: celebration.steps.shake.progress

import { createSequence } from '@mvtjs/utils'; · Chapter 18, Growing a Complex View

createSequenceTrackerRun code as each step of a sequence starts, while it's active, and as it ends. Call the tracker every tick.

createSequenceTracker(sequence: Sequence, handlers: { [step: string]: StepHandlers }): () => void
const refreshEffects = createSequenceTracker(celebration, {
    shake: {
        active: (progress) => shakeBy(1 - progress),
        inactive: () => shakeBy(0),
    },
});
setRefresh(view, refreshEffects);

import { createSequenceTracker } from '@mvtjs/utils'; · Chapter 18, Growing a Complex View

G.9 Slot Lists for Collections ​

Collections for a model whose items come and go, such as bullets. Each item keeps its slot for its whole life, so a view of the slot can keep its own state. A view shows them with <List>, on the JSX sheet.

G.9.1 Slot lists ​

createSlotListKeep items that come and go, such as bullets, each in a slot of its own until it's removed. A removed item's slot is reused.

createSlotList<T>(options?: SlotListOptions<T>): SlotList<T>
const bullets = createSlotList<Bullet>({ maxSlots: 64 });
const slot = bullets.insert({ x: 0, y: 0 });
// Later, as it leaves the screen
bullets.remove(slot);

import { createSlotList } from '@mvtjs/utils'; · Chapter 14, Lists and Switches

SlotListSee what a slot list has: its slots, which a <List> shows, and how to insert, remove and visit the live items.

interface SlotList<T> {
    slots: IndexedSlots<Slot<T>>;
    liveCount: number;
    isFull: boolean;
    forEachLive: (visit: (value: T, slot: Slot<T>) => void) => void;
    insert: (value: T) => Slot<T>;
    remove: (slot: Slot<T>, releaseDelayMs?: number | undefined) => void;
    clear: () => void;
    update: (deltaMs: number) => void;
}

import { SlotList } from '@mvtjs/utils';

createOrderedSlotListKeep items in an order that changes, such as a hand of cards, while each keeps its slot. Its ordered list follows the order.

createOrderedSlotList<T>(options?: SlotListOptions<T>): OrderedSlotList<T>

import { createOrderedSlotList } from '@mvtjs/utils'; · Chapter 14, Lists and Switches

G.10 Sound on the Audio80 ​

Sound effects and music, on the Audio80 sound chip that your start is passed as sound. A view plays a sound as a value changes, usually from a reaction.

More: Using the Audio80, Writing tracker music

G.10.1 Playing on the chip ​

Audio80.playPlay a sound effect, or start a song in place of the one playing. It returns an id, which stop takes.

Audio80.play(sound: Audio80Sound, options?: Audio80PlayOptions): number (+1 more)
const playZapOnEachShot = createReaction({
    watch: () => model.shotsFired,
    when: increased,
    react: () => sound.play(ZAP),
});

import { Audio80 } from 'audio90'; · Chapter 20, Sound and Music

Audio80.queuePlay a song next, without a gap, as the song playing reaches its end, such as the stage tune after a fanfare.

Audio80.queue(song: Audio80Song, options?: SongPlayOptions): number

import { Audio80 } from 'audio90'; · Chapter 20, Sound and Music

Audio80.stopStop a play by its id, or everything with no id, at once or with a fade.

Audio80.stop(id?: number, options?: StopOptions): void

import { Audio80 } from 'audio90';

Audio80.tempoScalePlay the music faster or slower than its own tempo, such as faster when time is running short. 1 is its own tempo.

Audio80.tempoScale: number

import { Audio80 } from 'audio90';

G.10.2 Making sounds and songs ​

createAudio80SoundMake a sound once, as a module loads, then play it as often as you like. Its options set its wave, envelope, pitch and steps.

createAudio80Sound(options: Audio80SoundOptions): Audio80Sound
export const ZAP = createAudio80Sound({
    note: 'C-6',
    glideTo: 'C-4',
    pulseWidth: 0.25,
    envelope: { attackMs: 0, decayMs: 120, sustain: 0, releaseMs: 0 },
});

import { createAudio80Sound } from 'audio90'; · Chapter 20, Sound and Music

createAudio80SongMake a song from patterns written as text, played by instruments that you make with createAudio80Sound.

createAudio80Song(options: Audio80SongOptions): Audio80Song
export const TUNE = createAudio80Song({
    bpm: 120,
    instruments: { L: LEAD },
    patterns: {
        a: `
            | C-5 L
            | E-5
            | G-5
            | C-6
        `,
    },
    order: ['a'],
});

import { createAudio80Song } from 'audio90'; · Chapter 20, Sound and Music

G.11 Pixi Essentials ​

The parts of Pixi that most views need: containers, shapes, text and sprites. Pixi's own docs cover the rest.

More: Pixi's guides, Pixi's API

G.11.1 Containers ​

ContainerHold other display objects, and move, scale, turn or fade them together. A view usually returns one.

new Container()

import { Container } from 'pixi.js';

Container.addChildAdd display objects to a container, drawn in the order they're added. The stage your start is passed is a container.

Container.addChild(...children: Container[]): Container

import { Container } from 'pixi.js';

Container.removeChildTake display objects out of a container, to add them again later or to destroy them.

Container.removeChild(...children: Container[]): Container

import { Container } from 'pixi.js';

Container.positionPlace a display object, relative to its parent's origin. position.set(x, y) sets both at once.

Container.position: ObservablePoint
ship.position.set(model.col * TILE, model.row * TILE);

import { Container } from 'pixi.js';

Container.scaleGrow or shrink a display object. scale.set(2) doubles it, and a negative x flips it.

Container.scale: ObservablePoint

import { Container } from 'pixi.js';

Container.rotationTurn a display object about its origin, in radians.

Container.rotation: number

import { Container } from 'pixi.js';

Container.alphaFade a display object and its children, from 0, invisible, to 1, opaque.

Container.alpha: number

import { Container } from 'pixi.js';

Container.visibleHide a display object. It's still refreshed, so return SKIP_DESCENDANTS too, to skip its children's work.

Container.visible: boolean

import { Container } from 'pixi.js';

Container.destroyFree a display object you no longer need, and its children with { children: true }.

Container.destroy(options?: DestroyOptions): void

import { Container } from 'pixi.js';

G.11.2 Shapes ​

GraphicsDraw shapes: a path, then fill or stroke it. Each call returns the graphics, so calls chain.

new Graphics()
const ball = new Graphics()
    .circle(0, 0, 10)
    .fill(0xffcc00)
    .stroke({ width: 2, color: 0x000000 });

import { Graphics } from 'pixi.js';

Graphics.rectAdd a rectangle to the path, from its top-left corner.

Graphics.rect(x: number, y: number, w: number, h: number): Graphics

import { Graphics } from 'pixi.js';

Graphics.roundRectAdd a rectangle with rounded corners to the path.

Graphics.roundRect(x: number, y: number, w: number, h: number, radius?: number): Graphics

import { Graphics } from 'pixi.js';

Graphics.circleAdd a circle to the path, from its centre.

Graphics.circle(x: number, y: number, radius: number): Graphics

import { Graphics } from 'pixi.js';

Graphics.ellipseAdd an ellipse to the path, from its centre.

Graphics.ellipse(x: number, y: number, radiusX: number, radiusY: number): Graphics

import { Graphics } from 'pixi.js';

Graphics.polyAdd a polygon to the path, from a list of points: [x0, y0, x1, y1, ...].

Graphics.poly(points: number[] | PointData[], close?: boolean): Graphics

import { Graphics } from 'pixi.js';

Graphics.moveToStart a new line at a point, without drawing.

Graphics.moveTo(x: number, y: number): Graphics

import { Graphics } from 'pixi.js';

Graphics.lineToDraw a line from the last point to this one. stroke draws it.

Graphics.lineTo(x: number, y: number): Graphics

import { Graphics } from 'pixi.js';

Graphics.fillFill the shapes added since the last fill or stroke, with a colour, such as 0xff8800, or { color, alpha }.

Graphics.fill(style?: FillInput): Graphics

import { Graphics } from 'pixi.js';

Graphics.strokeOutline the shapes added since the last fill or stroke, with { width, color }.

Graphics.stroke(style?: StrokeInput): Graphics

import { Graphics } from 'pixi.js';

Graphics.clearRub out everything drawn, to draw again. Redraw only when the shape changes. Moving, scaling or tinting it costs much less.

Graphics.clear(): Graphics

import { Graphics } from 'pixi.js';

G.11.3 Text and sprites ​

TextShow text. Setting its text makes a new texture, so set it only when the text changes.

new Text(options?: { text, style, anchor })
const label = new Text({
    text: '0',
    style: { fill: 0xffffff, fontSize: 18, fontFamily: 'monospace' },
    anchor: 0.5,
});

import { Text } from 'pixi.js';

SpriteShow a texture. Many sprites can share one texture.

new Sprite(texture?: Texture)

import { Sprite } from 'pixi.js';

Sprite.anchorChoose which point of a sprite or text sits at its position: anchor.set(0.5) centres it.

Sprite.anchor: ObservablePoint

import { Sprite } from 'pixi.js';

Sprite.tintColour a sprite, multiplying its own colours, such as red for a moment as it takes a hit.

Sprite.tint: number

import { Sprite } from 'pixi.js';

Texture.WHITEA white texture, ready made, for a sprite that you size and tint into a coloured rectangle.

Texture.WHITE: Texture<BufferImageSource>

import { Texture } from 'pixi.js';

G.11.4 Pointer input ​

Container.eventModeMake a display object take pointer events: set it to 'static'.

Container.eventMode?: EventMode

import { Container } from 'pixi.js';

Container.onListen for a click, a tap or a press on a display object, and pass on what the player did.

Container.on(event: 'pointertap' | 'pointerdown' | ..., listener: (event: FederatedPointerEvent) => void): Container
button.eventMode = 'static';
button.on('pointertap', () => bindings.onStartPressed?.());

import { Container } from 'pixi.js';

RectangleSet a display object's hitArea, so it takes clicks across the whole of a box, not only where it draws.

new Rectangle(x: number, y: number, width: number, height: number)

import { Rectangle } from 'pixi.js';

G.12 three.js Essentials ​

The parts of three.js that a first 3D project needs: meshes, their shapes and materials, lights, and placing objects. three.js's own docs cover the rest.

More: three.js's docs, three.js's manual

G.12.1 Meshes ​

MeshShow a shape: a geometry, drawn with a material. Share geometries and materials between meshes.

new Mesh(geometry?: BufferGeometry, material?: Material)
const BOX = new BoxGeometry(1, 1, 1);
const SKIN = new MeshNormalMaterial();
const cube = new Mesh(BOX, SKIN);
scene.add(cube);

import { Mesh } from 'three';

BoxGeometryMake a box, by its width, height and depth.

new BoxGeometry(width?: number, height?: number, depth?: number, widthSegments?: number, heightSegments?: number, depthSegments?: number)

import { BoxGeometry } from 'three';

SphereGeometryMake a sphere, by its radius. More segments make it smoother.

new SphereGeometry(radius?: number, widthSegments?: number, heightSegments?: number, phiStart?: number, phiLength?: number, thetaStart?: number, thetaLength?: number)

import { SphereGeometry } from 'three';

PlaneGeometryMake a flat rectangle, such as a floor. Turn it to lie flat with rotation.x = -Math.PI / 2.

new PlaneGeometry(width?: number, height?: number, widthSegments?: number, heightSegments?: number)

import { PlaneGeometry } from 'three';

MeshNormalMaterialColour a mesh by the way each face points. It needs no lights, so it suits a first try.

new MeshNormalMaterial(parameters?: MeshNormalMaterialParameters)

import { MeshNormalMaterial } from 'three';

MeshStandardMaterialColour a mesh, shaded by the lights in the scene: { color: 0x44aaff }. Without a light it shows black.

new MeshStandardMaterial(parameters?: MeshStandardMaterialParameters)

import { MeshStandardMaterial } from 'three';

MeshBasicMaterialColour a mesh one flat colour, whatever the lights.

new MeshBasicMaterial(parameters?: MeshBasicMaterialParameters)

import { MeshBasicMaterial } from 'three';

G.12.2 Lights ​

AmbientLightLight every object evenly, from no direction, so shadowed sides aren't black.

new AmbientLight(color?: ColorRepresentation, intensity?: number)

import { AmbientLight } from 'three';

DirectionalLightLight the scene from one direction, as the sun does. Its position sets where it shines from.

new DirectionalLight(color?: ColorRepresentation, intensity?: number)

import { DirectionalLight } from 'three';

G.12.3 Placing objects ​

GroupHold other objects, and move, turn or scale them together. A view usually returns one.

new Group()

import { Group } from 'three';

Object3D.addAdd objects to a group, or to the scene your start is passed.

Object3D.add(...objects: Object3D[]): Object3D

import { Object3D } from 'three';

Object3D.positionPlace an object, relative to its parent: position.set(x, y, z). The camera starts at z = 5, looking at the origin.

Object3D.position: Vector3
ship.position.set(model.x, 0, model.z);

import { Object3D } from 'three';

Object3D.rotationTurn an object about its x, y and z axes, in radians: rotation.y = model.heading.

Object3D.rotation: Euler

import { Object3D } from 'three';

MathUtils.degToRadTurn degrees into the radians that rotations take.

MathUtils.degToRad(degrees: number): number

import { MathUtils } from 'three';

ColorMake a colour, from a number such as 0xff8800 or a CSS name. A material's color is one.

new Color(color?: ColorRepresentation)

import { Color } from 'three';

G.13 PixiJS 3D Essentials ​

The parts of PixiJS 3D that a first 3D project needs: shapes and materials, and freeing them. PixiJS 3D's own docs cover the rest.

More: PixiJS 3D docs

G.13.1 Shapes ​

CubeGeometryMake a box, by its width, height and depth.

new CubeGeometry(options?: Partial<CubeGeometryOptions>)

import { CubeGeometry } from '@pixi/3d';

SphereGeometryMake a sphere, by its radius. More segments make it smoother.

new SphereGeometry(options?: Partial<SphereGeometryOptions>)

import { SphereGeometry } from '@pixi/3d';

CylinderGeometryMake a cylinder or a cone, standing upright along the y axis, by its two radii and its height.

new CylinderGeometry(options?: Partial<CylinderGeometryOptions>)

import { CylinderGeometry } from '@pixi/3d';

PlaneGeometryMake a flat rectangle that faces along the z axis. Turn it with rotationX={-Math.PI / 2} to lie flat, as a floor.

new PlaneGeometry(options?: Partial<PlaneGeometryOptions>)

import { PlaneGeometry } from '@pixi/3d';

G.13.2 Materials ​

Material3DColour a mesh, shaded by the lights in the scene: { baseColor: 0x44aaff, roughness: 0.5 }. Without a light it shows black.

new Material3D(options?: Material3DOptions)
const paint = new Material3D({ baseColor: 0xe8452c, roughness: 0.35, metallic: 0.2 });

import { Material3D } from '@pixi/3d';

FlatMaterialColour a mesh evenly, whatever the lights, like a glowing sign: { baseColor: 0xffcc33 }.

new FlatMaterial(options?: BaseMaterial3DOptions)

import { FlatMaterial } from '@pixi/3d';

G.13.3 Freeing what you make ​

ownsList the shapes, materials and textures that a view made, on its root element. Each one is freed when the element is destroyed.

owns={[geometry, material, texture]}

Chapter 7, Views

G.14 GSAP Essentials ​

GSAP's timelines, for a model whose moves are easier to write as a sequence of tweens. Make them paused, and move them on in the model's update, so they keep the model's time.

More: GSAP's docs

G.14.1 Timelines in a model ​

gsap.timelineMake a timeline of tweens. Make it paused, so GSAP's own clock never moves it, and move it on yourself in update.

gsap.timeline(vars?: { paused?: boolean, ... }): Timeline
const timeline = gsap.timeline({ paused: true });

update(deltaMs) {
    timeline.time(timeline.time() + deltaMs / 1000);
},

import { gsap } from 'gsap'; · Appendix E, Timelines with GSAP

gsap.toTween a state object's numbers to the values you give, over duration seconds. In a model, call a paused timeline's to, which takes the same arguments.

gsap.to(targets: TweenTarget, vars: TweenVars): Tween
const state = { x: 0, y: 0 };
timeline.to(state, { x: 3, duration: 0.25, ease: 'none' });

import { gsap } from 'gsap'; · Appendix E, Timelines with GSAP