Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Docs: interactive learn pages for worlds, animation, media and performance

Nguyen Xuan Anad84f7b2a3ca
diff --git a/changes/docs-interactive-worlds-animate.md b/changes/docs-interactive-worlds-animate.md
new file mode 100644
index 00000000..ee26adf7
--- /dev/null
+++ b/changes/docs-interactive-worlds-animate.md
@@ -0,0 +1 @@
+- Rewrite 13 later documentation pages as interactive learn pages (terrain and ground textures, trees and grass, grass fields, wheeled vehicles, baked liquid, deterministic animation, animation curves and mixing, skeletal and morph animation, humanoid retargeting and crowds, recorded physics, assemblies and interaction, images and films, performance and memory). Each has live examples with sliders, play and pause or time scrubbing, a console that prints what calls return, an options table and common mistakes, and replaces the guide section with the same id. Performance and memory is now an optimisation guide with numbers from `bench/runtime` and dated measurements.
diff --git a/docs/learn/animation-curves-and-mixing.md b/docs/learn/animation-curves-and-mixing.md
new file mode 100644
index 00000000..0d5957a1
--- /dev/null
+++ b/docs/learn/animation-curves-and-mixing.md
@@ -0,0 +1,198 @@
+# Animation curves and mixing
+
+A track decides how a value moves between two keyframes. A mixer decides how several clips share the same parts. Both are deterministic: you give an absolute time and get the same pose every time.
+
+## Compare the curves
+
+Four balls travel the same distance in two seconds. From the back: `LINEAR`, `STEP`, `SMOOTH` and `CUBICSPLINE` with tangents that overshoot, then `LINEAR` with an `easeOutBack` easing. Drag the slider to scrub.
+
+```js live poster=animation-curves
+import { Renderer67, sphere, createAnimationClip, createAnimationPlayer, sampleAnimationClip } from '67js';
+
+// The docs frame shares the engine of the page, so take the typed arrays that the engine checks for. In your own project this line changes nothing.
+const { Float32Array, Uint16Array, Uint32Array } = window.parent;
+
+const modes = [
+ { name: 'LINEAR', interpolation: 'LINEAR' },
+ { name: 'STEP', interpolation: 'STEP' },
+ { name: 'SMOOTH', interpolation: 'SMOOTH' },
+ { name: 'CUBICSPLINE', interpolation: 'CUBICSPLINE' },
+ { name: 'LINEAR + easeOutBack', interpolation: 'LINEAR', easing: 'easeOutBack' },
+];
+
+const ball = sphere(40, 24);
+const parts = modes.map((mode, index) => ({
+ name: mode.name,
+ geometry: ball,
+ matrix: new Float32Array([0.28, 0, 0, 0, 0, 0.28, 0, 0, 0, 0, 0.28, 0, -2, 0.3, index * 0.8 - 1.6, 1]),
+ material: { color: [0.25 + index * 0.15, 0.55, 0.9 - index * 0.12], metallic: 0, roughness: 0.45 },
+}));
+
+const tracks = modes.map((mode, index) => {
+ const z = index * 0.8 - 1.6;
+ const keyframes = mode.interpolation === 'CUBICSPLINE'
+ ? [
+ { time: 0, value: [-2, 0.3, z], inTangent: [0, 0, 0], outTangent: [5, 0, 0] },
+ { time: 2, value: [2, 0.3, z], inTangent: [5, 0, 0], outTangent: [0, 0, 0] },
+ ]
+ : [
+ { time: 0, value: [-2, 0.3, z], ...(mode.easing ? { easing: mode.easing } : {}) },
+ { time: 2, value: [2, 0.3, z] },
+ ];
+ return { target: mode.name, property: 'translation', interpolation: mode.interpolation, keyframes };
+});
+const clip = createAnimationClip({ duration: 2, loop: true, tracks });
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, parts);
+const player = createAnimationPlayer(clip, parts);
+function draw(seconds) {
+ player.apply(seconds);
+ renderer.updateParts(parts);
+ renderer.render({ eye: [0, 5, 5.5], target: [0, 0, 0], fov: 40 });
+}
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:8px;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+const slider = document.createElement('input');
+slider.type = 'range';
+slider.min = 0;
+slider.max = 2;
+slider.step = 0.01;
+slider.value = 0;
+bar.append('time', slider);
+document.body.append(bar);
+
+function report(seconds) {
+ const x = sampleAnimationClip(clip, seconds).map(sample => `${sample.target} ${sample.value[0].toFixed(2)}`);
+ console.log(`t=${seconds.toFixed(2)}:`, x);
+}
+let playing = true;
+let seconds = 0;
+let last = performance.now();
+slider.addEventListener('input', () => { playing = false; seconds = Number(slider.value); draw(seconds); });
+slider.addEventListener('change', () => report(seconds));
+report(0.5);
+report(1);
+report(1.5);
+function frame(now) {
+ if (playing) {
+ seconds = (seconds + (now - last) / 1000) % 2;
+ slider.value = seconds;
+ draw(seconds);
+ }
+ last = now;
+ requestAnimationFrame(frame);
+}
+requestAnimationFrame(frame);
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+`STEP` jumps at the next keyframe, `SMOOTH` is smoothstep, and the spline overshoots because its tangents (units per second) are larger than the straight slope of 2 units per second. The eased ball runs past its end and returns.
+
+### Interpolation and easing
+
+`CUBICSPLINE` tracks need `inTangent` and `outTangent` on every keyframe, with at least two keyframes. Tangents are component changes per second, and quaternion tangents are component derivatives. Overshoot clamps emission to zero or more, metallic to `[0, 1]`, roughness to `[1e-8, 1]` and scale to `1e-8` or more. Translation keeps its overshoot.
+
+A keyframe on a `LINEAR` or `SMOOTH` track can carry `easing`. The value is `linear`, `cubic-bezier(x1, y1, x2, y2)` or `ease<In|Out|InOut><Family>`, where Family is Sine, Quad, Cubic, Quart, Quint, Expo, Circ, Back, Bounce or Elastic. `easeOutBack(3)` takes an overshoot and `easeOutElastic(1.5, 0.4)` an amplitude and period. An unknown name throws a `RangeError` that lists the valid forms. The [curve contract](https://github.com/codepawl/67.js/blob/main/docs/animation-curves.md) defines interpolation, overshoot constraints and retained player buffers.
+
+## Mix clips with fades
+
+`createAnimationMixer(parts)` captures the base pose of the named parts. Each clip becomes an action with `clipAction(clip)`. Press the buttons to schedule a crossfade between a slow wobble and a fast spin. The mixer is applied at absolute time, so the fade is the same when you seek.
+
+```js live poster=animation-mixer
+import { Renderer67, box, createAnimationClip, createAnimationMixer } from '67js';
+
+// The docs frame shares the engine of the page, so take the typed arrays that the engine checks for. In your own project this line changes nothing.
+const { Float32Array, Uint16Array, Uint32Array } = window.parent;
+
+const rotation = angle => [0, Math.sin(angle / 2), 0, Math.cos(angle / 2)];
+const part = { name: 'Blade', geometry: box(0.05, 4), matrix: new Float32Array([1.6, 0, 0, 0, 0, 0.25, 0, 0, 0, 0, 0.4, 0, 0, 0.6, 0, 1]), material: { color: [0.9, 0.5, 0.25], metallic: 0, roughness: 0.5 } };
+const parts = [part];
+
+const wobble = createAnimationClip({ duration: 2, loop: true, tracks: [
+ { target: 'Blade', property: 'rotation', interpolation: 'SMOOTH', keyframes: [
+ { time: 0, value: rotation(-0.4) }, { time: 1, value: rotation(0.4) }, { time: 2, value: rotation(-0.4) },
+ ] },
+] });
+const spin = createAnimationClip({ duration: 1, loop: true, tracks: [
+ { target: 'Blade', property: 'rotation', keyframes: [
+ { time: 0, value: rotation(0) }, { time: 0.5, value: rotation(Math.PI) }, { time: 1, value: rotation(Math.PI * 1.999) },
+ ] },
+] });
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, parts);
+const mixer = createAnimationMixer(parts);
+const wobbleAction = mixer.clipAction(wobble).play({ at: 0 });
+const spinAction = mixer.clipAction(spin);
+console.log('same clip, same action:', mixer.clipAction(wobble) === wobbleAction);
+
+let clock = 0;
+let last = performance.now();
+let blendedTo = 'wobble';
+
+// Controls must be authored in nondecreasing time order, so each crossfade starts at the current clock.
+function crossFadeTo(name) {
+ if (name === blendedTo) return;
+ const [from, to] = name === 'spin' ? [wobbleAction, spinAction] : [spinAction, wobbleAction];
+ mixer.crossFade(from, to, { at: clock, duration: 0.8 });
+ blendedTo = name;
+ console.log(`crossFade to ${name} at ${clock.toFixed(2)} s`);
+}
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:8px;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+for (const name of ['wobble', 'spin']) {
+ const button = document.createElement('button');
+ button.textContent = name;
+ button.addEventListener('click', () => crossFadeTo(name));
+ bar.append(button);
+}
+document.body.append(bar);
+
+let reportAt = 0;
+function frame(now) {
+ clock += (now - last) / 1000;
+ last = now;
+ mixer.apply(clock);
+ renderer.updateParts(parts);
+ renderer.render({ eye: [0, 2.2, 4.5], target: [0, 0.6, 0], fov: 40 });
+ if (clock > reportAt) {
+ reportAt = clock + 1;
+ const weights = [wobbleAction, spinAction].map(action => action.getState(clock).weight.toFixed(2));
+ console.log(`t=${clock.toFixed(1)} weights wobble/spin`, weights.join(' / '));
+ }
+ requestAnimationFrame(frame);
+}
+requestAnimationFrame(frame);
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+The [mixer contract](https://github.com/codepawl/67.js/blob/main/docs/animation-mixer.md) defines blending, ownership and control ordering.
+
+1. Create clips and bind their actions through `mixer.clipAction(clip)`.
+2. Author `play`, `fadeTo` or `crossFade` controls in nondecreasing time order.
+3. Call `mixer.apply(time)` for the desired absolute time.
+4. Upload the changed parts with `renderer.updateParts(parts)`.
+
+Playback can seek backward independently of control authoring order. The mixer owns its registered properties and captures their base values during binding.
+
+## Options
+
+| Call | Options | Meaning |
+| --- | --- | --- |
+| `action.play(...)` | `at`, `offset = 0`, `timeScale = 1`, `weight = 1` | Starts or restarts the action. A negative `timeScale` reverses it and zero holds a pose. |
+| `action.stop(at)` | time | Stops contributing from that time on. |
+| `action.fadeTo(weight, ...)` | `at`, `duration` | Fades from the weight at `at` to the target. |
+| `mixer.crossFade(from, to, ...)` | `at`, `duration` | Fades the source to 0 and the destination to 1; starts a stopped destination at local time 0. |
+| `action.getState(time)` | none | Returns `phase` (`scheduled`, `playing`, `fading`, `stopped`), `playing`, `weight` and `localTime`. |
+
+Weights are finite numbers in `[0, 1]`. When the total weight is below one, the base pose fills the rest. Above one, the clips are normalized by their total. Rotations blend by shortest-arc spherical interpolation in registration order, so three or more rotations can differ if you register the actions in another order.
+
+## Common mistakes
+
+- Authoring controls out of time order on the same action. They must not decrease.
+- Using `crossFade` and expecting the rest of the scene to freeze. A clip blends only the properties it has tracks for.
+- A weight above 1 or a zero fade duration. Both throw.
+- Mixing in a second place that writes the same matrices. The mixer owns the properties it registered.
diff --git a/docs/learn/assemblies-and-interaction.md b/docs/learn/assemblies-and-interaction.md
new file mode 100644
index 00000000..975d0633
--- /dev/null
+++ b/docs/learn/assemblies-and-interaction.md
@@ -0,0 +1,100 @@
+# Assemblies and interaction
+
+An assembly lets you take an object apart for inspection. Each part keeps its assembled matrix, and a frame field `assemblyAmount` from 0 to 1 pushes the parts out along their section offsets. The same maths is exported as `assemblyOffset`, so a viewer and an export agree.
+
+## Explode a model
+
+Three layers sit in a stack. Drag the slider to separate them, drag the picture to orbit, and use the wheel to zoom. The console prints each part's offset from `assemblyOffset`.
+
+```js live poster=assembly-explode
+import { Renderer67, box, assemblyOffset } from '67js';
+
+function placeAt(x, y, z, sx, sy, sz) {
+ return new Float32Array([sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, x, y, z, 1]);
+}
+const shape = box(0.04, 3);
+const parts = [
+ {
+ name: 'Frame', geometry: shape, matrix: placeAt(0, 0.4, 0, 2, 0.5, 1.2),
+ material: { color: [0.35, 0.4, 0.5], metallic: 0, roughness: 0.6 },
+ assembly: { layer: 'interior', section: 'Structural frame', offset: [0, -1.2, 0], detailOffset: [0, -0.2, 0] },
+ },
+ {
+ name: 'Battery', geometry: shape, matrix: placeAt(0, 0.9, 0, 1.2, 0.4, 0.8),
+ material: { color: [0.9, 0.7, 0.2], metallic: 0, roughness: 0.5 },
+ assembly: { layer: 'interior', section: 'Battery cassette', offset: [0, 0, 0], detailOffset: [0, 0.3, 0] },
+ },
+ {
+ name: 'Roof', geometry: shape, matrix: placeAt(0, 1.35, 0, 2.1, 0.12, 1.3),
+ material: { color: [0.85, 0.35, 0.25], metallic: 0, roughness: 0.4 },
+ assembly: { layer: 'exterior', section: 'Roof panel', offset: [0, 1.4, 0], detailOffset: [0, 0.3, 0] },
+ },
+];
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const renderer = new Renderer67(canvas, parts);
+const orbit = { yaw: 0.7, pitch: 0.4, distance: 7, amount: 0.6 };
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance + 0.8, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 0.8, 0], fov: 40, assemblyAmount: orbit.amount });
+}
+
+const slider = document.createElement('input');
+slider.type = 'range';
+slider.min = 0;
+slider.max = 1;
+slider.step = 0.01;
+slider.value = orbit.amount;
+slider.setAttribute('aria-label', 'Assembly amount');
+slider.style.cssText = 'position:fixed;left:8px;bottom:8px;width:40%';
+slider.addEventListener('input', () => { orbit.amount = Number(slider.value); draw(); });
+slider.addEventListener('change', () => {
+ for (const part of parts) console.log(`amount ${orbit.amount.toFixed(2)}`, part.name, assemblyOffset(part, orbit.amount));
+});
+document.body.append(slider);
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.01;
+ orbit.pitch = Math.min(1.4, Math.max(0.05, orbit.pitch + event.movementY * 0.01));
+ draw();
+});
+canvas.addEventListener('wheel', event => {
+ event.preventDefault();
+ orbit.distance = Math.min(14, Math.max(3, orbit.distance * Math.exp(event.deltaY * 0.001)));
+ draw();
+}, { passive: false });
+new ResizeObserver(() => { renderer.resize(); draw(); }).observe(canvas);
+for (const part of parts) console.log(part.name, 'offset at 1:', assemblyOffset(part, 1));
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+The scene is static, so the code draws only after input. It does not run an animation loop.
+
+## The assembly field
+
+Explodable parts carry `assembly: { layer, section, offset, detailOffset }`. Base matrices stay assembled. Section offsets separate first, and small detail offsets separate later in the amount range.
+
+| Field | Values | Meaning |
+| --- | --- | --- |
+| `layer` | `'exterior'` or `'interior'` | Lets you filter a layer out, for example to see inside. |
+| `section` | A known section name such as `Roof panel`, `Structural frame` or `Battery cassette` | Groups parts and sets the direction and lift of the section layout. An unknown section throws `No detail layout for assembly section`. |
+| `offset` | `[x, y, z]` | The section's travel at amount 1. |
+| `detailOffset` | `[x, y, z]` | The extra travel of a small detail, later in the range. |
+| frame `assemblyAmount` | 0 to 1 | How far apart the parts are. |
+
+`assemblyOffset(part, amount)` returns the same offset, so an exporter can write the exploded pose. Parts with an `assembly` are not culled.
+
+## Interaction checklist
+
+Filter parts by `layer` and recreate the renderer after disposing its predecessor. The object studio implements pointer capture for orbit, wheel zoom, keyboard arrows and a slider. Render only after a change when the scene is static. Use a `ResizeObserver` to call `resize()` and redraw. Offer keyboard controls and honor `prefers-reduced-motion`.
+
+## Common mistakes
+
+- Using a section name the layout does not know. Use the names from the object studio or add the layout in the source.
+- Changing a part's matrix to explode it. Keep the base matrix assembled and animate `assemblyAmount`.
+- Setting `touch-action` too late. Without `touchAction = 'none'` a finger drag scrolls the page instead of orbiting.
+- Hiding a layer by editing the list without rebuilding the renderer.
diff --git a/docs/learn/baked-liquid.md b/docs/learn/baked-liquid.md
new file mode 100644
index 00000000..d2268fa7
--- /dev/null
+++ b/docs/learn/baked-liquid.md
@@ -0,0 +1,223 @@
+# Baked liquid
+
+`67js/addons/spume` plays back liquid that the Spume GPU solver baked offline. It is available from version `0.10.0`. The browser does not simulate anything: it loads a cache of frames and shows the frame for a time, so scrubbing and looping are free.
+
+## Cache, frame, time
+
+The docs run with the core module only and cannot load a Spume cache, so this example bakes a tiny cache itself, packs every frame into int16 (the way Spume stores frames), and plays it back with a `partsAt(seconds)` function shaped like the addon's. Drag the slider to scrub. Tick Loop to wrap time instead of holding the last frame. The console prints the cache size, the frame index for a time and how long each `replaceParts` took.
+
+```js live poster=spume-playback
+import { Renderer67, sphere, box } from '67js';
+
+function random(seed) {
+ let value = seed >>> 0;
+ return () => {
+ value = (value * 1664525 + 1013904223) >>> 0;
+ return value / 4294967296;
+ };
+}
+
+// Bake: droplets leave a spout and bounce on the floor. Done once, offline in the real workflow.
+const fps = 30;
+const frameCount = 75;
+const dropletCount = 180;
+const next = random(5);
+const droplets = Array.from({ length: dropletCount }, () => ({
+ start: next() * 1.2,
+ velocity: [1.5 + next() * 2.2, 2.2 + next() * 2, (next() - 0.5) * 1.6],
+ position: null,
+ speed: null,
+}));
+const baked = [];
+for (let frame = 0; frame < frameCount; frame++) {
+ const time = frame / fps;
+ const positions = new Float32Array(dropletCount * 3);
+ droplets.forEach((droplet, index) => {
+ const age = Math.max(0, time - droplet.start);
+ let y = 1.4 + droplet.velocity[1] * age - 4.9 * age * age;
+ let bounces = 0;
+ let vy = droplet.velocity[1] - 9.8 * age;
+ while (y < 0.05 && bounces < 3) { y = 0.05 - (y - 0.05) * 0.45; vy = -vy * 0.45; bounces++; }
+ const x = -3 + droplet.velocity[0] * age;
+ const z = droplet.velocity[2] * age;
+ positions.set(age === 0 ? [-3, 1.4, 0] : [x, Math.max(0.05, y), z], index * 3);
+ });
+ baked.push(positions);
+}
+
+// Pack each frame over its own min..max box into int16, like Spume's frame files.
+function pack(positions) {
+ const low = [Infinity, Infinity, Infinity];
+ const high = [-Infinity, -Infinity, -Infinity];
+ for (let index = 0; index < positions.length; index++) {
+ low[index % 3] = Math.min(low[index % 3], positions[index]);
+ high[index % 3] = Math.max(high[index % 3], positions[index]);
+ }
+ const packed = new Int16Array(positions.length);
+ for (let index = 0; index < positions.length; index++) {
+ const span = high[index % 3] - low[index % 3] || 1;
+ packed[index] = Math.round(((positions[index] - low[index % 3]) / span - 0.5) * 65534);
+ }
+ return { packed, low, high };
+}
+function unpack({ packed, low, high }) {
+ const positions = new Float32Array(packed.length);
+ for (let index = 0; index < packed.length; index++) positions[index] = low[index % 3] + (packed[index] / 65534 + 0.5) * (high[index % 3] - low[index % 3]);
+ return positions;
+}
+const cache = baked.map(pack);
+const packedBytes = cache.reduce((sum, frame) => sum + frame.packed.byteLength, 0);
+const floatBytes = baked.reduce((sum, frame) => sum + frame.byteLength, 0);
+console.log(`cache: ${frameCount} frames at ${fps} fps, ${dropletCount} droplets, ${(packedBytes / 1024).toFixed(1)} KiB packed vs ${(floatBytes / 1024).toFixed(1)} KiB as floats`);
+
+const state = { loop: false };
+const duration = frameCount / fps;
+function frameIndexAt(seconds) {
+ const frame = Math.floor(seconds * fps);
+ return state.loop ? ((frame % frameCount) + frameCount) % frameCount : Math.min(frameCount - 1, Math.max(0, frame));
+}
+
+const decoded = new Map();
+function partsAt(seconds) {
+ const index = frameIndexAt(seconds);
+ if (!decoded.has(index)) {
+ decoded.set(index, unpack(cache[index]));
+ if (decoded.size > 4) decoded.delete(decoded.keys().next().value);
+ }
+ const positions = decoded.get(index);
+ return Array.from({ length: dropletCount }, (unused, droplet) => ({
+ name: `Droplet ${droplet}`,
+ geometry: dropletShape,
+ matrix: new Float32Array([0.07, 0, 0, 0, 0, 0.07, 0, 0, 0, 0, 0.07, 0, positions[droplet * 3], positions[droplet * 3 + 1], positions[droplet * 3 + 2], 1]),
+ material: dropletMaterial,
+ }));
+}
+
+const dropletShape = sphere(10, 8);
+const dropletMaterial = { color: [0.45, 0.78, 0.9], metallic: 0, roughness: 0.15 };
+const scenery = [{ name: 'Spout', geometry: box(0.08, 3), matrix: new Float32Array([0.5, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 0.5, 0, -3.3, 1.4, 0, 1]), material: { color: [0.5, 0.5, 0.55], metallic: 0.6, roughness: 0.4 } }];
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, [...scenery, ...partsAt(0)]);
+const timings = [];
+let seconds = 1;
+let playing = true;
+let last = performance.now();
+
+function draw() {
+ const start = performance.now();
+ renderer.replaceParts([...scenery, ...partsAt(seconds)]);
+ timings.push(performance.now() - start);
+ renderer.render({ eye: [0, 3, 8], target: [0, 0.8, 0], fov: 40 });
+}
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:10px;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+const toggle = document.createElement('button');
+toggle.textContent = 'Pause';
+const slider = document.createElement('input');
+slider.type = 'range';
+slider.min = 0;
+slider.max = duration;
+slider.step = 0.01;
+slider.value = seconds;
+const loopLabel = document.createElement('label');
+const loopBox = document.createElement('input');
+loopBox.type = 'checkbox';
+loopLabel.append(loopBox, 'loop');
+bar.append(toggle, slider, loopLabel);
+document.body.append(bar);
+toggle.addEventListener('click', () => { playing = !playing; toggle.textContent = playing ? 'Pause' : 'Play'; last = performance.now(); });
+loopBox.addEventListener('change', () => { state.loop = loopBox.checked; console.log('loop', state.loop); });
+slider.addEventListener('input', () => { playing = false; toggle.textContent = 'Play'; seconds = Number(slider.value); draw(); });
+slider.addEventListener('change', () => console.log(`t=${seconds.toFixed(2)} s -> frameIndexAt ${frameIndexAt(seconds)}`));
+
+let nextReport = 1;
+function frame(now) {
+ if (playing) {
+ seconds += (now - last) / 1000;
+ if (!state.loop) seconds = Math.min(seconds, duration);
+ else seconds %= duration;
+ slider.value = seconds % duration;
+ draw();
+ }
+ last = now;
+ if (playing && seconds >= nextReport) {
+ const average = timings.reduce((sum, value) => sum + value, 0) / timings.length;
+ console.log(`replaceParts averaged ${average.toFixed(2)} ms over ${timings.length} frames`);
+ timings.length = 0;
+ nextReport = seconds + 1;
+ }
+ requestAnimationFrame(frame);
+}
+new ResizeObserver(() => renderer.resize()).observe(canvas);
+requestAnimationFrame(frame);
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+The droplets are plain parts, replaced each frame. The real cache holds a liquid mesh per frame and whitewater points, and draws them with the `liquid` and `foam` materials that refract opaque parts.
+
+## Play a real cache
+
+1. Bake a cache folder with Spume's `run.py` or its Blender add-on.
+2. Load it with `loadSpumeCache(folderUrl)`.
+3. Create a player with `createSpumePlayer(cache, { matrix, loop })`.
+4. Each frame, call `renderer.replaceParts([...sceneParts, ...player.partsAt(seconds)])` and render.
+
+```bash
+uv run python run.py --out out/geyser --name geyser --pressure cg --iterations 20
+```
+
+A low-resolution check takes seconds after the first kernel compile: `uv run python run.py --out out/test --cell 0.2 --width 6 --height 12 --frames 40 --mesh-cell 0.25`. Units are metres with +Y up and the floor at y = 0, which matches 67js. Serve the output folder next to the page. It holds `meta.json`, one `frame_NNNN.glb` per frame and the whitewater files `spray.bin`, `spray_ids.bin` and `spray_kinds.bin`.
+
+```js
+import { Renderer67 } from '67js';
+import { loadSpumeCache, createSpumePlayer } from '67js/addons/spume';
+
+const cache = await loadSpumeCache('/caches/geyser/');
+const player = createSpumePlayer(cache, { matrix: placeAt(0, 0, 0), loop: true });
+console.log(player.frameCount, player.fps, player.duration);
+const renderer = new Renderer67(canvas, [...sceneParts, ...player.partsAt(0)]);
+function draw(seconds) {
+ renderer.replaceParts([...sceneParts, ...player.partsAt(seconds)]);
+ renderer.render({ eye, target });
+}
+```
+
+`loadSpumeCache(source)` accepts a folder URL or an `async (fileName) => ArrayBuffer | null` reader, so the same cache loads from a server, from disk in Node or from a dropped folder. It validates `meta.json`, reads every frame file and keeps frames int16-packed until they are played, which is about a fifth of the decoded size. The frame files are not general glTF: positions are int16 spread over each frame's own min..max box, so standard loaders, including `67js/addons/gltf`, read them at the wrong scale. Use `decodeSpumeFrame(bytes)` for one frame.
+
+Skinned and morphed parts may stay in the list unchanged while frames are replaced. Adding or removing them needs a new renderer. Textured parts can be added and removed once `import '@codepawlhq/67js/addons/replace-textured-parts'` has run. Without it they must stay unchanged. The addon deletes a texture when no part uses it any more and keeps one another part still binds.
+
+## Options
+
+| Member or option | Meaning |
+| --- | --- |
+| `partsAt(seconds)` | Parts for the frame shown at that time: the liquid mesh, plus whitewater when the frame has any. |
+| `partsForFrame(index)` | The same by frame number. |
+| `frameIndexAt(seconds)` | The frame number for a time, clamped or wrapped. |
+| `frameCount`, `fps`, `duration` | From `meta.json`. |
+| `matrix` | Default identity. Places the bake; positions are relative to the first opening's centre on the floor (`meta.origin`). |
+| `waterMaterial` | Default `DEFAULT_WATER_MATERIAL`, any rigid untextured material. The default uses the `liquid` tag with `color: [0.56, 0.84, 0.88]`. |
+| `sprayMaterial` | Default `DEFAULT_SPRAY_MATERIAL`. The default uses the `foam` tag, with per-point vertex colours for foam and bubbles. |
+| `spray` | Default `{ radius: 0.014, shutter: 1 / 60, kinds: ['spray', 'foam'], maxPoints: 12000 }`, or `null` for liquid only. Bubbles are hidden by default. |
+| `loop` | Default `false`. Wraps time instead of holding the last frame. |
+| `cachedFrames` | Default `4`. Decoded frames kept for reuse, so scrubbing over a few frames costs nothing after the first decode. |
+
+## Cost
+
+Measured on the slab bake (the README example at 10 cm cells, 60 frames, 79 thousand liquid particles, up to 12,177 liquid vertices and 12,000 droplets shown) on an RTX 3060 in Chrome: `replaceParts` with a fresh frame took 7 to 13 ms and the render about 0.5 ms. The cache is 7.1 MB of frames. Decoding a frame takes about 1.3 ms and building its droplets about 4.5 ms in Node. Lower `maxPoints` first when a large bake drops frames, and raise `cachedFrames` for scrubbing (docs/spume.md).
+
+## Limits
+
+- A liquid refracts only opaque parts, not other liquids or itself, and its thickness is an estimate for convex bodies.
+- Frames are shown as stored, without interpolation between them.
+- The addon does not run, schedule or cancel bakes. Bake with Spume's command line or its Blender add-on.
+
+The [Spume contract](https://github.com/codepawl/67.js/blob/main/docs/spume.md) covers the cache format, whitewater options, placement and measured cost.
+
+## Common mistakes
+
+- Loading a frame file with the glTF loader. The int16 packing needs `decodeSpumeFrame`.
+- Forgetting `loop: true` and wondering why the liquid freezes on the last frame.
+- Mixing the liquid with parts that change topology without a new renderer.
+- Leaving `maxPoints` high on a large bake. Lower it first.
diff --git a/docs/learn/deterministic-animation.md b/docs/learn/deterministic-animation.md
new file mode 100644
index 00000000..83cc09dc
--- /dev/null
+++ b/docs/learn/deterministic-animation.md
@@ -0,0 +1,138 @@
+# Deterministic animation
+
+An animation clip in 67js is data: tracks of keyframes that name a part and a property. A player turns a time in seconds into part transforms. It keeps no state between calls, so the same time always gives the same picture, and you can seek forward, backward or to a fixed time for an export.
+
+## Play, pause and scrub
+
+The cube moves along a smooth path and turns, and the sphere pulses and glows. Press Pause and drag the slider: the scene follows the time you set, in either direction. The console shows what `sampleAnimationClip` returns and proves that a seek back reproduces an earlier frame.
+
+```js live poster=deterministic-animation
+import { Renderer67, box, sphere, createAnimationClip, sampleAnimationClip, createAnimationPlayer } from '67js';
+
+// The docs frame shares the engine of the page, so take the typed arrays that the engine checks for. In your own project this line changes nothing.
+const { Float32Array, Uint16Array, Uint32Array } = window.parent;
+
+function placeAt(x, y, z, size) {
+ return new Float32Array([size, 0, 0, 0, 0, size, 0, 0, 0, 0, size, 0, x, y, z, 1]);
+}
+
+const parts = [
+ { name: 'Cube', geometry: box(0.06, 4), matrix: placeAt(-1.2, 0.5, 0, 0.9), material: { color: [0.9, 0.45, 0.2], metallic: 0, roughness: 0.5 } },
+ { name: 'Ball', geometry: sphere(48, 32), matrix: placeAt(1.2, 0.5, 0, 0.5), material: { color: [0.3, 0.6, 0.95], metallic: 0, roughness: 0.4, emission: 0 } },
+];
+
+const quarterTurn = angle => [0, Math.sin(angle / 2), 0, Math.cos(angle / 2)];
+const clip = createAnimationClip({
+ duration: 4,
+ loop: true,
+ tracks: [
+ { target: 'Cube', property: 'translation', interpolation: 'SMOOTH', keyframes: [
+ { time: 0, value: [-1.2, 0.5, 0] }, { time: 2, value: [-1.2, 1.6, 0.6] }, { time: 4, value: [-1.2, 0.5, 0] },
+ ] },
+ { target: 'Cube', property: 'rotation', interpolation: 'LINEAR', keyframes: [
+ { time: 0, value: quarterTurn(0) }, { time: 2, value: quarterTurn(Math.PI) }, { time: 4, value: quarterTurn(Math.PI * 1.999) },
+ ] },
+ { target: 'Ball', property: 'scale', interpolation: 'SMOOTH', keyframes: [
+ { time: 0, value: [0.5, 0.5, 0.5] }, { time: 2, value: [0.9, 0.9, 0.9] }, { time: 4, value: [0.5, 0.5, 0.5] },
+ ] },
+ { target: 'Ball', property: 'emission', interpolation: 'LINEAR', keyframes: [
+ { time: 0, value: 0 }, { time: 2, value: 1.5 }, { time: 4, value: 0 },
+ ] },
+ ],
+});
+
+console.log('samples at 1 s:', sampleAnimationClip(clip, 1).map(sample => `${sample.target}.${sample.property}`));
+console.log('Cube translation at 1 s:', sampleAnimationClip(clip, 1)[0].value);
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, parts);
+const player = createAnimationPlayer(clip, parts);
+
+function draw(seconds) {
+ player.apply(seconds);
+ renderer.updateParts(parts);
+ renderer.render({ eye: [0, 2.2, 6], target: [0, 0.8, 0], fov: 40, time: seconds });
+}
+
+// Seek forward, then back: absolute time gives the same matrix both ways.
+draw(1.5);
+const first = Array.from(parts[0].matrix);
+draw(3.2);
+draw(1.5);
+console.log('seek back reproduces the frame:', first.every((value, index) => value === parts[0].matrix[index]));
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:8px;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+const toggle = document.createElement('button');
+const slider = document.createElement('input');
+slider.type = 'range';
+slider.min = 0;
+slider.max = clip.duration;
+slider.step = 0.01;
+slider.value = 0;
+bar.append(toggle, slider);
+document.body.append(bar);
+
+let playing = true;
+let seconds = 0;
+let last = performance.now();
+toggle.textContent = 'Pause';
+toggle.addEventListener('click', () => {
+ playing = !playing;
+ toggle.textContent = playing ? 'Pause' : 'Play';
+ last = performance.now();
+});
+slider.addEventListener('input', () => {
+ playing = false;
+ toggle.textContent = 'Play';
+ seconds = Number(slider.value);
+ draw(seconds);
+});
+slider.addEventListener('change', () => console.log(`t = ${seconds.toFixed(2)} s, Ball scale`, sampleAnimationClip(clip, seconds)[2].value));
+
+function frame(now) {
+ if (playing) {
+ seconds = (seconds + (now - last) / 1000) % clip.duration;
+ slider.value = seconds;
+ draw(seconds);
+ }
+ last = now;
+ requestAnimationFrame(frame);
+}
+requestAnimationFrame(frame);
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+The loop keeps a time, calls `player.apply(seconds)` and uploads the changed matrices with `renderer.updateParts(parts)`. The slider calls the same `draw` with another time. Nothing in `draw` reads the previous frame.
+
+## Tracks
+
+A track names one part (`target`) and one `property`. Each target property can have one track. The keyframes are absolute values, not offsets.
+
+| Option | Values | Meaning |
+| --- | --- | --- |
+| `target` | A unique part name | The part that the track drives. |
+| `property` | `translation`, `rotation`, `scale`, `metallic`, `roughness`, `emission` | Rotation is a quaternion in XYZW order. Scale must stay positive. |
+| `interpolation` | `LINEAR` (default), `STEP`, `SMOOTH`, `CUBICSPLINE` | How values blend between keyframes. |
+| `keyframes` | `{ time, value }` | Times are in seconds, from 0 to the clip `duration`. |
+| keyframe `easing` | `easeOutBack`, `easeInOutCubic`, `cubic-bezier(...)` and the other names | Shapes the segment that starts at that keyframe. |
+| clip `loop` | `true` or `false` | A looping clip wraps the time; otherwise the time clamps to the ends. |
+
+Metallic and roughness stay within their material range (roughness above 0), and emission cannot be negative. [Animation curves and mixing](#animation-curves-and-mixing) covers the interpolation modes and easing in detail.
+
+## Sampling without parts
+
+`sampleAnimationClip(clip, time)` returns an array of `{ target, property, value }` and does not touch any part. Use it to read a value, to test a clip or to feed another system. `createAnimationPlayer(clip, parts)` does the binding once and then each `apply(time)` writes the matrices.
+
+## Playback and export
+
+Preserve the original part graph and apply absolute time, so seeking backwards reproduces the scene. Use `requestAnimationFrame` for playback and pause when the page is hidden. For an export, use a fixed sample time per frame instead of the wall clock, as the [images and films](#images-and-films) commands do.
+
+## Common mistakes
+
+- Two parts with the same name: the tracks cannot tell them apart, and the renderer refuses duplicate part objects.
+- Adding `dt` to the part matrix each frame. Apply an absolute time instead, or a pause and a seek will drift.
+- A rotation that is not a quaternion. Pass four numbers in XYZW order.
+- A scale of 0 or a negative scale. Keep scale above zero.
+- Easing on a `STEP` or `CUBICSPLINE` track. It throws a `RangeError`.
+- A keyframe time past `duration`. The clip refuses it.
diff --git a/docs/learn/grass-fields.md b/docs/learn/grass-fields.md
new file mode 100644
index 00000000..16001f36
--- /dev/null
+++ b/docs/learn/grass-fields.md
@@ -0,0 +1,203 @@
+# Grass fields
+
+`67js/addons/grass` is in the current source and not yet published. It covers terrain with clumped, curved blades in tiles, with distance level of detail. Each tile is one part and one draw, and a coarser level keeps a fixed subset of the same blades, so a tile that changes level does not reshuffle.
+
+## Tiles and levels of detail
+
+The docs run with the core module only, so this example draws flat blade strips by hand with the same tile rule as the addon: three levels that keep all, 35 percent and 12 percent of the blades, at up to 10 m, 26 m and 60 m, with wider blades farther out. Move the slider to walk the eye across the field and watch tiles change level. The console prints what `grass.stats()` would: tiles per level, triangles and an estimate of geometry bytes.
+
+```js live poster=grass-tiles
+import { Renderer67 } from '67js';
+
+function random(seed) {
+ let value = seed >>> 0;
+ return () => {
+ value = (value * 1664525 + 1013904223) >>> 0;
+ return value / 4294967296;
+ };
+}
+
+const fieldSize = 48;
+const tileSize = 4;
+const levels = [
+ { distance: 10, keep: 1, widthScale: 1 },
+ { distance: 26, keep: 0.35, widthScale: 2 },
+ { distance: 60, keep: 0.12, widthScale: 4.5 },
+];
+const density = 4;
+const bladesPerTile = Math.round(density * tileSize * tileSize);
+
+// One blade is a two-sided strip: a quad of two triangles, front and back.
+const blade = {
+ positions: new Float32Array([-0.5, 0, 0, 0.5, 0, 0, 0, 1, 0, -0.5, 0, 0, 0, 1, 0, 0.5, 0, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1]),
+ indices: new Uint32Array([0, 1, 2, 3, 4, 5]),
+};
+const triangles = 2;
+const material = { color: [0.3, 0.55, 0.16], metallic: 0, roughness: 0.8 };
+
+// Blades of a tile come from the tile's own seed, in a fixed order, so keeping the first N keeps the same blades.
+const tiles = [];
+for (let row = 0; row < fieldSize / tileSize; row++) {
+ for (let column = 0; column < fieldSize / tileSize; column++) {
+ const next = random(row * 1000 + column + 7);
+ const blades = Array.from({ length: bladesPerTile }, () => ({
+ x: -fieldSize / 2 + (column + next()) * tileSize,
+ z: -fieldSize / 2 + (row + next()) * tileSize,
+ yaw: next() * Math.PI,
+ height: 0.25 + next() * 0.3,
+ }));
+ tiles.push({ centerX: -fieldSize / 2 + (column + 0.5) * tileSize, centerZ: -fieldSize / 2 + (row + 0.5) * tileSize, blades, level: -1 });
+ }
+}
+
+function levelFor(tile, eyeX) {
+ const distance = Math.hypot(tile.centerX - eyeX, tile.centerZ);
+ const boundary = levels.findIndex(entry => distance < entry.distance);
+ const target = boundary === -1 ? levels.length : boundary;
+ // Hysteresis: a tile moves to a coarser level only when it is 10 percent past the boundary.
+ if (tile.level >= 0 && target > tile.level && distance < levels[tile.level].distance * 1.1) return tile.level;
+ return target;
+}
+
+function update(eyeX) {
+ let changed = false;
+ const stats = { tiles: [0, 0, 0], culled: 0, triangles: 0 };
+ for (const tile of tiles) {
+ const level = levelFor(tile, eyeX);
+ if (level !== tile.level) changed = true;
+ tile.level = level;
+ if (level >= levels.length) stats.culled++;
+ else {
+ stats.tiles[level]++;
+ stats.triangles += Math.ceil(bladesPerTile * levels[level].keep) * triangles;
+ }
+ }
+ stats.geometryBytes = stats.triangles * 3 * 24;
+ return { changed, stats };
+}
+
+function partsFor() {
+ const parts = [];
+ for (const [tileIndex, tile] of tiles.entries()) {
+ if (tile.level >= levels.length) continue;
+ const { keep, widthScale } = levels[tile.level];
+ for (const [bladeIndex, entry] of tile.blades.slice(0, Math.ceil(bladesPerTile * keep)).entries()) {
+ const c = Math.cos(entry.yaw);
+ const s = Math.sin(entry.yaw);
+ const width = 0.03 * widthScale;
+ parts.push({ name: `Blade ${tileIndex}-${bladeIndex}`, geometry: blade, material, matrix: new Float32Array([c * width, 0, -s * width, 0, 0, entry.height, 0, 0, s, 0, c, 0, entry.x, 0, entry.z, 1]) });
+ }
+ }
+ return parts;
+}
+
+const canvas = document.querySelector('#scene');
+let eyeX = -12;
+let { stats } = update(eyeX);
+console.log('tiles', tiles.length, 'blades per tile at full detail', bladesPerTile);
+console.log('stats()', stats);
+const renderer = new Renderer67(canvas, partsFor(), { world: true });
+
+function draw() {
+ renderer.render({ eye: [eyeX, 1.3, 0], target: [eyeX + 12, 0.3, 4], fov: 60, wind: 0.3 });
+}
+
+const slider = document.createElement('input');
+slider.type = 'range';
+slider.min = -16;
+slider.max = 16;
+slider.step = 0.5;
+slider.value = eyeX;
+slider.setAttribute('aria-label', 'Eye position along the field');
+slider.style.cssText = 'position:fixed;left:8px;bottom:8px;width:40%';
+slider.addEventListener('input', () => {
+ eyeX = Number(slider.value);
+ const result = update(eyeX);
+ if (result.changed) {
+ renderer.replaceParts(partsFor());
+ console.log('update(eye) = true', result.stats);
+ }
+ draw();
+});
+document.body.append(slider);
+new ResizeObserver(() => { renderer.resize(); draw(); }).observe(canvas);
+draw();
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+The `update` function returns `changed` the way `grass.update(eye)` returns `true`: rebuild the part list only then, not every frame.
+
+## Grow a real field
+
+1. Create the field with `createGrass({ preset, area, terrainHeight, mask, eye })`. Presets are `meadow`, `lawn`, `savanna` and `wild`.
+2. Add `grass.parts` to the renderer and pass `wind` in each frame.
+3. When `grass.update(eye)` returns true, call `renderer.replaceParts` with the new part list.
+
+```js
+import { Renderer67 } from '67js';
+import { createGrass } from '67js/addons/grass';
+
+const grass = createGrass({
+ preset: 'meadow',
+ area: { minX: -40, maxX: 40, minZ: -50, maxZ: 50 },
+ terrainHeight: terrain.heightAt,
+ mask: (x, z) => (Math.abs(x) < 1.5 ? 0 : 1),
+ eye,
+});
+const renderer = new Renderer67(canvas, [...terrain.parts, ...grass.parts], { world: true, memoryBudgetMiB: 512 });
+function draw(eye, seconds) {
+ if (grass.update(eye)) renderer.replaceParts([...terrain.parts, ...grass.parts]);
+ renderer.render({ eye, target, wind: 0.5, time: seconds });
+}
+console.log(grass.stats());
+```
+
+Tint the ground under the grass with `grass.groundColor`. On a splat terrain, darken every layer the grass covers, not only the grass layer, because soil under a sward sits in the blades' shade and a bright floor between blades is what makes a field look fake.
+
+## Options
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `area` | required | `{ minX, maxX, minZ, maxZ }` in metres. |
+| `preset` | `'meadow'` | `meadow`, `lawn`, `savanna` or `wild`. Every other option overrides it. |
+| `terrainHeight` | `() => 0` | Ground height at `(x, z)`. |
+| `mask` | none | Coverage from 0 to 1. Zero clears paths, and partial values thin and shorten the grass. |
+| `density` | from preset | Blades per square metre at full detail. |
+| `height`, `bend`, `width` | from preset | `[min, max]` blade height in metres, tip bend 0 to 1, root width in metres. |
+| `clumpSize`, `clumpStrength` | from preset | Clump cell size in metres and how strongly blades follow their clump. |
+| `dryness`, `patchiness`, `stalks` | from preset | Dry share, field-scale variation (0 gives an even field), seed stalk share (`lawn` has none). |
+| `base`, `tip`, `dry` | from preset | Linear RGB colours of the root, the green tip and the dry tip. |
+| `tileSize` | `4` | Tile edge in metres. Each tile is one part and one draw. |
+| `levels` | `GRASS_LEVELS` | Distance, kept share, segments and width scale per level. |
+| `cullDistance` | last level's distance | Tiles farther than this are dropped. |
+| `castShadow` | `false` | Blade shadows cost a full extra pass of every blade. Blades still receive shadows. |
+| `eye`, `seed` | area centre, `1` | Initial camera position and random seed. |
+
+`createGrass` returns `{ parts, update(eye), material, stats(), groundColor, settings }`. `stats()` returns tile counts per level, triangles, vertices and an estimate of geometry bytes. The default levels are 0 up to 10 m (all blades, 4 segments, 1x width), 1 from 10 to 26 m (35 percent, 2 segments, 2x) and 2 from 26 to 60 m (12 percent, one triangle, 4.5x).
+
+## Cost
+
+On the demo meadow (80 by 100 m, eye 1.3 m above the ground, RTX 3060, headless Chrome), an eye height of 1.3 m showed 344 tiles, 1.21 M triangles and about 94 MB of geometry, built in 3.0 s. At 7 m the field showed 316 tiles, 0.74 M triangles and about 61 MB, built in 2.1 s. Thin patches drop blades, so the default meadow builds about 12 percent faster than the same field with `patchiness: 0` (measured in Node). Set `memoryBudgetMiB` high enough for the grass geometry, and lower `density` or `cullDistance` for phones.
+
+## Clutter and baked light
+
+`67js/addons/clutter` is in the current source and not yet published. It scatters pebbles, rocks, twigs and fallen leaves over terrain in the same streamed tiles. Pick a `preset` (`meadow`, `forest`, `riverbed`, `scree`), pass `terrainHeight`, and add `clutter.parts` next to the grass. The [clutter contract](https://github.com/codepawl/67.js/blob/main/docs/clutter.md) lists options and budgets.
+
+`67js/addons/light-bake` is in the current source and not yet published. `bakeLightmaps(parts, lights, options)` ray traces the light that bounces between surfaces into a lightmap texture for each part, and returns new parts that draw it through the emissive map. Direct light stays live. The [light bake contract](https://github.com/codepawl/67.js/blob/main/docs/light-bake.md) lists the limits.
+
+## Limits
+
+- Blades are flat strips, so seen exactly edge-on they thin out.
+- Tiles change level with a pop, not a cross-fade.
+- Wind has one fixed direction, and there is no interaction with characters or vehicles.
+
+The [grass contract](https://github.com/codepawl/67.js/blob/main/docs/grass.md) lists options, levels, measured budgets and limits.
+
+## Common mistakes
+
+- Calling `replaceParts` every frame. Call it when `update(eye)` returns true.
+- Leaving `castShadow` on for a large field. It doubles the blade cost.
+- A `mask` that never reaches 0 on a path, so grass grows on it.
+- Forgetting to raise `memoryBudgetMiB` for a dense field.
+- Lighting the ground bright under the grass, so the gaps look like bare soil.
diff --git a/docs/learn/humanoid-retargeting-and-crowds.md b/docs/learn/humanoid-retargeting-and-crowds.md
new file mode 100644
index 00000000..83e2234f
--- /dev/null
+++ b/docs/learn/humanoid-retargeting-and-crowds.md
@@ -0,0 +1,211 @@
+# Humanoid retargeting and crowds
+
+`67js/addons/retarget` is available from version `0.10.0`. It moves a humanoid clip onto another skeleton and offsets many copies in time, so a crowd does not march in step.
+
+## One clip, many walkers
+
+The docs run with the core module only and cannot load a rigged character, so this example shows the part of the pipeline that matters for a crowd: one shared clip, and for every instance a seeded placement, a time offset and a playback rate. The clip only has rotations, so it plays on figures of any size, which is the same reason a retargeted clip works on another skeleton. Drag the slider to change the count. The console prints the first instances the way `createCrowd` reports them.
+
+```js live poster=crowd-walk
+import { Renderer67, box, sphere, createAnimationClip, sampleAnimationClip } from '67js';
+
+function random(seed) {
+ let value = seed >>> 0;
+ return () => {
+ value = (value * 1664525 + 1013904223) >>> 0;
+ return value / 4294967296;
+ };
+}
+const multiply = (a, b) => {
+ const out = new Float32Array(16);
+ for (let column = 0; column < 4; column++) {
+ for (let row = 0; row < 4; row++) {
+ let sum = 0;
+ for (let k = 0; k < 4; k++) sum += a[k * 4 + row] * b[column * 4 + k];
+ out[column * 4 + row] = sum;
+ }
+ }
+ return out;
+};
+const move = (x, y, z) => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]);
+const scale = (x, y, z) => new Float32Array([x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1]);
+const turnY = a => new Float32Array([Math.cos(a), 0, -Math.sin(a), 0, 0, 1, 0, 0, Math.sin(a), 0, Math.cos(a), 0, 0, 0, 0, 1]);
+function fromQuaternion([x, y, z, w]) {
+ return new Float32Array([
+ 1 - 2 * (y * y + z * z), 2 * (x * y + z * w), 2 * (x * z - y * w), 0,
+ 2 * (x * y - z * w), 1 - 2 * (x * x + z * z), 2 * (y * z + x * w), 0,
+ 2 * (x * z + y * w), 2 * (y * z - x * w), 1 - 2 * (x * x + y * y), 0,
+ 0, 0, 0, 1,
+ ]);
+}
+
+const swing = angle => [Math.sin(angle / 2), 0, 0, Math.cos(angle / 2)];
+const track = (target, phase) => ({
+ target, property: 'rotation', interpolation: 'SMOOTH',
+ keyframes: [{ time: 0, value: swing(0.7 * phase) }, { time: 0.5, value: swing(-0.7 * phase) }, { time: 1, value: swing(0.7 * phase) }],
+});
+const clip = createAnimationClip({ duration: 1, loop: true, tracks: [track('LegL', 1), track('LegR', -1), track('ArmL', -1), track('ArmR', 1)] });
+
+// createCrowd in the addon returns position, yawRadians, timeOffset, playbackRate and matrix per instance, deterministic for a seed.
+function createCrowd({ count, seed, columns, spacing, rateJitter = 0.15 }) {
+ const next = random(seed);
+ const instances = Array.from({ length: count }, (unused, index) => ({
+ position: [(index % columns - (columns - 1) / 2) * spacing, 0, (Math.floor(index / columns) - 1.5) * spacing],
+ yawRadians: (next() - 0.5) * 0.8,
+ timeOffset: next() * clip.duration,
+ playbackRate: 1 + (next() * 2 - 1) * rateJitter,
+ height: 0.9 + next() * 0.25,
+ shirt: Math.floor(next() * 4),
+ }));
+ return { instances, clipTime: (index, seconds) => (instances[index].timeOffset + seconds * instances[index].playbackRate) % clip.duration };
+}
+
+const shirts = [[0.8, 0.25, 0.2], [0.2, 0.5, 0.8], [0.9, 0.75, 0.2], [0.3, 0.65, 0.35]].map(color => ({ color, metallic: 0, roughness: 0.7 }));
+const skin = { color: [0.85, 0.65, 0.5], metallic: 0, roughness: 0.6 };
+const trousers = { color: [0.2, 0.22, 0.3], metallic: 0, roughness: 0.8 };
+const block = box(0.06, 2);
+const headShape = sphere(14, 10);
+const limbs = [
+ { name: 'ArmL', pivot: [0.33, 1.3, 0], size: [0.14, 0.6, 0.14] },
+ { name: 'ArmR', pivot: [-0.33, 1.3, 0], size: [0.14, 0.6, 0.14] },
+ { name: 'LegL', pivot: [0.13, 0.7, 0], size: [0.18, 0.7, 0.18] },
+ { name: 'LegR', pivot: [-0.13, 0.7, 0], size: [0.18, 0.7, 0.18] },
+];
+
+function buildParts(crowd) {
+ return crowd.instances.flatMap((instance, index) => [
+ { name: `P${index} torso`, geometry: block, matrix: scale(1, 1, 1), material: shirts[instance.shirt] },
+ { name: `P${index} head`, geometry: headShape, matrix: scale(1, 1, 1), material: skin },
+ ...limbs.map(limb => ({ name: `P${index} ${limb.name}`, geometry: block, matrix: scale(1, 1, 1), material: limb.name.startsWith('Leg') ? trousers : skin })),
+ ]);
+}
+
+function pose(parts, crowd, seconds) {
+ crowd.instances.forEach((instance, index) => {
+ const samples = sampleAnimationClip(clip, crowd.clipTime(index, seconds));
+ const frame = multiply(multiply(move(...instance.position), turnY(instance.yawRadians)), scale(instance.height, instance.height, instance.height));
+ const base = index * 6;
+ parts[base].matrix = multiply(frame, multiply(move(0, 1.0, 0), scale(0.5, 0.7, 0.28)));
+ parts[base + 1].matrix = multiply(frame, multiply(move(0, 1.55, 0), scale(0.18, 0.18, 0.18)));
+ limbs.forEach((limb, limbIndex) => {
+ const rotation = samples.find(sample => sample.target === limb.name).value;
+ parts[base + 2 + limbIndex].matrix = multiply(frame, multiply(move(...limb.pivot), multiply(fromQuaternion(rotation), multiply(move(0, -limb.size[1] / 2, 0), scale(...limb.size)))));
+ });
+ });
+}
+
+const canvas = document.querySelector('#scene');
+let crowd = createCrowd({ count: 24, seed: 7, columns: 6, spacing: 1.4 });
+let parts = buildParts(crowd);
+const renderer = new Renderer67(canvas, parts);
+console.log('first instances:', crowd.instances.slice(0, 3).map(instance => ({ timeOffset: instance.timeOffset, playbackRate: instance.playbackRate })));
+console.log('parts', parts.length, 'draws are batched by shared geometry and material');
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:10px;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+const slider = document.createElement('input');
+slider.type = 'range';
+slider.min = 6;
+slider.max = 60;
+slider.step = 6;
+slider.value = 24;
+slider.addEventListener('change', () => {
+ const count = Number(slider.value);
+ crowd = createCrowd({ count, seed: 7, columns: 6, spacing: 1.4 });
+ parts = buildParts(crowd);
+ renderer.replaceParts(parts);
+ console.log(`crowd of ${count}: ${parts.length} parts`);
+});
+bar.append('count', slider);
+document.body.append(bar);
+
+const started = performance.now();
+let nextReport = 2000;
+function frame(now) {
+ const elapsed = now - started;
+ const before = performance.now();
+ pose(parts, crowd, elapsed / 1000);
+ renderer.updateParts(parts);
+ renderer.render({ eye: [0, 5, 9], target: [0, 0.9, 0], fov: 42 });
+ if (elapsed > nextReport) {
+ console.log(`pose + upload + render: ${(performance.now() - before).toFixed(2)} ms for ${crowd.instances.length} walkers`);
+ nextReport = elapsed + 3000;
+ }
+ requestAnimationFrame(frame);
+}
+new ResizeObserver(() => renderer.resize()).observe(canvas);
+requestAnimationFrame(frame);
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+Every walker plays the same clip at its own time, so the legs are never in step. The pose code touches every instance each frame, which is the cost the GPU crowd path removes.
+
+## Retarget a real clip
+
+1. Build rigs with `createRigFromSkin(asset.skins[0])`. Name families (Mixamo, VRM, Unreal, Rigify, Quaternius) map through `mapHumanoidBones`. Fix a miss with `targetOverrides`.
+2. Call `retargetClip(sourceRig, targetRig, clip, { rootMotion })`.
+3. Play it with `createSkinClipPlayer(skin, clip).apply(seconds)`, then `renderer.updateParts(parts)`.
+4. For a crowd, `createCrowd({ count, clip, seed })` gives placement, time offsets and playback rates. For dozens or hundreds of animated instances, bake the clip once with `67js/addons/crowd-skinning`, so they draw as a few instanced batches. The plain path needs one skin pose per instance.
+
+```js
+import { mapHumanoidBones, createRigFromSkin, retargetClip, createSkinClipPlayer, createCrowd } from '67js/addons/retarget';
+import { createCrowdRig, bakeCrowdPalette, createCrowdParts } from '67js/addons/crowd-skinning'; // import it before the Renderer67 is made
+
+const source = createRigFromSkin(mixamoAsset.skins[0]);
+const target = createRigFromSkin(characterAsset.skins[0], { rootMatrix: armatureWorldMatrix });
+// asset.animations holds three.js clips; convert them first with clipFromGltfAnimation from 67js/addons/skeleton-pose.
+const clip = retargetClip(source, target, clipFromGltfAnimation(mixamoAsset.animations[0]), { rootMotion: false });
+console.log(mapHumanoidBones(jointNames, { overrides: { leftLowerLeg: 'shinbone_left' } }));
+
+const rig = createCrowdRig(asset.parts);
+const player = createSkinClipPlayer(characterAsset.skins[0], clip);
+const palette = bakeCrowdPalette(rig, seconds => player.apply(seconds), { duration: clip.duration, frameRate: 30 });
+const crowd = createCrowd({ count: 500, clip, seed: 7 });
+const set = createCrowdParts({ rig, palette, instances: crowd.instances });
+const renderer = new Renderer67(canvas, set.parts, options);
+// each frame:
+set.setTimes(index => crowd.clipTime(index, seconds));
+renderer.updateParts(set.parts);
+```
+
+## Options
+
+| Call | Option | Meaning |
+| --- | --- | --- |
+| `mapHumanoidBones(jointNames, { overrides })` | `overrides` | Returns `{ mapping, unmapped, missing }`. Pass `{ leftLowerLeg: 'shinbone_left' }` to fix a miss. |
+| `retargetClip(source, target, clip, options)` | `bones` | Default every shared bone: the canonical bones to transfer. |
+| | `rootMotion` | Default `true`. `false` removes horizontal hips travel and keeps vertical bob. |
+| | `scale` | Default `1`. Extra multiplier on the hips translation. |
+| | `frameRate` | Default `30`. Resampling rate; output keyframes are linear. |
+| | `sourceOverrides`, `targetOverrides` | Bone fixes, as in `mapHumanoidBones`. |
+| `createCrowd({ count, clip, seed, layout, spacing, columns, size, rateJitter, randomYaw })` | `layout` | `'grid'` (centred, `columns` wide) or `'scatter'` (rejection sampling with at least `0.75 * spacing` where room allows). |
+
+Each crowd instance has `position`, `yawRadians`, a `timeOffset` in the clip duration, a `playbackRate` within `1 ± rateJitter` and a column-major `matrix`. `clipTime(index, seconds)` gives the instance's clip time and `sample(seconds)` returns every instance's tracks.
+
+Canonical bone names are in `HUMANOID_BONES`: `hips`, `spine`, `chest`, `upperChest`, `neck`, `head`, then per side `leftShoulder`, `leftUpperArm`, `leftLowerArm`, `leftHand`, `leftUpperLeg`, `leftLowerLeg`, `leftFoot`, `leftToes`, plus optional fingers. `REQUIRED_HUMANOID_BONES` (hips, spine, head, both arms with hands, both legs with feet) must all be mapped, or a `RangeError` lists the `missingBones`.
+
+| Family | Examples |
+| --- | --- |
+| Mixamo | `mixamorig:Hips`, `mixamorig1:LeftUpLeg`; `Spine1` and `Spine2` are chest and upper chest |
+| VRM and Unity humanoid | `leftUpperArm`, `upperChest`, `J_Bip_L_UpperArm` |
+| Unreal mannequin | `pelvis`, `spine_01` to `spine_03`, `upperarm_l`, `thigh_l`, `calf_l` |
+| Blender and Rigify | `DEF-spine` is the pelvis, `DEF-upper_arm.L`, `DEF-thigh.L`; twist bones stay unmapped |
+| Quaternius | `Abdomen`, `Torso`, `UpperArm.L`, `Fist.L` |
+
+## Cost and limits
+
+`npm run benchmark:crowd` draws the CC0 RobotExpressive (19 parts, 3 materials, 187 joints, 29 baked frames, 7,214 vertices) walking at 1280 by 720, no multisampling, with a ground and one shadow map. On an RTX 3060, one run each, 10 frames, update and render included, 500 instances took a median of 5.75 ms (best 4.51) with joints and weights in two attributes, and 8.27 ms (best 6.44) with them packed in one attribute for maps and morph targets. The second run shared the card with other jobs, so read the two as a range of about 5 to 8 ms (docs/retarget.md). The plain path cost about 0.26 ms of JavaScript per instance on a synthetic 3,000-vertex chain, so about 50 instances fit 60 fps.
+
+- Both rigs face the same direction with +Y up, and both rest poses must be the bind pose.
+- The clip is resampled at `frameRate`, so cubic-spline and step curves are baked to linear keys. Source scale and non-hips translation tracks are ignored.
+- There is no IK, so different proportions can make feet slide or arms intersect the body.
+
+The [retarget contract](https://github.com/codepawl/67.js/blob/main/docs/retarget.md) covers rest-pose assumptions and measured cost. Mixamo clips need the owner's Adobe login to download. The code only consumes files.
+
+## Common mistakes
+
+- Mapping a rig with a missing required bone and not reading `missingBones`.
+- A source that faces the other way. Rotate its root first.
+- Hundreds of instances on the plain path. Bake with `crowd-skinning` instead.
+- Importing `crowd-skinning` after the renderer is created. Import it first.
+- A shared seed for every crowd, so all crowds look the same.
diff --git a/docs/learn/images-and-films.md b/docs/learn/images-and-films.md
new file mode 100644
index 00000000..157070f4
--- /dev/null
+++ b/docs/learn/images-and-films.md
@@ -0,0 +1,144 @@
+# Images and films
+
+67js turns a scene into a PNG or an MP4 from the repository checkout. The exporter renders in headless Chrome, plans the render size against a memory budget and sends each frame to FFmpeg. The commands run from a source checkout, not from an installed npm package.
+
+## Plan a render before you run it
+
+`planRenderSize` is the same budget planner that the exporter uses. Pick a preset, change the samples or turn on HDR and bloom, and watch the frame shrink when the estimated memory passes the budget. The console prints the plan. This example draws on a 2D canvas, so it costs no WebGL context.
+
+```js live poster=films-budget
+import { RENDER_PRESETS, planRenderSize, estimateFrameBytes } from '67js';
+
+const canvas = document.querySelector('#scene');
+const context = canvas.getContext('2d');
+const state = { preset: 'balanced', samples: 4, hdr: false, bloom: false, pixelRatio: 1 };
+const mebibyte = 1024 * 1024;
+
+function plan() {
+ const preset = RENDER_PRESETS[state.preset];
+ return planRenderSize({
+ width: preset.width,
+ height: preset.height,
+ pixelRatio: state.pixelRatio,
+ samples: state.samples,
+ memoryBudgetMiB: preset.memoryBudgetMiB,
+ hdr: state.hdr,
+ bloom: state.bloom,
+ });
+}
+
+function draw() {
+ const result = plan();
+ const preset = RENDER_PRESETS[state.preset];
+ const ratio = devicePixelRatio || 1;
+ canvas.width = Math.round(canvas.clientWidth * ratio);
+ canvas.height = Math.round(canvas.clientHeight * ratio);
+ context.setTransform(ratio, 0, 0, ratio, 0, 0);
+ const width = canvas.clientWidth;
+ const height = canvas.clientHeight;
+ context.fillStyle = '#101014';
+ context.fillRect(0, 0, width, height);
+ const scale = Math.min((width - 40) / (preset.width * state.pixelRatio), (height - 90) / (preset.height * state.pixelRatio));
+ const requestedWidth = preset.width * state.pixelRatio * scale;
+ const requestedHeight = preset.height * state.pixelRatio * scale;
+ context.strokeStyle = '#667';
+ context.setLineDash([5, 4]);
+ context.strokeRect(20, 20, requestedWidth, requestedHeight);
+ context.setLineDash([]);
+ context.fillStyle = result.reduced ? '#d98a4a' : '#4aa3d9';
+ context.fillRect(20, 20, result.width * scale, result.height * scale);
+ context.fillStyle = '#fff';
+ context.font = '13px system-ui';
+ context.fillText(`${result.width} x ${result.height}${result.reduced ? ' (reduced)' : ''}`, 30, 40);
+ const used = result.estimatedBytes / mebibyte;
+ context.fillText(`${used.toFixed(1)} of ${result.memoryBudgetMiB} MiB`, 30, 60);
+ context.fillStyle = '#334';
+ context.fillRect(20, height - 40, width - 40, 10);
+ context.fillStyle = used > result.memoryBudgetMiB * 0.95 ? '#d98a4a' : '#4aa3d9';
+ context.fillRect(20, height - 40, (width - 40) * Math.min(1, used / result.memoryBudgetMiB), 10);
+}
+
+function report() {
+ const result = plan();
+ console.log(`${state.preset}, ${state.samples} samples, hdr ${state.hdr}, bloom ${state.bloom}`);
+ console.log(result);
+ console.log('frame targets only, MiB:', estimateFrameBytes(result.width, result.height, state.samples, 2048, { hdr: state.hdr, bloom: state.bloom }) / mebibyte);
+}
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;top:8px;display:flex;gap:8px;flex-wrap:wrap;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+for (const name of Object.keys(RENDER_PRESETS)) {
+ const button = document.createElement('button');
+ button.textContent = name;
+ button.addEventListener('click', () => { state.preset = name; draw(); report(); });
+ bar.append(button);
+}
+const samples = document.createElement('input');
+samples.type = 'range';
+samples.min = 1;
+samples.max = 8;
+samples.step = 1;
+samples.value = state.samples;
+samples.addEventListener('input', () => { state.samples = Number(samples.value); draw(); });
+samples.addEventListener('change', report);
+bar.append('samples', samples);
+for (const key of ['hdr', 'bloom', 'doubleResolution']) {
+ const label = document.createElement('label');
+ const box = document.createElement('input');
+ box.type = 'checkbox';
+ box.addEventListener('change', () => { state[key] = box.checked; if (key === 'doubleResolution') state.pixelRatio = box.checked ? 2 : 1; draw(); report(); });
+ label.append(box, key);
+ bar.append(label);
+}
+document.body.append(bar);
+new ResizeObserver(draw).observe(canvas);
+draw();
+report();
+```
+
+The planner counts geometry, textures and mipmaps, shadows, MSAA, HDR, bloom and one capture staging frame, and it reduces the render dimensions when it must. This is an estimated allocation budget, not a hard process RAM or VRAM cap. Driver and browser allocations can still fail, and sampled browser JS heap and Node RSS do not measure total graphics memory.
+
+## Render from the command line
+
+```sh
+npm run render -- --scene motion --kind image --backend gpu --time 3 --output artifacts/frame.png
+npm run render -- --scene motion --kind video --backend gpu --encoder cpu --preset balanced --duration 12 --fps 24 --memory 384 --output artifacts/film.mp4
+npm run render -- --scene motion --kind video --backend cpu --preset cpu --aspect portrait --duration 2 --output artifacts/cpu-trial.mp4
+```
+
+Install the checkout's dependencies and provide Chrome and FFmpeg. The exporter reports missing tools. On Windows it uses Chrome's standard install path and `~/.local/bin/ffmpeg.exe`.
+
+| Option | Values | Meaning |
+| --- | --- | --- |
+| `--scene` | `object`, `nature`, `film`, `motion`, `view2d`, `assets` | The scene to render. `--asset path/model.glb` goes with `assets`. |
+| `--kind` | `image`, `video` | A PNG or an MP4. |
+| `--backend` | `gpu`, `cpu` | GPU rasterization or the CPU path. |
+| `--encoder` | `gpu`, `cpu` | `gpu` needs NVENC. GPU rasterization and GPU encoding are independent. |
+| `--preset` | `preview`, `balanced`, `high`, `cpu` | Dimensions, samples, fps and memory (table below). |
+| `--aspect` | `landscape`, `portrait`, `square` | The frame shape. |
+| `--width`, `--height` | numbers | Set dimensions. Video needs even values. |
+| `--time`, `--duration`, `--fps`, `--start` | seconds, frames per second | One frame time, a video length and a range start. |
+| `--memory` | MiB | The memory budget for the plan. |
+| `--assembly 1` | 0 to 1 | Renders an exploded object for inspection. |
+| `--audio` | file | Selects original film audio. Other scenes default to silent. |
+
+The presets come from `RENDER_PRESETS`:
+
+| Preset | Size | Samples | fps | Budget |
+| --- | --- | --- | --- | --- |
+| `preview` | 960 x 540 | 2 | 24 | 256 MiB |
+| `balanced` | 1280 x 720 | 4 | 24 | 384 MiB |
+| `high` | 1920 x 1080 | 4 | 24 | 512 MiB |
+| `cpu` | 640 x 360 | 1 | 12 | 192 MiB |
+
+The exporter keeps one pending capture and respects encoder backpressure, so memory does not grow with the length of a film.
+
+Export one short trial before a full film. Inspect the output JSON and FFprobe for backend, dimensions, duration, frame count and audio.
+
+## Common mistakes
+
+- Running `npm run render` from an installed package. The commands live in the checkout.
+- Odd video dimensions. Use even `--width` and `--height`.
+- Asking for `--encoder gpu` on a machine without NVENC. Use `--encoder cpu`.
+- Starting several GPU exports at once. They compete for the same card.
+- Skipping the trial. Check a 2 second clip first, then render the full film.
diff --git a/docs/learn/performance-and-memory.md b/docs/learn/performance-and-memory.md
new file mode 100644
index 00000000..62597389
--- /dev/null
+++ b/docs/learn/performance-and-memory.md
@@ -0,0 +1,183 @@
+# Performance and memory
+
+A frame costs CPU time to prepare and GPU time to draw. Most wins come from drawing less: fewer draw calls, fewer triangles, fewer pixels and fewer render targets. This page covers what 67js does for you, what you control, and how to measure it. Every number below comes from the repository's own benchmarks, with the date and the conditions, and your machine will differ.
+
+## Measure first
+
+Time a frame on your own machine before you change anything. Reading one pixel back with `readPixels` waits for the GPU, so a loop around it includes the draw work and not only the CPU. Press a button to rebuild the scene in a mode and read the averages in the console.
+
+```js live poster=performance-batching
+import { Renderer67, box, sphere } from '67js';
+
+const canvas = document.querySelector('#scene');
+const count = 400;
+const material = { color: [0.4, 0.6, 0.85], metallic: 0, roughness: 0.5 };
+
+function makeParts(sharedGeometry) {
+ const shared = sharedGeometry ? box(0.05, 2) : null;
+ return Array.from({ length: count }, (unused, index) => {
+ const x = (index % 20 - 9.5) * 0.5;
+ const z = (Math.floor(index / 20) - 9.5) * 0.5;
+ return {
+ name: `Box ${index}`,
+ geometry: shared ?? box(0.05, 2),
+ matrix: new Float32Array([0.3, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 0.3, 0, x, 0.2, z, 1]),
+ material,
+ };
+ });
+}
+
+let renderer = null;
+let timer = 0;
+const pixel = new Uint8Array(4);
+// Reading a pixel back waits until the GPU has finished the frame.
+function forceGpu() {
+ const context = renderer.context;
+ context.readPixels(0, 0, 1, 1, context.RGBA, context.UNSIGNED_BYTE, pixel);
+}
+function setup(label, sharedGeometry, batching) {
+ clearInterval(timer);
+ renderer?.dispose();
+ const parts = makeParts(sharedGeometry);
+ renderer = new Renderer67(canvas, parts, { batching });
+ const view = { eye: [0, 7, 9], target: [0, 0, 0], fov: 45 };
+ renderer.render(view);
+ forceGpu();
+ const samples = [];
+ for (let frame = 0; frame < 30; frame++) {
+ const start = performance.now();
+ renderer.render(view);
+ forceGpu();
+ samples.push(performance.now() - start);
+ }
+ samples.sort((first, second) => first - second);
+ console.log(`${label}: median ${samples[15].toFixed(2)} ms, min ${samples[0].toFixed(2)}, max ${samples[29].toFixed(2)} (30 frames, ${count} parts)`);
+ console.log(` render targets: ${renderer.memoryReport().totalMegabytes} MB`);
+ timer = setInterval(() => renderer.render(view), 1000 / 30);
+}
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:8px;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+for (const [label, shared, batching] of [['shared geometry', true, true], ['one geometry per part', false, true], ['batching off', true, false]]) {
+ const button = document.createElement('button');
+ button.textContent = label;
+ button.addEventListener('click', () => setup(label, shared, batching));
+ bar.append(button);
+}
+document.body.append(bar);
+new ResizeObserver(() => renderer?.resize()).observe(canvas);
+setup('shared geometry', true, true);
+addEventListener('pagehide', () => { clearInterval(timer); renderer?.dispose(); });
+```
+
+The numbers depend on your GPU and on what else it is drawing. The goal is to see the order of magnitude and to compare modes on one machine, not to read an absolute value. Read a range, not one run.
+
+## Draw calls, batching and instancing
+
+Parts that share a geometry and a material go into one batch, and a batch is one instanced draw. The renderer batches by default (`batching: true`). A scene of 1,000 boxes with one geometry is one draw, and 1,000 boxes that each own a geometry is 1,000 draws. So build a geometry once with `box`, `sphere`, `cylinder` or `torus` and reuse the object for every part, and share material objects when parts look the same.
+
+The benchmark `instanced-objects` (bench/runtime/README.md, measured twice on 2026-11-04 at 960 by 540 with 4 samples) shows the effect. On an RTX 3060, 67js took 0.83 to 1.04 ms per frame and three.js with separate meshes took 2.44 to 2.61 ms. A three.js `InstancedMesh` took 0.25 ms, so an engine-level instance buffer is still faster than batching. On SwiftShader, the CPU path an agent uses, the same scene took 104 to 119 ms in 67js and 34 to 35 ms in three.js. The GPU was shared with other jobs during the runs, so the RTX numbers are noisy.
+
+Move existing transforms with `renderer.updateParts(parts)`. Adding or removing parts needs `replaceParts`, and an unchanged identity set is cheaper. Do not create a renderer per frame.
+
+## Culling and levels of detail
+
+Culling is on by default. Each frame the renderer tests every instance of a batch against the six view planes using its bounding sphere, and draws only the instances that touch the frustum. Skinned and morphed parts, parts with an `assembly`, alpha-blended and `liquid` passes are not culled, and the shadow passes draw every caster. Pass `culling: false` to compare pictures.
+
+Levels of detail swap a mesh for a coarser one by pixel error. Give a part `lods`, the array from `generateGeometryLods(geometry, { ratios: [0.25, 0.06] })`, with level 0 equal to the part's own geometry. An instance takes the coarsest level whose error covers at most `lodPixelError` pixels (default 1).
+
+```js
+const levels = generateGeometryLods(rock, { ratios: [0.25, 0.06] });
+const parts = positions.map((position, index) => ({ name: `rock-${index}`, geometry: rock, lods: levels, matrix: translate(position), material }));
+const renderer = new Renderer67(canvas, parts, { lodPixelError: 1 });
+```
+
+The scene `large-outdoor` (6,000 spheres of about 1,000 triangles over 600 by 600 units, seen from the edge, 960 by 540, measured on 2026-10-31) shows what this saves:
+
+| Mode | RTX 3060 frame (ms) | Triangles | SwiftShader frame (ms) |
+| --- | --- | --- | --- |
+| No culling, no levels | 8.41 | 5,760,014 | 4,428 |
+| Culling only | 7.68 | 4,359,374 | 4,061 |
+| Culling and levels | 1.55 | 270,474 | 517 |
+| three.js, per-mesh culling | 6.00 | 4,359,372 | 944 |
+
+Culling alone gives the same picture pixel for pixel. Levels change 1.9 percent of the pixels by more than 8 levels out of 255. The GPU was shared with other jobs (1 to 87 percent busy), so the GPU column is noisy. [Culling, levels and adaptive resolution](https://github.com/codepawl/67.js/blob/main/docs/culling-lod.md) holds the contract. Vegetation chooses its own levels by distance with `selectLevels`, and can fade between them.
+
+## Shadow cost and render targets
+
+Shadows and post effects are the biggest fixed memory in a frame. At 960 by 540 with 4 samples, a plain lit scene held these render targets (`renderer.memoryReport()`, measured 2026-11-04): a 2048 by 2048 `shadowMap` of 16 MB, `multisampleColor` 15.82 MB, `multisampleDepth` 3.96 MB and `frameColor` 3.96 MB, 41.36 MB in all. At 1920 by 1080 the total was 110.92 MB, and the multisampled colour alone was 63.28 MB, 57 percent of it.
+
+What you can do about it:
+
+- A scene with no shadow caster allocates a one texel shadow map instead of 16 MB. Bloom, ambient occlusion, cascades and the point light atlas allocate only when used.
+- Fewer samples cut the largest target. `samples: 2` halves the multisampled colour.
+- With `shadowCascades` on, a scene also holds the cascade array (48 MB for three 2048 slices). A scene that does not need cascades should leave them off. A scene wider than 40 m gets three cascades by default because one map would cover more than 80 m, so a texel would be 4 cm or wider; set `shadowCascades: 0` to keep the single map.
+- The opt-in addon `useCompactColor(renderer)` from `67js/addons/compact-color` stores the frame and multisample colour as R11F_G11F_B10F. At 1920 by 1080, 110.92 MB became 71.37 MB, 39.55 MB less. The 26 reference pictures differ from the default by a mean FLIP of 0.002 to 0.030 (median 0.021), so it changes pixels slightly.
+
+Rebuild a renderer with other options and read the totals yourself. This example swaps samples and shadows, disposes the old renderer, and prints the new target list.
+
+```js live poster=performance-memory
+import { Renderer67, box, sphere, estimateFrameBytes } from '67js';
+
+const canvas = document.querySelector('#scene');
+const parts = [
+ { name: 'Ball', geometry: sphere(48, 32), matrix: new Float32Array([0.8, 0, 0, 0, 0, 0.8, 0, 0, 0, 0, 0.8, 0, 0, 0.8, 0, 1]), material: { color: [0.9, 0.5, 0.3], metallic: 0, roughness: 0.4 } },
+ { name: 'Pillar', geometry: box(0.05, 3), matrix: new Float32Array([0.5, 0, 0, 0, 0, 1.6, 0, 0, 0, 0, 0.5, 0, 1.6, 0.8, 0, 1]), material: { color: [0.4, 0.6, 0.85], metallic: 0, roughness: 0.5 } },
+];
+
+let renderer = null;
+function rebuild(samples, hdr) {
+ renderer?.dispose();
+ renderer = new Renderer67(canvas, parts, { samples, hdr });
+ renderer.render({ eye: [0, 2.2, 6], target: [0, 0.8, 0], fov: 40 });
+ const report = renderer.memoryReport();
+ console.log(`samples ${samples}, hdr ${hdr}: ${report.totalMegabytes} MB in ${report.targets.length} targets`);
+ for (const target of report.targets) console.log(` ${target.name} ${target.width ?? ''}x${target.height ?? ''} ${(target.bytes / 1e6).toFixed(2)} MB`);
+ const estimate = estimateFrameBytes(canvas.width, canvas.height, samples, 2048, { hdr });
+ console.log(`estimateFrameBytes at ${canvas.width}x${canvas.height}: ${(estimate / 1e6).toFixed(2)} MB`);
+}
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:8px;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+for (const [samples, hdr] of [[1, false], [2, false], [4, false], [4, true]]) {
+ const button = document.createElement('button');
+ button.textContent = `${samples} samples${hdr ? ' + hdr' : ''}`;
+ button.addEventListener('click', () => rebuild(samples, hdr));
+ bar.append(button);
+}
+document.body.append(bar);
+rebuild(4, false);
+addEventListener('pagehide', () => renderer?.dispose());
+```
+
+## Textures and KTX2
+
+Reuse decoded textures and never decode the same image twice. A texture is stored as RGBA8 with a mip chain, which is a third more than the base level, so a 2K map takes about 22 MB. A KTX2 file keeps the texture GPU-compressed. When your KTX2 loader transcodes to BC7, BC1, BC3, ASTC 4x4 or ETC2, the renderer uploads each mip with `compressedTexSubImage2D`, and a 2K map takes about a quarter of the memory of RGBA8 (change 304). `ktx2WorkerConfigFor(context)` from `67js/addons/gltf` gives the loader the formats that the context accepts, and the loader falls back to RGBA8 where the GPU takes none. Large glTF texture sets are scaled down at load when they pass `maxTexturePixels`: 40 maps of 1024 px load as 512 px with the default options. `bench/ktx2/measure.mjs` measures the upload with a Khronos sample asset; run it yourself for numbers on your GPU.
+
+## Adaptive quality
+
+When the frame budget is the constraint, lower the resolution before the scene. `createGpuTimer(context)` from `src/adaptive-quality.js` wraps `EXT_disjoint_timer_query_webgl2`. Pass the function as the `createGpuTimer` option and the renderer times each frame, and `renderer.gpuMilliseconds` holds the latest finished result (a few frames late, or `null` after a disjoint measurement). `createAdaptiveResolution({ targetMilliseconds, minimumScale, step, window })` returns a controller. Feed it each frame time with `update(milliseconds)` and multiply the pixel ratio by the scale it returns. It lowers the scale by one `step` when the average of `window` frames is over the target, raises it only after a whole window under 0.6 of the target, and stays at or above `minimumScale` (default 0.5). `createAdaptiveResolution({ exporting: true })` throws, because exports keep full quality.
+
+## Release memory
+
+`renderer.dispose()` deletes the buffers, textures, programs and render targets that the renderer owns. Call it when a scene goes away, on `pagehide`, and before you build a new renderer for the same canvas. Dispose loaders and decoders yourself (`draco.dispose()`, `ktx2.dispose()`), and call `physics.dispose()` for a recorded physics scene. A texture added through `replace-textured-parts` is deleted when no part uses it any more.
+
+## Guidance
+
+Reuse geometry and decoded textures. Do not create a renderer per frame. Change existing transforms through `updateParts`. Lower scene detail before you increase the budget.
+
+Pause hidden scenes and avoid simultaneous GPU exports. For static previews, redraw on demand rather than looping.
+
+The planner includes geometry, textures and mipmaps, shadows, MSAA, HDR, bloom and one capture staging frame, and reduces render dimensions when necessary. The exporter keeps one pending capture and respects encoder backpressure. This is an estimated allocation budget, not a hard process RAM or VRAM cap. Driver and browser allocations can still fail, and sampled browser JS heap and Node RSS do not measure total graphics memory.
+
+## Where three.js still wins
+
+Be honest about the comparison. On 2026-11-04 (two runs, 960 by 540) three.js had the faster full frame on SwiftShader in all seven benchmark scenes and on the RTX 3060 in five of seven, and a faster first frame in all seven. 67js drew `instanced-objects` and `moving-shadows` faster than three.js with separate meshes. Run `npm run benchmark:runtime` for your own numbers; it takes about 8 minutes and needs Chrome and a GPU.
+
+## Common mistakes
+
+- Creating a new geometry per part when the shape is the same. It defeats batching.
+- Measuring with `performance.now()` around `render()` alone. Without a pixel read-back or the GPU timer you time only the CPU.
+- Quoting a number from one noisy run. Compare modes on one machine, as a range.
+- Leaving shadow cascades or bloom on for a small scene.
+- Never calling `dispose()`, so WebGL contexts and GPU memory pile up across navigations.
diff --git a/docs/learn/recorded-physics.md b/docs/learn/recorded-physics.md
new file mode 100644
index 00000000..ccbc0f09
--- /dev/null
+++ b/docs/learn/recorded-physics.md
@@ -0,0 +1,218 @@
+# Recorded physics
+
+`67js/addons/physics` bakes rigid-body motion into a timeline with the Rapier 3D solver. Playback samples that recording at an absolute time and never runs the solver again, so you can seek forward and backward and get the same pose. It is available from version `0.4.0`, and the main renderer does not need Rapier for playback.
+
+## Bake once, seek anywhere
+
+Rapier is an optional peer dependency and is not loaded in the docs, so this example bakes a ball and a crate with a tiny hand-written integrator and then plays the recording the same way: one pose per body per frame, seven floats each, sampled at an absolute time. Drag the slider back and forth, and tick a time in the middle of a bounce to see the interpolation. The console prints the plan, the bake time, the contact ticks, and the lowest height of the ball between frames.
+
+```js live poster=physics-recording
+import { Renderer67, sphere, box } from '67js';
+
+// A plan before the bake: frames x bodies x 7 floats x 4 bytes, like planPhysicsScene's timelineBytes.
+const frameCount = 361;
+const timestep = 1 / 60;
+const bodyNames = ['ball', 'crate'];
+const duration = (frameCount - 1) * timestep;
+console.log('plan:', { frameCount, timestep, duration, timelineBytes: frameCount * bodyNames.length * 7 * 4 });
+
+// Bake: gravity, a bounce on the floor (y = 0) and a kick at tick 120, like { tick: 120, body: 'ball', impulse }.
+const radius = 0.4;
+const events = [{ tick: 120, body: 'ball', impulse: [3, 3, 0] }];
+const contacts = [];
+const timeline = new Float32Array(frameCount * bodyNames.length * 7);
+const bakeStart = performance.now();
+const ball = { position: [-3, 4, 0], velocity: [0, 0, 0] };
+const crate = { position: [1.5, 0.35, 0], velocity: [-1.2, 0, 0] };
+for (let frame = 0; frame < frameCount; frame++) {
+ const ballAngle = -(ball.position[0] + 3) / radius;
+ const crateYaw = (crate.position[0] - 1.5) * 0.1;
+ timeline.set([...ball.position, 0, 0, Math.sin(ballAngle / 2), Math.cos(ballAngle / 2)], (frame * 2) * 7);
+ timeline.set([...crate.position, 0, Math.sin(crateYaw / 2), 0, Math.cos(crateYaw / 2)], (frame * 2 + 1) * 7);
+ for (const event of events) {
+ if (event.tick === frame) ball.velocity = ball.velocity.map((value, axis) => value + event.impulse[axis]);
+ }
+ ball.velocity[1] -= 9.81 * timestep;
+ ball.position = ball.position.map((value, axis) => value + ball.velocity[axis] * timestep);
+ if (ball.position[1] < radius && ball.velocity[1] < 0) {
+ ball.position[1] = radius;
+ ball.velocity[1] *= -0.62;
+ ball.velocity[0] *= 0.99;
+ contacts.push(frame);
+ }
+ crate.velocity[0] *= 0.985;
+ crate.position[0] += crate.velocity[0] * timestep;
+}
+console.log(`baked ${frameCount} frames in ${(performance.now() - bakeStart).toFixed(1)} ms; contact ticks:`, contacts.slice(0, 8));
+
+// Sampling: clamp time, linear translation, normalized shortest-arc quaternion, into a retained output.
+function sample(time, out) {
+ const clamped = Math.min(duration, Math.max(0, time));
+ const exact = clamped / timestep;
+ const first = Math.min(frameCount - 2, Math.floor(exact));
+ const blend = exact - first;
+ for (let body = 0; body < bodyNames.length; body++) {
+ const a = (first * bodyNames.length + body) * 7;
+ const b = ((first + 1) * bodyNames.length + body) * 7;
+ for (let index = 0; index < 3; index++) out[body * 7 + index] = timeline[a + index] + (timeline[b + index] - timeline[a + index]) * blend;
+ let dot = 0;
+ for (let index = 3; index < 7; index++) dot += timeline[a + index] * timeline[b + index];
+ const direction = dot < 0 ? -1 : 1;
+ let length = 0;
+ for (let index = 3; index < 7; index++) {
+ out[body * 7 + index] = timeline[a + index] + (direction * timeline[b + index] - timeline[a + index]) * blend;
+ length += out[body * 7 + index] ** 2;
+ }
+ for (let index = 3; index < 7; index++) out[body * 7 + index] /= Math.sqrt(length);
+ }
+ return out;
+}
+
+function matrixFrom(pose, offset, sx, sy, sz) {
+ const [x, y, z, qx, qy, qz, qw] = pose.slice(offset, offset + 7);
+ return new Float32Array([
+ (1 - 2 * (qy * qy + qz * qz)) * sx, 2 * (qx * qy + qz * qw) * sx, 2 * (qx * qz - qy * qw) * sx, 0,
+ 2 * (qx * qy - qz * qw) * sy, (1 - 2 * (qx * qx + qz * qz)) * sy, 2 * (qy * qz + qx * qw) * sy, 0,
+ 2 * (qx * qz + qy * qw) * sz, 2 * (qy * qz - qx * qw) * sz, (1 - 2 * (qx * qx + qy * qy)) * sz, 0,
+ x, y, z, 1,
+ ]);
+}
+
+const pose = new Float32Array(bodyNames.length * 7);
+const ballPart = { name: 'Ball', geometry: sphere(32, 20), matrix: matrixFrom(sample(0, pose), 0, radius, radius, radius), material: { color: [0.9, 0.45, 0.2], metallic: 0, roughness: 0.4 } };
+const cratePart = { name: 'Crate', geometry: box(0.05, 3), matrix: matrixFrom(pose, 7, 0.7, 0.7, 0.7), material: { color: [0.55, 0.4, 0.25], metallic: 0, roughness: 0.7 } };
+const parts = [ballPart, cratePart];
+
+// The lowest the ball gets between frames. An interpolated pose runs no collision test, so a rotated shape can dip below the floor; a ball stays above it.
+let lowest = Infinity;
+for (let time = 0; time <= duration; time += timestep / 10) lowest = Math.min(lowest, sample(time, pose)[1] - radius);
+console.log(`lowest ball underside while sampling at 10x the step: ${lowest.toFixed(4)} m`);
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, parts);
+function applyAnimation(time) {
+ sample(time, pose);
+ ballPart.matrix = matrixFrom(pose, 0, radius, radius, radius);
+ cratePart.matrix = matrixFrom(pose, 7, 0.7, 0.7, 0.7);
+ renderer.updateParts(parts);
+ renderer.render({ eye: [0, 3.5, 9], target: [0, 1, 0], fov: 42 });
+}
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:10px;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+const toggle = document.createElement('button');
+toggle.textContent = 'Pause';
+const slider = document.createElement('input');
+slider.type = 'range';
+slider.min = 0;
+slider.max = duration;
+slider.step = 0.01;
+slider.value = 1.1;
+bar.append(toggle, slider);
+document.body.append(bar);
+let playing = true;
+let seconds = 1.1;
+let last = performance.now();
+toggle.addEventListener('click', () => { playing = !playing; toggle.textContent = playing ? 'Pause' : 'Play'; last = performance.now(); });
+slider.addEventListener('input', () => { playing = false; toggle.textContent = 'Play'; seconds = Number(slider.value); applyAnimation(seconds); });
+slider.addEventListener('change', () => {
+ sample(seconds, pose);
+ console.log(`t=${seconds.toFixed(2)} s ball y=${pose[1].toFixed(3)} crate x=${pose[7].toFixed(3)}`);
+});
+function frame(now) {
+ if (playing) {
+ seconds = (seconds + (now - last) / 1000) % duration;
+ slider.value = seconds;
+ applyAnimation(seconds);
+ }
+ last = now;
+ requestAnimationFrame(frame);
+}
+new ResizeObserver(() => renderer.resize()).observe(canvas);
+requestAnimationFrame(frame);
+// Seeking back reproduces an earlier pose exactly: sampling is a pure function of the time.
+sample(1.25, pose);
+const firstPose = Array.from(pose);
+sample(5, pose);
+sample(1.25, pose);
+console.log('backward seek reproduces the pose:', firstPose.every((value, index) => value === pose[index]));
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+## Bake with Rapier
+
+The addon requires the optional peer dependency `@dimforge/[email protected]` (`npm install @dimforge/[email protected]`), and a package-aware dev server such as Vite to resolve it. It bakes body contacts, joints, limits and bounded motors into a timeline.
+
+1. Define named bodies, colliders, joints and tick events.
+2. Call `planPhysicsScene` to validate the definition and allocation estimate.
+3. Await `createPhysicsScene` to bake the bounded recording.
+4. Bind visual parts through `physics.bindParts`.
+5. Apply bindings at absolute time before uploading changed parts.
+6. Call `physics.dispose()` when the recording is no longer needed.
+
+```js
+import { createPhysicsScene, planPhysicsScene } from '67js/addons/physics';
+
+const definition = {
+ gravity: [0, -9.81, 0],
+ bodies: [
+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },
+ { name: 'box', type: 'dynamic', translation: [0, 3, 0] },
+ ],
+ colliders: [
+ { name: 'floor', body: 'floor', shape: 'cuboid', halfExtents: [5, 0.5, 5] },
+ { name: 'box', body: 'box', shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 },
+ ],
+ events: [{ tick: 120, body: 'box', impulse: [2, 4, 0] }],
+};
+const options = { frameCount: 601, timestep: 1 / 60, maxMemoryBytes: 64 * 1024 * 1024 };
+const plan = planPhysicsScene(definition, options);
+console.log(plan.timelineBytes, plan.estimatedPeakBytes);
+const physics = await createPhysicsScene(definition, options);
+const bindings = physics.bindParts([{ body: 'box', part: boxPart }]);
+
+function applyAnimation(time) {
+ bindings.apply(time);
+ renderer.updateParts([boxPart]);
+}
+applyAnimation(5);
+applyAnimation(1); // A backward seek produces the same recorded pose.
+physics.dispose();
+```
+
+`physics.sample(time, out)` returns packed poses in `physics.bodyNames` order, seven Float32 values per body `[x, y, z, qx, qy, qz, qw]`, and `physics.bodyIndex(name)` gives a body's index. Supply a retained `out` of `bodyNames.length * 7` values to avoid allocation. The binding replaces a part's world translation and rotation while keeping its scale and matrix identity, so the physics body origin must match the visual part origin. Several parts can bind to one body when they share that origin.
+
+## Options
+
+| Option | Default | Maximum |
+| --- | --- | --- |
+| `frameCount` | `601`, including frame zero | `maxFrames` |
+| `timestep` | `1 / 60` s, rounded to Float32 | 1 s |
+| `solverIterations` | `8` | integers 1 to 128 |
+| `maxBodies` | `256` | `4096` |
+| `maxColliders` | `1024` | `8192` |
+| `maxJoints` | `512` | `8192` |
+| `maxEvents` | `10000` | `100000` |
+| `maxFrames` | `3601` | `1000000` |
+| `maxMemoryBytes` | `134217728` | `2147483647` |
+
+Colliders are `ball` (`radius`), `cuboid` (`halfExtents`) and `capsule` (`radius`, `halfHeight` along local Y). Joints are `spherical`, `revolute` and `prismatic` (with a unit `axis`, and optional `limits` and `motor`) and `fixed`. A position motor takes `target`, positive `stiffness`, nonnegative `damping` and positive `maxForce`. A velocity motor takes `target`, positive `damping` and positive `maxForce`.
+
+Tick events run before their tick's integration step. Frame zero records the initial pose, tick zero events affect frame one, and the last valid tick is `frameCount - 2`. An `impulse` event targets a dynamic body with world-space `impulse` and `torqueImpulse` vectors, and an optional world `point`. `duration` equals `(frameCount - 1) * timestep`. `planPhysicsScene` validates the whole definition without loading Rapier, and its frozen result holds the exact `timelineBytes` and an estimated `solverReserveBytes`.
+
+## Limits
+
+- Recorded poses can seek forward or backward. Translations interpolate linearly and quaternions along the shortest arc. Interpolation between frames can show small penetrations, and a smaller timestep reduces them.
+- The bake can block the main thread after WASM initialization.
+- Cloth, soft bodies and direct skeletal bindings are unsupported by the rigid-body bake. The contract covers mesh colliders, sensors and the cloth recipes in their own sections.
+- Bindings validate every target before they update any matrix, and affine matrices with independent nonzero scales are supported. Shear and perspective fail.
+
+The [physics contract](/physics.md) defines supported colliders, joint controls, timing and disposal.
+
+## Common mistakes
+
+- Not calling `physics.dispose()` when the recording is done.
+- A visual part whose origin is not the body origin. Use a separate part or another body definition.
+- A timeline longer than `maxFrames` or `maxMemoryBytes`. Plan first.
+- Expecting the viewer to simulate. Playback only samples the recording.
+- A tick past `frameCount - 2`, which is not a valid event tick.
diff --git a/docs/learn/skeletal-and-morph-animation.md b/docs/learn/skeletal-and-morph-animation.md
new file mode 100644
index 00000000..ff24f7d2
--- /dev/null
+++ b/docs/learn/skeletal-and-morph-animation.md
@@ -0,0 +1,132 @@
+# Skeletal and morph animation
+
+A skinned mesh follows a skeleton, and a morph target moves its vertices by stored changes. 67js blends the morph targets first, then deforms the result with the joint palette, all on the GPU. Both poses are small retained arrays that you write each frame and upload with `renderer.updateParts(parts)`.
+
+## A bending column with a bulge
+
+The column has two joints. The upper joint bends it at the middle. A morph target makes it bulge. Drag the sliders for the bend angle and the bulge weight. The console prints the retained palette size and the weights.
+
+```js live poster=skeletal-morph
+import { Renderer67, box, createSkinPose, updateSkinPose, createMorphPose } from '67js';
+
+// The docs frame shares the engine of the page, so take the typed arrays that the engine checks for. In your own project this line changes nothing.
+const { Float32Array, Uint16Array, Uint32Array } = window.parent;
+
+function translation(x, y, z) {
+ return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]);
+}
+function bendZ(angle, pivotY) {
+ const c = Math.cos(angle);
+ const s = Math.sin(angle);
+ // Rotate about Z around (0, pivotY, 0): T(pivot) * R * T(-pivot).
+ return new Float32Array([c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, pivotY * s, pivotY - pivotY * c, 0, 1]);
+}
+
+// A box with subdivisions gives vertices along its height. Stretch it to a 2 m column on the floor.
+const unit = box(0.02, 10);
+const vertexCount = unit.positions.length / 3;
+const positions = new Float32Array(unit.positions.length);
+const skinIndices = new Uint16Array(vertexCount * 4);
+const skinWeights = new Float32Array(vertexCount * 4);
+const bulge = new Float32Array(unit.positions.length);
+for (let vertex = 0; vertex < vertexCount; vertex++) {
+ const x = unit.positions[vertex * 3] * 0.5;
+ const y = unit.positions[vertex * 3 + 1] * 2 + 1;
+ const z = unit.positions[vertex * 3 + 2] * 0.5;
+ positions.set([x, y, z], vertex * 3);
+ const upper = Math.min(1, Math.max(0, (y - 0.6) / 0.8));
+ skinIndices.set([0, 1, 0, 0], vertex * 4);
+ skinWeights.set([1 - upper, upper, 0, 0], vertex * 4);
+ const swell = Math.max(0, 1 - Math.abs(y - 1)) * 0.35;
+ bulge.set([Math.sign(x) * swell, 0, Math.sign(z) * swell], vertex * 3);
+}
+
+const skin = createSkinPose(2);
+const morph = createMorphPose(1);
+const geometry = {
+ positions,
+ normals: unit.normals,
+ indices: unit.indices,
+ skinIndices,
+ skinWeights,
+ morphTargets: [{ positions: bulge }],
+};
+const part = { name: 'Column', geometry, matrix: translation(0, 0, 0), material: { color: [0.85, 0.5, 0.3], metallic: 0, roughness: 0.5 }, skin, morph };
+const parts = [part];
+
+const jointRest = new Float32Array([...translation(0, 0, 0), ...translation(0, 1, 0)]);
+const inverseBind = new Float32Array([...translation(0, 0, 0), ...translation(0, -1, 0)]);
+console.log('skin palette floats:', skin.jointMatrices.length, '(2 joints x 16)');
+console.log('vertices:', vertexCount, 'morph targets:', morph.weights.length);
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, parts);
+const state = { bend: 0.6, swell: 0.5 };
+function draw() {
+ const joints = new Float32Array(jointRest);
+ joints.set(bendZ(state.bend, 1), 16);
+ updateSkinPose(skin, joints, inverseBind, part.matrix);
+ morph.weights[0] = state.swell;
+ renderer.updateParts(parts);
+ renderer.render({ eye: [0, 1.4, 5], target: [0, 1, 0], fov: 38 });
+}
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:12px;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+function slider(label, min, max, key) {
+ const wrap = document.createElement('label');
+ const input = document.createElement('input');
+ input.type = 'range';
+ input.min = min;
+ input.max = max;
+ input.step = 0.01;
+ input.value = state[key];
+ input.addEventListener('input', () => { state[key] = Number(input.value); draw(); });
+ input.addEventListener('change', () => console.log(`${key} = ${state[key].toFixed(2)}`, 'weights:', morph.weights));
+ wrap.append(label + ' ', input);
+ bar.append(wrap);
+}
+slider('bend', -1.2, 1.2, 'bend');
+slider('swell', -0.5, 1.5, 'swell');
+document.body.append(bar);
+draw();
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+The sliders reach beyond 0 to 1 on purpose: morph weights are not clamped, so `-0.5` pinches the column and `1.5` overshoots.
+
+## How the pieces fit
+
+Version `0.4.0` supports four-influence GPU skinning and relative position and normal morph targets.
+
+1. Define static skin influences or relative morph channels before the renderer is built: `skinIndices` and `skinWeights` (four per vertex) and `morphTargets` on the geometry.
+2. Assign the matching retained `skin` and `morph` poses to each part.
+3. Update the joint palette and the morph weights for the frame you want.
+4. Call `renderer.updateParts(parts)` to validate and upload the poses.
+
+`createSkinPose(jointCount)` holds a retained `Float32Array` named `jointMatrices`, 16 floats per joint in column-major order, starting as identity. `updateSkinPose(pose, jointWorldMatrices, inverseBindMatrices, meshWorldMatrix, bindMatrix)` computes `inverse(meshWorld) * jointWorld * inverseBind * bindMatrix` for each joint. `createMorphPose(count)` holds the retained `weights`. The renderer applies the morph deltas before skinning.
+
+Changing topology, influences or pose identities needs a new renderer. Parts that share one pose instance into one batch; separate poses make separate batches.
+
+## Import from glTF
+
+The glTF addon imports supported skins and relative targets, including joint and weight animation. `asset.applyAnimation(time, clipIndex)` updates the retained parts and poses, and you then call `renderer.updateParts`. The [glTF morph contract](https://github.com/codepawl/67.js/blob/main/docs/gltf-morph.md) and the [asset contract](/gltf.md) define the supported subset. The [skinning contract](https://github.com/codepawl/67.js/blob/main/docs/skinning.md) defines supported transforms, four influences and identity requirements. The [morph contract](https://github.com/codepawl/67.js/blob/main/docs/morph-targets.md) defines channel shapes, weight bounds and resource estimates.
+
+## Options
+
+| Field | Where | Rule |
+| --- | --- | --- |
+| `skinIndices` | geometry | `Uint16Array`, four joint indices per vertex; indices must be valid even when their weight is 0. |
+| `skinWeights` | geometry | `Float32Array`, four finite weights in 0 to 1 per vertex, total above 0. The renderer normalizes a copy. |
+| `morphTargets` | geometry | 1 to 64 (`MAX_MORPH_TARGETS`) targets, each with `positions` and/or `normals` as `Float32Array` XYZ deltas per vertex. |
+| `skin`, `morph` | part | The retained poses from `createSkinPose` and `createMorphPose`. |
+
+Joint matrices must be finite, affine and nonsingular. Weights can be negative or above one.
+
+## Common mistakes
+
+- Replacing the pose object each frame. Write into the retained `jointMatrices` and `weights`, because pose identity picks the batch.
+- Joint indices that point past the palette, even with zero weight.
+- Forgetting the inverse bind matrix, so the mesh jumps away from its rest pose.
+- A morph channel that is not `Float32Array`, or has the wrong length.
+- Expecting culling and levels of detail on skinned parts. They are skipped for skinned and morphed parts.
diff --git a/docs/learn/terrain-and-ground-textures.md b/docs/learn/terrain-and-ground-textures.md
new file mode 100644
index 00000000..4ab49015
--- /dev/null
+++ b/docs/learn/terrain-and-ground-textures.md
@@ -0,0 +1,191 @@
+# Terrain and ground textures
+
+`67js/addons/terrain` builds a chunked, seeded heightfield with distance level of detail. `67js/addons/texture-set` loads CC0 scans and a four-layer ground material draws them with slope, height and mask rules, height-based edge blending, triplanar cliffs and anti-tiling. Both are available from version `0.10.0`.
+
+## The idea: a height function and rules
+
+The docs run in the browser with the core module only, so the example builds a small heightfield by hand and sorts its triangles with the same kind of rules that the splat material uses: a slope range and a height range per layer. Drag the sliders. Grass takes what the other layers leave, rock takes the steep triangles and snow takes the high, flat ones. The console prints how many triangles each layer got and what `heightAt` returns for the ball.
+
+```js live poster=terrain-rules
+import { Renderer67, sphere } from '67js';
+
+// The docs frame shares the engine of the page, so take the typed arrays that the engine checks for. In your own project this line changes nothing.
+const { Float32Array, Uint16Array, Uint32Array } = window.parent;
+
+const size = 40;
+const cells = 64;
+const heightAt = (x, z) => 2.2 * Math.sin(x * 0.22 + 0.5) * Math.cos(z * 0.19) + 1.1 * Math.sin(x * 0.5 + z * 0.4)
+ + 0.5 * Math.sin(z * 0.9 - x * 0.3) + 4.5 * Math.exp(-((x - 7) ** 2 + (z + 5) ** 2) / 70);
+
+function build(slopeLimit, snowLine) {
+ const layers = { grass: [], rock: [], snow: [] };
+ const step = size / cells;
+ for (let row = 0; row < cells; row++) {
+ for (let column = 0; column < cells; column++) {
+ const x0 = -size / 2 + column * step;
+ const z0 = -size / 2 + row * step;
+ const corner = (dx, dz) => [x0 + dx * step, heightAt(x0 + dx * step, z0 + dz * step), z0 + dz * step];
+ for (const triangle of [[corner(0, 0), corner(0, 1), corner(1, 0)], [corner(1, 0), corner(0, 1), corner(1, 1)]]) {
+ const [a, b, c] = triangle;
+ const edgeA = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
+ const edgeB = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
+ const normal = [edgeA[1] * edgeB[2] - edgeA[2] * edgeB[1], edgeA[2] * edgeB[0] - edgeA[0] * edgeB[2], edgeA[0] * edgeB[1] - edgeA[1] * edgeB[0]];
+ const length = Math.hypot(...normal);
+ const unit = normal.map(value => value / length);
+ const slope = Math.acos(unit[1]) * 180 / Math.PI;
+ const height = (a[1] + b[1] + c[1]) / 3;
+ const layer = slope > slopeLimit ? 'rock' : height > snowLine ? 'snow' : 'grass';
+ layers[layer].push({ triangle, unit });
+ }
+ }
+ }
+ return layers;
+}
+
+function geometryOf(entries) {
+ const positions = new Float32Array(entries.length * 9);
+ const normals = new Float32Array(entries.length * 9);
+ entries.forEach(({ triangle, unit }, index) => {
+ triangle.forEach((point, corner) => {
+ positions.set(point, index * 9 + corner * 3);
+ normals.set(unit, index * 9 + corner * 3);
+ });
+ });
+ return { positions, normals, indices: Uint32Array.from({ length: entries.length * 3 }, (unused, index) => index) };
+}
+
+const materials = {
+ grass: { color: [0.25, 0.5, 0.18], metallic: 0, roughness: 0.9 },
+ rock: { color: [0.42, 0.4, 0.38], metallic: 0, roughness: 0.85 },
+ snow: { color: [0.92, 0.94, 0.97], metallic: 0, roughness: 0.6 },
+};
+const marker = { name: 'Marker', geometry: sphere(24, 16), matrix: new Float32Array([0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 0, heightAt(0, 0) + 0.5, 0, 1]), material: { color: [0.9, 0.2, 0.2], metallic: 0, roughness: 0.4 } };
+
+function partsFor(slopeLimit, snowLine) {
+ const layers = build(slopeLimit, snowLine);
+ const parts = Object.entries(layers).filter(([unused, entries]) => entries.length).map(([name, entries]) => ({
+ name: `Terrain ${name}`, geometry: geometryOf(entries), matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: materials[name],
+ }));
+ console.log(`slope limit ${slopeLimit}°, snow line ${snowLine} m:`, Object.fromEntries(Object.entries(layers).map(([name, entries]) => [name, entries.length])));
+ return [...parts, marker];
+}
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const state = { slope: 32, snow: 3.2, yaw: 0.6, pitch: 0.55, distance: 54 };
+const renderer = new Renderer67(canvas, partsFor(state.slope, state.snow), { world: true });
+console.log(`heightAt(0, 0) = ${heightAt(0, 0).toFixed(3)} m, ${cells * cells * 2} triangles`);
+
+function draw() {
+ const flat = Math.cos(state.pitch) * state.distance;
+ renderer.render({ eye: [Math.sin(state.yaw) * flat, Math.sin(state.pitch) * state.distance, Math.cos(state.yaw) * flat], target: [0, 1, 0], fov: 40 });
+}
+function rebuild() {
+ renderer.replaceParts(partsFor(state.slope, state.snow));
+ draw();
+}
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:12px;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+for (const [label, key, min, max] of [['slope limit', 'slope', 10, 70], ['snow line', 'snow', 0, 6]]) {
+ const wrap = document.createElement('label');
+ const input = document.createElement('input');
+ input.type = 'range';
+ input.min = min;
+ input.max = max;
+ input.step = 0.5;
+ input.value = state[key];
+ input.addEventListener('change', () => { state[key] = Number(input.value); rebuild(); });
+ wrap.append(label + ' ', input);
+ bar.append(wrap);
+}
+document.body.append(bar);
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ state.yaw -= event.movementX * 0.01;
+ state.pitch = Math.min(1.3, Math.max(0.15, state.pitch + event.movementY * 0.01));
+ draw();
+});
+new ResizeObserver(() => { renderer.resize(); draw(); }).observe(canvas);
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+The sliders apply on release (the `change` event), because each change rebuilds the triangle lists. The real addon does this per vertex in the shader, so the rules cost nothing on the CPU and blend smoothly instead of switching per triangle.
+
+## Build the real terrain
+
+1. Load a texture set per layer, then give the layers to one material: `const set = await loadTextureSet('/textures/leafy_grass')`, `material.layers = [{ ...set, scale: 3 }, ...]` and `material.splat = { rules }`.
+2. Create the heightfield: `const terrain = createTerrain({ size, chunks, resolution, levels, seed })`. Give every entry of `terrain.parts` the one shared material.
+3. Pass `terrain.heightAt` to `scatterVegetation` and to vehicles, and call `renderer.replaceParts` when `terrain.update(eye)` returns parts.
+
+```js
+import { Renderer67 } from '67js';
+import { createTerrain } from '67js/addons/terrain';
+import { loadTextureSet } from '67js/addons/texture-set';
+
+const material = { color: [1, 1, 1], metallic: 0, roughness: 1, tag: 'standard' };
+material.layers = [
+ { ...await loadTextureSet('/textures/leafy_grass'), scale: 3 },
+ { ...await loadTextureSet('/textures/rock'), scale: 4, triplanar: true },
+];
+material.splat = { rules: [undefined, { slope: [32, 90], slopeSoftness: 6 }] };
+
+const terrain = createTerrain({ size: 600, chunks: 10, resolution: 32, levels: 4, seed: 7, material });
+const renderer = new Renderer67(canvas, terrain.parts, { world: true });
+function draw(eye) {
+ const changed = terrain.update(eye);
+ if (changed.length) renderer.replaceParts(terrain.parts);
+ renderer.render({ eye, target: [0, 0, 0] });
+}
+```
+
+## Options
+
+`createTerrain({ size = 512, resolution = 32, chunks = 8, levels = 4, height, seed = 1, material, lodDistance, eye })` returns `{ parts, heightAt, normalAt, bounds, update, triangleCount, chunkSize, chunkLevels }`.
+
+| Option | Meaning |
+| --- | --- |
+| `size` | The ground spans x and z from `-size / 2` to `size / 2`. |
+| `chunks`, `resolution`, `levels` | `chunks` per side, each with `resolution` cells at level 0. `resolution` must divide by `2 ** (levels - 1)`. Level `n` uses `resolution / 2 ** n` cells. |
+| `height` | A function `(x, z) => metres`, a square `Float32Array` of metres (see `heightmapFromImageData(imageData, amplitude)`), or noise options such as `amplitude` (14), `mountainAmplitude` (46), `featureSize` (160 m), `octaves`, `gain`, `lacunarity`, `warp`, `baseHeight` and `mountainMask(x, z)`. |
+| `lodDistance` | Distance of the first level change, default 1.6 chunk sizes, doubling per level. |
+| `holes` | Up to 64 `{ center: [x, z], radius }` circles that leave no surface. `terrain.isHole(x, z)` tells whether a point is inside one. |
+
+`heightAt(x, z)` walks the same triangles as the level 0 mesh, so it matches the rendered surface there, and coordinates outside the ground clamp to the edge. `normalAt` interpolates smooth grid normals. `update(eye)` returns the parts whose geometry changed, and edges shared with a coarser neighbour snap onto it, so there are no cracks and no skirts. UVs are world metres `(x, z)`.
+
+| Splat layer field | Meaning |
+| --- | --- |
+| `color`, `normal`, `roughness`, `height` | Descriptors from `loadTextureSet`. Missing ones fall back to mid grey, a flat normal, roughness 1 and height 0.5. |
+| `scale` | Metres per texture tile (default 4). |
+| `tint` | RGB multiplier on colour. |
+| `normalStrength` | Scales the normal map tilt (default 1). |
+| `triplanar` | Projects from the sides on steep slopes, so cliffs do not stretch. |
+
+`material.splat.rules` has one entry per layer: `slope: [min, max]` in degrees, `height: [min, max]` in metres, each with `slopeSoftness` (4) and `heightSoftness` (1.5), and `mask: 'r' | 'g' | 'b' | 'a'` with `invertMask`. A layer with no rule takes what the others leave, so put grass first with no rule. Other `splat` options include `heightBlend` (0.22), `heightInfluence` (1), `triplanarStart` and `triplanarEnd` (38 and 52 degrees), `variation` (0 to 2, default 1), `edgeNoise` (0 to 2, default 1) and `parallax` (0 to 0.15 m, default 0.03). The [terrain contract](https://github.com/codepawl/67.js/blob/main/docs/terrain.md) lists every option.
+
+## Cost
+
+Measured on Windows with an RTX 3060, headless Chrome, 1600 by 900, 4x MSAA, HDRI, shadows and bloom, a 600 m terrain with 10 by 10 chunks at resolution 32 and 1,000 to 1,750 trees (docs/terrain.md):
+
+| Camera | Terrain triangles | Scene triangles | Batches | Frame |
+| --- | --- | --- | --- | --- |
+| Low, close to the path | 50,432 | 1.23 M | 164 | 13.8 ms |
+| High, whole scene | 12,896 | 0.53 M | 124 | 9.0 ms |
+
+Splat textures took 68 MiB of 74 MiB of texture memory at 1K per layer. They live in three texture arrays (colour, normal, and roughness with height), resized to the largest source with mipmaps and up to 8x anisotropic filtering.
+
+## Limits
+
+- Up to four layers, and one splat material per draw, so all chunks share one. Eight 1K layers would take about 136 MiB against the 74 MiB above.
+- The terrain is a heightfield, so there are no overhangs, caves or bridges, apart from `holes`.
+- Changing `layers` or `splat` after the renderer exists needs a new renderer.
+- Materials batch together only when they share the same `layers` array and `splat` object. Build them once.
+
+## Common mistakes
+
+- A splat material with a `map`, `normalMap` or a special tag such as `floor`. Use a standard PBR tag and no maps.
+- A `resolution` that does not divide by `2 ** (levels - 1)`.
+- One material per chunk. Chunks must share one material, or each chunk becomes its own draw.
+- Standing something on `heightAt` inside a hole. `heightAt` ignores holes, so check `isHole` first.
+- Calling `replaceParts` every frame. Do it only when `update(eye)` returns changed parts.
diff --git a/docs/learn/trees-and-grass.md b/docs/learn/trees-and-grass.md
new file mode 100644
index 00000000..96f01c19
--- /dev/null
+++ b/docs/learn/trees-and-grass.md
@@ -0,0 +1,182 @@
+# Trees and grass
+
+`67js/addons/vegetation` grows seeded trees with real branches and leaf cards, plus grass and flowers. It is available from version `0.10.0`. It scatters instances with Poisson-disk spacing, shares a few variants per species so the renderer can batch them, and picks a level of detail per instance from the camera.
+
+## Scatter, then pick detail by distance
+
+The docs run with the core module only, so this example scatters trees by hand and mirrors what the addon returns: a seeded scatter with a slope limit and an exclusion zone, and a per-camera level choice. Drag to orbit and the near trees get the detailed crown while the far ones get a coarse one. The slider changes the density. The console prints what `selectLevels` reports: level counts and triangles.
+
+```js live poster=trees-scatter
+import { Renderer67, cylinder, sphere } from '67js';
+
+function random(seed) {
+ let value = seed >>> 0;
+ return () => {
+ value = (value * 1664525 + 1013904223) >>> 0;
+ return value / 4294967296;
+ };
+}
+const terrainHeight = (x, z) => 1.5 * Math.sin(x * 0.18) * Math.cos(z * 0.15);
+const slopeAt = (x, z) => Math.atan(Math.hypot(terrainHeight(x + 0.6, z) - terrainHeight(x - 0.6, z), terrainHeight(x, z + 0.6) - terrainHeight(x, z - 0.6)) / 1.2) * 180 / Math.PI;
+const exclusion = (x, z) => Math.hypot(x, z) < 3.5;
+
+// Jittered grid: each cell holds at most one tree, so spacing is at least about half a cell.
+function scatter({ area, density, slopeLimit, seed }) {
+ const next = random(seed);
+ const cell = Math.sqrt(1 / density);
+ const instances = [];
+ for (let x = -area / 2; x < area / 2; x += cell) {
+ for (let z = -area / 2; z < area / 2; z += cell) {
+ const px = x + next() * cell;
+ const pz = z + next() * cell;
+ if (exclusion(px, pz) || slopeAt(px, pz) > slopeLimit) continue;
+ instances.push({ x: px, z: pz, y: terrainHeight(px, pz), scale: 0.8 + next() * 0.6, variant: Math.floor(next() * 3) });
+ }
+ }
+ return instances;
+}
+
+const trunk = cylinder(12, 0.02, 2);
+const crownLevels = [sphere(20, 14), sphere(8, 6)];
+const crownMaterials = [0, 1, 2].map(variant => ({ color: [0.12 + variant * 0.04, 0.38 + variant * 0.05, 0.14], metallic: 0, roughness: 0.8 }));
+const trunkMaterial = { color: [0.3, 0.2, 0.12], metallic: 0, roughness: 0.9 };
+const triangles = geometry => geometry.indices.length / 3;
+
+const state = { density: 0.35, yaw: 0.7, distance: 24, pitch: 0.5 };
+let instances = scatter({ area: 40, density: state.density, slopeLimit: 14, seed: 11 });
+let levels = [];
+
+function eye() {
+ const flat = Math.cos(state.pitch) * state.distance;
+ return [Math.sin(state.yaw) * flat, Math.sin(state.pitch) * state.distance + 2, Math.cos(state.yaw) * flat];
+}
+
+// Level 0 within 14 m of the camera, level 1 beyond it. Part objects are cached, so unchanged instances keep their identity.
+function selectLevels(position) {
+ let changed = false;
+ const counts = [0, 0];
+ let totalTriangles = 0;
+ instances.forEach((tree, index) => {
+ const level = Math.hypot(tree.x - position[0], tree.z - position[2]) < 14 ? 0 : 1;
+ if (levels[index] !== level) changed = true;
+ levels[index] = level;
+ counts[level]++;
+ totalTriangles += triangles(trunk) + triangles(crownLevels[level]);
+ });
+ return { changed, counts, totalTriangles };
+}
+
+function partsFor() {
+ return instances.flatMap((tree, index) => [
+ { name: `Trunk ${index}`, geometry: trunk, matrix: new Float32Array([0.18 * tree.scale, 0, 0, 0, 0, 1.2 * tree.scale, 0, 0, 0, 0, 0.18 * tree.scale, 0, tree.x, tree.y + 0.6 * tree.scale, tree.z, 1]), material: trunkMaterial },
+ { name: `Crown ${index}`, geometry: crownLevels[levels[index]], matrix: new Float32Array([0.9 * tree.scale, 0, 0, 0, 0, 1.1 * tree.scale, 0, 0, 0, 0, 0.9 * tree.scale, 0, tree.x, tree.y + 1.7 * tree.scale, tree.z, 1]), material: crownMaterials[tree.variant] },
+ ]);
+}
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const first = selectLevels(eye());
+console.log(`scattered ${instances.length} trees, 3 variants, slope limit 14°`, first);
+const renderer = new Renderer67(canvas, partsFor(), { world: true });
+
+function draw() {
+ const position = eye();
+ const result = selectLevels(position);
+ if (result.changed) {
+ renderer.replaceParts(partsFor());
+ console.log('levels changed:', { levelCounts: result.counts, triangles: result.totalTriangles });
+ }
+ renderer.render({ eye: position, target: [0, 1, 0], fov: 45 });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ state.yaw -= event.movementX * 0.01;
+ state.pitch = Math.min(1.3, Math.max(0.1, state.pitch + event.movementY * 0.01));
+ draw();
+});
+canvas.addEventListener('wheel', event => {
+ event.preventDefault();
+ state.distance = Math.min(40, Math.max(6, state.distance * Math.exp(event.deltaY * 0.001)));
+ draw();
+}, { passive: false });
+
+const slider = document.createElement('input');
+slider.type = 'range';
+slider.min = 0.1;
+slider.max = 0.8;
+slider.step = 0.05;
+slider.value = state.density;
+slider.setAttribute('aria-label', 'Trees per square metre');
+slider.style.cssText = 'position:fixed;left:8px;bottom:8px;width:40%';
+slider.addEventListener('change', () => {
+ state.density = Number(slider.value);
+ instances = scatter({ area: 40, density: state.density, slopeLimit: 14, seed: 11 });
+ levels = [];
+ selectLevels(eye());
+ renderer.replaceParts(partsFor());
+ console.log(`density ${state.density} per m²: ${instances.length} trees`);
+ draw();
+});
+document.body.append(slider);
+new ResizeObserver(() => { renderer.resize(); draw(); }).observe(canvas);
+draw();
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+## Grow the real forest
+
+```js
+import { Renderer67 } from '67js';
+import { scatterVegetation, selectLevels } from '67js/addons/vegetation';
+import { loadLeafTextures } from '67js/addons/texture-set';
+
+const forest = scatterVegetation({
+ area: { minX: -60, maxX: 60, minZ: -60, maxZ: 60 },
+ density: 0.04,
+ terrainHeight: terrain.heightAt,
+ slopeLimit: 30,
+ exclusion: (x, z) => Math.hypot(x, z) < 4,
+ mix: { broadleaf: 3, birch: 1, bush: 2 },
+ leafTextures: await loadLeafTextures('/textures/leaves'),
+});
+let view = selectLevels(forest.instances, eye);
+const renderer = new Renderer67(canvas, view.parts, { world: true });
+console.log(forest.counts, view.levelCounts, view.triangles);
+```
+
+1. Scatter with `scatterVegetation({ area, density, terrainHeight, slopeLimit, exclusion, mix, leaves })`.
+2. Pick detail per camera with `selectLevels(forest.instances, eye)`.
+3. Pass `view.parts` to `Renderer67` and rebuild when `view.changed` is true.
+
+Cards (`leaves: 'cards'`, the default) are single-sided, alpha-masked, double-sided `foliage` textures that sway with the wind. `'mesh'` leaves cost about twice the triangles. Pass `barkTextures` for scanned bark and `leafTextures: await loadLeafTextures('/textures/leaves')` for scanned leaf cards.
+
+## Options
+
+`scatterVegetation({ area, density, terrainHeight, slopeLimit, exclusion, seed, mix, variants, leaves, scale, spacing })` returns `{ instances, parts, variants, counts }`.
+
+| Option | Meaning |
+| --- | --- |
+| `area` | The ground rectangle. |
+| `density` | Instances per square metre. Spacing defaults to `sqrt(0.6 / density)` (Poisson-disk, Bridson with restarts, so exclusion zones cannot strand regions). |
+| `terrainHeight` | `(x, z) => y`. Pass `terrain.heightAt`. |
+| `slopeLimit` | Degrees, measured from `terrainHeight` over a 1.2 m span. |
+| `exclusion(x, z)` | Returns true to keep a spot clear. |
+| `mix` | Weights per species: `broadleaf`, `birch`, `conifer`, `palm`, `bush`, `grass`, `flowers`. Low-frequency noise groups species into stands. |
+| `variants` | Default 3 variants per species, shared by every instance so the renderer batches by geometry identity. Instances differ by yaw, scale and tint. |
+| `leaves` | `'cards'` (default) or `'mesh'`. |
+
+`selectLevels(instances, eye, { distanceScale, hysteresis, cullDistance })` returns `{ parts, changed, levelCounts, culled, triangles }`. A level changes only after the distance passes its threshold by `hysteresis` (default 0.12), so instances on a boundary do not flicker. Grass switches at 24 m. Set `cullDistance` to drop far instances, `fade` for a screen-door cross-fade, and `impostors` for a last level that draws one baked card per tree. `vegetationParts(variant, matrix, level, name)` places one tree or clump yourself.
+
+## Cost
+
+On the demo clearing (125 trees and bushes, 1,941 grass clumps and 129 flower patches, camera at the clearing edge, headless Chrome with a GPU), `mesh` leaves with level of detail drew 2.28M triangles in 65 draws, against 3.78M without level of detail. `cards` drew 1.15M. Building the scene took about 1 s and a frame took under 0.2 s (docs/vegetation.md). The [vegetation contract](https://github.com/codepawl/67.js/blob/main/docs/vegetation.md) lists species, triangle budgets and limits.
+
+## Common mistakes
+
+- Making a new geometry per tree. Share the variants, or every tree is its own draw.
+- Calling `replaceParts` when `changed` is false.
+- Expecting wind-bent skeletons or collisions between trees. Species are fixed presets without either.
+- Using cards for a close-up. Without `leafTextures` the leaf sprites are 128 px and look flat from under a few metres; scanned cards hold up to about 1 m.
+- Forgetting `exclusion` on a path or a house, and finding trees growing through it.
diff --git a/docs/learn/wheeled-vehicles.md b/docs/learn/wheeled-vehicles.md
new file mode 100644
index 00000000..9d7cfc2c
--- /dev/null
+++ b/docs/learn/wheeled-vehicles.md
@@ -0,0 +1,195 @@
+# Wheeled vehicles
+
+`67js/addons/vehicle` drives a car or truck along a path with deterministic, physics-free animation. It is available from version `0.10.0`. Wheel spin, front-wheel steering, roll, pitch and ground following all come from the path, and `sample(seconds)` gives the same pose for the same time.
+
+## The maths behind a drive
+
+The docs run with the core module only, so this example builds a car from boxes and cylinders and applies the same rules by hand on a circular path: wheel spin is `distance / radius`, the steer angle is `atan(wheelbase * curvature)` with Ackermann angles per front wheel, and roll follows lateral acceleration. Drag the speed slider. Faster driving leans the body more. The console prints the pose once a second.
+
+```js live poster=vehicle-drive
+import { Renderer67, box, cylinder } from '67js';
+
+const multiply = (a, b) => {
+ const out = new Float32Array(16);
+ for (let column = 0; column < 4; column++) {
+ for (let row = 0; row < 4; row++) {
+ let sum = 0;
+ for (let k = 0; k < 4; k++) sum += a[k * 4 + row] * b[column * 4 + k];
+ out[column * 4 + row] = sum;
+ }
+ }
+ return out;
+};
+const move = (x, y, z) => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]);
+const scale = (x, y, z) => new Float32Array([x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1]);
+const turnY = a => new Float32Array([Math.cos(a), 0, -Math.sin(a), 0, 0, 1, 0, 0, Math.sin(a), 0, Math.cos(a), 0, 0, 0, 0, 1]);
+const turnX = a => new Float32Array([1, 0, 0, 0, 0, Math.cos(a), Math.sin(a), 0, 0, -Math.sin(a), Math.cos(a), 0, 0, 0, 0, 1]);
+const turnZ = a => new Float32Array([Math.cos(a), Math.sin(a), 0, 0, -Math.sin(a), Math.cos(a), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+
+const wheelRadius = 0.35;
+const wheelbase = 2.6;
+const trackWidth = 1.5;
+const pathRadius = 6;
+const rollGain = 0.012;
+const wheelSpecs = [
+ { id: 'front left', x: trackWidth / 2, z: wheelbase / 2, front: true },
+ { id: 'front right', x: -trackWidth / 2, z: wheelbase / 2, front: true },
+ { id: 'rear left', x: trackWidth / 2, z: -wheelbase / 2, front: false },
+ { id: 'rear right', x: -trackWidth / 2, z: -wheelbase / 2, front: false },
+];
+
+const bodyPart = { name: 'Body', geometry: box(0.1, 3), matrix: scale(1.8, 0.55, 4), material: { color: [0.8, 0.2, 0.18], metallic: 0.3, roughness: 0.35 } };
+const cabinPart = { name: 'Cabin', geometry: box(0.15, 3), matrix: scale(1.5, 0.5, 2), material: { color: [0.15, 0.2, 0.28], metallic: 0, roughness: 0.2 } };
+const tire = cylinder(24, 0.05, 2);
+const wheelParts = wheelSpecs.map(spec => ({ name: `Wheel ${spec.id}`, geometry: tire, matrix: scale(1, 1, 1), material: { color: [0.06, 0.06, 0.07], metallic: 0, roughness: 0.8 } }));
+const parts = [bodyPart, cabinPart, ...wheelParts];
+
+// The pose for a time, from the path alone: nothing depends on the previous frame.
+function sample(seconds, speed) {
+ const distance = speed * seconds;
+ const angle = distance / pathRadius;
+ const curvature = 1 / pathRadius;
+ const steer = Math.atan(wheelbase * curvature);
+ const lateral = speed * speed * curvature;
+ return {
+ time: seconds,
+ distance,
+ speed,
+ position: [pathRadius * Math.sin(angle), 0, pathRadius * Math.cos(angle) - pathRadius],
+ heading: Math.PI / 2 + angle,
+ roll: rollGain * lateral,
+ steerAngle: steer,
+ wheels: wheelSpecs.map(spec => {
+ const side = spec.x > 0 ? 1 : -1;
+ const turnRadius = pathRadius - side * spec.x;
+ const ackermann = spec.front ? Math.atan2(spec.z + wheelbase / 2, turnRadius) : 0;
+ return { id: spec.id, spinAngle: distance * (turnRadius / pathRadius) / wheelRadius, steerAngle: ackermann };
+ }),
+ };
+}
+
+function apply(pose) {
+ const frame = multiply(multiply(move(...pose.position), turnY(pose.heading)), turnZ(pose.roll));
+ parts[0].matrix = multiply(frame, multiply(move(0, 0.65, 0), scale(1.8, 0.55, 4)));
+ parts[1].matrix = multiply(frame, multiply(move(0, 1.15, -0.2), scale(1.5, 0.5, 2)));
+ pose.wheels.forEach((wheel, index) => {
+ const spec = wheelSpecs[index];
+ const local = multiply(move(spec.x, wheelRadius, spec.z), multiply(turnY(wheel.steerAngle), multiply(turnX(-wheel.spinAngle), multiply(turnZ(Math.PI / 2), scale(wheelRadius, 0.28, wheelRadius)))));
+ parts[2 + index].matrix = multiply(frame, local);
+ });
+}
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const renderer = new Renderer67(canvas, parts);
+const state = { speed: 6, yaw: 0.5, pitch: 0.7, distance: 17, playing: true };
+let seconds = 0;
+let last = performance.now();
+let nextLog = 0;
+
+function draw() {
+ const pose = sample(seconds, state.speed);
+ apply(pose);
+ renderer.updateParts(parts);
+ const flat = Math.cos(state.pitch) * state.distance;
+ renderer.render({ eye: [Math.sin(state.yaw) * flat, Math.sin(state.pitch) * state.distance, Math.cos(state.yaw) * flat - pathRadius], target: [0, 0.5, -pathRadius], fov: 42 });
+ return pose;
+}
+
+function frame(now) {
+ if (state.playing) seconds += (now - last) / 1000;
+ last = now;
+ const pose = draw();
+ if (state.playing && seconds > nextLog) {
+ nextLog = seconds + 1;
+ console.log(`t=${seconds.toFixed(1)} s distance ${pose.distance.toFixed(1)} m, steer ${pose.steerAngle.toFixed(3)} rad, roll ${pose.roll.toFixed(3)} rad, front-left spin ${pose.wheels[0].spinAngle.toFixed(1)} rad`);
+ }
+ requestAnimationFrame(frame);
+}
+
+const bar = document.createElement('div');
+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:10px;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';
+const toggle = document.createElement('button');
+toggle.textContent = 'Pause';
+toggle.addEventListener('click', () => { state.playing = !state.playing; toggle.textContent = state.playing ? 'Pause' : 'Play'; });
+const speed = document.createElement('input');
+speed.type = 'range';
+speed.min = 1;
+speed.max = 14;
+speed.step = 0.5;
+speed.value = state.speed;
+speed.addEventListener('input', () => { state.speed = Number(speed.value); });
+speed.addEventListener('change', () => console.log(`speed ${state.speed} m/s, lateral acceleration ${(state.speed ** 2 / pathRadius).toFixed(2)} m/s²`));
+bar.append(toggle, 'speed', speed);
+document.body.append(bar);
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ state.yaw -= event.movementX * 0.01;
+ state.pitch = Math.min(1.3, Math.max(0.15, state.pitch + event.movementY * 0.01));
+});
+new ResizeObserver(() => renderer.resize()).observe(canvas);
+requestAnimationFrame(frame);
+addEventListener('pagehide', () => renderer.dispose());
+```
+
+In this model the inside wheels spin slower in the corner because their path is shorter, as in the addon, where they turn slower by their lateral offset times the heading change.
+
+## Drive a real vehicle
+
+1. Describe the vehicle with `createVehicleRig({ parts })`. Wheels are found by name and geometry. Check `rig.wheels` or `findWheelCandidates(names)`.
+2. Build a drive with `driveAlongPath(rig, points, { cruiseSpeed, groundHeight })`.
+3. Each frame, call `applyVehiclePoseToParts(rig, drive.sample(seconds))` and then `renderer.updateParts(parts)`.
+
+```js
+import { Renderer67 } from '67js';
+import { createVehicleRig, driveAlongPath, applyVehiclePoseToParts } from '67js/addons/vehicle';
+
+const rig = createVehicleRig({ parts: carParts });
+console.log(rig.wheels.length, rig.wheelbase, rig.trackWidth);
+const drive = driveAlongPath(rig, [[0, 0, 0], [10, 0, 4], [20, 0, 4], [30, 0, 0]], { cruiseSpeed: 8, groundHeight: terrain.heightAt });
+const renderer = new Renderer67(canvas, [...sceneParts, ...carParts]);
+function draw(seconds) {
+ const pose = drive.sample(Math.min(seconds, drive.duration));
+ applyVehiclePoseToParts(rig, pose);
+ renderer.updateParts(carParts);
+ renderer.render({ eye, target: pose.position });
+}
+```
+
+Scene-graph nodes and imported GLBs use `applyVehiclePoseToSceneGraph` and `applyVehiclePoseToAsset`.
+
+## Conventions and options
+
+Units are metres, +Y is up and the system is right-handed. Angles are radians. The model's forward axis is `+z` unless `forwardAxis` is `'+x'`, `'-x'` or `'-z'`. Left is `up x forward`, so left is `+x` when forward is `+z`. The rig builds a local frame on the ground under the centroid of the wheel centres and moves the whole model with it. `pose.heading` is yaw about +Y, zero when facing +z. `pitch` is positive nose up, `roll` is positive when the left side rises, and steering is positive toward the left.
+
+`driveAlongPath(rig, path, options)` returns `{ sample(seconds), duration, length, rig }`. The path is an array of `[x, y, z]` points, smoothed with a centripetal spline, or a camera path object whose eye track is followed. Give exactly one speed option.
+
+| Option | Meaning |
+| --- | --- |
+| `speed` | Constant metres per second, no ramp. |
+| `cruiseSpeed` | A profile with `acceleration` (3), `braking` (4), `startSpeed` (0), `endSpeed` (0) and `maxLateralAcceleration` (unlimited). |
+| `startTime`, `groundHeight(x, z)`, `maxSteerAngle` | Start offset, ground fit and steering clamp. |
+| `rollGain`, `pitchGain` | 0.012 rad per m/s² each. |
+| `bounceFrequency`, `dampingRatio`, `suspensionTravel` | 1.6 Hz, 0.45 and 0.2 m. |
+| `pathSamples` | 400, for camera paths. |
+
+`sample(seconds)` returns `{ time, distance, speed, direction, position, heading, pitch, roll, steerAngle, wheels: [{ id, spinAngle, steerAngle, suspensionOffset }], lights }`. Roll and pitch follow lateral and longitudinal acceleration through a spring and damper, integrated at a fixed step when the drive is created, so sampling order does not matter. With `groundHeight`, the body height and its slope are fitted to the ground under the four wheels, and each wheel gets a `suspensionOffset`. The vehicle holds the end of the path with zero speed. Use `cruiseSpeed` for a natural stop, because a constant `speed` stops instantly and the body pitches.
+
+## Limits
+
+- Kinematic only: no collisions, tire slip or jumps. Heading follows the path tangent, plus a half turn while reversing.
+- Ground is a plane fit under the wheels, so bumps narrower than the wheelbase show as suspension offsets, clamped to `suspensionTravel`.
+- Rear-steered wheels get no Ackermann angle.
+- Through MCP the tail lights drive only the materials of an asset recipe, and `groundHeight` is not available.
+- Scene-graph nodes with a nonzero `pivot` are rejected. Wheel radius from geometry assumes a round wheel in the plane across its axle.
+
+The [vehicle contract](https://github.com/codepawl/67.js/blob/main/docs/vehicle.md) lists conventions, options and limits.
+
+## Common mistakes
+
+- A model whose forward axis is not `+z` and no `forwardAxis`. The car drives sideways.
+- Wheels that are merged into one geometry. The rig finds wheels by name and geometry, so keep them separate parts.
+- Sampling past `drive.duration`. The vehicle holds the end of the path.
+- Using a constant `speed` and expecting a smooth stop.
+- Expecting collisions. The drive is kinematic.
diff --git a/public/docs-media/animation-curves.webp b/public/docs-media/animation-curves.webp
new file mode 100644
index 00000000..784eff92
Binary files /dev/null and b/public/docs-media/animation-curves.webp differ
diff --git a/public/docs-media/animation-mixer.webp b/public/docs-media/animation-mixer.webp
new file mode 100644
index 00000000..420b9749
Binary files /dev/null and b/public/docs-media/animation-mixer.webp differ
diff --git a/public/docs-media/assembly-explode.webp b/public/docs-media/assembly-explode.webp
new file mode 100644
index 00000000..c026ae54
Binary files /dev/null and b/public/docs-media/assembly-explode.webp differ
diff --git a/public/docs-media/crowd-walk.webp b/public/docs-media/crowd-walk.webp
new file mode 100644
index 00000000..722a3493
Binary files /dev/null and b/public/docs-media/crowd-walk.webp differ
diff --git a/public/docs-media/deterministic-animation.webp b/public/docs-media/deterministic-animation.webp
new file mode 100644
index 00000000..903646a4
Binary files /dev/null and b/public/docs-media/deterministic-animation.webp differ
diff --git a/public/docs-media/films-budget.webp b/public/docs-media/films-budget.webp
new file mode 100644
index 00000000..e3726f0e
Binary files /dev/null and b/public/docs-media/films-budget.webp differ
diff --git a/public/docs-media/grass-tiles.webp b/public/docs-media/grass-tiles.webp
new file mode 100644
index 00000000..7ac19c55
Binary files /dev/null and b/public/docs-media/grass-tiles.webp differ
diff --git a/public/docs-media/performance-batching.webp b/public/docs-media/performance-batching.webp
new file mode 100644
index 00000000..1a8eeef5
Binary files /dev/null and b/public/docs-media/performance-batching.webp differ
diff --git a/public/docs-media/performance-memory.webp b/public/docs-media/performance-memory.webp
new file mode 100644
index 00000000..7b03f90a
Binary files /dev/null and b/public/docs-media/performance-memory.webp differ
diff --git a/public/docs-media/physics-recording.webp b/public/docs-media/physics-recording.webp
new file mode 100644
index 00000000..ca4c1032
Binary files /dev/null and b/public/docs-media/physics-recording.webp differ
diff --git a/public/docs-media/skeletal-morph.webp b/public/docs-media/skeletal-morph.webp
new file mode 100644
index 00000000..e5adeab1
Binary files /dev/null and b/public/docs-media/skeletal-morph.webp differ
diff --git a/public/docs-media/spume-playback.webp b/public/docs-media/spume-playback.webp
new file mode 100644
index 00000000..26a1832b
Binary files /dev/null and b/public/docs-media/spume-playback.webp differ
diff --git a/public/docs-media/terrain-rules.webp b/public/docs-media/terrain-rules.webp
new file mode 100644
index 00000000..fa2401d3
Binary files /dev/null and b/public/docs-media/terrain-rules.webp differ
diff --git a/public/docs-media/trees-scatter.webp b/public/docs-media/trees-scatter.webp
new file mode 100644
index 00000000..cf972f6b
Binary files /dev/null and b/public/docs-media/trees-scatter.webp differ
diff --git a/public/docs-media/vehicle-drive.webp b/public/docs-media/vehicle-drive.webp
new file mode 100644
index 00000000..68af9379
Binary files /dev/null and b/public/docs-media/vehicle-drive.webp differ