Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add atomic agent lighting and look controls

Nguyen Xuan An52a4b6c7fb14
diff --git a/.gitignore b/.gitignore
index fe3df058..e18fe901 100644
--- a/.gitignore
+++ b/.gitignore
@@ -37,3 +37,4 @@ public/film-physics.md
public/surface-attachment.md
public/agent-scene.md
public/mcp.md
+public/agent-look.md
diff --git a/README.md b/README.md
index 76cccb13..bead8329 100644
--- a/README.md
+++ b/README.md
@@ -131,6 +131,7 @@ The optional addon retains unchanged parts and geometry across supported edits.
The source [MCP server](docs/mcp.md) connects these sessions to a persistent browser renderer.
Agents receive PNG previews and structured scene metadata through ten stdio tools.
+Agents can author [lights, volumetric fog, grading and shadow coverage](docs/agent-look.md), then restore the complete look from a checkpoint.
Run `node scripts/mcp-server.mjs --backend gpu --memory 192` from a checkout with project dependencies and a local Chrome installation.
Asset ingestion, animation authoring and persistent video jobs remain implementation work.
diff --git a/ROADMAP.md b/ROADMAP.md
index 3f40714e..0a1eb53f 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -24,9 +24,10 @@ This document separates shipping capabilities from work in progress. Performance
The current source, after npm `0.4.1`, includes agent scenes with stable IDs, atomic resource/node edits and checkpoints.
Its stdio MCP server supplies ten schema-backed tools and persistent CPU/GPU image previews.
+Recipes retain lighting, volumetric fog, grading and directional shadow coverage with atomic edits and undo.
1. Extend agent sessions to ingest validated local assets with stable IDs, bounded allocation, replay and undo.
-2. Extend MCP visual feedback with bounded multi-angle and absolute animation-time previews, plus persistent authored lighting and effect controls.
+2. Extend MCP visual feedback with bounded multi-angle and absolute animation-time previews.
3. Persistent render jobs with progress, cancellation, explicit CPU/GPU budgets and deterministic image and video export.
4. Geometry, rig and asset diagnostics that help agents correct intersections, invalid transforms and unsupported materials.
5. Agent workflows for imported assets, sculpting, surface fitting, lighting and animation, verified against rendered reference scenes.
diff --git a/docs/agent-look.md b/docs/agent-look.md
new file mode 100644
index 00000000..e1e2c5e2
--- /dev/null
+++ b/docs/agent-look.md
@@ -0,0 +1,227 @@
+# Agent lighting and look
+
+This feature is available in the current source checkout, after npm release `0.4.1`.
+It is not included in the published `0.4.1` package.
+
+Agent scene recipes can contain `environment`, `effects`, and `shadow` objects.
+These fields belong to canonical recipes and checkpoint snapshots.
+Look commands use the same atomic revision checks as node and material commands.
+Failed look validation preserves the previous recipe and revision.
+
+The source helper `normalizeAgentLook({ environment, effects, shadow })` returns detached, fully normalized JSON.
+It fills omitted fields without mutating the input.
+`resolveAgentShadow(shadow, lightDirection)` returns detached renderer bounds with `eye`, `target`, `up`, `extent`, `near`, and `far`.
+The helpers do not create geometry, render targets, or GPU resources.
+
+```js
+import { normalizeAgentLook, resolveAgentShadow } from '67js/addons/agent-scene';
+
+const look = normalizeAgentLook({
+ environment: {
+ world: true,
+ lightDirection: [-0.6, 1, 0.2],
+ keyIntensity: 0.8,
+ pointLights: [{ position: [0, 2, 1], color: [1, 0.6, 0.3], intensity: 12 }],
+ volumeFog: { density: 0.02, minimum: [-4, 0, -4], maximum: [4, 4, 4] },
+ },
+ effects: { exposure: 1.2, bloom: { strength: 0.25 } },
+ shadow: { target: [0, 1, 0], extent: 5, distance: 10, far: 24 },
+});
+
+const shadowBounds = resolveAgentShadow(look.shadow, look.environment.lightDirection);
+```
+
+The renderer uses `effects.exposure` as `frame.exposure`.
+The remaining effect controls belong to `frame.effects`.
+The environment's `world` flag selects the renderer's world presentation.
+Look normalization always supplies the authored key color, including in world mode.
+
+The MCP adapter applies the canonical look on every draw. A custom browser adapter must pass it explicitly:
+
+```js
+const renderer = new Renderer67(canvas, scene.parts, {
+ ground: false, hdr: true, depth: true,
+ world: scene.environment.world,
+ environment: scene.environment,
+ shadowBounds: resolveAgentShadow(scene.shadow, scene.environment.lightDirection),
+});
+
+function draw() {
+ renderer.world = scene.environment.world;
+ renderer.shadowBounds = resolveAgentShadow(scene.shadow, scene.environment.lightDirection);
+ renderer.shadowsDirty = true;
+ renderer.resize();
+ renderer.updateParts(scene.parts);
+ renderer.render({
+ ...scene.camera, environment: scene.environment, effects: scene.effects,
+ exposure: scene.effects.exposure, time: 0,
+ });
+}
+```
+
+For a frame loop, update shadow bounds and mark shadows dirty only when projector controls or geometry change.
+Use `replaceParts` when `topologyRevision` changes, as described in the scene guide.
+
+## Atomic look commands
+
+| Operation | Payload |
+| --- | --- |
+| `set-environment` | `{ environment: partialEnvironment }` |
+| `set-effects` | `{ effects: partialEffects }` |
+| `set-shadow` | `{ shadow: partialShadow }` |
+
+Each operation also contains its `type` discriminator.
+Omitted fields retain their current canonical values.
+Nested `volumeFog` and `bloom` objects merge their supplied fields.
+Vector arrays replace their previous vector.
+The complete `pointLights` list replaces the previous list, including `[]` to remove all point lights.
+Final merged look fields pass normalization before any command publishes.
+
+```js
+const checkpoint = scene.checkpoint();
+scene.apply([
+ { type: 'set-environment', environment: { keyIntensity: 0.4, volumeFog: { density: 0.03 } } },
+ { type: 'set-effects', effects: { exposure: 1.4, bloom: { threshold: 1.5 } } },
+ { type: 'set-shadow', shadow: { extent: 7 } },
+], { expectedRevision: scene.revision });
+
+scene.apply([
+ { type: 'set-environment', environment: { pointLights: [] } },
+], { expectedRevision: scene.revision });
+
+scene.restore(checkpoint, { expectedRevision: scene.revision });
+scene.releaseCheckpoint(checkpoint);
+```
+
+The helper normalizes a complete candidate rather than merging patches itself.
+Session and transport adapters own patch merging and renderer updates.
+Checkpoint restore recovers canonical lighting, effects, and shadow controls with the rest of the scene.
+
+## Environment
+
+All numeric values must be finite and representable as Float32.
+RGB arrays contain exactly three numbers.
+Key light, point light, and fog colors use linear RGB.
+Sky colors use display RGB, matching the renderer's existing environment contract.
+
+| Field | Default | Range or meaning |
+| --- | --- | --- |
+| `world` | `false` | Boolean world presentation flag |
+| `lightDirection` | `[-3, 6, 4]` | Components within ±1000000, length at least `0.000001` |
+| `keyColor` | `[5.2, 4.7, 4.1]` | Components from `0` to `1000` |
+| `keyIntensity` | `1` | `0` to `100` |
+| `fillIntensity` | `1` | `0` to `100` |
+| `ambientIntensity` | `1` | `0` to `100` |
+| `daylight` | `1` | `0` to `100` |
+| `pointLights` | `[]` | At most eight point light records |
+| `skyTop` | `[0.2, 0.38, 0.52]` | Components from `0` to `1` |
+| `skyBottom` | `[0.62, 0.7, 0.67]` | Components from `0` to `1` |
+| `fogColor` | `[0.35, 0.43, 0.43]` | Components from `0` to `1` |
+| `fogDensity` | `0.006` | `0` to `10` |
+| `volumeFog` | Complete defaults below | One bounded world volume |
+
+Directional key radiance equals `keyColor * keyIntensity`.
+Zero intensity disables that lighting contribution.
+Direction magnitude remains in the canonical recipe.
+The shadow projector uses its normalized direction, so changing only magnitude does not change shadow placement.
+High radiance can clip at the renderer's half-float HDR target limit of `65504` before bloom and tone mapping.
+
+## Point lights
+
+Each point light requires a world-space `position`.
+The renderer uses inverse-square attenuation outside its radius.
+Radius limits attenuation rather than creating an area emitter or softening shadows.
+Point lights currently cast no local shadows and do not scatter through volume fog.
+
+| Field | Default | Range |
+| --- | --- | --- |
+| `position` | Required | Three components within ±1000000 |
+| `color` | `[1, 1, 1]` | Linear RGB components from `0` to `1` |
+| `intensity` | `1` | `0` to `100000` |
+| `radius` | `0.05` | `0.001` to `1000000` |
+| `range` | `0` | `0` for unlimited falloff, otherwise `0.001` to `1000000` |
+
+Range values between zero and `0.001` reject.
+The existing directional shadow map remains the source of shadows.
+Point lights can illuminate through opaque walls.
+
+## Volume fog
+
+Active volume fog requires an opaque renderer with `{ hdr: true, depth: true }` and negotiated HDR support.
+The volume uses resolved opaque depth and directional scattering with the directional shadow map.
+Density zero disables the volume.
+These controls reuse `resolveVolumeFog` and its existing domain rules.
+
+| Field | Default | Range |
+| --- | --- | --- |
+| `density` | `0` | `0` to `10` |
+| `minimum` | `[-100, 0, -100]` | Three components within ±100000 |
+| `maximum` | `[100, 20, 100]` | Three components within ±100000, strictly above minimum after Float32 rounding |
+| `color` | `[0.8, 0.85, 0.9]` | Linear RGB components from `0` to `1` |
+| `ambient` | `[0.03, 0.035, 0.04]` | Linear RGB components from `0` to `10` |
+| `drift` | `[0.03, 0, 0]` | Three components within ±100 |
+| `steps` | `16` | Integer from `8` to `48` |
+| `anisotropy` | `0.3` | `-0.9` to `0.9` |
+| `noiseAmount` | `0.5` | `0` to `1` |
+| `noiseScale` | `0.3` | `0.001` to `100` |
+| `maxDistance` | `100` | `0.01` to `10000` |
+
+Fog bounds reject dimensions that collapse after Float32 rounding.
+The current volume supports one directional scattering source.
+Local point scattering, transparent depth, multiple scattering, and multiple volumes remain outside this contract.
+See [volume fog](volumetric.md) for renderer requirements and frame-time limits.
+
+## Effects
+
+The controls reuse `resolveEffects` with a preview bloom strength of `0.12`.
+Exposure remains independent and maps to `frame.exposure`.
+Bloom strength zero disables bloom.
+
+| Field | Default | Range |
+| --- | --- | --- |
+| `exposure` | `1` | `0.01` to `16` |
+| `saturation` | `1` | `0` to `2` |
+| `contrast` | `1` | `0.1` to `2` |
+| `temperature` | `0` | `-1` to `1` |
+| `vignette` | `0` | `0` to `1` |
+| `grain` | `0` | `0` to `0.1` |
+| `bloom.strength` | `0.12` | `0` to `2` |
+| `bloom.threshold` | `1` | `0` to `10` |
+| `bloom.radius` | `1` | `0.1` to `4` |
+
+## Directional shadows
+
+Shadow controls define an orthographic projector aligned with the current light direction.
+The derived eye equals `target + normalize(lightDirection) * distance`.
+The projector uses up vector `[0, 0, 1]` when the absolute normalized Y component exceeds `0.99`.
+Other directions use `[0, 1, 0]`.
+This avoids a collinear camera up vector for vertical lights.
+
+| Field | Default | Range |
+| --- | --- | --- |
+| `target` | `[0, 1, 0]` | Three components within ±1000000 |
+| `extent` | `3.5` | `0.01` to `100000`, half-width and half-height |
+| `distance` | `8` | `0.01` to `1000000` |
+| `near` | `0.1` | `0.001` to `1000000` |
+| `far` | `15` | `0.001` to `1000000`, above near after Float32 rounding |
+
+The derived eye and target must remain distinguishable at Float32 precision.
+View, projection, and combined matrices must remain finite and nonsingular at Float32 precision.
+Large targets and short distances can fail these combined checks even when each field fits its individual range.
+Derived projectors do not automatically fit scene or fog bounds.
+
+## Validation boundary
+
+Every object rejects unknown keys.
+Inputs must contain ordinary plain JSON objects and dense arrays without extra fields or hidden properties.
+Accessors, executable values, cyclic references, typed arrays, and nonfinite numbers reject.
+The helpers return independent arrays, including volume defaults.
+JSON nesting has a maximum depth of 32, and look arrays have at most eight entries.
+
+| Design | Benefit | Cost |
+| --- | --- | --- |
+| Forward raw renderer environment and postprocess options | Direct access to every renderer field | Defaults and validation vary across adapters |
+| Normalize a bounded JSON look before publication | Canonical defaults, replay, atomic validation, and one derived shadow direction | Explicit field vocabulary |
+
+The helper normalizes bounded JSON while reusing the engine's lighting, effects, and volume validators.
+Session and transport code remain responsible for revisions, patches, checkpoint ownership, and rendering.
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index 4f54fbc3..70717345 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -6,6 +6,8 @@ It is not included in the published `0.4.1` package.
The optional `agent-scene` addon creates bounded CPU scenes from JSON recipes and applies atomic editing commands.
It returns retained renderer parts with shared geometry and material resources.
It does not execute JavaScript, access the DOM, or provide an MCP transport.
+Recipes also retain [lighting, fog, effects and directional shadow coverage](agent-look.md).
+Their patches and checkpoints share the same atomic revision contract as model edits.
```js
import { Renderer67 } from '67js';
diff --git a/docs/guide.md b/docs/guide.md
index d43ac900..1e31f61d 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -403,6 +403,7 @@ Disconnect observers, cancel animation frames, release pointer state and call `d
The current source includes [agent scene sessions](/agent-scene.md), newer than npm `0.4.1`.
Its [MCP server](/mcp.md) provides ten tools for creating, inspecting, editing and previewing scenes through a persistent browser renderer.
Read the matching checkout's MCP guide for launch configuration, CPU/GPU selection and source-only availability.
+The [agent look contract](/agent-look.md) adds retained lighting, volumetric fog, grading and directional shadows to recipe edits and checkpoints.
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.
diff --git a/docs/mcp.md b/docs/mcp.md
index d5a4a2cf..abe23c85 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -96,6 +96,13 @@ Geometry fields remain flat inside each geometry record.
Set operations use `set-node`, `set-material`, or `set-camera`, with fields directly on each command.
`set-node` can rebind a mesh to another geometry/material pair.
+The recipe also accepts [authored lighting, fog, effects and shadow coverage](agent-look.md).
+Use `set-environment`, `set-effects` and `set-shadow` with nested partial records to adjust the look.
+Nested `volumeFog` and `bloom` fields merge. `pointLights` replaces the complete list.
+
+The preview allocates depth support at creation so enabling fog does not recreate render targets.
+Active volume fog requires HDR support. Unsupported previews reject that edit before committing.
+
Build from an empty recipe by adding resources and nodes in one revisioned batch:
```js
diff --git a/package.json b/package.json
index 20834e0a..b048aec6 100644
--- a/package.json
+++ b/package.json
@@ -43,7 +43,8 @@
"docs/shrinkwrap.md",
"docs/surface-attachment.md",
"docs/agent-scene.md",
- "docs/mcp.md"
+ "docs/mcp.md",
+ "docs/agent-look.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -84,6 +85,7 @@
"mcp": "node scripts/mcp-server.mjs",
"smoke:mcp": "node scripts/smoke-mcp.mjs",
"smoke:agent-topology": "node scripts/smoke-agent-topology.mjs",
+ "smoke:agent-look": "node scripts/smoke-agent-look.mjs",
"smoke:enhancements": "node scripts/smoke-enhancements.mjs",
"smoke:site": "node scripts/smoke-site.mjs",
"publish:ci": "node scripts/publish-ci.mjs"
diff --git a/public/llms.txt b/public/llms.txt
index 6897a7f1..0ca89ea7 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -16,6 +16,12 @@ This addon does not expose an MCP server or a render job queue.
The source checkout provides a separate stdio MCP server in `scripts/mcp-server.mjs`, after npm `0.4.1`.
Read `/mcp.md` before configuring it. Start with `scene_capabilities`, create a recipe and inspect its stable IDs.
+Read `/agent-look.md` for recipe environment, effects and shadow fields.
+Use `set-environment`, `set-effects` and `set-shadow` for atomic partial look patches.
+Nested volumeFog/bloom fields merge. pointLights replaces the list. Volume fog requires HDR/depth support.
+
+Checkpoint before relighting, inspect the PNG, then restore or export the full recipe. Point lights do not cast local shadows.
+
Checkpoint, apply small revisioned batches, then use `scene_look` to assess the actual PNG.
Restore failed experiments and release unused checkpoints. Export the recipe and dispose the scene when finished.
The runtime keeps one browser scene alive, serializes calls, caps PNG responses and releases resources on stdin EOF.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 40e847d7..55e1411f 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -2,10 +2,10 @@ import { createAgentScene } from '../src/agent-scene.js';
import { Renderer67 } from '../src/renderer.js';
import { applyProjection } from '../src/camera.js';
import { mat4 } from 'gl-matrix';
+import { resolveAgentShadow } from '../src/agent-look.js';
let active = null;
let canvas = document.querySelector('canvas');
-const effects = { bloom: { strength: 0.12, threshold: 1, radius: 1 }, grain: 0, vignette: 0 };
function requireSession(sessionId) {
if (!active || active.sessionId !== sessionId) {
@@ -49,6 +49,7 @@ function renderInfo(renderer) {
height: canvas.height,
samples: renderer.capabilities.samples,
hdr: renderer.capabilities.hdr,
+ depth: renderer.depth,
geometryBuffers: renderer.geometryBuffers?.size ?? 0,
gpuBuffers: renderer.buffers?.length ?? 0,
drawBatches: renderer.batches?.length ?? 0,
@@ -68,7 +69,17 @@ function draw(record) {
} else {
record.renderer.updateParts(record.scene.parts);
}
- record.renderer.render({ ...record.scene.camera, effects });
+ const environment = record.scene.environment;
+ const effects = record.scene.effects;
+ const shadow = record.scene.shadow;
+ const shadowKey = JSON.stringify([environment.lightDirection, shadow]);
+ if (record.shadowKey !== shadowKey) {
+ record.renderer.shadowBounds = resolveAgentShadow(shadow, environment.lightDirection);
+ record.renderer.shadowsDirty = true;
+ record.shadowKey = shadowKey;
+ }
+ record.renderer.world = environment.world;
+ record.renderer.render({ ...record.scene.camera, environment, effects, exposure: effects.exposure, time: 0 });
const error = record.renderer.context.getError();
if (error !== 0) {
throw new Error(`WebGL render failed with error ${error}.`);
@@ -116,6 +127,10 @@ window.__agentPreview = {
renderer = new Renderer67(canvas, scene.parts, {
ground: false,
hdr: true,
+ depth: true,
+ world: scene.environment.world,
+ environment: scene.environment,
+ shadowBounds: resolveAgentShadow(scene.shadow, scene.environment.lightDirection),
pixelRatio: 1,
samples: backend === 'cpu' ? 1 : 4,
memoryBudgetMiB,
@@ -144,6 +159,15 @@ window.__agentPreview = {
apply({ sessionId, operations, expectedRevision }) {
const record = requireSession(sessionId);
validatePreviewCamera(candidateCamera(record, operations));
+ let fogDensity = record.scene.environment.volumeFog.density;
+ for (const operation of operations) {
+ if (operation.type === 'set-environment' && Object.hasOwn(operation.environment?.volumeFog ?? {}, 'density')) {
+ fogDensity = operation.environment.volumeFog.density;
+ }
+ }
+ if (fogDensity > 0 && !record.renderer.capabilities.hdr) {
+ throw new Error('Volumetric fog requires HDR support; this preview cannot enable it.');
+ }
record.scene.apply(operations, { expectedRevision });
return mutationStatus(record);
},
@@ -161,7 +185,7 @@ window.__agentPreview = {
checkpoint({ sessionId, checkpointId }) {
const record = requireSession(sessionId);
const handle = record.scene.checkpoint();
- record.checkpoints.set(checkpointId, handle);
+ record.checkpoints.set(checkpointId, { handle, fogDensity: record.scene.environment.volumeFog.density });
return { sessionId, checkpointId, revision: record.scene.revision };
},
restore({ sessionId, checkpointId, expectedRevision }) {
@@ -169,7 +193,11 @@ window.__agentPreview = {
if (!record.checkpoints.has(checkpointId)) {
throw new Error('Unknown or released checkpoint.');
}
- record.scene.restore(record.checkpoints.get(checkpointId), { expectedRevision });
+ const checkpoint = record.checkpoints.get(checkpointId);
+ if (checkpoint.fogDensity > 0 && !record.renderer.capabilities.hdr) {
+ throw new Error('Volumetric fog requires HDR support; this preview cannot restore it.');
+ }
+ record.scene.restore(checkpoint.handle, { expectedRevision });
return mutationStatus(record);
},
releaseCheckpoint({ sessionId, checkpointId }) {
@@ -177,7 +205,7 @@ window.__agentPreview = {
if (!record.checkpoints.has(checkpointId)) {
throw new Error('Unknown or released checkpoint.');
}
- record.scene.releaseCheckpoint(record.checkpoints.get(checkpointId));
+ record.scene.releaseCheckpoint(record.checkpoints.get(checkpointId).handle);
record.checkpoints.delete(checkpointId);
return { sessionId, checkpointId, released: true };
},
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 5db3f6a3..f1beee89 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -40,6 +40,62 @@ const cameraFields = {
near: positive.optional().describe('Near clipping distance. Must be less than far.'),
far: positive.optional().describe('Far clipping distance. Must exceed near.'),
};
+const bounded = (minimum, maximum) => z.number().min(minimum).max(maximum);
+const boundedVector = (minimum, maximum) => z.tuple([bounded(minimum, maximum), bounded(minimum, maximum), bounded(minimum, maximum)]);
+const volumeFog = z.strictObject({
+ density: bounded(0, 10).optional(),
+ minimum: boundedVector(-1e5, 1e5).optional(),
+ maximum: boundedVector(-1e5, 1e5).optional(),
+ color: color.optional(),
+ ambient: boundedVector(0, 10).optional(),
+ drift: boundedVector(-100, 100).optional(),
+ steps: z.number().int().min(8).max(48).optional(),
+ anisotropy: bounded(-0.9, 0.9).optional(),
+ noiseAmount: unit.optional(),
+ noiseScale: bounded(0.001, 100).optional(),
+ maxDistance: bounded(0.01, 1e4).optional(),
+});
+const environment = z.strictObject({
+ world: z.boolean().optional().describe('Draw the sky and apply surface fog.'),
+ lightDirection: boundedVector(-1e6, 1e6).optional().describe('Nonzero direction toward the key light; shadows follow it.'),
+ keyColor: boundedVector(0, 1000).optional(),
+ keyIntensity: bounded(0, 100).optional(),
+ fillIntensity: bounded(0, 100).optional(),
+ ambientIntensity: bounded(0, 100).optional(),
+ daylight: bounded(0, 100).optional(),
+ pointLights: z.array(z.strictObject({
+ position: boundedVector(-1e6, 1e6),
+ color: color.optional(),
+ intensity: bounded(0, 1e5).optional(),
+ radius: bounded(0.001, 1e6).optional(),
+ range: z.union([z.literal(0), bounded(0.001, 1e6)]).optional(),
+ })).max(8).optional().describe('Replace the entire list; [] removes all point lights. No local shadows.'),
+ skyTop: color.optional(),
+ skyBottom: color.optional(),
+ fogColor: color.optional(),
+ fogDensity: bounded(0, 10).optional(),
+ volumeFog: volumeFog.optional().describe('Bounded depth-clipped directional scattering; requires HDR support.'),
+});
+const effects = z.strictObject({
+ exposure: bounded(0.01, 16).optional(),
+ saturation: bounded(0, 2).optional(),
+ contrast: bounded(0.1, 2).optional(),
+ temperature: bounded(-1, 1).optional(),
+ vignette: unit.optional(),
+ grain: bounded(0, 0.1).optional(),
+ bloom: z.strictObject({
+ strength: bounded(0, 2).optional(),
+ threshold: bounded(0, 10).optional(),
+ radius: bounded(0.1, 4).optional(),
+ }).optional(),
+});
+const shadow = z.strictObject({
+ target: boundedVector(-1e6, 1e6).optional(),
+ extent: bounded(0.01, 1e5).optional(),
+ distance: bounded(0.01, 1e6).optional(),
+ near: bounded(0.001, 1e6).optional(),
+ far: bounded(0.001, 1e6).optional(),
+}).describe('Directional shadow coverage. Backend checks Float32 view/projection consistency.');
const geometry = z.discriminatedUnion('type', [
z.strictObject({ id: identifier, type: z.literal('box'), bevel: finite.optional(), subdivisions: detail(1, 128) }),
z.strictObject({ id: identifier, type: z.literal('cylinder'), segments, bevel: finite.optional(), bevelSegments: detail(1, 128) }),
@@ -56,11 +112,17 @@ const recipe = z.strictObject({
materials: z.array(z.strictObject({ id: identifier, tag: z.enum(['surface', 'unlit']).optional(), ...materialFields })).max(256),
nodes: z.array(nodeRecord).max(4096),
camera: z.strictObject(cameraFields).optional(),
+ environment: environment.optional(),
+ effects: effects.optional(),
+ shadow: shadow.optional(),
}).describe('Bounded scene recipe. Backend validates references, mesh resource pairs, hierarchy, geometry budgets and camera consistency.');
const operation = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('set-node'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields }),
z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }),
z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),
+ z.strictObject({ type: z.literal('set-environment'), environment }),
+ z.strictObject({ type: z.literal('set-effects'), effects }),
+ z.strictObject({ type: z.literal('set-shadow'), shadow }),
z.strictObject({ type: z.literal('add-node'), node: nodeRecord }),
z.strictObject({ type: z.literal('remove-node'), id: identifier, recursive: z.boolean().optional().describe('Remove descendants too. Defaults to false; dangling children reject the batch.') }),
z.strictObject({ type: z.literal('add-geometry'), geometry }),
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index d670906c..913bc202 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -40,7 +40,7 @@ const sourceDocuments = [
'gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',
'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
- 'surface-attachment.md', 'agent-scene.md', 'mcp.md',
+ 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --git a/scripts/smoke-agent-look.mjs b/scripts/smoke-agent-look.mjs
new file mode 100644
index 00000000..5e51fc40
--- /dev/null
+++ b/scripts/smoke-agent-look.mjs
@@ -0,0 +1,130 @@
+import assert from 'node:assert/strict';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { createServer } from 'vite';
+import { chromium } from 'playwright';
+import { createAgentPreviewFixture } from './agent-preview-fixture.mjs';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const backend = process.argv[2] ?? 'cpu';
+assert.ok(['cpu', 'gpu'].includes(backend));
+await mkdir('artifacts', { recursive: true });
+const recipe = createAgentPreviewFixture();
+recipe.geometries.push({ id: 'floor', type: 'box', bevel: 0 });
+recipe.materials.push({ id: 'floor', color: [0.12, 0.16, 0.18], roughness: 0.75 });
+recipe.nodes.push({ id: 'floor', geometry: 'floor', material: 'floor', translation: [0, -0.08, 0], scale: [7, 0.15, 7] });
+recipe.environment = {
+ world: true, lightDirection: [-3, 6, 4], keyColor: [3, 2.5, 1.8],
+ fillIntensity: 0.2, ambientIntensity: 0.3,
+ skyTop: [0.035, 0.06, 0.09], skyBottom: [0.15, 0.2, 0.23],
+ fogDensity: 0,
+ pointLights: [{ position: [0, 1.4, 0], color: [0.15, 1, 0.7], intensity: 3, radius: 0.3 }],
+};
+recipe.shadow = { extent: 5, far: 20 };
+const harness = `<!doctype html><html><head><style>html,body{margin:0;height:100%}canvas{width:100vw;height:100vh;display:block}</style></head><body><canvas></canvas><script type="module">
+import {createAgentScene} from '/src/agent-scene.js';
+import {resolveAgentShadow} from '/src/agent-look.js';
+import {Renderer67} from '/src/renderer.js';
+const session=createAgentScene(${JSON.stringify(recipe)});
+const renderer=new Renderer67(document.querySelector('canvas'),session.parts,{ground:false,hdr:true,depth:true,samples:1,pixelRatio:1,memoryBudgetMiB:192});
+const counters={buffers:0,textures:0,framebuffers:0,renderbuffers:0};
+const context=renderer.context;
+for(const [method,field] of [['createBuffer','buffers'],['createTexture','textures'],['createFramebuffer','framebuffers'],['createRenderbuffer','renderbuffers']]) {
+ const original=context[method].bind(context);
+ context[method]=(...parameters)=>{counters[field]++;return original(...parameters);};
+}
+let shadowKey;
+function draw() {
+ const environment=session.environment;
+ const effects=session.effects;
+ const nextKey=JSON.stringify([environment.lightDirection,session.shadow]);
+ if(shadowKey!==nextKey) {
+ renderer.shadowBounds=resolveAgentShadow(session.shadow,environment.lightDirection);
+ renderer.shadowsDirty=true;
+ shadowKey=nextKey;
+ }
+ renderer.world=environment.world;
+ renderer.resize();
+ renderer.updateParts(session.parts);
+ renderer.render({...session.camera,environment,effects,exposure:effects.exposure,time:0});
+}
+function pixels() {
+ const result=new Uint8Array(context.drawingBufferWidth*context.drawingBufferHeight*4);
+ context.readPixels(0,0,context.drawingBufferWidth,context.drawingBufferHeight,context.RGBA,context.UNSIGNED_BYTE,result);
+ return result;
+}
+draw();
+window.__lookProof={session,renderer,draw,pixels,counters};
+</script></body></html>`;
+await writeFile('artifacts/agent-look-harness.html', harness);
+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+let browser;
+try {
+ await server.listen();
+ const args = ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'];
+ if (backend === 'cpu') args.push('--use-angle=swiftshader', '--enable-unsafe-swiftshader');
+ browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args });
+ const page = await browser.newPage({ viewport: { width: 768, height: 512 } });
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/artifacts/agent-look-harness.html`);
+ await page.waitForFunction(() => window.__lookProof);
+ await page.screenshot({ path: `artifacts/agent-look-${backend}-before.png` });
+ const result = await page.evaluate(() => {
+ const { session, renderer, draw, pixels, counters } = window.__lookProof;
+ draw();
+ const before = pixels();
+ const checkpoint = session.checkpoint();
+ const parts = session.parts;
+ const originalCounters = { ...counters };
+ session.apply([
+ { type: 'set-environment', environment: {
+ lightDirection: [0, 1, 0], keyColor: [1.1, 1.8, 4], keyIntensity: 1.5,
+ pointLights: [{ position: [-1, 1.4, 1], color: [1, 0.3, 0.04], intensity: 12, radius: 0.2 }],
+ volumeFog: { density: 0.12, minimum: [-4, 0, -4], maximum: [4, 4, 4], noiseAmount: 0.4, steps: 16 },
+ } },
+ { type: 'set-effects', effects: { exposure: 0.85, contrast: 1.08, bloom: { strength: 0.25 } } },
+ { type: 'set-shadow', shadow: { distance: 9, extent: 5, near: 0.1, far: 20 } },
+ ], { expectedRevision: 0 });
+ draw();
+ const fog = pixels();
+ const differences = data => data.reduce((count, value, index) => count + Number(value !== before[index]), 0);
+ const after = document.querySelector('canvas').toDataURL('image/png').split(',')[1];
+ session.apply([{ type: 'set-environment', environment: { volumeFog: { density: 0 } } }], { expectedRevision: 1 });
+ draw();
+ const dry = pixels();
+ const fogChannels = fog.reduce((count, value, index) => count + Number(value !== dry[index]), 0);
+ session.restore(checkpoint, { expectedRevision: 2 });
+ draw();
+ const restored = pixels();
+ const debug = renderer.context.getExtension('WEBGL_debug_renderer_info');
+ return {
+ after, changedChannels: differences(fog), fogChannels,
+ exactRestore: restored.every((value, index) => value === before[index]),
+ retainedParts: parts === session.parts, topologyRevision: session.topologyRevision,
+ allocations: Object.fromEntries(Object.entries(counters).map(([field, count]) => [field, count - originalCounters[field]])),
+ glError: renderer.context.getError(), hdr: renderer.capabilities.hdr, depth: renderer.depth,
+ graphics: renderer.context.getParameter(debug ? debug.UNMASKED_RENDERER_WEBGL : renderer.context.RENDERER),
+ estimatedBytes: renderer.memoryPlan.estimatedBytes,
+ };
+ });
+ await writeFile(`artifacts/agent-look-${backend}-after.png`, Buffer.from(result.after, 'base64'));
+ delete result.after;
+ await writeFile(`artifacts/agent-look-${backend}.json`, JSON.stringify(result, null, 2));
+ console.log(JSON.stringify(result, null, 2));
+ assert.deepEqual(errors, []);
+ assert.equal(result.exactRestore, true);
+ assert.equal(result.retainedParts, true);
+ assert.equal(result.topologyRevision, 0);
+ assert.equal(result.glError, 0);
+ assert.equal(result.hdr, true);
+ assert.equal(result.depth, true);
+ assert.ok(result.changedChannels > 10000);
+ assert.ok(result.fogChannels > 1000);
+ assert.ok(Object.values(result.allocations).every(count => count === 0));
+ if (backend === 'gpu') assert.doesNotMatch(result.graphics, /swiftshader|llvmpipe|software/i);
+ await page.evaluate(() => window.__lookProof.renderer.dispose());
+} finally {
+ await browser?.close();
+ await server.close();
+}
diff --git a/scripts/smoke-mcp.mjs b/scripts/smoke-mcp.mjs
index ff51335c..9f929a66 100644
--- a/scripts/smoke-mcp.mjs
+++ b/scripts/smoke-mcp.mjs
@@ -78,11 +78,17 @@ try {
{ type: 'set-node', id: 'lamp', translation: [0.18, 0.82, 0] },
{ type: 'set-node', id: 'glow', scale: [0.34, 0.3, 0.34], translation: [0, 0.75, 0] },
{ type: 'set-material', id: 'light', color: [0.9, 0.28, 0.04], emissiveColor: [0.9, 0.28, 0.04] },
+ { type: 'set-environment', environment: { lightDirection: [0, 1, 0], keyColor: [1, 2, 4], pointLights: [{ position: [1, 1, 1], color: [1, 0.2, 0.05], intensity: 4 }], volumeFog: { density: 0.04 } } },
+ { type: 'set-effects', effects: { exposure: 0.8, bloom: { strength: 0.2 } } },
+ { type: 'set-shadow', shadow: { extent: 5, distance: 9, far: 20 } },
],
})).structuredContent;
assert.equal(edited.revision, 2);
assert.equal(edited.committed, true);
assert.equal(edited.renderSucceeded, true);
+ assert.equal(edited.render.depth, true);
+ assert.equal(edited.inspection.look.pointLights, 1);
+ assert.equal(edited.inspection.look.volumeFogDensity, 0.04);
const after = await look(sessionId, 'after');
assert.notDeepEqual(after.bytes, before.bytes);
const stale = await client.callTool({ name: 'scene_apply', arguments: {
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index 521064b7..d9a273e4 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -130,7 +130,7 @@ if (${!published || metadata.version !== '0.4.0'}) {
}
solidIndex.dispose();
if (${!published}) {
- const { createAgentScene } = await import('67js/addons/agent-scene');
+ const { createAgentScene, resolveAgentShadow } = await import('67js/addons/agent-scene');
const agentScene = createAgentScene({
format: '67js.scene', schemaVersion: 1,
geometries: [{ id: 'cube', type: 'box', bevel: 0 }],
@@ -157,6 +157,17 @@ if (${!published}) {
assert.equal(agentScene.parts.length, 1);
assert.equal(agentScene.parts[0], agentPart);
agentScene.releaseCheckpoint(dynamicCheckpoint);
+ const lookCheckpoint = agentScene.checkpoint();
+ const originalLook = agentScene.exportRecipe();
+ agentScene.apply([
+ { type: 'set-environment', environment: { lightDirection: [0, 1, 0], pointLights: [{ position: [1, 2, 3] }] } },
+ { type: 'set-effects', effects: { exposure: 0.8, bloom: { strength: 0.2 } } },
+ ], { expectedRevision: agentScene.revision });
+ assert.deepEqual(resolveAgentShadow(agentScene.shadow, agentScene.environment.lightDirection).up, [0, 0, 1]);
+ assert.equal(agentScene.parts[0], agentPart);
+ agentScene.restore(lookCheckpoint, { expectedRevision: agentScene.revision });
+ assert.deepEqual(agentScene.exportRecipe(), originalLook);
+ agentScene.releaseCheckpoint(lookCheckpoint);
}
const parts = createModel();
assert.equal(parts.length, 574);
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index 35cf7b15..998e3f03 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -151,6 +151,12 @@ Use the revision returned by each committed apply or restore. A response with `c
Inspect or export the canonical recipe after a render failure; do not retry the edit with its old revision.
The server retains one renderer, bounds image dimensions and payloads, and closes its browser on stdio EOF.
Export the recipe before disposal. Asset ingestion, animation authoring and video jobs remain unsupported by these tools.
+Read `docs/agent-look.md` for authored lighting, fog, effects and shadow coverage, available after npm `0.4.1`.
+Use atomic `set-environment`, `set-effects` and `set-shadow` partial records instead of editing renderer internals through MCP.
+Nested volumeFog/bloom fields merge; pointLights replaces the full list. Point lights do not cast local shadows.
+Volume fog requires opaque HDR/depth rendering. The preview adapter allocates depth support at creation and rejects unsupported fog before commit.
+Keep key-light direction aligned with the derived shadow projector. The optional addon exports `resolveAgentShadow` for custom adapters.
+Checkpoint before relighting, inspect the actual image and restore or export the complete recipe. Look changes retain topology and geometry.
`cameraView('front' | 'right' | 'top')` returns an orthographic camera with the correct up vector.
`fitOrthographicHeight(bounds, view, aspect)` frames both model width and height.
diff --git a/src/agent-look.js b/src/agent-look.js
new file mode 100644
index 00000000..4423034a
--- /dev/null
+++ b/src/agent-look.js
@@ -0,0 +1,236 @@
+import { mat4 } from 'gl-matrix';
+import { createLightingState, updateLightingState, MAX_POINT_LIGHTS } from './lighting.js';
+import { resolveEffects } from './effects.js';
+import { resolveVolumeFog } from './volumetric.js';
+
+const ENVIRONMENT_FIELDS = [
+ 'world', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity',
+ 'daylight', 'pointLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog',
+];
+const EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'bloom'];
+const SHADOW_FIELDS = ['target', 'extent', 'distance', 'near', 'far'];
+const POINT_LIGHT_FIELDS = ['position', 'color', 'intensity', 'radius', 'range'];
+const VOLUME_VECTOR_FIELDS = ['minimum', 'maximum', 'color', 'ambient', 'drift'];
+const VOLUME_NUMBER_FIELDS = ['density', 'steps', 'anisotropy', 'noiseAmount', 'noiseScale', 'maxDistance'];
+const BLOOM_FIELDS = ['strength', 'threshold', 'radius'];
+
+function plainObject(value, label) {
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
+ (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)) {
+ throw new TypeError(`${label} must be a plain JSON object.`);
+ }
+}
+
+function knownKeys(value, fields, label) {
+ plainObject(value, label);
+ for (const key of Reflect.ownKeys(value)) {
+ if (typeof key !== 'string' || !fields.includes(key)) {
+ throw new TypeError(`Unknown ${label} field: ${String(key)}.`);
+ }
+ }
+}
+
+// Domain resolvers accept ordinary values. Copy descriptors first so accessors never execute.
+function copiedJson(input, depth = 0, ancestors = new Set()) {
+ if (depth > 32) {
+ throw new RangeError('Look JSON nesting exceeds 32 levels.');
+ }
+ if (input === null || typeof input === 'boolean' || typeof input === 'string') {
+ return input;
+ }
+ if (typeof input === 'number') {
+ if (!Number.isFinite(input) || !Number.isFinite(Math.fround(input))) {
+ throw new TypeError('Look JSON numbers must be finite Float32 values.');
+ }
+ return input;
+ }
+ if (!input || typeof input !== 'object' || ancestors.has(input)) {
+ throw new TypeError('Look must contain acyclic plain JSON data.');
+ }
+ const array = Array.isArray(input);
+ if (array && (Object.getPrototypeOf(input) !== Array.prototype || input.length > MAX_POINT_LIGHTS)) {
+ throw new TypeError(`Look JSON arrays must be ordinary arrays with at most ${MAX_POINT_LIGHTS} entries.`);
+ }
+ if (!array) {
+ plainObject(input, 'Look');
+ }
+ ancestors.add(input);
+ const result = array ? [] : {};
+ for (const key of Reflect.ownKeys(input)) {
+ if (array && key === 'length') {
+ continue;
+ }
+ if (typeof key !== 'string' || key === '__proto__') {
+ throw new TypeError('Look JSON keys must be ordinary strings.');
+ }
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
+ if (!descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) {
+ throw new TypeError('Look JSON accessors and hidden fields are unsupported.');
+ }
+ if (array && key !== String(result.length)) {
+ throw new TypeError('Look JSON arrays must be dense without extra fields.');
+ }
+ result[key] = copiedJson(descriptor.value, depth + 1, ancestors);
+ }
+ if (array && result.length !== input.length) {
+ throw new TypeError('Look JSON arrays cannot contain trailing holes.');
+ }
+ ancestors.delete(input);
+ return result;
+}
+
+function numberInRange(value, minimum, maximum, label) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value)) ||
+ value < minimum || value > maximum) {
+ throw new RangeError(`${label} must be a finite Float32 number within ${minimum} and ${maximum}.`);
+ }
+ return value;
+}
+
+function vectorInRange(value, minimum, maximum, label) {
+ if (!Array.isArray(value) || value.length !== 3) {
+ throw new TypeError(`${label} needs three JSON numbers.`);
+ }
+ return value.map(component => numberInRange(component, minimum, maximum, label));
+}
+
+function fallback(value, defaultValue) {
+ return value === undefined ? defaultValue : value;
+}
+
+function directionFrom(value) {
+ const direction = vectorInRange(value, -1e6, 1e6, 'lightDirection');
+ const length = Math.hypot(...direction);
+ if (length < 1e-6) {
+ throw new RangeError('lightDirection length must be at least 0.000001.');
+ }
+ return { direction, unitDirection: direction.map(component => component / length) };
+}
+
+function volumeFogFrom(input = {}) {
+ knownKeys(input, [...VOLUME_VECTOR_FIELDS, ...VOLUME_NUMBER_FIELDS], 'volumeFog');
+ for (const field of VOLUME_VECTOR_FIELDS) {
+ if (Object.hasOwn(input, field)) {
+ vectorInRange(input[field], -1e5, 1e5, `volumeFog.${field}`);
+ }
+ }
+ for (const field of VOLUME_NUMBER_FIELDS) {
+ if (Object.hasOwn(input, field)) {
+ numberInRange(input[field], -Number.MAX_VALUE, Number.MAX_VALUE, `volumeFog.${field}`);
+ }
+ }
+ return copiedJson(resolveVolumeFog(input));
+}
+
+function environmentFrom(input = {}) {
+ knownKeys(input, ENVIRONMENT_FIELDS, 'environment');
+ const world = fallback(input.world, false);
+ if (typeof world !== 'boolean') {
+ throw new TypeError('environment.world must be boolean.');
+ }
+ const pointLights = fallback(input.pointLights, []);
+ if (!Array.isArray(pointLights) || pointLights.length > MAX_POINT_LIGHTS) {
+ throw new RangeError(`pointLights must contain at most ${MAX_POINT_LIGHTS} lights.`);
+ }
+ const environment = {
+ world,
+ lightDirection: directionFrom(fallback(input.lightDirection, [-3, 6, 4])).direction,
+ keyColor: vectorInRange(fallback(input.keyColor, [5.2, 4.7, 4.1]), 0, 1000, 'keyColor'),
+ keyIntensity: numberInRange(fallback(input.keyIntensity, 1), 0, 100, 'keyIntensity'),
+ fillIntensity: numberInRange(fallback(input.fillIntensity, 1), 0, 100, 'fillIntensity'),
+ ambientIntensity: numberInRange(fallback(input.ambientIntensity, 1), 0, 100, 'ambientIntensity'),
+ daylight: numberInRange(fallback(input.daylight, 1), 0, 100, 'daylight'),
+ pointLights: pointLights.map(light => {
+ knownKeys(light, POINT_LIGHT_FIELDS, 'point light');
+ const range = numberInRange(fallback(light.range, 0), 0, 1e6, 'point light range');
+ if (range !== 0 && range < 0.001) {
+ throw new RangeError('Point light range must be zero or at least 0.001.');
+ }
+ return {
+ position: vectorInRange(light.position, -1e6, 1e6, 'point light position'),
+ color: vectorInRange(fallback(light.color, [1, 1, 1]), 0, 1, 'point light color'),
+ intensity: numberInRange(fallback(light.intensity, 1), 0, 1e5, 'point light intensity'),
+ radius: numberInRange(fallback(light.radius, 0.05), 0.001, 1e6, 'point light radius'),
+ range,
+ };
+ }),
+ skyTop: vectorInRange(fallback(input.skyTop, [0.2, 0.38, 0.52]), 0, 1, 'skyTop'),
+ skyBottom: vectorInRange(fallback(input.skyBottom, [0.62, 0.7, 0.67]), 0, 1, 'skyBottom'),
+ fogColor: vectorInRange(fallback(input.fogColor, [0.35, 0.43, 0.43]), 0, 1, 'fogColor'),
+ fogDensity: numberInRange(fallback(input.fogDensity, 0.006), 0, 10, 'fogDensity'),
+ volumeFog: volumeFogFrom(input.volumeFog),
+ };
+ updateLightingState(createLightingState(), environment, { world });
+ return environment;
+}
+
+function effectsFrom(input = {}) {
+ knownKeys(input, EFFECT_FIELDS, 'effects');
+ for (const field of EFFECT_FIELDS) {
+ if (field !== 'bloom' && Object.hasOwn(input, field)) {
+ numberInRange(input[field], -Number.MAX_VALUE, Number.MAX_VALUE, `effects.${field}`);
+ }
+ }
+ const bloom = fallback(input.bloom, {});
+ knownKeys(bloom, BLOOM_FIELDS, 'bloom');
+ for (const field of BLOOM_FIELDS) {
+ if (Object.hasOwn(bloom, field)) {
+ numberInRange(bloom[field], -Number.MAX_VALUE, Number.MAX_VALUE, `bloom.${field}`);
+ }
+ }
+ const resolved = resolveEffects({ ...input, bloom: { strength: 0.12, threshold: 1, radius: 1, ...bloom } });
+ return { ...resolved, exposure: numberInRange(fallback(input.exposure, 1), 0.01, 16, 'exposure') };
+}
+
+function shadowFrom(input = {}) {
+ knownKeys(input, SHADOW_FIELDS, 'shadow');
+ const shadow = {
+ target: vectorInRange(fallback(input.target, [0, 1, 0]), -1e6, 1e6, 'shadow target'),
+ extent: numberInRange(fallback(input.extent, 3.5), 0.01, 1e5, 'shadow extent'),
+ distance: numberInRange(fallback(input.distance, 8), 0.01, 1e6, 'shadow distance'),
+ near: numberInRange(fallback(input.near, 0.1), 0.001, 1e6, 'shadow near'),
+ far: numberInRange(fallback(input.far, 15), 0.001, 1e6, 'shadow far'),
+ };
+ if (Math.fround(shadow.near) >= Math.fround(shadow.far)) {
+ throw new RangeError('Shadow needs near < far at Float32 precision.');
+ }
+ return shadow;
+}
+
+function shadowBoundsFrom(shadow, direction) {
+ const { unitDirection } = directionFrom(direction);
+ const eye = shadow.target.map((component, axis) => component + unitDirection[axis] * shadow.distance);
+ if (!eye.every(component => Number.isFinite(Math.fround(component))) ||
+ eye.every((component, axis) => Math.fround(component) === Math.fround(shadow.target[axis]))) {
+ throw new RangeError('Shadow eye and target must remain finite and distinguishable at Float32 precision.');
+ }
+ const up = Math.abs(unitDirection[1]) > 0.99 ? [0, 0, 1] : [0, 1, 0];
+ const view = mat4.lookAt(mat4.create(), eye, shadow.target, up);
+ const projection = mat4.ortho(mat4.create(), -shadow.extent, shadow.extent, -shadow.extent, shadow.extent, shadow.near, shadow.far);
+ const combined = mat4.multiply(mat4.create(), projection, view);
+ for (const matrix of [view, projection, combined]) {
+ const determinant = mat4.determinant(matrix);
+ if (!matrix.every(Number.isFinite) || !Number.isFinite(determinant) || determinant === 0) {
+ throw new RangeError('Shadow view, projection, and combined matrices must remain finite and nonsingular at Float32 precision.');
+ }
+ }
+ return { eye, target: [...shadow.target], up, extent: shadow.extent, near: shadow.near, far: shadow.far };
+}
+
+/** Derive a detached directional shadow projector from validated ordinary JSON. */
+export function resolveAgentShadow(inputShadow = {}, inputDirection = [-3, 6, 4]) {
+ const shadow = shadowFrom(copiedJson(inputShadow));
+ const direction = copiedJson(inputDirection);
+ return shadowBoundsFrom(shadow, direction);
+}
+
+/** Normalize the complete look without mutating caller input or sharing default arrays. */
+export function normalizeAgentLook(input = {}) {
+ knownKeys(input, ['environment', 'effects', 'shadow'], 'look');
+ const copied = copiedJson(input);
+ const environment = environmentFrom(copied.environment);
+ const effects = effectsFrom(copied.effects);
+ const shadow = shadowFrom(copied.shadow);
+ shadowBoundsFrom(shadow, environment.lightDirection);
+ return { environment, effects, shadow };
+}
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 6551febc..88fad9c7 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -3,6 +3,8 @@ import { box, cylinder, sphere, torus } from './geometry.js';
import { lathe, extrude, tube } from './modeling.js';
import { createSceneGraph } from './scene-graph.js';
import { applyProjection } from './camera.js';
+import { normalizeAgentLook } from './agent-look.js';
+export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
const DEFAULT_LIMITS = Object.freeze({
maxNodes: 4096, maxDepth: 256, maxGeometries: 256, maxMaterials: 256,
@@ -13,6 +15,11 @@ const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [
const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material'];
const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor'];
const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
+const LOOK_OPERATION_FIELDS = Object.freeze({
+ 'set-environment': 'environment',
+ 'set-effects': 'effects',
+ 'set-shadow': 'shadow',
+});
const ADDITION_FIELDS = Object.freeze({
'add-geometry': ['geometries', 'geometry'],
'add-material': ['materials', 'material'],
@@ -29,9 +36,11 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
operations: Object.freeze([
'set-node', 'set-material', 'set-camera', 'add-node', 'remove-node',
'add-geometry', 'remove-geometry', 'add-material', 'remove-material',
+ 'set-environment', 'set-effects', 'set-shadow',
]),
materialTags: Object.freeze(['surface', 'unlit']),
fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,
+ authoredLook: true, maxPointLights: 8,
});
function knownKeys(value, allowed, label) {
@@ -414,7 +423,7 @@ function boundsFor(geometry, matrix) {
function normalizeRecipe(input, limits) {
let recipe = copiedJson(input, limits.maxRecipeBytes);
- knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'camera'], 'recipe');
+ knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'camera', 'environment', 'effects', 'shadow'], 'recipe');
if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {
throw new RangeError('Expected 67js.scene schemaVersion 1.');
}
@@ -431,6 +440,13 @@ function normalizeRecipe(input, limits) {
recipe.materials = resources(recipe.materials, limits.maxMaterials, 'materials', materialFrom);
recipe.nodes = resources(recipe.nodes, limits.maxNodes, 'nodes', nodeFrom);
recipe.camera = cameraFrom(recipe.camera);
+ const look = {};
+ for (const field of ['environment', 'effects', 'shadow']) {
+ if (Object.hasOwn(recipe, field)) {
+ look[field] = recipe[field];
+ }
+ }
+ Object.assign(recipe, normalizeAgentLook(look));
recipe = copiedJson(recipe, limits.maxRecipeBytes);
return recipe;
}
@@ -663,6 +679,15 @@ export function createAgentScene(input, inputLimits = {}) {
get camera() {
return structuredClone(state.recipe.camera);
},
+ get environment() {
+ return structuredClone(state.recipe.environment);
+ },
+ get effects() {
+ return structuredClone(state.recipe.effects);
+ },
+ get shadow() {
+ return structuredClone(state.recipe.shadow);
+ },
exportRecipe() {
return structuredClone(state.recipe);
},
@@ -676,6 +701,20 @@ export function createAgentScene(input, inputLimits = {}) {
const removedNodes = new Set();
const removedMaterials = new Set();
for (const operation of operations) {
+ const lookField = Object.hasOwn(LOOK_OPERATION_FIELDS, operation.type) ? LOOK_OPERATION_FIELDS[operation.type] : null;
+ if (lookField) {
+ knownKeys(operation, ['type', lookField], 'operation');
+ const patch = operation[lookField];
+ knownKeys(patch, Object.keys(candidate[lookField]), lookField);
+ const nestedField = lookField === 'environment' ? 'volumeFog' : lookField === 'effects' ? 'bloom' : null;
+ const merged = { ...candidate[lookField], ...patch };
+ if (nestedField && Object.hasOwn(patch, nestedField)) {
+ knownKeys(patch[nestedField], Object.keys(candidate[lookField][nestedField]), nestedField);
+ merged[nestedField] = { ...candidate[lookField][nestedField], ...patch[nestedField] };
+ }
+ candidate[lookField] = merged;
+ continue;
+ }
const addition = Object.hasOwn(ADDITION_FIELDS, operation.type) ? ADDITION_FIELDS[operation.type] : null;
if (addition) {
const [collection, field] = addition;
@@ -783,6 +822,12 @@ export function createAgentScene(input, inputLimits = {}) {
estimatedGeometryBytes: state.stats.estimatedGeometryBytes,
residentGeometryBytes: resident.geometryBytes,
residentGeometryVertices: resident.vertices,
+ look: {
+ world: state.recipe.environment.world,
+ pointLights: state.recipe.environment.pointLights.length,
+ volumeFogDensity: state.recipe.environment.volumeFog.density,
+ exposure: state.recipe.effects.exposure,
+ },
nodes, truncated: selected.length > nodes.length,
};
},
diff --git a/src/renderer.js b/src/renderer.js
index c935639b..58b19af1 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -706,7 +706,7 @@ export class Renderer67 {
if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Shadow framebuffer is incomplete.');
const defaults = this.world ? { eye: [-25, 60, 30], target: [0, 2, -10], extent: 65, near: 1, far: 220 } : { eye: [-3, 6, 4], target: [0, 1, 0], extent: 3.5, near: 0.1, far: 15 };
const light = { ...defaults, ...this.shadowBounds };
- const lightView = mat4.lookAt(mat4.create(), light.eye, light.target, [0, 1, 0]);
+ const lightView = mat4.lookAt(mat4.create(), light.eye, light.target, light.up ?? [0, 1, 0]);
mat4.ortho(this.lightProjection, -light.extent, light.extent, -light.extent, light.extent, light.near, light.far);
mat4.multiply(this.lightProjection, this.lightProjection, lightView);
context.viewport(0, 0, 2048, 2048);
diff --git a/tests/agent-look.test.js b/tests/agent-look.test.js
new file mode 100644
index 00000000..c7e04673
--- /dev/null
+++ b/tests/agent-look.test.js
@@ -0,0 +1,231 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mat4 } from 'gl-matrix';
+import { normalizeAgentLook, resolveAgentShadow } from '../src/agent-look.js';
+import { createLightingState, updateLightingState } from '../src/lighting.js';
+import { resolveVolumeFog } from '../src/volumetric.js';
+
+test('default look is complete, detached JSON and idempotent', () => {
+ const look = normalizeAgentLook();
+ assert.deepEqual(look.environment, {
+ world: false,
+ lightDirection: [-3, 6, 4],
+ keyColor: [5.2, 4.7, 4.1],
+ keyIntensity: 1,
+ fillIntensity: 1,
+ ambientIntensity: 1,
+ daylight: 1,
+ pointLights: [],
+ skyTop: [0.2, 0.38, 0.52],
+ skyBottom: [0.62, 0.7, 0.67],
+ fogColor: [0.35, 0.43, 0.43],
+ fogDensity: 0.006,
+ volumeFog: resolveVolumeFog(),
+ });
+ assert.deepEqual(look.effects, {
+ saturation: 1, contrast: 1, temperature: 0, vignette: 0, grain: 0,
+ bloom: { strength: 0.12, threshold: 1, radius: 1 }, exposure: 1,
+ });
+ assert.deepEqual(look.shadow, { target: [0, 1, 0], extent: 3.5, distance: 8, near: 0.1, far: 15 });
+ assert.deepEqual(JSON.parse(JSON.stringify(look)), look);
+ assert.deepEqual(normalizeAgentLook(look), look);
+ const other = normalizeAgentLook();
+ look.environment.lightDirection[0] = 999;
+ look.environment.volumeFog.minimum[0] = 999;
+ look.effects.bloom.strength = 999;
+ look.shadow.target[0] = 999;
+ assert.deepEqual(other, normalizeAgentLook());
+});
+
+test('normalization preserves author intent and publishes correct lighting radiance through existing validator', () => {
+ const input = {
+ environment: {
+ world: true,
+ lightDirection: [0, 12, 0],
+ keyColor: [2, 3, 4],
+ keyIntensity: 7,
+ fillIntensity: 0,
+ ambientIntensity: 0,
+ daylight: 0,
+ pointLights: [{ position: [1, 2, 3], range: 0 }, { position: [-1, 0, 4], color: [0.5, 0.2, 1], intensity: 100000, radius: 0.001, range: 1 }],
+ volumeFog: { density: 0.2 },
+ },
+ effects: { exposure: 2, bloom: { threshold: 2 }, contrast: 1.5 },
+ shadow: { distance: 10 },
+ };
+ const before = structuredClone(input);
+ const look = normalizeAgentLook(input);
+ assert.deepEqual(input, before);
+ assert.deepEqual(look.environment.lightDirection, [0, 12, 0]);
+ assert.deepEqual(look.environment.pointLights[0], { position: [1, 2, 3], color: [1, 1, 1], intensity: 1, radius: 0.05, range: 0 });
+ assert.deepEqual(look.effects.bloom, { strength: 0.12, threshold: 2, radius: 1 });
+ const lighting = updateLightingState(createLightingState(), look.environment, { world: look.environment.world });
+ assert.deepEqual(Array.from(lighting.keyColor), [14, 21, 28]);
+ assert.equal(lighting.pointCount, 2);
+ assert.equal(lighting.positions[3], 0);
+ assert.equal(lighting.colors[7], 100000);
+ look.environment.pointLights[0].position[0] = 100;
+ look.environment.volumeFog.color[0] = 0;
+ look.effects.bloom.threshold = 10;
+ assert.deepEqual(input, before);
+});
+
+test('strict look schema rejects unknown keys at every object boundary', () => {
+ const invalid = [
+ { lighting: {} },
+ { environment: { mystery: 1 } },
+ { environment: { pointLights: [{ position: [0, 0, 0], mystery: 1 }] } },
+ { environment: { volumeFog: { mystery: 1 } } },
+ { effects: { mystery: 1 } },
+ { effects: { bloom: { mystery: 1 } } },
+ { shadow: { eye: [1, 2, 3] } },
+ ];
+ for (const input of invalid) {
+ assert.throws(() => normalizeAgentLook(input), /Unknown/);
+ }
+ assert.throws(() => resolveAgentShadow({ up: [0, 1, 0] }), /Unknown/);
+});
+
+test('malformed JSON, getters, sparse arrays and executable values reject without executing accessors', () => {
+ const invalid = [null, [], new Date(), { effects: null }, { shadow: [] }, { environment: { world: 1 } },
+ { environment: { skyTop: new Float32Array([1, 1, 1]) } }, { effects: { exposure: undefined } },
+ { environment: { pointLights: [null] } }, { environment: { lightDirection: [1, 2] } },
+ { environment: { keyColor: ['1', 1, 1] } }, { effects: { grain: () => 0 } }];
+ for (const input of invalid) {
+ assert.throws(() => normalizeAgentLook(input));
+ }
+ const sparse = [0, 1, 0];
+ sparse.length++;
+ assert.throws(() => normalizeAgentLook({ environment: { lightDirection: sparse } }), /trailing holes/);
+ const hole = [0, 1, 0];
+ delete hole[1];
+ assert.throws(() => normalizeAgentLook({ shadow: { target: hole } }), /dense/);
+ let reads = 0;
+ const getter = {};
+ Object.defineProperty(getter, 'exposure', {
+ enumerable: true,
+ get() {
+ reads++;
+ return 1;
+ },
+ });
+ assert.throws(() => normalizeAgentLook({ effects: getter }), /accessors/);
+ assert.equal(reads, 0);
+ const cyclic = {};
+ cyclic.effects = cyclic;
+ assert.throws(() => normalizeAgentLook(cyclic), /acyclic/);
+ const hidden = {};
+ Object.defineProperty(hidden, 'exposure', { value: 1 });
+ assert.throws(() => normalizeAgentLook({ effects: hidden }), /hidden/);
+ const symbol = { [Symbol('hidden')]: true };
+ assert.throws(() => normalizeAgentLook(symbol), /Unknown/);
+});
+
+test('lighting ranges include zero intensity and unlimited point range while rejecting invalid edge values', () => {
+ const lights = Array.from({ length: 8 }, (_, index) => ({ position: [index, 0, 0], intensity: 0, range: 0 }));
+ const look = normalizeAgentLook({ environment: { pointLights: lights, keyIntensity: 0, fillIntensity: 0, ambientIntensity: 0, daylight: 0, fogDensity: 0 } });
+ assert.equal(look.environment.pointLights.length, 8);
+ assert.equal(look.environment.keyIntensity, 0);
+ assert.deepEqual(normalizeAgentLook({ environment: { pointLights: [] } }).environment.pointLights, []);
+ assert.throws(() => normalizeAgentLook({ environment: { pointLights: [...lights, lights[0]] } }), /8/);
+ const invalid = [
+ { pointLights: [{ position: [0, 0, 0], range: 0.0001 }] },
+ { pointLights: [{ position: [0, 0, 0], radius: 0 }] },
+ { pointLights: [{ position: [1000001, 0, 0] }] },
+ { pointLights: [{ position: [0, 0, 0], intensity: 100001 }] },
+ { pointLights: [{ position: [0, 0, 0], color: [1, -0.01, 0] }] },
+ { keyIntensity: 101 }, { fillIntensity: -1 }, { ambientIntensity: null }, { daylight: 101 },
+ { keyColor: [1001, 0, 0] }, { fogDensity: 11 }, { skyTop: [0, 2, 0] }, { fogColor: [0, -1, 0] },
+ { lightDirection: [0, 0, 0] }, { lightDirection: [0, 1e-7, 0] }, { lightDirection: [0, 1000001, 0] },
+ ];
+ for (const environment of invalid) {
+ assert.throws(() => normalizeAgentLook({ environment }));
+ }
+ for (const number of [Infinity, NaN, 1e100]) {
+ assert.throws(() => normalizeAgentLook({ environment: { fogDensity: number } }), /Float32/);
+ }
+ assert.deepEqual(normalizeAgentLook({ environment: { lightDirection: [1e-6, 0, 0] } }).environment.lightDirection, [1e-6, 0, 0]);
+});
+
+test('volume fog delegates defaults, domain ranges and Float32 bounds ordering', () => {
+ const look = normalizeAgentLook({ environment: { volumeFog: {
+ density: 10, minimum: [-1, -1, -1], maximum: [1, 1, 1], color: [1, 0, 1], ambient: [10, 0, 10],
+ drift: [-100, 0, 100], steps: 48, anisotropy: -0.9, noiseAmount: 0, noiseScale: 100, maxDistance: 10000,
+ } } });
+ assert.equal(look.environment.volumeFog.steps, 48);
+ const invalid = [
+ { minimum: [10000, 0, 0], maximum: [10000 + 1e-6, 1, 1] },
+ { density: null }, { steps: 8.5 }, { steps: 49 }, { color: [2, 0, 0] }, { ambient: [11, 0, 0] },
+ { drift: [101, 0, 0] }, { anisotropy: 1 }, { noiseAmount: -1 }, { noiseScale: 0 }, { maxDistance: 0 },
+ ];
+ for (const volumeFog of invalid) {
+ assert.throws(() => normalizeAgentLook({ environment: { volumeFog } }));
+ }
+ assert.throws(() => normalizeAgentLook({ environment: { volumeFog: { minimum: [1, 1, 1], maximum: [0, 0, 0] } } }), /Float32/);
+});
+
+test('effects enforce existing ranges, independent exposure and explicit bloom disable', () => {
+ const look = normalizeAgentLook({ effects: { exposure: 16, saturation: 2, contrast: 0.1, temperature: -1, vignette: 1, grain: 0.1, bloom: { strength: 0, threshold: 10, radius: 4 } } });
+ assert.equal(look.effects.bloom.strength, 0);
+ assert.equal(look.effects.exposure, 16);
+ assert.equal(normalizeAgentLook({ effects: { exposure: 0.01 } }).effects.exposure, 0.01);
+ const invalid = [
+ { exposure: 0 }, { exposure: 16.01 }, { saturation: 2.1 }, { contrast: 0 }, { temperature: 1.1 },
+ { vignette: -1 }, { grain: 0.11 }, { bloom: null }, { bloom: { strength: 2.1 } },
+ { bloom: { threshold: -1 } }, { bloom: { radius: 0 } }, { bloom: { radius: '1' } },
+ ];
+ for (const effects of invalid) {
+ assert.throws(() => normalizeAgentLook({ effects }));
+ }
+});
+
+test('shadow direction normalization preserves authored distance and handles vertical projectors', () => {
+ const first = resolveAgentShadow({ target: [2, 3, 4], distance: 10 }, [0, 200, 0]);
+ const second = resolveAgentShadow({ target: [2, 3, 4], distance: 10 }, [0, 2, 0]);
+ assert.deepEqual(first, second);
+ assert.deepEqual(first.eye, [2, 13, 4]);
+ assert.deepEqual(first.up, [0, 0, 1]);
+ assert.deepEqual(resolveAgentShadow({}, [0.01, -1, 0]).up, [0, 0, 1]);
+ assert.deepEqual(resolveAgentShadow({}, [1, 0, 0]).up, [0, 1, 0]);
+ const look = normalizeAgentLook({ environment: { lightDirection: [0, 1, 0] } });
+ assert.deepEqual(resolveAgentShadow(look.shadow, look.environment.lightDirection).eye, [0, 9, 0]);
+ const input = { target: [1, 2, 3] };
+ const bounds = resolveAgentShadow(input, [-3, 6, 4]);
+ bounds.target[0] = 9;
+ bounds.eye[0] = 9;
+ assert.deepEqual(input, { target: [1, 2, 3] });
+});
+
+test('shadow numerical combinations reject collapsed eye or clipping ranges before accepting the look', () => {
+ const invalid = [
+ { shadow: { target: [1e6, 0, 0], distance: 0.01 }, environment: { lightDirection: [1, 0, 0] } },
+ { shadow: { near: 10000, far: 10000 + 1e-6 } },
+ { shadow: { near: 15, far: 15 } },
+ { shadow: { extent: 0 } },
+ { shadow: { distance: 0 } },
+ { shadow: { target: [0, 1000001, 0] } },
+ { shadow: { near: 0.0001 } },
+ { shadow: { far: 1000001 } },
+ ];
+ for (const input of invalid) {
+ assert.throws(() => normalizeAgentLook(input));
+ }
+ assert.throws(() => resolveAgentShadow({}, [0, 0, 0]), /lightDirection/);
+ assert.throws(() => resolveAgentShadow({ target: [1e6, 0, 0], distance: 0.01 }, [1, 0, 0]), /distinguishable/);
+});
+
+test('valid shadow extremes produce finite nonsingular view, projection and combined matrices', () => {
+ for (const shadow of [
+ { extent: 0.01, distance: 0.01, near: 0.001, far: 0.002 },
+ { target: [1e6, -1e6, 1e6], extent: 1e5, distance: 1e6, near: 0.001, far: 1e6 },
+ ]) {
+ const bounds = resolveAgentShadow(shadow, [-3, 6, 4]);
+ const view = mat4.lookAt(mat4.create(), bounds.eye, bounds.target, bounds.up);
+ const projection = mat4.ortho(mat4.create(), -bounds.extent, bounds.extent, -bounds.extent, bounds.extent, bounds.near, bounds.far);
+ const combined = mat4.multiply(mat4.create(), projection, view);
+ for (const matrix of [view, projection, combined]) {
+ assert.ok(matrix.every(Number.isFinite));
+ assert.notEqual(mat4.determinant(matrix), 0);
+ }
+ }
+});
diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.js
index 5c317d27..14459803 100644
--- a/tests/agent-preview.test.js
+++ b/tests/agent-preview.test.js
@@ -5,6 +5,7 @@ import { Script, createContext } from 'node:vm';
import { mat4 } from 'gl-matrix';
import { createAgentScene } from '../src/agent-scene.js';
import { applyProjection } from '../src/camera.js';
+import { resolveAgentShadow } from '../src/agent-look.js';
const source = (await readFile(new URL('../scripts/agent-preview-browser.js', import.meta.url), 'utf8')).replace(/^import .+;\r?$/gm, '');
@@ -13,10 +14,12 @@ function previewHarness() {
let lost = false;
let replacementError = false;
let replacementCount = 0;
+ let currentRenderer;
const canvas = { width: 768, height: 512 };
class FaultInjectedRenderer {
memoryPlan = { estimatedBytes: 1024 };
capabilities = { hdr: true, samples: 4 };
+ constructor() { currentRenderer = this; }
context = {
isContextLost: () => lost,
getError: () => renderError,
@@ -37,7 +40,7 @@ function previewHarness() {
document: { querySelector: () => canvas },
// The real browser bundles these functions in one realm. Bridge only the VM realm here.
createAgentScene: input => createAgentScene(JSON.parse(JSON.stringify(input))),
- applyProjection, mat4,
+ applyProjection, mat4, resolveAgentShadow,
Renderer67: FaultInjectedRenderer,
});
// Evaluate only trusted repository adapter code; inject the driver boundary for failure cases.
@@ -48,9 +51,31 @@ function previewHarness() {
loseContext: () => { lost = true; },
rejectReplacement: value => { replacementError = value; },
replacementCount: () => replacementCount,
+ disableHdr: () => { currentRenderer.capabilities.hdr = false; },
};
}
+test('HDR fallback rejects enabling or restoring volume fog before canonical publication', () => {
+ const harness = previewHarness();
+ const sessionId = 'fog-fallback';
+ harness.preview.create({ recipe: recipe(), sessionId, backend: 'cpu', memoryBudgetMiB: 192 });
+ harness.preview.apply({ sessionId, expectedRevision: 0, operations: [
+ { type: 'set-environment', environment: { volumeFog: { density: 0.1 } } },
+ ] });
+ harness.preview.checkpoint({ sessionId, checkpointId: 'fog' });
+ harness.preview.apply({ sessionId, expectedRevision: 1, operations: [
+ { type: 'set-environment', environment: { volumeFog: { density: 0 } } },
+ ] });
+ harness.disableHdr();
+ const before = harness.preview.exportRecipe({ sessionId });
+ assert.throws(() => harness.preview.apply({ sessionId, expectedRevision: 2, operations: [
+ { type: 'set-node', id: 'cube', translation: [1, 2, 3] },
+ { type: 'set-environment', environment: { volumeFog: { density: 0.2 } } },
+ ] }), /HDR support/);
+ assert.throws(() => harness.preview.restore({ sessionId, checkpointId: 'fog', expectedRevision: 2 }), /HDR support/);
+ assert.deepEqual(harness.preview.exportRecipe({ sessionId }), before);
+});
+
function recipe() {
return { format: '67js.scene', schemaVersion: 1,
geometries: [{ id: 'cube', type: 'box', bevel: 0 }],
diff --git a/tests/agent-scene.test.js b/tests/agent-scene.test.js
index 503de813..73f09b3d 100644
--- a/tests/agent-scene.test.js
+++ b/tests/agent-scene.test.js
@@ -12,6 +12,52 @@ function recipe() {
{ id: 'other', label: 'Same label', geometry: 'box', material: 'finish' }] };
}
+test('authored look patches preserve resources and undo light, fog, exposure and projector together', () => {
+ const session = createAgentScene(recipe());
+ const before = session.exportRecipe();
+ const parts = session.parts;
+ const checkpoint = session.checkpoint();
+ session.apply([
+ { type: 'set-environment', environment: { world: true, lightDirection: [0, 1, 0], pointLights: [{ position: [1, 2, 3], intensity: 12 }], volumeFog: { density: 0.2 } } },
+ { type: 'set-effects', effects: { exposure: 0.8, bloom: { strength: 0.3 } } },
+ { type: 'set-shadow', shadow: { extent: 10, far: 40 } },
+ ], { expectedRevision: 0 });
+ assert.equal(session.parts, parts);
+ assert.equal(session.topologyRevision, 0);
+ assert.equal(session.environment.volumeFog.density, 0.2);
+ assert.deepEqual(session.environment.volumeFog.minimum, before.environment.volumeFog.minimum);
+ assert.equal(session.effects.bloom.threshold, before.effects.bloom.threshold);
+ const detached = session.environment;
+ detached.pointLights[0].position[0] = 999;
+ assert.equal(session.environment.pointLights[0].position[0], 1);
+ session.apply([{ type: 'set-environment', environment: { pointLights: [] } }], { expectedRevision: 1 });
+ assert.equal(session.environment.pointLights.length, 0);
+ session.restore(checkpoint, { expectedRevision: 2 });
+ assert.deepEqual(session.exportRecipe(), before);
+ assert.equal(session.parts, parts);
+ assert.equal(session.topologyRevision, 0);
+});
+
+test('invalid look in a mixed batch cannot publish transforms, material or render controls', () => {
+ const session = createAgentScene(recipe());
+ const before = session.exportRecipe();
+ const matrix = Array.from(session.parts[0].matrix);
+ for (const invalid of [
+ { type: 'set-environment', environment: { lightDirection: [0, 0, 0] } },
+ { type: 'set-effects', effects: { bloom: { unknown: 1 } } },
+ { type: 'set-shadow', shadow: { near: 15, far: 1 } },
+ ]) {
+ assert.throws(() => session.apply([
+ { type: 'set-node', id: 'child', translation: [9, 8, 7] },
+ { type: 'set-material', id: 'finish', color: [1, 0, 0] },
+ { type: 'set-effects', effects: { exposure: 2 } }, invalid,
+ ], { expectedRevision: 0 }));
+ assert.equal(session.revision, 0);
+ assert.deepEqual(session.exportRecipe(), before);
+ assert.deepEqual(Array.from(session.parts[0].matrix), matrix);
+ }
+});
+
test('shader arithmetic rejects cancelling product overflow and nonfinite emission atomically', () => {
const input = recipe();
const coordinate = Math.fround(1e20);
diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.js
index 7be8e074..0ccb09bf 100644
--- a/tests/mcp-tools.test.js
+++ b/tests/mcp-tools.test.js
@@ -117,6 +117,10 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'
const variants = recipeSchema.properties.geometries.items.oneOf ?? recipeSchema.properties.geometries.items.anyOf;
assert.deepEqual(variants.map(variant => variant.properties.type.const), ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube']);
assert.ok(variants.every(variant => variant.additionalProperties === false));
+ assert.equal(recipeSchema.properties.environment.additionalProperties, false);
+ assert.equal(recipeSchema.properties.environment.properties.pointLights.maxItems, 8);
+ assert.equal(recipeSchema.properties.effects.additionalProperties, false);
+ assert.equal(recipeSchema.properties.shadow.additionalProperties, false);
const look = tools.find(tool => tool.name === 'scene_look');
assert.equal(look.annotations.readOnlyHint, true);
assert.equal(look.inputSchema.properties.width.maximum, 1024);