3D engine that AI agents drive
Add local absorbing and emitting volumes (#710)
Nguyen Xuan Ance7acf995c33
diff --git a/changes/710.md b/changes/710.mdnew file mode 100644index 00000000..f0092b3a--- /dev/null+++ b/changes/710.md@@ -0,0 +1 @@+- `environment.localVolumes` adds up to 8 box or sphere volumes that absorb and emit light, in the rasterizer and the CPU path tracer (#710)diff --git a/docs/agent-look.md b/docs/agent-look.mdindex 36684252..8cf3d745 100644--- a/docs/agent-look.md+++ b/docs/agent-look.md@@ -142,6 +142,7 @@ Sky colors use display RGB, matching the renderer's existing environment contrac| `fogColor` | `[0.35, 0.43, 0.43]` | Components from `0` to `1` || `fogDensity` | `null` | `0` to `10`. `null` fits the density to the scene: `0.006`, or `1.2` divided by the scene diagonal in metres when that is smaller, so a 900 m scene keeps 30 percent of its contrast at the far side. Set `0` for no fog || `volumeFog` | Complete defaults below | One bounded world volume |+| `localVolumes` | Absent | Up to 8 box or sphere volumes that absorb and emit light; see [volume fog](https://67js.codepawl.com/volumetric.md#local-volumes) |Directional key radiance equals `keyColor * keyIntensity`.Zero intensity disables that lighting contribution.diff --git a/docs/volumetric.md b/docs/volumetric.mdindex ecfdb246..bfe4d325 100644--- a/docs/volumetric.md+++ b/docs/volumetric.md@@ -105,3 +105,26 @@ Measured at 1920 × 1080 with 24 steps on an RTX 3060 shared with other jobs, whRun `node scripts/smoke-volumetric.mjs` with the development server running for native GPU extinction, foreground clipping, directional shadow, long-distance ray, resource reuse and disposal checks. Run `node scripts/benchmark-volumetric.mjs` for a fixed laboratory comparison and deterministic noise seeking. These fixtures establish behavior, not cinematic trailer quality.In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is the grid's mean light at the cell instead of the fog's own 64 rays: the grid already holds the sun's bounce, the lights and the emission over several bounces, so the sun is not left out there. The fog's ambient then stands for the sky only (it follows the cell's sky visibility, with no floor for the sun's shadow), because the grid replaces what the ambient stood in for. Measured on the reference halls (FLIP against Cycles, lower is better): `temple-hall-a` 0.1454 to 0.1323, `temple-hall-b` 0.1211 to 0.1085, `temple-hall-c` 0.1078 to 0.0874, `temple-hall` 0.0576 to 0.0513. `dark-shaft`, a small room with dense fog, goes from 0.0569 to 0.0732: the grid's light in its shade is about three times the fog's old stand-in, and Cycles draws that shade darker still.++## Local volumes++`environment.localVolumes` holds up to 8 boxes or spheres that absorb and emit light: candle haze, a smoke puff, a glowing cloud in one place. They need no `volumeFog` and do not scatter, so a lamp does not light them; they only dim what is behind them and add their own glow. A scene without `localVolumes` draws exactly as before and compiles nothing extra.++```json+{ "environment": { "localVolumes": [+ { "shape": "sphere", "center": [0, 1.2, 0], "radius": 0.8, "density": 3, "absorption": [1, 1, 1], "emission": [1, 0.45, 0.1], "emissionStrength": 4, "noiseAmount": 0.6, "noiseScale": 2 }+] } }+```++| Field | Default | Meaning |+| --- | --- | --- |+| `shape` | `box` | `box` takes `size: [width, height, depth]`, `sphere` takes `radius` |+| `center` | required | World position |+| `density` | `1` | `0` to `100`. Extinction per unit length at the core |+| `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) |+| `noiseAmount`, `noiseScale` | `0`, `1` | Raster only. `noiseAmount` `0` to `1` breaks the density up with the cloud noise at `noiseScale` cells per unit |+| `steps` | `16` | `4` to `32` samples through the volume |++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. The path tracer traces them on `backend: "cpu"` with the same fields except the noise, and refuses them on the GPU backends rather than leaving them out. 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.diff --git a/src/agent-look.js b/src/agent-look.jsindex 89771f3e..69930517 100644--- a/src/agent-look.js+++ b/src/agent-look.js@@ -3,6 +3,7 @@ import { mat4 } from 'gl-matrix';import { createLightingState, updateLightingState, MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS, MAXIMUM_SPECULAR_ANTI_ALIASING } from './lighting.js';import { resolveEffects } from './effects.js';import { resolveVolumeFog } from './volumetric.js';+import { resolveLocalVolumes } from './local-volumes.js';import { LIQUID_OPTICS, resolveLiquidOptics } from './liquid-optics.js';import { createLightingSetupMap, createCatalogEnvironmentMap, lightingSetupFields } from './lighting-setups.js';import { agentSceneModule } from './agent-scene-modules.js';@@ -16,7 +17,7 @@ const MAX_LOOK_ARRAY_ENTRIES = Math.max(MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_Aconst ENVIRONMENT_FIELDS = ['world', 'ground', 'setup', 'hdri', 'environmentIntensity', 'environmentRotation', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity',- 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections', 'floorSkyTrace', 'sunBounce', 'specularAntiAliasing', 'sunAngularRadius', 'lines', 'resolveCoplanar', 'viewTransform', 'look', 'wind', 'sky',+ 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'localVolumes', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections', 'floorSkyTrace', 'sunBounce', 'specularAntiAliasing', 'sunAngularRadius', 'lines', 'resolveCoplanar', 'viewTransform', 'look', 'wind', 'sky',];const EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'ambientOcclusion', 'ambientOcclusionRadius', 'bloom', 'depthOfField', 'motionBlur'];const SHADOW_FIELDS = ['target', 'extent', 'distance', 'near', 'far'];@@ -317,6 +318,10 @@ function environmentFrom(input = {}) {if (input.areaLights !== undefined) {environment.areaLights = lightListFrom(input.areaLights, MAX_AREA_LIGHTS, 'environment.areaLights').map((light, index) => withFieldPrefix(`environment.areaLights[${index}]`, () => areaLightFrom(light)));}+ // Optional like the lights above, so a recipe without local volumes keeps its exported shape.+ if (input.localVolumes !== undefined) {+ environment.localVolumes = copiedJson(resolveLocalVolumes(input.localVolumes, 'environment.localVolumes'));+ }if (input.shadowCascades !== undefined) {environment.shadowCascades = shadowCascadesFrom(input.shadowCascades);}diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 4e0225bc..3dcfe047 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -268,6 +268,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']), fields: 'shape, center, size (box) or radius (sphere), density 0-100 (1), falloff 0-1 (0.5), absorption rgb 0-1 (1,1,1), emission rgb 0-1, emissionStrength 0-1000 (1), noiseAmount 0-1 (0), noiseScale (1), steps 4-32 (16)', note: 'Absorb and emit, no scattering; needs hdr and depth like volumeFog; noise is raster only; path tracer: backend cpu only.' }),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/agent-scene-modules.js b/src/agent-scene-modules.jsindex ce110f90..e6198d62 100644--- a/src/agent-scene-modules.js+++ b/src/agent-scene-modules.js@@ -67,7 +67,7 @@ const MODULE_MARKERS = {liquidShader: ['"transmission"', '"liquid"', '"foam"'],subsurfaceShader: ['"subsurface"'],// Any mention loads it, because an edit can set the density through a path or the environment of an operation.- fogShader: ['volumeFog'],+ fogShader: ['volumeFog', 'localVolumes'],worldMaterials: ['"tag":"water"', '"waterPreset"', '"absorption"', '"turbidity"', '"vegetation":{', '"tag":"foliage"', '"tag":"grass"', '"tag":"terrain"', '"tag":"fire"', '"tag":"smoke"', '"moss"'],terrain: ['"type":"terrain"'],// No recipe text asks for it, only the path option of scene_inspect does, so a host loads it with loadAllAgentSceneModules.diff --git a/src/agent-scene.js b/src/agent-scene.jsindex e3be67fe..05313660 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -1804,7 +1804,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {knownKeys(operation, ['type', lookField], 'operation');const patch = operation[lookField];// Spot and area lights, cascades and sun links are absent from a recipe until it sets them.- const optionalFields = lookField === 'environment' ? ['ground', 'spotLights', 'areaLights', 'shadowCascades', 'keyAffects', 'objectReflections', 'floorSkyTrace', 'sunBounce', 'specularAntiAliasing', 'sunAngularRadius', 'lines', 'resolveCoplanar', 'viewTransform', 'look', 'hdri', 'sky'] : lookField === 'effects' ? postStepSupport.fields : [];+ const optionalFields = lookField === 'environment' ? ['ground', 'spotLights', 'areaLights', 'shadowCascades', 'localVolumes', 'keyAffects', 'objectReflections', 'floorSkyTrace', 'sunBounce', 'specularAntiAliasing', 'sunAngularRadius', 'lines', 'resolveCoplanar', 'viewTransform', 'look', 'hdri', 'sky'] : lookField === 'effects' ? postStepSupport.fields : [];knownKeys(patch, [...Object.keys(candidate[lookField]), ...optionalFields], lookField);const nestedField = lookField === 'environment' ? 'volumeFog' : 'bloom';const merged = { ...candidate[lookField], ...(lookField === 'environment' ? environmentPatchWithSetup(patch) : patch) };diff --git a/src/fog-shader.js b/src/fog-shader.jsindex ebf69487..fda5c96f 100644--- a/src/fog-shader.js+++ b/src/fog-shader.js@@ -1,4 +1,5 @@import { registerShaderFeatureCode } from './shader-registry.js';+import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes } from './local-volumes.js';import { FogFieldTexture, createFogLightBuffers, packFogLights, volumeShadowAmbient, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD, resolveFogDetail, fogUsesDetail } from './fog-field.js';// The volume fog step of the post pass: its uniforms and the march that scatters light through the fog box. Only a renderer that@@ -73,14 +74,135 @@ function bindFieldAndLights(renderer, post, volume) {context.uniform4fv(post.uniforms['volumeLightCones[0]'], lights.cones);}+// The local volumes of the frame (environment.localVolumes): validated, packed and bound. Their uniforms exist only in a program+// with the local step compiled in, and a program without it never reaches this function.+function bindLocalVolumes(renderer, post, volumes, frame) {+ const context = renderer.context;+ const buffers = (renderer.localVolumeBuffers ??= createLocalVolumeBuffers());+ packLocalVolumes(resolveLocalVolumes(volumes, 'environment.localVolumes'), buffers);+ const locate = name => (post.uniforms[name] ??= context.getUniformLocation(post.program, name));+ context.uniform1i(locate('localVolumeCount'), buffers.count);+ context.uniform1f(locate('localOrthographic'), frame.projection === 'orthographic' ? 1 : 0);+ context.uniform4fv(locate('localVolumeCenters[0]'), buffers.centers);+ context.uniform4fv(locate('localVolumeExtents[0]'), buffers.extents);+ context.uniform4fv(locate('localVolumeAbsorption[0]'), buffers.absorption);+ context.uniform4fv(locate('localVolumeEmission[0]'), buffers.emission);+ context.uniform4fv(locate('localVolumeSteps[0]'), buffers.steps);+}++const LOCAL_VOLUME_DECLARATIONS = `+uniform int localVolumeCount;+uniform float localOrthographic;+uniform vec4 localVolumeCenters[8];+uniform vec4 localVolumeExtents[8];+uniform vec4 localVolumeAbsorption[8];+uniform vec4 localVolumeEmission[8];+uniform vec4 localVolumeSteps[8];+`;++// Each volume is marched on its own between its entry and exit (cut at the first surface) and composited nearest first: the colour+// behind it is dimmed by exp(-absorption * profile * step) and its emission is added, both per colour channel.+const LOCAL_VOLUME_FUNCTIONS = `+vec2 localVolumeInterval(int index, vec3 origin, vec3 direction) {+ vec3 center = localVolumeCenters[index].xyz;+ vec3 halfSize = localVolumeExtents[index].xyz;+ if (localVolumeCenters[index].w > 0.5) {+ vec3 offset = origin - center;+ float along = dot(offset, direction);+ float discriminant = along * along - (dot(offset, offset) - halfSize.x * halfSize.x);+ if (discriminant <= 0.0) return vec2(0.0);+ float root = sqrt(discriminant);+ return vec2(-along - root, -along + root);+ }+ float entry = -1e30;+ float exitDistance = 1e30;+ for (int axis = 0; axis < 3; axis++) {+ float relative = center[axis] - origin[axis];+ if (direction[axis] == 0.0) {+ if (abs(relative) > halfSize[axis]) return vec2(0.0);+ } else {+ float first = (relative - halfSize[axis]) / direction[axis];+ float second = (relative + halfSize[axis]) / direction[axis];+ entry = max(entry, min(first, second));+ exitDistance = min(exitDistance, max(first, second));+ }+ }+ return vec2(entry, exitDistance);+}+float localVolumeProfile(int index, vec3 position) {+ vec3 offset = position - localVolumeCenters[index].xyz;+ vec3 halfSize = localVolumeExtents[index].xyz;+ float distanceRatio = localVolumeCenters[index].w > 0.5 ? length(offset) / halfSize.x : max(max(abs(offset.x) / halfSize.x, abs(offset.y) / halfSize.y), abs(offset.z) / halfSize.z);+ float falloff = localVolumeExtents[index].w;+ float profile = falloff > 0.0 ? 1.0 - smoothstep(1.0 - falloff, 1.0, distanceRatio) : 1.0 - step(1.0, distanceRatio);+ float noiseAmount = localVolumeAbsorption[index].w;+ if (noiseAmount > 0.0) profile *= mix(1.0, cloudNoise(position * localVolumeEmission[index].w) * 2.0, noiseAmount);+ return profile;+}+vec3 localVolumes(vec3 background) {+ vec2 clipXY = textureCoordinate * 2.0 - 1.0;+ vec4 farPoint = inverseViewProjection * vec4(clipXY, 1.0, 1.0);+ vec4 nearPoint = inverseViewProjection * vec4(clipXY, -1.0, 1.0);+ vec3 origin = localOrthographic > 0.5 ? nearPoint.xyz / nearPoint.w : eye;+ vec3 direction = normalize(farPoint.xyz - origin * farPoint.w);+ float depth = texture(sceneDepth, textureCoordinate).r;+ vec4 surfacePoint = inverseViewProjection * vec4(clipXY, depth * 2.0 - 1.0, 1.0);+ float surfaceDistance = 1e30;+ if (surfacePoint.w > 0.0) surfaceDistance = max(0.0, dot(surfacePoint.xyz - origin * surfacePoint.w, direction) / surfacePoint.w);+ float entries[8];+ float exits[8];+ for (int index = 0; index < 8; index++) {+ entries[index] = 1e30;+ exits[index] = 0.0;+ if (index >= localVolumeCount) continue;+ vec2 span = localVolumeInterval(index, origin, direction);+ float entry = max(span.x, 0.0);+ float exitDistance = min(span.y, surfaceDistance);+ if (exitDistance > entry) {+ entries[index] = entry;+ exits[index] = exitDistance;+ }+ }+ vec3 transmittance = vec3(1.0);+ vec3 radiance = vec3(0.0);+ for (int pass = 0; pass < 8; pass++) {+ int nearest = -1;+ float nearestEntry = 1e29;+ for (int index = 0; index < 8; index++) {+ if (entries[index] < nearestEntry) {+ nearestEntry = entries[index];+ nearest = index;+ }+ }+ if (nearest < 0) break;+ float entry = entries[nearest];+ float exitDistance = exits[nearest];+ entries[nearest] = 1e30;+ int steps = int(localVolumeSteps[nearest].x);+ float stepSize = (exitDistance - entry) / float(steps);+ float jitter = hash(vec3(gl_FragCoord.xy, float(nearest) + 1.0));+ for (int step = 0; step < 32; step++) {+ if (step >= steps) break;+ vec3 position = origin + direction * (entry + (float(step) + jitter) * stepSize);+ float profile = localVolumeProfile(nearest, position);+ radiance += transmittance * localVolumeEmission[nearest].rgb * (profile * stepSize);+ transmittance *= exp(-localVolumeAbsorption[nearest].rgb * (profile * stepSize));+ }+ }+ return background * transmittance + radiance;+}+`;+function packLights(renderer) {renderer.fogLightBuffers ??= createFogLightBuffers();packFogLights(renderer.lighting, renderer.fogLightBuffers);}registerShaderFeatureCode('volumeFog', {- // The JavaScript half, which the renderer calls for a frame that draws a volume fog.- support: { packLights, bindUniforms, usesDetail: fogUsesDetail },+ // The JavaScript halfSize, which the renderer calls for a frame that draws a volume fog.+ support: { packLights, bindUniforms, usesDetail: fogUsesDetail, bindLocalVolumes },+ localDeclarations: LOCAL_VOLUME_DECLARATIONS,+ localFunctions: LOCAL_VOLUME_FUNCTIONS,postDeclarations: `uniform highp sampler2DShadow volumeShadowMap;uniform mat4 volumeLightProjection;@@ -231,7 +353,7 @@ float sunOpticalDepth(vec3 position, vec3 towardSun) {return volumeDensity * sum * exitDistance / 3.0;}// The sun's in-scatter at a point. The octave sum approximates multiple scattering (Wrenninge et al. 2015, "Oz: the great and-// volumetric"): octave n scatters multiScatter^n as much, sees half^n of the extinction and has half^n of the anisotropy.+// volumetric"): octave n scatters multiScatter^n as much, sees halfSize^n of the extinction and has halfSize^n of the anisotropy.float keyInScatter(float cosine, float opticalDepth) {float total = 0.0;float weight = 1.0;diff --git a/src/local-volumes.js b/src/local-volumes.jsnew file mode 100644index 00000000..ddf9cb6e--- /dev/null+++ b/src/local-volumes.js@@ -0,0 +1,122 @@+import { finiteRange } from './volumetric.js';++// Local volumes: up to MAX_LOCAL_VOLUMES boxes or spheres that absorb and emit light, for candle haze, smoke puffs and glowing+// fog in one place. They sit beside environment.volumeFog (the one scattering volume) and need no fog. The post pass marches+// each one separately and composites them from the nearest entry to the farthest, so overlapping volumes are an approximation.++export const MAX_LOCAL_VOLUMES = 8;+export const LOCAL_VOLUME_SHAPES = Object.freeze(['box', 'sphere']);+export const LOCAL_VOLUME_FIELDS = Object.freeze(['shape', 'center', 'size', 'radius', 'density', 'falloff', 'absorption', 'emission', 'emissionStrength', 'noiseAmount', 'noiseScale', 'steps']);+export const LOCAL_VOLUME_MAXIMUM_STEPS = 32;++function vectorField(value, minimum, maximum, label) {+ if (!Array.isArray(value) || value.length !== 3) throw new TypeError(`${label} must be an array of three numbers`);+ return value.map(component => finiteRange(component, minimum, maximum, label));+}++function resolveLocalVolume(input, label) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError(`${label} must be an object`);+ for (const field of Object.keys(input)) {+ if (!LOCAL_VOLUME_FIELDS.includes(field)) throw new TypeError(`${label} has no field "${field}"; use ${LOCAL_VOLUME_FIELDS.join(', ')}`);+ }+ const shape = input.shape ?? 'box';+ if (!LOCAL_VOLUME_SHAPES.includes(shape)) throw new RangeError(`${label}.shape must be one of ${LOCAL_VOLUME_SHAPES.join(', ')}`);+ const resolved = {+ shape,+ center: vectorField(input.center, -1e5, 1e5, `${label}.center`),+ density: finiteRange(input.density ?? 1, 0, 100, `${label}.density`),+ falloff: finiteRange(input.falloff ?? 0.5, 0, 1, `${label}.falloff`),+ absorption: vectorField(input.absorption ?? [1, 1, 1], 0, 1, `${label}.absorption`),+ emission: vectorField(input.emission ?? [0, 0, 0], 0, 1, `${label}.emission`),+ emissionStrength: finiteRange(input.emissionStrength ?? 1, 0, 1000, `${label}.emissionStrength`),+ 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`),+ };+ if (!Number.isInteger(resolved.steps)) throw new RangeError(`${label}.steps must be an integer`);+ if (shape === 'sphere') {+ if (input.size !== undefined) throw new TypeError(`${label}.size belongs to a box; a sphere takes radius`);+ resolved.radius = finiteRange(input.radius, 0.001, 1e4, `${label}.radius`);+ } else {+ if (input.radius !== undefined) throw new TypeError(`${label}.radius belongs to a sphere; a box takes size [width, height, depth]`);+ resolved.size = vectorField(input.size, 0.001, 1e4, `${label}.size`);+ }+ return resolved;+}++/** Checks a list of local volumes and returns them with every default filled in. Throws an error that names the field. */+export function resolveLocalVolumes(input, label = 'localVolumes') {+ if (!Array.isArray(input)) throw new TypeError(`${label} must be an array of volumes`);+ if (input.length > MAX_LOCAL_VOLUMES) throw new RangeError(`${label} holds at most ${MAX_LOCAL_VOLUMES} volumes, got ${input.length}`);+ return input.map((volume, index) => resolveLocalVolume(volume, `${label}[${index}]`));+}++/** 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, centers: new Float32Array(size), extents: new Float32Array(size), absorption: new Float32Array(size), emission: new Float32Array(size), steps: new Float32Array(size) };+}++export function packLocalVolumes(volumes, buffers) {+ buffers.count = volumes.length;+ 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);+ buffers.centers.set([...volume.center, volume.shape === 'sphere' ? 1 : 0], at);+ 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, 0, 0, 0], at);+ });+ return buffers;+}++/** The density factor of a volume at a point, 0 to 1, without noise: 1 at the core, fading over the outer `falloff` share. */+export function localVolumeProfile(volume, x, y, z) {+ const offsetX = x - volume.center[0];+ const offsetY = y - volume.center[1];+ const offsetZ = z - volume.center[2];+ const distance = volume.shape === 'sphere'+ ? Math.hypot(offsetX, offsetY, offsetZ) / volume.radius+ : Math.max(Math.abs(offsetX) / (volume.size[0] / 2), Math.abs(offsetY) / (volume.size[1] / 2), Math.abs(offsetZ) / (volume.size[2] / 2));+ if (distance >= 1) return 0;+ if (volume.falloff === 0) return 1;+ const ratio = Math.min(1, Math.max(0, (distance - (1 - volume.falloff)) / volume.falloff));+ return 1 - ratio * ratio * (3 - 2 * ratio);+}++/** Where a ray is inside a volume, as distances along it: writes `[entry, exit]` into `out`, clipped to `[0, limit]`, and returns true; false when it misses. */+export function localVolumeInterval(volume, originX, originY, originZ, directionX, directionY, directionZ, limit, out) {+ let entry = 0;+ let exit = limit;+ if (volume.shape === 'sphere') {+ const offsetX = originX - volume.center[0];+ const offsetY = originY - volume.center[1];+ const offsetZ = originZ - volume.center[2];+ const along = offsetX * directionX + offsetY * directionY + offsetZ * directionZ;+ const discriminant = along * along - (offsetX * offsetX + offsetY * offsetY + offsetZ * offsetZ - volume.radius * volume.radius);+ if (discriminant <= 0) return false;+ const root = Math.sqrt(discriminant);+ entry = Math.max(entry, -along - root);+ exit = Math.min(exit, -along + root);+ } else {+ for (let axis = 0; axis < 3; axis++) {+ const origin = axis === 0 ? originX : axis === 1 ? originY : originZ;+ const direction = axis === 0 ? directionX : axis === 1 ? directionY : directionZ;+ const relative = volume.center[axis] - origin;+ const halfSize = volume.size[axis] / 2;+ if (direction === 0) {+ if (Math.abs(relative) > halfSize) return false;+ continue;+ }+ const first = (relative - halfSize) / direction;+ const second = (relative + halfSize) / direction;+ entry = Math.max(entry, Math.min(first, second));+ exit = Math.min(exit, Math.max(first, second));+ }+ }+ if (!(entry < exit)) return false;+ out[0] = entry;+ out[1] = exit;+ return true;+}diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.jsindex b92faf4e..3cdc55f2 100644--- a/src/path-tracer-scene.js+++ b/src/path-tracer-scene.js@@ -3,6 +3,7 @@ import { createTracer } from './ray-query.js';import { SUN_BIT, POINT_FIRST_BIT, SPOT_FIRST_BIT, AREA_FIRST_BIT } from './light-link-bits.js';import { boxProjectedGeometry, columnLengths } from './export-box-uv.js';import { resolveTraceVolume } from './path-tracer-volume.js';+import { resolveLocalVolumes } from './local-volumes.js';import { resolveTraceSubsurface } from './path-tracer-subsurface.js';import { lightShapeSupport } from './shader-registry.js';import { flushOrderOf } from './depth-layer.js';@@ -315,6 +316,7 @@ export function buildTraceScene(parts, environment = {}) {lights: resolveLights(environment),environment: resolveEnvironment(environment.map),volume: resolveTraceVolume(environment.volumeFog),+ localVolumes: environment.localVolumes?.length ? resolveLocalVolumes(environment.localVolumes, 'environment.localVolumes') : null,surfaceOffset: extent * 1e-5,farDistance: extent * 1e4,});diff --git a/src/path-tracer-volume.js b/src/path-tracer-volume.jsindex 03778dce..5184119c 100644--- a/src/path-tracer-volume.js+++ b/src/path-tracer-volume.js@@ -1,4 +1,5 @@import { resolveVolumeFog } from './volumetric.js';+import { localVolumeInterval, localVolumeProfile } from './local-volumes.js';// Homogeneous fog for the path tracer: a box of uniform scattering medium with the colour, density and anisotropy of the// rasterizer's `environment.volumeFog`. Distances to the next scattering event are drawn from the exact free-flight@@ -61,3 +62,49 @@ export function sampleHenyeyGreensteinCosine(anisotropy, unit) {const ratio = (1 - squared) / (1 - anisotropy + 2 * anisotropy * unit);return Math.max(-1, Math.min(1, (1 + squared - ratio * ratio) / (2 * anisotropy)));}++/**+ * Builds the function that carries a ray through the scene's local volumes (environment.localVolumes). Each volume is marched with+ * its own step count between its entry and exit, nearest entry first: the emitted light is added in proportion to the throughput+ * so far, then the throughput is dimmed by exp(-absorption * profile * step). Emission and absorption do not scatter, so no light+ * sample is taken. The rasterizer's noise is not traced. `jitter` (0 to 1) offsets the samples within a step.+ * The returned function writes the emitted light into `emitted` and scales `throughput` in place.+ */+export function createLocalVolumeCrossing(volumes) {+ const entries = new Float64Array(volumes.length);+ const exits = new Float64Array(volumes.length);+ const order = new Int32Array(volumes.length);+ const span = new Float64Array(2);+ return function crossLocalVolumes(originX, originY, originZ, directionX, directionY, directionZ, length, jitter, throughput, emitted) {+ emitted[0] = 0;+ emitted[1] = 0;+ emitted[2] = 0;+ let count = 0;+ for (let index = 0; index < volumes.length; index++) {+ if (!localVolumeInterval(volumes[index], originX, originY, originZ, directionX, directionY, directionZ, length, span)) continue;+ entries[index] = span[0];+ exits[index] = span[1];+ let slot = count++;+ while (slot > 0 && entries[order[slot - 1]] > span[0]) {+ order[slot] = order[slot - 1];+ slot--;+ }+ order[slot] = index;+ }+ for (let rank = 0; rank < count; rank++) {+ const volume = volumes[order[rank]];+ const entry = entries[order[rank]];+ const stepLength = (exits[order[rank]] - entry) / volume.steps;+ for (let step = 0; step < volume.steps; step++) {+ const distance = entry + (step + jitter) * stepLength;+ const profile = localVolumeProfile(volume, originX + directionX * distance, originY + directionY * distance, originZ + directionZ * distance);+ if (profile <= 0) continue;+ const width = profile * stepLength;+ for (let channel = 0; channel < 3; channel++) {+ emitted[channel] += throughput[channel] * volume.emission[channel] * volume.emissionStrength * width;+ throughput[channel] *= Math.exp(-volume.absorption[channel] * volume.density * width);+ }+ }+ }+ };+}diff --git a/src/path-tracer.js b/src/path-tracer.jsindex c4e60767..73c3d2dd 100644--- a/src/path-tracer.js+++ b/src/path-tracer.js@@ -11,7 +11,7 @@ import {} from './path-tracer-shading.js';import { buildLightTree, chooseLightFromTree, LIGHT_TREE_FIRST_HIT_LIGHTS, resolveLightSelection } from './path-tracer-light-tree.js';import { createRandomWalk, WALK_OUTCOME } from './path-tracer-subsurface.js';-import { henyeyGreensteinPhase, sampleHenyeyGreensteinCosine, volumeInterval } from './path-tracer-volume.js';+import { henyeyGreensteinPhase, sampleHenyeyGreensteinCosine, volumeInterval, createLocalVolumeCrossing } from './path-tracer-volume.js';// Offline still renderer: unidirectional path tracing on the CPU with next-event estimation for every light, the// environment map drawn by importance, and a wavelet denoiser. It reads the same parts, materials, lights and camera@@ -772,6 +772,9 @@ function createPathTracer(scene, options) {return henyeyGreensteinPhase(volume.anisotropy, cosine);}+ const crossLocalVolumes = scene.localVolumes ? createLocalVolumeCrossing(scene.localVolumes) : null;+ const localEmitted = new Float64Array(3);+const walkSubsurface = createRandomWalk(scene, random, intersect);const walkWeight = new Float64Array(3);@@ -829,7 +832,13 @@ function createPathTracer(scene, options) {let afterMirror = true;for (let depth = 0; depth <= options.bounces; depth++) {const found = intersect(scene, positionX, positionY, positionZ, direction[0], direction[1], direction[2], hit);- if (scene.volume && scatterInFog(positionX, positionY, positionZ, found ? hit.distance : scene.farDistance)) {+ const scattersInFog = scene.volume && scatterInFog(positionX, positionY, positionZ, found ? hit.distance : scene.farDistance);+ if (crossLocalVolumes) {+ const segmentLength = scattersInFog ? Math.hypot(hit.point[0] - positionX, hit.point[1] - positionY, hit.point[2] - positionZ) : (found ? hit.distance : scene.farDistance);+ crossLocalVolumes(positionX, positionY, positionZ, direction[0], direction[1], direction[2], segmentLength, random.next(), throughput, localEmitted);+ addRadiance(depth, localEmitted[0], localEmitted[1], localEmitted[2]);+ }+ if (scattersInFog) {previousPdf = scatterInMedium(depth);afterMirror = false;positionX = hit.point[0];@@ -1111,6 +1120,9 @@ export async function renderPathTracedImage({ parts, environment = {}, camera },const { width, height } = options;const view = createCamera(camera, width, height);const scene = buildTraceScene(parts, environment);+ if (scene.localVolumes && options.backend !== 'cpu') {+ throw new RangeError(`environment.localVolumes is traced by the CPU path tracer only; use backend "cpu" or remove the volumes (backend "${options.backend}" was asked for).`);+ }const pixelCount = width * height;const buffers = {color: new Float32Array(pixelCount * 3), albedo: new Float32Array(pixelCount * 3), normal: new Float32Array(pixelCount * 3),diff --git a/src/post.js b/src/post.jsindex 68dcfdcc..3878fc66 100644--- a/src/post.js+++ b/src/post.js@@ -78,6 +78,7 @@ void main() {color *= mix(1.0, visibility / 9.0, occlusionStrength * directShare);}if (POST_BLOOM) color += texture(bloomTexture, textureCoordinate).rgb * bloomStrength;+ if (POST_LOCAL) color = localVolumes(color);if (POST_VOLUME) color = volumeFog(color);if (hdrEnabled > 0.5) {color = clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);@@ -165,6 +166,7 @@ const POST_STEP_CONDITIONS = {field: ['POST_FIELD', 'true'],detail: ['POST_DETAIL', 'true'],lights: ['POST_LIGHTS', 'volumeLightCount > 0'],+ local: ['POST_LOCAL', 'localVolumeCount > 0'],explosion: ['POST_EXPLOSION', 'volumeExplosion > 0.5'],finish: ['POST_FINISH', 'true'],};@@ -172,11 +174,12 @@ const POST_STEP_CONDITIONS = {// The program with every step is the one a frame draws while a variant builds. It leaves out the steps below: the fog sky grid,// field and lights exist only inside a fog, and the volume fog and explosion code load from fog-shader.js and explosion-shader.js// only for a renderer that draws them.-export const POST_STEPS_WITH_OPTIONAL_CODE = Object.freeze(['volume', 'sky', 'field', 'detail', 'lights', 'explosion']);+export const POST_STEPS_WITH_OPTIONAL_CODE = Object.freeze(['volume', 'sky', 'field', 'detail', 'lights', 'local', 'explosion']);export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS).filter(step => !POST_STEPS_WITH_OPTIONAL_CODE.includes(step)));const EXPLOSION_STUB = 'vec3 explosion(vec3 background) { return background; }';const VOLUME_FOG_STUB = 'vec3 volumeFog(vec3 background) { return background; }';+const LOCAL_VOLUMES_STUB = 'vec3 localVolumes(vec3 background) { return background; }';function explosionFunctionFor(enabledSteps) {if (!enabledSteps.has('explosion')) return EXPLOSION_STUB;@@ -186,9 +189,23 @@ function explosionFunctionFor(enabledSteps) {}function fogCodeFor(enabledSteps) {- if (!enabledSteps.has('volume')) return { declarations: '', functions: VOLUME_FOG_STUB };- const code = requireFeatureCode('volumeFog');- return { declarations: code.postDeclarations, functions: code.postFunctions };+ let declarations = '';+ let functions = '';+ if (enabledSteps.has('volume')) {+ const code = requireFeatureCode('volumeFog');+ declarations += code.postDeclarations;+ functions += code.postFunctions;+ } else {+ functions += VOLUME_FOG_STUB;+ }+ if (enabledSteps.has('local')) {+ const code = requireFeatureCode('volumeFog');+ declarations += code.localDeclarations;+ functions += code.localFunctions;+ } else {+ functions += LOCAL_VOLUMES_STUB;+ }+ return { declarations, functions };}/** The post pass with only the listed steps compiled in; every step is switched by its uniform, as before. */diff --git a/src/renderer.js b/src/renderer.jsindex 274a059a..e3a1c89b 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -1850,7 +1850,7 @@ export class Renderer67 {}// The post steps this frame uses. A step that is off costs nothing in a program that has it compiled out.- postStepsOf(frame, effects, volume, occluded, fogSky) {+ postStepsOf(frame, effects, volume, occluded, fogSky, localVolumes) {const steps = [];if (this.transparent) steps.push('transparent');if (occluded) steps.push('occlusion');@@ -1859,6 +1859,7 @@ export class Renderer67 {if (volume.density > 0 && volume.field) steps.push('field');if (volume.density > 0 && requireFeatureCode('volumeFog').support.usesDetail(volume)) steps.push('detail');if (volume.density > 0 && this.fogLightBuffers?.count > 0) steps.push('lights');+ if (localVolumes) steps.push('local');if (fogSky) steps.push('sky');if (frame.volumeExplosion) steps.push('explosion');const gradesColor = effects.saturation !== 1 || effects.contrast !== 1 || effects.temperature !== 0;@@ -1917,9 +1918,10 @@ export class Renderer67 {context.bindVertexArray(null);const fogSky = this.fogSkyVisibility?.(this.sceneParts, volume, context, environment);const fogSupport = volume.density > 0 ? requireFeatureCode('volumeFog').support : null;+ const localVolumes = environment.localVolumes?.length ? environment.localVolumes : null;if (fogSupport) fogSupport.packLights(this);else if (this.fogLightBuffers) this.fogLightBuffers.count = 0;- const post = this.selectPostProgram(this.postStepsOf(frame, effects, volume, occluded, fogSky));+ const post = this.selectPostProgram(this.postStepsOf(frame, effects, volume, occluded, fogSky, localVolumes));context.useProgram(post.program);if (this.look) viewTransformShader.bindLook(this, post.program);context.activeTexture(context.TEXTURE0);@@ -1938,6 +1940,7 @@ export class Renderer67 {context.bindTexture(context.TEXTURE_2D, this.depthTexture ?? this.whiteTexture);context.uniform1i(post.uniforms.sceneDepth, 1);fogSupport?.bindUniforms(this, post, volume, environment, frame);+ if (localVolumes) requireFeatureCode('volumeFog').support.bindLocalVolumes(this, post, localVolumes, frame);context.activeTexture(context.TEXTURE2);context.bindTexture(context.TEXTURE_2D, effects.bloom.strength > 0 ? this.bloomTargets[1].texture : this.whiteTexture);context.uniform1i(post.uniforms.bloomTexture, 2);@@ -2279,6 +2282,10 @@ export class Renderer67 {const lightLength = direction?.length === 3 ? Math.hypot(...direction) : NaN;if (!Number.isFinite(lightLength) || lightLength < 1e-6 || !Array.from(direction).every(component => typeof component === 'number' && Math.abs(component) <= 1e6)) throw new RangeError('Volume light direction must have a finite nonzero length and bounded components');}+ if (environment.localVolumes?.length) {+ requireFeatureCode('volumeFog');+ if (!this.depth || !this.hdr || this.transparent || this.benchmark) throw new Error('Local volumes require depth:true, active HDR and an opaque canvas');+ }updateLightingState(this.lighting, environment, { world: this.world });this.syncViewTransform(environment);// The shadow view follows the sun, so a moved sun redraws the map.diff --git a/tests/local-volumes.test.js b/tests/local-volumes.test.jsnew file mode 100644index 00000000..6b1e83bc--- /dev/null+++ b/tests/local-volumes.test.js@@ -0,0 +1,195 @@+// Local volumes (issue 710): boxes and spheres that absorb and emit light, beside the one scattering volumeFog.+// The first tests check the fields and the packing in Node. The last draws in headless Chrome (SwiftShader, no GPU) from the+// Vite dev server and skips when Chrome cannot start.+import test from 'node:test';+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { freePort } from './helpers/free-port.js';+import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes, localVolumeProfile, MAX_LOCAL_VOLUMES } from '../src/local-volumes.js';+import { renderPathTracedImage } from '../src/path-tracer.js';+import { createPostFragment, POST_STEPS } from '../src/post.js';+import { normalizeAgentLook } from '../src/agent-look.js';+import { agentSceneModulesNeeded } from '../src/agent-scene-modules.js';++test('a volume resolves with its defaults and rejects what it cannot draw, naming the field', () => {+ const [sphere, box] = resolveLocalVolumes([{ shape: 'sphere', center: [0, 1, 0], radius: 2 }, { center: [1, 2, 3], size: [1, 2, 3], density: 4, emission: [1, 0.5, 0], emissionStrength: 3 }]);+ assert.equal(sphere.density, 1);+ assert.equal(sphere.falloff, 0.5);+ assert.deepEqual(sphere.absorption, [1, 1, 1]);+ assert.equal(box.shape, 'box');+ assert.equal(box.steps, 16);+ assert.throws(() => resolveLocalVolumes('smoke'), /localVolumes must be an array/);+ assert.throws(() => resolveLocalVolumes(new Array(MAX_LOCAL_VOLUMES + 1).fill({ center: [0, 0, 0], size: [1, 1, 1] })), /at most 8 volumes/);+ assert.throws(() => resolveLocalVolumes([{ center: [0, 0, 0] }]), /localVolumes\[0\]\.size must be an array of three numbers/);+ assert.throws(() => resolveLocalVolumes([{ shape: 'sphere', center: [0, 0, 0] }]), /localVolumes\[0\]\.radius/);+ assert.throws(() => resolveLocalVolumes([{ shape: 'sphere', center: [0, 0, 0], radius: 1, size: [1, 1, 1] }]), /size belongs to a box/);+ assert.throws(() => resolveLocalVolumes([{ shape: 'cone', center: [0, 0, 0] }]), /shape must be one of box, sphere/);+ assert.throws(() => resolveLocalVolumes([{ center: [0, 0, 0], size: [1, 1, 1], density: -1 }]), /density must be between 0 and 100/);+ assert.throws(() => resolveLocalVolumes([{ center: [0, 0, 0], size: [1, 1, 1], steps: 8.5 }]), /steps must be an integer/);+ assert.throws(() => resolveLocalVolumes([{ center: [0, 0, 0], size: [1, 1, 1], glow: 1 }]), /no field "glow"/);+});++test('packing scales absorption by density and emission by strength, and the profile fades over the falloff share', () => {+ const volumes = resolveLocalVolumes([{ shape: 'sphere', center: [1, 2, 3], radius: 2, density: 3, absorption: [1, 0.5, 0], emission: [1, 0, 0], emissionStrength: 4, falloff: 0.5, noiseAmount: 0.25, noiseScale: 2, steps: 10 }]);+ const buffers = packLocalVolumes(volumes, createLocalVolumeBuffers());+ assert.equal(buffers.count, 1);+ assert.deepEqual(Array.from(buffers.centers.slice(0, 4)), [1, 2, 3, 1]);+ assert.deepEqual(Array.from(buffers.extents.slice(0, 4)), [2, 2, 2, 0.5]);+ assert.deepEqual(Array.from(buffers.absorption.slice(0, 4)), [3, 1.5, 0, 0.25]);+ assert.deepEqual(Array.from(buffers.emission.slice(0, 4)), [4, 0, 0, 2]);+ assert.equal(buffers.steps[0], 10);+ const [volume] = volumes;+ assert.equal(localVolumeProfile(volume, 1, 2, 3), 1);+ assert.equal(localVolumeProfile(volume, 3, 2, 3), 0);+ assert.equal(localVolumeProfile(volume, 1 + 1.5, 2, 3), 0.5);+ assert.equal(localVolumeProfile({ ...volume, falloff: 0 }, 1 + 1.99, 2, 3), 1);+});++test('the post program carries the local step only when asked, and a recipe names the volumes through its look', async () => {+ assert.equal(POST_STEPS.includes('local'), false);+ assert.match(createPostFragment(), /#define POST_LOCAL false/);+ assert.match(createPostFragment(), /vec3 localVolumes\(vec3 background\) \{ return background; \}/);+ assert.doesNotMatch(createPostFragment(), /localVolumeCount/);+ await import('../src/fog-shader.js');+ const source = createPostFragment([...POST_STEPS, 'local']);+ assert.match(source, /#define POST_LOCAL \(localVolumeCount > 0\)/);+ assert.match(source, /uniform vec4 localVolumeCenters\[8\]/);+ const environment = { localVolumes: [{ center: [0, 1, 0], radius: 1, shape: 'sphere' }] };+ assert.equal(normalizeAgentLook({ environment }).environment.localVolumes[0].steps, 16);+ assert.equal('localVolumes' in normalizeAgentLook({}).environment, false);+ assert.throws(() => normalizeAgentLook({ environment: { localVolumes: [{ center: [0, 0, 0], size: [1, 1, -1] }] } }), /environment\.localVolumes\[0\]\.size/);+ assert.ok(agentSceneModulesNeeded({ environment }).includes('fogShader'));+});++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;+}++// A grey wall at z = 0 seen from z = 5; each scenario adds local volumes between the camera and the wall (or behind it).+async function drawScenarios(page, scenarios) {+ const task = async (list) => {+ const { box } = await import('/src/geometry.js');+ const { Renderer67 } = await import('/src/renderer.js');+ await import('/src/fog-shader.js');+ const canvas = document.createElement('canvas');+ canvas.width = 64;+ canvas.height = 64;+ document.body.append(canvas);+ const copy = document.createElement('canvas');+ copy.width = 64;+ copy.height = 64;+ const copyContext = copy.getContext('2d', { willReadFrequently: true });+ const wall = { geometry: box(0, 1), matrix: new Float32Array([12, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0.2, 0, 0, 0, -0.1, 1]), material: { tag: 'unlit', color: [0.4, 0.4, 0.4], metallic: 0, roughness: 1, emission: 0 } };+ const results = [];+ for (const localVolumes of list) {+ const renderer = new Renderer67(canvas, [wall], { hdr: true, depth: true, samples: 1, pixelRatio: 1, ground: false });+ const environment = { keyIntensity: 0, fillIntensity: 0, ambientIntensity: 0 };+ if (localVolumes) environment.localVolumes = localVolumes;+ renderer.render({ eye: [0, 0, 5], target: [0, 0, 0], fov: 40, time: 0, environment });+ copyContext.drawImage(canvas, 0, 0, 64, 64);+ const center = Array.from(copyContext.getImageData(32, 32, 1, 1).data);+ const corner = Array.from(copyContext.getImageData(2, 2, 1, 1).data);+ results.push({ center, corner, glError: renderer.context.getError() });+ renderer.dispose?.();+ }+ return results;+ };+ return page.evaluate(task, scenarios);+}++test('absorption darkens, emission glows, and a scene without volumes draws the same', 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 {+ browser = await chromium.launch({ headless: true, args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'] });+ } catch (error) {+ context.skip(`Chrome did not start: ${error.message.split('\n')[0]}`);+ return;+ }+ const page = await browser.newPage({ viewport: { width: 64, height: 64 } });+ await page.goto(`http://127.0.0.1:${port}/`);+ const sphere = { shape: 'sphere', center: [0, 0, 1.5], radius: 1, falloff: 0.3, steps: 24 };+ const [plain, empty, smoke, glow, tinted, behindWall] = await drawScenarios(page, [+ undefined,+ [],+ [{ ...sphere, density: 1.5 }],+ [{ ...sphere, density: 0, emission: [1, 0.4, 0.1], emissionStrength: 1.5 }],+ [{ ...sphere, density: 1.5, absorption: [0.1, 0.6, 1] }],+ [{ shape: 'sphere', center: [0, 0, -3], radius: 1.5, density: 5, emission: [1, 1, 1], emissionStrength: 5 }],+ ]);+ for (const result of [plain, empty, smoke, glow, tinted, behindWall]) assert.equal(result.glError, 0);+ assert.deepEqual(empty, plain, 'an empty list changes nothing');+ assert.deepEqual(behindWall, plain, 'a volume behind the wall is hidden by it');+ assert.ok(smoke.center[0] < plain.center[0] - 20, 'absorption darkens the wall behind the volume');+ assert.deepEqual(smoke.corner, plain.corner, 'pixels outside the volume are untouched');+ assert.ok(glow.center[0] > plain.center[0] + 20, 'emission with no density still glows');+ assert.ok(glow.center[0] > glow.center[2] + 20, 'the emission colour tints the glow');+ assert.ok(tinted.center[0] > tinted.center[2] + 10, 'a channel with a larger absorption is dimmed more: blue goes first and leaves a red cast');+ } finally {+ await browser?.close();+ server.kill();+ }+});++const LOOKING_DOWN = { eye: [0, 3, 0], target: [0, 0, 0], up: [0, 0, -1], fov: 40 };+const IMAGE = { width: 16, height: 16, denoise: false, threads: 1, bounces: 1, samples: 1 };+const CENTER_PIXEL = (8 * 16 + 8) * 3;++function ground(emission) {+ 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]),+ };+ return [{ name: 'ground', geometry, material: { tag: 'surface', metallic: 0, roughness: 1, color: [0, 0, 0], ior: 1, emission, emissiveColor: [1, 1, 1] } }];+}++async function centerRadiance(parts, environment) {+ const { linear } = await renderPathTracedImage({ parts, environment, camera: LOOKING_DOWN }, IMAGE);+ return Array.from(linear.slice(CENTER_PIXEL, CENTER_PIXEL + 3));+}++test('the path tracer attenuates by exp(-density * thickness) and adds emission times thickness', async () => {+ const slab = { shape: 'box', center: [0, 1.5, 0], size: [20, 1, 20], falloff: 0, steps: 8 };+ const [clear] = await centerRadiance(ground(1), {});+ const [dimmed] = await centerRadiance(ground(1), { localVolumes: [{ ...slab, density: 1 }] });+ assert.equal(clear, 1);+ assert.ok(Math.abs(dimmed - Math.exp(-1)) < 2e-3, `transmitted ${dimmed}`);+ const [glowRed, glowGreen] = await centerRadiance(ground(0), { localVolumes: [{ ...slab, density: 0, emission: [0.5, 0.25, 0], emissionStrength: 2 }] });+ assert.ok(Math.abs(glowRed - 1) < 2e-3, `red ${glowRed}`);+ assert.ok(Math.abs(glowGreen - 0.5) < 2e-3, `green ${glowGreen}`);+ const [nothing] = await centerRadiance(ground(1), { localVolumes: [] });+ assert.equal(nothing, clear);+});++test('the path tracer refuses local volumes on a GPU backend instead of dropping them', async () => {+ await assert.rejects(+ renderPathTracedImage({ parts: ground(1), environment: { localVolumes: [{ shape: 'sphere', center: [0, 1, 0], radius: 1 }] }, camera: LOOKING_DOWN }, { ...IMAGE, backend: 'gpu' }),+ /localVolumes is traced by the CPU path tracer only/,+ );+});