3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Stop raising bloom in add-explosion; add flat Cycles comparison script (#1735)
Nguyen Xuan Anc306cc370193
diff --git a/changes/1735.md b/changes/1735.mdindex 80232b17..b29db9ef 100644--- a/changes/1735.md+++ b/changes/1735.md@@ -1 +1 @@-- Grid volumes take `flameTemperature: { ignition, maximum }`, Blender's flame remap (`flame > 0.01 ? ignition + flame * (maximum - ignition) : 0`), so the blackbody comes from the flame channel at 1500 to 3000 K whatever the smoke density, and the add-explosion fireball uses it: the smoke edge glows orange as it does in Cycles. Volumes without the field render as before. The Glaze, CPU, WebGPU and native paths and the fire light share the remap.+- Grid volumes take `flameTemperature: { ignition, maximum }`, Blender's flame remap (`flame > 0.01 ? ignition + flame * (maximum - ignition) : 0`), so the blackbody comes from the flame channel at 1500 to 3000 K whatever the smoke density, and the add-explosion fireball uses it: the smoke edge glows orange as it does in Cycles. Volumes without the field render as before. add-explosion no longer raises `effects.bloom` to 0.5 (the scene keeps its own bloom), which made the fireball glow where Cycles has no glare. The Glaze, CPU, WebGPU and native paths and the fire light share the remap.diff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex 61d50ef9..fe59a456 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -436,7 +436,7 @@ What it writes (read it back with `scene_export_recipe`, then tweak any part):- `effects.flash` and an `effects.distortion` ring at the centre, which fade by their own decay and falloff on the scene clock.- One gas-sim grid volume in `environment.localVolumes` for the fireball and the smoke: a baked simulation of a ground blast (`src/gas-sim.js`), lit by the physical blackbody of each voxel's flame, remapped to 1500 to 3000 K as Blender does (`flameTemperature`, `blackbodyIntensity`), so the smoke edge glows orange, with `castShadow` on so the smoke shades the floor and `lightsScene` on so the fire lights the set. It is the look of the gas-sim preview (#1735). `size` scales it: the box is 3.2 times `size` on a side, the density and emission shrink with the box so the blast keeps its optical depth, and it plays at 24 frames a second divided by the square root of `size / 2.5`, so a bigger fire rises slower. The grid is 32 cubed and 72 frames (3 s of simulation at the reference size), held on its last frame, baked once per fuel and seed in about 4 s. `oily` bakes more and darker smoke and thickens the volume.- The grid files are named `explosion-<fuel>-<seed>-velocity_0000.67vg` to `_0071`, plus `explosion-empty-velocity.67vg` for the wait. With `motionBlur: false` the files carry no velocity and the names drop `-velocity` (`explosion-<fuel>-<seed>_0000.67vg`, `explosion-empty.67vg`); a velocity bake is twice the bytes (about 28 MB for the 72 frames) and bakes in about the same time. The empty file is for the wait before `start` (one empty frame per frame of playback, so `start` is at most about 18 s at size 2.5 and the error says the limit for the size you pass). No such files exist on disk: the MCP server bakes them from the name (about 4 s the first time for a fuel and seed, cached after) and sends them to the preview page with `scene_apply`, so the page spends no time on the bake, and so `scene_export_recipe`, `scene_create` and the render jobs work with the recipe as it is.-- `effects.bloom.strength` raised to at least 0.5 so the glow spills past the flames. The volume's own light replaces the old point light and its track.+- `effects.bloom` is left as the scene has it (the default is strength 0.12), so the fireball is not glowier than the volume itself; raise it for a hazier look. The volume's own light replaces the old point light and its track.- `effects.flash` and an `effects.distortion` ring at the centre, which fade by their own decay and falloff on the scene clock.- Particle systems `id-sparks`, `id-dust` and `id-rubble`, delayed to `start` (the `delay` field of a particle system). The sparks are a `type: "sparks"` system (see `docs/physics.md`) with an unlit white `id-spark-glow` material, thrown from a small ball 0.2 `size` above the ground; their speed and size scale with the square root of `size / 2.5`, and their shutter stays the spark default (half a frame), as in the approved preview. Both options are on by default because Glaze at the early, peak and late frames of that preview matches its mean luminance within 3 percent, while a blast with both off is much dimmer.- A dark `id-scorch` disc decal that appears at `start`, and a camera eye shake track.diff --git a/scripts/explosion-cycles-reference.mjs b/scripts/explosion-cycles-reference.mjsindex cc4896f3..87029dfd 100644--- a/scripts/explosion-cycles-reference.mjs+++ b/scripts/explosion-cycles-reference.mjs@@ -32,7 +32,7 @@ function gridBytesForCycles(bytes, flameTemperature) {return encodeVolumeGrid({ resolution: grid.resolution, size: grid.size, channels: { ...grid.channels, temperature: Uint16Array.from(remapped, floatToHalf) } });}-/** Renders `frameIndex` of the grid volume with Cycles and returns the path of the PNG. */+/** Renders `frameIndex` of the grid volume with Cycles and returns the path of the PNG. `floor` null draws the gas on the flat background alone. */export async function renderCyclesReference({ volume, frameIndex, camera, floor, floorColor, folder, width, height, samples, blender = DEFAULT_BLENDER }) {await mkdir(folder, { recursive: true });const name = volume.frames[frameIndex];@@ -43,7 +43,7 @@ export async function renderCyclesReference({ volume, frameIndex, camera, floor,const spec = {vdb: [`${name.replace(/\.67vg$/, '')}.vdb`], frame: 0, volume: volumeFields,camera: { eye: camera.eye, target: camera.target, up: [0, 1, 0], fov: camera.fov },- floor: { y: floor, color: floorColor }, background: [0.2, 0.22, 0.25],+ ...(floor === null ? {} : { floor: { y: floor, color: floorColor } }), background: [0.2, 0.22, 0.25],image: { width, height, samples, device: 'GPU' },};await writeFile(join(folder, 'spec.json'), JSON.stringify(spec, null, 2));diff --git a/scripts/measure-explosion-breakup-flat.mjs b/scripts/measure-explosion-breakup-flat.mjsnew file mode 100644index 00000000..823d1816--- /dev/null+++ b/scripts/measure-explosion-breakup-flat.mjs@@ -0,0 +1,134 @@+#!/usr/bin/env node+// Draws the add-explosion recipe in Glaze (the rasterizer) and scores its peak frame against a Cycles render of the SAME scene, camera, gas and frame (#1736):+// how much the cloud breaks up (silhouette roughness), how fast it fades at its edge, how far its luminance distribution is from the reference's, and an RMSE+// of the two after both are centred and scaled to the same cloud size (scripts/explosion-breakup-metrics.mjs explains the reduction).+//+// GPU_LOCK_WEIGHT=heavy bash ~/.agents/tools/gpu-lock.sh node scripts/measure-explosion-breakup.mjs --out artifacts/explosion-breakup/before+//+// The Cycles frame (scripts/explosion-cycles-reference.mjs, Blender 5.3 at below normal priority) shows the grid frame the recipe plays at the first time, so it+// moves with the bake: the numbers say how well Glaze matches Cycles on that gas, and the Cycles row of the report says how ragged that gas is in truth.+// Not shared between the two: the sky (Cycles has a flat colour), the sun and the sparks, dust, rubble and debris, which only Glaze draws (sparks are off).+// --reference <png> scores against a Cycles frame already rendered (the grid frame must be the same: 9 for --times 0.45, size 4, seed 1) and runs no Blender.+// --detail off|strength,scale,octaves replaces the volume's detailNoise (#1832) to compare settings on one build.+// --times lists the motion times to draw in Glaze (the first one is scored), --backend gpu|cpu, --blender <exe>, --samples <n>.+// Prints one JSON object and saves frame-<time>.png and the Cycles render as cycles.png.+import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { Client } from '@modelcontextprotocol/client';+import { InMemoryTransport } from '@modelcontextprotocol/server';+import { createAgentRuntime } from './agent-runtime.mjs';+import { createAgentMcpServer } from './mcp-server.mjs';+import { decodePng } from '../bench/agent-modeling/png-check.mjs';+import { compareFrames, describeFrame, luminanceImage } from './explosion-breakup-metrics.mjs';+import { renderCyclesReference } from './explosion-cycles-reference.mjs';++const CYCLES_SIZE = { width: 960, height: 540 };+const FLOOR_COLOR = [0.12, 0.11, 0.1];+const FRAME_SIZE = { width: 1024, height: 576 };++// The scene the evidence stills use: a floor disc and a camera that looks at the blast from above and to the side.+const SCENE = {+ format: 'crucible.scene', schemaVersion: 1,+ geometries: [{ id: 'disc', type: 'cylinder' }],+ materials: [{ id: 'floor', color: FLOOR_COLOR, roughness: 1 }],+ nodes: [{ id: 'floor', geometry: 'disc', material: 'floor', scale: [9, 0.1, 9], translation: [0, -0.05, 0] }],+ camera: { eye: [0, 3.2, 9], target: [0, 1.6, 0], fov: 40 },+};++function parseArguments(argv) {+ const options = { backend: 'gpu', times: [0.45], samples: 128, size: 4, seed: 1, out: 'artifacts/explosion-breakup/run' };+ for (let index = 0; index < argv.length; index += 2) {+ const name = argv[index]?.replace(/^--/, '');+ if (!['backend', 'times', 'samples', 'size', 'seed', 'out', 'blender', 'reference', 'detail', 'flat', 'view', 'effects', 'volume'].includes(name) || argv[index + 1] === undefined) {+ throw new Error(`Unknown or incomplete option ${argv[index]}; use --out <folder> [--times 0.45,1.2] [--backend gpu|cpu] [--size 4] [--seed 1] [--samples 128] [--blender <exe>] [--reference <cycles.png>] [--detail off|strength,scale,octaves].`);+ }+ options[name] = argv[index + 1];+ }+ options.times = String(options.times).split(',').map(Number);+ options.size = Number(options.size);+ options.seed = Number(options.seed);+ options.samples = Number(options.samples);+ return options;+}++async function connect(backend) {+ const runtime = createAgentRuntime({ backend, memory: 192 });+ const server = createAgentMcpServer(runtime);+ const client = new Client({ name: 'measure-explosion-breakup', version: '1' });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ return { client, close: async () => { await client.close(); await server.close(); await runtime.close?.(); } };+}++async function call(client, name, argumentsValue) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 180000 });+ if (result.isError) throw new Error(result.content?.find(item => item.type === 'text')?.text ?? `${name} failed`);+ return result;+}++async function overrideDetailNoise(client, sessionId, revision, detail) {+ const exported = (await call(client, 'scene_export_recipe', { sessionId })).structuredContent;+ const current = exported.recipe ?? exported;+ const volume = { ...current.environment.localVolumes[0] };+ delete volume.detailNoise;+ if (detail !== 'off') {+ const [strength, scale, octaves] = detail.split(',').map(Number);+ volume.detailNoise = { strength, scale, octaves };+ }+ await call(client, 'scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-environment', environment: { localVolumes: [volume] } }] });+}++/** Merges the given fields into the first local volume, to try one emission setting without editing the recipe code. */+async function patchVolume(client, sessionId, revision, patch) {+ const exported = (await call(client, 'scene_export_recipe', { sessionId })).structuredContent;+ const volume = { ...(exported.recipe ?? exported).environment.localVolumes[0], ...patch };+ for (const [field, value] of Object.entries(patch)) if (value === null) delete volume[field];+ await call(client, 'scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-environment', environment: { localVolumes: [volume] } }] });+}++async function drawFrames(options) {+ const { client, close } = await connect(options.backend);+ try {+ const created = (await call(client, 'scene_create', { recipe: SCENE })).structuredContent;+ const operation = { type: 'add-explosion', id: 'blast', center: [0, 0, 0], size: options.size, seed: options.seed, sparks: 'none', motionBlur: false };+ let applied = (await call(client, 'scene_apply', { sessionId: created.sessionId, expectedRevision: created.revision, operations: [operation] })).structuredContent;+ const frames = [];+ if (options.flat === '1') {+ const flat = [0.2, 0.22, 0.25];+ applied = (await call(client, 'scene_apply', { sessionId: created.sessionId, expectedRevision: applied.revision, operations: [{ type: 'set-motion', motion: null }, { type: 'remove-node', id: 'floor' }, { type: 'remove-node', id: 'blast-dust' }, { type: 'remove-node', id: 'blast-rubble' }, { type: 'remove-node', id: 'blast-scorch' }, { type: 'set-particles', particles: null }, { type: 'set-environment', environment: { skyTop: flat, skyBottom: flat, daylight: 0, ...(options.view ? { viewTransform: options.view } : {}) } }, ...(options.effects ? [{ type: 'set-effects', effects: JSON.parse(options.effects) }] : [])] })).structuredContent;+ }+ if (options.volume) await patchVolume(client, created.sessionId, applied.revision, JSON.parse(options.volume));+ if (options.detail !== undefined) await overrideDetailNoise(client, created.sessionId, applied.revision, options.detail);+ for (const motionTime of options.times) {+ const look = await call(client, 'scene_look', { sessionId: created.sessionId, motionTime, ...FRAME_SIZE });+ const image = look.content.find(item => item.type === 'image');+ frames.push({ motionTime, png: Buffer.from(image.data, 'base64') });+ }+ const exported = (await call(client, 'scene_export_recipe', { sessionId: created.sessionId })).structuredContent;+ await writeFile(join(options.out, 'recipe.json'), JSON.stringify(exported.recipe ?? exported, (key, value) => (key === 'frames' ? undefined : value), 1));+ return { frames, volume: (exported.recipe ?? exported).environment.localVolumes[0] };+ } finally {+ await close();+ }+}++const options = parseArguments(process.argv.slice(2));+await mkdir(options.out, { recursive: true });+const { frames, volume } = await drawFrames(options);+const frameIndex = Math.round(options.times[0] * volume.fps);+const cyclesPng = options.reference ?? await renderCyclesReference({ volume, frameIndex, camera: SCENE.camera, floor: options.flat === '1' ? null : 0, floorColor: FLOOR_COLOR, folder: join(options.out, 'cycles-work'), ...CYCLES_SIZE, samples: options.samples, blender: options.blender });+await copyFile(cyclesPng, join(options.out, 'cycles.png'));+const reference = describeFrame(luminanceImage(decodePng(await readFile(cyclesPng))));+const report = { backend: options.backend, size: options.size, seed: options.seed, gridFrame: frameIndex, samples: options.samples, times: [] };+for (const [position, frame] of frames.entries()) {+ await writeFile(join(options.out, `frame-${frame.motionTime}.png`), frame.png);+ const described = describeFrame(luminanceImage(decodePng(frame.png)));+ const entry = { motionTime: frame.motionTime, cloudRadiusPixels: Math.round(described.geometry.radius), roughness: described.roughness, edgeFalloff: described.edgeFalloff };+ if (position === 0) entry.againstReference = compareFrames(reference, described);+ report.times.push(entry);+}+report.reference = { cloudRadiusPixels: Math.round(reference.geometry.radius), roughness: reference.roughness, edgeFalloff: reference.edgeFalloff };+await writeFile(join(options.out, 'report.json'), JSON.stringify(report, null, 2));+console.log(JSON.stringify(report, null, 2));+process.exit(0);diff --git a/src/agent-explosion.js b/src/agent-explosion.jsindex 8401355a..eb59c46d 100644--- a/src/agent-explosion.js+++ b/src/agent-explosion.js@@ -246,9 +246,8 @@ function addBlastVolume(candidate, plan) {lightsScene: true,});environment.localVolumes = existing;- // The volume's own light (lightsScene) follows the fire, so the old point light and its track are gone. A stronger bloom lets the glow spill.- const bloom = candidate.effects.bloom ?? {};- candidate.effects.bloom = { ...bloom, strength: Math.max(bloom.strength ?? 0, 0.5) };+ // The volume's own light (lightsScene) follows the fire, so the old point light and its track are gone. The bloom stays as the scene has it: raising it to 0.5+ // made the fireball glow where Cycles has no glare, and without the raise the blast is closer to Cycles at 0.1 and 0.45 s and equal at 1.2 s (#1735).if (plan.motionBlur) openShutter(candidate);}diff --git a/tests/agent-explosion.test.js b/tests/agent-explosion.test.jsindex 3c8b8410..6477e37d 100644--- a/tests/agent-explosion.test.js+++ b/tests/agent-explosion.test.js@@ -204,10 +204,10 @@ test('the MCP server finds the grids an add-explosion operation will name, so thassert.equal(readVolumeGridFiles([blast({ seed: -1 })], '.').size, 0);});-// Both options are off: the recipe is the one the first release wrote, byte for byte (hashes taken from main before #1775, refreshed for #1736's emission change and #1735's flame remap).+// Both options are off: the recipe is the one the first release wrote, byte for byte (hashes taken from main before #1775, refreshed for #1736's emission change and #1735's flame remap and unraised bloom).const FIRST_RELEASE_HASHES = new Map([- ['{}', 'd391923bb69c2e00dbe3cb82811dc3a8cb0f76f5f3a3d9c0ec5cd8ec39b7ac24'],- ['{"start":0.5,"fuel":"oily","seed":7}', '48ede2e133f804d0a35b675edbd031289702993cdbcbc60ec0872e132ec1dfc0'],+ ['{}', 'df70567bd19d0d575a77bf3d6b8209768f859d0ac689986baa46c15075f1b7f0'],+ ['{"start":0.5,"fuel":"oily","seed":7}', '9c8225756d33fd331a836f0018a4c78200f1d9a55a41d91355c833eebf8f535e'],]);test('sparks specks and motionBlur false write exactly the recipe of the first release, and false is an alias of specks', () => {@@ -259,6 +259,14 @@ test('by default the sparks are streaks born at start and the fireball grid carrassert.equal(applyBlast(blast({ fuel: 'oily' })).recipe.particles.systems[0].count, 900);});+test('the blast leaves the scene bloom as it is, so the fire glows only as far as its own emission (#1735)', () => {+ const plain = applyBlast(blast()).recipe.effects.bloom;+ assert.equal(plain.strength, 0.12);+ const withBloom = setRecipe();+ withBloom.effects = { bloom: { strength: 0.3 } };+ assert.equal(applyBlast(blast(), withBloom).recipe.effects.bloom.strength, 0.3);+});+test('motionBlur takes the shutter the scene already has, and leaves the effects alone when off', () => {const withShutter = setRecipe();withShutter.effects = { motionBlur: { shutter: 0.02 } };