Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Rewrite six guide sections as docs pages with live examples (part of #508)

Nguyen Xuan An532429424928
diff --git a/changes/508-learn-pages.md b/changes/508-learn-pages.md
new file mode 100644
index 00000000..15ac507e
--- /dev/null
+++ b/changes/508-learn-pages.md
@@ -0,0 +1 @@
+- Docs: rewrite six guide sections as teaching pages with live examples (part of #508). The pages cover cameras, materials, lighting, model import and export, troubleshooting, and AI agents. The examples include mouse orbit, a material chart, a canvas texture, a moving sun and a lamp with bloom. They also include a GLB viewer and PNG and GLB download buttons. The pages correct stale text. Without `world: true`, the default field of view is about 32.7 degrees. The glTF importer has its own parser and reads alpha and double-sided materials.
diff --git a/docs/guide.md b/docs/guide.md
index a0976f83..4eb27a7a 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -242,21 +242,6 @@ Updates sample the selected triangle without rebuilding a BVH.
Static raycast hits can supply binding coordinates, but query indices cannot raycast a visibly skinned or morphed surface.
An attachment positions one rigid frame. It does not conform the accessory footprint or prevent every intersection.
-## Materials and color
-
-`color` and `emissiveColor` are linear RGB. `metallic` and `roughness` describe the PBR surface. `emission` sets emission intensity. `material.map` is a decoded texture descriptor with an image, UV channel 0, color space and supported sampler settings.
-
-The optional GLB addon creates these descriptors. HDR requires `EXT_color_buffer_float`. Inspect `renderer.capabilities.hdr` and `hdrFallbackReason`. The renderer falls back when floating-point targets are unavailable.
-
-Tags select specialized behavior: `armor` allows studio finish overrides. `floor` is a studio floor. `water` adds animated normals and ripples. `foliage` and `grass` add wind and accept a base-colour `map` with alpha mask, a `normalMap` and `doubleSided` for leaf cards.
-In code, a renderer that draws a `water`, `foliage`, `grass`, `terrain`, `moss`, `fire` or `smoke` part needs `import '@codepawlhq/67js/addons/world-material-shader'` first, and one that draws a transmissive, `liquid` or `foam` part needs `import '@codepawlhq/67js/addons/liquid-shader'`. The terrain, vegetation, grass, clutter and film addons and the MCP server import them for you.
-
-`material.alphaMode` is `'opaque'` (default), `'mask'` (cutout at `alphaCutoff`, default 0.5, shadows follow it) or `'blend'` (drawn last, back to front, no depth write). `material.opacity` (default 1) multiplies the base map alpha. `material.doubleSided` (default false) disables back-face culling and lights both faces. These are batch state and cannot change after upload. See `docs/material-maps.md`.
-
-`terrain` adds surface variation. `fire` and `smoke` support film effects. `unlit` is a flat color. Other tags use ordinary PBR shading.
-
-`water` flattens normals into a rippled pond and only suits horizontal surfaces. Shaped water uses `liquid`: it is drawn after the opaque scene, refracts what lies behind it, darkens with thickness and reflects the environment by the Fresnel term. Its `color` is the light one metre of liquid lets through, so `[0.56, 0.84, 0.88]` is clear blue-green water. `foam` draws soft alpha-blended droplets for whitewater. Tune both with `frame.liquid` or `environment.liquid`: `{ thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 }`. A liquid refracts opaque parts only.
-
## Renderer reference
`new Renderer67(canvas, parts, options)` owns GPU geometry, texture and target allocations. Constructor options:
@@ -284,43 +269,6 @@ Construct a new renderer for a new graph. `dispose()` releases owned resources.
Read `memoryPlan` for actual width, height, estimatedBytes and reduced status. `capabilities` for HDR and MSAA negotiation. `triangles`, `batches.length` and `cpuMilliseconds` for diagnostics. CPU submission time is not GPU frame time.
-## Cameras and framing
-
-A perspective frame supplies `eye`, `target`, optional `up`, `fov` in degrees, `near` and `far`. Set `projection: 'orthographic'` and `orthographicHeight` for axis views. Clipping planes must satisfy `0 < near < far`.
-
-`cameraView('front' | 'right' | 'top' | 'perspective', { target, height, distance })` creates an axis camera. `fitOrthographicHeight(bounds, view, aspect, padding)` frames the bounds without cropping. Bounds have `minimum` and `maximum` vectors. Flat 2D uses XY geometry, the `unlit` tag and a front orthographic camera.
-
-The canvas2d addon supplies a reusable poster scene.
-
-## Effects and lighting
-
-```js
-renderer.render({
- eye: [3,2,4], target: [0,0,0], exposure: 1,
- effects: {
- bloom: { strength: 0.18, threshold: 0.9, radius: 1.2 },
- saturation: 1, contrast: 1.04, temperature: 0.03, vignette: 0.12, grain: 0,
- },
-});
-```
-
-`EFFECT_PRESETS` provides ready-made looks. `resolveEffects` validates and resolves settings. Bloom uses retained half-resolution targets included in the memory estimate. Start with neutral settings and small changes.
-
-Bloom cannot recover missing geometry or lighting detail.
-
-### Depth of field, motion blur and render passes
-
-Depth of field and camera motion blur live in `67js/addons/camera-effects`, so the core carries none of their shader text.
-Call `installCameraEffects(renderer)` on a renderer made with `depth: true`, then set `effects.depthOfField: { blur: 0.6, focusDistance: 4 }` or `effects.motionBlur: { shutter: 0.1 }`.
-Motion blur also needs `frame.previousCamera` (`eye`, `target`, `up` and the lens fields) for the camera at `time - shutter`; derive it from the frame time and the result repeats on every seek.
-Each effect compiles and allocates its targets on the first frame that turns it on. These targets are not in the memory estimate.
-
-`renderer.render({ ...camera, pass: 'depth' })` draws a raw pass instead of the lit image: `albedo`, `normal`, `emission`, `depth` (with `passDepthRange` metres, default 100) or `objectId`.
-Passes draw without multisampling into their own target, and `renderer.passObjectNames()` lists the part behind each object ID.
-The pass branch of the main shader compiles on the first pass request. MCP render jobs write passes to files; see [agent render jobs](agent-render-jobs.md#render-passes).
-
-Outdoor `environment` accepts `skyTop`, `skyBottom` (display RGB), `fogColor` (linear RGB), `fogDensity` (unset, it is 0.006, thinned to 1.2 divided by the scene diagonal for scenes wider than about 200 m), `lightDirection` and `daylight`. Set `world: true` and `ground: false`. Frames can override environment and supply `time`, `wind`, `waterRipple` and `rippleTime`.
-
## Local lights and volume fog
Version `0.4.0` supports local lighting through the renderer's `environment` option and per-frame environment overrides.
@@ -422,25 +370,6 @@ Explodable parts include `assembly: { layer: 'exterior' | 'interior', section, o
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`.
-## Import and export models
-
-```js
-import { loadGltf } from '67js/addons/gltf';
-const asset = await loadGltf('/model.glb');
-const renderer = new Renderer67(canvas, asset.parts, { ground: false, hdr: true });
-if (asset.animations.length) renderer.updateParts(asset.applyAnimation(1));
-renderer.render({ eye: [3,2,4], target: [0,0,0] });
-// Close in this order: renderer.dispose(); asset.dispose();
-```
-
-Version `0.4.0` imports supported opaque meshes, vertex colors, five PBR texture channels, skins, relative morph targets and animation.
-Transparent or double-sided materials and compressed geometry remain unsupported.
-The optional decoder uses Three.js GLTFLoader without its renderer. Read the [asset contract](/gltf.md) before choosing a model.
-
-Core `exportGlb(parts)` returns GLB geometry. This geometry exporter is not a full texture/animation round-trip. For exploded output, apply `assemblyOffset` to copied matrices. Use the browser demo's PNG controls for a still.
-
-Render immediately before canvas capture.
-
## Images and films
Offline media commands run from the repository checkout, not from an installed npm package. Install checkout 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`.
@@ -471,53 +400,6 @@ The planner includes geometry, textures and mipmaps, shadows, MSAA, HDR, bloom a
Driver/browser allocations can still fail. Sampled browser JS heap and Node RSS do not measure total graphics memory.
-## Lifecycle and troubleshooting
-
-WebGL2 unavailable: enable hardware acceleration or choose a supported browser. CPU export can use SwiftShader. Jagged edges: inspect actual render size and negotiated samples. Increase pixelRatio only within the budget.
-
-Blown highlights: lower exposure and bloom, check linear color values. Missing asset: inspect its unsupported-feature error and convert the asset to the supported subset. Memory error: reduce resolution, MSAA, textures or scene detail. Context loss: stop playback, dispose the renderer and recreate on restoration.
-
-Release mismatch: compare VERSION and homepage release metadata.
-
-Disconnect observers, cancel animation frames, release pointer state and call `dispose()` on page/component teardown. Dispose decoded assets after the renderer. Keep errors visible. Do not silently substitute a different asset.
-
-## Models and AI agents
-
-Version `0.5.0` includes [agent scene sessions](/agent-scene.md) and the `67js-mcp` command.
-Its [MCP server](/mcp.md) provides twenty-two tools for authoring, previewing and exporting scenes through a persistent browser runtime.
-Release `0.7.0` adds [agent motion](/agent-motion.md) for deterministic joint, material and camera keyframes.
-Read the MCP guide for npm installation, client configuration and CPU/GPU selection.
-The [agent look contract](/agent-look.md) adds retained lighting, volumetric fog, grading and directional shadows to recipe edits and checkpoints.
-Release `0.8.0` adds [imported character motion](/agent-character-motion.md) with editable joints and retained skin, morph and texture resources.
-
-Release `0.9.0` adds [visual review](/agent-review.md) for several labeled views or motion samples in one PNG grid.
-Review uses an isolated snapshot and preserves the source preview pose, revision and checkpoint handles.
-
-The [asset adapter](/agent-asset.md) imports local catalog GLBs with supported textures, rigs, morphs and deterministic clip sampling.
-
-The addon accepts JSON recipes with stable object IDs, shared geometry and material resources, hierarchy and a camera.
-Edits use an expected revision and commit as one batch. Checkpoints restore the supported scene state.
-The session keeps existing renderer-facing parts and matrices for transform, material and camera edits.
-
-Agents can build from an empty recipe with `add-geometry`, `add-material` and `add-node` commands.
-Explicit removal and rebinding use the same atomic batch contract.
-Checkpoints retain shared geometry under the session budget. Release unused snapshots before increasing scene detail.
-The preview reconciles rigid topology, textured parts too with the `replace-textured-parts` addon, while keeping unchanged geometry buffers and draw batches.
-
-The CPU addon owns recipe state. The separate Node MCP server connects it to browser rendering. Background render jobs remain unsupported.
-
-Give the agent this guide and the matching repository skill. Start with a scene brief: focal subject, visual references, camera, output size, required interaction, GPU/CPU backend and memory budget. Read the matching scene recipe and run the smallest trial first.
-
-Suggested prompt: “Use 67js to build an interactive mechanical study. Reuse meshes, use a 256MiB render budget, provide orbit and keyboard controls, pause hidden playback, and capture a real wide and mobile preview. List unsupported features. Do not claim speed superiority without a comparable benchmark.”
-
-Agent workflow: inspect the installed `VERSION` and supported exports. Create finite invertible transforms. Share geometry identities. Validate bounds.
-
-Render and inspect edges/highlights. Exercise interactions. Run project tests. Export one deterministic frame.
-
-Report actual dimensions and estimated memory separately from observed process metrics. Never infer visual quality from successful compilation.
-
-Repository skills: `skills/build-67js-scene/SKILL.md` and `skills/render-67js-media/SKILL.md` contain the scene and media procedures. Copy or reference them in your agent's skill system. They are also included in the npm archive. A model can use the plain-text guide without a skill runtime.
-
## Addons and limits
Core exports are available from `67js`:
diff --git a/docs/learn/cameras-and-framing.md b/docs/learn/cameras-and-framing.md
new file mode 100644
index 00000000..b5aad6e2
--- /dev/null
+++ b/docs/learn/cameras-and-framing.md
@@ -0,0 +1,156 @@
+# Cameras and framing
+
+The camera is not an object in the scene. Each call to `renderer.render(frame)` gets a frame object, and the frame sets where the camera is, where it looks and how wide it sees. To move the camera, draw the next frame with other values.
+
+## Frame fields
+
+| Field | Default | Meaning |
+| --- | --- | --- |
+| `eye` | required | The camera position. |
+| `target` | `[0, 1.2, 0]` | The point that the camera looks at. |
+| `up` | `[0, 1, 0]` | The direction that is up in the picture. |
+| `fov` | about `32.7`, or `45` with `world: true` | The vertical field of view in degrees, more than 0 and less than 180. |
+| `near` | `0.1` | The nearest distance that the camera draws. |
+| `far` | `100`, or `600` with `world: true` | The farthest distance that the camera draws. |
+| `projection` | `'perspective'` | Set `'orthographic'` for a view without perspective. |
+| `orthographicHeight` | `4` | The height of an orthographic view in world units. |
+
+The clipping planes must satisfy `0 < near < far`. Keep `far / near` small, because a large ratio makes far surfaces flicker. [Contact detection](#contact-detection) explains how to fix depth precision for very large scenes.
+
+## Orbit with the mouse
+
+Most viewers turn the camera around the subject. Drag in the picture below to orbit, and use the wheel to zoom. On a phone, drag with one finger.
+
+```js live poster=cameras-orbit
+import { Renderer67, box } from '67js';
+
+function placeAt(x, y, z, width, height) {
+ return new Float32Array([width, 0, 0, 0, 0, height, 0, 0, 0, 0, width, 0, x, y, z, 1]);
+}
+
+// One geometry for all towers: the renderer draws them in one batch.
+const tower = box(0.04, 2);
+const parts = [];
+for (let row = -1; row <= 1; row++) {
+ for (let column = -1; column <= 1; column++) {
+ const height = 0.6 + ((row + 2) * (column + 3)) % 5 * 0.35;
+ parts.push({
+ name: `Tower ${row} ${column}`,
+ geometry: tower,
+ matrix: placeAt(column * 1.1, height / 2, row * 1.1, 0.8, height),
+ material: { color: [0.32, 0.4 + row * 0.08, 0.55], metallic: 0, roughness: 0.6 },
+ });
+ }
+}
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const renderer = new Renderer67(canvas, parts);
+const orbit = { yaw: 0.7, pitch: 0.45, distance: 7 };
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance + 0.6, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 0.6, 0], fov: 45 });
+}
+
+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(20, Math.max(3, orbit.distance * Math.exp(event.deltaY * 0.001)));
+ draw();
+}, { passive: false });
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+```
+
+The code keeps three numbers: the angle around the subject (`yaw`), the angle above the floor (`pitch`) and the distance. Each pointer move changes them and draws one frame. The scene does not change, so the page draws only after input.
+
+Try `fov: 20` for a long lens with flat depth, or `fov: 80` for a wide lens with strong perspective. Move `distance` at the same time to keep the subject the same size.
+
+> **Tip:** `touchAction = 'none'` stops the browser from scrolling the page when a finger drags on the canvas. Give the reader a keyboard control too, such as the arrow keys.
+
+## Axis views and fitted framing
+
+`cameraView(name, { target, height, distance })` returns a complete frame for the `'front'`, `'right'`, `'top'` or `'perspective'` view. The first three are orthographic, so parallel lines stay parallel. `fitOrthographicHeight(bounds, view, aspect, padding)` finds the `orthographicHeight` that shows the bounds without cropping. Bounds have `minimum` and `maximum` vectors.
+
+```js live poster=cameras-front
+import { Renderer67, box, sphere, cameraView, fitOrthographicHeight } from '67js';
+
+const placeAt = (x, y, z, size) => new Float32Array([size, 0, 0, 0, 0, size, 0, 0, 0, 0, size, 0, x, y, z, 1]);
+const parts = [
+ { name: 'Base', geometry: box(), matrix: placeAt(0, 0.5, 0, 1), material: { color: [0.3, 0.42, 0.55], metallic: 0, roughness: 0.6 } },
+ { name: 'Head', geometry: sphere(), matrix: placeAt(0, 1.45, 0, 0.45), material: { color: [0.9, 0.62, 0.2], metallic: 0, roughness: 0.4 } },
+];
+const bounds = { minimum: [-0.5, 0, -0.5], maximum: [0.5, 1.9, 0.5] };
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, parts);
+
+function draw() {
+ const view = cameraView('front', { target: [0, 0.95, 0], distance: 6 });
+ const aspect = canvas.clientWidth / canvas.clientHeight;
+ view.orthographicHeight = fitOrthographicHeight(bounds, view, aspect, 1.2);
+ renderer.render(view);
+}
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+```
+
+The model fills the height of the picture with a margin of 20 percent. Change `'front'` to `'right'`, `'top'` or `'perspective'` to see the other views. A perspective view uses `fitPerspectiveDistance(bounds, view, aspect, padding)` instead, which returns the distance from the eye to the target.
+
+Flat 2D uses XY geometry, the `unlit` material tag and a front orthographic camera. The `67js/addons/canvas2d` addon supplies a poster scene that you can reuse.
+
+## Camera moves
+
+For a planned shot, `createCameraPath` samples the eye, the target, the field of view and the roll at a time. The frame that `path.sample(seconds)` returns goes straight to `renderer.render`.
+
+```js live poster=cameras-path loop=4
+import { Renderer67, box, sphere, createCameraPath, fovFromFocalLength } from '67js';
+
+const placeAt = (x, y, z, size) => new Float32Array([size, 0, 0, 0, 0, size, 0, 0, 0, 0, size, 0, x, y, z, 1]);
+const parts = [
+ { name: 'Cube', geometry: box(), matrix: placeAt(0, 0.5, 0, 1), material: { color: [0.2, 0.55, 0.38], metallic: 0, roughness: 0.55 } },
+ { name: 'Ball', geometry: sphere(), matrix: placeAt(1.4, 0.4, -0.6, 0.4), material: { color: [1, 0.72, 0.3], metallic: 1, roughness: 0.25 } },
+];
+const path = createCameraPath({
+ duration: 4,
+ loop: true,
+ eye: {
+ interpolation: 'SMOOTH',
+ keyframes: [
+ { time: 0, value: [-3, 1.2, 3.5] },
+ { time: 2, value: [3, 2.4, 3.5] },
+ { time: 4, value: [-3, 1.2, 3.5] },
+ ],
+ },
+ target: [0.3, 0.5, 0],
+ fov: fovFromFocalLength(40, { sensorHeight: 24 }),
+});
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, parts);
+new ResizeObserver(() => renderer.resize()).observe(canvas);
+
+function frame(milliseconds) {
+ renderer.render(path.sample(milliseconds / 1000));
+ requestAnimationFrame(frame);
+}
+requestAnimationFrame(frame);
+```
+
+![The camera swings from left to right in front of a cube and a gold ball, then back](/docs-media/cameras-path.webm "A looping camera path with a 40 mm lens.")
+
+`fovFromFocalLength(40, { sensorHeight: 24 })` turns a lens of 40 mm on a full-frame sensor into a field of view in degrees. The [camera path contract](https://github.com/codepawl/67.js/blob/main/docs/camera-path.md) lists the channels, the tangents, the tracking options and the limits.
diff --git a/docs/learn/effects-and-lighting.md b/docs/learn/effects-and-lighting.md
new file mode 100644
index 00000000..8f7e5deb
--- /dev/null
+++ b/docs/learn/effects-and-lighting.md
@@ -0,0 +1,134 @@
+# Effects and lighting
+
+Every renderer starts with a studio light rig: one key light that casts shadows, two fill lights and a soft ambient light. You can turn the key light, change the strength of each light, add local lamps, switch to an outdoor sky, and grade the final picture.
+
+## Move the sun
+
+`environment.lightDirection` points from the scene toward the key light. Set it on the renderer, or override it in one frame with `frame.environment`. Drag across the picture below to move the light, and watch the shadows.
+
+```js live poster=lighting-sun
+import { Renderer67, box, sphere, cylinder } from '67js';
+
+const placeAt = (x, y, z, width, height = width) => new Float32Array([width, 0, 0, 0, 0, height, 0, 0, 0, 0, width, 0, x, y, z, 1]);
+const parts = [
+ { name: 'Column', geometry: cylinder(48), matrix: placeAt(-1, 0.9, 0, 0.3, 1.8), material: { color: [0.8, 0.78, 0.72], metallic: 0, roughness: 0.7 } },
+ { name: 'Block', geometry: box(), matrix: placeAt(0.4, 0.35, 0.3, 0.7), material: { color: [0.3, 0.45, 0.62], metallic: 0, roughness: 0.5 } },
+ { name: 'Ball', geometry: sphere(), matrix: placeAt(1.3, 0.3, -0.4, 0.3), material: { color: [0.9, 0.55, 0.2], metallic: 0, roughness: 0.35 } },
+];
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const renderer = new Renderer67(canvas, parts);
+let sunAngle = 0.9;
+
+function draw() {
+ const lightDirection = [Math.cos(sunAngle) * 4, 5, Math.sin(sunAngle) * 4];
+ renderer.render({ eye: [0, 2.6, 5], target: [0, 0.5, 0], environment: { lightDirection } });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ sunAngle += event.movementX * 0.01;
+ draw();
+});
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+```
+
+These `environment` fields set the strength of the studio lights. Each one defaults to 1.
+
+| Field | Effect |
+| --- | --- |
+| `keyIntensity` | The key light, which casts the shadows. `keyColor` sets its color in linear RGB. |
+| `fillIntensity` | The two fill and rim lights. |
+| `ambientIntensity` | The soft light from all sides and the reflection of the studio. |
+
+Set all three to 0 to see only your own lamps. The sky, emission and fog still show.
+
+## Lamps and glow
+
+`environment.pointLights` adds up to 16 local lights. Each light has a `position`, a linear `color`, an `intensity`, a `radius` and a `range` in meters. To make the bulb itself glow, give its part `emission`, and add bloom in the frame.
+
+```js live poster=lighting-lamp
+import { Renderer67, box, sphere } from '67js';
+
+const placeAt = (x, y, z, width, height = width, depth = width) => new Float32Array([width, 0, 0, 0, 0, height, 0, 0, 0, 0, depth, 0, x, y, z, 1]);
+const bulbPosition = [0, 1.3, 0];
+const parts = [
+ { name: 'Table', geometry: box(0.02), matrix: placeAt(0, 0.4, 0, 2.4, 0.08, 1.4), material: { color: [0.36, 0.24, 0.16], metallic: 0, roughness: 0.55 } },
+ { name: 'Bulb', geometry: sphere(), matrix: placeAt(...bulbPosition, 0.12), material: { color: [1, 0.8, 0.55], metallic: 0, roughness: 0.3, emission: 6 } },
+ { name: 'Cup', geometry: box(0.2), matrix: placeAt(0.6, 0.6, 0.2, 0.3, 0.32, 0.3), material: { color: [0.85, 0.85, 0.82], metallic: 0, roughness: 0.25 } },
+ { name: 'Book', geometry: box(0.05), matrix: placeAt(-0.6, 0.5, 0.1, 0.7, 0.12, 0.5), material: { color: [0.2, 0.32, 0.5], metallic: 0, roughness: 0.7 } },
+];
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, parts, {
+ hdr: true,
+ environment: {
+ keyIntensity: 0.05,
+ fillIntensity: 0.05,
+ ambientIntensity: 0.15,
+ pointLights: [{ position: bulbPosition, color: [1, 0.72, 0.45], intensity: 6, radius: 0.12, range: 6 }],
+ },
+});
+
+new ResizeObserver(() => {
+ renderer.resize();
+ renderer.render({
+ eye: [0, 1.9, 3.2],
+ target: [0, 0.6, 0],
+ exposure: 1.1,
+ effects: { bloom: { strength: 0.35, threshold: 1, radius: 1.2 }, vignette: 0.2 },
+ });
+}).observe(canvas);
+```
+
+The studio lights are almost off, so the warm point light lights the table. The bright bulb is above the bloom `threshold`, so it glows. Point lights have no local shadows and can light through walls. `radius` softens the falloff near the light. It does not make an area light. The [lighting contract](/lighting.md) has spot lights, area lights, local shadows and light linking.
+
+## Grade the picture
+
+The frame takes `exposure` and an `effects` object. Start with neutral values and change one at a time.
+
+```js
+renderer.render({
+ eye: [3, 2, 4], target: [0, 0, 0], exposure: 1,
+ effects: {
+ bloom: { strength: 0.18, threshold: 0.9, radius: 1.2 },
+ saturation: 1, contrast: 1.04, temperature: 0.03, vignette: 0.12, grain: 0,
+ },
+});
+```
+
+| Effect | Range | Default |
+| --- | --- | --- |
+| `bloom.strength` | 0 to 2 | 0 |
+| `bloom.threshold` | 0 to 10 | 1 |
+| `bloom.radius` | 0.1 to 4 | 1 |
+| `saturation`, `contrast` | 0 to 2, 0.1 to 2 | 1 |
+| `temperature` | -1 (cool) to 1 (warm) | 0 |
+| `vignette` | 0 to 1 | 0 |
+| `grain` | 0 to 0.1 | 0 |
+
+`EFFECT_PRESETS` has the ready looks `neutral`, `cinematic` and `vivid`. `resolveEffects(effects)` checks your settings and fills in the defaults. Bloom uses retained half-resolution targets, which the memory estimate includes. Bloom cannot add detail that the geometry or the lights do not have.
+
+### Depth of field, motion blur and render passes
+
+Depth of field and camera motion blur live in `67js/addons/camera-effects`, so the core carries none of their shader text. Call `installCameraEffects(renderer)` on a renderer made with `depth: true`. Then set `effects.depthOfField: { blur: 0.6, focusDistance: 4 }` or `effects.motionBlur: { shutter: 0.1 }`.
+
+Motion blur also needs `frame.previousCamera` (`eye`, `target`, `up` and the lens fields) for the camera at `time - shutter`. Derive it from the frame time, so the result repeats on every seek. Each effect compiles and allocates its targets on the first frame that turns it on. The memory estimate does not include these targets.
+
+`renderer.render({ ...camera, pass: 'depth' })` draws a raw pass instead of the lit image: `albedo`, `normal`, `emission`, `depth` (with `passDepthRange` meters, default 100) or `objectId`. Passes draw without multisampling into their own target. `renderer.passObjectNames()` lists the part behind each object ID. The pass branch of the main shader compiles on the first pass request. MCP render jobs write passes to files. See [agent render jobs](/agent-render-jobs.md#render-passes).
+
+## Outdoor sky
+
+For an outdoor scene, set `world: true` and `ground: false` on the renderer, and add your own ground. Outdoor `environment` accepts these fields:
+
+- `skyTop` and `skyBottom`: the sky gradient in display RGB.
+- `fogColor`: the fog color in linear RGB.
+- `fogDensity`: 0.006 when unset. For a scene wider than about 200 m, it is 1.2 divided by the scene diagonal.
+- `lightDirection` and `daylight`: the sun direction and the amount of daylight.
+
+Frames can override the environment and supply `time`, `wind`, `waterRipple` and `rippleTime`. [HDR environment lighting](#hdr-environment-lighting) lights a scene from a photo of a real sky, and [Local lights and volume fog](#local-lights-and-volume-fog) adds light shafts.
diff --git a/docs/learn/import-and-export-models.md b/docs/learn/import-and-export-models.md
new file mode 100644
index 00000000..ea184a8e
--- /dev/null
+++ b/docs/learn/import-and-export-models.md
@@ -0,0 +1,145 @@
+# Import and export models
+
+67js reads and writes GLB, the binary form of glTF 2.0. Blender, Maya, Sketchfab and most model sites export it. The importer is the addon `67js/addons/gltf`, so a scene without models does not download it.
+
+## Load a GLB file
+
+`loadGltf(url)` returns an asset. `asset.parts` is a list of ordinary parts, ready for `Renderer67`. The example loads a robot from this site and frames it from its size.
+
+```js live poster=gltf-robot
+import { Renderer67 } from '67js';
+import { loadGltf } from '67js/addons/gltf';
+
+// The smallest box that holds every vertex of every part, in world units.
+function boundsOf(parts) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (const { geometry, matrix } of parts) {
+ const positions = geometry.positions;
+ for (let index = 0; index < positions.length; index += 3) {
+ const [x, y, z] = [positions[index], positions[index + 1], positions[index + 2]];
+ for (let axis = 0; axis < 3; axis++) {
+ const world = matrix[axis] * x + matrix[axis + 4] * y + matrix[axis + 8] * z + matrix[axis + 12];
+ minimum[axis] = Math.min(minimum[axis], world);
+ maximum[axis] = Math.max(maximum[axis], world);
+ }
+ }
+ }
+ return { minimum, maximum };
+}
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const asset = await loadGltf('/wall-e.glb');
+const renderer = new Renderer67(canvas, asset.parts, { hdr: true });
+const { minimum, maximum } = boundsOf(asset.parts);
+const center = minimum.map((value, axis) => (value + maximum[axis]) / 2);
+const size = Math.max(...maximum.map((value, axis) => value - minimum[axis]));
+let turn = 0.6;
+
+function draw() {
+ const distance = size * 1.9;
+ const eye = [center[0] + Math.sin(turn) * distance, center[1] + size * 0.35, center[2] + Math.cos(turn) * distance];
+ renderer.render({ eye, target: center, fov: 35 });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ turn -= event.movementX * 0.01;
+ draw();
+});
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+```
+
+`loadGltf` accepts a URL string, a `URL`, a `Blob` or a `File` from an `<input type="file">`. For an `ArrayBuffer` or a glTF JSON string, use `parseGltf(data, options)`. A `.gltf` file with separate `.bin` and texture files loads from its URL, because the importer finds the other files next to it. The result has these fields:
+
+| Field | Meaning |
+| --- | --- |
+| `parts` | The parts, with world matrices, shared geometry and decoded textures. |
+| `animations` | The animation clips in the file. |
+| `applyAnimation(seconds, clipIndex)` | Poses the parts at a time and returns them for `renderer.updateParts`. |
+| `warnings` | Features of the file that the importer skipped. |
+| `dispose()` | Releases the decoded images. |
+
+The importer reads meshes, vertex colors, the five PBR texture channels, alpha modes, double-sided materials, skins, morph targets and animation. It has its own parser and does not use three.js. The [asset contract](/gltf.md) lists the supported extensions, the decoders for compressed files and the size limits.
+
+> **Tip:** A model from Poly Haven or a similar site often comes as a folder with a `.gltf` file, a `.bin` file and textures. `loadGltf` reads that folder from its URL. To make one GLB file of it, run `npx @gltf-transform/cli copy model.gltf model.glb`.
+
+## Play an animation
+
+If `asset.animations` is not empty, pose the asset at a time in each frame:
+
+```js
+function frame(milliseconds) {
+ renderer.updateParts(asset.applyAnimation(milliseconds / 1000, 0));
+ renderer.render({ eye, target });
+ requestAnimationFrame(frame);
+}
+requestAnimationFrame(frame);
+```
+
+The second argument is the index of the clip. Skinned characters work the same way. [Skeletal and morph animation](#skeletal-and-morph-animation) and [Humanoid retargeting and crowds](#humanoid-retargeting-and-crowds) explain rigs, blending and moving one clip onto another character.
+
+## Save a picture or a model
+
+The canvas holds the last frame until the browser paints. Draw a frame, then read the canvas in the same task. `exportGlb(parts)` returns the parts as a GLB `ArrayBuffer`. Click the buttons in the example to save both files.
+
+```js live poster=export-buttons
+import { Renderer67, box, sphere, exportGlb } from '67js';
+
+const placeAt = (x, y, z, size) => new Float32Array([size, 0, 0, 0, 0, size, 0, 0, 0, 0, size, 0, x, y, z, 1]);
+const parts = [
+ { name: 'Cube', geometry: box(), matrix: placeAt(-0.6, 0.5, 0, 1), material: { color: [0.2, 0.55, 0.38], metallic: 0, roughness: 0.55 } },
+ { name: 'Ball', geometry: sphere(), matrix: placeAt(0.9, 0.45, 0.2, 0.45), material: { color: [1, 0.72, 0.3], metallic: 1, roughness: 0.25 } },
+];
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, parts);
+const draw = () => renderer.render({ eye: [0, 2, 4.5], target: [0, 0.4, 0] });
+
+function save(blob, fileName) {
+ const link = document.createElement('a');
+ link.href = URL.createObjectURL(blob);
+ link.download = fileName;
+ link.click();
+ URL.revokeObjectURL(link.href);
+}
+
+function button(label, onClick) {
+ const element = document.createElement('button');
+ element.textContent = label;
+ element.style.cssText = 'position:fixed;top:12px;padding:8px 14px;border:0;border-radius:10px;background:#ececec;color:#171717;font:14px system-ui';
+ element.style.left = `${12 + document.querySelectorAll('button').length * 120}px`;
+ element.addEventListener('click', onClick);
+ document.body.append(element);
+}
+
+button('Save PNG', () => {
+ draw();
+ canvas.toBlob(blob => save(blob, 'scene.png'), 'image/png');
+});
+button('Save GLB', () => {
+ save(new Blob([exportGlb(parts)], { type: 'model/gltf-binary' }), 'scene.glb');
+});
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+```
+
+`toBlob` reads the canvas at its real size, which is the CSS size times `pixelRatio`. For a picture of a fixed size, set the canvas size before you draw, or use `npm run render` from a checkout ([Images and films](#images-and-films)).
+
+The GLB keeps the geometry, the shared meshes, the colors, the UVs, the emission and the current morph weights. It is a snapshot of the static scene, not a full round trip of textures and animation. For an exploded view, apply `assemblyOffset` to copies of the matrices before the export. The [GLB snapshot contract](/export-glb.md) lists every stored channel.
+
+## Release the asset
+
+Release the renderer first, then the asset:
+
+```js
+renderer.dispose();
+asset.dispose();
+```
diff --git a/docs/learn/lifecycle-and-troubleshooting.md b/docs/learn/lifecycle-and-troubleshooting.md
new file mode 100644
index 00000000..43bc4391
--- /dev/null
+++ b/docs/learn/lifecycle-and-troubleshooting.md
@@ -0,0 +1,64 @@
+# Lifecycle and troubleshooting
+
+This page lists the problems that new users meet most often. Each section starts with what you see, then gives the cause and the fix. Most errors from 67js name the part or the value that failed, so read the full message in the browser console first.
+
+## The canvas stays empty
+
+- **The canvas has no size.** The renderer reads the CSS size of the canvas. A canvas inside an element with no height is 0 pixels high. Give the canvas or its parent a height in CSS, as in [step 1 of the tutorial](#first-scene/add-a-canvas).
+- **Nothing calls `render`.** `new Renderer67()` uploads the parts but does not draw. Call `renderer.render(frame)` after you make the renderer, and again after each `resize()`.
+- **The camera looks away from the parts.** Put `target` near the parts, and keep `eye` outside them. Start with `eye: [3, 2, 4]` and `target: [0, 0.5, 0]`.
+- **The parts are too small or too large.** `box()` has sides of 1 and `sphere()` has a radius of 1. A model in centimeters can be 100 times larger than you expect. [Load a GLB file](#import-and-export-models/load-a-glb-file) frames a model from its size.
+
+## Error: WebGL2 is unavailable
+
+The full message is `WebGL2 is unavailable. Enable hardware acceleration or use a supported browser.` Turn on hardware acceleration in the browser settings, or update the graphics driver. A current Chrome, Edge, Firefox or Safari has WebGL2. CPU export from a checkout can use SwiftShader, a software renderer, instead of a graphics card.
+
+## Error: Invalid transform or Singular transform
+
+`Invalid transform: Cube` means that the matrix of the part named Cube does not have 16 finite numbers. `Singular transform: Cube` means that the matrix cannot be inverted, for example because a scale is 0. Use a very small scale such as `0.0001` to hide a part, or leave the part out.
+
+## Error: Unknown part identity
+
+`updateParts` changes the matrices and the materials of parts that the renderer already has. A new part object, or a part that the renderer did not get at construction, causes this error. Change the fields of the existing part objects, as in [step 5 of the tutorial](#first-scene/animate-the-cube). To add or remove parts, make a new renderer, or call `renderer.replaceParts(parts)` for rigid parts without textures.
+
+## Error: Memory budget cannot hold
+
+The renderer estimates the memory of the geometry, the textures and one frame before it allocates them. If the estimate is over `memoryBudgetMiB`, the error names each amount and the budget that fits. Pass that budget, or make the scene smaller:
+
+1. Lower the resolution with a smaller `pixelRatio`.
+2. Lower `samples`, the antialiasing count.
+3. Use smaller textures, and share geometry and texture descriptors between parts.
+
+The estimate is an allocation budget, not a hard limit on the memory of the process.
+
+## Colors look washed out or too bright
+
+`color` is linear RGB. A value copied from a CSS color looks too light. Convert it as shown in [Colors are linear](#materials-and-color/colors-are-linear). If highlights are pure white, lower `exposure` and the bloom `strength`, and check that no `color` value is above 1.
+
+## Edges look jagged
+
+Read `renderer.memoryPlan` for the real width and height of the drawing, and `renderer.capabilities.samples` for the antialiasing count that the device accepted. Raise `pixelRatio` only while the memory plan stays inside the budget.
+
+## A model does not load
+
+The glTF importer refuses a file that it cannot read correctly, and the error names the feature or the limit. It does not draw a different model in its place. Convert the file to the supported subset, for example with `npx @gltf-transform/cli`. The [asset contract](/gltf.md) lists the supported features and the limits. Show the error to the user, and do not swap in another asset without a message.
+
+## The page loses the WebGL context
+
+A browser can drop the WebGL context when the graphics driver resets or when too many pages use WebGL. Stop the playback, call `dispose()` on the renderer, and make a new renderer when the browser fires `webglcontextrestored` on the canvas.
+
+## A feature in these docs is missing
+
+The site shows the current source, which can be newer than the npm release. Compare `VERSION` from `import { VERSION } from '67js'` with the [release metadata](/release.json), and read the [changelog](/changelog.html) for the version that adds the feature.
+
+## Clean up a scene
+
+When a page or a component goes away, release everything that the scene holds:
+
+1. Disconnect the `ResizeObserver`.
+2. Cancel the animation frame request.
+3. Release the pointer capture and remove the listeners.
+4. Call `renderer.dispose()`.
+5. Call `asset.dispose()` for each loaded GLB asset, after the renderer.
+
+[Step 6 of the tutorial](#first-scene/clean-up) has the code.
diff --git a/docs/learn/materials-and-color.md b/docs/learn/materials-and-color.md
new file mode 100644
index 00000000..454b17da
--- /dev/null
+++ b/docs/learn/materials-and-color.md
@@ -0,0 +1,148 @@
+# Materials and color
+
+A material tells the renderer how light hits a part. 67js uses physically based shading (PBR), the model of Blender, Unreal and the glTF format. So the values from those tools mean the same thing here.
+
+## The four basic fields
+
+| Field | Values | Effect |
+| --- | --- | --- |
+| `color` | three numbers from 0 to 1 | The base color in linear RGB. Required. |
+| `metallic` | 0 to 1 | 0 is a dielectric such as paint, plastic or wood. 1 is metal. Required. |
+| `roughness` | 0 to 1 | 0 is polished, 1 is fully matte. Required. The renderer keeps a minimum of `0.075`. |
+| `emission` | 0 or more | The strength of the light that the surface gives off. Optional, the default is 0. |
+| `emissiveColor` | three numbers from 0 to 1 | The color of that light in linear RGB. Optional, the default is `color`. |
+
+The chart below has a dielectric row in front and a metal row behind. Roughness goes from 0 on the left to 1 on the right. Drag to turn it.
+
+```js live poster=materials-chart
+import { Renderer67, sphere } from '67js';
+
+const ball = sphere(48, 24);
+const parts = [];
+for (let column = 0; column < 5; column++) {
+ for (const metallic of [0, 1]) {
+ const x = (column - 2) * 0.95;
+ const z = metallic ? -0.6 : 0.6;
+ parts.push({
+ name: `Ball ${column} ${metallic}`,
+ geometry: ball,
+ matrix: new Float32Array([0.4, 0, 0, 0, 0, 0.4, 0, 0, 0, 0, 0.4, 0, x, 0.4, z, 1]),
+ material: { color: metallic ? [0.95, 0.64, 0.32] : [0.75, 0.16, 0.14], metallic, roughness: column / 4 },
+ });
+ }
+}
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const renderer = new Renderer67(canvas, parts);
+let turn = 0;
+
+function draw() {
+ const eye = [Math.sin(turn) * 5.2, 2.6, Math.cos(turn) * 5.2];
+ renderer.render({ eye, target: [0, 0.3, 0], fov: 36 });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ turn -= event.movementX * 0.01;
+ draw();
+});
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+```
+
+A metal takes its reflection color from `color`, so gold, copper and steel differ by `color` only. A dielectric shows its `color` under a white reflection.
+
+## Colors are linear
+
+`color` and `emissiveColor` are linear RGB, not the sRGB values of CSS and color pickers. If you copy `#d94f2b` as `[0.85, 0.31, 0.17]`, the part looks too light and grey. Convert an sRGB hex color first:
+
+```js
+function linearColor(hex) {
+ const channels = hex.replace('#', '').match(/../g).map(pair => parseInt(pair, 16) / 255);
+ return channels.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4);
+}
+
+const material = { color: linearColor('#d94f2b'), metallic: 0, roughness: 0.5 };
+```
+
+## Textures
+
+A texture is a descriptor: an object with an `image` and a `colorSpace`. The image can be an `HTMLImageElement`, an `ImageBitmap` or a canvas. Textures sample `geometry.uvs`, so the geometry needs two UV values for each vertex. `sphere()` and `torus()` have UVs.
+
+```js live poster=materials-texture
+import { Renderer67, sphere } from '67js';
+
+// Draw a checkerboard on a 2D canvas and use it as the color map.
+const pattern = document.createElement('canvas');
+pattern.width = 256;
+pattern.height = 128;
+const pen = pattern.getContext('2d');
+for (let row = 0; row < 8; row++) {
+ for (let column = 0; column < 16; column++) {
+ pen.fillStyle = (row + column) % 2 ? '#f2efe6' : '#2f6f8f';
+ pen.fillRect(column * 16, row * 16, 16, 16);
+ }
+}
+
+const globe = {
+ name: 'Globe',
+ geometry: sphere(64, 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: [1, 1, 1], metallic: 0, roughness: 0.45, map: { image: pattern, colorSpace: 'srgb' } },
+};
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, [globe]);
+new ResizeObserver(() => {
+ renderer.resize();
+ renderer.render({ eye: [2.2, 1.6, 3], target: [0, 0.75, 0] });
+}).observe(canvas);
+```
+
+`map` multiplies `color`, so keep `color` white to show the image as it is. A material can have five texture channels:
+
+| Field | Color space | Effect |
+| --- | --- | --- |
+| `map` | `'srgb'` | Multiplies the base color. |
+| `normalMap` | `'linear'` | Adds surface detail that catches the light. `normalScale` sets its strength. |
+| `metallicRoughnessMap` | `'linear'` | Multiplies roughness by G and metallic by B. |
+| `occlusionMap` | `'linear'` | Darkens indirect light by R. `occlusionStrength` sets its strength. |
+| `emissiveMap` | `'srgb'` | Multiplies `emissiveColor * emission`. |
+
+The glTF addon makes these descriptors for you when it loads a GLB file. Reuse one descriptor object for many parts, because each new descriptor uploads a new texture. To change the pixels of an uploaded texture, import `@codepawlhq/67js/addons/texture-update` and call `renderer.updateTexture(descriptor, { image, region })`. The [material maps contract](https://github.com/codepawl/67.js/blob/main/docs/material-maps.md) lists the sampler settings and the limits.
+
+## Transparency and both sides
+
+`material.alphaMode` is `'opaque'` (the default), `'mask'` or `'blend'`. With `'mask'`, a pixel with alpha under `alphaCutoff` (default 0.5) is cut out, and shadows follow the cut. With `'blend'`, the part is drawn last, from back to front, and does not write depth. `material.opacity` (default 1) multiplies the alpha of the base map.
+
+`material.doubleSided` (default false) turns off back-face culling and lights both faces. Use it for leaves, paper and cloth.
+
+> **Warning:** `alphaMode`, `doubleSided` and the texture descriptors are batch state. `updateParts` cannot change them. Make a new renderer to change them. `updateParts` can change `color`, `metallic`, `roughness`, `emission`, `emissiveColor` and the matrix.
+
+## Material tags
+
+`material.tag` selects special shading. A part without a tag uses ordinary PBR shading.
+
+| Tag | Effect |
+| --- | --- |
+| `unlit` | A flat color without light. Use it for 2D and for labels. |
+| `floor` | The studio floor. |
+| `armor` | Allows the studio finish overrides `armorColor` and `armorSurface` in the frame. |
+| `water` | Animated normals and ripples. Flat water on horizontal surfaces only. |
+| `liquid` | Shaped water that refracts, darkens with thickness and reflects the sky. |
+| `foam` | Soft droplets for whitewater. |
+| `foliage`, `grass` | Wind. They accept a `map` with an alpha mask, a `normalMap` and `doubleSided` for leaf cards. |
+| `terrain`, `moss` | Surface variation for ground. |
+| `fire`, `smoke` | Effects for films. |
+
+A renderer that draws a `water`, `foliage`, `grass`, `terrain`, `moss`, `fire` or `smoke` part needs `import '@codepawlhq/67js/addons/world-material-shader'` first. A renderer that draws a transmissive, `liquid` or `foam` part needs `import '@codepawlhq/67js/addons/liquid-shader'`. The terrain, vegetation, grass, clutter and film addons and the MCP server import them for you.
+
+The `color` of a `liquid` is the light that one meter of liquid lets through, so `[0.56, 0.84, 0.88]` is clear blue-green water. Tune liquid and foam with `frame.liquid` or `environment.liquid`: `{ thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 }`. A liquid refracts opaque parts only.
+
+## High dynamic range
+
+With `hdr: true`, the renderer keeps colors above 1 for bloom and exposure. HDR needs the `EXT_color_buffer_float` extension. If the device does not have it, the renderer falls back to normal range. Read `renderer.capabilities.hdr` and `renderer.capabilities.hdrFallbackReason` to see the result.
diff --git a/docs/learn/models-and-ai-agents.md b/docs/learn/models-and-ai-agents.md
new file mode 100644
index 00000000..b1278855
--- /dev/null
+++ b/docs/learn/models-and-ai-agents.md
@@ -0,0 +1,81 @@
+# Models and AI agents
+
+An AI agent can build a 67js scene in two ways. With the MCP server, the agent calls tools that take JSON and return pictures, and it writes no engine code. Without MCP, the agent writes JavaScript like the code in these docs and renders it in a browser.
+
+## Connect an agent through MCP
+
+The package includes the `67js-mcp` server. It needs Node.js 20.19 or later and an installed Chrome or Chromium. It renders in a local browser and talks to the agent over stdin and stdout.
+
+1. Install the package in your project:
+
+```sh install
+npm install 67js@npm:@codepawlhq/67js
+```
+
+2. Check that the server starts. It prints the installed version:
+
+```sh
+npx 67js-mcp --version
+```
+
+3. Add the server to your MCP client with absolute paths to Node and the installed command:
+
+```json
+{
+ "mcpServers": {
+ "67js-scene": {
+ "command": "/usr/local/bin/node",
+ "args": ["/path/to/my-scene/node_modules/67js/bin/67js-mcp.mjs", "--backend", "gpu", "--memory", "192"]
+ }
+ }
+}
+```
+
+On Windows, the command is like `C:/Program Files/nodejs/node.exe`. `--backend` is `gpu` or `cpu`. `--memory` is the render budget from 32 to 384 MiB, and the default is 192. `--assets` names a folder of GLB files that the agent can place. The [MCP guide](/mcp.md) has every option, the tested clients and the limits.
+
+## What the agent does
+
+The server has 22 tools for authoring, previewing and exporting scenes. A normal session uses them in this order:
+
+1. `scene_capabilities` reads the supported features and limits.
+2. `scene_create` makes a scene from a [recipe](/agent-scene.md). A recipe is JSON with object IDs, geometry, materials, a hierarchy and a camera.
+3. `scene_look` returns a picture of the scene.
+4. `scene_apply` changes the scene in one batch. Each edit names the expected revision, so a stale edit fails without partial changes.
+5. `scene_checkpoint` and `scene_restore` save and return to a state. `scene_review` shows several views or variants in one picture grid.
+6. `scene_export_recipe` and the render job tools save the recipe, PNG images, image sequences and MP4 video.
+
+The agent can start from an empty recipe and add parts with `add-geometry`, `add-material` and `add-node` commands. The tools check every argument against a schema. The server never runs code that the agent writes.
+
+These guides cover the parts of a recipe:
+
+- [Look](/agent-look.md): lights, volume fog, grading and shadows.
+- [Motion](/agent-motion.md): keyframes for joints, materials and the camera.
+- [Character motion](/agent-character-motion.md): imported characters with editable joints.
+- [Assets](/agent-asset.md): GLB files from the catalog folder, with their textures, rigs and clips.
+- [Visual review](/agent-review.md): several labeled views or poses in one PNG grid.
+- [Render jobs](/agent-render-jobs.md): images, sequences, video and render passes.
+
+## Give the agent these docs
+
+An agent reads plain text best. Give it [the plain-text guide](/guide.md), which holds all of these docs in one Markdown file. The repository also has two skills that hold the scene and media procedures: `skills/build-67js-scene/SKILL.md` and `skills/render-67js-media/SKILL.md`. The npm archive includes them. Copy them into the skill folder of your agent, or point the agent at them.
+
+Start with a short brief: the subject, references, the camera, the output size, the interaction, the GPU or CPU backend and the memory budget. Ask for the smallest trial first. A prompt can look like this:
+
+```text
+Use 67js to build an interactive mechanical study. Reuse meshes, use a 256 MiB
+render budget, provide orbit and keyboard controls, pause hidden playback, and
+capture a real wide and mobile preview. List unsupported features. Do not claim
+speed superiority without a comparable benchmark.
+```
+
+## Check the work of an agent
+
+A successful build does not prove a good picture. Ask the agent to do these checks and to report the results:
+
+1. Read the installed `VERSION` and the exports that it uses.
+2. Use finite, invertible matrices, share geometry, and check the bounds.
+3. Render a frame and look at the edges and the highlights.
+4. Try every interaction, run the project tests and export one frame at a fixed time.
+5. Report the real size and the estimated memory apart from the measured process memory.
+
+Without MCP, the agent can still save an image from a script: [Render a PNG from a script without MCP](#render-a-png-from-a-script-without-mcp) has a tested example.
diff --git a/public/docs-media/cameras-front.webp b/public/docs-media/cameras-front.webp
new file mode 100644
index 00000000..f0fe7a5c
Binary files /dev/null and b/public/docs-media/cameras-front.webp differ
diff --git a/public/docs-media/cameras-orbit.webp b/public/docs-media/cameras-orbit.webp
new file mode 100644
index 00000000..8e869954
Binary files /dev/null and b/public/docs-media/cameras-orbit.webp differ
diff --git a/public/docs-media/cameras-path.webm b/public/docs-media/cameras-path.webm
new file mode 100644
index 00000000..78b5e109
Binary files /dev/null and b/public/docs-media/cameras-path.webm differ
diff --git a/public/docs-media/cameras-path.webp b/public/docs-media/cameras-path.webp
new file mode 100644
index 00000000..15a4d61f
Binary files /dev/null and b/public/docs-media/cameras-path.webp differ
diff --git a/public/docs-media/export-buttons.webp b/public/docs-media/export-buttons.webp
new file mode 100644
index 00000000..5f01cbae
Binary files /dev/null and b/public/docs-media/export-buttons.webp differ
diff --git a/public/docs-media/gltf-robot.webp b/public/docs-media/gltf-robot.webp
new file mode 100644
index 00000000..8b30294d
Binary files /dev/null and b/public/docs-media/gltf-robot.webp differ
diff --git a/public/docs-media/lighting-lamp.webp b/public/docs-media/lighting-lamp.webp
new file mode 100644
index 00000000..2cc8da1e
Binary files /dev/null and b/public/docs-media/lighting-lamp.webp differ
diff --git a/public/docs-media/lighting-sun.webp b/public/docs-media/lighting-sun.webp
new file mode 100644
index 00000000..2f48dc8e
Binary files /dev/null and b/public/docs-media/lighting-sun.webp differ
diff --git a/public/docs-media/materials-chart.webp b/public/docs-media/materials-chart.webp
new file mode 100644
index 00000000..58709c1a
Binary files /dev/null and b/public/docs-media/materials-chart.webp differ
diff --git a/public/docs-media/materials-texture.webp b/public/docs-media/materials-texture.webp
new file mode 100644
index 00000000..2b693c9b
Binary files /dev/null and b/public/docs-media/materials-texture.webp differ
diff --git a/tests/mcp-tool-count.test.js b/tests/mcp-tool-count.test.js
index db7a9c93..4fbfc6e7 100644
--- a/tests/mcp-tool-count.test.js
+++ b/tests/mcp-tool-count.test.js
@@ -34,7 +34,7 @@ async function countStatedIn(file, pattern) {
test('documented MCP tool counts match the protocol listing', async () => {
const listed = await listedToolCount();
const statements = {
- 'docs/guide.md': /([\w-]+) tools for authoring/,
+ 'docs/learn/models-and-ai-agents.md': /(\d+) tools for authoring/,
'docs/mcp.md': /Lists all (\d+) tools/,
'index.html': /(\d+) MCP tools/,
'scripts/smoke-mcp.mjs': /listing\.tools\.length, (\d+)\)/,