3D engine that AI agents drive
Blur the light seen through a local volume by its optical depth and document density as extinction per metre (#855)
Nguyen Xuan An46f3403d3e90
diff --git a/changes/855-blur-density.md b/changes/855-blur-density.mdnew file mode 100644index 00000000..42085030--- /dev/null+++ b/changes/855-blur-density.md@@ -0,0 +1 @@+- A local volume blurs the light seen through it by its optical depth (new `blur` field, 0 to 1, default 1, at most 14 px of a 540 row frame, never smearing objects in front of the volume), and `density` is documented as extinction per metre with a table of thin haze and thick smoke values (#855)diff --git a/docs/volumetric.md b/docs/volumetric.mdindex b73056f4..6b06b7d9 100644--- a/docs/volumetric.md+++ b/docs/volumetric.md@@ -125,12 +125,27 @@ In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is th| `absorption` | `[1, 1, 1]` | Per colour channel share of the density, `0` to `1`. A larger value dims that channel more, so `[0.1, 0.6, 1]` removes blue first and leaves a warm tint || `emission`, `emissionStrength` | `[0, 0, 0]`, `1` | Glow colour and its radiance per unit length at the core, `0` to `1000`. Emission does not depend on `density`, so `density: 0` is a pure glow || `falloff` | `0.5` | `0` to `1`. The outer share of the volume over which the density fades to zero (`0` is a hard edge) |+| `blur` | `1` | `0` to `1`. How much the light seen through the volume is blurred, by its optical depth (see Thick smoke and thin haze). `0` keeps it sharp || `scatter` | `0` | `0` to `1`. The share of the light the volume extinguishes that it scatters back instead of absorbing, lit by the key light and the sky (see "Lit volumes"). `0` draws exactly as before. Not allowed with `fit: "mesh"` || `noiseAmount`, `noiseScale` | `0`, `1` | `noiseAmount` `0` to `1` breaks the density up with value noise at `noiseScale` cells per unit: the profile is multiplied by `mix(1, 2 * noise, noiseAmount)`. The rasterizer and the CPU path tracer read the same field. A `fit: "mesh"` volume ignores it || `steps` | `16` | `4` to `32` samples through the volume. With `noiseAmount` above 0 the count is raised to two samples per noise cell along the ray (`ceil(length * noiseScale * 2)`, at most 32), because fewer samples than that skip whole cells and a fine pixel-pitch dither of the start offset shows in dense smoke (8 steps measured); a volume without noise takes exactly `steps` |Each volume is marched on its own between its entry and its exit, cut at the first surface, and the volumes are composited nearest entry first. Overlapping volumes are therefore an approximation. Local volumes are drawn before `volumeFog`, so a fog in front of a puff also dims it. They need the same renderer as the fog (`hdr: true`, `depth: true`, an opaque canvas) and are drawn in the post pass, so they are not in the lightmap bake: a scene bake (`bake` in a recipe) leaves them out, an emissive volume lights no baked surface and no volume dims the baked light, and the bake report names them in `skippedLocalVolumes` (index, shape, whether emissive) with a `warnings` line. A scene without local volumes bakes and reports exactly as before. Add a point light or an emissive part where the volume's glow should reach a wall. The path tracer traces them on `backend: "cpu"` with the same fields, noise included, and every other tracer entry point (backends `gpu`, `webgpu` and `native`, the progressive and both realtime tracers, the GPU light bake) throws `environment.localVolumes is traced by the CPU path tracer only` instead of leaving them out. The GPU tracers are refused, not ported: each would need a second march loop in its kernel and a volume table in every pack, for a feature the CPU tracer already draws. Cost grows with the covered pixels times `steps` times the number of volumes that the pixel's ray crosses; a ray that misses every volume pays only the interval test.+### Thick smoke and thin haze++`density` is the extinction per metre at the core, times each channel of `absorption`. The light behind a ray that crosses `length` metres of core is multiplied by `exp(-density * absorption * length)` (Beer-Lambert), in the rasterizer and the CPU path tracer alike. Scattering is not a second loss: `scatter` only returns that share of what the extinction took, so a lit volume never adds more than its lights give. The faded skin and the noise lower the mean along a ray (a 3.2 m box with `falloff` 0.7 crosses about 2 m of core density), so pick by the transmittance you want:++| Look | `density` (3.2 m box) | Light left behind the core | Use |+| --- | --- | --- | --- |+| Thin haze or wisp | `0.3` (`falloff` 0.5) | 50 to 65 percent | The background shows, blurred |+| Medium smoke | `1.5` (`falloff` 0.7) | 6 to 25 percent | Shapes behind are faint ghosts |+| Thick smoke | `3` (`falloff` 0.6) | under 3 percent | The core hides the background |++Measured on the 2.4 m high, 3.2 m wide box of the smoke still, from rays through its middle (noise 0.5): density 0.3 let 50 to 64 percent of the green channel through, 1.5 let 6 to 25 percent and 3 let 0.2 to 2.7 percent. A uniform slab of 1 m (`falloff: 0`) of density 3.5 let 0.0303 through in the rasterizer and 0.0302 in the tracer against exp(-3.5) = 0.0302; density 0.7 gave 0.4978 and 0.4965 against 0.4966 (`tests/local-volume-blur.test.js`; worst 8 by 8 region differed by 0.0013).++Thin smoke also blurs what is behind it. The rasterizer averages 12 taps of the frame over a disc of radius `14 * (1 - exp(-opticalDepth))` pixels of a 540 row frame (it scales with the frame height), where the optical depth is the mean of the extinction along the ray, times `blur`. It is zero at zero depth and never passes 14 px, only runs on pixels whose ray meets a volume, and a tap counts only where its surface lies at or past the ray's first volume entry, so an object in front of the volume is not smeared into it. It reads the frame's mip chain, so a frame with a blurring volume generates mips like a frame with `volumeFog`. The CPU path tracer marches straight through a local volume and does not scatter the background, so it draws the same dimming but no blur: set `blur: 0` to compare the two.+### Lit volumesA volume with `scatter` above `0` returns, in each step, `scatter * (1 - exp(-extinction * step))` of the light it dims, per colour channel, times the light that arrives at that point: the sky term plus the key light. Smoke or haze in sun then reads bright on the side toward the sun and grey in shade, where a `scatter: 0` volume draws as a dark stain.diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex de11c4e1..158de1fd 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -272,7 +272,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({maxSpotLights: MAX_SPOT_LIGHTS, maxAreaLights: MAX_AREA_LIGHTS,localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, tileSize: 512 }),lightLinking: Object.freeze({ fields: Object.freeze(['environment.keyAffects', 'pointLights[].affects', 'spotLights[].affects', 'areaLights[].affects']), unlisted: 'a light without affects lights every node', unknownNode: 'rejected', bake: 'honoured', pathTracer: 'ignored, named in report.ignored' }),- localVolumes: Object.freeze({ field: 'environment.localVolumes', maximum: 8, shapes: Object.freeze(['box', 'sphere', 'mesh']), fields: 'shape, center, size (box) or radius (sphere) or part + fit bounds|mesh (mesh: the named part, bounds by default; fit mesh fills a closed part, ignoring falloff, noise and steps), density 0-100 (1), falloff 0-1 (0.5), absorption rgb 0-1 (1,1,1), emission rgb 0-1, emissionStrength 0-1000 (1), scatter 0-1 (0; lit by the key light and the sky, not with fit mesh), noiseAmount 0-1 (0), noiseScale (1), steps 4-32 (16)', note: 'Absorb and emit; scatter above 0 lights the volume with the key light (shadow map, own depth toward the sun) and the sky term, 0 draws as before; needs hdr and depth like volumeFog; noise is the same field in the rasterizer and the CPU path tracer; path tracer: backend cpu only (gpu, webgpu and native throw); a bake leaves them out, so an emissive volume lights no baked surface (bake report: skippedLocalVolumes, warnings).' }),+ localVolumes: Object.freeze({ field: 'environment.localVolumes', maximum: 8, shapes: Object.freeze(['box', 'sphere', 'mesh']), fields: 'shape, center, size (box) or radius (sphere) or part + fit bounds|mesh (mesh: the named part, bounds by default; fit mesh fills a closed part, ignoring falloff, noise and steps), density 0-100 (1), falloff 0-1 (0.5), absorption rgb 0-1 (1,1,1), emission rgb 0-1, emissionStrength 0-1000 (1), scatter 0-1 (0; lit by the key light and the sky, not with fit mesh), blur 0-1 (1; softens the light behind it by optical depth, max 14 px at 540 rows), noiseAmount 0-1 (0), noiseScale (1), steps 4-32 (16)', note: 'Absorb and emit; scatter above 0 lights the volume with the key light (shadow map, own depth toward the sun) and the sky term, 0 draws as before; density is extinction per metre times absorption, light behind = exp(-density * absorption * metres): about 0.3 is a thin haze (half shows through), 3 is thick smoke (under 3 percent); needs hdr and depth like volumeFog; noise is the same field in the rasterizer and the CPU path tracer; path tracer: backend cpu only (gpu, webgpu and native throw); a bake leaves them out, so an emissive volume lights no baked surface (bake report: skippedLocalVolumes, warnings).' }),shadowCascades: Object.freeze({ field: 'environment.shadowCascades', counts: Object.freeze([0, 1, 2, 3, 4]), zero: 'one shadow map', automatic: 'three cascades when shadow.extent is above 40 and the field is unset', maximumDistance: 150, note: 'volume fog and water read the single map' }),lineArt: Object.freeze({ field: 'environment.lines', fields: 'width px 0.25-16 (1.5), color, boundaries, creaseAngle deg (35), depthJump (0.08), toon steps 0-8, polylines [{points [x,y,z] 2-256, color, width, depthTest, closed}] max 64; {} turns on, null clears; material toon 0-8', note: 'docs/line-art.md' }),viewTransform: Object.freeze({diff --git a/src/fog-shader.js b/src/fog-shader.jsindex 79605106..b59f5a4d 100644--- a/src/fog-shader.js+++ b/src/fog-shader.js@@ -1,5 +1,5 @@import { registerShaderFeatureCode } from './shader-registry.js';-import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes, LOCAL_VOLUME_MAXIMUM_STEPS, LOCAL_VOLUME_STEPS_PER_NOISE_CELL, LOCAL_VOLUME_KEY_GAIN, LOCAL_VOLUME_LIGHT_DEPTH_SATURATION, LOCAL_VOLUME_SHADOW_STRENGTH, LOCAL_VOLUME_SKY_GAIN, LOCAL_VOLUME_SUN_FLATTEN } from './local-volumes.js';+import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes, LOCAL_VOLUME_MAXIMUM_STEPS, LOCAL_VOLUME_STEPS_PER_NOISE_CELL, LOCAL_VOLUME_BLUR_PIXELS, LOCAL_VOLUME_KEY_GAIN, LOCAL_VOLUME_LIGHT_DEPTH_SATURATION, LOCAL_VOLUME_SHADOW_STRENGTH, LOCAL_VOLUME_SKY_GAIN, LOCAL_VOLUME_SUN_FLATTEN } from './local-volumes.js';import { bindLocalVolumeParts } from './local-volume-parts.js';import { drawMeshVolumes } from './mesh-volume-pass.js';import { FogFieldTexture, createFogLightBuffers, packFogLights, volumeShadowAmbient, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD, resolveFogDetail, fogUsesDetail } from './fog-field.js';@@ -253,6 +253,26 @@ vec3 localVolumeInScatter(int index, vec3 position, vec3 direction) {}return localVolumeSkyLight(index, position) + sunLight;}+// The light behind a volume, blurred by the optical depth in front of it: taps of the frame spread over a disc whose radius grows with the depth,+// each counted only where its surface lies at or past the ray's first volume entry, so an object in front of the volume is never smeared into it.+vec3 localVolumeBlurred(vec3 background, float opticalDepth, float firstEntry, vec3 origin, vec3 direction) {+ float radiusPixels = ${LOCAL_VOLUME_BLUR_PIXELS.toFixed(1)} * (resolution.y / 540.0) * (1.0 - exp(-opticalDepth));+ if (radiusPixels < 0.05) return background;+ float lod = max(0.0, log2(radiusPixels * 0.5));+ vec3 sum = background;+ float weight = 1.0;+ for (int tap = 0; tap < 12; tap++) {+ float index = float(tap) + 0.5;+ vec2 offsetPixels = vec2(cos(index * 2.4), sin(index * 2.4)) * (radiusPixels * sqrt(index / 12.0));+ vec2 coordinate = textureCoordinate + offsetPixels / resolution;+ vec4 tapPoint = inverseViewProjection * vec4(coordinate * 2.0 - 1.0, texture(sceneDepth, coordinate).r * 2.0 - 1.0, 1.0);+ float tapDistance = tapPoint.w > 0.0 ? dot(tapPoint.xyz - origin * tapPoint.w, direction) / tapPoint.w : 1e30;+ if (tapDistance < firstEntry) continue;+ sum += textureLod(frameTexture, coordinate, lod).rgb;+ weight += 1.0;+ }+ return mix(background, sum / weight, min(radiusPixels, 1.0));+}vec3 localVolumes(vec3 background) {vec2 clipXY = textureCoordinate * 2.0 - 1.0;vec4 farPoint = inverseViewProjection * vec4(clipXY, 1.0, 1.0);@@ -290,6 +310,8 @@ vec3 localVolumes(vec3 background) {}vec3 transmittance = vec3(1.0);vec3 radiance = vec3(0.0);+ float blurDepth = 0.0;+ float blurEntry = 1e30;for (int pass = 0; pass < 8; pass++) {int nearest = -1;float nearestEntry = 1e29;@@ -312,6 +334,8 @@ vec3 localVolumes(vec3 background) {vec3 gain = mix(vec3(insideLength), (1.0 - factor) / max(absorption, vec3(1e-6)), step(vec3(1e-6), absorption));radiance += transmittance * localVolumeEmission[nearest].rgb * gain;transmittance *= factor;+ blurDepth += localVolumeSteps[nearest].w * dot(absorption, vec3(0.3333)) * insideLength;+ blurEntry = min(blurEntry, entry);continue;}int steps = int(localVolumeSteps[nearest].x);@@ -328,8 +352,11 @@ vec3 localVolumes(vec3 background) {vec3 extinction = localVolumeAbsorption[nearest].rgb * (profile * stepSize);if (scatterAlbedo > 0.0 && profile > 0.0) radiance += transmittance * (scatterAlbedo * (1.0 - exp(-extinction))) * localVolumeInScatter(nearest, position, direction);transmittance *= exp(-extinction);+ blurDepth += localVolumeSteps[nearest].w * dot(extinction, vec3(0.3333));}+ blurEntry = min(blurEntry, entry);}+ if (blurDepth > 0.0) background = localVolumeBlurred(background, blurDepth, blurEntry, origin, direction);return background * transmittance + radiance;}`;diff --git a/src/local-volumes.js b/src/local-volumes.jsindex 123105b2..77658b2b 100644--- a/src/local-volumes.js+++ b/src/local-volumes.js@@ -8,7 +8,7 @@ import { localVolumeNoiseFactor } from './local-volume-noise.js';export const MAX_LOCAL_VOLUMES = 8;export const LOCAL_VOLUME_SHAPES = Object.freeze(['box', 'sphere', 'mesh']);export const LOCAL_VOLUME_FIT = Object.freeze(['bounds', 'mesh']);-export const LOCAL_VOLUME_FIELDS = Object.freeze(['shape', 'part', 'fit', 'center', 'size', 'radius', 'density', 'falloff', 'absorption', 'emission', 'emissionStrength', 'scatter', 'noiseAmount', 'noiseScale', 'steps']);+export const LOCAL_VOLUME_FIELDS = Object.freeze(['shape', 'part', 'fit', 'center', 'size', 'radius', 'density', 'falloff', 'absorption', 'emission', 'emissionStrength', 'scatter', 'blur', 'noiseAmount', 'noiseScale', 'steps']);export const LOCAL_VOLUME_MAXIMUM_STEPS = 32;function vectorField(value, minimum, maximum, label) {@@ -32,6 +32,7 @@ function resolveLocalVolume(input, label) {emission: vectorField(input.emission ?? [0, 0, 0], 0, 1, `${label}.emission`),emissionStrength: finiteRange(input.emissionStrength ?? 1, 0, 1000, `${label}.emissionStrength`),scatter: finiteRange(input.scatter ?? 0, 0, 1, `${label}.scatter`),+ blur: finiteRange(input.blur ?? 1, 0, 1, `${label}.blur`),noiseAmount: finiteRange(input.noiseAmount ?? 0, 0, 1, `${label}.noiseAmount`),noiseScale: finiteRange(input.noiseScale ?? 1, 0.001, 100, `${label}.noiseScale`),steps: finiteRange(input.steps ?? 16, 4, LOCAL_VOLUME_MAXIMUM_STEPS, `${label}.steps`),@@ -69,7 +70,7 @@ export function resolveLocalVolumes(input, label = 'localVolumes') {/** The uniform arrays the post shader reads, one vec4 per volume. Pass resolved volumes. */export function createLocalVolumeBuffers() {const size = MAX_LOCAL_VOLUMES * 4;- return { count: 0, meshParts: [], centers: new Float32Array(size), extents: new Float32Array(size), absorption: new Float32Array(size), emission: new Float32Array(size), steps: new Float32Array(size), axes: new Float32Array(size * 3) };+ return { count: 0, blurred: false, meshParts: [], centers: new Float32Array(size), extents: new Float32Array(size), absorption: new Float32Array(size), emission: new Float32Array(size), steps: new Float32Array(size), axes: new Float32Array(size * 3) };}const IDENTITY_AXES = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);@@ -81,6 +82,7 @@ export function packLocalVolumes(volumes, buffers) {if (volumes.some(volume => volume.shape === 'mesh' && !volume.center)) throw new RangeError('A mesh volume names a part: bind it with bindLocalVolumeParts before packing');buffers.count = volumes.length;buffers.meshParts = [];+ buffers.blurred = volumes.some(volume => volume.blur > 0 && volume.density > 0);volumes.forEach((volume, index) => {const at = index * 4;const half = volume.shape === 'sphere' ? [volume.radius, volume.radius, volume.radius] : volume.size.map(extent => extent / 2);@@ -89,7 +91,7 @@ export function packLocalVolumes(volumes, buffers) {buffers.extents.set([...half, volume.falloff], at);buffers.absorption.set([...volume.absorption.map(channel => channel * volume.density), volume.noiseAmount], at);buffers.emission.set([...volume.emission.map(channel => channel * volume.emissionStrength), volume.noiseScale], at);- buffers.steps.set([volume.steps, packedShape === PACKED_SHAPE_MESH ? buffers.meshParts.length : 0, volume.scatter ?? 0, 0], at);+ buffers.steps.set([volume.steps, packedShape === PACKED_SHAPE_MESH ? buffers.meshParts.length : 0, volume.scatter ?? 0, volume.blur ?? 0], at);if (packedShape === PACKED_SHAPE_MESH) buffers.meshParts.push({ part: volume.part, label: `environment.localVolumes[${index}]` });const axes = volume.axes ?? IDENTITY_AXES;for (let axis = 0; axis < 3; axis++) buffers.axes.set([axes[axis * 3], axes[axis * 3 + 1], axes[axis * 3 + 2], 0], (index * 3 + axis) * 4);@@ -121,6 +123,13 @@ export const LOCAL_VOLUME_SHADOW_STRENGTH = 3;/** The share of the mean sky radiance the sky term of a scattering volume keeps. The sky lights the whole volume evenly, so a high share flattens the form the sun gives it. */export const LOCAL_VOLUME_SKY_GAIN = 0.5;+/**+ * The widest blur, in pixels of a 540 row frame (it scales with the frame height), that the light behind a volume gets: the radius grows as+ * `cap * (1 - exp(-opticalDepth))`, so none at zero depth, most of the cap by an optical depth of 2, and it never passes the cap. A thick volume hides the+ * background anyway, a thin one shows it blurred (#855).+ */+export const LOCAL_VOLUME_BLUR_PIXELS = 14;+/** Samples the march takes per cell of the density noise at least: fewer step over whole cells and the dither of the start offset shows as pixel-pitch grain (#855). */export const LOCAL_VOLUME_STEPS_PER_NOISE_CELL = 2;diff --git a/src/renderer.js b/src/renderer.jsindex c79f41da..14d5ee86 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -2212,7 +2212,7 @@ export class Renderer67 {context.activeTexture(context.TEXTURE0);context.bindTexture(context.TEXTURE_2D, sourceTexture);// The fog's glow reads blurred copies of the frame from its mip chain, so a tap is smooth instead of one speckled pixel.- if (volume.density > 0) {+ if (volume.density > 0 || (localVolumes && this.localVolumeBuffers.blurred)) {context.generateMipmap(context.TEXTURE_2D);context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR_MIPMAP_LINEAR);this.mipmappedTexture = sourceTexture;diff --git a/tests/local-volume-blur.test.js b/tests/local-volume-blur.test.jsnew file mode 100644index 00000000..8a1e9d61--- /dev/null+++ b/tests/local-volume-blur.test.js@@ -0,0 +1,224 @@+// Density as extinction per metre, and the blur of the light seen through a local volume (issue 855). The pure tests check the field and the+// packing; the browser test draws unlit scenes in the rasterizer (headless Chrome, SwiftShader, Vite dev server) and compares them with the CPU+// path tracer, and skips when Chrome cannot start. Set LOCAL_VOLUME_BLUR_ARTIFACTS to a folder to write the measured numbers there.+import test from 'node:test';+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { freePort } from './helpers/free-port.js';+import { renderPathTracedImage } from '../src/path-tracer.js';+import { applyViewTransform } from '../src/view-transform.js';+import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes, LOCAL_VOLUME_BLUR_PIXELS } from '../src/local-volumes.js';++const SIZE = 128;+const CPU_SIZE = 32;+const LOOKING_DOWN = { eye: [0, 8, 0], target: [0, 0, 0], up: [0, 0, -1], fov: 30 };+const SLAB = { shape: 'box', center: [0, 1.5, 0], size: [1.2, 1, 1.2], falloff: 0, scatter: 0 };++test('blur defaults to 1, accepts 0 to 1 and rejects the rest with the field name', () => {+ assert.equal(resolveLocalVolumes([{ ...SLAB }])[0].blur, 1);+ assert.equal(resolveLocalVolumes([{ ...SLAB, blur: 0 }])[0].blur, 0);+ assert.throws(() => resolveLocalVolumes([{ ...SLAB, blur: 1.5 }]), /blur/);+ assert.throws(() => resolveLocalVolumes([{ ...SLAB, blur: 'a lot' }]), /blur/);+});++test('the packed volume carries its blur in the fourth component of steps, and the buffers say whether any volume blurs', () => {+ const buffers = createLocalVolumeBuffers();+ packLocalVolumes(resolveLocalVolumes([{ ...SLAB, blur: 0.25 }, { ...SLAB, blur: 0 }]), buffers);+ assert.equal(buffers.steps[3], 0.25);+ assert.equal(buffers.steps[7], 0);+ assert.equal(buffers.blurred, true);+ packLocalVolumes(resolveLocalVolumes([{ ...SLAB, blur: 0 }, { ...SLAB, density: 0 }]), buffers);+ assert.equal(buffers.blurred, false, 'a volume with blur 0 or no density never reads the frame');+ assert.ok(LOCAL_VOLUME_BLUR_PIXELS > 0 && LOCAL_VOLUME_BLUR_PIXELS <= 32);+});++async function startServer(port) {+ const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });+ await new Promise((resolve, reject) => {+ const timeout = setTimeout(() => reject(new Error('The dev server did not start.')), 30000);+ server.stdout.on('data', (data) => {+ if (/ready in/.test(data.toString())) {+ clearTimeout(timeout);+ resolve();+ }+ });+ server.on('exit', (code) => {+ clearTimeout(timeout);+ reject(new Error(`The dev server exited ${code}.`));+ });+ });+ return server;+}++// Draws a white unlit ground, the extra black parts and the volumes; returns the red channel of every pixel, top row first.+async function drawRaster(page, extraParts, volumes) {+ const task = async ({ size, camera, extraParts: extras, volumes: localVolumes }) => {+ const { box } = await import('/src/geometry.js');+ const { Renderer67 } = await import('/src/renderer.js');+ const { createFloatOutput, readFloatPixels } = await import('/src/float-output.js');+ await import('/src/fog-shader.js');+ document.body.innerHTML = '';+ const canvas = document.createElement('canvas');+ canvas.width = size;+ canvas.height = size;+ canvas.style.width = size + 'px';+ canvas.style.height = size + 'px';+ document.body.append(canvas);+ const unlit = color => ({ tag: 'unlit', color, metallic: 0, roughness: 1, emission: 0 });+ const scaled = ([width, height, depth], [x, y, z]) => new Float32Array([width, 0, 0, 0, 0, height, 0, 0, 0, 0, depth, 0, x, y, z, 1]);+ const parts = [{ name: 'ground', geometry: box(0, 1), matrix: scaled([40, 0.2, 40], [0, -0.1, 0]), material: unlit([1, 1, 1]) }];+ extras.forEach((extra, index) => parts.push({ name: `black${index}`, geometry: box(0, 1), matrix: scaled(extra.size, extra.center), material: unlit([0, 0, 0]) }));+ const renderer = new Renderer67(canvas, parts, { hdr: true, depth: true, samples: 1, pixelRatio: 1, ground: false });+ const output = createFloatOutput(renderer.context, size, size);+ const environment = { keyIntensity: 0, fillIntensity: 0, ambientIntensity: 0, localVolumes };+ renderer.render({ ...camera, time: 0, environment, outputFramebuffer: output.framebuffer });+ const pixels = Array.from(readFloatPixels(renderer.context, output.framebuffer, size, size));+ const glError = renderer.context.getError();+ output.dispose();+ renderer.dispose?.();+ return { pixels, glError };+ };+ const { pixels, glError } = await page.evaluate(task, { size: SIZE, camera: LOOKING_DOWN, extraParts, volumes });+ assert.equal(glError, 0);+ const image = new Float64Array(SIZE * SIZE);+ for (let row = 0; row < SIZE; row++) for (let column = 0; column < SIZE; column++) image[row * SIZE + column] = pixels[((SIZE - 1 - row) * SIZE + column) * 4];+ return image;+}++// The display shows aces(light) ^ (1 / 2.2); this undoes both, so the ratio of two frames is the light that got through.+function lightOf(displayed) {+ let low = 0;+ let high = 64;+ for (let round = 0; round < 40; round++) {+ const middle = (low + high) / 2;+ if (applyViewTransform('aces', [middle, middle, middle])[0] ** (1 / 2.2) < displayed) low = middle;+ else high = middle;+ }+ return low;+}++async function cpuTransmittance(volume) {+ const material = { tag: 'surface', metallic: 0, roughness: 1, color: [0, 0, 0], ior: 1, emission: 1, emissiveColor: [1, 1, 1] };+ const half = 20;+ const geometry = {+ positions: new Float32Array([-half, 0, half, half, 0, half, half, 0, -half, -half, 0, -half]),+ normals: new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]),+ uvs: new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ };+ const { linear } = await renderPathTracedImage(+ { parts: [{ name: 'ground', geometry, material }], environment: { localVolumes: [volume] }, camera: LOOKING_DOWN },+ { width: CPU_SIZE, height: CPU_SIZE, denoise: false, threads: 1, bounces: 1, samples: 4 },+ );+ const result = new Float64Array(CPU_SIZE * CPU_SIZE);+ for (let pixel = 0; pixel < result.length; pixel++) result[pixel] = linear[pixel * 3];+ return result;+}++const centerOf = image => image[(SIZE / 2) * SIZE + SIZE / 2];++function worstRegionDifference(raster, plain, cpu) {+ const cells = SIZE / 8;+ const scale = CPU_SIZE / SIZE;+ let worst = 0;+ for (let cellRow = 0; cellRow < cells; cellRow++) {+ for (let cellColumn = 0; cellColumn < cells; cellColumn++) {+ let rasterTotal = 0;+ let cpuTotal = 0;+ for (let y = cellRow * 8; y < cellRow * 8 + 8; y++) {+ for (let x = cellColumn * 8; x < cellColumn * 8 + 8; x++) {+ rasterTotal += lightOf(raster[y * SIZE + x]) / lightOf(plain[y * SIZE + x]);+ cpuTotal += cpu[Math.floor(y * scale) * CPU_SIZE + Math.floor(x * scale)];+ }+ }+ worst = Math.max(worst, Math.abs(rasterTotal - cpuTotal) / 64);+ }+ }+ return worst;+}++// The steepest step between neighbouring pixels along the centre row, over the whole range of the row: how sharp the black bar's edge is.+function edgeSharpness(image) {+ const row = SIZE / 2;+ let steepest = 0;+ let low = Infinity;+ let high = -Infinity;+ for (let column = 1; column < SIZE; column++) {+ steepest = Math.max(steepest, Math.abs(image[row * SIZE + column] - image[row * SIZE + column - 1]));+ low = Math.min(low, image[row * SIZE + column]);+ high = Math.max(high, image[row * SIZE + column]);+ }+ return steepest / (high - low);+}++test('density is extinction per metre: a slab of density d and thickness t lets exp(-d t) through, in the rasterizer and the CPU path tracer', async (context) => {+ let chromium;+ try {+ ({ chromium } = await import('playwright'));+ } catch {+ context.skip('playwright is not installed');+ return;+ }+ const port = await freePort();+ const server = await startServer(port);+ let browser;+ try {+ try {+ const launchArguments = ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'];+ browser = await chromium.launch({ headless: true, args: launchArguments }).catch(() => chromium.launch({ headless: true, channel: 'chrome', args: launchArguments }));+ } catch (error) {+ context.skip(`Chrome did not start: ${error.message.split('\n')[0]}`);+ return;+ }+ const page = await browser.newPage({ viewport: { width: SIZE, height: SIZE } });+ await page.goto(`http://127.0.0.1:${port}/`);+ const numbers = {};+ const plain = await drawRaster(page, [], []);+ const blackBar = { size: [0.3, 0.2, 6], center: [0, 0.1, 0] };++ // Thick smoke hides what is behind it; a haze lets about half through. The slab is 1 m thick (the ray runs straight down).+ for (const [name, density, expected] of [['thick', 3.5, Math.exp(-3.5)], ['haze', 0.7, Math.exp(-0.7)]]) {+ const volume = { ...SLAB, size: [6, 1, 6], density };+ const raster = await drawRaster(page, [], [volume]);+ const rasterLight = lightOf(centerOf(raster)) / lightOf(centerOf(plain));+ assert.ok(Math.abs(rasterLight - expected) < 0.01, `${name}: raster let ${rasterLight} through, Beer-Lambert says ${expected}`);+ const cpu = await cpuTransmittance(volume);+ const cpuLight = cpu[(CPU_SIZE / 2) * CPU_SIZE + CPU_SIZE / 2];+ assert.ok(Math.abs(cpuLight - expected) < 0.01, `${name}: CPU let ${cpuLight} through, Beer-Lambert says ${expected}`);+ numbers[name] = { density, expected: +expected.toFixed(4), raster: +rasterLight.toFixed(4), cpu: +cpuLight.toFixed(4), worstRegionRasterAgainstCpu: +worstRegionDifference(raster, plain, cpu).toFixed(4) };+ assert.ok(numbers[name].worstRegionRasterAgainstCpu < 0.01, `${name}: worst 8 by 8 region ${numbers[name].worstRegionRasterAgainstCpu}`);+ }+ assert.ok(numbers.thick.raster < 0.05, 'a thick smoke leaves under 5 percent of the background');++ // Thin smoke blurs the bar behind it: the edge is less sharp with blur than without, and the same with density 0 volume elsewhere.+ const haze = { ...SLAB, density: 1.2, size: [2.4, 1, 2.4] };+ const sharp = await drawRaster(page, [blackBar], [{ ...haze, blur: 0 }]);+ const blurred = await drawRaster(page, [blackBar], [haze]);+ const clearBar = await drawRaster(page, [blackBar], []);+ numbers.sharpness = { clear: +edgeSharpness(clearBar).toFixed(3), blur0: +edgeSharpness(sharp).toFixed(3), blur1: +edgeSharpness(blurred).toFixed(3) };+ assert.ok(numbers.sharpness.blur1 < numbers.sharpness.blur0 * 0.8, `blur must soften the edge: ${JSON.stringify(numbers.sharpness)}`);++ // Nothing outside the volume's footprint changes: the far left column band sees no volume.+ let outsideChange = 0;+ for (let row = 0; row < SIZE; row++) for (let column = 0; column < 8; column++) outsideChange = Math.max(outsideChange, Math.abs(blurred[row * SIZE + column] - sharp[row * SIZE + column]));+ assert.equal(outsideChange, 0, 'blur stays inside the screen footprint of the volume');++ // An object between the camera and the volume is not smeared into it: next to its edge the light is what blur 0 gives.+ const occluder = { size: [0.5, 0.2, 0.5], center: [0, 3, 0] };+ const withoutBlur = await drawRaster(page, [occluder], [{ ...haze, blur: 0 }]);+ const withBlur = await drawRaster(page, [occluder], [haze]);+ let smear = 0;+ for (let offset = 14; offset <= 16; offset++) smear = Math.max(smear, Math.abs(withBlur[(SIZE / 2) * SIZE + SIZE / 2 + offset] - withoutBlur[(SIZE / 2) * SIZE + SIZE / 2 + offset]));+ numbers.smearNextToObjectInFront = +smear.toFixed(5);+ assert.ok(smear < 0.005, `an object in front smeared into the volume by ${smear}`);+ if (process.env.LOCAL_VOLUME_BLUR_ARTIFACTS) {+ mkdirSync(process.env.LOCAL_VOLUME_BLUR_ARTIFACTS, { recursive: true });+ writeFileSync(join(process.env.LOCAL_VOLUME_BLUR_ARTIFACTS, 'blur-test-numbers.json'), `${JSON.stringify(numbers, null, 2)}\n`);+ }+ } finally {+ await browser?.close();+ server.kill();+ }+});