Skip to the manual
In this manual

mote-engine / v0.42.0

Developer manual

A 3D engine for the web with three modes: ASCII characters, Ray surfaces with physical materials and WebGPU ray tracing, and Wireframe indexed edges with hidden-line removal. Objects share the same owned mesh, deformation and continuous material/cut fields in every mode. It loads glTF models, includes primitives, physics, lights, independent particle effects, stage transitions, a code backdrop.

Install

After you buy a licence, your download link delivers the versioned ESM package and its TypeScript declarations. Version 0.42.0 has no runtime dependencies.

With npm, from your project folder:

npm install ./mote-engine-0.42.0.tgz

Then import it by name:

import { createScene, cssColors } from "mote-engine";

The package is ESM only and ships its TypeScript types. Entry points:

Import What
mote-engine everything
mote-engine/geometry meshes, sampling, built-in shapes (no browser needed)
mote-engine/gltf the glTF reader (no browser needed)
mote-engine/text still frames as plain text (no browser needed)
mote-engine/backdrop the code backdrop
mote-engine/effects effect factories and live parameter definitions
mote-engine/physics rigid bodies, joints, raycasts and snapshots
mote-engine/director scene-operation and timeline validation, the timeline compiler and sampler, createSceneFromJson (Scene JSON v2) and replayLog (loaded on demand by the scene)
mote-engine/constellation the constellation renderer plugin (small wireframe solids on every surface)
mote-engine/components component registry (experimental)
mote-engine/element the <mote-scene> custom element
mote-engine/native native adapter transport (experimental)

Release notes

mote-engine 0.42

0.42 opens the engine to an AI. The package installs a second command, mote-engine-mcp: a local MCP server that drives a scene in headless Chrome, so a coding assistant or an agent can load a scene, look at it, stage it and render its frames — all as data, nothing it sends is ever evaluated as code. Working with AI has the one line to connect it.

Under it, three parts of the director's API are now public, and ASCII and Wireframe scenes still draw as in 0.41 — the director runtime loads only when you reach for it.

A runtime for scene operations. scene.applyOps(opsOrBatch) applies add, remove, set, animate, camera, stage, physics, timeline and render operations to a running scene — the vocabulary that was validation-only in 0.41. Every operation is appended to a capped log (scene.log()); with a stepped clock, replayLog() from mote-engine/director rebuilds any frame from it, bit for bit. A batch is validated whole and refused whole.

Observation. scene.describe() returns the running scene as a reloadable Scene JSON v2 document, with diagnostics and the assets it uses (each with a SHA-256 digest). scene.observe(cb) reports what happened on screen, and scene.project(point), scene.bounds(id) and scene.pick(x, y) answer where a point lands in the frame, where an object sits, and what lies under a pixel.

Scene JSON v2. createSceneFromJson(doc), from mote-engine/director, reads a version: 2 document — the richer shape describe() emits, carrying the camera rig, the clock, the timeline and the log. Version 1 is untouched: every 0.41 document still loads through sceneFromJson(), byte for byte.

mote-engine 0.41

0.41 adds a renderer that comes with the engine: constellation. It draws every object as small wireframe solids riding on its surface, in rows that run into its folds, coloured by how the surface turns towards you, and hides the far side. It is a renderer plugin, so it is mode: "custom"; the other modes draw as in 0.40.

import { createScene } from "mote-engine";
import { constellation } from "mote-engine/constellation";

const stars = constellation({ shape: "tetrahedron", spacing: 0.03, size: 0.0115 });
const scene = createScene(canvas, {
  mode: "custom", renderer: stars,
  stages: [{ items: [brain] }, { items: [world] }],
});

Morphs between any shapes. When the next stage's objects differ in topology, the solids of the leaving object fly over to places on the arriving one, each on its own arc. Renderer plugins can read the same transition through the new optional RendererItem.weight (0 to 1).

Burst. stars.burst (0 to 1, set at any time, from a scroll position or a clock) sends the solids flying off the surface, and brings them back.

Effects as solids. Particle effects are drawn in the same solid, very small; surface effects (dissolve, hologram, neon, gravity and the others) cut, tint and light the solids as they do the ASCII cells.

Options. shape (tetrahedron, triangle, cube, octahedron or your own corners and edges), spacing, layout (lattice or scatter), size, folds, depth, behind, stroke, spin, glow, pointer, drifters, colors and weight(u, v, w). Options are validated and copied; Canvas 2D alone, no GPU needed.

Wireframe. The GPU pass skips faces behind the nearest opaque one, and a fragment arena that fills no longer paints the frame magenta: it draws what fits and grows. Large meshes pulled apart by tornado or vortex stay fluid. stats().ray.wireframe reports the arena (fragments, capacity, overflow, edges).

mote-engine 0.40

0.40 gives a scene the controls a director needs. A clock that moves only when you step it, cameras that follow and orbit what is on the set, and a timeline that moves objects, lights, the camera and effects over time. Scenes that use none of it draw exactly as in 0.39.

Stepped clock. clock: { time, step } makes a scene whose time advances only by scene.step(frames), each step exactly step seconds. Two runs of the same steps give the same frames, the same physics and the same random numbers.

const scene = createScene(canvas, { mode: "ray", clock: { time: 0, step: 1 / 60 } });
await scene.step(30); // half a second, frame by frame

Camera rigs. scene.setCameraRig(rig) sets a camera the scene evaluates every frame, in every mode: static, path, lookAt, orbit and follow, with an optional fov, roll, handheld noise and a blend from the previous camera. In Ray a moving rig is motion, not a cut, so the picture stays clean while the camera travels. scene.camera reads the camera a frame drew; scene.cameraCut() asks for a hard cut.

scene.setCameraRig({ kind: "follow", target: "car", offset: [0, 1.5, 6], fov: 40, blend: 0.8 });

Scene timeline. scene.setTimeline(doc) installs tracks of keyframes over objects' transforms, visibility and materials, lights, the camera rig, exposure, zoom and effects' live parameters, plus named cues (timeline.onCue tells you when the playhead crosses one). The document is validated whole before anything changes (errors carry a JSON pointer), and playback allocates nothing per frame. The handle (scene.timeline) plays, pauses, seeks and sets the rate. Effects with live parameters (water, clouds, fog, smoke, wind, vortex, magnet) can be animated by the timeline; EFFECT_PARAMS marks them live.

const { ok, timeline, errors } = await scene.setTimeline({
  version: 1, duration: 8,
  tracks: [
    { target: "item:car", property: "position", keys: [{ t: 0, v: [-3, 0, 0] }, { t: 8, v: [3, 0, 0], ease: "inOut" }] },
    { target: "camera", property: "fov", keys: [{ t: 0, v: 50 }, { t: 8, v: 30 }] }
  ]
});
timeline.seek(2); // a motion, never a cut

New entry point. mote-engine/director exports the validators (validateSceneOps, validateTimeline) and the timeline compiler and sampler, for tools that prepare scene documents outside the page. The scene loads this code on demand, the first time a timeline is set, so pages that never use it do not download it.

The API change is additive. Behaviour to note:

  • An object with a dynamic body is kinematic while a timeline track holds its transform, then dynamic again at rest, as under animate.
  • The first setTimeline loads the director's code; scene.ready covers it.

mote-engine 0.39

0.39 makes Ray volumes hold their picture and makes mode switches cheap. Animated smoke keeps its temporal history, switching back to ASCII is instant, and a sliced scene no longer blocks the page while it resamples.

0.39.1 is the version to install. It draws the black hole in Ray exactly as 0.38 did. 0.39.0 moved that effect onto the public custom-shader parts and drew it wrong in real scenes (a sphere covering the disk a few seconds after the scene opened); 0.39.1 takes that change back, and nothing else. If you installed 0.39.0, update.

The API change is additive. A shader parameter declaration takes an optional history:

params: {
  time: { type: "f32", default: 0, min: -1e6, max: 1e6, history: "continuous" }, // a change keeps the history
  density: { type: "f32", default: 1, min: 0, max: 4 }  // "reset", the default: a change restarts it
}

"reset" is the rule until now: a written change rejects the temporal history of the manifest's volumes once. "continuous" declares a value that evolves smoothly from frame to frame, such as a clock; its changes keep the history, reprojected by the volume's advection. Any other value fails validation, and manifests without the field behave exactly as before. See Custom shaders.

Behaviour to note:

  • Animated smoke in Ray (speed other than 0) accumulates its temporal history again (its clock is history: "continuous"), and a step of Ray's adaptive internal scale no longer restarts the history of api: 1 volumes.
  • Switching a scene back to ASCII reuses its glyph pen's WebGL2 context instead of making a new one each time; at most 4 idle pens are kept on a page. Outside ASCII, after the scene has drawn ASCII, scene.glyphRenderer and stats().glyphRenderer may now read "gpu" (the kept pen) where they read "canvas" before.
  • A fireworks shell climbs from four radii of its own star below the edge, not four object-dot radii, so a larger particleStyle.size or a switch to ASCII no longer moves where shells start and burst.
  • A sliced scene (sliceLayout: true) no longer blocks the page while its stages are sampled again, for example while the particle count changes: the same points in the same order, computed in steps. GlyphParticles.spawn and the sparks burst no longer allocate for each random number; seeded and fixed-clock results are unchanged.

mote-engine 0.38

One scene API for every renderer. The scene function and its type no longer say ASCII, because the same scene draws in ASCII, Wireframe, Ray and your own renderer. The old names are removed, with no alias; TypeScript points at each use.

Before 0.38 0.38
createAsciiScene(canvas, options) createScene(canvas, options)
AsciiScene (and AsciiScene<M>) Scene (and Scene<M>)
AsciiArtOptions, AsciiDust (runArt) ArtOptions, ArtDust
AsciiBlocksOptions (runBlocks) BlocksOptions
renderer: "auto" | "gpu" | "canvas" (what draws the glyphs) glyphRenderer: "auto" | "gpu" | "canvas"
scene.renderer, stats().renderer, type Renderer scene.glyphRenderer, stats().glyphRenderer, type GlyphRenderer
<mote-scene renderer="canvas"> <mote-scene glyph-renderer="canvas">
mode: "toon", setMode("toon") (a plugin's id as the mode) mode: "custom", renderer: "toon", setMode("custom", "toon")

A renderer plugin draws in the new mode "custom". Give the scene the plugin, or the id it was registered with, as renderer:

import { createScene, registerPlugin, torusKnot } from "mote-engine";
import { createToonPlugin } from "./toon.js"; // your renderer plugin

const toon = createToonPlugin();
const scene = createScene(canvas, {
  mode: "custom", renderer: toon,
  stages: [{ items: [{ id: "knot", source: torusKnot(2, 3) }] }]
});
await scene.ready;

scene.setMode("ray");            // the same scene, traced
scene.setMode("custom");         // back to the renderer it was given
registerPlugin(toon);
scene.setMode("custom", "toon"); // or one registered by id

SceneMode is now "ascii" | "ray" | "wireframe" | "custom". While a plugin draws, scene.mode and stats().mode read "custom" and stats().rendererPlugin.id names the plugin; before, they read the plugin's id. A plugin's id as the mode still works as a deprecated alias, with the same choice and fallback. renderer now names mode custom's plugin and nothing else: given with any other mode it throws a TypeError that points old glyph code at glyphRenderer. In scene JSON, render.mode takes "custom" with render.renderer; on the element, <mote-scene mode="custom" renderer="toon">. "ascii", asciiScaleDensity and the ascii-scale-density attribute keep their names, because they act in ASCII alone.

In Ray, smoke() is now a 3D volume built on the public custom-shader volume contract: objects hide the plume and the plume hides them, with the camera inside or outside it. SmokeOptions.ray adds temporal and shadows (both on by default). ASCII and Wireframe draw smoke as before.

The natural lens flare draws a starburst of more, thinner rays: 30 for the default 6 blades instead of 18. The cinematic look is unchanged. In Ray on Chrome with Apple GPUs, mirrors show what is beside them again near their silhouette. ASCII picks the exact number of shadow casters among objects without a mesh, and effects in a scene without a fixed clock no longer allocate memory for each random number; seeded and fixed-clock results are unchanged.

mote-engine 0.37

Bring your own shaders. A ray manifest with api: 1 is a stable contract for the volume, light, post, unlit layer and lens part kinds. Existing api: 0 manifests keep working unchanged; changing only the number to 1 opts a manifest into the stability rules. validateRayManifest(manifest) checks a manifest on the CPU, without WebGPU, for authoring tools and build steps, and the part types (VolumePart, LightPart, PostPart, LayerPart, LensPart, SurfacePart) are exported from the package root. See Custom shaders.

A new surface part kind is available as a candidate of api: 1: Ray grows engine-made shells over one scene item and your WGSL decides each shell fragment's coverage and colour. The fur on the home page is built this way. A candidate may still change before it is frozen; ASCII and Wireframe draw the item's base mesh.

In ASCII, an object scaled up on screen keeps the density it has at its own size. This costs more samples; set asciiScaleDensity: false (or scene.asciiScaleDensity = false) on slow systems to keep the 0.36 behaviour. Objects without a mesh, such as point-sampled sources, are now drawn next to meshes in the same stage.

In Ray, settings that rebuild the scene no longer pause the page while the picking structures are rebuilt. In Wireframe and Ray, the heat haze, scanlines and glitch effects draw on the GPU instead of reading the canvas back every frame.

mote-engine 0.36

ASCII caches the constant part of each mesh sample between frames. When changing a raw texture, assign a new RawTexture or replace its pixels array so the renderer sees the change. Editing the same byte array in place leaves the cached image in use.

ASCII pages now load less JavaScript up front. Ray and Wireframe load the GPU rendering modules when requested. A Ray effect with a shader manifest also loads the experimental effect host. Keep the complete installed package together so its lazy imports resolve.

The built-in modes are "ascii", "wireframe" and "ray". Older Dots scenes should select a supported mode and move their independent particle settings to particleStyle. Toon is a renderer plugin. Register the plugin and follow its setup before calling scene.setMode("toon").

A first display-space capture now reads the same pixel values as subsequent captures of the same fixed-clock frame. Use the same browser, renderer, scene and clock when comparing frames.

First scene

Give the canvas a CSS size, then mount the scene when the element exists.

<canvas id="art" style="width: 100%; height: 360px"></canvas>
import { createScene, materials, torusKnot } from "mote-engine";

const canvas = document.querySelector("#art");
const scene = createScene(canvas, {
  mode: "ray",
  ray: { fallback: "ascii", samples: 32 },
  stages: [{ items: [{
    id: "knot", source: torusKnot(2, 3),
    material: materials.copper, motion: "tumble"
  }] }]
});
await scene.ready;
// Release the scene when its view is removed.
// scene.destroy();

Choosing a renderer

Look When to use it
ASCII Character-based surfaces, editorial graphics and a fallback on devices without WebGPU.
Wireframe Inspect indexed edges and hidden lines. Use the wireframe options for antialiasing and surface opacity.
Ray Trace reflections, refraction and shadows. Inspect scene.mode for the actual renderer after fallback.
Toon plugin Banded lighting, hatching and outlines from your own renderer plugin, drawn in mode "custom". The showcase uses an example plugin written against the experimental renderer API.

The material collection shows the same studio lighting on six physical surfaces. materials.glass and materials.diamond set different indices of refraction. Use ray.flare for an optical highlight in Ray mode, and scene.capture({ refined: true }) when a still frame should include the path tracer's accumulated samples.

Browser imports

If you have no build step, unpack the archive and serve the folder that holds index.js next to the rest of your site. An import map keeps the short name:

<script type="importmap">
  { "imports": { "mote-engine": "/vendor/mote-engine/index.js" } }
</script>
<script type="module" src="/app.js"></script>

Working with AI

mote-engine is built to be driven by code, which makes it easy to drive from an AI: a coding assistant that writes your scenes, an agent that directs the camera, or a training loop that needs a world it can reset. Three properties make that work.

Training worlds. The physical world API runs in Node.js without a browser: bodies, joints, ray queries and snapshots you can restore, for a learning loop that needs a world it can reset.

Giving an assistant the context. Point your coding assistant at the package's TypeScript declarations (node_modules/mote-engine/dist/**/*.d.ts) and the schemas above, and ask it to write scenes as JSON rather than as code. Then let it check its own work with sceneFromJson(), which needs no browser, before anything is drawn.

Driving it from outside the browser. The package installs a second command, mote-engine-mcp: a local MCP server that drives a scene in headless Chrome. A coding assistant or an agent — Claude Code, Claude Desktop or any MCP client — connects to it and loads, observes, stages and renders scenes as data, with the same validators and the same determinism. Connecting an AI over MCP has the one line to add it and the full list of its tools.

Scenes an AI can write

A scene written as JSON is checked whole by sceneFromJson(doc). It gives the options to make the scene with, or every error found.

{
  "version": 1,
  "camera": { "position": [0, 0, 4.2], "target": [0, 0, 0], "fov": 32, "width": 800, "height": 500 },
  "objects": [
    { "id": "knot", "shape": "torusKnot", "material": { "preset": "gold" } }
  ],
  "lights": [{ "kind": "environment", "preset": "studio", "intensity": 1 }],
  "render": { "mode": "ray" }
}
import { createScene, sceneFromJson } from "mote-engine";

const result = sceneFromJson(textFromTheModel);
if (!result.ok) {
  // Send these back to the model: each says where, what was expected and what was found.
  return result.errors.map((e) => `${e.path}: ${e.message}`).join("\n");
}
const scene = createScene(canvas, result.options);

An error reads like /objects/0/material/roughness must be a number from 0 to 1, not 2. Unknown fields are refused rather than ignored, so a model that invents an option finds out at once. Parsing never loads the models or maps a document names.

Directing a scene

An AI that directs a scene needs a clock it controls, a camera it can aim and a way to plan motion ahead. All three are in the engine.

import { validateTimeline } from "mote-engine/director";

const check = validateTimeline(planFromTheModel);
if (!check.ok) return check.errors; // JSON pointers again, e.g. /tracks/2/keys/1/t
const { timeline } = await scene.setTimeline(planFromTheModel);

validateSceneOps(), from the same entry point, checks a batch of scene operations against the same rules, with the same kind of errors: add, remove, set and animate on an object, a light or an effect, camera, stage, physics impulses, timeline and render. Since 0.42 the matching runtime is public: scene.applyOps(batch) applies it to a running scene, every operation is appended to scene.log(), and replayLog() (also from mote-engine/director) rebuilds any frame of a stepped scene from that log. Validation is bounded, so an untrusted document cannot make it run away: depth, nodes and size are capped.

Looking at the scene. An agent that acts needs to see. scene.describe() returns the whole running scene as a reloadable Scene JSON v2 document (the shape createSceneFromJson() reads back), with diagnostics and the assets it uses. scene.observe(cb) reports stage changes, cues and physics events as they happen, and scene.project(point), scene.bounds(id) and scene.pick(x, y) answer where a point lands on screen, where an object sits and what lies under a pixel. The same API drives the MCP server: an AI outside the browser does all of this through mote-engine-mcp.

Images for training. To build a dataset, combine a fixed clock with scene.capture(): the same scene JSON at the same time puts every object, light and camera in the same place, so keeping the document is enough to make the frame again. Your own code handles annotation and training.

Physical world API

The mote-engine/physics entry point runs in Node.js without a browser or GPU. It supplies rigid bodies, static and kinematic colliders, articulated joints, contact events, batch ray queries and deterministic CPU snapshots. Rendering is optional.

For a learning environment, your application defines the task, action space, observations, reward and episode boundaries. The engine advances the physical state. A policy can command a hinge through setDriveTarget() or setMotor(), or apply forces and impulses to a body. Use a fixed step such as world.step(1 / 60) independently of the display frame rate.

Operation Public API
Create the environment createPhysicsWorld({ jointSolver: "chain" })
Add objects and constraints world.addBody(spec), world.addJoint(spec)
Drive a joint hinge.setDriveTarget(radians), hinge.setMotor(speed, torque)
Move a kinematic body body.moveTo(position, quaternion)
Read physical state body.position, body.velocity, hinge.angle, hinge.angularVelocity, hinge.torque
LiDAR-style observations world.raycastBatch(origin, directions, range, distances)
Advance time world.step(dt)
Save and reset state world.snapshot(), world.restore(snapshot)

A snapshot restores into the same engine version and an identically configured world. Use the new body and joint handles returned by world.restore(snapshot). A miss in a batch ray query is NaN; the optional body-id output uses -1.

The physical-world lab shows recordings of an air dancer driven by seven hinge joints and a LiDAR sweep with measured distances. Download the adapter and episode loop from the training API section, keep them together in a project with mote-engine installed, and run:

node physical-training.mjs

The example adapter exposes reset(), step(action), observe() and scan(). Its action is seven joint targets in radians, clamped to ±1.2. Each action advances twelve 1/60-second steps. Observations contain joint angles and angular velocities; reward is the negative Euclidean error from the target pose. Success requires error below 0.06 radians and each joint speed below 0.15 rad/s. Episodes are truncated after 120 actions. The included controller asks for the target pose; replace it with your policy and training algorithm. No model training is bundled into the engine.

For visual observations, render a browser scene and call scene.capture(). Use sceneFromJson() to validate saved scene descriptions and a fixed clock to repeat a camera view. The vision gallery shows frames from different seeds. Your training code handles annotation, optimisation and model evaluation.

Scan an object in Node.js

The direction buffer packs XYZ triples. Both output arrays use the same ray order. Resolve body IDs to application labels such as a pallet, wall or moving target.

import { createPhysicsWorld } from "mote-engine/physics";

const world = createPhysicsWorld();
const target = world.addBody({
  type: "static", shape: { type: "sphere", radius: 0.5 },
  position: [0, 1, -2]
});
const labels = new Map([[target.id, "target"]]);
const rays = new Float32Array([0, 0, -1, 1, 0, 0]);
const distances = new Float32Array(2);
const bodies = new Int32Array(2);
world.raycastBatch([0, 1, 0], rays, 5, distances, { bodies });
console.log(labels.get(bodies[0]), distances[0]); // target, 1.5
console.log(bodies[1], distances[1]);             // -1, NaN
world.clear();

Quick start

<canvas id="art" style="width: 100%; height: 480px"></canvas>
import { createScene, loadGltf, cssColors } from "mote-engine";

const scene = createScene(document.getElementById("art") as HTMLCanvasElement, {
  stages: [loadGltf("/models/logo.glb"), loadGltf("/models/shield.glb")],
  colors: cssColors(), // reads --ascii-text and --ascii-accent
});

Each stage holds for five seconds, then the particles melt into smoke and gather into the next one. Add mode: "ray" and the models are drawn as solids with their own materials, ray traced with WebGPU (ascii where the browser has none); add physics: {} and objects with a body fall, collide and can be thrown. The canvas is sized by CSS; the drawing follows its size and the pixel ratio. Call scene.destroy() when the canvas goes away.

The <mote-scene> element

The same scene as an HTML element, for a page with no build step (a CMS, a static site): one script, then the element where the scene goes.

<script type="module">
  import { defineMoteScene } from "/vendor/mote-engine/element/mote-scene.js";
  defineMoteScene();
</script>
<mote-scene src="/models/logo.glb /models/shield.glb" mode="ray"></mote-scene>

In this example, the contents of the installed dist/ directory are served at /vendor/mote-engine/. With a bundler, register the element through the package export:

import { defineMoteScene } from "mote-engine/element";
defineMoteScene(); // or defineMoteScene("my-scene")

The element is 16:9 of its width unless the page sets its height, draws on a canvas in its shadow root (mote-scene::part(canvas)), and destroys its scene when it leaves the page; moved within the page (an editor reordering blocks), it keeps it. Its colours are --ascii-text and --ascii-accent, read on the element, so a page can set them for one scene.

Attribute
src the stages, one to each source, separated by spaces: a model's URL (.glb, .gltf), or shape:box, shape:sphere, shape:torus, shape:knot. Without it, a knot
motion turn (default), sway, steady, tumble, none, for every stage
mode ascii (default), ray (solids with materials, WebGPU; ascii where there is none, ray's chunk fetched only then), wireframe (the meshes' edges) or custom (the renderer plugin renderer names; without one, left out with a warning)
renderer with mode="custom", the id of the renderer plugin it draws with (registered with registerPlugin): <mote-scene mode="custom" renderer="toon">. With another mode it is kept for when the mode becomes custom
glyph-renderer auto, gpu or canvas: what draws the glyphs (ASCII's characters and the effects' glyphs), as the glyphRenderer option
morph-style, morph, hold as the options of the same names
autoplay autoplay="false" stays on the first stage
particles, max-particles, ascii-scale-density, font-size, zoom, halo, trails, smoke, interactive, ambient-ripples, reduced-motion as the options
color, accent the colours, over the CSS ones
label the picture's accessible name. Default 3D scene, which says nothing: give it
controls native buttons on the picture, as on a <video>: Previous, Pause or Play, Next, and the stage (2 / 3). Tab reaches them, Space and Enter press them, the left and right arrows step the stages from inside them. mote-scene::part(controls), part(control), part(status)
paused stopped. The picture stays, and survives a rebuild and leaving the page; el.paused is the same thing
label-pause, label-play, label-previous, label-next, label-controls the controls' words, for a page in another language

What the page writes inside the element is its text alternative, so the canvas is not the only channel: see Accessibility.

A boolean attribute is true when present and false as "false"; a value the option does not take is left out with a warning in the console. The scene takes src, motion, mode, morph-style, morph, autoplay, particles, max-particles, ascii-scale-density, font-size, zoom, renderer, glyph-renderer, color, accent, reduced-motion, paused, label, controls and the label-* words as they change; any other attribute, or one of the first ones taken away, rebuilds it on the stage it was showing.

From code:

const el = document.querySelector("mote-scene")!;
el.scene?.goTo(1);                          // the scene (null while the element is off the page)
el.stages = [{ source: box(), motion: "sway" }, loadGltf("/models/gear.glb")]; // in place of src
el.options = { effects: [snow()], click: explode() };                          // what the attributes do not cover; an attribute set wins
el.paused = true;                                                              // stops it, as the attribute does: use this rather than el.scene.pause(), it survives a rebuild
el.addEventListener("mote-ready", () => {});                                   // the sources of the latest load are in
el.addEventListener("mote-error", (e) => e.preventDefault());                  // one failed, or the scene could not start (e.detail); the content shows; without preventDefault it goes to the console

Scenes, stages and objects

A scene is a list of stages. A stage is one or more objects shown together, and the scene morphs from stage to stage. A stage can be written in three ways:

stages: [
  loadGltf("/models/monkey.glb"),                                   // a source: one object, turning
  { source: box(), motion: "sway", transform: { scale: 0.8 } },      // one object
  {                                                                 // several objects
    hold: 8,
    items: [
      { id: "left", source: torus(), transform: { position: [-0.9, 0, 0], scale: 0.5 }, motion: "tumble" },
      { id: "right", source: loadGltf("/models/gear.glb"), transform: { position: [0.9, 0, 0], scale: 0.5 } },
    ],
  },
]

The scene's space has y up, x to the right and z towards the viewer, as in glTF. One unit is half the smaller side of the canvas (times zoom, 0.85 by default). Every source is normalised to fit a sphere of radius 1, so an object at scale 1 fills most of the height of a square canvas, whatever its size was in Blender.

Moving between stages:

// createScene(canvas, { stages, stage: 2 }) starts on stage 2
scene.goTo(2);                 // morphs to stage 2
scene.show(0);                 // shows stage 0 at once, no morph
scene.morphStyle = "explode";  // "smoke" (default), "direct", "swirl", "explode"
scene.morph = 2.5;             // seconds a morph takes
scene.next();
scene.previous();
scene.autoplay = false;
await scene.setStages([...]); // a new list, resolves when the models have loaded
await scene.setStages([...], 3); // the same, showing stage 3 from the first frame
await scene.ready;            // every source of the current list loaded

Moving objects

Every object has a transform (position, rotation, scale) and a motion that runs on top of it.

const gear = scene.item("right")!;

gear.set({ position: [0.5, 0.2, 0], rotation: [0, 45, 0], scale: 0.7 }); // at once
await gear.animate({ position: [0, 0, 0.5], scale: 1 }, 1.5);           // eased, in 1.5 s
gear.motion = { spin: { axis: [0, 0, 1], speed: 40 }, tilt: 20 };       // degrees per second
console.log(gear.transform); // { position, rotation (quaternion), scale }

An object can be hidden and shown again where it is: gear.visible = false (or visible: false in its ItemSpec). Hidden, it is absent from the picture in every mode (no surface, shadow, reflection or Wireframe edge, and it hides nothing behind it), and pointer picks and scene.physics.raycast pass through it. Everything else goes on: its motion, its mesh effects, a morph in progress and its body, which is simulated and collides as before. Showing it rebuilds nothing.

For an animation of your own, change transforms in onFrame:

createScene(canvas, {
  stages: [...],
  onFrame: (t, scene) => scene.item("planet")?.set({ position: [Math.cos(t) * 0.5, 0, Math.sin(t) * 0.5] }),
});

Models from Blender

The reader takes glTF 2.0: .glb, or .gltf with its .bin next to it or embedded. In Blender use File › Export › glTF 2.0 with:

What is read:

Animations, armatures and shape keys are not read; textures are drawn in every mode: per pixel in ray and wireframe, as each glyph's colour in ascii (see Render modes), and in ray a model keeps its own materials (see Materials: Blender's Principled BSDF as glTF exports it, transmission, IOR, volume, clear coat and textures included). Points, lines and curves have no surface and are skipped; convert text and curves to meshes first (Object › Convert › Mesh).

Colours

Characters come in two colours by default: the theme's text colour, and the accent for every material whose name contains accent (for example accent, accent glass). With colors: "material" each material keeps its own base colour (converted from Blender's linear colour to sRGB), and accent materials still take the accent:

loadGltf("/models/rocket.glb", { colors: "material" });
loadGltf("/models/logo.glb", { accent: /blue|glow/i }); // which materials are accent
loadGltf("/models/scene.glb", { nodes: ["Gear", "Hub"] }); // only these objects (and their children)

loadGltf takes a URL, a File or Blob (a dropped file), or bytes. gltfSource(bytes) does the same without awaiting, and parseGltf, gltfMesh, gltfNodes and gltfMaterials give the parts on their own.

Size

A model is drawn with points spread over its surface by area, about half a character apart; small models need no more points than big ones. A mesh needs no particular resolution: a cube of 12 triangles and a sculpt of 500,000 both work. Above 80,000 points the spacing gets coarser (sample: { maxPoints }). For a fast first load, keep .glb files small: decimate dense sculpts in Blender (Decimate modifier) before exporting.

Other sources

Built-in shapes, as meshes: box(w, h, d), sphere(), torus(major, minor), torusKnot(p, q), cylinder(radius, halfHeight) and cone(radius, halfHeight) (around y, centred halfway up the axis; the cone's apex up), blocks() (a 3 × 3 × 3 cube of blocks), and the mesh builders boxMesh, sphereMesh, torusMesh, cylinderMesh, coneMesh, tubeMesh(curve).

The cylinder uses the physics engine's cylinder collider convention (axis y, radius, halfHeight; 32 sides by default, at the angles of the prism the collider collides as). Like every source it is fitted to the unit sphere, so its radius is Math.hypot(radius, halfHeight): give the object that scale and a body { shape: { type: "cylinder", radius, halfHeight } } and the drawn surface and the collider coincide.

Flat drawings extruded into solids (browser only):

extrudedPath("m12,1.5 l9.265,4.344 v3.621 s-0.475,9.052,-9.265,13.035 C2.735,18.517,2.735,9.465,2.735,9.465 v-3.621 L12,1.5 Z", { viewBox: [24, 24], depth: 0.17 });
extrudedText("hello", { weight: 800 });
extruded((ctx) => { ctx.fillStyle = "#f00"; ctx.fillRect(0, 0, 10, 10); }, [10, 10]);

What is painted red (#f00) is drawn in the accent on the front face.

Your own meshes: meshSource({ positions, indices, normals?, slots?, palette? }). The figures of the day's occasions, as the 404 page shows them: seasonSources(date, seasons, { religious: false }) (without religious: false, the religious feasts and symbols in RELIGIOUS_SEASONS are included). Effects on any source: crumbling(source, at, blend, side) turns one side into flickering dust that sheds glyphs.

Render modes

A scene draws its objects in one of three modes: ascii, ray, and wireframe, or with a renderer plugin of the application's (custom, below). The scene is one: the objects, their motions, the rigid bodies, the morphs, the effects and the clicks are the same whatever draws them, and the mode only decides how they look.

const scene = createScene(canvas, {
  stages: [loadGltf("/models/city.glb")],
  mode: "ray",                                // "ascii" (default), "ray", or "wireframe"
  ray: { quality: "auto", toneMapping: "agx-punchy" },
});
scene.setMode("ascii");  // the other way from the next frame, the same owned mesh and effects continue
scene.mode;              // "ascii" | "ray" | "wireframe": what draws now (ray asked for where it cannot be: its fallback)
registerPlugin(toon);
const scene = createScene(canvas, { stages, mode: "custom", renderer: "toon", ray: {} });
scene.setMode("ray");
scene.setMode("custom");             // back to the renderer it was given
scene.setMode("custom", otherPlugin); // or another one, by id or object
scene.mode;                          // "custom"; scene.stats().rendererPlugin says which plugin, its state, and why the scene fell back from one

mode: "custom" with no plugin given throws a TypeError, as does setMode("custom") on a scene never given one, or a renderer with any other mode (in the options or in setMode). An id nobody registered draws as ascii, stats().rendererPlugin.reason saying renderer "…" is not registered (the rule unknown ids always had), and a plugin that fails goes along its fallback chain, which ends at ascii. What draws the glyphs is a separate option, glyphRenderer, in every mode. Before 0.38 the plugin's id was itself the mode (mode: "toon"): still accepted, deprecated.

The studio scene drawn in ASCII: a warm field of shaded characters.

Ray

The studio scene in Ray: a glossy sphere, a coral knot and a glass ring, with traced reflections and a soft floor shadow.

Ray mode draws a hybrid frame, built for fluidity first. The solids are rasterised into a G-buffer, and rays are traced from it through a bounding volume hierarchy (built once per mesh on the CPU; the scene's objects in a top-level tree every frame, the traversal on the GPU): shadow rays towards the lights (soft, from their size), a reflection ray, refraction chains through glass, water and diamond (with the volume's absorption, and dispersion), ambient occlusion and the environment. The light is traced at an internal resolution (three-eighths to full, per side) and cleaned by a denoiser (an edge-avoiding à-trous filter of each frame, which keeps mirrors and clear glass sharp, then a temporal accumulation at full resolution); the geometry, textures and Fresnel come from the full-resolution G-buffer, and temporal antialiasing resolves the picture at the canvas's size, so a change of internal resolution keeps the history. A tone curve maps the HDR picture to the screen. When nothing moves the picture is held and refined, up to ray.samples samples, and then the GPU rests.

Light bounced off the other objects (indirect light) is found first by rays marched across the screen (against the depth buffer, reading the light the previous frame's denoiser filtered spatially, before any accumulation over frames, after McGuire and Mara, "Efficient GPU Screen-Space Ray Tracing", 2014). Where such a ray leaves the screen or passes behind a surface, it reads a cache of probes laid over the objects in world space (an irradiance volume, Greger et al. 1998, of spherical-harmonic probes, Ramamoorthi and Hanrahan 2001), a few of them traced again each frame and reused across pixels and frames (the principle of irradiance caching, Ward et al. 1988). Rough reflections and frosted glass read the same cache, so they stay calm in motion.

The still picture. When nothing moves, ray refines the held picture with a path tracer: the same scene and materials, every light and the environment sampled at each bounce and weighed against the surface's own sampling (multiple importance sampling, Veach and Guibas 1995), glass crossed by its Fresnel coin flip (a glass ball focuses a light into a caustic), dispersion with each pixel's wavelengths spread evenly over the spectrum. It takes as many samples a pixel a frame as fit in what the rest of the held frame leaves of one 60 fps frame's budget (12 ms of the GPU's time at most, whatever the page's rate: a frame drawn after a held one, an effect starting over the still picture, never waits behind a longer one; the held frame is timed whole, with what is drawn over it, while the path tracer refines it and whenever particles (with the pass that lights them), the effects' look over the solids (glyph hooks, ripples), a post pass (halo, bloom, lens) or the water are drawn over it, refined or not (a refined picture with nothing drawn over it is not timed); the readings size the path tracer's share and show in stats().ray, and copies back the solids' depth kept when it was first held rather than drawing them again), so effects animating over a still picture stay smooth; on large canvases a sample is spread over up to 256 frames (the next run of a 16 × 16 ordered dither's values a frame, as many as its share holds); the scene paints a still picture at its idle rate (ambientFps, 30 a second by default) whether the path tracer refines it or not, as any resting frame (the hold never changes the paint rate: while an effect moves, every frame is painted, as always); once it is refined the GPU is nearly at rest (the picture copied, nothing traced); always at the full resolution, each sample's random numbers independent (a pixel converges to its own picture, not a pattern). What is shown blends its running mean over the hybrid's picture by how sure the mean is: per pixel, from that pixel's own mean and the hybrid's picture there alone, the mean's variance against how far it stands from the hybrid's (a shrinkage weight), at least a share that grows to the whole at ray.samples; so the picture shown is never further from the converged one than the hybrid's own, and the path tracer's alone at the end. The hand-over is a fade (a pixel moves by a level or two a frame at most on the screen, in the dark as in the light; the objects' silhouettes go over to the path tracer's own coverage too), so a still picture never flickers while it refines. A path's radiance is clamped at a luminance of 256 (the rare far brighter paths, a small light found through glass, are cut there), and while samples gather, a mean its own samples disagree on (a firefly: one sample far above the rest) is shown no brighter than that mean without the stray sample, about, or a little over the hybrid's picture there (a first sample alone, at most four times it), the limit loosening as samples gather and gone at ray.samples; the mean itself keeps it. Above the device's largest storage buffer (24 bytes a pixel) a still picture is not path traced: a console warning, once, stats().ray.pathTracer is "off" and stats().ray.samples stays 0.

Refinement costs power. Until a still picture is refined the GPU works every frame painted, up to one 60 fps frame's budget each: on the budget scene (Performance) that is minutes at the idle rate of 30 a second, where a GPU that clocks down under that steady load reads each held frame up to twice as long, so the path tracer gets fewer samples a frame. On a page read on a laptop or a phone, ask for fewer samples (ray: { samples: 64 }), or none (samples: 0: the hybrid's picture is held as it is, and the GPU rests at once); a page that wants the picture refined sooner paints faster at rest (ambientFps: 60, the idle rate of every resting frame, refined or not). Refined, the GPU only copies the held picture, about 2 ms a frame.

Fast screens. On a screen faster than 60 Hz, ray paints its busy frames (an effect, a morph, a touch) every n-th refresh, the most refreshes apart that still give at least 60 paints a second (a screen a little slower than n × 60 Hz, by up to 6 Hz, counts as n × 60 Hz and paints a little under 60 a second: 5 % slower at 120 Hz, 2.5 % at 240, about 1.7 % at 360; at 119.9 Hz, every other refresh, 59.95 a second), evenly spaced: 75, 90 and 100 Hz, every refresh (75, 90 and 100 a second); 120 Hz, every other (60); 144 Hz, every other (72); 165 Hz, every other (82.5); 240 Hz, every fourth (60); 360 Hz, every sixth (60). ASCII and Wireframe paint at the screen's own rate. The refresh is the shortest recent interval between animation frames. auto's budget is the period painted at when that is shorter than a 60 fps frame (90 Hz: 11.1 ms; 144 Hz, two refreshes: 13.9 ms), and the 60 fps budget otherwise: the period only tightens ray's budget, never relaxes it, so a page whose animation frames come at 30 a second (a battery saver) still budgets each frame for 60 fps. A frame budgeted for 60 fps is not asked for at every refresh of a fast screen, so the GPU is not saturated and no frame comes late or unevenly. In both modes the bodies and the particles in flight are drawn where they are at each painted frame's own time (interpolated between the fixed 60 Hz steps: Physics), so motion is smooth either way, at 60 to 100 paints a second in ray and at the screen's rate in ascii.

Quality. quality: "auto" (the default) holds the frame rate on two axes, and a last resort, from the GPU's time of the whole frame: from its first pass through the last pass drawn over the solids (the effects' particles, the halo and bloom), then the tone curve's own time (not the wait between for the canvas to come back from the screen). The internal resolution is continuous: it is chosen again every frame from the time of the newest frame that completed (the passes at the internal resolution apart from those at the canvas's, so the cost per pixel is known), in steps of 1/32 within the lighting tier's range, aiming at 12.45 ms (a quarter of a 60 fps frame left for the page, the compositor and a frame's spread) with a band of ±10 % that keeps it from hunting, and it is applied at once; while the picture is still the resolution does not rise (it falls if even the still picture is over the band). The lighting tier (ambient occlusion, secondary shadows, the second glossy ray, the indirect light's screen rays and probes, the shadow rays) changes only on a sustained run, counted: a reading over the band even at the tier's smallest resolution counts up (by more when it is far over), one within it counts down, and at a count of 30 readings the tier steps down, at once to the tier that reading says fits (several at once when far over); a reading over the frame's whole budget (16.6 ms) counts at least 2 (at lowest, where the count drives the output, it counts as itself); up after 120 readings in a row in which the next tier would fit. A climb the load takes back soon is not tried again as soon: a step down past a tier entered less than 480 frames before doubles that tier's wait before it climbs again, up to 960 readings (16 s at 60 fps), and a climb that holds 480 frames (8 s) sets its wait back to 120 (2 s); each tier keeps its own wait, and asking for auto again starts them over. So a load that comes and goes (4 s light, 4 s heavy) changes the tier a few times in ten minutes, not every cycle. One slow frame never changes it, except once at the start: the first reading from the fourth frame on (the first frames fill caches and make their pipelines: the budget scene's first one read 36 ms of passes that take 4) far over twice the band takes auto straight to a tier that fits. Only the GPU's time drives it (timestamp queries where the device has them, the submission's time otherwise), never how the picture changes. A fixed quality fixes the tier and lets the resolution move within that tier's range, aiming at the same 12.45 ms for the whole frame (so heavy effects drawn over the solids lower its resolution too), and a still frame over the band lowers it as well (never raises it); on a scene heavier than its smallest resolution can hold, it may exceed the frame's budget. Below low, auto alone goes to lowest; and when even lowest at its smallest resolution stays over the band on the same count, the last resort: the whole frame drawn at half the canvas's pixels per side (at a pixel ratio of 2, the page's own resolution; the solids and the effects' dots alike, stretched to the canvas: a last resort, for weak GPUs; the page's text stays sharp; stats().ray.output is 0.5), back to the whole once lowest would fit at it for 120 readings in a row (its cost at the whole output from the capped one by their ratio measured across the step: a frame's fixed costs do not shrink with its pixels), then the tiers up as before. And after 240 readings at half the output the whole is tried: its first steady reading measures the ratio anew (from the third frame at the whole output: each change of output makes the frame's textures again, and its first two frames read more than the output costs; on the budget scene 22.5 and 10.0 ms, the third 8.8, then 8.3), and over the band the half output is back at once and the next trial comes twice as late (240, 480, 960, then every 1920 readings: 4, 8, 16, then 32 s at 60 fps). For 240 frames after any return, three readings over the band in a row take the half output again at once (a load in bursts: a few frames over, not the counter's 30; the odd slow frame of a load the whole output holds does not) and the next return waits at least twice as long, up to 1920 readings (32 s at 60 fps); so it does when the counter reaches 30 first in those 240 frames (readings over the band one or two in a row, never three). So no reading, however far off, holds the output down for more than 1920 readings (32 s at 60 fps). Bursts that come within 240 frames of a return keep the half output between them (the return cut short, the next held longer); bursts further apart than that still take the half output once each and give it back after (two to four changes a burst: 40 frames at twice the load every 400, 100 changes in 20,000 frames). Each trial, and each change of output, costs a short shimmer: the antialiasing's and the denoiser's histories start again with the new textures (a few frames noisier, as after a cut), and the first frame at the new output takes longer (on the budget scene, 22.5 ms against 8.3 at the whole output, 6.8 against 4.5 at half); a trial that finds the line still crossed shows about four frames at the whole output, over the budget. A canvas resized makes the frame's textures again too, and its first two frames' readings are left out alike: a window's edge dragged for seconds does not walk auto down its tiers or halve the output on those frames' readings. The tiers:

Quality Internal resolution Ambient occlusion Secondary shadows Glossy rays Refraction interfaces Indirect light
lowest (auto only) 0.375 to 0.5 no no 1 4 the probe cache (64 a frame); one shadow ray a pixel instead of one a light (to a light drawn by its share of the light, its visibility standing for all of theirs: exact where every light is seen or none, noisier in partial shadow), and the shadow catcher reflects nothing; the effects' particles one shadow ray each, the same way
low 0.5 to 0.69 no no 1 4 the probe cache (64 probes traced a frame); the effects' particles one shadow ray each, to a light drawn by its share
medium 0.5 to 0.81 yes no 1 6 the cache (128 a frame)
high 0.59 to 0.94 yes yes 1 6 1 screen ray a pixel, then the cache (192 a frame)
ultra 0.75 to 1 yes yes 2 on rough surfaces 6 2 screen rays, then the cache (384 a frame, twice the rays each)

auto starts at high.

Options (SceneOptions.ray; scene.setRay(options) changes them while the scene runs, fallback apart, and scene.ray reads the ones in effect):

Option Default
quality "auto" "auto", or "low", "medium", "high", "ultra" (above)
samples 512 the most samples a still picture refines to; 0: never refined (the hybrid's picture held, the GPU at rest at once: for battery-sensitive pages, a lower count or 0)
exposure 0 in stops
flare off the lens flare: true, or { kind, look, intensity, blades, ghosts, streak, veil, tint, squeeze, sources }; see the lens flare
toneMapping "agx-punchy" AgX with a contrasty look (coloured light, a fire's, keeps its colour); "agx" (AgX's base look: bright colours go pale towards white), "aces", "neutral" (the materials' colours kept), "none"
floor a shadow catcher, when the scene has a floor shadow or a physics floor true or { y, catcher, material, shadow, reflect }: y defaults to just under the objects (to the physics floor, with physics); a catcher (the default) is invisible but for the shadows and reflections that fall on it, over the page; otherwise a surface of material; shadow how dark its shadows are (0 to 1), reflect how much it mirrors the objects (0 to 1); false: none
fallback "ascii" the mode drawn where WebGPU is not, or "wireframe"
scene.setRay({ exposure: 1, toneMapping: "neutral" }); // from the next frame, same device and renderer
scene.setRay({ flare: { kind: "anamorphic" } });       // the lens flare, on and off the same way
scene.setRay({ ...scene.ray, quality: "high" });      // what is in effect, one thing changed

A value it does not know (an unknown quality or curve, an exposure that is not a finite number, samples that are not a finite number from 0, a floor's y that is not a number or its shadow or reflect outside 0 to 1, another fallback) throws a TypeError with a message and changes nothing; the options given when the scene is made are checked the same way (createScene throws). While the scene draws another mode, the options are kept for when it is in ray.

WebGPU and the fallback. Ray needs WebGPU: Chrome and Edge from 113 on Windows, macOS and ChromeOS, and from 121 on Android 12 or later (Qualcomm and ARM GPUs); Safari 26 (macOS, iOS, iPadOS, visionOS); Firefox from 141 on Windows and from 145 on Apple silicon Macs with macOS 26. On Linux, Firefox on Android and Intel Macs it is still coming, GPU by GPU or behind a flag, so check rather than assume: the scene does. Where there is none (no navigator.gpu, no adapter, a device refused, no WebGPU canvas context), the scene draws ray.fallback from the first frame: scene.mode says so, and stats().backend says why (webgl2 (ray fell back: no WebGPU here (navigator.gpu missing))). The first time, ray loads its side and waits for its device before it draws (scene.ready too).

Loaded when needed. Ray's side (the renderer, its passes and shaders, and the points' rasterizer that draws the effects' particles in ray and wireframe) is loaded with import() the first time a scene asks for ray or wireframe, the custom-effect host (the ray manifests' validator and compiler front, see custom shaders) the first time ray runs an effect with a manifest, the public CPU validator the first time validateRayManifest is called, and the rigid bodies' world (about 145 KB) when a scene has physics; an ASCII page that does not call the validator never downloads any of them. With a bundler that splits chunks (esbuild, Vite, webpack, Rollup) they are chunks of their own: a page that imports createScene alone takes about 283 KB minified (112 KB gzipped) up front with esbuild (plain build, measured after 0.35.0). Until ray's side is there nothing is drawn in ray (as while its device is asked for) and scene.ray and setRay work as always; if it cannot be fetched (a network error, a chunk missing), the scene falls back to ray.fallback and draws, stats().ray.fellBack says ray did not load (…), and the browser keeps the failed module: ray is not tried again until the page is reloaded (a bundler's own chunk loader may fetch it again on the next switch to ray); until the world is there the objects with a body stay where they are placed, and scene.physics and item.body keep what is set and called on them for it. The world on its own (createPhysicsWorld) is mote-engine/physics. A device lost later is asked for again, and ray comes back on the new one. destroy() releases every buffer and texture, and a scene destroyed while its device is still being asked for makes nothing. Shaders and pipelines are kept per device: switching back to ray, or a second ray scene on the page, compiles none again.

Heavy models. Objects own their geometry in all three modes. Ray prepares the indexed mesh, retained BVH and GPU arenas before scene.ready resolves. Vertex data uses 80 bytes per packed vertex, including immutable rest coordinates; a deformation refits the existing hierarchy and updates retained buffers rather than replacing the source. Large animated imports still have a synchronous deformation/refit cost: measure it for the intended model and viewport. Wireframe can explicitly simplify its preview with lowPoly; Ray and physics continue to use the full source. Texture uploads remain budgeted, with material factors used until images arrive.

Mesh effects. Each object owns its modified indexed mesh. Ordered vertex hooks deform that geometry; normals and tangents are rebuilt and the retained BVH is refitted before tracing. Continuous surface programs evaluate cuts, coats, tint and emission at each actual intersection, including a hole smaller than one triangle. Primary, reflection, shadow and transmission rays share that coverage. Free dust, snow and sparks are independent emitters: their count never controls whether an object exists. Geometry and surface revisions invalidate temporal history. keepClear masks only the final picture under page text; it never removes physical shadows or material.

Stats. stats().ray gives the GPU's time a frame (gpuMs: the whole frame, the effects drawn over the solids and the tone curve included; held frames while the path tracer refines them or while anything is drawn over them: an effect's particles and the pass that lights them, the effects' look over the solids (glyph hooks, ripples), the halo, the bloom, the lens, the water; a refined picture with nothing drawn over it is not timed, so gpuMs keeps its last reading then; a reading arrives every frame or two, some frames late: readings counts them, so each is counted once), the lighting tier it was drawn at, the internal resolution's scale, the share of the canvas per side the frame was drawn at (output: 1 at usual sizes, 0.5 at auto's last resort, less past the device-pixel ceiling or the device's largest texture: Memory), the path tracer's samples (0 while anything moves) and whether it can run at this size (pathTracer, "on" or "off"), the probes traced again last frame (probes), whether the picture is refined (held, its samples gathered and faded in: nothing more will change ray's picture of the objects, so with nothing moving the canvas no longer changes from that frame on; it comes when the fade's longest schedule ends, which can be some frames after the last visible change, never before; where the path tracer does not run (pathTracer "off", or samples: 0) the final picture is the hybrid's held one, refined from the first held frame with samples 0; effects, particles or water moving over the still objects change the canvas whether it is refined or not), the objects drawn solid, and, in the fallback mode, why ray fell back (fellBack, "" when it did not).

Wireframe

The studio scene in Wireframe: glowing indexed mesh edges on a dark background.

mode: "wireframe" draws the edges of the actual indexed mesh. A triangle depth prepass hides rear edges, including across continuous cuts and alpha textures. A scene draws Wireframe with WebGPU, through ray's lazily loaded module and its device (stats().backend reads webgpu-wireframe); where there is no WebGPU it falls back to ascii, as ray does, with the reason in stats().ray.fellBack. The renderer option selects the ASCII/emitter backend.

Use the Render tab's Scene inspection controls, or configure the scene directly:

scene.setWireframe({
  lowPoly: 0.7,               // 0: original; 1: coarsest preview
  surfaces: "transparent",  // "hidden", "solid", "transparent"
  surfaceOpacity: 0.25,
  edges: true,
  hiddenLines: false,        // X-ray view of occluded edges
  lineWidth: 1,
});
scene.setMode("ray");        // full geometry, same scene and camera

The same options can be supplied as SceneOptions.wireframe or JSON render.wireframe. scene.wireframe returns the current settings. The demo remembers them across reloads and rebuilds. Low poly clusters vertices in rest space and removes collapsed faces; it is an approximate inspection view that can lose small features. It never edits the source, effect state or physics colliders. Set lowPoly: 0 to inspect exact topology.

Wireframe includes triangulation diagonals. It does not trace reflections or refraction, or add a contour around a newly cut boundary. Edges use material colours and emission; visible faces have flat preview shading by default, and smoothSurfaces: true interpolates the vertex normals instead. The inspection buffer is capped at 524,288 pixels and scaled to the visible canvas, including on Retina displays. Coverage, depth and alpha are worked out in the GPU's fragment shaders, into a fragment pool sized to the buffer, so the cost grows with the fragments covered, on the GPU. Use measured frame costs for large imported models. Sources without an indexed mesh() choose a whole-scene ASCII fallback before readiness, with the reason available in stats.

The lens flare

Off unless asked for: what a camera's lens adds round a strong light, in Ray only (ASCII and Wireframe ignore it, and do not load it). ray: { flare: true } turns on the natural look, faint as in real footage; look: "cinematic" is the stronger one, and kind: "anamorphic" swaps the iris's spikes and round ghosts for a thin horizontal streak and oval ghosts.

createScene(canvas, {
  mode: "ray",
  lights: [{ kind: "environment", preset: "sunset", background: true }],
  ray: { flare: { kind: "spherical", look: "natural", blades: 6 } },
});
scene.setRay({ flare: false });

Two kinds of source flare. Every bright pixel of the frame's emission (glowing surfaces, sprites, the black hole's disk) gets a little: the veil, screen ghosts, and spikes or streak. Up to 8 key sources get all of it, faded by how much of them the objects hide and tinted by glass (32 rays through the scene a key, a frame): the environment's sun while its background shows, the effects that declare one (the black hole, fireworks), and your own in flare.sources, { x, y, intensity, color, z?, size? } in canvas pixels, read every frame. A sun out of frame still veils the picture and throws ghosts in, up to 25° past the edge. intensity, ghosts, streak and veil run from 0 to 4. The flare is added before the tone map, reads only this frame's light, and costs nothing while off. It is drawn over the whole frame: unlike the halo and the bloom it does not keep to the room text leaves, and it does not protect DOM text laid over the canvas. Keeping that legible is the page's job, with a text shadow or a soft scrim. The sun is found in a map only at 100 or more, and 50 times the map's mean, so a dim map has no key source. At the low and lowest tiers only the key sources draw.

Toon

The studio scene drawn by the Toon renderer plugin: inked outlines and flat bands of light.

A renderer plugin draws the very same scene — the objects, their lights, motions and effects — in a look of your own. The Toon look on motedrift.com inks the outlines and lays flat bands of light over the geometry the built-in modes draw. It runs as mode: "custom" with the plugin as the renderer; setMode("custom", "toon") switches to it and setMode("ray") back, the scene unchanged. The engine ships the plugin API, and this look is an example of it.

Constellation

A brain covered in small wireframe tetrahedra, drawn by the constellation renderer.

The engine's own renderer plugin, mote-engine/constellation, covers each object with small wireframe tetrahedra that ride its surface and run in rows into its folds, turning amber where the surface faces away. Change the stage and the solids fly from one object to the next; effects draw in the same solids, and burst sends them off into the dark or brings them home. It draws in Canvas 2D, so it needs no GPU.

import { createScene } from "mote-engine";
import { constellation } from "mote-engine/constellation";

const scene = createScene(canvas, {
  mode: "custom", renderer: constellation({ shape: "tetrahedron" }),
  stages: [{ items: [brain] }, { items: [world] }],
});
scene.next();   // the solids fly to the next stage

Particles effects

particleStyle configures independent emitters: size, bloom, focus, aperture, haze, custom sprites, and a custom emitter adapter. It never changes object coverage. particles controls ASCII sampling density: the objects of a stage share it, and an object larger on the screen than at its own size (scaled up, or nearer the camera) takes as many more samples as its surface grew there (in steps of 2^(1/4), within maxParticles; stats().particles counts them), so it keeps the density on screen it has at scale 1. That costs what the samples cost: on top of the 0.36.0 sample cache, Suzanne at scale 2.4 takes 90,509 samples and about 5 ms more a frame (headless Chrome, M3 Max); maxParticles caps it. asciiScaleDensity: false (attribute ascii-scale-density="false", live as scene.asciiScaleDensity) turns the growth off for slow systems: each object keeps its share of particles whatever its size, and a big one draws paler and thinner. Ray and Wireframe object coverage is independent of particle density; only the explicit Wireframe lowPoly setting simplifies preview geometry.

The actual EffectFrame.mode is ascii, ray, or wireframe. Object effects use Effect.mesh: per-object prepare, ordered local-space vertex, continuous surface, and dispose(objectId). ASCII samples the resulting geometry and material after those hooks. glyph is presentation decoration, such as Matrix characters or scanlines. draw emits independent particles and overlays; worldAt, projectWorld, and unprojectWorld connect screen triggers and world anchors. Legacy custom object particle callbacks and explicit Dots mode are rejected with migration diagnostics. The demo converts saved Dots preferences to Wireframe and retains unrelated preferences.

Equal-topology stage transitions interpolate actual vertices. Different topologies crossfade two real meshes; interrupted transitions retain the current geometry and weights. Physics colliders remain rigid: visual vertex deformation does not rebuild them each frame.

Materials

In ray each object is drawn with physical materials: glTF's metallic-roughness model with the extensions Blender's Principled BSDF exports. A glTF model keeps its own materials (a material picked as the accent takes the theme's accent); shapes and extrusions take their colour slots' (the theme's colours), matte. ItemSpec.material gives an object one material for all its surfaces, or a map of its glTF materials' names to the ones that replace them (the others kept), and item.material changes it while the scene runs (from the next frame; undefined for its own; anything but an object is refused). A material is read by identity: changing a field of one in place is not seen, so give a new object (item.material = { ...m, roughness: 0.2 }). So is a texture's image: a RawTexture's bytes changed in place (the same object, the same pixels array, length and size) are not seen, in ray (it uploads a source once) nor in ASCII (it keeps what it sampled until the texture, the map or the material changes); give a new RawTexture or a new pixels array. An <img>, a canvas, or a RawTexture whose width, height or pixels is a getter of your own (on it or its prototype, from the frame it is there) is read again for every sample of every frame in ASCII, as before. ASCII and Wireframe consume the same current mesh/material fields; independent particles keep their own colours. In a browser loadGltf decodes the images ray's materials use the first time ray draws them (until then a map is drawn with its factors alone, as while an image loads): ASCII and Wireframe decode the textures they sample. A scaled node's volume (thickness, attenuation distance) is scaled with it.

import { createScene, materials, loadGltf, sphere, torusKnot } from "mote-engine";

const scene = createScene(canvas, {
  mode: "ray",
  stages: [{
    items: [
      { id: "ball", source: sphere(), material: materials.glass, transform: { position: [-0.6, 0, 0], scale: 0.45 } },
      { id: "knot", source: torusKnot(2, 3), material: { ...materials.gold, roughness: 0.35 }, transform: { position: [0.6, 0, 0], scale: 0.45 } },
      { id: "car", source: loadGltf("/models/car.glb"), material: { paint: materials.plastic("#c01818") } }, // by glTF material name
    ],
  }],
});
scene.item("ball")!.material = materials.diamond;

Presets (materials; the ones that take a colour accept linear RGB or CSS):

Preset
glass, frostedGlass, water, diamond clear solids traced through their volume: glass (IOR 1.5, a faint green through its depth), frosted (a mottled rough surface), water (IOR 1.333, blue-green), diamond (IOR 2.417, dispersion)
chrome, gold, copper, aluminium, brushedSteel metals, their colour the measured reflectance; chrome a true mirror, brushed steel streaked in colour and roughness
plastic(color), rubber(color), ceramic(color) a smooth plastic, a matte rubber, a glazed ceramic (a clear glossy coat)
marble, wood polished white marble with grey veins (under a clear polish); honey oak: flat-sawn white oak, two boards glued edge to edge (cathedral arches and straight rift grain, uneven growth rings, open pores in relief, rays, a pin knot) under a satin varnish, with its colour, normal and roughness maps
emissive(color, strength) a surface that gives light, as a neon tube: a dark glassy body glowing in color (the bloom makes it shine)

Every texture of the presets is made procedurally (seamless 512 × 512, the same bytes every time) and kept; no image ships. Reading a preset that uses one returns at once and starts its work, which runs a slice of about 8 ms at a time between the page's own tasks (no long task); until it is done the preset's maps are empty (0 × 0) and ray draws it with its factors, then from the next frame with its textures. The wood's three maps take about 150 to 200 ms of work in all on an M3 Max, marble's about 90 to 120, and the wood holds 3 MB (4 MB on the GPU with their mips). To have them ready:

import { finishTextures, materials, texturesReady } from "mote-engine";

const wood = materials.wood;   // its maps empty for now, their work started
await texturesReady();         // a page: the slices done, wood.map.image is 512 × 512
finishTextures();              // Node, offline: done at once (nothing left here)

The wood, in detail:

import { materials, type Material, type TextureMap } from "mote-engine";

// The oak moved by `offset` (and scaled): one per object, so no two crates look alike.
const woodAt = (offset: [number, number], scale: [number, number] = [1, 1]): Material => {
  const w = materials.wood;
  const moved = (m: TextureMap): TextureMap => ({ ...m, offset, scale });
  return { ...w, map: moved(w.map!), normalMap: moved(w.normalMap!), occlusionMap: moved(w.occlusionMap!), metallicRoughnessMap: moved(w.metallicRoughnessMap!) };
};
scene.item("crate-2")!.material = woodAt([0.37, 0.58]);
scene.item("crate-3")!.material = woodAt([0.71, 0.12], [1.25, 1.25]);

A flip (a negative scale) mirrors the image, but a normal map's relief keeps the mesh's own tangent frame: flipped across the grain (scale: [1, -1]) the pores' grooves light as ridges. Prefer offsets.

A material (Material; colours are linear RGB or CSS, lengths scene units):

Field Default
color, map white base colour, and a texture that multiplies it (its alpha multiplies opacity)
metallic, roughness, metallicRoughnessMap 0, 0.5 dielectric to metal; mirror to matte (under 0.05 the exact mirror ray); glTF's map (G roughness, B metal)
normalMap, normalScale, occlusionMap, occlusionStrength tangent-space normals; ambient occlusion
emissive, emissiveStrength, emissiveMap black, 1 light it gives
transmission, transmissionMap, ior 0, 1.5 how much light goes through, refracted by the index
thickness, attenuationColor, attenuationDistance 0, white, none the volume: its thickness for thin or open shapes (0: thin-walled), the colour white light turns after that distance inside
dispersion 0 20 / the Abbe number (diamond about 0.36)
clearcoat, clearcoatRoughness 0, 0 a clear varnish over it
specular, specularColor 1, white the dielectric reflection's strength and tint
opacity, alphaMode, alphaCutoff 1, "opaque" "mask" cuts at the cutoff, "blend" blends
doubleSided false both faces drawn and lit

Every texture takes KHR_texture_transform's offset, rotation and scale, a UV set and a wrap. resolveMaterial(material) gives it with every field filled. The built-in shapes and extrusions carry UVs and tangents, so any of them takes a textured material.

From Blender. Export with glTF 2.0 and a Principled BSDF: base colour (and an Image Texture), metallic, roughness, normal map, emission and its strength, Transmission Weight and IOR (KHR_materials_transmission, _ior), Coat Weight and Coat Roughness (_clearcoat), Specular IOR Level and tint (_specular). A volume (_volume): connect a Volume Absorption shader (its colour and density: the distance is 1 / density) to the Material Output's Volume, and give the thickness on a node group named glTF Material Output with a Thickness input (Blender's exporter reads it there).

Lights

The scene's lights (lights, scene.setLights(list), scene.setLight(i, partial)) are in scene units in the objects' frame: x right, y up, z towards the viewer. Ray traces them; ascii shades its glyphs by them (the new kinds approximated: an area light as a point light at its centre of intensity × width × height, an environment as a hemisphere light of its mean sky and ground). Wireframe does not light by them: its preview faces are shaded by their facing alone, flat by default, with interpolated vertex normals when wireframe.smoothSurfaces is true.

Kind Fields
ambient color, intensity light from everywhere
hemisphere sky, ground, intensity, up sky above, ground below
directional direction (towards the light), color, intensity, castShadow, angle the sun: angle is its apparent diameter in degrees (the sun's is 0.53; default 1 in ray): wider, softer shadows
point position, color, intensity, range, castShadow, radius a bulb; radius the glowing sphere's (scene units; default 0.04 in ray): bigger, softer shadows
spot position, direction, angle (radians, half the cone), penumbra, range, color, intensity, castShadow, radius a spot light
area position, direction (the way its lit face looks), width, height, color, intensity, twoSided, castShadow a glowing rectangle: a softbox, a window
environment preset ("studio", "sky", "sunset", "night", "none"), map, intensity, rotation (degrees about the vertical), background the world around the scene: ray reflects it, refracts it and is lit by it; map an equirectangular HDR (a .hdr URL, or one decoded with loadHdr); background shows it behind the objects (default false: the page shows)
import { loadHdr } from "mote-engine";

scene.setLights([
  { kind: "directional", direction: [-0.45, 0.6, 0.66], angle: 2, castShadow: true },
  { kind: "area", position: [-1.3, 1.5, 1.5], direction: [1.3, -1.5, -1.5], width: 1.4, height: 0.9, intensity: 1.5 },
  { kind: "environment", map: await loadHdr("/sky.hdr"), intensity: 1, rotation: 40, background: true },
]);

Units. Intensities are in the scene's units, the same in every mode: a white matte surface facing a directional light of intensity 1 shows about 1. Ray turns them into physical units (radiance and irradiance, the inverse-square falloff with range as a soft cut): a directional light's irradiance is π × its intensity; a point or spot light's power is its intensity × π × (0.4 × range)², so it shows its intensity at 0.4 of its range as the ascii falloff about does; an area light's power is that of the point light ascii stands in for it; an environment of intensity 1 sits at today's brightness. The effects' lights (f.light) join ray's lights as point lights. An effect's flash (f.flash, lightning's) joins them as a directional light casting shadows, at π × its intensity, and a hemisphere light for the sky it lights.

Shadows. In ray every light casts a ray-traced shadow unless it says castShadow: false, soft by its size (angle, radius, an area's sides). Outside ray, shadows (ShadowOptions) asks for the CPU's shadow maps and floor shadow: ascii draws them for every shown object (a mesh casts from the samples ascii draws of its surface, any other object from its points; past 32768 points the same share of each object's casts), and wireframe draws neither. Without lights, the scene keeps today's lighting (an ambient and one directional light towards light), and ray adds a studio environment around it, so metal and glass have something to reflect.

HDR. decodeHdr(bytes) and loadHdr(url | Blob | bytes) read Radiance .hdr files (RGBE and XYZE, flat and run-length encoded) into the equirectangular map an environment light takes. A map wider than maxWidth (an option of both, 4096 by default: ray's environment has no use for more, and an 8K map is about 400 MB of floats) is averaged down by a whole factor as it is read ({ maxWidth: Infinity } keeps every pixel); a file too short for the size it claims is refused before anything is allocated.

Physics

A rigid-body engine written for the scene: convex shapes made from the models themselves, static meshes, contacts with friction and bounce, joints, sleeping, continuous collision for small fast bodies, ray casts and contact events. It writes the objects' transforms, so the bodies behave the same in ASCII, Ray and Wireframe. Without physics there are no bodies at all. The world is loaded with import() when a scene has physics (scene.ready waits for it; what is set on scene.physics or called on item.body before is kept for it), and in ray its floor is a shadow catcher by default (ray.floor: false for none). The world on its own: import { createPhysicsWorld } from "mote-engine/physics"; a static or kinematic body added to it (or turned so) wakes the sleeping bodies it overlaps, which are pushed out.

const scene = createScene(canvas, {
  mode: "ray",
  physics: { gravity: [0, -9.81, 0], colliders: () => document.querySelectorAll("h1") },
  stages: [{
    items: [
      { id: "crate", source: box(), material: materials.wood, transform: { position: [0, 0.6, 0], scale: 0.3 }, body: { restitution: 0.2 } },
      { id: "ball", source: sphere(), material: materials.chrome, transform: { position: [0.2, 1, 0], scale: 0.15 }, body: { shape: "sphere", restitution: 0.6 } },
      { id: "monkey", source: loadGltf("/models/suzanne.glb"), motion: "sway", body: { type: "kinematic" } },
    ],
  }],
  click: shockwave(), // a click's blast wave throws the bodies
});
await scene.ready;                                // the world loaded: the bodies' masses known
const ball = scene.item("ball")!.body!;
ball.applyImpulse([ball.mass * 1.5, 0, 0]);       // 1.5 units a second to the right (an impulse is mass × Δv)
// or simply: ball.velocity = [1.5, 0, 0];
await scene.spawn({ source: box(), transform: { position: [-0.5, 1, 0], scale: 0.2 }, body: {}, instant: true });

The world

Its options, SceneOptions.physics:

Option Default
gravity [0, -9.81, 0] metres per second² (scene.physics.gravity reads and sets it while the scene runs)
scale 1 metres to a scene unit (one unit is half the canvas's smaller side × zoom)
floor 0.05 under the stage's lowest object a static floor's height in scene units, or false for none; the floor shadow and ray's floor lie on it
walls true static planes at the canvas's edges (in the z = 0 plane) and in front and behind at z = ±1.5: what is thrown stays in view
colliders none HTML elements (their border boxes) or boxes in canvas pixels, as kinematic boxes 2 units deep in the z = 0 plane where they are on screen: a heading or a panel a body lands on. An element not found (null) is left out. Measured at most once a frame: on scroll, on resize, and four times a second while the scene draws. A collider is put where its element is at once, and a body resting on its top moves with it, so it rides a scroll or a fling at any speed and is never thrown; a body it meets otherwise is pushed out gently (3 units a second at most). Each element keeps its own collider: one hidden, collapsed or added to the list moves no other's (boxes in canvas pixels are known by their place among the boxes). When the page's layout changes while the scene rests, call scene.resize()
grab true a press on a dynamic body grabs it and letting go throws it
substeps 4 solver sub-steps per 60 Hz step
paused false nothing moves (scene.physics.paused; scene.physics.step() moves one step)
onContact (e) => … when two bodies start touching: their objects' ids ("floor", "wall-left"…, an element's id or "collider-0"…), the point, the normal, the impulse and the closing speed

Borrowed events

Set physics.events to receive onContactBegin, onContactPersist, onContactEnd, onImpact, onSensorEnter, onSensorExit, onSleep, onWake, onJointBreak, onJointLimit and onBodyRemoved. Each SceneEvent carries cached scene ids (a, b; an unknown or absent body is ""), material names, time in seconds, a scene-unit point, unitless normal, joint and which. Impulse is N·s; closing speed and tangential slip are m/s. The world applies scale once; the scene forwards those SI values unchanged. The record and its typed arrays are borrowed until the callback returns: copy the values you need to retain. The old onContact remains an independent allocating callback with its original raw solver units and ownership; leave it unset for allocation measurements.

A body opts in with the physics entry point's EV_CONTACT, EV_PERSIST, EV_IMPACT, EV_SLEEP and EV_SENSOR bit flags in body.events; body.material names its sound/interaction material and body.sensor makes it overlap without force. Event options accept impact: { minImpulse, minSpeed, cooldown, maxPerStep } and persistEvery. scene.physics.events exposes the current stage's raw PhysicsEvents callbacks alongside the scene-id callbacks; it is undefined until that world exists, and is replaced when the stage changes. Optional physics.modules install after the built-in events module. Physics and all modules keep loading lazily: a scene without physics does not request them.

The demo's Sounds of things stage is a debugging aid for the events above, not sound design: its audio is deliberately crude synthetic sine tones and noise that make impacts and slip audible while you inspect a scene, and it does not try to sound like real wood, metal, glass or rubber. Mote ships no natural or production audio feature; bring your own samples or synthesis through the same callbacks. The stage has wooden blocks, metal cans, glass marbles and a rubber ball you can grab and throw in ASCII or ray. Press Enable sound to synthesize its buffers after a real gesture. Impact impulse controls gain, each voice varies its rate by ±5%, and contact x pans it. Tangential slip drives a bounded rolling/scrape loop. The example owns Web Audio, caps the pool at 16 voices and 4 per material, drops the quietest, and stops/disconnects every voice on mute or stage teardown. No audio runs inside the engine.

Bodies

ItemSpec.body: type is "dynamic" (the default: physics moves it, its motion is ignored), "static" (it stays) or "kinematic" (it follows its transform and motion, and pushes what it meets). shape is "auto" (the default: the convex hull of the object's surface at its scale, at most 64 vertices), "box", "sphere" or "capsule" fitted to it, or a shape of the engine's in scene units ({ type: "sphere", radius }, "box", "capsule", "cylinder", "convex", "compound", and for static and kinematic bodies "mesh" and "plane"). Then the body's weight (density, 1000 by default, water's, times its volume in units³, a unit being scale metres: a ball 0.3 units across weighs 14 kg, a unit box 1000 kg; or mass), restitution (bounce, 0.3), friction (0.5), rollingFriction (0; a ball rolls on forever without it), linearDamping and angularDamping, gravityScale, collision group and mask, ccd (swept against static and kinematic geometry, the colliders too: small, fast bodies; thin dynamic bodies, the thinnest side under a quarter of the largest, cards, planks, coins, are swept by default, and ccd: false turns it off), canSleep, and a starting velocity and angularVelocity. An impulse is momentum (kg · units a second): body.mass × Δv, or set velocity. An object scaled (item.set, item.animate) keeps its body's joints, contacts and grab: its shape changes in place, and no onContact fires again for what it already touched.

The handles

item.body (applyImpulse(impulse, at?), applyForce(force, at?), velocity, angularVelocity, mass (kg; 0 for static and kinematic bodies; NaN while its model or the world loads), sleeping, wake(), sleep(), type; calls made before the body exists, its model or the world still loading, are kept and done in the order made, the velocities read meanwhile being those asked for, and after destroy() they do nothing). scene.physics (gravity, paused, raycast(x, y): the object under a canvas pixel and the point hit, as drawn, step()). scene.spawn(item) adds an object to the stage on screen (its particles fade in on it, or it shows at once with instant: true) and scene.remove(id) takes it out. A stage's world is its own: the stage shown makes its bodies from its objects' transforms as they are then.

Drawn between the steps

The world steps at a fixed 60 Hz and each frame draws every dynamic body where it is at the frame's own time, between its poses before and after the last step (position blended, rotation along the shorter way; Physics), so a body moves on every frame of a 120 Hz display. item.transform of a dynamic body is that drawn pose: up to one step's motion behind the world's (its velocity, its contacts and the grab are the world's), and the world's exactly at 60 Hz, while paused and after step(). A press grabs a body where it is drawn, and raycast hits it there. A body put somewhere at once (spawned, a stage shown, moved by item.set) is drawn there at once. item.animate carries a dynamic body along the animation as a kinematic one, and lets it go at rest where the animation ends.

Joints

StageSpec.joints, between objects by their ids (b left out: pinned to the world): ball (a point of each kept together), hinge (turning about axis only, with limits in radians and a motor), distance (a rigid rod of length, by default as long as it is, a spring with stiffness in Hz and damping, or a rope with min and max), weld and slider (along axis, with limits). ball, hinge, weld and slider take one anchor; a distance joint takes its two ends, anchorA on a and anchorB on b (or the world). Anchors and axes are in scene units, where the objects are when the stage is shown. Jointed bodies do not collide with each other. A body named by a joint waits (is not made) while another object the joint names has its model loading, up to 5 s after the stage is shown, so the joint holds them as the stage placed them; an object removed and spawned again under its id gets its joints back: without a position it is placed on the first of its joints' partners that is there, as the stage had them (with none there, where the stage had it), and its joints pull a partner that has moved back to it (a chain that swung meanwhile is whole again); with a position given, it stays there and its joints are made from where it is, the stage's anchors carried with it, a joint's anchor in the world (anchorB of one pinned to the world) too.

// A slab in its own proportions, w × h × d scene units (a source is fitted to a radius of 1: its half diagonal).
const slab = (w: number, h: number, d: number, position: Vec3) => ({ source: box(w, h, d), transform: { position, scale: Math.hypot(w, h, d) / 2 } });

const stage: StageSpec = {
  items: [
    { id: "post", ...slab(0.04, 0.6, 0.05, [0, -0.4, 0]), body: { type: "static" } },
    { id: "door", ...slab(0.5, 0.6, 0.035, [0.28, -0.4, 0]), material: materials.wood, body: {} },
    { id: "lamp", source: sphere(), material: materials.glass, transform: { position: [0.7, 0.3, 0], scale: 0.12 }, body: { shape: "sphere" } },
  ],
  joints: [
    { type: "hinge", a: "door", b: "post", anchor: [0.03, -0.4, 0], axis: [0, 1, 0], limits: [-1.7, 1.7] },
    // A rope from the lamp's top to a point of the world above it, at most as long as it is now.
    { type: "distance", a: "lamp", anchorA: [0.7, 0.42, 0], anchorB: [0.7, 0.9, 0], min: 0, max: 0.48 },
  ],
};

Grab and throw

A press on a dynamic body grabs it where the camera's ray through the pixel hits it (a soft spring to the pointer, on the plane through that point parallel to the screen); letting go throws it with the pointer's velocity over its last 80 ms. The grab is its pointer's: another finger neither grabs, clicks nor drags meanwhile, and a cancelled pointer (or a page hidden) lets the body go at rest. A press anywhere else is a click, as before. A finger on a body grabs it without scrolling the page: the scene prevents that touch's touchstart, through a non-passive listener on the pointer target registered when physics has grab on (a scroll that starts there waits for it: microseconds, or one pick where the browser sends the touch before the pointer); a finger elsewhere scrolls the page as usual. For a full-screen playground where no drag should scroll, set touch-action: none on the canvas or its pointer target.

Colliders and keepClear

A collider is an element's border box (getBoundingClientRect): a panel or a heading a body lands on whole. Each time it is measured it is put where its element is, and the bodies resting on its top (touching it, the contact's normal within 45° of up), and what rests so on them, move with its top in the same frame, keeping their own velocity: a body (or a stack) on a card rides a scroll or a fling with it, never thrown and, within the walls, never left behind (a rider the page carries past the canvas's top or bottom wall is left there), and stays on its top when the element grows. While physics is paused the colliders still follow their elements, and what rests on them stays where it is. A body the collider meets from the side or from below is pushed out by the solver as by anything put in its way, at most 3 units a second. keepClear measures an element's contents (a range over its text, falling back to its box), so a short heading leaves the space beside its line free. The same element can therefore collide over its whole box while the scene clears only its text.

The effects push the bodies

An object's mesh vertices are its body's sensors: what the effects' mesh hooks do to them (the accelerations and changes of velocity of explode, vortex and blackHole, and the points shockwave and magnet move them to) is summed into a force and a torque on the body. So explode and shockwave throw the bodies, vortex and blackHole pull them round, magnet gathers them. wind and a tornado's funnel also drag the bodies as air does (the drag grows with the area a body shows and the square of the air's speed relative to it): the default wind rolls a ball and slides a light box, while a unit box of water's density only leans into it. jelly and disintegrate are the object's own deformation, and do not push.

Limits

These follow from the soft-step solver (one sweep per sub-step, contacts as soft constraints) and the shapes it takes:

Orbit

orbit: { yaw, pitch } (degrees) turns the view about the origin, in every mode: yaw about the vertical (the objects' fronts turn to the right), then pitch about the horizontal (their tops towards the viewer). The objects and the lights turn together (the lights stay in the world's frame) and gravity stays the world's −y. scene.orbit reads { yaw, pitch } (both can be set on it) and takes an Orbit (only what is given changes), from the next frame. Under a pitch ray's floor tips with the world (a resting object's shadow lies under it), and an environment turns with the yaw only. The demo turns the view with a right-drag or two fingers.

Ray also accepts a world-space cameraPose: { position, target, up?, allowOrbit? } or cameraPath: { keys, interpolation? }. position, target and up are three-component vectors in scene units; up defaults to [0, 1, 0]. A path has 2–4096 keys, each a pose with at, strictly increasing from 0 to 1. All keys must have the same normalized up; paths cannot allow orbit. interpolation is "linear" (default) or "smooth" (smoothstep within each segment). Coincident eye/target, collinear up, nonfinite values, and paths crossing a degenerate basis are rejected before replacing the current camera. The key limit bounds synchronous validation and copying work.

import { createScene, bindCameraScroll, sphere } from "mote-engine";

const scene = createScene(canvas, {
  stages: [sphere()], mode: "ray", ray: {},
  cameraPath: {
    keys: [
      { at: 0, position: [-3, 1, 9], target: [0, 0, 0] },
      { at: 1, position: [3, 1, 7], target: [0, 0, 0] },
    ],
    interpolation: "smooth",
  },
  cameraProgress: 0,
});
scene.cameraProgress = 0.5; // A clock or animation can drive this directly.
const unbind = bindCameraScroll(scene, section, { start: 0, end: 1 });
// At page teardown:
unbind();
scene.destroy();

scene.setCameraPose(pose) and scene.setCameraPath(path) validate and deep-copy their input; the last successful non-null setter replaces the other mode. If both options are supplied initially, the path takes precedence. Setting either to null clears both and restores the saved legacy orbit and scalar camera distance. Explicit cameras use the eye-target distance in place of camera. cameraProgress accepts finite numbers, clamps to 0–1, and remains unchanged when switching renderers or replacing the camera. Pose/path replacement is a camera cut; ordinary progress is motion. Returning to ray clears its camera history.

An explicit pose ignores scene.orbit writes, including a page's drag controls, unless allowOrbit: true; paths always ignore them. Allowed orbit starts at zero relative to the pose and does not change the legacy orbit restored on clear. ASCII and Wireframe draw the objects from the same world camera, target translation and roll included, and retain the requested pose/path and progress through a mode change, so returning to ray restores the world view. Physics picks and grab targets follow the camera, while body coordinates, gravity and force/velocity vectors keep their world frame. Environments currently follow eye-target heading only, independently of roll; a vertical eye-target direction retains the last defined heading (zero initially).

bindCameraScroll(scene, element, { start?, end? }) is optional. The element's travel runs from its top entering the viewport bottom (0) to its bottom exiting the viewport top (1); start and end select that interval (defaults 0 and 1). Distinct finite values are required; reversed intervals play backwards. Scroll and resize listeners are passive and coalesce into one animation frame. Geometry is cached at binding and refreshed on window/element resize, so scroll updates use numbers without requesting a new rectangle. Rebind after a layout change that only moves the element. Call the returned disposer before destroying the scene; it removes the listeners, disconnects its resize observer and cancels pending work. The engine itself does not depend on scrolling.

Camera rigs

scene.setCameraRig(rig) sets a camera the scene evaluates every frame, in every mode, from the objects where they are: a follow or an orbit is motion for Ray's temporal history, not a cut a frame. The rig's kinds, by kind:

kind fields the camera
static pose today's pose (setCameraPose is this rig)
path path, progress? today's path; scene.cameraProgress drives it
lookAt position, target (an object's id or a point) a free eye looking at an object or a point
orbit center (id or point), distance, yaw, pitch the eye at distance from the centre, turned as orbit turns the view (yaw 0 on +z, 90 on −x; pitch raises it; keep pitch within ±89)
follow target (id), offset, lookAt? (id, point or "target"), stiffness?, damping?, frame? the eye at the object plus offset (in the world's frame, or the object's with frame: "target"), looking at the object (or lookAt), both smoothed by a critically damped spring (stiffness /s², default 25; damping 0 or absent: critical)

Every rig takes fov (vertical degrees, 5–150: the projection then spans it at the rig's distance, unit = h / (2 d tan(fov / 2)), so ASCII, Wireframe and Ray draw the same picture), roll (degrees about the view axis), up (before the roll; default the pose's or [0, 1, 0]), handheld: { amplitude, frequency, seed? } (value noise on eye and target, a function of scene time: a stepped scene reproduces it) and blend (seconds to crossfade eye, target, up, fov and roll from the camera as it was; 0, the default, is a cut).

scene.setCameraRig({ kind: "follow", target: "hero", offset: [0, 1.2, 4.5], fov: 45, handheld: { amplitude: 0.02, frequency: 2, seed: 7 } });
scene.setCameraRig({ kind: "orbit", center: "hero", distance: 6, yaw: 30, pitch: 15, blend: 0.5 }); // motion, not a cut
scene.cameraCut();         // the next frame resets Ray's history
const { position, target, up, fov, roll, distance, cut } = scene.camera;  // the camera as the last frame drew it (a copy)
scene.setCameraRig(null);  // the pose, path or orbit set before the rig

The rig is validated and deep-copied before anything changes (a TypeError or RangeError leaves the rig in place); setting one is synchronous (no module to load). A replacement is a cut unless blend is above 0; setCameraPose and setCameraPath replace a rig as they replace each other, and setCameraRig(null) restores whatever they had set. An object a rig names that is gone, or not on the stage shown, freezes the rig where it is (no error in the frame loop); a degenerate basis (the eye on its target, the up along the view) does the same. The pointer's orbit is off under a rig, but for a static one whose pose allows it. scene.cameraRig reads the rig set (a copy), or the pose or path as a static or path rig. Rig evaluation allocates nothing a frame; a rolled or custom-up rig costs two numbers a frame in the pose's validation. scene.camera reads single-precision values (the frame's matrices); fov is the rig's, or the one the projection spans (0 before the first layout).

The scene timeline

scene.setTimeline(doc) installs a timeline (TimelineJson, schemas/timeline.schema.json): tracks of keys over the objects' transforms, the lights' fields, the camera rig's parameters, an effect's live parameters, the scene's exposure or zoom, the stage index; and cues, named operation batches fired once each time the playhead crosses them. The playhead moves with the scene's time, so it follows the real, fixed or stepped clock without a case of its own: under a stepped clock a consumed step moves it by step × rate.

const { ok, timeline, errors } = await scene.setTimeline({
  version: 1, duration: 12,
  tracks: [
    { target: "item:jet", property: "position", keys: [{ t: 0, v: [0, 0, 0] }, { t: 4, v: [2, 1, 0], ease: "inOut" }] },
    { target: "item:jet", property: "rotation", keys: [{ t: 0, v: [0, 0, 0] }, { t: 4, v: [0, 90, 0], ease: [0.4, 0, 0.2, 1] }] },
    { target: "camera", property: "rig.yaw", keys: [{ t: 0, v: 0 }, { t: 12, v: 90 }] },
    { target: "light:1", property: "intensity", keys: [{ t: 2, v: 0 }, { t: 3, v: 5, ease: "in" }] },
    { target: "effect:fx:0", property: "density", keys: [{ t: 0, v: 0 }, { t: 2, v: 1 }] },
    { target: "item:jet", property: "visible", keys: [{ t: 8, v: false }] },
  ],
  cues: [{ t: 3, name: "shot-2", ops: [{ op: "set", target: "item:jet", property: "material", value: { preset: "gold" } }] }],
});
timeline.seek(2);           // a motion, never a cut
timeline.onCue((name, t) => console.log(name, t));

Targets are item:<id>, camera, light:<index>, effect:<id> (the effects' ids are fx:<n> in order of registration: the scene's, then each stage's, then addEffect's), scene and stage. Value kinds: position, scale (a number or three), a light's position, direction, up and the rig's rig.position, rig.target, rig.offset lerp; rotation (Euler degrees or a quaternion) slerps; fov, roll, rig.distance, rig.yaw, rig.pitch, rig.progress, rig.handheld.amplitude, a light's intensity, range, angle, penumbra, radius, width, height, rotation, the scene's exposure and zoom, and an effect's numeric parameters lerp; colours (color, sky, ground; [r, g, b] linear or a CSS string) lerp in linear RGB; visible, material, motion, a light's castShadow and background, a boolean effect parameter and the stage index are steps, held until the next key. The ease named on a key is the ease into it: "linear", "in" (quadratic), "out", "inOut" (the engine's smoothstep, so a one-key animate and a two-key track agree), "hold", or a cubic Bézier [x1, y1, x2, y2] with x1 and x2 from 0 to 1.

A track writes its target every frame within its first and last keys (the last key's value is written once when crossed, so a frame that skips it still lands there); before its first key it writes nothing, and past its last key the object is the hand's again. A track on an object's transform ends that object's animate (as set does) and overwrites a set at the next sample. An object with a dynamic body is kinematic from its track's first key to its last, then dynamic at rest (animate's rule). A track on a camera parameter needs a rig: when the scene has none, a static rig is made from the camera as it is (a cut, once, at the install). An effect parameter can be tracked only when the effect serves it live (EFFECT_PARAMS[name][key].live === "param": the numbers and flags of water, clouds, fog, smoke, wind, vortex and magnet; the others, and every select and colour, change through set alone) — the document is refused at /tracks/<i>/property otherwise, as it is for an effect the page added without a param hook. A page-made effect takes part by giving param(key, value) (liveParams from the root builds a typed block for it, which the timeline writes in place).

The document is validated whole before anything changes, with JSON-pointer diagnostics and the walk's caps (256 tracks, 4096 keys a track and 65 536 in all, 256 cues, 64 operations a cue, times finite and strictly increasing within [0, duration], duration at most 3600 s); a cue's operations go through validateSceneOps and may not be step, timeline, stages or system (refused at /cues/<i>/ops/<j>/op). setTimeline resolves { ok: true, timeline } with the handle (playing from 0; scene.timeline reads it), { ok: false, errors } for a refused document (nothing changed), and rejects with { kind: "load" } or { kind: "destroyed" }; it throws a TypeError for an argument that is not an object or null (null removes the timeline). The director's module loads with import() on the first call and scene.ready covers the load. The handle: play(), pause(), seek(seconds) (a RangeError outside 0..duration; a motion, never a cut), rate (0.25 to 4), playing, time, duration, onCue(cb) (the unsubscribe is returned; cues fire in order, once per crossing, and a loop restarts them; their operations are recorded for the operations runtime, which executes them). A handle replaced by another setTimeline is inert. Sampling allocates nothing a frame: the keys live in typed arrays, the samples are written in place into the objects' transforms, the lights' fields, the rig's block and the effects' live blocks; under a stepped clock two runs give bit-identical state. validateTimeline, compileTimeline and sampleTimeline are exported by mote-engine/director for tools that check a document before sending it.

Scene operations and the log

scene.applyOps(batch) applies a batch of scene operations (SceneOp[], one operation, or their JSON text; schemas/scene-ops.schema.json), the director's way of driving a scene with data: it is validated whole against what the scene has now (validateSceneOps, loaded with the director's module on the first call, scene.ready covering the load) and refused whole with JSON-pointer diagnostics ({ ok: false, errors }, nothing applied), else queued and applied in order at the next frame boundary, before the step that frame consumes.

const result = await scene.applyOps([
  { op: "add", item: { id: "crate", shape: "box", transform: { position: [1, 1, 1], scale: 0.2 }, material: { preset: "gold" } } },
  { op: "effect", action: "add", name: "fog", id: "mist", params: { density: 0.4 } },
  { op: "camera", rig: { kind: "orbit", center: [0, 0, 0], distance: 3, yaw: 10, pitch: 5, fov: 40 } },
  { op: "animate", target: "item:crate", property: "position", to: [-1, 0, 0], seconds: 1.5, ease: "inOut" },
  { op: "step", frames: 90 },                      // a stepped clock: the frames consumed before the next operation
  { op: "set", target: "effect:mist", property: "density", value: 0.8 },
]);
// { ok: true, applied: 6, frame: 90, ids: { 0: "crate", 1: "mist" } }

add spawns an object (a model named by URL is fetched by the runtime and recorded with its SHA-256, a .gltf's separate buffers each fetched and recorded too, under the model's path, a hash and the URI as written; the batch waits for its bytes, so a step after it steps with the object in), remove takes one out, set writes one property at once (an object's position, rotation, scale, visible, material, motion; a light's field; a camera parameter, fov, roll, rig.yaw... written into the rig's block as a track writes it; the scene's exposure or zoom; an effect's parameter through its one-off set), animate moves one over seconds on the timeline's own evaluator (the same eases; inOut unless given; a step kind such as visible is written when the seconds are up; a set on the same property ends it, as a track does), camera replaces the rig (cut for a cut), light and lights change or replace the lights, effect adds one (its id as given, else fx:<n>), sets, triggers or removes one, stage and stages move between or replace the stages, physics pushes a body, timeline installs or drives the timeline, render changes the mode, Ray's settings or the Wireframe style, step consumes frames (1 to 600 a batch in all; a stepped clock only). system operations are the engine's own and refused from callers. A batch holds at most 256 operations, 64 of them add.

The promise resolves after the frame that applied the last operation: { ok: true, applied, frame, ids } (the ids the add and effect add operations got, by operation index), or { ok: false, applied, failed, error } when a setter threw on what validation could not know (a model that fails to load, an object without a body): the operations before it stay, there is no rollback, the rest are not applied. It rejects with { kind, message }: "load", "destroyed", "paused" (the scene draws no frame: resume it). A TypeError, synchronous, for an argument that is neither an object, an array nor a string. A timeline cue's operations go through the same runtime, queued behind the batches queued: with none ahead they run right after the sample that crossed the cue; while a batch is still waiting (on a step, a model) they wait for it, as a batch queued then would. In cue order, once per crossing, one operation after the other (a cue's own models fetched in sequence), never from inside a paint, a physics step, an effect hook or another cue (a cue may not step, replace the timeline or the stages). An effect declared in a stages operation's stage runs in that stage alone.

scene.log() is the scene's operations log: every batch that applied and every system operation the engine applied on a stepped scene (a layout, the DOM colliders measured), each at the frame it applied to, oldest first by the time it was recorded (a batch that waited, for a step or a model, as one entry per stretch, the entries sharing its batch number, each with the frame it applied at and the frame its last operation settled at, until; a batch's entries are recorded when its stretches settle, so they may follow system operations of frames they span). It returns a page of copies, at most 1024 entries (limit), from the entry after after (an entry's seq), with next to page on, the totals (ops, bytes: UTF-8, as the validator counts), firstFrame, the scene's frame and clock, and assets (the models and maps fetched by URL, with their digests). The log keeps at most 65 536 operations or 64 MiB of JSON: past either cap the oldest entries go (dropped) and complete reads false; scene.log({ clear: true }) empties it (clearedAt), with the same effect; so does a pause or a destroy that interrupts an operation a batch was waiting for whose effect may still land (interruptedAt: a timeline installed, stages replaced, a map fetched; a step interrupted is recorded with the frames it consumed, and leaves the log complete under a pause or a destroy, interrupted under a timeout; an add interrupted is undone). Under a real clock the log is a record; under the stepped clock a complete log replays the scene:

import { replayLog } from "mote-engine/director";

const log = sceneA.log();                      // complete: true
const result = await replayLog(sceneB, log);   // sceneB: the same document, a stepped clock
// { ok: true, entries, frame, partial: false }: sceneB's CPU state is sceneA's, frame for frame

replayLog takes the entries in frame order, puts each batch's stretches back together (the frames the page stepped through while the batch waited become steps of the batch's own, so what waited behind it waits the same), applies each batch at its frame and each system operation at its frame as the engine applied it (the layout as recorded, its size and pixel ratio instead of the canvas's measure; the DOM colliders' boxes as recorded, placed instead of the page's elements), and steps on to the log's frame after the last entry; it refuses an incomplete log ({ ok: false, kind: "incomplete" }) unless given { partial: true } (the result then says partial), a scene whose clock is not stepped ("clock"), an entry behind the scene's frame ("order"), a batch the scene refuses ("ops"), and a model or buffer whose digest differs from the log's ("asset-mismatch", with the path and the two digests).

Effects

Effects load into a scene and combine freely: they push the objects' particles (and, with physics, the bodies), change the glyphs drawn, draw glyphs of their own, shake the picture or react to clicks. In ray they are drawn in the same 3D frame as the solids.

import { createScene, fire, smoke, heatHaze, explode, holes, rain, lightning } from "mote-engine";

const scene = createScene(canvas, {
  stages: [model, { items: [...], effects: [rain(), lightning()] }], // effects of one stage
  effects: [fire({ intensity: 0.8 }), smoke(), heatHaze()],          // effects of every stage
  click: explode(),                                                  // what a click does
});
const wind = scene.addEffect(EFFECTS.wind({ strength: 0.6 }));
wind.set({ angle: 30 });   // change it while it runs
wind.remove();
scene.click = [ "ripple", holes({ heal: 8 }) ];
Kind Effects
Forces on the objects wind, vortex, magnet (the pointer pushes or gathers), explode (debris, then it flies back together), holes (a click destroys a piece, the edge burns, it heals), shockwave, gravity (crumbles from below and piles up like sand, at the angle of repose), jelly, blackHole (opens beside the objects, bends them and swallows them slowly, then lets them go)
Glyph changes rainbow (style: spectrum a hue wheel, film the thin-film interference of a soap bubble, oil of an oil slick), glitch, shake, scanlines, dissolve (burns away like paper, or falls to dust, and back), hologram, matrix, neon, heatHaze, laser, halo (light around the objects' outline, with turning rays; the outline lit too)
Glyphs and forces tornado: a funnel from the ground (in ray, its floor line) up into the sky (or to the clouds' underside, fading into it), narrow at its foot and wrapped in a debris cloud that trails behind it, turning, snaking (bend) and wandering (wander); its wind is a Rankine vortex with inflow at the ground and an updraft in the core, carrying dust up the funnel, flinging heavier debris out and tearing the objects apart where it is faster than they hold (pull)
All three disintegrate: the objects dissolve from one end into a stream of dust and crystal shards that flows away and settles on the ground; with metal, steel faces with a moving sheen
Glyphs of their own fire, smoke, rain (splashes on the objects), snow (piles up on them), sparks (style: classic, grinder a jet of streaks bursting into stars, welding a flickering arc, curling spatter and glowing drops; from the edges, the pointer, a point or a contact point running along the objects), fireworks, starfield (with warp), bubbles, water (with the objects' reflection), lightning (strikes the objects, flashes; in ray the flash is a light of the scene, from the channel and casting shadows, the clouds lit as a sky all around, the objects keeping their colours; in every mode a fractal bolt (in ascii, characters along its segments): a branching leader, the return stroke, restrikes, with branchiness, restrikes, slowmo and kind: cloud-to-ground, cloud-to-cloud, forked), confetti (paper pieces tumbling and gliding, from the sky or cannons, in mixed shapes and rainbow, party, pastel, gold or custom colours, lying where they land), aurora, fog, clouds (style: overcast, cumulus or layers; with rain and lightning a storm: the rain falls from their underside, the bolts strike from there and light them up), meteors, drip, orbit (hidden behind the objects)

In Wireframe water uses full-resolution scene pixels for its reflections and submerged refraction on both GPU and Canvas, without ASCII-cell sampling or a blur pass. The GPU path uses a dedicated continuous water shader with projected height-field swells with crest occlusion, finer wave bands, angle-dependent reflection, depth absorption and normal-dependent highlights; Canvas uses a pixel-based approximation with a continuous normal field. Neither path draws regular wave strokes or reflects the ASCII cell grid. In ray mode the water is ray traced: a plane at the level with the same wave field and the same layers (the body, the sky and the objects reflected, glints), its reflections traced through the scene (an object above the water shows its underside in it) and its refraction meeting the submerged parts of the objects, absorbed by the water's colour; where nothing is under it the page shows through. Its glints are the highlights of the scene's direct lights (directional, point, spot and area) on the waves: with only ambient or hemisphere light (or the environment, which the water reflects as the sky) glints adds nothing in ray, where the other modes draw a highlight from a fixed key direction. It is traced at ray mode's internal resolution, within its frame budget. A level at or above the eye (the upper half of the canvas with a level camera) is drawn as in Wireframe. ASCII uses the same wave phase and optical boundary, refracting submerged surface glyphs. level, waves (0–3), speed (0–4), scale (.25–3), opacity (0–1), reflection, reflectivity (0–1), distortion (0–3) and glints (0–3) remain live. speed: 0 freezes the wave phase. ior (1–2.5, default 1.333) sets the optical index; 1 removes optical bending. Submerged image distortion is a screen-space approximation of apparent depth and animated surface slopes, rather than a full 3D transmission/shadow solver. Lasers share the animated boundary and use Snell transmission plus dielectric Fresnel reflection, including total internal reflection, in graphical modes and ASCII. Their display tone mapping keeps the weaker reflected branch visible; traced branch powers sum to one. The laser overlay follows the water composite so its already split rays are not reflected a second time. Controls and wave clocks survive renderer/mode changes. Laser contact adds interpolated linear surface light in graphical modes (including the optional code scanner), preserving each particle’s material and opacity instead of recolouring whole ASCII cells. The code scanner uses a segmented graphical core in graphical modes; literal scanner characters are confined to ASCII mode.

matrix draws distinct columns of crisp code in graphical modes and ASCII, with white-green leading characters and fading green tails. size (.5–6, default 1.7) scales the rain characters and their spacing independently of the scene font. density (0–3) immediately changes the active columns; speed (0–4) freezes all movement and flicker at 0. trail (0–3) changes tail length without moving the heads, mutation (0–4) controls symbol changes, and head (0–2) controls the white highlight. charset selects kana, binary or latin. color preserves saturated code colours, intensity (0–3) controls overall visibility, and surface (0–1) blends code into the objects (0 preserves their material). rain: false hides the background streams; intensity: 0 leaves everything untouched. Timing is independent of render FPS.

glitch applies short bursts of coherent horizontal tears, red/cyan channel fringes and local block corruption to the objects. Quiet intervals leave the surface clean; the effect does not shake the whole scene. Graphical modes and ASCII share burst timing, offsets and corruption. intensity (0–3) controls the overall strength, rate (0–5) controls new bursts, and speed (0–4) controls time (0 freezes the current failure). tear (0–2), rgb (0–2), blocks (0–1) and noise (0–1) independently control displacement, colour separation, packet-like dropout and corrupt characters. All controls update existing bursts; intensity: 0 leaves the surface untouched, while rate: 0 lets existing bursts finish and then stays clean. Burst scheduling uses a fixed time step, independent of rendered FPS. The shared GlitchModel used by other modules is unchanged.

drip gathers small beads under the objects' silhouettes, pinches them off, accelerates them under gravity and splashes on lower surfaces or the bottom of the canvas. Ray and Wireframe use translucent, non-emissive water with fine highlights; ASCII uses growing beads, falling marks and spreading splash glyphs from the same simulation. rate (0–5) controls arrivals, speed (0–3) controls the whole simulation (0 freezes it), size (0.25–8) scales water in every mode, and gravity (0–3) controls downward acceleration. opacity (0–1, default 0.7), splash (0–2), trail (0–2, the velocity-dependent stretch), wind (-2–2) and color (default neutral #bed1dc) update live. rate: 0 stops new beads while existing water finishes. Surface collision is a swept screen-space approximation; drops do not simulate fluid refraction or wet the underlying material. Emission and motion are independent of rendered FPS and backend.

meteors draws fast, straight streaks with a compact white-hot core, a cooling train that remains after the head has passed, and occasional daughter fragments. Graphical modes and ASCII share the same flight simulation; trails are deposited by distance rather than by rendered frame. rate (0–4) controls new arrivals, speed (0–4) controls the whole simulation (0 pauses flight and fading), and size (0.25–10) scales heads and train width, including multi-cell heads in ASCII. trail (0–3) controls train lifetime (0 hides it), intensity (0–3) controls brightness, and fragmentation (0–1) controls splitting. angle is in screen degrees (0 right, 90 down, 180 left); it and spread (0–90°) affect new arrivals without bending existing flights. Choose palette: "natural" | "ice" | "ember" | "custom", with color used by the custom palette. light (0–2, default 0) optionally lights nearby scene surfaces. Setting rate: 0 stops new meteors while existing heads and trains finish. These are bounded visual approximations, not a physical atmosphere simulation.

EFFECTS maps every name to its function, for menus, and EFFECT_PARAMS describes every effect's settings (a number with its range and step, an on/off, a choice, a colour, each with its default), so a settings panel can be built from it; effectDefaults(name) gives the defaults as an object. Sizes are in scene units, so an effect looks the same at any canvas size; effects with emitters can start from the objects' outline (source: "objects"), the ground or the pointer.

starfield uses compact warm-white and blue-white stars with a range of magnitudes and perspective speeds. size, brightness, twinkle and color work live in graphical modes and ASCII. warp stretches stars radially by their projected velocity; speed: 0 freezes both movement and scintillation. Changing the count or renderer keeps the existing stars in place.

Custom effects use frame(f), mesh.prepare(state, frame), mesh.vertex(vertex, frame), mesh.surface(writer, frame) and mesh.dispose(objectId). Vertex positions are local; frames provide local/world matrices and picked world anchors. Surface programs are bounded, atomic transactions managed by the scene. A nonfinite vertex update preserves the last coherent geometry and quarantines that installation. glyph decorates ASCII text; draw, offset and trigger provide independent emitters, presentation and input. f.mode reports the actual mode. f.worldAt, f.projectWorld and f.unprojectWorld convert triggers and emitter positions without attaching them to camera pixels. f.surfaceTop and f.surfaceBottom query the current covered mesh. Material particles set lit: true; Ray lights them with its scene lights. f.sky shares environmental information between effects. GlyphParticles, noise2, fbm, hsl and gradient remain available for standalone effects. Glitch, scanlines and heat haze are intentional final-image effects in graphical modes; their decoration never changes traced geometry or shadows.

In graphical modes and ASCII, aurora({ bands: 4, light: 1 }) draws overlapping, folded curtains with fine striations: green bodies, pink lower fringes, violet regions and diffuse red upper emission. These colours vary coherently along the moving folds. colorMix (0 to 1, default 1; "colours" in the demo) blends from green-only to the full palette, affecting both the sky and its reflected illumination without restarting the animation. bands sets the number of curtains (1 to 6); light controls the aurora's illumination of the scene's actual materials (0 disables it). intensity changes both the visible emission and the lighting, and speed: 0 freezes both. ASCII samples the same optical field as one coloured density glyph per cell; switching modes preserves both animation clocks. The demo's Aurora preset shows it over the skyline with stars.

The aurora's internal rays have a faster clock than the large curtain folds: fine filaments drift sideways while packets of light rise and fade along them. raySpeed (default 1, range 0 to 3) controls this motion relative to the curtains; 0 stops the internal flow. Changing it preserves the animation phase. The aurora's illumination follows the moving emission too.

heatHaze bends the objects' contours with clear, rising pockets of turbulence in graphical modes and ASCII, on both renderers. amplitude controls displacement (0 disables it), from sets the top of the heated band as a viewport fraction (1 disables it), speed controls its evolution (0 freezes it), and scale controls pocket size. The field uses viewport units rather than cell indices, so the font size does not change its strength; live controls and mode changes preserve its phase. In ASCII it displaces the scene's glyphs; in Ray and Wireframe it bends the finished picture on the canvas, the other effects' marks included (a final-image effect, as above), rather than refracting a background image.

laser defaults to a physical scan sheet: a thin continuous pale core, a narrow coloured halo and stronger scattering where it crosses the objects. style: "code" uses a segmented core in graphical modes and code-scanner characters in ASCII. color, width, intensity, angle (degrees from vertical) and light (local reflected illumination; 0 disables it) update live in graphical modes and ASCII, on GPU and Canvas. speed: 0 freezes the current scan position and its scattering; changing controls or modes preserves the phase. The beam's thickness follows viewport scale, independently of camera aperture; ASCII represents its core and halo with oriented line characters and shaded neighbouring cells.

disintegrate advances a ragged, chipped fracture front through the actual surface. Each removed point can transfer material once into fine drifting dust or tumbling shards; the intact shape does not keep emitting duplicate silhouettes. Both modes and renderers share the same debris and floor deposits. amount selects the initial removed fraction (0 restores the whole object and clears debris; 1 removes every surface point); erosion adds removal per simulation second (default 0; keep it and breathe at 0 for a static front). Changing amount restarts that progression. The effect does not automatically rebuild consumed material. cut controls the dissolving side, independently of the stream's angle; ragged controls fracture detail and breathe modulates the front. speed: 0 freezes erosion, debris, facet reflections, steel sheen and settling. size, turbulence, gravity, opacity, dust, shards and rate control the debris; ground shows accumulated grains, metal adds the optional steel finish, and the halo control keeps unrelated surface glow subdued. Dust follows a smooth rotating air flow while heavier shards retain inertia and fall. Grain sizes and floor deposits use viewport units, independently of the ASCII font; particle pools and emission are capped.

orbit draws satellites on several inclined elliptical planes, with perspective, compact luminous heads and continuous tapered wakes. The near half passes in front of objects and the far half behind them; ASCII hides rear marks in occupied cells and reconstructs the same planes with bright heads and fading trail characters. bands (1–5), eccentricity, tilt, screen rotation and precession control the geometry. Satellites accelerate near their closest approach and the inner bands travel faster. speed integrates motion without phase jumps: 0 freezes heads, tails and precession, and negative values reverse travel. trail, size (0.25–10), intensity, color, radius and count work live in graphical modes and ASCII on both renderers. Existing satellite identities survive count changes and form the shared subset on mode/renderer changes. Head size follows viewport scale independently of aperture. ASCII reconstructs large bright bodies and wide trails across multiple character cells, rather than retaining a single glyph with a faint halo. Trail sampling and satellite counts are bounded.

bubbles draws translucent soap films with thin rims, white reflections and slowly changing iridescent grazing colours. Larger bubbles rise faster, sway and deform gently, then rupture into a brief perimeter spray. Graphical modes and ASCII share their live particles and animation phase: ASCII draws large hollow contours with coloured reflections and small bubbles as compact glyphs. size, rise, wobble, opacity, iridescence and color update live in both modes; speed: 0 freezes emission, motion and film evolution. rate controls new emission, and source selects the ground, objects or pointer (no emission outside the canvas). wind and windAngle steer the air independently of buoyancy: 0° right, 90° down, 180° left, 270° up. Scene lights tint reflections; camera aperture does not blur or enlarge the films. Pools, reflection detail and simulation steps are bounded.

smoke transports density through a persistent 2D fluid velocity field, with buoyancy, pressure projection and vorticity confinement producing rolling folds and fine wisps. Detail enters at the source and travels with the material; there is no independently animated density mask. Ray and Wireframe reconstruct its optical depth with overlapping soft kernels; ASCII shades the same evolving field and leaves the surface behind it visible. Projected optical self-shadowing darkens the inner rolls while thinner illuminated regions approach white. Its dominant shading direction follows the scene's light; scene and effect lights tint the smoke locally. opacity (0 to 1, default 0.85) controls transparency independently of density, colour and self-shadowing, so thin wisps transmit the background without black fringes. source selects object edges, the ground or the pointer (emission pauses outside the canvas); density and color update the existing smoke immediately. wind controls strength and windAngle its screen direction: 0° right, 90° down, 180° left, 270° up; negative strength reverses it. rise controls buoyancy independently. turbulence changes rotational flow and scale changes the source width, affecting subsequent evolution rather than reshaping frozen material. speed: 0 freezes motion and emission. Every mode and renderer preserves the fluid field on switching. Font size and camera aperture do not enlarge the smoke. A short initial plume avoids an empty start, and simulation, field resolution and light sampling are bounded.

angle ("tilt" in the demo) inclines the aurora clockwise in screen space, from -180° to 180° (default 0°), about the middle of the sky. rotation turns transparent curtain planes around their vertical axis with perspective projection. The curtains sit at different depths, so turning them produces foreshortening and parallax; their light sources also move in depth. A full turn restores the same view. Both controls preserve the animation phase in either mode.

waveSpeed ("wave speed", 0 to 3, default 1) controls how quickly the large curtain folds evolve, independently of raySpeed. Set it to 0 to keep the curtain shapes still while their rays flow; master speed: 0 freezes both. Bright filaments and overlapping curtains develop restrained pale cores while their outer regions retain pink, green and violet.

fog({ density: 0.6, height: 0.55, turbulence: 1 }) forms low, rolling banks with curling wisps and a clear upper sky. Ray and Wireframe reconstruct a continuous optical field at three depths, so near vapour veils objects while far banks pass behind them. ASCII samples the same field into shaded density characters and attenuates the original surface glyphs under foreground fog. height (0.1 to 1), turbulence (0 to 2), density, speed and color work live in every mode. speed: 0 holds the field still unless another effect supplies wind; changing speed or render mode preserves its phase. layer: "under" keeps all fog behind the objects. The Fog demo preset shows it around the skyline.

clouds({ style: "cumulus" }) forms irregular sunlit masses with eroded, translucent edges and shaded interiors. In Ray, once its built-in volume shader is installed, the clouds are a volume in the scene and this screen field is not drawn; Wireframe (and Ray until then) reconstructs a continuous optical field without repeated puff sprites; ASCII samples the same field into coloured density characters. overcast retains a broad storm ceiling; layers adds three depths, including a foreground bank. height (default 0.6) sets the sky's extent, scale the size of the masses, detail their fine billows, and thickness their optical density. light and sunAngle (screen degrees, default -135 toward the upper left) control directional illumination. sceneLight (0 to 2, default 1) also makes each bank respond to the actual scene and effect lights: coloured point lights brighten nearby vapour with range falloff, spots respect their cone, and directional/hemisphere lights follow the billows. Moving or dimming a source updates the screen field and ASCII alike; 0 disables this response. Thin, irregular openings break up the underside, especially at low coverage. These controls, cover, speed and color work live in either mode; zero cover or thickness clears the clouds, and zero speed freezes drift and internal evolution without resetting their phase. Cloud-limited rain and ground strikes use the actual underside; embedded lightning follows the bank through its openings. The Clouds demo preset shows fair-weather cumulus above the city.

For blackHole, inclination sets how face-on the accretion disk is, while tilt rotates its orientation on screen (-180° to 180°). hotspots (0 to 2, default 0.7) adds compact bright gas condensations that orbit with the disk and appear in its lensed images; 0 disables them. The GPU pen (Ray, and Wireframe on the GPU renderer) traces these features in the disk plane, including their bent images, while the Canvas pen's dots and ASCII provide approximations with the same controls. palette: "thermal" retains the blackbody colour fit; "lilac" and "blue" apply cinematic grades as the local gas gets hotter, retaining warm outer gas and pale bright cores. Increase diskTemperature (1500 to 30000 K in the panel) to bring out these hues. Tilt, palette, temperature and hotspots update live without restarting ingestion; spin: 0 freezes the disk texture and condensations.

Tornado in the demo shows a continuous condensation funnel with rotating helical filaments, irregular rolling dust plumes and angular solid debris carried by its Rankine vortex. The dust occupies six depth slices, rises into the lower cone and darkens the condensation at the base, concealing its narrow foot. debrisColor (default dark grey, #52575e) colours dust and fragments separately from the funnel's color. Where its wind is strong enough it pulls the objects' mesh vertices into its flow, depth included, releasing their spring back to the surface while they are entrained; with pull: 0 they return to rest. Ray and Wireframe reconstruct front and back optical shells at real depth, with soft contact against the objects; ASCII samples the same field into density glyphs. density controls condensation, detail fine edge turbulence, and flow the upward filament motion independently of spin. Master speed: 0 freezes the shape, filaments, dust and debris. Changing these rates preserves animation phase. ground (0.35 to 1, default 1) sets the ground's position on the canvas; sceneLight (default 1) lets actual scene and effect lights shade the vortex and its dust locally. width, taper, bend, wander, pull and debris remain available in either mode.

fire uses continuous rising sheets with warped folds, thin luminous fronts, openings and detached tips. With source: "objects" it burns across the full surface, including lower faces, partly obscures the surface behind its luminous sheets, and rises above it; ground makes a broad bed and pointer a local torch. Ray and Wireframe reconstruct the field with smooth emission kernels instead of repeated flame cutouts; ASCII shades the same heat field into characters. height, intensity, speed (0 freezes the flame), turbulence and light work live in every mode. palette selects natural, blue, green, violet, red or custom (using color); these are visual emission palettes, with matching scene illumination when light is enabled. Changing a palette or mode preserves the flame's phase. Camera aperture does not enlarge or defocus it.

fireworks in graphical modes uses compact, bright optical cores and fine glittering trails. Their size follows the viewport; foreground camera aperture and haze do not defocus the distant stars. GPU bloom adds surrounding glare while the cores stay defined. The same focused cores render on Canvas, preserving the shell shapes, colour changes, timings and glitter. ASCII shares the same shell programme, colour changes, glitter, splits and finale. Bright stars use compact crosses, trails cool into fine dots and ticks, and overlapping particles resolve to one glyph per cell. type, intensity, rate and finale work in both modes; switching mode preserves the live burst.

wind progressively erodes objects: sustained wind cuts their surface away over several seconds and releases what it removes as small fragments carried downwind, while the objects' vertices flex in the gusts. The surface thins as the fragments disperse, rather than launching the entire object as a moving copy. erosion (0 to 3, default 1) controls the erosion rate separately from wind strength; 0 pauses new erosion while released fragments keep moving. Released fragments follow the current wind, so changing angle redirects them. No long streaks are drawn: sparse, tiny, transparent dust specks drift in a bounded volume around the origin, soft dots in Ray and Wireframe and . characters in ASCII. The panel's airborne dust switch (API option streaks, retained for compatibility) hides these specks without changing the wind forces.

The demo's Storm preset uses dark slate-grey clouds with subdued sunlight, thin neutral rain reflections and near-white lightning. The palette applies in graphical modes and ASCII; selecting Storm restores these colours even after tuning another weather preset.

Rain draws thin, neutral reflections with low alpha so the scene remains visible through the water. rain({ opacity: 0.35 }) controls this transparency independently of density; 0 makes existing drops and splashes invisible, and changes apply immediately in graphical modes and ASCII. color tints the reflections, defaulting to neutral grey rather than blue. Ray and Wireframe retain depth and motion blur, with finer streaks and translucent splashes. Tilted rain is emitted beyond the upwind edge to cover the whole viewport. The default source: "sky", also used by Storm, emits across the whole sky so rain remains visible through openings within the bank. The optional source: "clouds" limits emission to staggered heights inside the lower bank. Both fade through the continuous optical field, avoiding a dark separation band.

snow({ style: "natural" }) draws irregular white aggregates at different depths: many small distant flakes and fewer large foreground flakes. style: "classic" retains the eight decorative six-armed crystals. ASCII gives near natural flakes irregular multi-character footprints with faint outer fibres, while classic draws small branched crystals. Far flakes remain fine points, and flakes behind objects are screened by their silhouette. Both styles share live speed, size, wind (metres per second), gusts and flutter controls, alongside density, pile and melt. A separate wind effect takes precedence. The weather volume is populated immediately and continues beyond the screen edges; strong wind does not leave empty side strips. speed: 0 freezes the flakes and gust phase; changing speed or style does not restart the snowfall. White, softly transparent sprite edges stay in the same depth-sorted pass as the crystals, avoiding the dark masks caused by converting some flakes to defocused discs. Settled snow follows the objects' actual upper surfaces, stays white in the natural style, and falls away when its support moves.

Custom shaders

An effect can carry a ray manifest: WGSL that ray mode runs on the GPU next to the engine's own passes. This page describes the stable api: 1 contract and the legacy api: 0 compatibility path.

Stable for the installed kinds below. volume, light, post, unlit layer and lens are the api: 1 contract. simulate and lit: true layers remain explicitly unsupported; no item shader material is promised. Existing api: 0 manifests are accepted with their existing semantics.

Support matrix

“CPU hooks” means the effect's own draw, glyph, offset and particle drawing, subject to its cpu policy. A GPU manifest is never translated to glyphs or wireframe edges.

Part kind Ray ASCII Wireframe api: 1 state
volume: an analytic participating medium marched by the engine Installed; ready after validation, compilation and media admission CPU hooks CPU hooks Stable
light: up to 256 light slots written from JavaScript Installed CPU hooks CPU hooks Stable
post: a pointwise pass at the hdr or display stage Installed CPU hooks CPU hooks Stable
layer, lit absent or false: a quad, billboard or screen sheet placed behind or in front of an item Installed, depth-tested against solids CPU hooks CPU hooks Stable
layer with lit: true unsupported; no GPU batch from this manifest CPU hooks CPU hooks Unsupported
lens: a world sphere whose rays are bent and walked against solids with bounded queries Installed; composition limits below apply CPU hooks CPU hooks Stable
simulate unsupported; no GPU batch from this manifest CPU hooks CPU hooks Unsupported
Shader materials replacing a scene item's BRDF Not available Not available Not available Not in the contract

Prepared buffer/texture uploads are part of the same contract through Effect.prepareRayResources; see resource uploads. Public CPU validation is exported; the GPU compiler and GPU handles are not. Runtime installation status is read through scene.stats().effects.

Versioning and migration from api: 0

The API version belongs to each manifest, not to the package as a whole. api: 0 and api: 1 currently use the same declarations, WGSL ABI, validation and runtime behavior. There is no automatic rewrite and no migration diagnostic: changing only api: 0 to api: 1 opts the same manifest into the stability promise. New manifests should use api: 1; old ones can remain on api: 0 as a legacy, non-stable compatibility path. The api: 0 contract is not covered by the api: 1 freeze and may change in a future release.

Within api: 1, a release may fix implementation defects, improve diagnostic wording or add warnings, add helpers without changing existing ones, and add optional declarations whose omission preserves existing behavior. FxPart and diagnostics may also grow by additions within api: 1, so consumers must handle a default case for part kinds and diagnostics they do not know. The FxStatus["state"] union does not change. A later candidate part kind has its own row in the support matrix; when installed it reports ready and also emits the warning diagnostic candidate kind (api: 1 candidate; may change before it is frozen). It remains a candidate until separately promoted and does not change the frozen meaning of the five installed kinds above.

The freeze does not cover SimulatePart or the lit slot of LayerPart: those typed-but-unsupported slots, their declarations and their diagnostics may change within api: 1.

api: 2 is required to remove or rename an existing frozen kind, field, type or helper; change an entry signature, units, colour/alpha convention, default, ownership rule or fallback rule; tighten a limit so a previously valid manifest fails; or otherwise change an existing manifest's documented result. Relaxing a limit or adding an optional, backward-compatible capability does not by itself require api: 2. Security or robustness corrections, and device-dependent compilation or admission, may reject a manifest accepted by an earlier release or on another device without requiring api: 2. A future api: 2 does not withdraw api: 1 support.

Imports and public validation

Everything comes from the package root, with no deep imports. dist/ray/fx/* is internal, and the package exports map does not expose it.

import {
  createScene, validateRayManifest,
  type Effect, type EffectFrame, type RayPart, type FxPart,
  type VolumePart, type LightPart, type PostPart, type LayerPart, type LensPart,
  type SimulatePart, type FxLayerPlace, type ParamDecl, type ResourceDecl,
  type BudgetDecl, type FxWriter, type FxLightValue, type FxValidation,
  type FxStatus, type FxDiagnostic,
} from "mote-engine";

const checked: FxValidation = await validateRayManifest(candidate); // candidate may be unknown JSON
if (!checked.ok) console.error(checked.diagnostics);

validateRayManifest is asynchronous so its CPU validator loads on demand rather than becoming an eager dependency of every ASCII page. With the current plain, minified browser bundle, the first call downloads about 386 KB for the validator chunk. It acquires no adapter or device and exposes no GPU handle. It performs the same structural, ABI, resource-declaration and static-work checks used before installation; it does not run the driver compiler, bind scene item names, or apply device-specific and aggregate media admission. Therefore ok: true means eligible for those later gates, not guaranteed ready. Its FxValidation contains a fresh ok flag and diagnostics array.

The declarations name no WebGPU type. A project without @webgpu/types compiles them with skipLibCheck: false.

The manifest

const ray: RayPart = {
  api: 1,
  cpu: "none",                        // "all" (default) | "particles" | "none"
  params: { density: { type: "f32", default: 2, min: 0, max: 8 }, glow: { type: "color", default: "#ff8a3d" } },
  wgsl: `…one module for every part…`,
  parts: [
    { kind: "volume", name: "fogball", fn: "fog", bounds: { min: [-1, -1, -1], max: [1, 1, 1] }, animated: true },
    { kind: "light", name: "lamp", max: 1 },
    { kind: "post", name: "grading", fn: "grade", stage: "hdr" },
  ],
};
const effect: Effect = { name: "my-shader", ray, frame(f) { /* feed f.fx */ }, draw(f) { /* fallback */ } };
scene.addEffect(effect);

Rules checked on the CPU before anything reaches the GPU:

WGSL module rules

fxVisible and fxShadow retain eight geometric visits per query, shared by TLAS nodes, BLAS nodes and triangle tests. Procedural surface operations do not consume those eight visits. Instead, an entry that calls either helper reserves its fixed work first, then receives separate scalar-operation and loop-visit credits from the remaining limits above. The declared cost multiplier applies before those credits are allocated. Wrappers, loops and later queries in the same entry share the credits; they cannot refill them. Volume sampling, including sky and shadow sampling, starts a new credit allocation for each actual user-entry invocation.

Every surface operation pays its conservative opcode/profile cost and one visit before evaluation. Within both credits, the complete original surface/material formulas run. If either credit cannot pay the next operation, that query returns opaque visibility/transmittance; a partially evaluated surface cannot create a transparent hole. This enforces the declared work limit on previously unbounded procedural work. The fault belongs to that query: a later query clears the fault while retaining the remaining credits and its own eight geometric visits. Base Ray rendering and engine-generated segment shadows use their original surface evaluation without the user-query credits. A query-bearing entry can be rejected at a higher cost weight or by aggregate volume planning; the engine does not reduce material quality or march steps to admit it.

Public ABI (types and helpers callable from your WGSL): FxCtx FxParams FxRay FxMedium FxPhase FxBent FxSeg FxSurface FxLight, fxItem fxHas fxCameraPos fxCameraDir fxWorldToView fxProject fxPixelSize fxDistance fxSurface fxId fxLightCount fxLight fxLightAt fxShadow fxVisible fxSunTransmittance fxAmbient fxAmbientIn fxSky fxPhaseHG fxPhaseTwoLobe fxPhaseMie fxPhaseDraine fxPhase fxStep fxOctaves fxPowder fxBlackbody fxNoise3 fxNoise3p fxWorley3 fxFbm3 fxCurl3 fxIgn.

struct FxCtx { time: f32, dt: f32, frame: u32, tier: u32, steps: u32, budgetScale: f32, params: FxParams };
struct FxPhase { kind: u32, p: vec4f };                       // build with fxPhaseHG(g), fxPhaseTwoLobe, fxPhaseMie, fxPhaseDraine
struct FxMedium { sigmaT: vec3f, albedo: vec3f, emission: vec3f, phase: FxPhase };

c.time and c.dt are in seconds (the scene clock). c.tier is the ray quality tier, from 0 (lowest) to 4 (ultra).

Entry signatures, colour, alpha and units

volume: fn name(p: vec3f, c: FxCtx) -> FxMedium

post: fn name(color: vec4f, pix: vec2f, c: FxCtx) -> vec4f

layer: fn name(uv: vec2f, i: u32, c: FxCtx) -> vec4f

{ kind: "layer", name: "halo", fn: "halo", shape: "billboard",
  place: { of: "ship", side: "behind", offset: 0.2, soft: 0.5 } }

lens: fn name(r: FxRay, c: FxCtx) -> FxBent

{ kind: "lens", name: "hole", fn: "bend", center: [0, 0, 0], radius: 8 }

A lens is a sphere in the world. Every pixel whose ray enters it calls your function, which returns the path that ray really takes. The engine then walks that path against the scene's geometry: this is not a screen warp, and it can show what is in no pixel of the picture, such as something behind the camera or behind a wall.

struct FxRay { o: vec3f, d: vec3f, tMin: f32, tMax: f32 };
struct FxSeg { o: vec3f, d: vec3f, len: f32, shift: f32 };
struct FxBent { segs: array<FxSeg, 32>, count: u32, captured: bool };

light: no WGSL

max (1–256) reserves slots, which you write with fx.light(part, index, value). A slot is off while its intensity is ≤ 0 (the initial state) and keeps its last written value. Effect lights join the scene's lights up to 32 in total.

FxLightValue field Meaning
kind "point", "spot" or "directional"
position World units (point, spot)
direction Unit vector, normalised by the engine. Directional: towards the light. Spot: where it points
color Linear RGB
intensity Scale on color
range, radius World units: where the light fades to nothing, and the emitter's radius for soft shadows
angle Radians. Spot: half-angle of the cone. Directional: apparent diameter
flare Show the light's disc in this frame's emission: bloom takes it, and the lens flare's image passes when ray.flare is on. It is not one of the flare's key sources

Effect spots have no penumbra and always cast shadows.

Feeding the shader: FxWriter

f.fx exists only in ray mode, inside the effect's frame hook:

frame(f) {
  const fx = f.fx;
  if (!f.ray || !fx) return;              // ascii, wireframe: no writer
  fx.set("density", density);             // a declared param, within its min/max
  fx.transform("fogball", matrix);        // 12 numbers, row-major 3x4, local → world: [a b c tx, d e f ty, g h i tz]
  fx.light("lamp", 0, lamp);
  fx.advection("fogball", 0.1, 0, 0);
}

CPU policy and the fallback you write

The engine never turns your WGSL into ascii glyphs, effect dots or wireframe edges. What draws when the GPU version does not is whatever your CPU hooks draw (draw, glyph, offset, particles). The cpu policy decides which of them keep running while the GPU version is installed:

cpu Installed in ray mode Not installed (ascii, wireframe, no WebGPU, pending, failed, unsupported, quarantined)
"all" (default) draw, glyph and offset still run, alongside the GPU version They run
"particles" draw, glyph and offset are suppressed. The scene has no separately gated particle hook on this base, so this currently behaves exactly like "none": particles you draw from draw (e.g. f.dots) are suppressed too They run
"none" draw, glyph and offset are suppressed They run

frame always runs, because it feeds the writer. trigger, set and mesh hooks are not gated by the policy either. The suppression switches together with the GPU batch: it starts when the batch is installed and stops when it is removed or lost. A manifest does not mean an equivalent fallback exists. If you want something to show in ascii, write it (the example draws a cluster of soft dots with f.projectWorld and f.dot).

Diagnostics: scene.stats().effects

scene.stats().effects is a readonly FxStatus[]: one entry per running effect that has a ray manifest, in the order of the running effects (scene effects, then the current stage's). Entries are created only when ray mode runs with a GPU device.

The engine's effect host (the manifest validator, the WGSL bindings and the trusted query cache) is loaded with import() the first time ray runs an effect that has a ray manifest; an ascii or wireframe page, or a ray scene with no manifest, never downloads it (with the <mote-scene> bundle it is the host-….js chunk and a chunk it shares with ray's side). While it loads, the effect is pending and its CPU hooks draw, as while it is validated and compiled. In ray, scene.ready also waits for the host to load when a scene effect or a stage's effect has a manifest, but not for the manifest to compile: wait for ready in stats().effects for that. ready never rejects, and a ready already handed out settles when the scene no longer needs the host (destroyed, switched away from ray, fallen back, its device lost, or no effect with a manifest left), as it does for ray's own device; the load itself goes on for the other scenes of the page. The stats().effects array and its entries published while the host loads are the ones the host then keeps up to date. If the host does not load (a network error, a chunk missing from the folder), the effect reads failed with the custom effect host did not load (…), its CPU hooks keep drawing, and the load is tried again the next time ray resumes. A scene that never reached ray (ascii, wireframe, or ray fell back) has an empty array: check scene.mode and stats().ray.fellBack. After a switch from ray to another mode, the entries stay and read failed until ray resumes and prepares them again. The array and its objects are reused, so copy what you want to keep.

type FxStatus = { state: "pending" | "ready" | "failed" | "quarantined" | "unsupported"; diagnostics: readonly FxDiagnostic[]; gpuMs: number | null };
type FxDiagnostic = { part: string; line: number; column: number; length: number; severity: "error" | "warning"; message: string };
State Meaning
pending Being validated or compiled, or the engine's effect host is still loading
ready Installed in the current GPU batch
failed Rejected by the validator, the WGSL compiler, the media planner or the device, or the engine's effect host did not load. A failed reload of a new manifest leaves the previous installed version drawing
unsupported Contains a part with no renderer consumer (simulate, or a layer with lit: true)
quarantined The device was lost within 120 frames of installing this manifest. A new manifest object is needed to try again

Where diagnostics come from:

For the example's deliberately broken manifest, the CPU validator gives:

error broken:2:65 Unknown or engine-private identifier 'anisotropy'

For its simulate manifest, the state is unsupported with simulate installation is unsupported in foundation phase 1 and This part has no installed renderer consumer; CPU fallback remains active.

To change the WGSL, give the effect a new manifest object (or replace the effect). Editing a manifest in place does not reload it.

Known limits on this base

These are explicit api: 1 limits, not silent fallbacks or promises of future support.

Public resource uploads

Effect.prepareRayResources(writer, signal) prepares buffer and texture content outside frame hooks. It is called once for each demanded tier of each scene's manifest version. It exposes no device, GPU resource or private packed offset. The old composition stays installed during a replacement's preparation.

import type { Effect, FxResourceWriter } from "mote-engine";
const writers = new Set<FxResourceWriter>();
const effect: Effect = {
  name: "resource-example",
  ray: myManifest, // declares resources and their five tier sizes
  async prepareRayResources(writer, signal) {
    writers.add(writer);
    signal.addEventListener("abort", () => writers.delete(writer), { once: true });
    await writer.writeBuffer("gain", new Float32Array([0.5]));
    await writer.writeTexture("image", rgbaBytes, {
      origin: [0, 0, 0], size: [width, height, 1], bytesPerRow: width * 4,
    });
  },
};

Resource uploads are covered by api: 1 and remain accepted in legacy api: 0 manifests. They do not make simulate, lit layers or item shader materials supported.

Candidate: surface (shells over one item)

A candidate part kind of api: 1: not covered by the stable matrix above and free to change before it is frozen. It installs and reports ready like the other kinds, and its status always carries the warning surface: candidate kind (api: 1 candidate; may change before it is frozen), from validateRayManifest on. FxStatus.state has no extra value for it.

Part kind Ray ASCII Wireframe api: 1 state
surface: engine-generated shells over one item; your WGSL decides each shell fragment Installed: shells drawn into the G-buffer, an engine-owned stand-in for traced rays The item's base mesh, CPU hooks The item's base mesh, CPU hooks Candidate
{ kind: "surface", name: "fur", fn: "strands", item: "creature", shells: 24, length: 0.15,
  gravity: 0.35, density: 0.55, color: "#c98a4b" }

surface: fn name(s: FxSurfaceIn, c: FxCtx) -> FxSurfaceOut

struct FxSurfaceIn { p: vec3f, rest: vec3f, n: vec3f, uv: vec2f, shell: u32, shells: u32, h: f32, item: u32, facing: f32 };
struct FxSurfaceOut { coverage: f32, albedo: vec3f, normal: vec3f, roughness: f32, occlusion: f32, emission: vec3f };

Traced rays never run your WGSL. For each installed part the renderer adds a trace-only stand-in: the item's mesh pushed out along its normals by half of length, with a blended material of opacity density and colour color. Shadow rays take its fractional coverage (soft fur shadows on the floor and on the item, tips above it stay lit), reflections and the probe cache see it stochastically, and it is never rasterised.

The path tracer holds the hybrid picture wherever an item with shells, or its stand-in, is seen in a pixel or its 3 × 3 neighbours (the stand-in is rasterised into a mask for this, depth-tested against the hybrid's depth): the refined still keeps exactly the fur the hybrid frame drew (it neither disappears nor grows), while the rest of the picture refines as before. A hidden item has neither shells nor a stand-in. Each installed part keeps its own stand-in mesh for as long as it is installed: several parts on one item do not rebuild each other, and a part reinstalled with another length lets the old mesh go.

Limits of the candidate:

Options

Option Default
stages the stages (required)
mode "ascii" how the objects are drawn: "ascii", "ray", "wireframe" or "custom" (see Render modes)
glyphRenderer "auto" glyphs only: "auto", "gpu" or "canvas", what draws ASCII's characters and the effects' glyphs; live as scene.glyphRenderer
renderer none mode "custom" only: the renderer plugin, a registered id or a RendererPlugin
plugins none renderer plugins for this scene alone, before the page's under the same id
ray {} how ray draws: quality, samples, exposure, toneMapping, floor, fallback, flare (see Ray; scene.setRay changes them while it runs)
particleStyle {} independent emitters: size, bloom, focus, aperture, haze, sprites and adapter
lights, shadows today's lights, none the scene's lights (see Lights), and ASCII's shadow maps and floor shadow
physics none rigid bodies: gravity, floor, walls, colliders, grab (see Physics)
orbit none the view turned about the origin, { yaw, pitch } in degrees (see Orbit)
particles 16000 in ASCII and solid Ray, 40000 in Wireframe the fewest particles drawing the objects; the scene adds more when objects cover more of the canvas (a big scale) and gives them back when they shrink (in ray, also as many as the solids' skins need)
maxParticles 200000 in ASCII, 48000 in solid Ray, 500000 on Wireframe GPU (50000 on Canvas) the most particles; set it to particles for an exact count
asciiScaleDensity true ASCII: an object larger on the screen than at its own size takes more samples (within maxParticles), so its surface stays as dense; false keeps each object at its share of particles (cheaper, a big object draws paler); live as scene.asciiScaleDensity
hold, morph 5, 3.8 seconds a stage holds, and a morph takes; a stage can set its own hold
autoplay true move on by itself
fontSize, lineHeight, fontFamily 11, 14, a monospace stack the character grid
colors grey and blue { text, accent } or a function; cssColors() reads CSS custom properties
zoom, origin 0.85, [0.5, 0.5] size of a unit, and where the origin sits on the canvas
camera 12 camera distance in units: larger is flatter
light upper left, front direction towards the light
ramp .,:-=+*#%@ characters from dark to bright
halo 1 the glyphs flickering around the objects and flying off them, 0 to 1
trails true short trails behind fast particles
smoke "rise" how the smoke moves in a morph: "rise" or "sideways"
morphStyle "smoke" how a morph looks: "smoke", "direct", "swirl", "explode"
interactive, pointerTarget true, the canvas's parent clicks and pointer moves drop ripples (and grab and throw bodies, with physics)
click "ripple" what a click does: ripples, "none", effects (explode(), holes(), shockwave()…), several in a list
ambientRipples true a ripple now and then on its own
keepClear elements (or boxes) the scene keeps clear of, such as a heading over the canvas: the characters and the dots leave them, and in ray the solids fade under them on the screen
clearFloor 0 how much still shows over what keepClear keeps clear (0 to 1): a little lets the figures and the effects pass faintly under a heading, so the clear area does not read as a solid panel
ambientFps 30 frames per second while nothing moves fast; the display's full rate during morphs and interaction
reducedMotion "static" with the system's reduce motion, draw still frames (in ray the still frame is drawn again at the idle rate, so the path tracer refines it: nothing in it moves); "ignore" animates anyway. The system's setting is followed as it changes, without a rebuild: scene.still says which it is, and scene.reducedMotion changes this option on a running scene
sliceLayout false sample the stages again a few milliseconds at a time between frames, the stages on screen first, when the particles, the mode, the glyph size, the renderer or the size change (the picture keeps its points until the new ones are in, a few frames later); ray makes a new sky, and the surfaces of the stages not on screen, a slice at a time, and smoke spreads its warm-up over its first frames. The demo, with it on: no settings change makes a task over 50 ms on an M3 Max, the GPU 18–98 % busy with other work (a known issue aside: the Tornado scene, whose effect took 40–95 ms every frame, measured in the dots mode removed in 0.30.0). Off, every stage at once in the call
onFrame called every frame with the time in seconds
onState called with the scene when stage, stageCount, paused or still change, whoever changed them: it needs no frame, so it keeps a page's text in step on a still or paused scene
paused false start paused with one picture (scene.pause() alone never draws a first one)
clock none (the time runs) { time }: the scene's time fixed at time seconds, so two pictures of it can be compared: the stage that time selects, animations where they end, no time passing for the effects and the physics, the same random numbers every frame (scene.setTime moves it; there is no way back to the running time); { time, step }: a stepped clock, see The stepped clock)

scene.mode says how the objects are drawn and scene.setMode("ascii" | "ray" | "wireframe" | "custom") changes it (setMode("custom", renderer) with a plugin) (in TypeScript a SceneMode; a scene made from options written inline without ray, no mode: "ray" and no ray options, is typed as before ray came, its mode a RenderMode, "ascii" | "wireframe": give ray: {} to switch it to ray later; a scene made from a SceneOptions variable, or held in a variable typed Scene, may be in ray, and its mode is a SceneMode). scene.particles, scene.maxParticles, scene.fontSize, scene.zoom, scene.morph and scene.morphStyle can be changed while the scene runs (scene.particles = undefined and scene.maxParticles = undefined give the mode's own back). scene.ready resolves when the sources, the physics world and, in ray, ray's side and device are there (one promise until one of them changes). Other methods: scene.ripple(x, y), scene.setColors(...), scene.refreshColors() (after a theme change), scene.zoom = 1.2, scene.resize(), scene.pause() and scene.resume() (no frame comes, Ray's refinement stops too; a picture that is up stays, drawn again once when something makes it stale; a scene paused before its first frame draws nothing, and the paused option starts one paused with a picture; scene.paused says so; scene time goes on, so the frame after resume() shows the time it is then, and goTo() while paused asks for a morph that waits for resume(), where show() puts the stage on the picture), scene.capture({ space, refined, samples }) (a promise of the next frame's picture: as displayed, 8-bit sRGB, or in ray the linear picture before the tone map, float RGBA premultiplied; in ray it can wait for the path tracer to refine it, refined: true: until stats().ray.refined, the hybrid's held picture at once where the path tracer is off), scene.setTime(seconds) (the time fixed there, as the clock option does: it cannot be undone; on a stepped clock a seek forward, below), scene.clock, scene.time, scene.frame and scene.step() (the stepped clock, below), and scene.stats(), which gives the grid, the particles in use, the points per stage, the density drawn, the frames drawn in the last second (fps), the time a frame takes (frameMs), whether the scene is resting at its ambient rate, what draws (backend) and, in ray, the GPU's time, the internal scale, the path tracer's samples and state, the probes and the solids (ray, which also says why ray fell back). Ray, lights, physics and the orbit add scene.ray, scene.setRay(options), scene.setLights(list), scene.setLight(i, partial), scene.shadows, item.material, item.body, scene.physics, scene.spawn(item), scene.remove(id) and scene.orbit.

A scene can also be written as JSON (schemas/scene.schema.json, which the package ships): sceneFromJson(doc) checks the document (no browser needed) and gives the options to make it with (createScene(canvas, r.options), on a canvas of r.camera.width × r.camera.height CSS pixels), its camera, its render settings and its time, or every error found, each with the field's JSON pointer.

The scene pauses while the canvas is off screen or the tab is hidden.

The stepped clock

clock: { time: 0, step: 1 / 60 } makes a stepped scene for reproducible animation: its time starts at time and moves only when scene.step(frames = 1) is called (1 to 600 frames a call). Each queued step advances the scene by exactly step seconds (k / 60 with k a whole number from 1 to 60, else a RangeError), is consumed by exactly one frame, and that frame is the only one on which the effects get a dt (exactly the step) and the physics world runs (exactly k fixed steps, onStep before each); tweens, morphs and autoplay run on the stepped time, and the random numbers are seeded by the frame's index (frame 0 draws what the fixed clock draws at the same time). Between two steps the scene is a fixed scene: frames keep coming (in ray the path tracer refines the still picture, capture({ refined: true }) works as it does), nothing moves and no CPU state changes. The same document and the same steps give the same transforms, bodies and CPU pictures bit for bit, and the same state as real time on the 1/60 grid.

scene.step() resolves with { frame, time } after the frame that consumed its last step; calls are serialized (Promise.all([scene.step(), scene.step()]) resolves frames 1 and 2 in order), wait for scene.ready (a step taken before the physics world is there would advance the time with no physics step), and reject with { kind, message }: "paused" (a pause rejects the steps queued), "destroyed", "load", "timeout" (no frame consumed a step within 60 s a frame: a hidden page, a canvas of no size). scene.clock reads "real", "fixed" or "stepped"; scene.time and scene.frame read the last step applied. On a stepped scene scene.setTime(seconds) is a seek forward only: on the step grid it resolves when that frame is reached, with the frames already queued when they cover it (the same { frame, time } and the same rejections as step), else queuing the steps missing; off the grid or behind the frame reached it throws a RangeError (backward seek is not available in 0.40: reload the document and step again).

On a stepped scene the pointer is ignored (interactive and the physics grab read false; a director triggers effects and ripples by the API), ambient ripples and the halo's flying glyphs are off, reducedMotion: "static" is not followed and sliceLayout is ignored (every stage is prepared at once). A canvas resize, a font's readiness, scene.resize(), scene.fontSize and scene.zoom are measured as they arrive but applied only at the next step's frame, before it is drawn (until then scene.fontSize and scene.zoom read what the frames draw with), and the DOM colliders of physics.colliders are measured again only on stepped frames; each is recorded as a system operation in the scene's internal log (the director's replay, 0.40, re-applies them at the same frame).

A still frame as text

renderText draws a source as plain text, without a browser:

import { renderText } from "mote-engine/text";
import { gltfSource } from "mote-engine/gltf";

console.log(renderText(gltfSource(bytes), { cols: 100, rows: 45, rotation: [20, -30, 0] }));

Connecting an AI over MCP

The package installs a second command, mote-engine-mcp: the director's tool server. It is a local process that speaks newline-delimited JSON-RPC 2.0 on its standard input and output, with the three MCP methods (initialize, tools/list, tools/call), so an MCP client (Claude Code, Claude Desktop, another agent harness) starts it and attaches directly; a program of your own writes the same JSON lines. It drives a scene in headless Chrome through the director's API (the stepped clock, camera rigs, the timeline, operations and their log, Scene JSON v2), so an AI can load a scene, look at it, stage it, and render its frames, all with data: nothing it sends is ever evaluated as code.

It needs Node 20 or later and Chrome (--chrome <path>, CHROME_PATH, or one of the usual places), and nothing else: no dependency, no network service (it listens on stdio; its own Chrome is served the page from a loopback port, under a path no other process knows).

# Claude Code, in the project that has the package installed:
claude mcp add mote-director -- npx mote-engine-mcp --out ./renders --root .

For any MCP client that takes a configuration file (.mcp.json in a project for Claude Code, claude_desktop_config.json for Claude Desktop):

{
  "mcpServers": {
    "mote-director": { "command": "npx", "args": ["mote-engine-mcp", "--out", "./renders", "--root", "."] }
  }
}

By hand, one JSON object a line in, one a line out:

mkdir -p renders
printf '%s\n' \
  '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"me","version":"1"}}}' \
  '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"load_scene","arguments":{"document":{"version":2,"camera":{"rig":{"kind":"orbit","center":"box","distance":4,"yaw":20,"pitch":10},"fov":35,"width":640,"height":360},"objects":[{"id":"box","shape":"box"}],"lights":[{"kind":"directional","direction":[0.3,1,0.5],"intensity":2}],"render":{"mode":"ascii"}}}}}' \
  '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"preview","arguments":{"name":"first"}}}' \
  | npx mote-engine-mcp --out ./renders        # writes renders/first.png
Option
--out <dir> Mandatory, and it must exist: the only folder anything is written to.
--root <dir> The folder a document's model and environment-map paths are relative to. Without it no file is served.
--mode ray|ascii|wireframe The mode scenes are drawn in unless a call names one (default: the document's render.mode).
--allow-url <origin> An origin besides the server's own that the page may fetch from (repeatable). Every other request is failed at the network layer.
--quota-bytes N, --quota-frames N The session's disk quota: PNG bytes (default 8 GiB) and pictures (default 20 000) written.
--timeout S The time one command to the page has (default 120 s).
--chrome <path> Chrome's executable.
--json A wrong command line is told as one JSON object on stdout ({ ok: false, kind: "usage", message }), not as text on stderr.

The tools (their input schemas are generated at startup from schemas/scene.schema.json, schemas/scene-ops.schema.json and schemas/timeline.schema.json, so what an AI is shown is what the validators accept):

Tool Takes Answers
capabilities — the engine's version, the modes this Chrome can draw, the effects with their parameters, the rig kinds, every cap and quota with what is left, the schemas
load_scene document (Scene JSON v2, or v1), expectAssets? { ok, errors, assets }. A fresh page; the scene is stepped at 60 frames a second unless the document gives its own clock
describe_scene — scene.describe() (a reloadable v2 document, diagnostics, the assets with digests), a stats() summary, the frame, the observations waiting
apply_ops ops (an operation or a batch) the engine's OpsResult
set_timeline timeline (or null) { ok, errors, duration }
step frames? (1 to 600) { frame, time }
goto_frame frame forward it steps; backward it reloads the document and re-applies the log up to that frame (what was applied after it is gone)
preview name, width?, height?, mode?, samples?, refined?, overwrite? { png, frame, time, stats }: <out>/<name>.png, and the picture inline as an MCP image when it is no more than 1 MiB
render_sequence name, from, to, fps?, width?, height?, mode?, samples?, overwrite?, verify? { frames, manifest, truncated }: <out>/<name>/frame-%06d.png and frames.json (the document, the timeline, the log, the assets with digests, the engine's version, per-frame times and stats, replayable, truncated)
query { kind: "pick", x, y }, { kind: "bounds", id } or { kind: "project", point } the observation API's answer
events since? the observations after that sequence number (at most 1024)
log after?, limit? one page of the operations log, next, complete

A failed call is { ok: false, kind, message, ... } (MCP's isError set), the kind one of usage, scene (with the validators' JSON-pointer errors), no-chrome, no-webgpu, timeout, readback, gpu, exception, interrupted, internal, too-large, busy, exists, quota, asset-mismatch (path, expected, got). A message that is not a call at all (not JSON, an unknown method or tool, too large) is a JSON-RPC error with the kind in error.data.kind. Every response is exactly one JSON object on one line.

Limits, all checked before the page is asked anything:

Frames are reproducible because the clock is stepped, not because time is faked: Chrome runs in real time. A batch is handed whole to the scene (validated whole and refused whole, as scene.applyOps does), and any frame can be reached, or rendered, again by re-applying the log; a frame that falls inside a batch's step operations is reached by re-applying that batch up to it, then the rest of it (a sequence's manifest counts such batches in splitBatches; a timeline cue's operations that were waiting behind that batch apply at that frame instead of at the batch's end). Ray and wireframe need WebGPU in that Chrome (capabilities says which modes it has); ascii needs none. Chrome never outlives the server, however it ends, and its profile folder is removed when the server exits; after a forced kill (SIGKILL, which no process survives to clean up after) Chrome still ends, and the profile folder left in the temporary folder is removed by the next server that starts.

Code backdrop

import { createCodeBackdrop } from "mote-engine/backdrop";

const backdrop = createCodeBackdrop(canvas, {
  keepClear: () => document.querySelectorAll(".hero > *"), // the code keeps clear of the heading
  snippets: [myCode],                                      // C# by default
  keywords: ["fn", "let", "mut", "pub"],                   // the language's keywords
});

Columns of code cycle on their own clocks: readable, swept into glyphs (identifiers first, keywords and punctuation last), scrambled, then decoded into the next snippet. Keywords are drawn in the accent, strings and numbers in colors.string.

Performance

Applications can provide particleStyle.adapter to replace the emitter output device while keeping the simulation and effects. stats().backend identifies the concrete device; the existing glyphRenderer flag remains compatible. Native adapters are experimental; effect support depends on the host application.

glyphRenderer: "auto" | "gpu" | "canvas" (an option, and scene.glyphRenderer while it runs; ASCII's characters and the effects' glyphs only) chooses what draws the glyphs; stats().glyphRenderer says what draws them now. Characters are drawn by the GPU with WebGL 2, every glyph of a frame in one call; every modern browser has it (Chrome, Edge, Firefox, Safari, on desktop and mobile). Without it, or if the GPU context is lost, the engine draws each glyph on the 2D canvas: the same picture, more CPU. useGpu(false) forces the canvas.

In ray the CPU's frame is the particles (the skin, the effects' matter) and the scene's bookkeeping; the skins' presence grids are dilated on the GPU, every one that changed the same frame, and only the objects whose particles' skin changed are marked again. The GPU's frame is the tracing and the passes at the canvas's resolution, which auto holds by the internal resolution and the lighting tier; on this scene and this machine it settles at lowest (one shadow ray a pixel, no reflection in the catcher, a third to a half of the resolution per side), and under a heavier load still auto takes its last resort, the whole frame at half the canvas's pixels per side. A still picture is refined by the path tracer with what one frame's budget leaves, a sample spread over up to 256 frames on large canvases, painted at the scene's idle rate.

Memory

destroy() (and the function the page effects return) stops the frames, removes every listener and observer, and releases the glyph atlases and the WebGL context at once rather than at the next garbage collection: browsers keep only a few WebGL contexts alive, and an app that mounts and unmounts effects (a theme switched on and off) must not pile them up. Caches are bounded (glyph atlases refill when full, colours are capped), and every effect keeps its state in fixed-size pools.

In ray the GPU holds about 236 bytes a device pixel at high: the full-resolution targets 141 (the denoiser's accumulation among them, and the 8 of the light that glass lets through to the particles behind it), the denoiser's spatial stage 72 × the internal scale² (63 at high's largest, 72 at ultra), the held picture's copies 8, the path tracer's mean 24, and 8 more when the environment is the background. A canvas past 5.2 million device pixels (MAX_PIXELS, a fixed ceiling) is drawn at that size and stretched to the canvas, its projection kept (stats().ray.output says the share per side), so at high ray's frame holds about 1.23 GB at most:

Canvas (device pixels) Pixels Drawn at Memory at high
1920 × 1080 2.07 M whole 0.49 GB
2560 × 1440 3.69 M whole 0.87 GB
2880 × 1800 5.18 M whole 1.22 GB
3840 × 2160 8.29 M 0.79 a side (5.2 M) 1.23 GB

Textures and models add their own (Heavy models).

scene.capture() also allocates temporary readback storage and the pixel array it returns, on demand. Those capture buffers are separate from the frame-target estimates above.

Effect reference

All controls below can be updated with effect.set({ parameter: value }). Appearance and support depend on the render mode. Numeric limits describe the recommended ranges for controls.

wind

Parameter Default Range / choices
strength 1 0–3
angle 0 -180–180 °
erosion 1 0–3
gusts true true / false
streaks true true / false

vortex

Parameter Default Range / choices
style air air, water, energy
strength 1 0–3
radius 1.1 0.2–3
x 0.5 0–1
y 0.5 0–1
core 0.18 0.05–0.6
inflow 1 0–3 ×
density 1 0–3 ×
spin cw cw, ccw
trail 1 0–3 ×

magnet

Parameter Default Range / choices
mode repel repel, attract, ferrofluid
radius 0.35 0.05–1.5
strength 1 0–3
spikes 10 3–24

explode

Parameter Default Range / choices
kind fireball fireball, dust, classic
power 1 0.2–3
recover 2.2 0.5–8 s
debris true true / false
fireball 1 0–3 ×
smoke 1 0–3 ×
flash 1 0–3 ×
light 1 0–3 ×
shockwave true true / false

holes

Parameter Default Range / choices
kind burn burn, punch
radius 0.22 0.05–0.8
heal 5 0.5–20 s
speed 1 0.1–4 ×
char 1 0–3 ×
smoke 1 0–3 ×
light 1 0–3 ×

shockwave

Parameter Default Range / choices
style blast blast, energy
speed 1.8 0.3–5
width 0.14 0.03–0.5
power 1 0–3
dust 1 0–3 ×
distortion 1 0–3 ×
condensation 1 0–3 ×

gravity

Parameter Default Range / choices
strength 1 0–4
repose 33 15–50 °
chunks 0.5 0–1
dust 1 0–3
bounce 0.25 0–0.9
cycle 0 0–10 s

jelly

Parameter Default Range / choices
amplitude 0.06 0–0.3
speed 3 0–12
wavelength 0.45 0.1–2
poke 1 0–3 ×
damping 2.2 0.2–8 /s

blackHole

Parameter Default Range / choices
place beside beside, fixed
x 0.5 0–1
y 0.5 0–1
strength 1 0–3
radius 1.4 0.3–3
duration 8 2–20
size 0.3 0.3–3
inclination 80 0–90 °
tilt 0 -180–180 °
diskInner 3 1.5–8 Rs
diskOuter 14 6–24 Rs
diskTemperature 2100 1500–30000 K
palette thermal thermal, lilac, blue
hotspots 0.7 0–2
turbulence 1 0–2
spin 1 -3–3
doppler 0.15 0–1

rainbow

Parameter Default Range / choices
style spectrum spectrum, film, oil
mode diagonal diagonal, radial, vertical, horizontal
speed 0.18 -1–1
scale 1 0.2–5
saturation 0.85 0–1
thickness 500 60–900 nm
drain 1 0–1.5
swirl 1 0–2
intensity 1 0–1

glitch

Parameter Default Range / choices
intensity 1 0–3
rate 1 0–5
speed 1 0–4
tear 1 0–2
rgb 0.7 0–2
blocks 0.45 0–1
noise 0.3 0–1

shake

Parameter Default Range / choices
amplitude 0.05 0–0.3
decay 0.6 0.1–3 s
continuous 0 0–1
frequency 12 1–40 Hz
axis both both, horizontal, vertical

scanlines

Parameter Default Range / choices
strength 0.5 0–1
speed 0.25 0–2
flicker true true / false
mask 1 0–1
curvature 1 0–3 ×
vignette 1 0–2 ×
hum 1 0–2 ×
interlace true true / false
wobble 1 0–3 ×
beam 0.6 0–1

dissolve

Parameter Default Range / choices
style burn burn, dust, classic
mode loop loop, out, in
period 7 1–20 s
edge 0.07 0.01–0.3
char 1 0–2 ×
glow 1 0–2 ×
smoke 1 0–2 ×
light 1 0–2 ×
drift 1 0–3 ×
angle -30 -180–180 °

hologram

Parameter Default Range / choices
color #5ab8ff CSS hex colour
jitter 1 0–3
scan 1 0–1
flicker 1 0–1
noise 1 0–3 ×
transparency 0.35 0–0.9
cone true true / false
glow 1 0–3 ×

matrix

Parameter Default Range / choices
color #3cff7a CSS hex colour
rain true true / false
density 1 0–3
size 1.7 0.5–6
speed 1 0–4
trail 1 0–3
intensity 1 0–3
mutation 1 0–4
head 1 0–2
surface 1 0–1
charset kana kana, binary, latin

neon

Parameter Default Range / choices
color #31b5ff CSS hex colour
pulse 0 0–3
failing true true / false
glow 1 0–3 ×
segments 6 1–32
warmup true true / false
tubes one one, two
color2 #2af5ff CSS hex colour
tube outline outline, fill

heatHaze

Parameter Default Range / choices
amplitude 1 0–3
from 0.2 0–1
speed 1 0–3
scale 1 0.25–3

laser

Parameter Default Range / choices
style physical physical, code
color #ff3b6b CSS hex colour
speed 0.45 0–3
width 3 1–12
intensity 1 0–3
angle 0 -90–90 °
light 0.6 0–3

fire

Parameter Default Range / choices
intensity 1 0–3
height 1 0.2–3
speed 1 0–3
turbulence 1 0–2
palette natural natural, blue, green, violet, red, custom
color #ff9d32 CSS hex colour
source objects objects, ground, pointer
light 0 0–2

smoke

Parameter Default Range / choices
density 1 0–3
opacity 0.85 0–1
source objects objects, ground, pointer
color #aeb6c1 CSS hex colour
speed 1 0–3
rise 1 0–3
turbulence 1 0–3
scale 1 0.25–3
wind 0 -2–2
windAngle 0 0–360 °

rain

Parameter Default Range / choices
density 1 0–4
angle 12 -60–60 °
opacity 0.35 0–1
source sky clouds, sky
splash true true / false
color #dedede CSS hex colour

snow

Parameter Default Range / choices
style natural natural, classic
density 1 0–4
speed 1 0–3
size 1 0.25–3
wind 0.15 -3–3
gusts 0.65 0–2
flutter 0.8 0–2
pile true true / false
melt 0.02 0–0.5

sparks

Parameter Default Range / choices
style classic classic, grinder, welding
rate 1 0–5
source edges edges, pointer, point, contact
x 0.5 0–1
y 0.5 0–1
direction -90 -180–180 °
spread 1 0–3 ×
speed 1 0–3 ×
gravity 1 0–3 ×
bursts 1 0–3 ×
trail 1 0–3 ×
curl 1 0–3 ×
bounce 1 0–2 ×
settle 1 0–3 ×
flash 1 0–3 ×
light 1 0–3 ×
smoke 1 0–3 ×
palette steel steel, stainless, hot, custom
color #ffb347 CSS hex colour
bokeh 1 0–3 ×

fireworks

Parameter Default Range / choices
rate 0.7 0.1–4
type festival festival, peony, chrysanthemum, multi, kamuro, willow, palm, ring, crossette, senrin, strobe, niagara
intensity 1 0.2–3
finale 30 0–120 s

starfield

Parameter Default Range / choices
speed 0.6 0–3
warp false true / false
count 420 0–3000
size 1 0.25–8
brightness 1 0–3
twinkle 0.35 0–1
color #e8f0ff CSS hex colour

bubbles

Parameter Default Range / choices
rate 1 0–5
source ground objects, ground, pointer
size 1 0.25–3
speed 1 0–3
rise 1 0–3
wobble 1 0–3
opacity 0.75 0–1
iridescence 0.65 0–1
color #e6f3ff CSS hex colour
wind 0 -2–2
windAngle 0 0–360 °

water

Parameter Default Range / choices
level 0.8 0.3–0.98
waves 1 0–3
speed 1 0–4
scale 1 0.25–3
opacity 0.7 0–1
reflection true true / false
reflectivity 0.8 0–1
distortion 1 0–3
glints 1 0–3
ior 1.333 1–2.5
color #3fa7ff CSS hex colour

lightning

Parameter Default Range / choices
interval 3 0.5–10 s
flash true true / false
color #d8ecff CSS hex colour
kind cloud-to-ground cloud-to-ground, cloud-to-cloud, forked, mixed
branchiness 0.5 0–1
restrikes 2 0–4
slowmo 1 0.5–10 ×

confetti

Parameter Default Range / choices
rate 1 0–5
burst 80 0–300
source sky sky, cannons
interval 2.5 0.5–10 s
shape mixed mixed, rectangles, strips, discs, squares
palette rainbow rainbow, party, pastel, gold, custom
color #ff4f8b CSS hex colour
size 1 0.3–3 ×
speed 1 0–3 ×
flutter 1 0–3 ×
tumble 1 0–3 ×
wind 0 -3–3 m/s
pile true true / false
linger 6 0–30 s

aurora

Parameter Default Range / choices
intensity 1 0–2
speed 0.15 0–1
angle 0 -180–180 °
rotation 0 -180–180 °
waveSpeed 1 0–3
raySpeed 1 0–3
bands 4 1–6
light 1 0–2
colorMix 1 0–1

fog

Parameter Default Range / choices
density 0.6 0–1
speed 0.12 0–1
height 0.55 0.1–1
turbulence 1 0–2
color #c4cdd3 CSS hex colour

tornado

Parameter Default Range / choices
x 0.3 0–1
width 0.9 0.2–2.5
taper 0.15 0.05–1
bend 0.5 0–2
spin 0.6 0–3
wander 0.3 0–2
pull 1 0–3
debris 1 0–4
speed 1 0–3
density 1 0–2
detail 1 0–2
flow 1 0–3
sceneLight 1 0–2
ground 1 0.35–1
color #8e9aaa CSS hex colour
debrisColor #52575e CSS hex colour

clouds

Parameter Default Range / choices
style overcast overcast, cumulus, layers
cover 0.5 0–1
speed 0.25 0–2
height 0.6 0.1–1
scale 1 0.3–3
detail 1 0–2
thickness 1 0–2
light 1 0–2
sceneLight 1 0–2
sunAngle -135 -180–180 °
color #9aa7b8 CSS hex colour

meteors

Parameter Default Range / choices
rate 0.6 0–4
speed 1 0–4
size 1 0.25–10
trail 1 0–3
intensity 1 0–3
angle 145 -180–180 °
spread 12 0–90 °
fragmentation 0.35 0–1
palette natural natural, ice, ember, custom
color #78d5ff CSS hex colour
light 0 0–2

drip

Parameter Default Range / choices
rate 1 0–5
speed 1 0–3
size 1 0.25–8
gravity 1 0–3
opacity 0.7 0–1
splash 1 0–2
trail 0.35 0–2
wind 0 -2–2
color #bed1dc CSS hex colour

halo

Parameter Default Range / choices
color #31b5ff CSS hex colour
size 0.16 0.05–1.2
intensity 1 0–2
pulse 0.35 0–3
rays 0.5 0–1
spin 6 -60–60 °/s
rim 0.5 0–1

orbit

Parameter Default Range / choices
count 40 4–200
radius 1.15 0.3–3
speed 0.6 -3–3
tilt 18 -90–90 °
bands 3 1–5
rotation 0 -180–180 °
eccentricity 0.15 0–0.7
precession 0.12 -1–1
trail 0.8 0–3
size 1 0.25–10
intensity 1 0–3
color #31b5ff CSS hex colour

disintegrate

Parameter Default Range / choices
amount 0.38 0–1
angle 160 -180–180 °
cut 180 -180–180 °
rate 1 0–4
shards 0.18 0–1
speed 1 0–4
erosion 0 0–0.25
size 1 0.25–6
turbulence 1 0–3
gravity 0.45 0–2
opacity 0.85 0–1
ragged 1 0–3
breathe 0.06 0–0.4
ground true true / false
metal true true / false
dust #c6ccd5 CSS hex colour
calm 0.15 0–1