Skip to the manual
In this manual

mote-engine / v0.56.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.56.0 has no runtime dependencies.

With npm, from your project folder:

npm install ./mote-engine-0.56.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 and capsuleMesh (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 that can break, puppets (physicsPuppets, humanoid), raycasts and snapshots
mote-engine/director scene-operation and timeline validation, the timeline compiler and sampler, createSceneFromJson (Scene JSON v2), replayLog (loaded on demand by the scene), the shot prompt describeShot and orthographic views (orthographicView, drawOrthoMesh)
mote-engine/video recordVideo, which records a scene with a stepped clock as an MP4 file in the browser (WebCodecs), and muxMp4, the MP4 writer on its own (no browser needed)
mote-engine/constellation the constellation renderer plugin (small wireframe solids on every surface)
mote-engine/components components: record catalog, registry, the motor family dc-servo, the sensor families (imu, encoder, lidar-2d, tof-zone) and robots from description files (loadRobot, loadRobotInScene) (experimental)
mote-engine/element the <mote-scene> custom element
mote-engine/native native adapter transport (experimental)

Release notes

mote-engine 0.56

0.56 gives every scene a scene graph and reads more model formats. scene.graph hands out a stable handle for each object of a stage, with its parent and children, its local transform and its exact world matrix, and lets you create, attach, move and detach nodes while the scene runs. Models now also load from COLLADA and binary FBX, and glTF files compressed with Draco or KTX2 load through decoders your application hosts. A scene that never touches its graph draws as in 0.55, apart from the custom-mode change below.

The scene graph. scene.graph is the graph of the stage on screen, and scene.graphAt(index) that of another stage. Each stage has a root, @root/<index>, and each node is a NodeHandle: its id, its parent, its children in order, its roles (mesh, bone, camera, light, helper) and item, the object it draws. getById, find and traverse search a node and everything under it, depth first. A glTF file read as a tree keeps its node names, and its bones, cameras and lights are nodes too. IDs must be unique across the whole scene: reading the graph of a scene with duplicates throws a GraphError of kind invalid, and the scene is left as it was.

Local transforms and world matrices. A node's position, quaternion and scale are live views of its transform in its parent's space, written with .set(...) or .copy(...); setTransform writes a partial transform at once. matrixWorld is the exact column-major world matrix, shear included, and copyMatrixWorld(out) fills a Float64Array of yours without allocating, for code that reads it every frame.

Creating, attaching, detaching. await scene.graph.create(spec) makes a node from a NodeSpec: a Scene JSON v2 object (a primitive, a model file, one glTF node, an SVG or Gaussian splats), a group, a camera or a light. A new node is detached, and drawn only once you add it under a parent. parent.add(a, b) moves nodes under a parent in one step, keeping their local transforms; remove and removeFromParent() detach a subtree without destroying it. While a subtree is detached its geometry, materials and handles are kept, its bodies leave the simulation, its joints and effects pause and its running tweens end where they are. Attached again, its bodies start at rest, its joints are made again and its effects resume without catch-up particles.

Helpers. graph.create({ id, helper: { kind: "axes" } }) makes an inspection overlay: axes, an XZ grid, or a box, light or camera drawn for the node named by target. Helpers draw in ASCII, Wireframe, Ray and custom mode, and are never geometry, colliders or something pick finds. graph.useCamera(node) looks through a camera node, a glTF camera for instance, and useCamera(null) puts the previous rig back.

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

const scene = createScene(canvas, {
  stages: [{ items: [{ id: "room" }, { id: "door", parent: "room", source: box(), motion: "none" }] }],
});
await scene.ready;

const graph = scene.graph;
const door = graph.getById("door");               // door.parent.id === "room"
door.position.set(1, 0, 0);                       // in the room's space
const world = door.copyMatrixWorld(new Float64Array(16));

const panel = await graph.create({ id: "panel", object: { shape: "box", material: { color: "#6688cc" } } });
door.add(panel);                                  // drawn from now on, under the door
graph.root.add(await graph.create({ id: "axes", helper: { kind: "axes" } }));
panel.removeFromParent();                         // detached, kept for later

Using the scene graph and Local transforms and world matrices have the whole API, its guards and its errors (GraphError, with a kind and a path).

Scene JSON and the log. Scene JSON stays at version 2, with no graph fields: a graph edit is drawn but not recorded. An edit that changes something marks scene.log() incomplete (unrecorded says from which frame and why), and describe() lists with complete: false each node it cannot write: helpers, detached nodes and nodes made with create. Graph operations in the log and Scene JSON version 3 are planned for 0.57.

COLLADA and FBX. loadCollada(url) reads static COLLADA 1.4 and 1.5 models: triangles, polylists and simple polygons, node hierarchies, the file's unit and up axis, and Phong, Blinn and Lambert colours. loadFbx(url) reads binary FBX 7.x static meshes with their hierarchy's transforms, normals, UVs, vertex colours and materials, and converts the file's axes and units to Y-up metres. loadModel detects both, Scene JSON takes { "model": "statue.dae" } or an .fbx file (format: "dae" or "fbx" when the name does not say), and <mote-scene src> loads them. Both are bounded by MODEL_LIMITS; ColladaOptions and FbxOptions are their options. See Collada models and Binary FBX.

Draco and KTX2 through your own decoders. loadGltf and loadGltfFiles take decoders: the Draco glTF decoder and the Basis Universal transcoder, as files your application hosts (path) or as their contents (module). The engine ships no decoder and fetches none of its own; each decode runs in a short-lived Worker within timeoutMs. parseGltfAsync(bytes, { decoders }) gives a document for gltfTree, skins and animations.

import { loadGltf } from "mote-engine";

const source = await loadGltf("/models/model.glb", {
  decoders: { draco: { path: "/decoders/draco/" }, ktx2: { path: "/decoders/basis/" }, timeoutMs: 15000 },
});

Without a decoder, an optional compression extension falls back to the file's uncompressed data, as parseGltf, gltfSource, Scene JSON and <mote-scene> always do; a file that requires the extension is refused with the names of the decoder files it needs. External glTF decoders lists the files and where to get them.

Also in 0.56: an OBJ's MTL Ps and map_Ps now set sheenColor and sheenColorMap, without the warning 0.55 gave.

Breaking changes:

  • ItemSpec no longer takes glTF metadata as input. name, bone, provenance, cameraDefinition and lightDefinition on an object you write are refused with a TypeError that names the field's JSON pointer, and the scene does not change. The items gltfTreeItems returns still carry them, also when you spread them into your own. To make a named node, a bone, a camera or a light, use a NodeSpec with graph.create.

Behaviour changes:

  • describe() of a tree built in code. A scene made from gltfTreeItems(tree, { gltf }) in your page now gets complete: false, with an unserializable diagnostic for each node's glTF name and origin, which version 2 cannot hold. A tree declared in the document with gltfTree stays complete.
  • Custom mode draws scene.debug primitives last, after the effects and the plugin's output. While any helper is attached they also draw without depth occlusion, because a plugin exposes no depth.

Known limits: the graph has no reparenting that keeps the world pose, no clone, no node events, no lookAt and no layers. Structural edits are capped at 4096 nodes and 256 helpers a stage and 64 levels. An orthographic camera node stays readable, but useCamera refuses it with unsupported-projection. In ASCII a helper is depth-tested against the nearest sampled surface point in each cell, so a sparsely sampled object can let it show through. COLLADA reads the static pose only: skins, morphs, polygon holes and external references are refused, and textures are ignored with a warning. FBX reads binary static meshes only: no skinning, animation, blend shapes, cameras, lights or textures, and ASCII FBX is refused. Scene JSON, <mote-scene> and loadModel take no decoder configuration, so a model that is only compressed is loaded with loadGltf and given to the scene in code. In Node a decoder needs a Web Worker adapter. KTX2 textures are 2D, at most 4096 × 4096, and only their base mip is kept.

mote-engine 0.55

0.55 reads more of the 3D formats a web project meets and widens the GPU paths. Models load from OBJ with MTL materials, STL and mesh PLY; SVG drawings become flat or extruded shapes; glTF files compressed with meshopt load with no decoder to host; and glTF materials gain unlit, sheen, anisotropy and iridescence. ASCII can draw its glyphs with WebGPU, and Wireframe without WebGPU now falls back to WebGL2 instead of ASCII.

Models from OBJ, STL and PLY. loadModel(url) picks the reader by extension or content: OBJ with its MTL files and textures, STL (ASCII or binary, with VisCAM and SolidView colours) and mesh PLY (ASCII or binary). loadObj, loadStl and loadPlyMesh read one format, and all take normalize: false to keep the file's units. OBJ triangulates concave polygons and keeps smoothing groups; MTL maps the classic and PBR factors, base-colour maps and normal maps. A file is checked before its meshes are allocated, within MODEL_LIMITS (64 MiB a file by default; maxBytes, maxVertices, maxFaces and maxMaterials tighten them). Scene JSON takes { "model": "part.obj" }, and <mote-scene src> loads .obj, .stl and .ply URLs. A PLY without faces still goes to the Gaussian-splat reader.

SVG as shapes. svgSource(text, { depth, bevel, curveSegments, stroke }) reads paths with arcs, the basic shapes and nested transforms without a DOM, in Node or a browser, each fill in its own colour and with its holes. depth: 0, the default, gives a flat shape. Scene JSON takes { "svg": "mark.svg", "depth": 0.08 }.

import { createScene, loadModel, svgSource } from "mote-engine";

const mark = svgSource(svgText, { depth: 0.08, bevel: 0.01 });
const scene = createScene(canvas, {
  mode: "ray",
  stages: [{ items: [{ id: "part", source: loadModel("/models/part.obj"), motion: "none" }] }, mark],
});

OBJ, STL and mesh PLY and Other sources have the details.

meshopt without a decoder. glTF files compressed with EXT_meshopt_compression or KHR_meshopt_compression load through every glTF reader, decoded by the engine itself: no WebAssembly, no decoder path, no setup. Every compressed range is checked before its output is allocated, within 64 MiB a buffer view and 256 MiB a model.

glTF materials. KHR_materials_unlit, KHR_materials_sheen, KHR_materials_anisotropy and KHR_materials_iridescence are read with their textures, and Material has the same fields for your own materials: unlit; sheenColor, sheenRoughness; anisotropyStrength, anisotropyRotation; iridescence, iridescenceIor, iridescenceThicknessMin, iridescenceThicknessMax; and their maps. Ray shades all four; ASCII and Wireframe draw an unlit material without lighting and the other three as their base colour. Mesh.tangents keeps a file's own tangents. See Materials.

ASCII on WebGPU. glyphRenderer: "webgpu" draws ASCII's characters and the effects' glyphs with WebGPU, falling back to WebGL2 and then Canvas2D. With "auto", the default, WebGPU is used only once the scene has a device for Ray or Wireframe, so a plain ASCII page downloads nothing more and asks for no device. The element takes glyph-renderer="webgpu".

Also in 0.55: the new readers, and the WebGL2 Wireframe, load on demand, the first time a scene or <mote-scene> needs them, so a page that uses none of them downloads none of them.

Behaviour changes:

  • Wireframe without WebGPU draws with WebGL2, hidden lines and preview faces included, where 0.54 drew the scene in ASCII; ASCII stays the last fallback. scene.mode stays "wireframe", stats().backend starts with webgl2 and stats().ray.fellBack gives the reason. See Wireframe.
  • ASCII after Ray or Wireframe. In a scene that already opened a WebGPU device, "auto" now draws the glyphs with it. The pictures match WebGL2's except for small local differences where a glyph overlaps a halo.
  • glTF files that 0.54 refused now load: those compressed with meshopt, and those that require unlit, sheen, anisotropy or iridescence.

Known limits: SVG has no CSS stylesheets, no text and no gradients (a gradient fill takes its first stop's colour). An OBJ face has at most 4096 vertices. The WebGL2 Wireframe shades flat, keeps its coverage cap of 262,144 pixels, and has no smoothing or mipmap options. Ray's refined glass does not add sheen or anisotropy, and tangents cannot be morph targets. Draco is not read in 0.55: 0.56 reads it through a decoder you host.

mote-engine 0.54

0.54 lets code, or an AI working through it, arrange a scene by where its objects really are. Five new scene operations place objects on, beside and in line with others by their world bounding boxes; orthographic views draw a scene from above, the front and the side at a known scale; and scene.geometry hands over each object's triangles as they stand. Scenes that use none of it run as in 0.53.

Spatial operations. placeOn, placeRelative, align, distribute and resolveOverlaps join scene.applyOps and timeline cues. They measure each object's world bounding box, its children included, with Y up and a metre to a scene unit: rest a vase on a table without sinking into it, put a chair 20 cm in front of it, line shelves up against a wall, space objects evenly, push overlapping ones apart. A batch is validated whole before anything moves, every error with its JSON pointer, and the operations are logged and replayed like the others. OpsResult.placed says where each operation left its objects (PlacedObject: position, world box, moved).

const { placed } = await scene.applyOps([
  { op: "placeOn", id: "table" },                                                  // on the floor
  { op: "placeOn", id: "vase", on: "table" },                                      // on the table, centred
  { op: "placeRelative", id: "chair", to: "table", side: "front", distance: 0.2 }, // 20 cm in front of it
  { op: "resolveOverlaps", ids: ["chair", "stool"], fixed: ["table"], gap: 0.05 }, // 5 cm apart at least
]);

Scene operations and the log has every field of the five.

Orthographic views. From mote-engine/director: orthographicView(kind, min, max, width, height) frames a world box from the "top", the "front" or the "side" with no perspective, projectOrthographic and unprojectOrthographic go between world points and pixels, and createOrthoPicture with drawOrthoMesh draw a scene's triangles into an RGBA picture in their base colours: a plan or an elevation on which lengths are read with one number. See Orthographic views of a scene.

The scene's triangles. scene.geometry(visit) hands over each drawn object's mesh as the frame draws it (skins and morph targets applied), the matrix that places it, and its materials' base colours and doubleSided flags. What it hands over is borrowed until the visitor returns. It is a query, not a call for every frame.

Also in 0.54: scene.bounds(id, out) fills a SceneBounds record of yours and returns it, so an outline that follows an object every frame allocates nothing. See Measuring the scene.

Placeholders in a shot prompt. describeShot takes placeholders: a sentence that tells a video model the guide's figures are blocking placeholders, whose paths, actions and timing it keeps while it gives them natural human motion. ShotDescription.placeholders says whether it was added.

Behaviour change: describeShot adds the placeholders sentence by default when the scene has skinned figures, or subjects whose ids contain the whole word mannequin, dummy or puppet. Pass placeholders: false to keep the 0.53 text.

Known limits: the boxes are axis-aligned in the world, so a turned object's box is larger than the object, and a chair pushed under a table overlaps it. An object with nothing to measure yet (a model still loading, a group whose children draw nothing) is the operation's runtime error. Orthographic pictures are flat drawings in base colours: no texture maps, lights, shadows, effects or Gaussian splats.

mote-engine 0.53

0.53 takes a scene from Blender to a video file. A glTF file's cameras and punctual lights now drive the scene, a Scene JSON document can name them so that the same small document loads each new export, recordVideo records a scene as an MP4 file in the browser, and describeShot writes the text prompt that goes with a guide video for an AI video model. Scenes without them run as in 0.52.

A model's cameras. gltfCameras(doc, tree) lists a file's cameras, each with its field of view and the nodes that carry it, and gltfCameraRig(doc, tree, ids, { camera }) gives the rig that puts the scene's camera on a camera's node, by index or name. The node's animation, played by gltfTracks, moves the camera as it moves in Blender. The rig is a new kind, { kind: "attach", target, distance? }: the eye at an object's origin, looking along its −Z axis with its +Y up, read every frame where the object is drawn. Any object can carry the camera this way, and the camera operation and timeline cues take it too. See A model's cameras and Camera rigs.

A model's lights. gltfLights(doc, tree) reads a file's KHR_lights_punctual lights, and gltfSceneLights(doc, tree, ids) makes a scene light for each node that carries one, attached to that node's object, so the node's animation moves it. The file's lux and candela become Ray's physical units: with Blender's Data › Lighting › Standard export, a light comes back with the power it had in Blender, measured against Cycles within 0.05%. Directional, point and spot lights you write in code take attach: "<item id>" too. See A model's lights.

From Blender and back. In a version 2 document, a stage object { "gltfTree": "shot.glb" } declares the file's whole node tree, "camera": { "gltf": "shot.glb", "camera": "Camera", ... } names one of its cameras, a lights entry { "gltf": "shot.glb", "lights": "all" } selects its lights, and "animation": { "clip": "Dolly" } on the tree plays one of its clips. createSceneFromJson resolves them (sceneFromJson only checks them), and describe() writes them back as references to the file, not as copied poses: edit in Blender, export over the same file and load the same document again. See From Blender to mote and back.

Exporting a video. recordVideo(scene, options), from the new entry point mote-engine/video, steps a scene with a stepped clock frame by frame, encodes each picture with the browser's WebCodecs encoder and writes the MP4 file itself, with no other library. It takes seconds or from and to, fps (it must divide the clock's rate), codec ("avc", the default, "vp9" or "av1"), bitrate, background, refined for path-traced Ray frames, signal and onProgress, and resolves with the file as a blob. muxMp4, the MP4 writer on its own, runs without a browser. See Exporting a video.

A prompt for a video model. describeShot(scene, { from, to, style, negative, maxLength, language }), from mote-engine/director, describes what a stepped scene made by createSceneFromJson (or a Scene JSON document) plays over a frame range: the camera's moves with their measured degrees and metres, the subjects in view, the lights and the look. It samples a private copy, so the scene you pass is neither stepped nor changed, and the same scene and options give the same text byte for byte. prompt and promptShort stay within maxLength (900 by default), in English or, with language: "it", Italian.

import { createSceneFromJson, describeShot } from "mote-engine/director";
import { recordVideo } from "mote-engine/video";

// shotJson: a version 2 document with a gltfTree, the file's camera and lights,
// and a stepped clock: "clock": { "time": 0, "step": 0.016666666666666666 }
const made = await createSceneFromJson(canvas, shotJson);
if (!made.ok) throw new Error(made.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const scene = made.scene;
await scene.ready;

const shot = await describeShot(scene, { to: 240, style: "soft morning light" });
const video = await recordVideo(scene, { to: 240, fps: 30, background: "#ffffff" });
// video.blob: the MP4 file; shot.prompt: the text that goes with it

Also in 0.53: cameras and lights are read as untrusted input like the rest of a glTF file, at most 256 of each and 4096 nodes that carry them (GLTF_CAMERA_LIMITS, GLTF_LIGHT_LIMITS). A light with out-of-range values is skipped with a light-invalid diagnostic and never fails the file. The flat loaders, loadGltf among them, read neither and load files as before.

Known limits: recordVideo needs a stepped clock and a canvas on screen, records no audio, and makes at most 10 000 pictures a recording. With the browser's software H.264 encoder the bytes repeat from run to run up to 640 × 360; at 720p and above the frames, timing and size repeat but the bytes can differ. gltfCameraRig refuses an orthographic camera, and a camera's animated zoom is not played: animate the rig's fov with a timeline track instead. A light's range fades smoothly rather than cutting off as in Blender (about 0.56 times Cycles' light at half the range), and Blender's area lights are not exported as punctual lights. describeShot's thresholds for a file camera's composite shot were tuned on a single shot, the default maxLength can leave out the least visible subjects of a rich scene, and a scene not made from Scene JSON (procedural sources, puppets) is refused with a TypeError.

mote-engine 0.52

0.52 brings the engine's first characters: puppets. A puppet is a figure of rigid parts, one body for each bone, that stands in its pose in a physics world or a scene and turns into a ragdoll when it is hit hard enough, one part at a time. Worlds and scenes without puppets step exactly as before.

A mannequin puppet of rigid wooden parts standing on a round platform, in Ray.

Puppets in a world. world.use(physicsPuppets()), from the physics entry point, makes a figure with one body per bone and one joint from each bone to its parent. humanoid("mannequin") gives a standing figure of 15 parts with a human body's shares of the mass; "dummy" has 11, its hands in the forearms and its feet in the shins. Elbows, knees, ankles, wrists, the neck and the waist are hinges with limits, and shoulders and hips are ball joints. A figure of your own is a PuppetSpec: a list of bones, each with its parent, where it lies in the rest pose, its shape and its joint. The whole spec is checked before one body is made.

Standing, then limp. A puppet starts "animated": its parts are kinematic bodies in the rest pose, which push what they meet, and moveTo takes the figure somewhere else over the next step. goLimp() turns every part dynamic where it is, keeping its velocity and its contacts. With limpOnImpact, a hit of at least impulse N·s turns limp the bone it lands on, the bones within spread joints of it and everything that hangs from them. The parts collide with each other unless they are joined, without taking any of the 16 collision groups, and a step with puppets allocates nothing.

import { createPhysicsWorld, physicsEvents, physicsPuppets, humanoid } from "mote-engine/physics";

const world = createPhysicsWorld();
world.use(physicsEvents());                 // the impacts limpOnImpact reads
const puppets = world.use(physicsPuppets());
world.addBody({ type: "static", shape: { type: "plane", normal: [0, 1, 0], offset: 0 } });

const puppet = puppets.add(humanoid("mannequin", { height: 1.75, mass: 70 }), { position: [0, 0, 0] });
puppet.limpOnImpact = { impulse: 2, spread: 1 };  // N·s: the part hit and its neighbours
// ... later, all of it:
puppet.goLimp();                                  // a ragdoll, which falls

Puppets in a scene. A stage declares them in puppets, and the scene (it needs physics) draws each part as an ordinary object of the stage, "actor.head" or "actor.forearm.L", in ASCII, Ray and Wireframe. scene.puppet(id) is the puppet's handle. The scene's events name the parts by their ids, a limp part can be grabbed and thrown, and a body thrown at a standing puppet turns limp what its limpOnImpact says.

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

const scene = createScene(canvas, {
  mode: "ray",
  physics: { scale: 1.25, floor: -0.8 },       // metres to a scene unit
  stages: [{ items: [], puppets: [{
    id: "actor", spec: "mannequin", position: [0, -0.8, 0],
    material: { head: materials.gold },        // one material, or one per bone
    limpOnImpact: { impulse: 5 },
  }] }],
});
await scene.ready;
scene.puppet("actor").goLimp();

Each part is drawn with the mesh of its collision shape. capsuleMesh, new in the geometry entry point, is that capsule as a mesh, for your own objects too. Puppets and Puppets in a scene have the whole API.

Also in 0.52: a scene's fixed physics step no longer allocates while bodies are awake, in contact or pushed, with the same results bit for bit.

Known limits: this first version has no cone or twist limits (joint: { type: "cone" } is refused, so shoulders and hips turn freely), no "powered" mode, no clips and no getting up. A ragdoll does not return to "animated": remove the puppet and add it again, or show its stage again, which stands a new one in its place. Puppets are not in Scene JSON yet, and world.snapshot() and restore() throw while a world holds one. A landing stretches the soft joints: the dummy's part by about 2 cm, and the mannequin's hands and feet can go past their hinges' limits by up to 17° for a few steps. jointSolver: "chain" holds every hinge's limit. A stage's joints cannot name a puppet's part, and a puppet cannot be added to a stage already on screen.

mote-engine 0.51

0.51 lets joints break and say when they reach their limits, and puts a robot's description file in a scene. World snapshots have a new version: read the breaking changes below before you update.

Joints that break. Every joint takes breakForce in newtons, and a hinge, a weld and a slider also take breakTorque in newton metres, at every scale. When the load over a step passes the threshold, the joint breaks after that step: it leaves the world, joint.broken turns true and onJointBreak tells it once. In a scene the event carries the objects' ids and the joint's jointId, scene.physics.hinge(id).broken says so, and a broken joint stays broken until its stage is shown again. Scene JSON's joints and a robot file's take the same two fields.

Limits that tell. onJointLimit now fires when a hinge, a slider or a distance joint starts to push against its limit: once, and again only after the joint has left the limit and come back.

const scene = createScene(canvas, {
  physics: {
    events: {
      onJointBreak: (e) => console.log(`${e.jointId} let go of ${e.a}`),
      onJointLimit: (e) => console.log(`${e.jointId} is on its ${e.which} stop`),
    },
  },
  stages: [{
    items: [lamp],   // a 2 kg lamp: it weighs 19.6 N
    joints: [{ id: "cord", type: "distance", a: "lamp", anchorA: [0.7, 0.42, 0], anchorB: [0.7, 0.9, 0], breakForce: 30 }],
  }],
});

Choose a threshold with a margin: with the default solver a load put on at once swings to about 1.4 times its resting value before it settles.

A body changes type in place. body.setType("dynamic", { keepContacts: true }) lets go of a kinematic body without ending its contacts or losing its velocity, and the same works from dynamic to kinematic. Puppets go limp this way.

A robot in a scene. loadRobotInScene(scene, json, catalog, options), from the components entry point, builds a robot's description file in the stage on screen: each body an object of the stage, each joint a joint of the stage, with its motors and sensors attached. It steps bit for bit as the same file loaded in a world with loadRobot, and robot.remove() leaves the scene as it was.

Ray queries without allocating. world.raycastInto(origin, dir, maxDistance, hit) finds the nearest hit like raycast and writes the body, point, normal and distance into a record you reuse.

Breaking changes:

  • World snapshots are version 2. They now keep the joints' break thresholds and which limits hold each joint. A snapshot taken with 0.50 or earlier is refused whole (Invalid world snapshot: version 1; expected 2) and the world is left as it was. Before you update, finish or discard the runs whose snapshots you keep, then take them again with this version. There is no conversion.
  • SceneHinge.index follows the joint's place in its stage. When a robot loaded earlier in the same stage is removed, the joints after it move up, and a removed joint's handle reads -1. Keep the handle scene.physics.hinge(id) gives you, or look a hinge up by its id, never by an index you stored.
  • ItemSpec.shape is checked. On a source from gltfTreeItems(tree, { gltf }), a shape that does not name the source's real node and file is refused with a TypeError, where 0.50 accepted it.

Known limits: a robot loads only into the stage on screen, and when its stage is shown again its motors and sensors are attached anew, without the commands they had (robot.generation counts it).

mote-engine 0.50

0.50 loads scenes and robots from files. A robot written as data is built exactly as the same calls would build it, and Scene JSON keeps a scene's hierarchy, so describe() writes parents and groups and the document loads back as the same scene.

A robot from a file. loadRobot(world, json, catalog, options), from the components entry point, reads a robot written as data: its bodies and their collision shapes, its joints between bodies named by id, and its motors and sensors, each citing the id of its record in a component catalog. It builds them in a physics world in the file's order, and the robot steps bit for bit as the same robot built in code. validateRobotFile(json) checks a description without building it. A wrong file is refused whole before a body is made, every error with its JSON pointer, what was expected and what was found.

import { createPhysicsWorld } from "mote-engine/physics";
import { components, createComponentCatalog, dcServoMotor, jsonComponentSource, loadRobot } from "mote-engine/components";

const world = createPhysicsWorld({ jointSolver: "chain" });
const comps = world.use(components());
comps.registerMotorModel("dc-servo", dcServoMotor);
const parts = jsonComponentSource(partsJson);   // the records the file cites
const catalog = createComponentCatalog(parts.source, { families: comps.families });

const loaded = await loadRobot(world, robotJson, catalog, { components: comps, position: [0, 0, 0.5] });
if (!loaded.ok) console.log(loaded.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
else loaded.robot.motor("servo").setPosition(0.5);   // handles by the file's ids

A hierarchy in Scene JSON. A version 2 object can have a parent, the id of another object of its stage, and its transform is then in its parent's space. An object without a shape is a group, and { "gltf": "robot.glb", "node": "Arm.L" } is one node of a glTF file as a shape. scene.describe() now writes a hierarchy as it is, a tree read with gltfTreeItems(tree, { gltf }) included, and the document loads back as the same scene. A parent that is missing, a cycle and more than 64 levels are refused with the field's JSON pointer.

Rigged characters on the timeline. A timeline now holds up to 4096 tracks instead of 256, so the animation of a glTF rig with a hundred joints and more plays through gltfTracks. Validating the largest timelines takes a few hundred milliseconds: install them outside interaction handlers.

Integration recipes. The manual has Integration recipes for the <mote-scene> element's lifecycle, a React component that survives StrictMode and a paste-ready block for a CMS page.

Behaviour changes:

  • Ray culls the back faces of skinned and morphed meshes when their material is not double-sided, as it already did for static meshes. A skinned model that was visible from behind or from inside now disappears from there. Give the materials that must show their back doubleSided: true, for example with doc.json.materials?.forEach((m) => { m.doubleSided = true; }) before gltfTree.
  • Unit quaternions are kept to the bit. A rotation given as a quaternion within 1e-12 of unit length is no longer normalised again, so item.set(item.transform) changes nothing. Matrices, and physics runs started from them, can differ from 0.49 in the last digit.

Known limits: a robot's description holds no mesh and no plane, and a compound's children are solids; a motor, and a sensor on a joint, go on a hinge. Skins and morph targets cannot be written in Scene JSON: describe() says so with item-skin and item-morph.

mote-engine 0.49

0.49 gives a physics world motors. A robot simulated with the engine can now drive its hinges with geared DC servos described by data, next to the sensors of 0.48, and a whole robot with every motor and sensor attached saves and restores exactly. A handful of smaller changes come with it. Scenes and worlds without motors run exactly as before.

A tube figure on a base whose hinged arms are driven, swaying in the airflow.

Servos on hinges. The components entry point ships its first motor family, dcServoMotor. Register it under the family name your records use, then attach a record to a hinge of a world made with jointSolver: "chain". The servo commands the hinge in position, velocity or torque, whichever its record lists, and its numbers are the record's: two servos are two records, and the same code moves both.

  • At the battery's voltage the motor follows its torque-speed line: the stall torque and the no-load speed scale with the voltage.
  • The gearbox's backlash, static and viscous friction and the rotor's reflected inertia are modelled, with a current limit that must be above the no-load current (one at or below it is refused).
  • A servo holding still does no work, a step allocates nothing, and the servo's state is in the world's snapshot.
import { createPhysicsWorld } from "mote-engine/physics";
import { components, dcServoMotor } from "mote-engine/components";

const world = createPhysicsWorld({ jointSolver: "chain" });
const comps = world.use(components());
comps.registerMotorModel("dc-servo", dcServoMotor);

const motor = comps.attachMotor(shoulder, servoRecord, { voltage: 11.1 });   // shoulder: a hinge of this world
motor.setPosition(0.5);                    // rad; setVelocity(rad/s) and setTorque(N·m) if the record lists them
const reading = new Float64Array(4);
world.step(1 / 60);
motor.read(reading);                       // [angle, speed, torque, current]

attachMotor also takes a scene's hinge, the handle scene.physics.hinge(id) gives: the servo follows that hinge through every rebuild of the scene.

Commanding a hinge without allocating. world.writeHinge(hinge, from, at?) sets a hinge's motor, drive, friction and damping from eight numbers of your typed array, and world.readHingeLoad(hinge, out, at?) writes its torque and work into one. They are for controllers that compute their commands at every step.

A whole robot, saved and restored. Motors and sensors of every family share one module, one step and one snapshot. A robot with eight servos and twelve sensors restored from a snapshot continues bit for bit, sensor noise included, in the same world or in a new one built the same way.

Morph weights from the director. The director's set and animate operations take an object's weights, the weights of its morph targets: set writes them at once, animate blends them over the same eases as the other properties. Scene JSON objects and the director's add accept weights too. A list of the wrong length, or weights on an object without morph targets, is refused and writes nothing.

Collapsed objects stop colliding. An object whose scale has a zero component, its own or a parent's, is not drawn, and now its body no longer collides either. Contacts open when it collapses end with one contactEnd, the scene's raycasts miss it, and a dynamic body stays where it is until the scale comes back. In 0.48 such a body kept a thin collider that still collided.

Scene JSON checks driven hinges. sceneFromJson now refuses a hinge with an active drive, friction or damping when the document has physics without jointSolver: "chain", with the field's JSON pointer and the message createScene gives. In 0.48 the document loaded and the scene refused it when it was made. A document without physics is accepted, as before.

Ray. The mesh arena no longer allocates at every frame for each mesh it holds.

Known limits: the servo applies the rotor's inertia and the backlash once per step, so with several sub-steps it can run up to about 20 % faster than the model. Sensors cannot be attached to a scene's hinge yet, and a motor on a scene's hinge leaves with the world when the stage changes. A model's own weights given in the director's add are not checked against its number of morph targets.

mote-engine 0.48

0.48 gives a physics world sensors. A robot simulated with the engine can now read an IMU, its joints' encoders, a 2D LiDAR and a zoned time-of-flight sensor, each at its own rate, with its own delay and noise, and with no allocation in the step. Scenes and worlds without sensors run exactly as before.

A 2D LiDAR sweeping a set of spheres and boxes, each hit labelled with its range.

Sensors. The components entry point ships the engine's first four sensor families: imuSensor, encoderSensor, lidar2dSensor and tofZoneSensor. A sensor is a record of data with its parameters in SI units; register the families your records name, then attach each record to a body or a hinge.

  • Each sensor reads at its own rate, with a latency.
  • Its noise comes from a seed: the same seed gives the same readings in every run, and another sensor's draws never change it.
  • Readings are copied into your own Float64Array or Float32Array, with NaN where there is no measure.
  • The sensors' state is saved and restored with the world's snapshot, so a restored run continues bit for bit.
import { createPhysicsWorld } from "mote-engine/physics";
import { components, imuSensor, lidar2dSensor } from "mote-engine/components";

const world = createPhysicsWorld();
const comps = world.use(components());
comps.registerSensorModel("imu", imuSensor);
comps.registerSensorModel("lidar-2d", lidar2dSensor);

const imu = comps.attachSensor(chassis, { position: [0, 0.02, 0] }, imuRecord, { seed: 42 });
const lidar = comps.attachSensor(chassis, { position: [0, 0.05, 0] }, lidarRecord, { group: 2, mask: 1, seed: 7 });

const reading = new Float64Array(imu.size);   // [ax, ay, az, gx, gy, gz]
const scan = new Float32Array(lidar.size);    // one distance per ray
world.step(1 / 60);
imu.read(reading);
lidar.read(scan);

The LiDAR and the ToF cast their rays in one batch through the world's batched raycast. A full 360-ray LiDAR sweep costs about 0.13 ms. A sensor of another kind is a family of your own, made with createSensor, which gives it the same rate, latency, seeded noise and snapshot.

Reading the world without allocating. world.readPose, readVelocity and readCenter write a body's pose, its linear and angular velocity, and its centre of mass into a buffer of yours. world.readHinge writes a hinge's angle and speed. They are what the sensors use, and are there for controllers that run every step.

Hinges that stay on their axis. A hinge whose load hangs off its axis, such as a wheel mounted beside its arm, twists with the default solver. With physics: { jointSolver: "chain" }, an eight-hinge robot of 1.8 kg turning in place stays within about 0.001° of its axes, where the default twists about 3°. Scene JSON can now ask for it too, with physics.jointSolver and physics.jointHertz, and describe() keeps them. The default solver is unchanged.

Determinism, stated. The manual now says which levels of determinism the world guarantees. The same code, inputs and runtime give bit-identical runs in one process and in separate Node processes on the same host, and a restored snapshot continues bit for bit. It also says what is not promised: other machines, other runtimes, other engine versions, and GPU images.

Known limits: the chain solver is chosen for the whole world or scene, not per hinge, and costs about 2.5 times the default's joint work. The range sensors need a collision group and mask that keep them from seeing their own body. Motors as components (attachMotor with a servo family) come in a later release.

mote-engine 0.47

0.47 lets a model move the way its file says. A skinned mesh now bends with its skeleton, and a mesh with morph targets changes shape, in ASCII, Ray and Wireframe. Models without skins or shape keys draw exactly as before.

A skinned purple tentacle bending on its skeleton beside a coral sphere, in Ray.

Skinning. gltfTree now reads a file's skins. Every bone becomes an object of the scene, and the mesh follows its bones every frame. Move a bone the way you move any object, with set, animate or a timeline track, and the skin bends with it. gltfTracks plays the file's own animation on the bones, so a walk cycle walks.

Morph targets. Shape keys are read too. A mesh with targets gets weights, one number for each target: set them by hand, or animate them with the timeline's new weights kind. gltfTracks now plays the file's weights channels as well, stepped, linear or cubic-spline.

import { createScene, parseGltf, gltfTree, gltfTreeItems } from "mote-engine";

const doc = parseGltf(await (await fetch("/models/squid.glb")).arrayBuffer());
const { items } = gltfTreeItems(gltfTree(doc), { id: "squid", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });

await scene.item("squid/Arm").animate({ rotation: [0, 0, 40] }, 1); // a bone: the skin bends
scene.item("squid/Body").weights = [1, 0];                          // the first shape key, fully on

// The second shape key, in and out every 2 s: a `weights` track.
await scene.setTimeline({ version: 1, duration: 2, loop: true, tracks: [{
  target: "item:squid/Body", property: "weights",
  keys: [{ t: 0, v: [0, 0] }, { t: 1, v: [0, 1] }, { t: 2, v: [0, 0] }],
}] });

The timeline drives physics. A position or rotation track on a kinematic body now moves it at the track's own velocity on every physics step, so whatever it hits is pushed as hard as it really moves. Impulse cues fire once each time the playhead crosses them, even when a slow frame skips past.

Also in 0.47: picks and bounds follow the deformed mesh, and a skin that is not valid is refused with an error naming the skin and the accessor, instead of loading unskinned.

mote-engine 0.46

0.46 lets a model's animation mirror and hide its parts. A scale can now be negative or 0, on any object, in a timeline and in Scene JSON. Scenes that use neither draw exactly as before.

Mirrors and collapses. A negative scale component mirrors the object along that axis: scale: [-1, 1, 1] is its mirror image, drawn the right way round in ASCII, Ray and Wireframe, with its children mirrored too. A component of 0 collapses the object: it draws nothing until its scale changes again, and neither does anything under it. A glTF animation that flips or hides a node now plays as the file has it.

const gear = scene.item("gear");
await gear.animate({ scale: [-1, 1, 1] }, 1); // turns into its own mirror image in 1 s
gear.set({ scale: [1, 0, 1] });               // gone, until its scale is set again

Saved scenes keep their curves. Scene JSON now accepts the timeline's hermite keys, so a scene playing a model's cubic-spline animation is saved and loaded again with the exact same motion.

Also in 0.46: the fire and snow effects no longer make garbage every frame, so scenes with them run without the small pauses of the garbage collector. Ray's still-frame refinement also stays within its frame time when another page or app shares the GPU.

mote-engine 0.45

0.45 lets a model keep its parts. A glTF file can now be read as a tree of nodes, one object for each node, each one under its parent. Its own animations then play on those objects: the walk cycle or the opening door that came with the file. Models read the usual way, with loadGltf, draw exactly as before.

A model as a tree. gltfTree(doc) reads the file's nodes with their hierarchy and gltfTreeItems makes the scene's objects of them. Turn one node and its children follow, about the node's own origin: a door turns on its hinge, not around the middle of its panel. At rest the tree is the same model you get from loadGltf.

import { createScene, parseGltf, gltfTree, gltfTreeItems } from "mote-engine";
import { gltfTracks } from "mote-engine/director";

const doc = parseGltf(await (await fetch("/models/robot.glb")).arrayBuffer());
const tree = gltfTree(doc);
const { items, ids } = gltfTreeItems(tree, { id: "robot", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });

const { timeline, diagnostics } = gltfTracks(doc, tree, ids, { animation: "Walk", loop: true });
await scene.setTimeline(timeline); // diagnostics lists what is not played

Parents and groups for any object. Every object can now have a parent: give it the id of another object of the same stage, and moving, animating or spinning the parent carries the child with it, in ASCII, Ray and Wireframe. An object without a source is a group: it draws nothing and only places its children. Removing a parent leaves its children where they are.

The file's own animations. gltfTracks turns an animation's channels into timeline tracks for position, rotation and scale. Stepped, linear and cubic-spline curves play exactly as the glTF specification defines them. Skins and shape keys are not played yet, and diagnostics says so instead of dropping them silently.

Also in 0.45: effects do less work in their first frames, so scenes with fire, snow or sparks start more smoothly.

mote-engine 0.44

0.44 puts three more effects in the scene's world. In Ray with WebGPU a nebula, a lightning strike and fireworks now stand among your objects: hidden by what is in front of them, seen from any camera, and lighting what is around them. In ASCII, Wireframe and Ray without WebGPU they draw as before.

A nebula in a box. nebula({ volume: { min, max } }) fills a box of the world with glowing gas in filaments, crossed by dark dust lanes, going from color to color2 towards its core. It fades to nothing at the box's faces, the camera can fly into it, and it mixes with fog, smoke, fire and clouds in the same march.

import { createScene } from "mote-engine";
import { nebula, lightning, fireworks } from "mote-engine/effects";

const scene = createScene(canvas, {
  mode: "ray", stages: [{ items: [city] }],
  effects: [
    nebula({ volume: { min: [-2.2, 0.3, -2.5], max: [2.2, 1.6, -0.8] } }),
    lightning({ kind: "mixed" }),
    fireworks({ ray: { light: true, smoke: true } }),
  ],
});

Lightning among the objects. A strike now stands on an upright plane through the point it hits. It passes behind the buildings in front of it, and its flash is a real light: it lights and shadows the scene and glows inside the clouds, fog and smoke.

Fireworks that light the night. Each burst lights the scene in its stars' colours and leaves a puff of smoke that the next bursts light up. The light and the smoke cost GPU time while a burst is alive; fireworks({ ray: { light: false, smoke: false } }) keeps the stars alone, at the old cost.

Also in 0.44: smoke follows the wind the same whatever the order of your effects, and scene.seek() refuses to go back after a change that failed halfway, instead of silently undoing it.

mote-engine 0.43

0.43 puts effects inside the scene. In Ray a fire, smoke and fog can now live in a box of the world: hidden by what stands in front of them, seen through glass, lit by the scene's lights, and able to burn and drift together at every quality. Outside Ray, and in ASCII and Wireframe, they draw as in 0.42.

A fire in the scene. fire({ volume: { min, max } }) makes the flames an emissive volume in that box, with embers among the objects and, with light, a flickering light of its own. Flames taller than their box bend under its top and run along it, as in a fireplace.

import { createScene } from "mote-engine";
import { fire, smoke } from "mote-engine/effects";

const hearth = { min: [2.0, 0.4, -2.5], max: [3.0, 1.05, -1.9] };
const scene = createScene(canvas, {
  mode: "ray", stages: [{ items: [house] }],
  effects: [
    fire({ volume: hearth, intensity: 1.2, light: 0.8 }),
    smoke({ volume: hearth, density: 0.8, opacity: 0.7 }),
  ],
});

Smoke and fog in the world. smoke({ volume }) anchors the plume to a box: it rises, pools under the box's top and rolls down its sides. fog({ volume }) is a volumetric fog, densest on the box's floor and thinning with height, that the camera can walk into. Behind a window or a pane, fog, smoke and fire are now seen through it instead of stopping at the glass.

Together at every quality. A volume can leave the march toward local lights (lightMarch: false in a custom volume manifest); fire, smoke and fog do, so all three install side by side at fixed "high" and "ultra", and "auto" no longer drops the scene to the low tier.

Lights you do not see. visible: false on a point, spot or area light keeps its light and its shadows but hides the light itself, in view, in mirrors and through glass — for a light standing in for a fire, or a soft-shadow radius without the glowing ball. Emissive surfaces seen through glass keep their glow.

Also in 0.43: Gaussian splats (INRIA PLY) in Ray and scene.seek() back in time for stepped scenes.

mote-engine 0.42

0.42 opens the engine to an AI: 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 shows how.

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.

A brain covered in small wireframe tetrahedra, drawn by the constellation renderer.
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.

A knot and a ring drawn by a custom renderer plugin: inked outlines and flat bands of light.
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 furry ball with eyes, its fur drawn by a custom api: 1 shader in Ray.

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. A robot can be written as data too: validateRobotFile() checks its description with the same kind of errors, each with its JSON pointer, and loadRobot() builds it.

Giving an assistant the context. Point your coding assistant at the package's TypeScript declarations (node_modules/mote-engine/dist/**/*.d.ts) and the scene schema 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 downloadable package installs no command. A process of your own that drives a page with the engine (in a headless browser, for example) gets the same control through the scene's API: scene operations, the timeline, describe() and the validators, with the same determinism.

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.

A version 2 document can also keep a hierarchy: an object's parent, groups without a shape, and one node of a glTF file as a shape. A missing parent or a cycle is refused at the object's JSON pointer, and scene.describe() writes a hierarchy back the same way. See A hierarchy in Scene JSON.

A document can name a model file as a shape, { "model": "chair.obj" } (glTF, OBJ, STL, PLY, COLLADA or binary FBX), or an SVG drawing, { "svg": "mark.svg", "depth": 0.08 }. A version 2 document can also declare a glTF file's whole node tree with its camera, its lights and an animation clip, so an AI can work on a scene made in Blender without copying its poses: see From Blender to mote and back. Edits made through scene.graph are not in Scene JSON yet; describe() says which nodes it left out.

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, and since 0.54 the spatial operations placeOn, placeRelative, align, distribute and resolveOverlaps, which place objects by their world bounding boxes. 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. For measuring, orthographicView() and drawOrthoMesh() (from mote-engine/director) draw the scene's triangles, read with scene.geometry(visit), as a plan or an elevation at a known scale. See Orthographic views of a scene.

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.

Guide videos. With a stepped clock, recordVideo() (from mote-engine/video) records the shot as an MP4 file in the browser, and describeShot() (from mote-engine/director) writes the prompt that goes with it for an AI video model: the camera's moves, the subjects, the lights and the look, the same text for the same scene and options. See Exporting a video.

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)
Joints that break, limits that tell breakForce, breakTorque on a joint; physicsEvents() with onJointBreak and onJointLimit
Let go of a kinematic body body.setType("dynamic", { keepContacts: true })
Move a kinematic body body.moveTo(position, quaternion)
Read physical state body.position, body.velocity, hinge.angle, hinge.angularVelocity, hinge.torque
Read state every step without allocating world.readPose(body, out), world.readVelocity(body, out), world.readHinge(hinge, out), world.readHingeLoad(hinge, out)
Command a hinge every step without allocating world.writeHinge(hinge, commands) (motor, drive, friction and damping from eight numbers)
Simulated motors world.use(components()), then attachMotor(hinge, record, { voltage }) with dcServoMotor (mote-engine/components)
Simulated sensors world.use(components()), then attachSensor(body, pose, record, { seed }) with imuSensor, encoderSensor, lidar2dSensor or tofZoneSensor (mote-engine/components)
A robot from a description file loadRobot(world, json, catalog, options), validateRobotFile(json) (mote-engine/components)
Figures that fall world.use(physicsPuppets()), then puppets.add(humanoid("mannequin")), puppet.limpOnImpact, puppet.goLimp(), puppet.readPose(out)
LiDAR-style observations world.raycastBatch(origin, directions, range, distances)
Nearest hit without allocating world.raycastInto(origin, direction, maxDistance, hit)
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; snapshots are version 2 since 0.51, and a world that holds a puppet cannot be saved yet. Use the new body and joint handles returned by world.restore(snapshot). With the same engine build, runtime and inputs, a run repeats bit for bit, in one process and across Node processes on the same host, and a sensor's noise repeats from its seed; bit equality across machines, JavaScript runtimes or engine versions is not promised (Physics → Determinism). 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/: serve the whole directory, which holds the element, its modules and the ones Ray, physics and custom effects load when a scene asks for them (an ASCII page fetches neither Ray's nor the physics world's). On upgrade, replace the directory as one unit, so no module comes from another version. 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 Space-separated stages. A glTF, OBJ, STL or mesh/Gaussian PLY URL (prefix a splat with splat: to force the Gaussian reader), or shape:box, shape:sphere, shape:torus, shape:knot. Defaults to a knot.
src-normalize Set to false to preserve the coordinates of model and Gaussian PLY stages.
splat-ambient Apply ambient and hemisphere lights to Gaussian PLY colours in Ray.
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, webgpu, 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

Integration recipes

The wrappers below are optional: the engine itself has no React or CMS dependency. Every snippet in this section is the exact source the engine's browser test runs — the React files byte for byte, the element snippet as its own page, the CMS block as the recipe's paste-ready HTML — so mount, draw, updates, unmount and remount are all verified.

Custom element lifecycle

Registration is idempotent, so a page that evaluates the element module twice — two bundles that both register it, a second script URL — defines one class and makes no second scene. The element owns its scene, follows live attributes and CSS resize, and destroys the scene after the disconnection microtask; moving it within the page does not recreate it.

<div id="scene-host" style="width: 480px"></div>
<script type="module">
  import { defineMoteScene } from "mote-engine/element";

  defineMoteScene();
  defineMoteScene(); // no second registration, no second scene

  const host = document.querySelector("#scene-host");
  const element = document.createElement("mote-scene");
  element.setAttribute("src", "shape:box");
  element.setAttribute("glyph-renderer", "canvas");
  element.setAttribute("autoplay", "false");
  element.setAttribute("label", "A rotating box");
  element.textContent = "A rotating three-dimensional box.";
  element.addEventListener("mote-error", (event) => {
    event.preventDefault(); // our status text handles it instead
    host.textContent = `Could not start the scene: ${event.detail}`;
  });
  const ready = new Promise((resolve) => element.addEventListener("mote-ready", resolve, { once: true }));
  host.append(element);
  await ready;

  element.setAttribute("color", "#eeeeee"); // live theme, same scene
  element.setAttribute("src", "shape:sphere"); // new source, same scene
  host.style.width = "320px"; // observed automatically

  element.remove();
  await Promise.resolve(); // element.scene is now null
  host.append(element); // one new scene, using the same shadow canvas
  await element.scene.ready;
</script>

Listen for mote-error and keep fallback HTML inside the element. A rejected load marks data-mote-state="failed"; without preventDefault() the error is also reported to the console. mode="ray" falls back to ASCII when WebGPU or its lazy module is unavailable.

React

The effect cleanup owns scene.destroy(). It runs when the component unmounts, before a shape/mode replacement, and between StrictMode's development setups, so a double mount ends with one live scene. Colours and zoom update the existing scene. The active flag keeps a late scene.ready settlement — in StrictMode's first pass the promise resolves after that scene was destroyed — from reaching an effect that was already cleaned up.

MoteScene.jsx, the component to copy:

import { useEffect, useRef, useState } from "react";
import { box, createScene, sphere, torusKnot } from "mote-engine";

const sources = { box, sphere, knot: torusKnot };

export function MoteScene({ shape = "box", mode = "ascii", color = "#222222", accent = "#006699", zoom = 0.85, onReady }) {
  const canvasRef = useRef(null);
  const sceneRef = useRef(null);
  const readyRef = useRef(onReady);
  const [error, setError] = useState(null);
  readyRef.current = onReady;

  useEffect(() => {
    let active = true;
    let scene;
    setError(null);
    try {
      scene = createScene(canvasRef.current, {
        stages: [{ source: sources[shape]() }],
        mode,
        glyphRenderer: "canvas",
        autoplay: false,
        ambientRipples: false,
        colors: { text: color, accent },
        zoom,
        ray: { fallback: "ascii" },
      });
    } catch (cause) {
      setError(cause);
      return undefined;
    }
    sceneRef.current = scene;
    scene.ready.then(
      () => {
        if (active) readyRef.current?.(scene);
      },
      (cause) => {
        if (active) setError(cause);
      },
    );
    return () => {
      active = false;
      scene.destroy();
      if (sceneRef.current === scene) sceneRef.current = null;
    };
  }, [shape, mode]);

  useEffect(() => {
    sceneRef.current?.setColors({ text: color, accent });
  }, [color, accent]);

  useEffect(() => {
    if (sceneRef.current) sceneRef.current.zoom = zoom;
  }, [zoom]);

  return (
    <div
      data-scene-state={error ? "failed" : "mounted"}
      style={{ width: "100%", aspectRatio: "16 / 9", background: "#ffffff" }}
    >
      <canvas
        ref={canvasRef}
        aria-label={`A ${shape}`}
        style={{ display: "block", width: "100%", height: "100%" }}
      />
      {error && <p role="alert">Could not start the scene: {String(error)}</p>}
    </div>
  );
}

The application mounts it under StrictMode at the root: in development React then runs every effect's setup, cleanup and setup again on mount, and the cleanup above is what leaves one scene alive. main.jsx, complete:

import React, { StrictMode, useEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { MoteScene } from "./MoteScene.jsx";

// A still of the scene's first frame, as a CMS would take it for a share image.
function Still({ capture }) {
  const canvasRef = useRef(null);
  useEffect(() => {
    const canvas = canvasRef.current;
    canvas.width = capture.width;
    canvas.height = capture.height;
    canvas.getContext("2d").putImageData(
      new ImageData(new Uint8ClampedArray(capture.data), capture.width, capture.height),
      0,
      0,
    );
  }, [capture]);
  return (
    <canvas
      ref={canvasRef}
      aria-label="A still of the scene"
      style={{ width: 120, height: "auto", display: "block", border: "1px solid currentColor", marginTop: 8 }}
    />
  );
}

function App() {
  const [mounted, setMounted] = useState(true);
  const [shape, setShape] = useState("box");
  const [dark, setDark] = useState(false);
  const [zoom, setZoom] = useState(0.85);
  const [narrow, setNarrow] = useState(false);
  const [readyShape, setReadyShape] = useState(null);
  const [still, setStill] = useState(null);
  const [captureError, setCaptureError] = useState(null);

  return (
    <main>
      <h1>React lifecycle</h1>
      <p>
        <button
          id="toggle"
          type="button"
          onClick={() => {
            setReadyShape(null);
            setStill(null);
            setCaptureError(null);
            setMounted((value) => !value);
          }}
        >
          {mounted ? "Unmount" : "Mount"}
        </button>
        <button
          id="theme"
          type="button"
          onClick={() => {
            setDark((value) => !value);
            setZoom((value) => (value === 0.85 ? 1 : 0.85));
          }}
        >
          Change props
        </button>
        <select id="shape" aria-label="Shape" value={shape} onChange={(event) => setShape(event.target.value)}>
          <option value="box">Box</option>
          <option value="sphere">Sphere</option>
          <option value="knot">Knot</option>
        </select>
        <button id="resize" type="button" onClick={() => setNarrow((value) => !value)}>
          Resize
        </button>
      </p>
      <div id="host" style={{ width: narrow ? 320 : 480, maxWidth: "100%" }}>
        {mounted && (
          <>
            <MoteScene
              shape={shape}
              color={dark ? "#eeeeee" : "#222222"}
              accent={dark ? "#66ccff" : "#006699"}
              zoom={zoom}
              onReady={(scene) => {
                setReadyShape(shape);
                // MoteScene calls this with the live scene only: in StrictMode's
                // first pass the scene is destroyed before its ready settles, and
                // a destroyed scene rejects capture with "destroyed".
                scene.capture().then(
                  setStill,
                  (cause) => setCaptureError(cause?.message ?? String(cause)),
                );
              }}
            />
            {still && <Still capture={still} />}
            {captureError && <p role="alert">Could not capture a still: {captureError}</p>}
          </>
        )}
      </div>
      <p id="status" role="status">
        {mounted ? (readyShape === shape ? `Ready: ${shape}` : "Loading") : "Unmounted"}
      </p>
    </main>
  );
}

// StrictMode at the root: in development React runs every effect's setup,
// cleanup and setup again on mount, exactly as a real double mount does.
createRoot(document.querySelector("#root")).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

The example's onReady captures a still of the ready scene with scene.capture(), which a destroyed scene rejects with destroyed: the guard above is what keeps that callback on the live scene. Pass new shape, color, accent or zoom props through your normal React state.

CMS and static HTML

Serve the installed package's dist/ directory, whole, under a versioned URL such as /vendor/mote-engine/0.50.0/: the element module and every module it loads, those Ray and physics load on demand included. Replace that folder as a unit on upgrade. Load the module once per page, even with several scenes: loading it again under another URL evaluates it again and still registers one class and no second scene.

<script type="module">
  import { defineMoteScene } from "/vendor/mote-engine/0.50.0/element/mote-scene.js";
  defineMoteScene();
</script>
<mote-scene
  id="scene"
  src="shape:box"
  mode="ascii"
  glyph-renderer="canvas"
  autoplay="false"
  ambient-ripples="false"
  label="A rotating box"
  style="width: 480px; max-width: 100%"
>
  <p>A rotating three-dimensional box.</p>
</mote-scene>

The CMS editor owns insertion and removal: removing the tag destroys its scene, and no React runtime or server-side engine component is required. Any site builder that takes custom HTML — WordPress, Wix, Squarespace, Webflow — can host this block; keep the fallback paragraph inside the element so the canvas is never the only channel.

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

Object IDs across stages

Give objects distinct IDs across the whole scene, and update their parent references together when renaming them. This works with the current API:

const scene = createScene(document.querySelector("canvas")!, {
  autoplay: false,
  stages: [
    { items: [
      { id: "entry-door", source: box(), motion: "none" },
      { id: "entry-handle", parent: "entry-door", source: box(), transform: { scale: 0.1 } },
    ] },
    { items: [
      { id: "exit-door", source: box(), motion: "none" },
      { id: "exit-handle", parent: "exit-door", source: box(), transform: { scale: 0.1 } },
    ] },
  ],
});
await scene.ready;
scene.item("exit-door")!.set({ rotation: [0, 45, 0] });
scene.show(1);

Existing programmatic scenes with repeated IDs remain usable: scene.item(id) keeps its existing resolution. The internal scene graph identity check reads every stage and reports duplicates and reserved IDs without renaming objects or changing that lookup. Reserve @root, IDs starting with @root/, and IDs starting with @legacy/ for the engine. The graph facade rejects ambiguous scenes with invalid when scene.graph or scene.graphAt is accessed. Migrate by renaming IDs and their references in the original stage data, then recreate the scene or call setStages with the corrected data.

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] }),
});

Parents and groups

An object can move with another: give it parent, the id of an object of the same stage. Its transform is then in its parent's frame, and every frame it is drawn with its ancestors' matrices times its own (each T × R × S, the object's motion in its rotation). Moving, turning or scaling a parent, by set, animate, a timeline track, its motion or its body, moves its children exactly so, in ASCII, Ray and Wireframe alike.

stages: [{
  items: [
    { id: "arm", source: box(), motion: "none", transform: { position: [-0.4, 0, 0], scale: [0.5, 0.1, 0.1] } },
    { id: "hand", parent: "arm", source: sphere(), motion: "none", transform: { position: [1, 0, 0], scale: [0.4, 2, 2] } },
    { id: "rig", motion: "none" },                                   // no source: a group
    { id: "lamp", parent: "rig", source: loadGltf("/models/lamp.glb"), transform: { position: [0.6, 0.5, 0], scale: 0.3 } },
  ],
}]

scene.item("arm")!.set({ rotation: [0, 0, 45] }); // the hand goes round with it
scene.item("hand")!.parent;                       // "arm"
scene.item("hand")!.transform;                    // still its own: position [1, 0, 0] in the arm's frame

Using the scene graph

The 0.56 scene graph exposes each stage's tree and supports detached creation, attachment and removal:

const scene = createScene(document.querySelector("canvas")!, {
  autoplay: false,
  stages: [{ items: [
    { id: "room" },
    { id: "door", parent: "room", source: box(), motion: "none" },
  ] }],
});
await scene.ready;
const graph = scene.graph;
const door = graph.getById("door");
console.log(door?.parent?.id); // "room"
console.log(graph.root.children.map(node => node.id)); // ["room"]
graph.traverse(node => console.log(node.id)); // root, room, door
console.log(graph.find(node => node.id === "door") === door); // true
scene.destroy();

scene.graph selects the current stage, or the destination during a morph. scene.graphAt(index) selects one existing stage; its searches cannot find objects in another stage. IDs must be unique across the whole scene. Legacy duplicates and reserved IDs cause an invalid error on graph access and leave the scene unchanged. Each synthetic root has ID @root/<index> and no parent or item. Nodes expose the existing item through node.item; ItemHandle.parent continues to return a string. children is a frozen insertion-order view, stable until a structural edit. Searches and visits use depth-first preorder including the starting node; misses return undefined. Mutating scene APIs during find or traverse throw traversal (asynchronous spawn rejects); nested visits are allowed up to 16 levels and release the block even when a callback throws. The visit guard does not cover direct writes to live data such as lights, shadows, effects or material fields, replacement of writable data properties such as debug, or raw physics bodies exposed by puppet bones. These remain open limits; use scene methods, item setters and item body controls for guarded edits.

The graph exposes identity, relations, item, queries and the transforms below. glTF nodes keep their existing IDs, names and supplied URL provenance; a node can have mesh, camera, light and bone roles together. Skin joints follow their declared order and the model is fitted once. Detaching a joint restores bind pose with one diagnostic until it returns; reattachment resolves live nodes without reviving old handles. name, bone, provenance, cameraDefinition and lightDefinition are internal glTF item metadata, not authored ItemSpec fields: ordinary inputs reject them with a TypeError naming the JSON pointer before changing the scene. Items returned by gltfTreeItems carry a protected loader snapshot, preserved by object spread; editing their descriptive metadata does not change the graph. Use NodeSpec for graph authoring.

glTF loader snapshots populate node.camera and node.light; their public descriptive fields remain independent copies. Light data retains file units; gltfSceneLights remains the explicit fitted photometric adapter, without duplicate rendered lights. graph.useCamera(node) selects an attached perspective camera in the current stage; useCamera(null) restores the saved rig. Detach freezes its last pose. Orthographic data stays readable, but selection throws unsupported-projection; FOV and clip reductions are diagnosed. Graph-created lights use local positions/directions, follow their parents once and stop lighting while detached, within the existing light limit. Legacy light attachments retain their origin/axis behavior. A legacy Light.attach target's light role is snapshotted when its node handle is created; later attachment edits do not recompute that handle's role list.

graph.create({ id, helper: { kind: "axes" } }) adds inspection overlays in ASCII, Wireframe, Ray and custom modes. Helpers support axes (default size 1), an XZ grid (default side 2, 10 divisions; 1–256 divisions), and box, light or camera with a same-stage node ID in target. Axes and grids follow their own composed transform. Boxes include mesh descendants and current skin/morph deformation; icons follow their target. Directional and spot arrows both point in the direction light travels. Perspective frusta use the viewport aspect and the selected camera's viewer policy (FOV 5–150°, near .001, unbounded far), with the drawable far plane shortened to keep depth and half-extents within 1000 scene units. Like the selected camera, perspective inspection normalizes the target's orientation so inherited scale/shear does not skew the projection. Orthographic frusta retain their authored extents and clips. Box/light/camera helpers require identity TRS at creation and reject every later TRS setter, including identity writes, with GraphError kind invalid at /transform. They may be detached or direct children of the stage root only. No helper may parent or target another helper; helpers may parent non-helper nodes. These rules also apply while detached. Rejected setters and topology batches preserve all nodes, history and ready. If a target ID is removed and recreated during helper preparation, publication rejects with invalid at /helper/target; retry creation to bind the new incarnation.

Helpers reuse the existing debug primitives: ASCII draws X/Y/Z glyphs and at most one glyph per handle/cell/frame; graphical axes use distinct radii 1/2/3 CSS pixels as well as color. Wireframe and Ray share the existing 4096-dot budget with public debug primitives. Helpers are depth-tested, including the WebGL2/ASCII fallbacks. In ASCII the test compares against the nearest sampled surface point in each cell, so a sparsely sampled occluder (a large or very near object beyond maxParticles, or asciiScaleDensity: false) can let helpers and scene.debug primitives show through its gaps. Ray draws them after composition, outside lighting, reflections, BVH and temporal/path-tracing history. Custom renderer plugins expose no readable depth: the overlay follows their output without occlusion, with one projection-reduced warning per scene. Display capture() includes the overlay, including refined Ray stills; linear capture retains its raw Ray radiance contract, before display inspection and decorations.

Overlay support loads lazily when helper topology is linked and joins scene.ready. If the overlay chunk fails to load, a helper overlay did not load warning names the cause; scene.ready settles with inspection unavailable and public debug drawing still usable, like the Ray loader's fallback. Updates reuse buffers after composition/deformation; boxes share bounds of only their target subtrees, selected once per topology change. enabled: false hides only inspection. Missing, detached or collapsed targets hide their helper with one missing-target warning per absence transition; reattachment or restoring scale resumes it. Removed IDs never reconnect. Mode changes, detach, replacement and destruction release internal draw handles; detached nodes retain their preallocated geometry for reattachment. Helpers participate in traversal and node/helper limits but have no Source, collider, mesh, shadow, occlusion, pick or spatial-operation target.

Public debug drawing (scene.debug.points / scene.debug.lines) keeps the same API and shared budgets. In custom mode, starting with 0.56, it draws after the effects over-layer and the plugin output, even without helpers. While any helper is attached (including disabled helpers), the shared overlay also draws public primitives without depth occlusion or the scene cell mask (nearest = Infinity, room = 1), because plugins expose no readable depth. Detaching all helpers restores the ordinary public depth/mask inputs; the custom draw order stays the same. ASCII, Wireframe and Ray keep their existing public debug depth behaviour.

Internal structural preflight checks a proposed batch before resource preparation: 4096 nodes per stage including the root, detached nodes and fit nodes, 64 real ancestors, 256 helpers, and 1024 UTF-8 bytes per new ID or name. It rejects cycles and cross-stage parenting without changing the scene. These limits do not restrict queries on previously accepted legacy scenes. On a stage already above one of them, structural edits, create and empty batches included, are refused with a limit error; a reparent that repairs excessive depth can pass. Concurrent create calls wait in the operations queue and are each rechecked before fetching, so the ones beyond a limit are refused before any download.

create validates and copies a serializable NodeSpec, reserves its ID across all stages, then waits in the scene's operations queue for its assets:

const node = await scene.graph.create({
  id: "panel",
  object: { shape: "box", material: { color: "#6688cc" } },
  transform: { position: [1, 0, 0] },
});
console.log(node.attached); // false
console.log(scene.graph.getById("panel")); // undefined
console.log(node.getById("panel") === node); // true

Shapes use the same loader as Scene JSON v2: primitives, model files, glTF (including one named or indexed node), SVG and Gaussian splats. A whole gltfTree is not a single-node shape. Motion defaults to none. Until attached, new nodes are not drawn; attaching one makes it render, and a body on it joins the physics simulation once attached. They never enter legacy item lookup; node.item is reserved for existing legacy items. Optional names, provenance and component data are copied and exposed read-only; cameras and lights use the component behavior described above. Duplicate IDs, including puppet IDs and future puppet parts, reject before fetching. Failures and cancellation release the reservation without publishing a partial node. Pausing cancels queued creation; setStages and destroy also release detached storage and make old handles report alive === false. A loader already in flight may finish, but its result cannot publish after cancellation. Stage replacement and destruction reject pending creates and release their preparation jobs even while a module or asset is still loading. Successful creation marks the operation history incomplete; describe() reports detached nodes omitted from Scene JSON v2, and graph-created nodes as unserializable even once attached.

Creation errors have GraphError.kind and path: module/asset failures use load, and pausing queued work uses paused. An already paused scene uses busy. Precedence follows execution: visit/lifecycle/morph guards, bounded input copy and identity/structural checks and ID reservation, the seek/replay busy guard, Director loading and pause admission, then queued readiness, structural rechecks, lazy module loading, payload validation and assets. Cancellation wins over a pending load; publication rechecks lifecycle and structure.

Attach, transfer or detach nodes with the same handles:

const group = await scene.graph.create({ id: "assembly" });
scene.graph.root.add(group);
group.add(node);                 // keeps the node's local transform
node.removeFromParent();        // keeps the node and its resources
scene.graph.root.add(node);     // visible at the end of the root's children

parent.add(a, b) transfers all arguments atomically within one stage. New children append in argument order; existing children keep their position, and repeated arguments count once. parent.remove(a, b) detaches direct children; other children are no-ops. Detached subtrees retain IDs, handles, geometry and local transforms. Reattaching reuses the same CPU mesh and material. Legacy removal, stage replacement and scene destruction release owned CPU storage once, including detached meshes, without disposing borrowed sources or changing another item sharing the source. ASCII sampling pauses while detached and reuses the mesh's samples on reattachment; removal and teardown clear owned sample caches without invalidating another node that shares its source. Wireframe drops cached mesh references at these structural changes; its render buffers are released when leaving the backend or destroying the scene, including when nodes are detached. Ray detachment retires pending preparation immediately and completed CPU preparation claims at the next scene frame or mode/device release boundary. A same-task or microtask reattach before that boundary retains completed BLAS/preview preparation; after retirement it rebuilds from the retained CPU geometry. Removal and destruction release only their own cache claims and never submit late GPU work. Root queries exclude detached nodes; their handle queries still work. Their world matrices compose from the detached root's local transform. Cycles, cross-stage transfers, using the root as a child and individual puppet-part transfers reject before changing relationships. No-op edits preserve views and history; effective edits mark history incomplete. The common busy, transition and traversal guards apply even to no-ops. Detach removes subtree bodies from simulation and closes each active contact or sensor pair once, delivered on the next physics tick. Reattachment starts from the current pose with zero linear and angular velocity; body commands while detached do not accumulate. Destruction also releases detached body state. A reattached body also re-enters at rest when its stage is later hidden and shown again. A contact end queued at detach is not delivered if the scene is destroyed or its stages are replaced before the next physics tick; while physics is paused it is held and delivered once, on the first tick after resuming. Detach also cancels every running tween in the subtree at its current local pose and resolves its promise once; reattachment does not restart it. Graph TRS edits and transfers that stay attached keep tweens running. Legacy removal, stage replacement and scene destruction also settle pending tweens on detached items. Mesh effects and their emitted particles pause while detached, retaining bounded state, geometry and materials. Reattachment resumes without catch-up emission; removal, stage replacement and scene destruction clear the owned effect pools once, including detached nodes. This also applies to CPU fallbacks. Detach suspends joints; reattachment recreates each once, with the same local anchors, axes and limits, only when both bodies are active (or the sole body for a world anchor). Recreated joints may emit jointLimit again. If the stage is hidden and shown while an endpoint is detached, its suspended binding is discarded: reattachment recalculates anchors from the stage definition at the current body poses. Broken joints stay broken. Parent authority changes at the topology commit without a physics step; the fixed rate remains 60 Hz. Destruction clears suspended joint registrations too. Legacy removal and respawn keep their existing joint behavior. An effective topology edit stores the stage's objects in depth-first order, so the order describe() lists them, and the by-position pairing a stage morph uses, can change for that stage; scenes that never edit the graph keep their order.

Removing a legacy item invalidates its node handle; setStages and destroy invalidate all old handles, including detached nodes and roots. Dead handles keep their final transforms, world matrix and metadata, report alive and attached as false, and expose no parent, children or item. Their queries visit only themselves; node edits throw stale. Reusing an ID creates a new incarnation. Retained stage facades also throw stale after replacement or destruction. Roots cannot be removed individually. Legacy spawn rejects IDs owned by graph-created nodes, attached or detached, and automatic IDs skip them; legacy remove still addresses legacy items only. The internal node listener registry suspends delivery while detached and unsubscribes once when its incarnation ends. Queued callbacks become inert; destruction also closes scene inputs, observers and cue subscriptions. Scene-wide observe() subscriptions survive setStages. There is no public node listener API. After destruction, observe() returns an inert unsubscribe, including on scenes using seek. Destruction is checked before callback type validation: even an invalid late callback returns a no-op; on a live scene a non-function callback throws TypeError.

Local transforms and world matrices

On an existing scene with a "door" object, move it in its parent's space and read its exact world matrix:

const door = scene.graph.getById("door")!;
door.position.set(1, 0, 0);
door.setTransform({ rotation: [0, 45, 0], scale: [-1, 2, 1] });
const world = new Float64Array(16);
door.copyMatrixWorld(world);
console.log(world[12], world[13], world[14]); // scene-space position

position, quaternion (x, y, z, w) and scale are stable live views with read-only components and chainable .set(...) / .copy(tuple) methods. setTransform accepts partial local transforms; Euler input is in degrees, X then Y then Z. Inputs are copied and validated atomically; signed and zero scales are supported. Quaternion normalization matches item setters and preserves already-unit values within 1e-12; input norms below 1e-12 are rejected with invalid. Graph writes leave existing tweens running toward their original targets; item.set retains its cancellation behavior. Use timeline tracks for animation.

matrixWorld is a live read-only view of 16 column-major doubles, including ancestors, motion and the current interpolated body pose, without the camera or view rotation. It preserves shear exactly. Retaining the view does not capture a snapshot; copyMatrixWorld(out) writes the first 16 entries of a caller-owned Float64Array. Warm TRS/facade reads and matrix copies allocate no storage and never step the clock or solver. For per-frame use, call allocation-free copyMatrixWorld(out) with reused storage. Reading matrixWorld[i] component by component may allocate a number in some JavaScript engines. Each stage keeps its own transforms during a morph; the synthetic root stays immutable identity and never becomes a physics parent. Writes during graph visits throw traversal; writes during a morph throw transition. Pending batches, steps, seeks, replay, preparation and frame callbacks reject synchronous writes with busy, before state or history changes. Await pending work and scene.ready, or the morph hold, before editing. Effective edits mark scene.log().complete false and expose the first frame and reason in unrecorded, also in describe().log. No-op and rejected edits preserve history. Graph commands/replay and Scene JSON v3 are scheduled for 0.57. The 0.56 JSON v1/v2 loaders and schema have no graph fields.

describe() still returns a v2 document. It sets complete: false for each unrepresentable helper, detached node, camera/light component, glTF node metadata or graph-created node, including nodes already attached. Diagnostics include the node ID and a JSON-pointer-like path into the runtime stage's items or detached array; detached-node identifies detached omissions, and unserializable identifies graph creation and omitted metadata/components. The remaining mesh/group data stays v2-compatible. A declarative gltfTree can preserve its original nodes through the file declaration; edits it cannot preserve retain tree-item diagnostics. Setup completeness and describe().log.complete are independent: a representable TRS edit can leave the setup complete while making unrecorded history incomplete.

The graph's public types are exported from the root API: SceneGraph, GraphScene, NodeHandle, NodeQuaternion, NodeSpec, NodeRole, NodeCamera, NodeProvenance, HelperSpec, DeepReadonly, GraphError and GraphErrorKind. Graph visits release their mutation block in a finally, so a callback that throws leaves the scene editable.

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:

Both EXT_meshopt_compression and KHR_meshopt_compression work without a decoder download or any setup. The reader supports vertex streams v0 and v1, triangle and general index sequences, and the OCTAHEDRAL, QUATERNION, EXPONENTIAL and COLOR filters. A placeholder or marked uncompressed fallback buffer is not fetched when the compressed data is present. Compressed output is limited to 64 MiB per buffer view and 256 MiB per model; malformed streams are refused before their output is allocated.

const source = await loadGltf("model.glb"); // compressed or uncompressed glTF 2.0

What is read:

Animations, armatures and shape keys are not read by this flat loader (a model read as a node tree plays all three: A model as a tree of nodes); 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).

A file's cameras are not read by this flat loader either. A model read as a node tree takes them, and their animation with them: A model's cameras.

Everyday object library

The examples include 30 original procedural everyday objects for scene prototypes: furniture, kitchenware, appliances, vehicles and street fixtures. A catalog records each model's category, size in metres, named anchors and their positions, licence, content hashes and preview. Sizes are [width, height, depth] in glTF's Y-up frame. Load these models with normalize: false to preserve their real scale.

Anchors are empty glTF nodes with names such as anchor.seat, anchor.back, anchor.top, anchor.handle, anchor.door, anchor.driver_seat and anchor.wheel.fl. They give spatial tools stable places for sitting, placing objects, opening parts and locating wheels. The catalog has a JSON Schema 2020-12 definition; all geometry, colours and small PNG previews regenerate from one script without downloaded assets.

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.

Collada models

Load a static .dae model from a URL, File/Blob, or bytes with loadCollada, or let loadModel detect it:

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

const canvas = document.querySelector("canvas");
const source = await loadCollada("/models/sculpture.dae");
const scene = createScene(canvas, {
  mode: "wireframe",
  stages: [{ items: [{ id: "sculpture", source, motion: "none" }] }],
});
await scene.ready;
// Call scene.destroy() when the canvas is removed.

The returned source supports both sample() and mesh(). COLLADA 1.4/1.5 triangles, polylist and simple polygons (including concave ones) are supported, with separate input offsets, accessor strides, normals and UVs. Geometry instances and node hierarchies bake matrix, translate, axis-angle rotate and scale in document order. The root asset's unit meter and X_UP/Y_UP/Z_UP convert to metres and Y-up before the default fit to a unit sphere. Pass { normalize: false } to keep those metric coordinates; ColladaOptions is the options type at the root API. Reflection preserves face winding; normals use the inverse transpose. The lowest numbered UV set becomes the mesh's UVs, with V converted to the image's top-down convention.

Scene JSON accepts { "model": "/models/sculpture.dae", "format": "dae", "normalize": false } in either version; format is optional when extension or content identifies the file. The custom element's src can also point to a .dae URL through the lazy model loader.

Phong, Blinn and Lambert profile_COMMON effects map linear diffuse, emission and specular colours, opacity and index of refraction to materials. Only materials bound by active geometry instances are read. Texture inputs are ignored with a warning: diffuse uses its colour factor or white, and emission uses its colour factor or no emission. Constant shaders use the emission colour as an unlit base; texture-only or absent emission gives an unlit white base with no emissive channel. Emission colour factors may exceed 1 and stay linear. Phong shininess converts to perceptual roughness; Lambert uses roughness 1. Degenerate faces (repeated vertices or zero area) and untriangulable polygons are dropped with one warning and a count per file; loading fails if no triangles remain. Animation libraries are ignored: this is the authored static pose. Skin/morph controllers, polygon holes, lookat/skew, external document references and nested asset unit/axis overrides are refused with diagnostics. Export a static mesh with colour factors for this reader.

Collada uses the same configurable MODEL_LIMITS as mesh loaders: 64 MiB per file, 3,000,000 expanded polygon corners, 1,000,000 triangulated faces and 65,280 bound materials by default. XML is UTF-8 only; the five predefined entities and valid XML numeric character references are decoded once without expansion beyond the input size. DOCTYPE, external and custom entities are refused. Additional parser caps are 100,000 XML elements/node visits, 1,000,000 work units (node visits and child scans, one-time geometry/primitive and binding scans, and 1 + nonempty part count per geometry-instance visit), depth 64, 64 attributes per element, 16 inputs, stride/offset width 32, UV set indices 0–7 and 256 corners per polygon. A per-file budget of 8,000,000 repeated ear-clipping search steps bounds superlinear triangulation work; triangles, quads and linear convex clipping do not spend it. Each instance_geometry element shares one resolved geometry, binding map and face/vertex counts across visits. Zero-count primitives are dropped but charged to the work budget. Expanded face/corner totals across all visits, ranges and references are checked before triangulation or sized output allocation. Each geometry is triangulated once in local space, then transformed per instance. Parsing and baking happen during loading.

OBJ, STL and mesh PLY

loadModel reads glTF, OBJ, STL, PLY, COLLADA and binary FBX from a URL, File/Blob, or bytes. It chooses by filename extension or content; format: "gltf" | "obj" | "stl" | "ply" | "dae" | "fbx" overrides detection. The returned source has the same sample() and mesh() contract as every other model:

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

const canvas = document.querySelector("canvas")!;
const scene = createScene(canvas, {
  stages: [{ source: loadModel("/models/part.obj"), motion: "none" }],
  mode: "ray",
});
await scene.ready;
// Use scene.item("...") or change stages here; call scene.destroy() when finished.

Use loadObj, loadStl or loadPlyMesh when the format is already known. All four functions accept normalize: false to retain file units. OBJ bytes or a Blob with external references also need baseUrl; mtllib paths resolve against the OBJ URL and map_* paths against their MTL URL. Browser image decoding is automatic. Elsewhere, pass decodeImage(bytes, mimeType); a failed MTL or image load emits a diagnostic and leaves usable geometry and colour factors in place. URL references follow the same rule as glTF buffers (new URL(reference, containingFileUrl)), including parent paths and other origins; the host controls which URLs may be fetched.

Untrusted inputs are checked for finite values, valid indices and structure before sized mesh arrays are allocated. MODEL_LIMITS for OBJ, STL and mesh PLY defaults to 64 MiB a file, 3,000,000 vertices, 1,000,000 triangulated faces and 65,280 materials; maxBytes, maxVertices, maxFaces and maxMaterials can tighten them. Downloads are counted while streaming; PLY headers select the mesh or Gaussian budget before the body is accumulated. Gaussian splats retain their own 768 MiB budget and glTF retains its existing behaviour. OBJ dependencies are bounded to 128 MTL libraries, 4096 texture references, 256 MiB of downloaded dependency bytes in total and 16,777,216 pixels per decoded image. These are parser setup costs, not work in animation frames.

Starting with 0.56, MTL Ps sets sheenColor to the linear triplet [Ps, Ps, Ps], clamped to 0–1, without a warning. map_Ps sets sheenColorMap using RGB in sRGB, multiplied by Ps; a map without Ps uses a white factor, while an explicit Ps 0 disables sheen. Image URLs, decoding, limits and failure diagnostics follow the other MTL maps. Pr still sets the base roughness: the PBR MTL extension defines no separate sheen roughness, so sheenRoughness keeps its default of 0.

For example, save this as cloth.mtl beside an OBJ that declares mtllib cloth.mtl and selects usemtl cloth:

newmtl cloth
Kd 0.35 0.12 0.08
Pr 0.7
Ps 0.6

Loading that OBJ with loadObj produces sheenColor: [0.6, 0.6, 0.6] and roughness: 0.7. Add map_Ps sheen.png to multiply the sheen by an image beside the MTL; the mesh needs texture coordinates for the image.

The element loads the general model parsers on demand. The director records model files and their MTL, texture and glTF buffer dependencies in assets and describe().assets; clay also replaces general models' source materials.

In Scene JSON v1 or v2, the equivalent shape is:

{ "model": "models/part.ply", "format": "ply", "normalize": false }

format is optional. <mote-scene src="/models/part.obj"> and .stl/.ply URLs use the same dispatcher; a splat: prefix still forces the Gaussian reader.

Binary FBX

loadModel also accepts binary FBX 7.x, detected from .fbx or its binary header. Use format: "fbx" to select it explicitly, or loadFbx when the format is known:

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

const canvas = document.querySelector("canvas")!;
const source = await loadFbx("/assets/sculpture.fbx");
const scene = createScene(canvas, {
  mode: "ray",
  stages: [{ items: [{ source, motion: "none" }] }],
});
await scene.ready;
// Call scene.destroy() when removing the canvas.

The source fits a unit sphere by default. normalize: false retains the model's placement and converts its declared axes and units to Y-up metres, with +Z towards the viewer. Geometry connections, repeated mesh instances, parent transforms, all six Euler orders, pre/post rotations, pivots, offsets and geometric transforms are baked into the static mesh. Concave polygons are triangulated. Degenerate or untriangulable faces are dropped, with one warning per file reporting the count; files with no remaining triangles are rejected. The first normal, UV and colour layers retain their mapping and indexed references. UV V is converted to top-down coordinates. Missing normals become flat triangle normals. Per-polygon materials map diffuse/emissive colours and factors, opacity, specular colour/strength and a Phong-to-roughness approximation; explicit roughness and metalness are read when present.

Both 32-bit and 64-bit node records and raw/zlib arrays are supported without a runtime dependency. The loader uses platform decompression when available and its own decoder otherwise. FbxOptions accepts normalize, sample and the four MODEL_LIMITS overrides. Additional fixed caps are 64 MiB per expanded array, 256 MiB in total, a 256:1 expansion ratio, 100,000 nodes, 1,000,000 properties, 64 hierarchy levels and 4096 corners per polygon; triangulation shares a deterministic budget of 10,000,000 steps across the whole file. For polygons with more than four corners, each blocker visit in an ear test (including visits skipped by adjacency or bounds) and each failed ear candidate costs one step. Triangles and quads cost zero steps; linear per-corner setup, successful clips and orientation calculations are not charged. Convex caps avoid quadratic ear searches; concave polygons scan reflex/collinear blockers without a spatial index (O(n·r) for n corners and r blockers). Files exceeding that work budget are rejected. Smaller maxBytes values tighten the expanded array caps. Actual decompressed lengths and back-references are checked before allocating decompression output.

This import reads static mesh data. Skinning, animation, blend shapes, constraints, cameras, lights, texture/video resources, extra UV/colour sets and custom property-template defaults are not imported. ASCII/big-endian FBX, spheric rotations and edge-mapped layers are rejected. Vertex colour alpha is ignored. The same reader works through Scene JSON { "model": "/assets/sculpture.fbx", "format": "fbx" } and <mote-scene src="/assets/sculpture.fbx">.

A model as a tree

loadGltf reads a model into one object: every node's transform is applied to its vertices and the parts are merged, so a part can no longer be turned on its own. gltfTree reads the same scene with its hierarchy kept, and gltfTreeItems makes the scene's objects of it, one per node, each the child of its parent's:

import { createScene, parseGltf, gltfTree, gltfTreeItems } from "mote-engine";

const doc = parseGltf(await (await fetch("/models/robot.glb")).arrayBuffer());
const tree = gltfTree(doc);                                  // nodes, parents first, and the model's fit
const { items, ids } = gltfTreeItems(tree, { id: "robot" }); // ItemSpecs: a root, the fit, one object per node
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });

scene.item("robot")!.set({ scale: 0.8 });                    // the whole model, as a flat one
scene.item("robot/Arm.L")!.animate({ rotation: [0, 0, 60] }, 1); // one node, about its own origin: its children follow

Retained camera and light data

Tree nodes and generated items expose cameraDefinition and lightDefinition alongside their camera and light indices. The definitions keep the file's units and values, including perspective yfov/fov, optional aspect and far plane, orthographic magnifications and clipping planes, and punctual light colour, intensity, range and cone angles. Each definition's nodes contains only the carrying node's original index.

import { parseGltf, gltfTree, gltfTreeItems } from "mote-engine";

const url = new URL("scene.glb", location.href).href;
const response = await fetch(url);
if (!response.ok) throw new Error(`Model request failed: ${response.status}`);
const tree = gltfTree(parseGltf(await response.arrayBuffer()));
const { items } = gltfTreeItems(tree, { id: "shot", gltf: url });
for (const item of items) {
  if (item.cameraDefinition || item.lightDefinition) {
    console.log(item.provenance, item.cameraDefinition, item.lightDefinition);
  }
}

provenance: { gltf, node } identifies every original node, including camera-only and light-only nodes without a source or shape; the generated root and fit have none. Without the gltf option, definitions remain available and provenance is absent. Items own copies of the definitions and their arrays. Invalid light values keep their index and a tree diagnostic, with no lightDefinition.

The graph exposes these loader snapshots through node.camera, node.light and node.provenance. Passing items to a scene does not select a camera or add illumination: use graph.useCamera or gltfCameraRig for the camera, and gltfSceneLights for fitted photometric lights. Orthographic scene projection remains unsupported. Scene JSON v2 does not encode per-node metadata; describe() diagnoses the loss unless a declarative gltfTree preserves it through the original file.

Skinned meshes

A glTF skin binds one mesh to a skeleton: every vertex follows up to four joints by weights (JOINTS_0, WEIGHTS_0), each joint a node of the file. gltfTree reads it, and gltfTreeItems gives the skinned node's object a skin (ItemSpec.skin): the ids of its joints' objects, the skeleton's root and the inverse bind matrices. Nothing else is needed: turn a joint's object (set, animate, a timeline track, gltfTracks) and the mesh bends.

const doc = parseGltf(bytes);
doc.json.materials?.forEach((material) => { material.doubleSided = true; }); // a cape visible from behind in Ray
const tree = gltfTree(doc);                                     // tree.nodes[n].skin: joints, root, inverseBind
const { items, ids } = gltfTreeItems(tree, { id: "hero", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });
scene.item("hero/Forearm.L").animate({ rotation: [0, 0, 70] }, 0.6);   // a joint: the skin follows
await scene.setTimeline(gltfTracks(doc, tree, ids, { loop: true }).timeline);   // or the file's own animation

Morph targets

A glTF mesh may carry morph targets (Blender's shape keys): each a set of displacements, one a vertex, and a weight says how much of it is applied. gltfTree reads them, and gltfTreeItems gives the node's object its weights (ItemSpec.weights): the node's own, else the mesh's defaults, else zeros.

const tree = gltfTree(parseGltf(bytes));                         // tree.nodes[n].weights: one number a target
const { items, ids } = gltfTreeItems(tree, { id: "face", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });
scene.item("face/Head").weights = [1, 0, 0.3];                    // by hand: from the next frame
await scene.setTimeline(gltfTracks(doc, tree, ids, { loop: true }).timeline);   // or the file's own `weights` animation

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.

External glTF decoders

loadGltf accepts Draco geometry and Basis KTX2 textures through decoder files hosted by your application. Configuration belongs to one load, so separate applications and models can choose different decoder versions.

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

const source = await loadGltf("/models/model.glb", {
  decoders: {
    draco: { path: "/decoders/draco/" },
    ktx2: { path: "/decoders/basis/" },
    timeoutMs: 15000,
  },
});
const scene = createScene(document.querySelector("canvas"), {
  mode: "ascii",
  stages: [{ items: [{ source, motion: "none" }] }],
});
await scene.ready;

Place draco_wasm_wrapper_gltf.js and draco_decoder_gltf.wasm in the Draco directory, and basis_transcoder.js and basis_transcoder.wasm in the Basis directory. Obtain matching files from the Draco releases and prebuilt decoder instructions and Basis Universal project. Both external decoders use Apache-2.0; retain their licenses when hosting them. For existing filenames, set js and wasm relative to path. The JavaScript-only Draco build uses { path: "/decoders/draco/", js: "draco_decoder_gltf.js", wasm: false }.

The engine loads the selected files only when a model uses that format. It has no default decoder URL, bundled decoder, WebAssembly payload or runtime dependency. Without a decoder for an extension, an optional extension uses its uncompressed accessors or PNG/JPEG texture source. Required extensions and missing fallbacks reject the load with the filenames and upstream location. A configured decoder takes precedence; corrupt data and decoder failures reject the load even when a fallback exists.

Applications that already own the files can pass { module: { javascript: jsFileContents, wasm: wasmBytes } } for either decoder. javascript is the complete classic Emscripten script as a string and wasmBytes is a Uint8Array; functions and initialized module instances cannot cross the Worker boundary. This form makes no engine fetch for decoder assets.

parseGltfAsync(bytes, { decoders }, externalFileResolver) returns a document usable with gltfMesh, gltfTree, skin and animation APIs. loadGltfFiles also accepts decoders; its resolver supplies external KTX2 images as well as binary buffers. parseGltf and gltfSource remain synchronous: they always use the uncompressed fallback for optional extensions and reject required extensions or missing fallbacks.

<mote-scene> and Scene JSON do not accept decoder configuration. They use fallbacks for optional extensions; compressed-only models need loadGltf with decoders, followed by passing the returned source to a scene in JavaScript. The general loadModel API also has no decoder option in its public type.

Every decode runs in a short-lived Worker, terminated on success, error or timeout. The deadline covers decoder download, initialization and decoding once a job obtains a slot; two jobs run concurrently, with at most 64 queued. timeoutMs accepts 1–120000 milliseconds. Serve assets with suitable CORS and allow Blob Workers and WebAssembly compilation in the page's CSP. Node callers need a Web Worker adapter; there is no main-thread decoding fallback. Worker termination protects responsiveness; browser Workers do not impose a hard memory or network sandbox on application-supplied scripts.

Draco currently accepts indexed TRIANGLES, at most 16 million components per accessor, 64 MiB decoded per primitive and 256 MiB per document. Counts, attribute widths, finite values and index ranges are checked before geometry is exposed. KTX2 accepts 2D Basis ETC1S/UASTC LDR images up to 4096×4096, with a 64 MiB encoded input cap and 256 MiB decoded image budget per document. It transcodes the base mip to RGBA8: four bytes per texel (4 MiB at 1024×1024), shared by CPU sampling and Ray materials. Ray retains its existing 2048-pixel resampling limit. Texture arrays, cubemaps, HDR, sparse Draco accessors and non-triangle Draco primitives are rejected. GPU block compression and authored KTX2 mip chains are not retained.

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, capsuleMesh, tubeMesh(curve).

capsuleMesh(radius, halfHeight, segments, rings) is the physics engine's capsule collider drawn: a cylinder around y from −halfHeight to +halfHeight closed by a half sphere at each end (it reaches halfHeight + radius either way), one smooth surface of segments sides (16) and rings bands of latitude over the two caps together (8, an even number). meshSource(capsuleMesh(0.1, 0.3), { normalize: false }) is a source in the mesh's own units: an object of it at scale 1 is the body { shape: { type: "capsule", radius: 0.1, halfHeight: 0.3 } }, which is how a puppet's parts are drawn.

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.

svgSource(text, options) reads SVG geometry without a DOM, in Node or a browser, and gives every fill its own colour in all render modes:

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

const mark = svgSource(`<svg viewBox="0 0 24 24">
  <path fill="#e04b3a" fill-rule="evenodd"
    d="M12 2 21 12 12 22 3 12Z M12 7 17 12 12 17 7 12Z"/>
</svg>`, { depth: 0.08, bevel: 0.01, curveSegments: 24, stroke: true });
const scene = createScene(canvas, { stages: [mark], mode: "ray" });

Supported geometry is path (including elliptical arcs), rect, circle, ellipse, line, polyline, polygon and nested g transforms, with inherited fill, fill-rule and presentation attributes. depth is a fraction of the viewBox's larger side; its default 0 makes two flat faces. bevel defaults to 0 and is limited to half the thickness, curveSegments is 16 by default (1–128), and stroke: true turns stroke/stroke-width into filled outlines. In Scene JSON v1 and v2, an object's shape is { "svg": "/shapes/mark.svg", "depth": 0.08 }; the file is fetched only when the scene loads it.

The XML reader accepts the five predefined XML entities, refuses a DOCTYPE with an internal subset, and limits input to 2 MiB, 256 elements, 4096 generated points and 16 levels (SVG_LIMITS). CSS stylesheets, SVG text and gradient shading are not supported. A gradient fill uses its first stop's colour; unsupported elements are skipped and named in source.diagnostics. Strokes use butt caps and mitred joins; bevels use mitred offsets. Separate overlapping contours are filled independently with nonzero; triangles may overlap in flat and extruded geometry, covering the union without a polygon boolean operation. For overlapping evenodd contours and self-intersecting contours, a diagnostic names the element and the importer fills each contour (or its simple lobes) independently as nonzero. True XOR/union polygon booleans are not supported.

All 148 CSS named colours are supported. transparent, none and zero fill-opacity produce no fill geometry; fill/stroke opacity inherits through groups. Unknown colour names and missing gradient references emit a diagnostic naming the element and use black. Coordinates and viewBox components must be finite with absolute values at most 1e12; viewBox width and height must be at least 1e-12. Transformed and normalized coordinates must also be finite and at most 1e12 in absolute value, before triangulation and typed mesh allocation. Out-of-range input is refused.

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 with WebGPU available. The WebGL2 Wireframe fallback and its particle pen load only when that fallback is needed, without fetching Ray or asking for a WebGPU device. The custom-effect host (the ray manifests' validator and compiler front, see custom shaders) loads 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: the no-build-step <mote-scene> bundle takes about 464 KB minified (180 KB gzipped) up front with esbuild (plain build). 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. Ray asks for a replacement device after loss; Wireframe continues with WebGL2. An explicit setMode("wireframe") tries WebGPU again. 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).

3D Gaussian splats

Load a binary little-endian INRIA PLY alongside a glTF building model in one scene. Use metre-scale coordinates for the building and supply a column-major matrix that maps the splat into that space. The matrix is optional when the two inputs already share coordinates.

const scan = await loadGaussianSplats("house.ply", {
  normalize: false,
  matrix: scanToBuilding,
  shDegree: 3,
  ambient: true,
});
const building = await loadGltf("house.glb", { normalize: false });

const scene = createScene(canvas, {
  mode: "ray",
  lights: [{ kind: "ambient", color: [1, 0.95, 0.88], intensity: 0.9 }],
  stages: [{ items: [{ id: "scan", source: scan, motion: "none" }, { id: "building", source: building, motion: "none" }] }],
});
scene.setCameraRig({ kind: "static", pose: { position: [0, 1.6, 2], target: [0, 1.6, 0] }, fov: 60 });

Both loaders fit the source to a unit sphere by default. Splat colours come from the PLY's spherical harmonics and use the captured lighting by default. With ambient: true, Ray multiplies the captured colours in linear space by the scene's ambient lights and the average of each hemisphere light. Use exposure for a cloud-specific adjustment in stops and maxSplats to retain an evenly spaced subset. Ray quality tiers can reduce the effective SH degree. ASCII and Wireframe draw coloured point centres.

Ray composites the splats into the same linear HDR image as the glTF mesh, after temporal antialiasing, against the mesh's unjittered depth. Director camera rigs and timeline camera and ambient-light operations apply to these sources. The JSON representation is { "gaussianSplats": "house.ply", "normalize": false, "ambient": true } in an object's shape. The Director records the PLY's path and hash for replay.

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. WebGPU draws first (stats().backend reads webgpu-wireframe). If WebGPU is missing, its module or device cannot be prepared, or its device is lost, WebGL2 draws the same indexed meshes with hidden lines and preview faces. scene.mode stays "wireframe", stats().backend starts with webgl2, and stats().ray.fellBack gives the reason. If WebGL2 is unavailable or its context is lost, the whole scene draws ASCII. Ray still defaults to ASCII on failure; ray: { fallback: "wireframe" } selects the Wireframe fallback chain. The glyphRenderer option controls the glyphs and effect particles separately from the meshes.

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 WebGPU inspection buffer is capped at 524,288 pixels and scaled to the visible canvas, including on Retina displays. WebGL2 uses a CPU coverage buffer capped at 262,144 pixels and draws triangles and edge strips, or presents the resolved pixels for wide strokes, alpha textures and continuous cuts. Both use CSS-pixel stroke widths and the same face opacity. WebGL2 keeps flat face shading; smoothSurfaces, antialias, fxaa and mipmaps are WebGPU-only. Raster boundaries can differ by a device pixel; above the caps, the different internal resolutions can change thin-line detail. Effect particles keep their layers; their intersections with meshes in WebGL2 use visibility at each particle's centre. Lenses and continuous glows use their CPU or image fallback so they can affect the complete picture. On WebGPU, 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:

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.

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.

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
unlit false base colour (factor, texture and vertex colour) as emitted light, with no lighting and no emissive term
sheenColor, sheenRoughness, sheenColorMap, sheenRoughnessMap black, 0 a Charlie cloth lobe with energy-conserving attenuation of the base material; colour map RGB is sRGB, roughness map A is linear
anisotropyStrength, anisotropyRotation, anisotropyMap 0, 0 anisotropic GGX, rotated counter-clockwise in tangent space (radians); map RG is direction from 0..1 to −1..1, B is strength
iridescence, iridescenceIor, iridescenceThicknessMin, iridescenceThicknessMax, iridescenceMap, iridescenceThicknessMap 0, 1.3, 100, 400 a Belcour/Barla thin film, thickness in nanometres; strength map R and thickness map G (0 selects the minimum, 1 the maximum) are linear
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
import { createScene, sphere } from "mote-engine";

const canvas = document.querySelector("canvas")!;
const scene = createScene(canvas, {
  mode: "ray",
  stages: [{ items: [
    { id: "fabric", source: sphere(), transform: { position: [-1, 0, 0] },
      material: { color: "#384050", roughness: 0.8,
        sheenColor: [0.6, 0.6, 0.6], sheenRoughness: 0.4,
        anisotropyStrength: 0.35, anisotropyRotation: Math.PI / 4,
        iridescence: 0.2, iridescenceIor: 1.3, iridescenceThicknessMax: 400 } },
    { id: "sign", source: sphere(), transform: { position: [1, 0, 0] },
      material: { color: "#ffb000", unlit: true } },
  ] }],
});
await scene.ready;
// Call scene.destroy() when the canvas is removed.

Ray reads KHR_materials_unlit, _sheen, _anisotropy and _iridescence, including their textures. Anisotropy uses authored TANGENT vectors even without UVs; otherwise it uses the normal-map UV-derived tangent frame, or a stable frame when UVs are degenerate. The public Mesh.tangents field accepts four floats per vertex (xyz direction and a bitangent sign of −1 or 1). Tangent morph targets remain unsupported. ASCII and Wireframe draw unlit base colour without lighting and approximate the other three extensions by ordinary base colour.

These are JavaScript/TypeScript material fields. Scene JSON can load them from glTF assets; inline Scene JSON material fields have not been extended. Imported maps retain the loader's UV0-only and zero texture-rotation restrictions. Without a thickness map, the maximum thickness is used; a reversed minimum/maximum range is valid, and zero thickness disables the film. Sheen uses a minimum squared roughness of 0.002, a numerical directional-albedo table, and a reciprocal energy bound at grazing angles. Hybrid environment sheen uses the local diffuse irradiance as an approximation; refined opaque paths sample the sheen lobe.

The refined dielectric path used when transmission * (1 - metallic) >= 0.5 retains its existing isotropic glass model: sheen, anisotropy and the thin film are not yet composed into that path. Use opaque materials when comparing these three extensions across hybrid and refined rendering.

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.

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
jointSolver "sequential" how the hinges are solved. "sequential": each joint on its own, softly, as every earlier version. "chain": the hinges of a step together, exactly, so a hinge carrying a load off its axis stays on it; a hinge then also takes drive, friction and damping. See Hinges under load
jointHertz Infinity with "chain" only: how fast a hinge's position error is closed, in Hz (above 0 and up to 1e6, or Infinity: within one sub-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

Determinism

With the same engine code and runtime, identical options and exactly the same calls in the same order—including insertion order, dt, substeps and sensor seeds—the CPU world is bit-for-bit deterministic in one process and in separate Node processes on the same host. Restoring a world snapshot continues bit for bit under the same subsequent commands, with matching modules and components and the application-owned state restored too. A fixed sensor seed repeats its noise sequence; another seed gives another sequence.

Bit equality is not promised across machines, operating systems, JavaScript runtimes, Node/browser boundaries or engine versions. Changing insertion order, step size, substep count or command timing is a different numerical run. Scene interpolation, effects and application state are outside the world guarantee, as are wall-clock timings and GPU images, which are not bit-deterministic across hardware. Each level, with the test behind it, is listed in Determinism.

Borrowed events

Set physics.events to receive onContactBegin, onContactPersist, onContactEnd, onImpact, onSensorEnter, onSensorExit, onSleep, onWake, onJointBreak, onJointLimit and onBodyRemoved. Each SceneEvent carries:

The world applies scale once; the scene forwards those SI values unchanged.

The old onContact remains an independent allocating callback with its original raw solver units and ownership; leave it unset for allocation measurements.

The two joint events come from the stage's joints:

For both:

A joint removed by the application, or with one of its objects, tells nothing.

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.

On a standalone world, readPose, readVelocity and readCenter write a body's current state into a caller-owned Float64Array or Float32Array, starting at an optional index (0 by default), without allocating:

A Float32Array rounds each value as usual. Each method returns false, writing nothing, when the body is not live in that world.

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

const world = createPhysicsWorld({ gravity: [0, 0, 0] });
const body = world.addBody({
  shape: { type: "sphere", radius: 0.5 },
  position: [0, 2, 0],
  velocity: [1, 0, 0],
});
const pose = new Float64Array(7);
const velocity = new Float64Array(6);
const centre = new Float64Array(3);
world.step(1 / 60);
if (world.readPose(body, pose) && world.readVelocity(body, velocity) && world.readCenter(body, centre)) {
  console.log(pose[1], velocity[0], centre[1]);
}

readHinge does the same for a hinge: it writes the hinge's angle (radians) and angular velocity (rad/s) into the buffer, two numbers from the index, bit for bit what hinge.angle and hinge.angularVelocity give. Those two are getters, and a number a getter returns is a new 16-byte heap number wherever the JavaScript engine does not inline the getter into the code that reads it (Node 22 often does not); readHinge never allocates, so it is the read for a loop that runs at every step. It returns false, writing nothing, for a joint that is not a live hinge of that world (another kind of joint, a removed hinge, another world's).

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

const world = createPhysicsWorld();
const arm = world.addBody({ shape: { type: "box", halfExtents: [0.25, 0.05, 0.05] }, position: [0.25, 0, 0], mass: 0.2 });
const hinge = world.addJoint({ type: "hinge", a: arm, b: null, anchor: [0, 0, 0], axis: [0, 0, 1] });
hinge.setMotor(2, 5);                       // 2 rad/s, up to 5 N·m
const state = new Float64Array(2);          // [angle, angular velocity]
for (let i = 0; i < 60; i++) {
  world.step(1 / 60);
  if (world.readHinge(hinge, state)) {
    // state[0] is hinge.angle, state[1] hinge.angularVelocity
  }
}
console.log(state[0], state[1]);            // about 2 rad after a second, at 2 rad/s

Two more calls complete it, for a controller that computes a hinge's commands at every step (a servo's model, a robot's firmware):

A drive whose maxTorque is 0 is no drive; the joined bodies are woken when a command changes, and only then; what the setters refuse throws before anything changes (a drive, a friction or a damping that is not 0 needs jointSolver: "chain").

Both return false, changing nothing, for a joint that is not a live hinge of that world.

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

const world = createPhysicsWorld({ jointSolver: "chain", gravity: [0, 0, 0] });
const arm = world.addBody({ shape: { type: "box", halfExtents: [0.25, 0.05, 0.05] }, position: [0.25, 0, 0], mass: 0.2 });
const hinge = world.addJoint({ type: "hinge", a: arm, b: null, anchor: [0, 0, 0], axis: [0, 0, 1] });
// [motor speed, motor maxTorque, drive target, stiffness, damping, drive maxTorque, friction, damping]
const commands = new Float64Array([0, 0, 0, 20, 2, 5, 0.01, 0]);
const state = new Float64Array(2), load = new Float64Array(2);
for (let i = 0; i < 120; i++) {
  commands[2] = 0.5 * Math.sin(i / 20);     // a new drive target at every step, without a heap number
  world.writeHinge(hinge, commands);
  world.step(1 / 60);
  world.readHinge(hinge, state);            // [angle, angular velocity]
  world.readHingeLoad(hinge, load);         // [torque (N·m), work (J)] of that step
}
console.log(state[0], load[0]);

A body's type can change while the world runs: body.setType("kinematic"), "dynamic" or "static".

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

const world = createPhysicsWorld();
const events = world.use(physicsEvents());
events.onContactBegin = (e) => console.log("begin", e.idA, e.idB);
events.onContactEnd = (e) => console.log("end", e.idA, e.idB);
world.addBody({ type: "static", shape: { type: "plane", normal: [0, 1, 0], offset: 0 } });                              // id 1
const tray = world.addBody({ type: "kinematic", shape: { type: "box", halfExtents: [1, 0.1, 1] }, position: [0, 0.1, 0], mass: 5 }); // id 2
world.addBody({ shape: { type: "box", halfExtents: [0.2, 0.2, 0.2] }, position: [0, 0.4, 0], mass: 1 });                 // id 3
for (let i = 0; i < 30; i++) world.step(1 / 60);    // "begin 2 3": the crate rests on the tray
tray.setVelocity([0.5, 0, 0]);                      // carried along by hand...
for (let i = 0; i < 30; i++) world.step(1 / 60);
tray.setType("dynamic", { keepContacts: true });    // ...then let go: it keeps its 0.5 m/s and the crate on it
for (let i = 0; i < 30; i++) world.step(1 / 60);    // "begin 1 2" only: the tray, now dynamic, meets the floor

Ray queries

On a standalone world, raycastInto(origin, dir, maxDistance, out, filter?) finds the nearest hit like raycast, equal to it within a relative tolerance of 1e-12 (and an absolute 1e-12 near zero), but writes it into storage the caller reuses (a RayHitRecord: { body, point, normal, distance }) and allocates nothing after its internal buffers have reached their high-water mark.

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

const world = createPhysicsWorld({ gravity: [0, 0, 0] });
world.addBody({ shape: { type: "sphere", radius: 0.5 }, position: [0, 0, 0] });
const hit = { body: null, point: new Float64Array(3), normal: new Float64Array(3), distance: 0 };
if (world.raycastInto([0, 0, 5], [0, 0, -2], 10, hit)) {
  console.log(hit.distance);       // 4.5
  console.log([...hit.point]);     // [0, 0, 0.5]
  console.log([...hit.normal]);    // [0, 0, 1]
}

The optional filter is the same body callback as raycast's and may itself run raycast, raycastInto or raycastBatch without corrupting the outer result.

Use raycastBatch for a sweep of many rays with a group/mask filter.

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.

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 },
  ],
};

Joints that break, limits that tell

A joint can carry a limit to what it holds, each finite and positive, at every scale:

After each step's solve, a joint whose load, as the mean over that step, was more than a threshold breaks: it leaves the world, its objects move freely from the next step (and collide with each other, as they did not while joined), and physics.events.onJointBreak tells it once, with the objects' ids, the joint's jointId and jointIndex, and which threshold it passed.

A broken joint stays broken. The scene does not make it again by itself; it is made again where every joint is: when one of its objects is removed and spawned again under its id (all that object's joints are made again), and when its stage is shown again. A hinge's handle says it with scene.physics.hinge(id).broken, and reads 0 with made false meanwhile. Scene JSON's joints and a robot file's take the same two fields.

const stage: StageSpec = {
  items: [
    { id: "lamp", source: sphere(), material: materials.glass, transform: { position: [0.7, 0.3, 0], scale: 0.12 }, body: { shape: "sphere", mass: 2 } },
  ],
  joints: [
    // The lamp's cord: a 2 kg lamp weighs 19.6 N; pulled with more than 30 N, the cord breaks.
    { id: "cord", type: "distance", a: "lamp", anchorA: [0.7, 0.42, 0], anchorB: [0.7, 0.9, 0], breakForce: 30 },
  ],
};
const physics: ScenePhysicsOptions = {
  events: {
    onJointBreak: (e) => console.log(`${e.jointId} let go of ${e.a}: ${(e.impulse * 60).toFixed(0)} N`),   // "cord let go of lamp: ..."
  },
};

The same on a world of its own, where the events module is installed by hand and joint.broken says what happened to a joint (false for one removed with remove() or with one of its bodies):

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

const world = createPhysicsWorld();                 // a unit is a metre, gravity 9.81 m/s² down
const events = world.use(physicsEvents());
events.onJointLimit = (e) => console.log(`the gate is on its ${e.which} stop`);
events.onJointBreak = (e) => console.log(`the cord broke: ${(e.impulse * 60).toFixed(0)} N (${e.which})`);

// A 2 kg lamp on a cord that carries 30 N (its weight is 19.6 N), and a gate between two stops.
const lamp = world.addBody({ shape: { type: "sphere", radius: 0.1 }, mass: 2, position: [0, 1, 0] });
const cord = world.addJoint({ type: "distance", a: lamp, b: null, anchorA: [0, 1, 0], anchorB: [0, 1.5, 0], breakForce: 30 });
const gate = world.addBody({ shape: { type: "box", halfExtents: [0.25, 0.05, 0.05] }, mass: 1, position: [1.25, 1, 0] });
world.addJoint({ type: "hinge", a: gate, b: null, anchor: [1, 1, 0], axis: [0, 0, 1], limits: [-0.5, 0.5] });

for (let i = 0; i < 60; i++) world.step(1 / 60);    // "the gate is on its lower stop", once
console.log(cord.broken, world.joints.length);      // false 2: the cord holds the lamp
lamp.applyImpulse([0, -2, 0]);                      // a tug: 2 N·s taken within one step is 120 N more
world.step(1 / 60);                                 // "the cord broke: 140 N (force)"
console.log(cord.broken, world.joints.length);      // true 1: the lamp falls, the gate's hinge stays

Choose a threshold with a margin. By default joints are soft: a load put on at once swings past its resting value before it settles (a weight let go on a level arm loads its joint by about 1.4 times what it weighs there, for a few steps), and a body that lands on a hinge's limit loads it far more than one resting on it. With jointSolver: "chain" a hinge carries exactly the static load from the first step. A world that is restored from a snapshot has its thresholds and its limits' state back: a joint resting on its limit tells no second arrival, and a joint breaks at the same step again.

Hinges under load

By default each joint is solved on its own, softly, and a hinge whose load hangs off its axis (a wheel beside its arm) twists: on an eight-hinge robot of 1.8 kg turning in place, about 3° off axis with the pins 2.3 mm apart. Two options change how hinges are solved:

Both are for the whole scene, given to every stage's world, read once when the scene is made, and a value that is not one throws from createScene; createPhysicsWorld takes the same two options, and Scene JSON has them as physics.jointSolver and physics.jointHertz. Without them nothing changes: a scene is solved as before, bit for bit. Ball, weld, slider and distance joints are solved as before in either case.

The options, the measurements and a hinge's commands (scene.physics.hinge(id): motor, position drive, friction, damping, and its angle, speed, torque and work) are in Commanding a hinge.

Puppets

A puppet is a figure of rigid parts: one body per bone and a joint from each bone to its parent, made in a world by the puppets module. While it is animated it stands in its pose: its parts are kinematic bodies, which push what they meet and are pushed by nothing. As a ragdoll its parts are dynamic bodies held by their joints. It turns ragdoll when it is told to, or bone by bone when it is hit hard enough. The module is in the physics entry point and works on a world of its own (createPhysicsWorld), as below; a scene makes the puppets its stages declare and draws them in every mode: Puppets in a scene.

import { createPhysicsWorld, physicsEvents, physicsPuppets, humanoid, EV_CONTACT, EV_IMPACT } from "mote-engine/physics";

const world = createPhysicsWorld();                  // a unit is a metre, gravity 9.81 m/s² down
const events = world.use(physicsEvents());           // before the puppets, to have its callbacks: they read its impacts
const puppets = world.use(physicsPuppets());
world.addBody({ type: "static", shape: { type: "plane", normal: [0, 1, 0], offset: 0 } });

// A mannequin of 15 parts, 1.75 m and 70 kg, standing at the origin and facing +z: animated.
const puppet = puppets.add(humanoid("mannequin", { height: 1.75, mass: 70 }), { position: [0, 0, 0] });
// A hit of 2 N·s or more turns limp the bone it lands on, the bones one joint away, and what hangs from them.
puppet.limpOnImpact = { impulse: 2, spread: 1 };
events.onImpact = () => console.log(puppet.bones.filter((b) => b.body.type === "dynamic").map((b) => b.name).join(" "));

// A 2 kg ball thrown at its left forearm.
const [forearm] = puppet.bones.filter((b) => b.name === "forearm.L");
const arm = forearm.body.position;
world.addBody({ shape: { type: "sphere", radius: 0.06 }, mass: 2, position: [arm[0], arm[1], arm[2] + 1], velocity: [0, 0.8, -6], events: EV_CONTACT | EV_IMPACT });
for (let i = 0; i < 20; i++) world.step(1 / 60);     // "upperArm.L forearm.L hand.L": the arm hangs limp from the shoulder
console.log(puppet.mode);                            // "animated": the rest of the figure stands

events.onImpact = null;
puppet.goLimp();                                     // all of it: a ragdoll, which falls
for (let i = 0; i < 240; i++) world.step(1 / 60);
const pose = new Float32Array(puppet.bones.length * 4 + 3);
puppet.readPose(pose);                               // each bone's turn from its rest pose, then where the pelvis is
console.log(puppet.mode, pose[puppet.bones.length * 4 + 1] < 0.5);   // "ragdoll true": the pelvis is on the floor
puppet.remove();                                     // its bodies and joints leave the world
console.log(world.bodies.length);                    // 2: the floor and the ball

The figure is a PuppetSpec: a list of bones, the root first and every parent before its children. A bone has a name, its parent's name, and where it lies in the rest pose, from its head (where it meets its parent: the joint is there) to its tail, in the puppet's own space and in world units. Its part is a capsule from head to tail by default (radius, 0.2 × its length unless given), or shape: "box", "sphere", or any shape a dynamic body takes, in the bone's own frame: its centre midway along the bone, y from head to tail, x the bone's roll (xAxis; by default the hinge's axis, or the puppet's x). joint says how it hangs from its parent:

joint
{ type: "hinge", axis, limits: [lower, upper] } turns about axis (a direction in the rest pose) only, between the two angles, in radians from the rest pose: lower ≤ 0 ≤ upper, each within ±π
{ type: "ball" } turns freely about the head, without limits: the default
{ type: "fixed" } held to its parent as it is in the rest pose
{ type: "free" } the same as "ball"

Masses:

selfCollide (true by default) makes the parts that are not joined to each other collide (an arm against the chest); joined parts never do, and with every other body, another puppet's parts included, they collide as any body does: a puppet uses none of the 16 collision groups.

The whole spec is checked before one body is made. These all throw (naming the bone) and leave the world as it was:

humanoid(kind, { height, mass }) gives the spec of a standing figure, its feet on y = 0, facing +z, its left side (the bones named ….L) at +x: "mannequin" (the default) has 15 parts, "dummy" 11 (the hands are part of the forearms and the feet of the shins). height is in world units (1.75), mass in kilograms (70), shared out as the segments of a human body. Elbows (0° to 140°), knees (0° to 120°), ankles (−35° to +15°), wrists (±60°), the neck (±35°) and the waist (±30°) are hinges with those limits; shoulders and hips are balls without limits, and it is the parts' collisions with each other that keep an arm out of the chest.

puppets.add(spec, { position, rotation, mode }) puts the figure's rest pose in the world there (mode is "animated" unless given) and returns a Puppet; puppets.list has those in the world.

Puppet
bones per bone, in the spec's order: name, index, the body and the joint to its parent (the world's own handles; null for the root's joint)
mode "animated", or "ragdoll" once no bone is animated any more
moveTo(position, rotation?) where the figure is to stand at the end of the next step: its animated parts go there with the velocities that take them, as Body.moveTo, and push what is in the way. Call it at every step to walk the figure
setMode("ragdoll"), goLimp() every part turns dynamic where it is. It keeps the velocity it had and the contacts it had: no contact ends or begins and nothing is an impact because of the change
limpOnImpact { impulse, spread?, all? } or null: an impact of at least impulse N·s on a part, from a body that is not another part of the same puppet, turns limp the bone it hit, the bones within spread joints of it (0 by default) and, however far, everything that hangs from a limp bone: a part still animated is a kinematic body, which nothing moves, and under a limp parent it would hold that parent up in the air. So a hit on a thigh takes the shin and the foot with it, and one that reaches the root takes the whole figure. With all, the whole puppet at any hit. It happens before the events module's callbacks, so onImpact already sees the bones limp. Assign a new object to change it
readPose(out) the pose now, allocating nothing: per bone its rotation from its rest pose, in its parent's frame (x, y, z, w; all [0, 0, 0, 1] in the rest pose), then the root's head in the puppet's frame: 4 × bones + 3 numbers, into a Float32Array or a Float64Array
remove() takes its bodies and joints out of the world

The impacts are the events module's: its thresholds and its maxPerStep choose them, and the module is installed with the puppets when the world does not have it yet (install physicsEvents() first to keep its handle and its options). Removing one of a puppet's bodies by hand removes the whole puppet; removing one of its joints lets that bone, and what hangs from it, go limp. A step with puppets allocates nothing.

What is not there yet:

Puppets in a scene

A stage declares its puppets in puppets, and the scene (with physics) makes each one in the stage's world and draws it as objects of the stage, one per part, in ASCII, Ray and Wireframe alike: physics writes the parts' transforms as it writes every body's, between the steps, so nothing jumps at 120 Hz. scene.puppet(id) is the puppet itself, the Puppet of the section above, in scene units.

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

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const scene = createScene(canvas, {
  mode: "ray",                                        // or "ascii", "wireframe": the same simulation
  physics: {
    scale: 1.25,                                      // metres to a scene unit: the mannequin, 1.75 m, is 1.4 units tall
    floor: -0.8,
    events: { onImpact: (e) => console.log(e.a, e.b) },   // the parts by their objects' ids
  },
  stages: [{
    items: [],
    puppets: [{
      id: "actor",
      spec: "mannequin",                              // or "dummy", or a PuppetSpec of your own, in scene units
      position: [0, -0.8, 0],                         // its feet on the floor
      rotation: [0, 20, 0],                           // degrees, as an object's
      material: { head: materials.gold },             // one material for every part, or by the bones' names
      limpOnImpact: { impulse: 5 },                   // a hit of 5 N·s turns limp the bone it lands on and what hangs from it
    }],
  }],
});
console.log(scene.puppet("actor"));                   // undefined: the physics is still loading
await scene.ready;                                    // loaded: the parts are objects of the stage now
const puppet = scene.puppet("actor")!;
console.log(puppet.bones.length, scene.items().length, scene.item("actor.head")!.transform.position[1].toFixed(2));   // 15 15 0.47

// A 2 kg ball thrown at its left forearm: "actor.forearm.L ball" (onImpact).
const arm = scene.item("actor.forearm.L")!.transform.position;
await scene.spawn({
  id: "ball", source: sphere(), material: materials.rubber("#e5484d"), instant: true,
  transform: { position: [arm[0], arm[1], arm[2] + 0.8], scale: 0.07 },
  body: { shape: "sphere", mass: 2, velocity: [0, 0.5, -6] },
});
await wait(500);
console.log(puppet.mode, puppet.bones.filter((b) => b.body.type === "dynamic").map((b) => b.name).join(" "));   // animated forearm.L hand.L

puppet.goLimp();                                      // the whole figure: a ragdoll, which falls
await wait(3000);
console.log(puppet.mode, scene.item("actor.head")!.transform.position[1] < 0);   // ragdoll true: its head is down

scene.remove("actor.head");                           // one part taken out takes the whole puppet with it
console.log(scene.puppet("actor"), scene.items().map((item) => item.id).join(" "));   // undefined ball
StageSpec.puppets[]
id its name for scene.puppet(id). Its parts are the objects "<id>.<bone>" ("actor.head", "actor.forearm.L"), and every id that begins with "<id>." is the puppet's: no object and no other puppet of the scene may have one
spec "mannequin" (15 parts) or "dummy" (11), a person 1.75 m tall and 70 kg at the scene's scale (1.75 / physics.scale units tall); or a PuppetSpec of your own, its lengths in scene units, as the bodies' shapes are
position, rotation where the figure's frame is and how it is turned, as an object's transform: scene units, and Euler degrees [x, y, z] or a quaternion. A preset stands on that point, facing +z, the viewer
material Ray's material for every part, or a map from bones' names to their parts' materials; the parts not named keep the scene's own colour
mode "animated" (the default) or "ragdoll", limp from the start
limpOnImpact what a hit does while it is animated: the puppet's limpOnImpact, set each time its stage is shown

The parts are ordinary objects: they are listed by scene.items(), each has a handle (scene.item("actor.head"): its material, its visible, its transform to read), a pixel's ray finds them (scene.physics.raycast gives the part's id), and a limp part can be grabbed and thrown with the pointer as any dynamic body (an animated one cannot: a press on it is a click). Their transforms are physics': each is drawn where its body is, and a transform set on one by hand does not last. They have no body handle of their own (item.body is undefined): the puppet is the handle of them all, and puppet.bones[i].body is each part's body in the stage's world. Another object can hang from one (parent: "actor.hand.L") and is carried with it. Each part is drawn with the mesh of its collision shape, a capsule along its bone by default (capsuleMesh), a box or a sphere; parts of the same size share one mesh source (a figure's left and right limbs, two puppets of one preset).

Events and hits. The scene's events name a part by its object's id (e.a, e.b, and onContact's), so a callback tells an arm from a head; a body of the scene thrown at an animated puppet turns limp what limpOnImpact says, as in a world. The events module is installed in a stage's world when the stage has puppets, with the scene's physics.events options.

Its life. The parts' objects are made when the physics has loaded, which scene.ready waits for: before that scene.puppet(id) is undefined. A stage's puppets are made in its world when the stage is shown; shown again (another stage in between, or setStages), the stage makes them again, standing where it puts them: a ragdoll does not get up, a new puppet stands in its place, and scene.puppet(id) is then a new handle. scene.remove("<id>.<bone>") takes the whole puppet out of the scene, and so does puppet.remove() (its objects go after the frame). scene.destroy() clears everything. Puppets add nothing to what a frame allocates.

What is checked. When the scene is made and at setStages, before anything changes: puppets without physics, a puppet without an id or with another puppet's (in any stage), an object or another puppet whose id is a puppet's or begins with its "<id>." (a bone's name may have a . in it, so "a" and "a.b" could both have a part "a.b.root": the second is refused), a spec that is neither a preset nor a PuppetSpec, a mode that is not one of the two ("powered" is not available yet), a position, rotation or limpOnImpact of the wrong shape: each is a TypeError naming the stage and the puppet. An object without an id is named by the scene ("item-0", "item-1"…) with an id that is no puppet's. What only the puppets module can tell of a custom spec (a bone of no length, a missing parent) throws at setStages once the physics is there, and nothing changes. In a scene just made, where the physics is still loading, every spec of every stage is checked when it has loaded, before one part is made: if one is refused, scene.ready rejects with that error and none of the scene's puppets is made, the valid ones neither (no part, no handle, no body; the stages keep the objects they were built with, and setStages with valid puppets makes them). scene.spawn refuses an id that is a puppet's or one of its parts'.

Not there yet, beyond the puppets' own limits (no cone or twist limits, no "powered" mode, no clips, and a mannequin's hands and feet that a hard landing pushes past their limits for a few steps):

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:

Motors and sensors (components)

A motor or a sensor is a record of data (its model, where its values come from, its parameters in SI units), never code: the engine holds no component's data, and a new sensor of a kind it already models is one more record. Three parts, all in mote-engine/components, an entry point of its own that only a page using components loads:

The engine's own families are four sensors, imuSensor, encoderSensor, lidar2dSensor and tofZoneSensor, and one motor, dcServoMotor (below). From a record's JSON to an IMU read at every step:

import { createPhysicsWorld } from "mote-engine/physics";
import { components, createComponentCatalog, encoderSensor, imuSensor, jsonComponentSource } from "mote-engine/components";

// The records are data: here a JSON text, as a file read by the application would be.
const text = JSON.stringify({
  format: 1,
  components: [{
    format: 1, id: "acme-imu6", type: "sensor", family: "imu", model: "Acme IMU-6", version: 1,
    source: { kind: "datasheet", ref: "https://acme.example/imu6.pdf" },
    params: { rate: 100, accelNoise: 0.02, accelBias: 0.05, accelRange: 78.5, gyroNoise: 0.002, gyroBias: 0.01, gyroRange: 34.9 },
  }],
});

const world = createPhysicsWorld();
const comps = world.use(components());           // once per world: keep the handle
comps.registerSensorModel("imu", imuSensor);     // the families the records name
comps.registerSensorModel("encoder", encoderSensor);

const json = jsonComponentSource(text);          // { ok, source } or { ok: false, errors }
if (!json.ok) throw new Error(json.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const catalog = createComponentCatalog(json.source, { families: comps.families });
const found = await catalog.get("acme-imu6");    // checked by its family: { ok, component } or the errors
if (!found.ok) throw new Error(found.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));

world.addBody({ type: "static", shape: { type: "plane", normal: [0, 1, 0], offset: 0 } });
const chassis = world.addBody({ shape: { type: "box", halfExtents: [0.1, 0.03, 0.06] }, position: [0, 0.03, 0], mass: 1 });
// On the chassis, 2 cm above its origin, with the body's axes; the seed is this unit's noise.
const imu = comps.attachSensor(chassis, { position: [0, 0.02, 0] }, found.component, { seed: 42 });

const reading = new Float64Array(imu.size);      // [ax, ay, az, gx, gy, gz]
for (let i = 0; i < 120; i++) {
  world.step(1 / 60);
  if (imu.read(reading)) {
    // reading is of the instant imu.time; at rest reading[1] is the 9.81 m/s² the floor pushes with
  }
}
console.log(imu.count, imu.time, reading[1]);    // 120 readings, the last at 2 s, about 9.81

A sensor's handle (what attachSensor returns for these families): read(out, at?) copies the current reading into a Float64Array or Float32Array of the application's, from an optional index, and returns false, writing NaN, before the first reading; time is the world's time the reading is of, count how many readings there have been (it grows when a new one is current), size how many numbers a reading is; rate and latency are the ones in use; detach() takes the sensor off, and attached tells. NaN in a reading is no measure.

What every sensor does. It reads at its own rate: at the instants t0 + k / rate from the moment it is attached, each taken at the end of the first step that reaches it (a sensor faster than the steps reads once a step). A reading taken at t is the current one from the first step that ends at t + latency. Its noise comes from a generator of its own, seeded by the attachment: the same seed gives the same readings in every run, another seed another sequence, and no other sensor's draws change it. The attachment's options are what depends on how the sensor is mounted and run, not on the component: rate and latency (replacing the record's) and seed (a whole number from 0 to 4294967295, default 0; give each sensor its own). A step allocates nothing with sensors working, nor does read; the sensors' state (generator, readings on their way) is saved and restored with world.snapshot() and world.restore(), so a restored run continues bit for bit.

Family Attached to Parameter Unit
imu a body, at a pose rate (required) Hz readings a second
latency s default 0
accelNoise, gyroNoise m/s², rad/s standard deviation of one reading, per axis; default 0
accelBias, gyroBias m/s², rad/s standard deviation of a unit's constant offset: each sensor draws its own, once, from its seed; default 0
accelRange, gyroRange m/s², rad/s readings are held within ± the range; default none
encoder a hinge (pose null) resolution (required) rad the encoder's step: 2π over its counts a turn
rate (required) Hz readings a second
latency s default 0
lidar-2d a body, at a pose scanRate (required) Hz sweeps a second
angularResolution (required) rad the nearest whole ray count to 2π over this
maxRange (required), minRange m outside these, no measure; minimum default 0
rangeNoise m standard deviation of one ray; default 0
dropout 1 probability of a lost point; default 0
latency s default 0
mass, size kg, m optional component data; size is three numbers
tof-zone a body, at a pose zones (required) 1 [columns, rows], whole numbers
fieldOfView (required) rad [horizontal, vertical]
maxRange (required), minRange m outside these, no measure; minimum default 0
frameRate Hz frames a second, or the attachment's rate
latency s default 0

LiDAR and zoned ToF

import { createPhysicsWorld } from "mote-engine/physics";
import { components, lidar2dSensor, tofZoneSensor } from "mote-engine/components";

const lidarRecord = {
  format: 1, id: "acme-lidar", type: "sensor", family: "lidar-2d", model: "Acme 360 LiDAR", version: 1,
  source: { kind: "datasheet", ref: "https://acme.example/lidar.pdf" },
  params: { scanRate: 10, angularResolution: Math.PI / 180, maxRange: 8 },
};
const tofRecord = {
  format: 1, id: "acme-tof", type: "sensor", family: "tof-zone", model: "Acme zoned ToF", version: 1,
  source: { kind: "datasheet", ref: "https://acme.example/tof.pdf" },
  params: { zones: [2, 1], fieldOfView: [Math.PI / 2, Math.PI / 4], maxRange: 4, frameRate: 60 },
};
const world = createPhysicsWorld({ gravity: [0, 0, 0] });
const comps = world.use(components());
comps.registerSensorModel("lidar-2d", lidar2dSensor);
comps.registerSensorModel("tof-zone", tofZoneSensor);
const chassis = world.addBody({ type: "static", group: 2, mask: 1, shape: { type: "box", halfExtents: [0.1, 0.05, 0.1] } });
world.addBody({ type: "static", group: 1, shape: { type: "box", halfExtents: [0.1, 1, 1] }, position: [2, 0, 0] });
const lidar = comps.attachSensor(chassis, { position: [0, 0.05, 0] }, lidarRecord, { group: 2, mask: 1, blindSector: Math.PI / 18 });
const tof = comps.attachSensor(chassis, null, tofRecord, { group: 2, mask: 1 });
const scan = new Float32Array(lidar.size), zones = new Float32Array(tof.size);
for (let i = 0; i < 6; i++) world.step(1 / 60);
lidar.read(scan);       // 360 distances in metres, NaN where there is no measure
tof.read(zones);        // two distances, row by row
console.log(lidar.size, tof.size, scan[190], zones[0]);

A sensor of another kind is a family of the application's, registered the same way and made with the same mechanism: createSensor(ctx, { size, rate, sample }) gives it the rate, the latency, the seeded noise, the buffer and the snapshot, and the family writes only what it measures. sensorOptions(ctx, own) checks and copies an attachment's options for such a family: rate, latency and seed, which it checks, and the names in own, which are the family's to check (any other name is a TypeError naming the family). docs/embed/components.md has the catalog, the sources, and how to write a family.

A servo on a hinge (dc-servo)

dcServoMotor is the family of a geared DC servo: attachMotor(hinge, record, options) puts one on a hinge of a world made with jointSolver: "chain", and the hinge's motor, drive, friction and damping are the servo's from then on. The servo's numbers are the record's: two servos are two records, and the same code moves both.

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

// Two servos as data: an arm's, commanded in position, and a wheel's, in velocity.
const armServo = {
  format: 1, id: "acme-s30", type: "motor", family: "dc-servo", model: "Acme S-30 bus servo", version: 1,
  source: { kind: "datasheet", ref: "https://acme.example/s30.pdf" },
  params: { nominalVoltage: 12, voltageRange: [6, 12.6], stallTorque: 2.94, noLoadSpeed: 4.7, stallCurrent: 2.7, noLoadCurrent: 0.2, commands: ["position"] },
};
const wheelServo = {
  format: 1, id: "acme-s20-hs", type: "motor", family: "dc-servo", model: "Acme S-20 HS bus servo", version: 1,
  source: { kind: "datasheet", ref: "https://acme.example/s20hs.pdf" },
  params: { nominalVoltage: 12, stallTorque: 1.96, noLoadSpeed: 11.1, stallCurrent: 2.4, noLoadCurrent: 0.2, commands: ["velocity"] },
};

const world = createPhysicsWorld({ jointSolver: "chain" });   // the servo's rows are the chain solver's
const comps = world.use(components());
comps.registerMotorModel("dc-servo", dcServoMotor);

// An arm on a post, and a wheel at its end.
const arm = world.addBody({ shape: { type: "box", halfExtents: [0.1, 0.01, 0.01] }, position: [0.1, 0, 0], mass: 0.1 });
const wheel = world.addBody({ shape: { type: "sphere", radius: 0.03 }, position: [0.2, 0, 0], mass: 0.1 });
const shoulder = world.addJoint({ type: "hinge", a: arm, b: null, anchor: [0, 0, 0], axis: [0, 0, 1] });
const axle = world.addJoint({ type: "hinge", a: wheel, b: arm, anchor: [0.2, 0, 0], axis: [0, 0, 1] });

const armMotor = comps.attachMotor(shoulder, armServo, { voltage: 11.1 });   // the battery's voltage: the attachment's
const wheelMotor = comps.attachMotor(axle, wheelServo);
armMotor.setPosition(0.5);      // rad, the hinge's angle
wheelMotor.setVelocity(6);      // rad/s
// wheelMotor.setPosition(1) would throw: the record lists "velocity" only.

const reading = new Float64Array(8);
for (let i = 0; i < 120; i++) world.step(1 / 60);
armMotor.read(reading, 0);      // [angle (rad), speed (rad/s), torque (N·m), current (A)]
wheelMotor.read(reading, 4);
console.log(reading[0].toFixed(3), reading[2].toFixed(3), reading[5].toFixed(3), reading[7].toFixed(2));

A whole robot: motors and sensors together

Motors and sensors of every family share one module, one step and one snapshot. A cart on four wheels, built from a catalog: a servo and an encoder on each wheel's hinge, an IMU and a LiDAR on the chassis; driven for two seconds, and its second second run again from a snapshot.

import { createPhysicsWorld } from "mote-engine/physics";
import { components, createComponentCatalog, dcServoMotor, encoderSensor, imuSensor, jsonComponentSource, lidar2dSensor } from "mote-engine/components";

// The robot's parts as data: one document, as a file the application reads would be.
const text = JSON.stringify({
  format: 1,
  components: [
    { format: 1, id: "acme-s20-hs", type: "motor", family: "dc-servo", model: "Acme S-20 HS bus servo", version: 1,
      source: { kind: "datasheet", ref: "https://acme.example/s20hs.pdf" },
      params: { nominalVoltage: 12, voltageRange: [6, 12.6], stallTorque: 1.96, noLoadSpeed: 11.1, stallCurrent: 2.4, noLoadCurrent: 0.2, commands: ["velocity"] } },
    { format: 1, id: "acme-enc12", type: "sensor", family: "encoder", model: "Acme 12-bit magnetic encoder", version: 1,
      source: { kind: "datasheet", ref: "https://acme.example/enc12.pdf" },
      params: { resolution: (2 * Math.PI) / 4096, rate: 50 } },
    { format: 1, id: "acme-imu6", type: "sensor", family: "imu", model: "Acme IMU-6", version: 1,
      source: { kind: "datasheet", ref: "https://acme.example/imu6.pdf" },
      params: { rate: 100, latency: 0.005, accelNoise: 0.02, accelBias: 0.05, gyroNoise: 0.002, gyroBias: 0.01 } },
    { format: 1, id: "acme-lidar", type: "sensor", family: "lidar-2d", model: "Acme 360 LiDAR", version: 1,
      source: { kind: "datasheet", ref: "https://acme.example/lidar.pdf" },
      params: { scanRate: 10, angularResolution: Math.PI / 180, maxRange: 8, rangeNoise: 0.01, latency: 0.02 } },
  ],
});

const world = createPhysicsWorld({ jointSolver: "chain" });   // a dc-servo's rows are the chain solver's
const comps = world.use(components());
comps.registerMotorModel("dc-servo", dcServoMotor);           // the families the records name
comps.registerSensorModel("encoder", encoderSensor);
comps.registerSensorModel("imu", imuSensor);
comps.registerSensorModel("lidar-2d", lidar2dSensor);

const json = jsonComponentSource(text);
if (!json.ok) throw new Error(json.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const catalog = createComponentCatalog(json.source, { families: comps.families });
const part = async (id) => {
  const found = await catalog.get(id);                        // checked by its family
  if (!found.ok) throw new Error(found.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
  return found.component;
};
const [servo, encoder, imuPart, lidarPart] = await Promise.all(["acme-s20-hs", "acme-enc12", "acme-imu6", "acme-lidar"].map(part));

// A floor, a wall 2 m ahead (+X) and a cart: a chassis on four wheels, each on a hinge about Z.
// The robot's bodies are in group 2 and meet the surroundings (group 1) only, not each other.
const ROBOT = 2, AROUND = 1;
world.addBody({ type: "static", group: AROUND, shape: { type: "plane", normal: [0, 1, 0], offset: 0 }, friction: 0.8 });
world.addBody({ type: "static", group: AROUND, shape: { type: "box", halfExtents: [0.05, 0.5, 1] }, position: [2, 0.5, 0] });
const chassis = world.addBody({ group: ROBOT, mask: AROUND, shape: { type: "box", halfExtents: [0.1, 0.02, 0.05] }, position: [0, 0.04, 0], mass: 1, canSleep: false });
const onZ = [Math.SQRT1_2, 0, 0, Math.SQRT1_2];               // a cylinder's axis is its Y: turned onto Z
const hinges = [[0.07, -0.07], [0.07, 0.07], [-0.07, -0.07], [-0.07, 0.07]].map(([x, z]) => {
  const wheel = world.addBody({ group: ROBOT, mask: AROUND, shape: { type: "cylinder", radius: 0.03, halfHeight: 0.01 }, position: [x, 0.03, z], rotation: onZ, mass: 0.1, friction: 0.9, canSleep: false });
  return world.addJoint({ type: "hinge", a: wheel, b: chassis, anchor: [x, 0.03, z], axis: [0, 0, 1] });
});

// Motors on the hinges, sensors on the hinges and on the chassis. What depends on the mounting is the
// attachment's: the battery's voltage, a sensor's pose and seed, the rays' collision group and mask.
const motors = hinges.map((hinge) => comps.attachMotor(hinge, servo, { voltage: 11.1 }));
const encoders = hinges.map((hinge) => comps.attachSensor(hinge, null, encoder));
const imu = comps.attachSensor(chassis, { position: [0, 0.02, 0] }, imuPart, { seed: 1 });
const lidar = comps.attachSensor(chassis, { position: [0, 0.05, 0] }, lidarPart, { group: ROBOT, mask: AROUND, seed: 2 });
for (const motor of motors) motor.setVelocity(0);

// The controller's buffers, made once: commanding, stepping and reading allocate nothing.
const command = new Float64Array(1), servoNow = new Float64Array(4), wheelNow = new Float64Array(2);
const inertial = new Float64Array(imu.size), scan = new Float32Array(lidar.size), up = new Float64Array(1);
const step = (i) => {
  command[0] = -Math.min(5, 0.1 * i);                         // rad/s about Z: the wheels roll toward +X, up to 0.15 m/s
  for (const motor of motors) motor.write(command);
  world.step(1 / 60);
  if (imu.read(inertial)) up[0] += inertial[1] / 60;          // [ax, ay, az, gx, gy, gz]: the mean of ay over a second
};
// One second of steps from step `from`, and what the robot reads at its end.
const second = (from) => {
  up[0] = 0;
  for (let i = from; i < from + 60; i++) step(i);
  motors[0].read(servoNow);                                   // [angle, speed, torque, current]
  encoders[0].read(wheelNow);                                 // [angle, speed]
  lidar.read(scan);                                           // 360 distances; ray 180 looks ahead
  return [servoNow[1], servoNow[3], wheelNow[1], up[0], scan[180]].map((n) => n.toFixed(4)).join(" ");
};

second(0);
const saved = world.snapshot();     // with every motor's command, every sensor's noise and its readings on their way
const first = second(60);
world.restore(saved);               // the same world, one second back
const again = second(60);
console.log(first === again, first);  // true: wheel speed -5 rad/s, about 0.24 A, the encoder's -5, 9.81 m/s² up, the wall 1.7 m ahead

A robot from a file

A robot can be written once, as data, and built from it: its bodies and their shapes, its joints, and the motors and sensors on them, each cited by the id of its record in a catalog. validateRobotFile(json) checks a description; loadRobot(world, json, catalog, options) checks it, asks the catalog for the records it cites, and makes the robot in a physics world.

import { createPhysicsWorld } from "mote-engine/physics";
import { components, createComponentCatalog, dcServoMotor, encoderSensor, imuSensor, jsonComponentSource, loadRobot } from "mote-engine/components";

// Two documents, as the files the application reads would be: the parts, and the robot that cites them.
const parts = JSON.stringify({
  format: 1,
  components: [
    { format: 1, id: "acme-s30", type: "motor", family: "dc-servo", model: "Acme S-30 bus servo", version: 1,
      source: { kind: "datasheet", ref: "https://acme.example/s30.pdf" },
      params: { nominalVoltage: 12, voltageRange: [6, 12.6], stallTorque: 2.94, noLoadSpeed: 4.7, commands: ["position"] } },
    { format: 1, id: "acme-enc12", type: "sensor", family: "encoder", model: "Acme 12-bit magnetic encoder", version: 1,
      source: { kind: "datasheet", ref: "https://acme.example/enc12.pdf" },
      params: { resolution: (2 * Math.PI) / 4096, rate: 50 } },
    { format: 1, id: "acme-imu6", type: "sensor", family: "imu", model: "Acme IMU-6", version: 1,
      source: { kind: "datasheet", ref: "https://acme.example/imu6.pdf" },
      params: { rate: 100, accelNoise: 0.02, gyroNoise: 0.002 } },
  ],
});
const arm = JSON.stringify({
  format: 1,
  bodies: [
    { id: "base", type: "static", shape: { type: "box", halfExtents: [0.1, 0.02, 0.1] }, position: [0, 0.02, 0] },
    { id: "arm", mass: 0.1, canSleep: false, position: [0.1, 0.1, 0],
      shape: { type: "compound", children: [
        { shape: { type: "box", halfExtents: [0.1, 0.01, 0.01] } },
        { shape: { type: "sphere", radius: 0.02 }, position: [0.1, 0, 0] },
      ] } },
  ],
  joints: [{ id: "shoulder", type: "hinge", a: "arm", b: "base", anchor: [0, 0.1, 0], axis: [0, 0, 1], limits: [-1.5, 1.5] }],
  motors: [{ id: "servo", joint: "shoulder", component: { id: "acme-s30" }, options: { voltage: 11.1 } }],
  sensors: [
    { id: "turned", joint: "shoulder", component: { id: "acme-enc12" } },
    { id: "imu", body: "arm", pose: { position: [0.05, 0, 0] }, component: { id: "acme-imu6" }, options: { seed: 3 } },
  ],
});

const world = createPhysicsWorld({ jointSolver: "chain" });   // a dc-servo's rows are the chain solver's
const comps = world.use(components());
comps.registerMotorModel("dc-servo", dcServoMotor);           // the families the records name
comps.registerSensorModel("encoder", encoderSensor);
comps.registerSensorModel("imu", imuSensor);
const source = jsonComponentSource(parts);
if (!source.ok) throw new Error(source.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const catalog = createComponentCatalog(source.source, { families: comps.families });

// The robot, half a metre along +Z: its handles by the ids of the file.
const loaded = await loadRobot(world, arm, catalog, { components: comps, position: [0, 0, 0.5] });
if (!loaded.ok) throw new Error(loaded.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const robot = loaded.robot;
robot.motor("servo").setPosition(0.5);                        // rad: the shoulder, to half a radian
for (let i = 0; i < 120; i++) world.step(1 / 60);
const turned = new Float64Array(2);
robot.sensor("turned").read(turned);                          // [angle, speed] of the hinge, as the encoder counts them

// A description that cites a record the catalog does not have is refused, and nothing of it is made.
const other = JSON.parse(arm);
other.motors[0].component.id = "acme-s31";
const refused = await loadRobot(world, other, catalog, { components: comps });
console.log(turned[0].toFixed(2), robot.bodies.get("arm").position[2], world.bodies.length, refused.ok ? "loaded" : refused.errors[0].path);
// 0.50 0.5 2 /motors/0/component/id

Limits, for now: a description holds no mesh and no plane (the shapes of a place, static), and a compound's children are solids, not compounds; a motor, and a sensor on a joint, go on a hinge; lengths are in the world's units, as addBody takes them. The robot's controller is the application's: a file describes what the robot is, not what it does. A robot taken out again while it was being made has used the world's body ids and fired its removal events. docs/embed/components.md has every field.

A robot in a scene

The same file goes in a scene with physics: loadRobotInScene(scene, json, catalog, options) makes each body an object of the stage on screen with that body, each joint a joint of the stage, and puts the motors and the sensors on them; it resolves to a SceneRobot (objects, joints, hinge(id), motor(id), sensor(id), made, generation, remove()) inside { ok, robot }. The robot is then the scene's: drawn in every mode, grabbed and thrown, pushed by the effects, with its hinges under scene.physics.hinge(id).

import { createScene } from "mote-engine";
import { components, createComponentCatalog, createComponentRegistry, dcServoMotor, encoderSensor, imuSensor, jsonComponentSource, loadRobotInScene } from "mote-engine/components";

// The same two documents as above: the parts, and the robot that cites them.
const parts = JSON.stringify({
  format: 1,
  components: [
    { format: 1, id: "acme-s30", type: "motor", family: "dc-servo", model: "Acme S-30 bus servo", version: 1,
      source: { kind: "datasheet", ref: "https://acme.example/s30.pdf" },
      params: { nominalVoltage: 12, voltageRange: [6, 12.6], stallTorque: 2.94, noLoadSpeed: 4.7, commands: ["position"] } },
    { format: 1, id: "acme-enc12", type: "sensor", family: "encoder", model: "Acme 12-bit magnetic encoder", version: 1,
      source: { kind: "datasheet", ref: "https://acme.example/enc12.pdf" },
      params: { resolution: (2 * Math.PI) / 4096, rate: 50 } },
    { format: 1, id: "acme-imu6", type: "sensor", family: "imu", model: "Acme IMU-6", version: 1,
      source: { kind: "datasheet", ref: "https://acme.example/imu6.pdf" },
      params: { rate: 100, accelNoise: 0.02, gyroNoise: 0.002 } },
  ],
});
const arm = JSON.stringify({
  format: 1,
  bodies: [
    { id: "base", type: "static", shape: { type: "box", halfExtents: [0.1, 0.02, 0.1] }, position: [0, 0.02, 0] },
    { id: "arm", mass: 0.1, canSleep: false, position: [0.1, 0.1, 0],
      shape: { type: "compound", children: [
        { shape: { type: "box", halfExtents: [0.1, 0.01, 0.01] } },
        { shape: { type: "sphere", radius: 0.02 }, position: [0.1, 0, 0] },
      ] } },
  ],
  joints: [{ id: "shoulder", type: "hinge", a: "arm", b: "base", anchor: [0, 0.1, 0], axis: [0, 0, 1], limits: [-1.5, 1.5] }],
  motors: [{ id: "servo", joint: "shoulder", component: { id: "acme-s30" }, options: { voltage: 11.1 } }],
  sensors: [
    { id: "turned", joint: "shoulder", component: { id: "acme-enc12" } },
    { id: "imu", body: "arm", pose: { position: [0.05, 0, 0] }, component: { id: "acme-imu6" }, options: { seed: 3 } },
  ],
});

// The families the records name, in a registry the scene's worlds share, and the components module itself:
// a scene makes a world for each stage it shows, and the module is installed on each.
const registry = createComponentRegistry();
registry.registerMotorModel("dc-servo", dcServoMotor);
registry.registerSensorModel("encoder", encoderSensor);
registry.registerSensorModel("imu", imuSensor);
const robots = components({ registry });
const source = jsonComponentSource(parts);
if (!source.ok) throw new Error(source.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const catalog = createComponentCatalog(source.source, { families: registry.families });

// A scene with physics on the chain solver (a dc-servo's), a metre to a unit (physics.scale, 1 by default).
// Paused, and stepped by hand below; a page leaves it running and commands from physics.onStep.
const scene = createScene(canvas, {
  physics: { jointSolver: "chain", paused: true, modules: [robots] },
  stages: [{ items: [] }],
});

// The robot in the stage on screen, half a metre along +Z, its objects and joints under a prefix of their own.
const loaded = await loadRobotInScene(scene, arm, catalog, { components: robots, idPrefix: "arm.", position: [0, 0, 0.5] });
if (!loaded.ok) throw new Error(loaded.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const robot = loaded.robot;
robot.motor("servo").setPosition(0.5);                        // rad: the shoulder, to half a radian
for (let i = 0; i < 120; i++) scene.physics.step();
const turned = new Float64Array(2);
robot.sensor("turned").read(turned);                          // [angle, speed] of the hinge, as the encoder counts them
const shoulder = robot.hinge("shoulder");                     // the scene's own handle: scene.physics.hinge("arm.shoulder")
const object = scene.item(robot.objects.get("arm"));          // the scene's object "arm.arm", drawn where its body is
const seen = [turned[0].toFixed(2), shoulder.angle.toFixed(2), object.id, object.transform.position[2], robot.made];

// The same file again under the same prefix is refused, and nothing of it is made. Removed, the robot leaves the scene as it was.
const again = await loadRobotInScene(scene, arm, catalog, { components: robots, idPrefix: "arm." });
robot.remove();
console.log(...seen, scene.items().length, again.ok ? "loaded" : again.errors[0].path);
// 0.50 0.50 arm.arm 0.5 true 0 /bodies/0/id

Limits, for now: a robot is loaded in the stage on screen, not in another one; sources takes sources already loaded; the scene's default floor is worked out when a stage is first shown, before a robot loaded later (give floor a height); a robot's components are not kept across a stage's worlds (attached again, new). docs/embed/components.md has the options, the handles and what is checked.

Limits

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

const shelf = scene.item("shelf")!;
shelf.set({ scale: [1, 0, 1] });    // falling bodies pass through its body
shelf.set({ scale: [1, 0.1, 1] });  // they collide with this thin shelf again

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)
attach target (id), distance? the camera on the object: the eye at its origin, looking along its −Z axis, its +Y axis up, where the object is drawn (under its parents, with its motion, tweens and timeline tracks). The camera of a glTF file: see A model's cameras

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).

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:

The ease named on a key is the ease into it:

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.

With bodies:

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:

A cue's operations go through validateSceneOps and may not be step, timeline, stages or system (refused at /cues/<i>/ops/<j>/op).

setTimeline:

The director's module loads with import() on the first call and scene.ready covers the load.

The handle:

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.

A model's animations

The animations of a glTF model read as a tree (gltfTree, above) play as a timeline: gltfTracks turns one animation's channels into tracks on the nodes' objects, and setTimeline installs it.

import { createScene, parseGltf, gltfTree, gltfTreeItems } from "mote-engine";
import { gltfTracks } from "mote-engine/director";

const doc = parseGltf(await (await fetch("/models/robot.glb")).arrayBuffer());
const tree = gltfTree(doc);
const { items, ids } = gltfTreeItems(tree, { id: "robot", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });
const { timeline, animation, diagnostics } = gltfTracks(doc, tree, ids, { animation: "Walk", loop: true });
await scene.setTimeline(timeline);                 // animation.duration seconds; diagnostics: what is not played

A hermite key can be written by hand too: { t, v, ease: "hermite", in, out }, the segment into the key glTF's cubic Hermite spline from the previous key's out tangent to this key's in tangent, in the value's units a second (a missing tangent is 0). It applies to interpolated properties alone (numbers, vectors, colours in linear RGB, quaternions: a hermite rotation's two keys must be [x, y, z, w]), and the tangents are read by a hermite segment alone.

A model's cameras

A scene built in Blender, with its camera and the camera's animation, plays through that camera: the cameras of a glTF model read as a tree (gltfTree, above) are listed by gltfCameras, and gltfCameraRig gives the rig that puts the scene's camera on a camera's node. The node's own animation and its parents' are tracks like any others (gltfTracks), so the camera flies as in Blender with no track of its own.

import { createScene, parseGltf, gltfTree, gltfTreeItems, gltfCameras, gltfCameraRig } from "mote-engine";
import { gltfTracks } from "mote-engine/director";

const doc = parseGltf(await (await fetch("/models/shot.glb")).arrayBuffer());
const tree = gltfTree(doc);                                 // tree.nodes[n].camera: the camera a node carries
const { items, ids } = gltfTreeItems(tree, { id: "shot", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });

gltfCameras(doc, tree).cameras;                             // [{ index, name, type, yfov, fov, aspectRatio, znear, zfar, nodes }]
const { rig, camera, diagnostics } = gltfCameraRig(doc, tree, ids, { camera: "Camera" });
scene.setCameraRig(rig);                                    // { kind: "attach", target: "shot/Camera", fov, distance }
const { timeline } = gltfTracks(doc, tree, ids, { loop: true });
await scene.setTimeline(timeline);                          // the camera moves with its node and its node's parents

In Blender, export with File › Export › glTF 2.0 as for any model (Models from Blender), and tick:

Edit the scene in Blender, export again to the same file and load it again: the camera is found by its index or its name, whatever node the exporter puts it on.

A model's lights

A glTF file's KHR_lights_punctual directional, point and spot lights can light the scene and follow their nodes. gltfLights lists what the file declares; gltfSceneLights turns each node that carries a light into a scene light attached to that node's object. The node's own animation and its parents', played by gltfTracks, move the light without a separate light track.

import { createScene, parseGltf, gltfTree, gltfTreeItems, gltfLights, gltfSceneLights } from "mote-engine";
import { gltfTracks } from "mote-engine/director";

const doc = parseGltf(await (await fetch("/models/shot.glb")).arrayBuffer());
const tree = gltfTree(doc);
const { items, ids } = gltfTreeItems(tree, { id: "shot", motion: "none" });
const { lights, diagnostics } = gltfSceneLights(doc, tree, ids);
const scene = createScene(canvas, { mode: "ray", stages: [{ items }], lights });
await scene.setTimeline(gltfTracks(doc, tree, ids, { loop: true }).timeline);

gltfLights(doc, tree).lights; // [{ index, name, type, color, intensity, range, nodes, ... }]

In Blender, use File › Export › glTF 2.0 and tick Include › Data › Punctual Lights. Choose Data › Lighting › Standard for the physical round trip below. Export Animation too when the light objects or their parents are animated. Editing and re-exporting the file and loading it again preserves the lights by their names and nodes.

From Blender to mote and back

A Blender scene can keep its objects, parent hierarchy, camera, punctual lights and animation in one GLB, while a small Scene JSON document keeps only mote's own choices. The document names the file's content; it does not copy node transforms, camera poses or light directions. Editing and re-exporting the GLB therefore updates the next scene made from the same document.

In Blender, choose File › Export › glTF 2.0 and tick:

Declare the file's node tree as a stage group with gltfTree. A camera entry names a camera in that same file, a lights entry selects its punctual lights, and animation on the tree group selects a clip:

{
  "version": 2,
  "camera": { "gltf": "shot.glb", "camera": "Camera", "width": 960, "height": 540 },
  "stages": [{
    "items": [{
      "id": "shot",
      "gltfTree": "shot.glb",
      "normalize": false,
      "motion": "none",
      "animation": { "clip": "Dolly", "loop": true }
    }]
  }],
  "lights": [{ "gltf": "shot.glb", "lights": "all", "intensity": 1 }],
  "render": { "mode": "ray", "quality": "low" },
  "clock": { "time": 0, "step": 0.016666666666666666 },
  "autoplay": false
}

Load it with createSceneFromJson(canvas, document, { resolveUrl }). Parsing validates the document and fetches nothing. Creating the scene reads each file once, makes the tree with gltfTreeItems, the camera's attach rig with gltfCameraRig, attached lights with gltfSceneLights, and the clip's timeline with gltfTracks. sceneFromJson alone is only the synchronous parser: it accepts these declarations but returns no generated tree objects, file camera rig, file lights or file-animation timeline for them; use createSceneFromJson to resolve them.

After editing Blender, export over the same GLB and create the scene again with the unchanged document. describe() writes these declarations back as file references—the gltfTree group, camera name, light selections and clip—not as expanded nodes, poses or generated tracks. A describe → load → describe round trip is identical. If the timeline is replaced after loading, describe() writes the explicit timeline and omits the stale tree animation; post-load node changes, removals and additions are reported by tree-item diagnostics with complete: false.

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" } }

An add's object is a Scene JSON v2 object, so it can have a parent, be a group (no shape) or be one node of a glTF file (A hierarchy in Scene JSON):

await scene.applyOps([
  { op: "add", item: { id: "pivot", transform: { position: [0, 0.5, 0] } } },                                  // a group
  { op: "add", item: { id: "blade", parent: "pivot", shape: "box", transform: { scale: [0.8, 0.05, 0.1] } } },
  { op: "animate", target: "item:pivot", property: "rotation", to: [0, 0, 180], seconds: 2 },                  // the blade goes round with it
]);

The parent must be there when the operation is applied, in the stage the object is added to (the one shown, or the one a transition is going to). Validation refuses, with the pointer /ops/<i>/item/parent, a parent the scene does not have (one added earlier in the same batch counts, one removed earlier does not) and an object that is its own parent. A parent that the scene has in another stage passes validation and fails when the operation is applied (the parent "x" of "y" is not an object of its stage): the operations before it stay and the rest are not applied. A stages operation's hierarchies are checked whole, as a document's.

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, weights; 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.

An object's weights (one number a morph target, as many as its mesh has, ItemHandle.weights) is written by set and animated by animate one component at a time, nothing allocated a frame:

await scene.applyOps([
  { op: "set", target: "item:face", property: "weights", value: [1, 0, 0.3] },
  { op: "animate", target: "item:face", property: "weights", to: [0, 1, 0], seconds: 2, ease: "inOut" },
]);

Validation checks every list's shape (1 to 64 finite numbers) and checks its count whenever the object's mesh is known. This includes an object already in the scene and a primitive added earlier in the batch: a primitive has no morph targets, so neither add with its own weights nor a later set/animate weights is accepted. These validation failures refuse the whole batch with JSON-pointer diagnostics and apply nothing.

Five operations put objects where they belong from their world bounding boxes: each object's real box, its mesh's vertices through its transform, with every object under it in its hierarchy (a group's box is its children's). Y is up; a scene unit is a metre.

const { placed } = await scene.applyOps([
  { op: "placeOn", id: "table" },                                                  // on the floor, where it stands in plan
  { op: "placeOn", id: "vase", on: "table", at: [0.3, -0.1], gap: 0 },             // on top of the table, its centre at world x 0.3, z -0.1
  { op: "placeRelative", id: "chair", to: "table", side: "front", distance: 0.2 }, // 20 cm in front of it, centred on it
  { op: "align", ids: ["lamp", "shelf"], axis: "z", edge: "min", to: -2 },         // their backs against z = -2
  { op: "distribute", ids: ["a", "b", "c", "d"], axis: "x" },                      // equal gaps between the first and the last
  { op: "resolveOverlaps", ids: ["chair", "stool"], fixed: ["table"], gap: 0.05 }, // out of each other's way, 5 cm apart
]);
// placed[0]: [{ id: "table", position: [0, 0.37, 0], box: { min, max }, moved: [0, -0.13, 0] }]
Operation What it does
placeOn Rests id on the floor, or on top of on: its lowest point ends gap (default 0) above the support's highest, and never below it, so it does not reach into it. Without on the level is the floor's y where the scene gives one, else the physics floor, else 0, and the object keeps its place in plan. With on it is centred over that object. at: [x, z] is the world place of its centre in plan instead.
placeRelative Puts id on a side of to: "right" (+X), "left" (−X), "above" (+Y), "below" (−Y), "front" (+Z, towards the viewer) or "behind" (−Z), with distance (default 0) between their facing faces. Above or below, it is centred on to in plan. Beside it, it is centred along the other horizontal axis and keeps its height: what stands on the floor stays on it.
align Moves each of ids along axis ("x", "y", "z") so that its box's edge ("min", "center", "max"; default "center") is at to: a world coordinate, another object's same edge (its id) or, left out, the first listed object's, which stays.
distribute Spaces ids evenly along axis, in the order they stand in along it: equal gaps between their boxes (spacing: "gaps", default) or equal steps between their centres ("centers"). Without gap the first and the last stay and the others are spread between them (three objects at least; an error when they do not fit). With gap the first stays and each next one follows at that distance.
resolveOverlaps Moves objects apart until no two of their boxes overlap, gap apart at least. ids are taken in order of rank (default: the shown stage's visible objects without a parent): each gives way to those before it and to fixed, which never move, and goes to the nearest place clear of them, pushed in plan (axes: "xz", default) or along any axis ("xyz"). Two objects that do not move and overlap each other (two of fixed) cannot be put right: the operation is then a runtime error that names the pairs, and nothing is moved.

Each one answers where it left its objects, in placed (type PlacedObject) under its index in the batch: the object's own position (in its parent's space when it has a parent: the world move goes through the parent's transform), its world box after the move as the scene measures it, and the world translation moved.

A parent and its child can be in one operation. Each object is then measured without the others the operation moves under it (a table and the cup on it are two boxes), its world target is worked out first, and the moves are applied from parents to children: a child is carried by its parent's move, and its own transform takes only the rest. So each ends where the operation says: two of them aligned on a centre both end centred there. Its box in placed is measured the same way, and moved is its whole world move, its parent's included. A reference (on, to, an object of fixed) must not hang under an object the same operation moves, since it would move with it: that is refused with a JSON pointer where the hierarchy is known when the batch is validated, and is the operation's runtime error otherwise.

Two boxes overlap when they share a volume: more than a nanometre on every axis. Boxes that touch do not, so an object resting on another is left alone. The boxes are axis-aligned in the world: a chair pushed under a table overlaps it, and a turned object's box is larger than the object.

Validation refuses, with a JSON pointer, an id the scene does not have (one added earlier in the batch counts), an object placed on or relative to itself, an id listed twice, more than 256 ids, an align of one object without a to, a distribute of two without a gap, and a reference under an object the operation moves. An object with nothing to measure (a group whose children draw nothing, a model still loading) is the operation's runtime error. The operations are logged and replayed as the others are.

The promise resolves after the frame that applied the last operation:

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).

Orthographic views of a scene

A scene's frames are perspective pictures. For measuring where things are, mote-engine/director has orthographic views: a projection with no perspective, in which a world point's place does not depend on its depth and a length is read with one number, and a small rasterizer that draws a scene's triangles through it.

import { createOrthoPicture, drawOrthoMesh, orthographicView, projectOrthographic } from "mote-engine/director";

// The plan of a 6 × 3 × 5 m room, in a picture of 800 × 600.
const view = orthographicView("top", [-3, 0, -2.5], [3, 3, 2.5], 800, 600);
view.scale;                                    // pixels a metre
projectOrthographic(view, 1, 0, 2);            // [x, y, depth]: the pixel of the world point (1, 0, 2), and its height towards the viewer

const picture = createOrthoPicture(800, 600, [24, 27, 33, 255]);
scene.geometry((object) => {
  drawOrthoMesh(picture, view, { ...object, cull: true });   // picture.data: RGBA, row 0 at the top
});

The drawing has no materials' maps, lights, shadows or effects.

Measuring the scene

Three reads answer where things are in the picture the scene draws now, with no physics world:

const outline: SceneBounds = { sphere: { center: [0, 0, 0], radius: 0 }, box: { min: [0, 0, 0], max: [0, 0, 0] }, screen: { x: 0, y: 0, width: 0, height: 0, visible: false } };
function everyFrame() {
  const b = scene.bounds("chair", outline); // filled in place: no allocation
  if (b?.screen.visible) drawBox(b.screen);
  requestAnimationFrame(everyFrame);
}
requestAnimationFrame(everyFrame);

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 ray with WebGPU the strike stands in the scene's world, on an upright plane through the point it struck: seen from any camera, hidden by the objects in front of it, inside the clouds, the fog and the smoke, its flash a point light on the channel that lights those media from within; 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), nebula (glowing gas in filaments crossed by dark dust lanes; with volume, a participating medium in a world box in Ray), 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.

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. 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. Controls and wave clocks survive renderer/mode changes.

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.

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.

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.

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); volume: { min: [x, y, z], max: [x, y, z] } instead anchors the plume to a world-space box in scene units, overriding source. In Ray the whole plume is bounded by that box, rising from its bottom centre and fading at its top; the CPU fallback projects that bottom centre as its nozzle. Change the box with set({ volume }), or pass null to return to source. 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.

In Ray, volume makes it a real participating medium in a world box (scene units, axis-aligned). This is ground fog:

fog({
  volume: { min: [-4, 0, -3], max: [4, 0.8, 3] },
  density: 0.6, height: 0.55, speed: 0.12, turbulence: 1, color: "#c4cdd3",
})

It is:

Objects inside it are veiled, the camera can walk into it, and nothing outside the box is fogged; its sides fade over 8% of the box's smaller horizontal side. At the floor the extinction is density × 2 per scene unit. set({ volume }) moves it to a new box, set({ volume: null }) returns to the 2D fog.

Without volume, Ray keeps the 2D fog: an effect cannot know the scene's world extent or its units (normalized objects or metres), so a guessed box would be wrong in one of them and would change every existing Ray scene.

Like the built-in smoke and clouds, it is admitted at fixed tiers through high; a fixed quality: "ultra" exceeds the media planner's aggregate work bound and reports it, while "auto" stays at the highest admitted tier.

nebula({ glow: 1, dust: 0.5, filaments: 1 }) is glowing gas crossed by dark dust: a body with an irregular outline that fades to nothing before its rim, its light gathered into thin filaments and arcs over a faint haze, going from color (the thin gas, default "#ff4fa3") to color2 (the dense gas towards the core, default "#7a5cff") and paling to white at its densest, with dust lanes that dim it. density (0 to 3) is how much gas and dust there is (0 draws nothing), glow (0 to 4) how bright the gas is, dust (0 to 3) how much dust crosses it, filaments (0 smooth to 2), scale (0.25 to 4) the size of its features, speed (0 to 1, default 0.05; 0 holds it still) how fast it slowly churns, and seed its pattern. Every number is a live parameter (a timeline can track it). Without volume it is a 2D backdrop over the whole canvas, under the objects (layer: "over" puts it over them): soft dots in Ray and Wireframe, coloured density characters in ASCII.

In Ray, volume makes it a participating medium in a world box (scene units, axis-aligned):

nebula({ volume: { min: [-2.6, -1.5, -2.2], max: [2.6, 1.5, 1.2] } })

The gas is emission and the dust is extinction (the blue more than the red, so what is behind a lane is reddened) with a low, blue albedo (dark lanes; a faint blue veil where the scene's lights reach it) and Draine's phase function for the light it scatters (phase: { g, alpha }; by default the g whose mean cosine is 0.6).

It is drawn by the engine's volume march on the public api: 1 volume contract, so it is:

Its density is zero at the box's faces, so the box never shows, and its light and extinction are relative to the box's size: the same settings look the same in a box of any size. It is out of the march toward the local lights (lightMarch: false, as the built-in fire, smoke and fog), so the media planner charges it its own samples alone and it is admitted at every tier, fixed "ultra" included, alone and beside them.

ray: { temporal: false } turns the temporal history off and ray: { shadows: false } the solids' and the sun's shadows on its dust. set({ volume }) moves the box without a new installation; set({ volume: null }) returns to the 2D nebula.

ASCII, Wireframe and Ray without WebGPU (or before the volume is installed) draw the 2D nebula where the box shows on the canvas, at the box's depth among the objects. Its light is seen and adds to the picture; it does not light the objects.

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:

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. Tilt, palette, temperature and hotspots update live without restarting ingestion.

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.

fire({ volume: { min: [2.17, 0.5, -2.45], max: [2.83, 1.0, -2.10] } }) burns in a box of the scene's world instead (scene units, y up): a fire on a log pile, in a fireplace. The box's bottom face is the fuel bed and the flames rise to its top; height below 1 ends them lower. The box is a boundary, not a window: flames as tall as the box (height 1 or more) break against its top face, bend over and run along it, and curl back at its edges, as under a firebox's ceiling. For a fire in the open, give it a box taller than the flames you want and a height below 1. In Ray with WebGPU the flames are a volume of light in that box: seen from any camera, hidden by what stands in front (the hood, a wall), seen through glass, with embers rising among the objects, and light becomes a flickering point light in the box that casts the objects' shadows (0, the default: the flames light nothing but the picture and its bloom). The shape follows the box: a square bed burns to a peak, a long one to a ridge, and the flames keep their size relative to the box's height at any scene scale. Their pace does not follow the scale (scene units are not metres unless the scene says so): speed 1 suits a hearth, where the tongues pass a few times a second and the fine folds flicker at about 8 Hz; a real fire pulses slower as it grows (about 1.5/√width Hz, width in metres), so lower speed for a bonfire and raise it for a candle. intensity, height, speed, turbulence, palette, color and light work as above, and set({ volume }) moves the fire without reloading its shader; set({ volume: null }) returns to the 2D fire. Everywhere else (ASCII, Wireframe, Ray without WebGPU, or a volume Ray could not install) the 2D flames burn where the box's base shows on the canvas, as wide and as tall as the box shows, over the picture (they are not hidden by the objects). While Ray prepares the volume's shader nothing is drawn (up to 180 frames; wait for ready in scene.stats().effects to show the scene with its fire lit). source is not read while a volume is set. The volume is one of the scene's Ray media (at most 8, see custom shaders): it uses no texture and only emits, so it is out of the media's march toward the local lights and costs its own march samples alone: it is admitted at every quality tier and a medium beside it (smoke, clouds, a fog) is admitted where it is admitted alone. fire({ volume }) and smoke({ volume }) install together at every tier, fixed "ultra" included. A volume a fixed tier cannot admit is refused (failed in stats().effects, the fire's 2D form drawn instead). A value that is not a box (finite corners, max above min on every axis) throws, as does a box with a corner beyond 1e30 or a side under 1e-4 scene units (a RangeError naming the field); the settings table (EFFECT_PARAMS) lists it as a box, which the director's operations validate.

smoke({ volume: { min: [2.17, 0.68, -2.45], max: [2.83, 0.95, -2.08] } }) keeps the plume in a box of the scene's world (scene units, y up). In Ray with WebGPU the smoke is a volume in that box and the box is its boundary: it rises from the bottom centre as a column, breaks against the top face, pools and spreads under it and rolls down the side faces, so it reads as smoke under a ceiling (a firebox's, behind its glass). Its density is relative to the box: the same density and opacity look the same in a box of any size. It is lit by the scene's lights and shadowed by the solids, without the media's own dimming of the local lights (it leaves that march, so it stands beside a fire or a fog at every quality tier). While Ray prepares the volume, or if Ray refuses it, nothing is drawn: the 2D flow, which knows neither the box nor the solids about it, is the fallback only where there is no Ray volume (ASCII, Wireframe, Ray without WebGPU), rising from where the box's bottom centre shows. With a volume, scale only affects the CPU fallback's nozzle in ASCII and Wireframe (and Ray without WebGPU): the Ray volume is sized by the box alone. set({ volume }) moves the box without reloading the shader; set({ volume: null }) returns to the free plume of source. A box with a corner beyond 1e30 or a side under 1e-4 scene units throws a RangeError naming the field (the GPU holds its numbers as 32-bit floats; such a box would otherwise vanish silently).

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. In Ray with WebGPU each burst also lights the scene and leaves smoke: a point light where its stars are, in their colour as it changes, for as long as they burn (three bursts' lights at once at most; it lights the objects, casts their shadows and lights the scene's other volumes), and a puff of thin volumetric smoke that grows, drifts with the wind and is gone in a few seconds, dark until a later burst or the scene's light falls on it. Both cost GPU time: while a burst's light is on, Ray traces the objects again every frame (a still scene no longer rests), and the smoke is one more volume to march, one of the eight a scene composes. fireworks({ ray: { light: false } }), ray: { smoke: false } or both leave them out; with both off the effect installs no Ray shader at all and costs what its stars alone cost (in a scene that is otherwise still, either part alone keeps Ray drawing every frame while it is alive; only both off let it rest). ray is read when the effect is created: set does not change it, so make the effect again to switch. ASCII, Wireframe and Ray without WebGPU draw the stars alone either way.

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", "webgpu", "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, 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 either:

A v2 stage item has id, optional shape, parent, transform and material, plus motion, visible, body and weights. weights is a list of 1 to 64 finite numbers passed to ItemSpec.weights, one for each morph target in the mesh's order; for example:

{ id: "face", shape: "sphere", weights: [0.5, 0.25] }

describe() writes an object's own weights back to its v2 document, so loading that document preserves them.

A hierarchy in Scene JSON

A version 2 object (a stage's item, and the object of an add operation) can have a parent, can be a group, and can be one node of a glTF file:

{
  "version": 2,
  "camera": { "position": [0, 1.6, 4.6], "target": [0, 0, 0], "fov": 40, "width": 640, "height": 480 },
  "stages": [{
    "items": [
      { "id": "crane", "transform": { "position": [0, -0.6, 0], "rotation": [0, 30, 0] }, "motion": { "spin": { "axis": [0, 1, 0], "speed": 10 } } },
      { "id": "mast", "parent": "crane", "shape": "box", "transform": { "position": [0, 0.7, 0], "scale": [0.12, 0.7, 0.12] } },
      { "id": "boom", "parent": "crane", "transform": { "position": [0, 1.4, 0], "rotation": [0, 0, 20] } },
      { "id": "arm", "parent": "boom", "shape": "box", "transform": { "position": [0.6, 0, 0], "scale": [0.6, 0.08, 0.08] } },
      { "id": "hook", "parent": "boom", "shape": { "gltf": "models/crane.glb", "node": "Hook" }, "transform": { "position": [1.2, -0.3, 0], "scale": 0.25 } }
    ]
  }],
  "lights": [{ "kind": "directional", "direction": [1, 1.2, 0.8] }],
  "render": { "mode": "ray" }
}
/stages/0/items/3/parent: the parent "bom" of "arm" is not an object of its stage.
/stages/0/items/2/parent: "boom" is its own ancestor (a cycle of parents).
/stages/0/items/1/body: an object without a shape is a group, which draws nothing and has no body: remove body, or give the object a shape.

scene.describe() writes a hierarchy as it is: a child with its parent and its own transform (the one item.transform reads, in its parent's space), a group as an object without a shape, an object made from a document's or an operation's { gltf, node } as that shape. Loading the document gives the same hierarchy, composed to the same matrices to the bit. What a document cannot say is reported in diagnostics, never written wrong:

kind What it says
item-parent The object is written without its parent, with the transform that draws it on its own where it is now: its parent is not in the document (a source made by the page), or the object has more than 64 ancestors.
item-skin The object has a skin (ItemSpec.skin). The document draws its mesh undeformed.
item-morph The object is a glTF node with morph targets. The document draws it unmorphed, without weights.

A tree loaded from a document or added by operations is written whole, and describe() stays complete. One the page made with gltfTreeItems(tree, { gltf: path }), which names the file each mesh node came from (A model as a tree), is written with the same hierarchy, transforms and meshes, but Scene JSON v2 cannot carry each node's glTF name and provenance: describe() lists them as unserializable and returns complete: false. Load the tree from a document to keep the description complete:

const doc = parseGltf(await (await fetch("/models/robot.glb")).arrayBuffer());
const { items } = gltfTreeItems(gltfTree(doc), { id: "robot", gltf: "models/robot.glb" });
const scene = createScene(canvas, { stages: [{ items }] });
const described = scene.describe();                        // complete: false, with an `unserializable` diagnostic per node name/provenance
const again = sceneFromJson(described.document, { resolveUrl: (path) => new URL(path, location.href).href });
if (again.ok) createScene(otherCanvas, again.options);     // the same hierarchy, composed to the same matrices, without glTF names/provenance

Without gltf, the tree's mesh nodes are sources the page made: describe() leaves them out as procedural-source, as it does any such source, and what hangs from one is written without its parent (item-parent).

In Scene JSON v2, a document that has physics needs physics.jointSolver: "chain" for a hinge's active drive, positive friction or positive damping, just as createScene does. With the solver omitted or set to "sequential", sceneFromJson refuses the document and points to each offending field, for example /stages/0/joints/0/drive. A complete valid hinge document is:

{
  "version": 2,
  "camera": { "position": [0, 0, 5], "target": [0, 0, 0], "fov": 40, "width": 640, "height": 480 },
  "stages": [{
    "items": [{ "id": "arm", "shape": "box", "body": { "mass": 0.2 } }],
    "joints": [{
      "id": "axle", "type": "hinge", "a": "arm", "anchor": [0, 0, 0], "axis": [0, 0, 1],
      "drive": { "target": 0.2, "stiffness": 12, "damping": 0.05, "maxTorque": 7 },
      "friction": 0.05, "damping": 0.02
    }]
  }],
  "lights": [{ "kind": "directional", "direction": [1, 1, 1] }],
  "physics": { "jointSolver": "chain" },
  "render": { "mode": "wireframe" }
}

Zero-valued drive, friction and damping fields remain accepted with either solver.

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" (a request at the head of the queue did not finish within 60 s per 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) and scene.seek(seconds) use the step queue for forward targets and resolve with { frame, time }. The time must be on the step grid, at or after the clock's starting time.

A backward seek replays up to 36,000 frames from the original declarative setup and the complete operations log. Success updates the original scene and canvas and discards the operations after the target. Item handles for IDs present on both sides continue to work. Scene observers and cues on the retained timeline stay subscribed. Advance with step() to continue on the new branch.

In-place rewind supports declarative scenes made with local primitives and built-in effects. An incomplete log, unrecorded edits, URL assets without retained bytes, renderer plugins and work still waiting at a frame boundary can cause { kind: "not-replayable" }. A newer seek supersedes one in progress, and destroy() releases its staging resources.

On a stepped scene:

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).

Exporting a video

recordVideo turns a scene into an MP4 file, in the browser, with no server and no other library: it steps the scene frame by frame on its stepped clock, reads each picture, encodes it with the browser's own encoder (WebCodecs) and writes the file itself. A frame may take as long as it needs (a path-traced one, seconds): the video still plays at the scene's speed.

It is a module of its own, mote-engine/video: a page that does not import it downloads none of it.

import { createScene, box } from "mote-engine";
import { recordVideo } from "mote-engine/video";

// A stepped clock: the time moves only when a step is taken, 1/60 s each.
const scene = createScene(canvas, {
  clock: { time: 0, step: 1 / 60 },
  stages: [{ items: [{ id: "crate", source: box() }] }],
});
await scene.ready;

// What happens in the five seconds: here, a turn.
await scene.setTimeline({
  version: 1, duration: 5,
  tracks: [{ target: "item:crate", property: "rotation", keys: [{ t: 0, v: [0, 0, 0] }, { t: 5, v: [0, 180, 0], ease: "inOut" }] }],
});

const video = await recordVideo(scene, { seconds: 5, fps: 30, background: "#ffffff" });
// video.frames 150, video.seconds 5, video.codec such as "avc1.64001f", video.blob: the file

const link = document.createElement("a");
link.href = URL.createObjectURL(video.blob);
link.download = "scene.mp4";
link.click();
URL.revokeObjectURL(link.href);

The first picture is the scene as it stands at the frame it starts from; picture N is the scene's frame from + N × (clock rate / fps). When the promise resolves the scene stands at the last frame recorded, and can be stepped, captured or recorded again. Nothing else may step the scene while it records.

The picture is the canvas's, in device pixels: the canvas's CSS size times the pixel ratio is the video's size. A canvas is transparent where the scene draws nothing and a video has no transparency, so the picture is put over background. An odd width or height loses its last column or row (H.264 pictures have even sides; the other codecs are given the same picture).

Options (all optional but the length):

Option Default Meaning
seconds — The video's length, rounded to whole frames. Give this or to.
from the scene's frame The scene's frame the video starts at (scene.frame's count). The scene is taken there first: ahead by stepping; behind by replaying the scene from its setup, which only a scene that can be replayed does (see the stepped clock).
to — The scene's last frame recorded, included. Give this or seconds.
fps the clock's rate Frames a second. It must divide the clock's rate: on a 60 Hz clock 60, 30, 20, 15, 12, 10…; every rate / fps-th frame of the scene is a picture.
codec "avc" "avc" (H.264: it opens everywhere, video editors included), "vp9" or "av1", all in an MP4 file.
bitrate 0.2 bit a pixel a frame, from 1 to 80 Mbit/s Bits a second asked of the encoder (12.4 Mbit/s for 1920 × 1080 at 30 fps).
keyframeInterval two seconds' worth A key frame every this many pictures (a player seeks to key frames).
background "#000" The opaque CSS colour behind the scene.
refined, samples false, ray.samples Ray: every picture path traced to samples before it is read (capture({ refined: true })). Slow: each frame waits for its refinement, so a minute of video can take hours. Without it Ray records its real-time picture.
timeoutMs 60000 The longest one picture may take to be drawn and read.
signal — An AbortSignal: aborting rejects with its reason (an AbortError by default).
onProgress — Called with { frame, frames } after each picture is handed to the encoder.

It resolves with { blob, mimeType, codec, width, height, fps, frames, seconds, bytes, hardwareAcceleration }: blob is the file (video/mp4), mimeType its type with the codec (video/mp4; codecs="avc1.640028"), codec the codec string of the stream as the encoder made it (its own profile and level), hardwareAcceleration the encoder that was asked of the browser (below).

Limits.

Browsers. It needs WebCodecs' VideoEncoder: Chrome and Edge 94 or later (H.264, VP9 and AV1, each where the browser and the machine encode it), Safari 16.4 or later for the codecs it encodes (H.264 on every Mac and iPhone), Firefox 130 or later on desktop. Before the first frame recordVideo asks the browser whether it encodes the codec at this size: where it does not, it rejects with a NotSupportedError whose message names the codecs it can (It can encode: "vp9", "av1"); where there is no VideoEncoder at all, with a NotSupportedError that says that.

However a recording ends (an abort, an error of the encoder, a scene paused or destroyed: the scene's own { kind, message }), the encoder and every frame are closed and the scene is left usable, at the frame it had reached.

From the command line

mote-engine video records a Scene JSON document in headless Chrome and writes an MP4. The mote-engine alias has the same subcommand. Chrome is found through CHROME_PATH or the usual installation places.

# Five seconds at 30 fps, with model and map paths relative to the current directory.
mote-engine video scene.json --seconds 5 --fps 30 --root . --out shot.mp4

# A guide video and its uncompressed first and last frames for an AI video model.
mote-engine video scene.json --preset ai-video --stills --out guide.mp4

# Portrait 1080p: 1080 × 1920, still at 24 fps.
mote-engine video scene.json --preset ai-video --hd --aspect 9:16 --seconds 8 --out portrait.mp4

--look clay requests a neutral matte guide; the equivalent director option is look: "clay". Bundle references select muted subject colours, inherited by every generated node of a glTF tree. Lights, shadows, geometry and material sidedness are kept. Emissive is zeroed and transmission and clearcoat are set to 0. Opaque materials become opaque clay; MASK and BLEND materials keep their alpha mode, cutoff, opacity factor and base-colour texture alpha (the texture's RGB is ignored), so their coverage is unchanged.

Starting with 0.56, clay also replaces the source fill materials of { "svg": "mark.svg", "depth": 0.1 } shapes. Multiple fills become the same neutral matte (or the subject's muted colour), while geometry, sidedness and per-fill opacity stay intact. With an SVG scene loaded in the director, export it with:

{ "name": "svg-guide", "seconds": 1, "stills": true, "look": "clay" }

Pass these arguments to render_video; the session returns to its original SVG fills afterwards.

Clay applies only to that render: afterwards a director session returns to its original scene and materials. describe_shot and the bundle's prompt files still describe the original document, including glass, metal and emissive materials rather than their temporary clay substitutes. The current implementation rejects Gaussian splats, and material-changing director histories must be cleared by reloading the scene.

Give --seconds, or --from and --to (the last scene frame is included). The starting frame defaults to 0. Other picture and encoding options are --fps, --width, --height, --mode ascii|ray|wireframe, --refined, --samples, --codec avc|vp9|av1, --bitrate and --background. --refined and --samples are Ray-only: in ASCII or Wireframe either is a usage error naming the selected mode. The width and height are the page canvas's size and therefore the picture's size; an odd side is cropped for the video as described above. --root locates model and environment-map files. The command and render_video sample the nearest stepped scene frame when a requested rate does not divide the clock's rate; direct recordVideo keeps its divisor rule.

A 1/24-second clock is not expressible on the stepped scene's whole-frame grid. At 24 fps from a 60 Hz scene, nearest-frame sampling therefore records positions 0, 3, 5, 8, 10, 13…: the steps alternate 3, 2 scene frames. The resulting 12.5 ms timing jitter can show as slight judder. For perfectly even motion use 30 or 60 fps, or 20/15/12 fps. The manifest records the exact positions as frames.positions and omits the misleading single render.stride for a sampled video.

The ai-video preset makes guide videos for AI video models that take a reference video and first/last frames. It fixes H.264 and 24 fps, chooses 1280 × 720 by default or 1920 × 1080 with --hd, and derives the bitrate from the duration: the smaller of a 12 Mbit/s quality ceiling and 90% of the byte-limit budget. The encoded file is checked again, so the limit is enforced even if the encoder overshoots its requested bitrate. The preset trades perfectly even motion for 24 fps compatibility.

--aspect 720p (default) 1080p (--hd)
16:9 1280 × 720 1920 × 1080
9:16 720 × 1280 1080 × 1920
1:1 720 × 720 1080 × 1080
4:3 960 × 720 1440 × 1080
3:4 720 × 960 1080 × 1440
21:9 1680 × 720 2520 × 1080

A preset video lasts at most 30 seconds, is at most 50 MiB and has at least 17 frames. A different explicit frame rate or codec, an explicit bitrate, dimensions that contradict the selected geometry, an unsupported aspect, a longer duration or fewer frames is refused with a message naming the limit.

--stills writes <name>.start.png and <name>.end.png beside <name>.mp4. They are lossless PNGs of exactly capture() at the first and last recorded scene frames, at the canvas's full size and without video compression. In Ray both stills always equal capture({ refined: true }), whether or not --refined is given; that option controls refinement of the video frames, not the stills. These are the first/last images to supply with the guide video.

The destination is written only on success: encoding streams to temporary files in the destination's folder. Just before publication the command checks again that no target appeared unless --force was given, then renames the stills first and the video last, so the video's presence means the set is complete. A rename failure removes outputs renamed by that run. Chrome is closed and temporary output is removed on an error, SIGINT or SIGTERM. Existing video or still outputs require --force. Success prints one JSON summary with the paths, frame count, duration, size, codec, encoder and any fallback.

Exit codes are 0 for success; 2 for command-line, preset, Scene JSON or existing-output errors; 1 for Chrome, codec, recording or output failures; 130 for SIGINT and 143 for SIGTERM. A missing Chrome explains CHROME_PATH; an explicitly set CHROME_PATH naming a missing file is an error and is not ignored in favour of discovery. An unsupported codec names the encoders that Chrome supports; document diagnostics retain their JSON pointers. If Ray falls back because WebGPU is unavailable, the warning on stderr and the summary's fallback field say so explicitly.

From the director

After load_scene, the render_video tool takes the same length, rate, picture, codec, preset and still options, plus a required name and optional overwrite. It writes <out>/<name>/video.mp4; with stills: true, video.start.png and video.end.png; and video.json.

{
  "name": "guide",
  "seconds": 5,
  "preset": "ai-video",
  "stills": true
}

The answer contains those paths and the recording summary. The manifest includes the document, timeline, operations log, asset digests, engine version, requested and actual codec and size, frame rate, frames.count, seconds, bytes, hardwareAcceleration, preset and its limits, any fallback, and the stills' paths, frame times and refinement. For nearest-frame sampling, frames.positions records every sampled scene frame and render.stride is absent. render.refined and render.stillsRefined say what was actually refined, including when Ray fell back. Only one preview, sequence or video render runs at a time; other page-dependent calls answer busy meanwhile.

A bundle for AI video models

--bundle <dir> gathers everything a video model needs in one folder. It implies --preset ai-video and --stills; --aspect, --hd, --seconds/--from/--to, --mode and --refined work as they do for the preset. --style, --negative and --max-length go to the shot description. The flow is Blender or Scene JSON → mote → bundle → video model: the engine writes data only, calls no generation service and holds no service keys.

mote-engine video scene.json --seconds 5 --bundle handoff \
  --style "cinematic, natural motion" --negative "no text, no watermark" \
  --ref woman=references/face.png --ref car=references/car.jpg

The complete folder is:

handoff/
  guide.mp4             # the guide video
  start.png, end.png    # its exact first and last scene frames
  prompt.txt            # describeShot().prompt
  prompt-short.txt      # describeShot().promptShort
  shot.json             # the whole shot description
  refs/               # present only with references
    1-woman.png         # subject identity images, in the declared order
    2-car.jpg
  request.json          # generic media roles and suggested parameters
  bundle.json           # engine/document/asset/video metadata and file digests

Each --ref <subject>=<image> names a scene object id and a PNG, JPEG or WebP file. There may be at most 9 references, each at most 20 MiB. The file's magic bytes, not just its extension, determine the accepted format. An unknown subject, an unreadable or unsupported image and a tenth reference are errors that name the offending input. The prompt ties every image to the same noun used for its scene subject: for example, The woman at the centre is the subject in reference image 1. A technical id uses its shape noun; a subject absent from the sampled frames is marked (appears later). These sentences are mandatory under --max-length: if they and the other mandatory prompt parts cannot fit, the command fails with the minimum length needed rather than dropping them. prompt-short.txt also includes a compact list such as reference images: 1 the woman, 2 the car when it fits; the short prompt omits that list where it does not.

request.json follows the published schemas/ai-video-request.schema.json (JSON Schema 2020-12). It records version: 1, the video's exact durationSeconds, aspectRatio and resolution, the prompts, and an ordered media list. The generic roles are:

Role File
video_reference guide.mp4
start_image / end_image start.png / end.png
image_reference one refs/ image per --ref, with its subject, in declaration order

The uses field suggests two workflows. restyle lists video_reference (and image_reference when present): use the guide as a reference or for an edit, with the prompt and identity images, keeping its motion. keyframes lists start_image, end_image (and image_reference when present): generate from the first and last frames with the prompt and identity images. For example, a service that takes a reference video, first/last frames and reference images might map video_reference to its video_references field (or its video-edit input), the frame roles to start_image and end_image, and the identity entries to image_references. These names are examples, not a service dependency.

When describeShot resolves placeholders: true, prompt.txt and the request's full prompt contain the blocking-placeholder sentence, and uses.restyle also lists placeholders. This tells a restyle consumer to preserve figure paths, actions and timing but not copy stiff placeholder motion. The keyframes use is unchanged.

{
  "version": 1,
  "durationSeconds": 5,
  "aspectRatio": "16:9",
  "resolution": "720p",
  "prompt": "Subject: woman … car … The woman at the centre is the subject in reference image 1. The car on the right is the subject in reference image 2.\nCamera: …\nKeep the guide video's composition and camera timing.",
  "promptShort": "woman …; reference images: 1 the woman, 2 the car. Keep the guide video's composition and camera timing.",
  "negative": "no text, no watermark",
  "media": [
    { "role": "video_reference", "file": "guide.mp4" },
    { "role": "start_image", "file": "start.png" },
    { "role": "end_image", "file": "end.png" },
    { "role": "image_reference", "file": "refs/1-woman.png", "subject": "woman" },
    { "role": "image_reference", "file": "refs/2-car.jpg", "subject": "car" }
  ],
  "uses": {
    "restyle": ["video_reference", "image_reference"],
    "keyframes": ["start_image", "end_image", "image_reference"]
  }
}

From the director, pass bundle: true to render_video, with optional style, negative, placeholders, maxLength and refs: [{ subject, path }]. placeholders: true or false overrides the prompt's automatic blocking-placeholder choice; the command-line bundle accepts the same override as --placeholders true or --placeholders false. Reference paths must stay under the server's --root. The bundle is written as <out>/<name>/; the answer contains its paths and the parsed request.json, ready for an agent with access to a generation service.

{
  "name": "handoff",
  "seconds": 5,
  "bundle": true,
  "style": "cinematic, natural motion",
  "refs": [{ "subject": "woman", "path": "references/face.png" }]
}

bundle.json includes the engine version, the document and asset digests, the video's recording fields, the options used, and every payload file's byte count and SHA-256 (the manifest itself is excluded). The bundle adds no timestamp fields and no absolute reference-source paths. Text, stills, copied references and request data are byte-identical across runs on the same scene and inputs. Measured in Chrome with the software H.264 encoder, guide bytes are identical across processes up to 640 × 360; at 720p and above the browser's encoder output can vary between runs while frame count, fps, duration and dimensions stay equal. Only guide.mp4, video.bytes, and the guide entry's bytes and sha256 in bundle.json vary with that output. video.hardwareAcceleration records the encoder policy, normally prefer-software, and any other value is explicitly visible there and in the command result.

The destination is staged privately and renamed only when the video, stills, prompt, references, request, manifest and scene restoration have all succeeded. An existing non-empty folder requires --force (an empty folder is accepted), and force replaces only a version-1 bundle made by this tool with no entries outside the bundle layout. A destination that is or contains the current directory, scene file, --root or a reference image is refused before rendering, using real paths so symlinks count. The old bundle moves aside until the new one is published and is restored on failure. MCP overwrite: true follows the same rules. An error, SIGINT or SIGTERM leaves no partial folder and closes Chrome. The preset's duration, frame-count, geometry and 50 MiB errors are unchanged.

muxMp4 is the file writer on its own, and needs no browser: given encoded pictures in order ({ data, key }, the first a key frame), their size, rate and codec string, and for H.264 the decoder configuration record WebCodecs gives (decoderConfig.description under avc: { format: "avc" }), it returns the file's bytes as parts, the index first so the file plays while it downloads (new Blob(muxMp4(input), { type: "video/mp4" })).

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] }));

Live Director in an embedded scene

The application supplies intent batches on its own schedule. The runtime validates each batch synchronously, keeps up to 64 waiting batches per scene, and starts one at each drawing boundary. A receipt identifies the batch. Await applied(id) for its outcome.

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

const director = await createDirectorRuntime(scene, { tickHz: 1 });
const receipt = director.intents([
  { op: "animate", target: "item:hero", property: "position", to: [0, 1, 0], seconds: 0.9 },
]);
if (receipt.ok) {
  const outcome = await director.applied(receipt.id);
  console.log(outcome);
}

observation() returns an owned scene description or changes since the previous call, with scene events. Each packet is capped at 64 KiB of UTF-8. After a packet marked truncated, the next call attempts a full description. stop() cancels waiting intents. A successful backward seek stops the attached Director, so attach a new one to continue on the new branch.

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" | "webgpu" | "gpu" | "canvas" chooses what draws ASCII's characters and the effects' glyphs. "auto" (the default) uses WebGPU only when this scene already acquired a live device for Ray or Wireframe. A plain ASCII scene stays on WebGL2, then Canvas2D: it fetches no glyph WebGPU chunk and requests no device. "webgpu" explicitly requests WebGPU, with WebGL2 and Canvas2D fallbacks when unavailable or lost. "gpu" selects WebGL2 with Canvas2D fallback; "canvas" selects Canvas2D. Change it live with scene.glyphRenderer; reading it or stats().glyphRenderer reports "webgpu", "gpu" or "canvas". In ASCII, stats().backend identifies webgpu, webgl2 or canvas2d.

WebGPU glyphs load separately from Ray and share an existing Ray or Wireframe device. scene.ready and scene.capture() wait for the selected glyph pen’s preparation. The glyph atlas preserves coloured ink, transparency, draw order and integer pixel placement. Destroying a scene frees its glyph buffers, textures and canvas context; the last glyph-only user also releases the shared device. A device still owned by Ray remains available to other scenes. useGpu(false) makes the default glyph renderer use Canvas2D; an explicit "webgpu" or "gpu" overrides that default. Explicitly scaled effect glyphs retain their existing Canvas2D path. Standalone glyphPen() retains its WebGL2/Canvas2D default; { webgpu: true } opts into the same WebGPU preference.

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
volume null CSS hex colour
light 0 0–2

smoke

Parameter Default Range / choices
density 1 0–3
opacity 0.85 0–1
source objects objects, ground, pointer
volume null CSS hex colour
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

nebula

Parameter Default Range / choices
density 1 0–3
glow 1 0–4
dust 0.5 0–3
filaments 1 0–2
scale 1 0.25–4
speed 0.05 0–1
seed 1 0–9999
color #ff4fa3 CSS hex colour
color2 #7a5cff CSS hex colour
volume null 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