3D engine that AI agents drive
Raise a noisy local volume's march to two samples per noise cell (#855)
Nguyen Xuan Anb30509078a54
diff --git a/changes/855-lit-local-volumes.md b/changes/855-lit-local-volumes.mdindex 55e34540..d5207745 100644--- a/changes/855-lit-local-volumes.md+++ b/changes/855-lit-local-volumes.md@@ -1,2 +1,3 @@- `environment.localVolumes[].scatter` (0 to 1, default 0 draws as before) lights a local volume with the key light (shadow map, phase function and the volume's own depth toward the sun) and the sky, in the rasterizer and the CPU path tracer (#855)- A local volume's march starts from interleaved gradient noise instead of a sine hash, so low step counts no longer leave clumped grain in smoke (#855)+- A noisy local volume is marched with at least two samples per noise cell along the ray (up to 32), so a low `steps` no longer leaves a pixel-pitch dither in smoke (#855)diff --git a/docs/volumetric.md b/docs/volumetric.mdindex 542c2185..b73056f4 100644--- a/docs/volumetric.md+++ b/docs/volumetric.md@@ -127,7 +127,7 @@ In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is th| `falloff` | `0.5` | `0` to `1`. The outer share of the volume over which the density fades to zero (`0` is a hard edge) || `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; below about 12 a fine pixel-pitch dither shows in dense smoke (8 steps measured), the default 16 is clean |+| `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.@@ -163,4 +163,4 @@ A volume with `scatter` above `0` returns, in each step, `scatter * (1 - exp(-ex### Not covered yet-The noise is `localVolumeNoise` in `src/fog-shader.js` and `src/local-volume-noise.js`: trilinear value noise on a hash made of multiplies, adds and `fract` only, which rounded the same way on SwiftShader, where it was measured; it is unchecked on hardware GPUs. The fog's `cloudNoise` hashes with `sin`, whose error grows with its argument: on SwiftShader its lattice values differed from a 32-bit JavaScript port by up to 0.3, so the two renderers drew different clouds. The JavaScript port rounds every step to 32 bits. `tests/local-volume-noise.test.js` draws a noisy box (`density` 1.2, `falloff` 0.3, `noiseAmount` 0.9, `noiseScale` 3) in both renderers and compares the light let through in 8 by 8 regions: on SwiftShader the worst region differed by 0.003 and the mean of the whole frame by 0.0008, and the test allows 0.01 and 0.005. The rasterizer starts each pixel's march at an interleaved gradient noise offset (`localVolumeJitter`; a sine hash left clumps of error that read as grain at 8 steps, measured: mid-frequency energy 1.06 with the hash against 0.42 with the gradient noise, 0.41 with no jitter at all, and no grain left at 16 steps or more) and the tracer with its sampler, so single pixels differ by a few percent. Volumes with `noiseAmount` drew with the fog's sine noise before this change, so their pattern moved; the mean density is unchanged. Lighting baked surfaces from a volume's emission is not planned (#809): the bake reports the limit instead.+The noise is `localVolumeNoise` in `src/fog-shader.js` and `src/local-volume-noise.js`: trilinear value noise on a hash made of multiplies, adds and `fract` only, which rounded the same way on SwiftShader, where it was measured; it is unchecked on hardware GPUs. The fog's `cloudNoise` hashes with `sin`, whose error grows with its argument: on SwiftShader its lattice values differed from a 32-bit JavaScript port by up to 0.3, so the two renderers drew different clouds. The JavaScript port rounds every step to 32 bits. `tests/local-volume-noise.test.js` draws a noisy box (`density` 1.2, `falloff` 0.3, `noiseAmount` 0.9, `noiseScale` 3) in both renderers and compares the light let through in 8 by 8 regions: on SwiftShader the worst region differed by 0.003 and the mean of the whole frame by 0.0008, and the test allows 0.01 and 0.005. The rasterizer starts each pixel's march at an interleaved gradient noise offset (`localVolumeJitter`; a sine hash left clumps of error that read as grain at 8 steps, measured: mid-frequency energy 1.06 with the hash against 0.42 with the gradient noise, 0.41 with no jitter at all, and no grain left at 16 steps or more; the dither that remained at 8 steps went away by raising the count to two samples per noise cell: high-pass grain in the core 3.47 to 1.47 against 1.40 in the clear frame, mid-band 0.418 to 0.404 against 0.352, at 1.4 to 2.4 ms per 960 x 540 frame on a shared GPU against 1.6 before) and the tracer with its sampler, so single pixels differ by a few percent. Volumes with `noiseAmount` drew with the fog's sine noise before this change, so their pattern moved; the mean density is unchanged. Lighting baked surfaces from a volume's emission is not planned (#809): the bake reports the limit instead.diff --git a/src/fog-shader.js b/src/fog-shader.jsindex 113dd4e8..79605106 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_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_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';@@ -315,6 +315,8 @@ vec3 localVolumes(vec3 background) {continue;}int steps = int(localVolumeSteps[nearest].x);+ float noiseAmount = localVolumeAbsorption[nearest].w;+ if (noiseAmount > 0.0) steps = min(${LOCAL_VOLUME_MAXIMUM_STEPS}, max(steps, int(ceil((exitDistance - entry) * localVolumeEmission[nearest].w * ${LOCAL_VOLUME_STEPS_PER_NOISE_CELL.toFixed(1)}))));float stepSize = (exitDistance - entry) / float(steps);float jitter = fract(localVolumeJitter() + float(nearest) * 0.618034);float scatterAlbedo = localVolumeSteps[nearest].z;diff --git a/src/local-volumes.js b/src/local-volumes.jsindex 51d17c5d..123105b2 100644--- a/src/local-volumes.js+++ b/src/local-volumes.js@@ -121,6 +121,19 @@ 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;+/** 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;++/**+ * The samples a ray takes through a noisy volume: the volume's `steps`, raised so that each noise cell along `length` gets+ * LOCAL_VOLUME_STEPS_PER_NOISE_CELL of them, up to LOCAL_VOLUME_MAXIMUM_STEPS. Without noise it is `steps`. The post shader repeats the rule.+ */+export function localVolumeStepCount(volume, length) {+ if (!(volume.noiseAmount > 0)) return volume.steps;+ const cellSteps = Math.ceil(length * volume.noiseScale * LOCAL_VOLUME_STEPS_PER_NOISE_CELL);+ return Math.min(LOCAL_VOLUME_MAXIMUM_STEPS, Math.max(volume.steps, cellSteps));+}+/*** How much of the sun's elevation the depth toward the sun keeps (1 is the true direction). A low sun lights a smoke box through its top face as* quickly as through its side, so with the true direction the top edge glows as bright as the sunward edge and the gradient across the form is lost;diff --git a/src/path-tracer-volume.js b/src/path-tracer-volume.jsindex dc05c69c..3a734c36 100644--- a/src/path-tracer-volume.js+++ b/src/path-tracer-volume.js@@ -1,5 +1,5 @@import { resolveVolumeFog } from './volumetric.js';-import { localVolumeInterval, localVolumeProfile, 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 { localVolumeInterval, localVolumeProfile, localVolumeStepCount, 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 { countOpenEdges } from './local-volume-parts.js';import { buildTriangleBvh } from './triangle-bvh.js';import { createTracer } from './ray-query.js';@@ -269,8 +269,9 @@ export function createLocalVolumeCrossing(volumes, lighting = null) {continue;}const entry = entries[order[rank]];- const stepLength = (exits[order[rank]] - entry) / volume.steps;- for (let step = 0; step < volume.steps; step++) {+ const stepCount = localVolumeStepCount(volume, exits[order[rank]] - entry);+ const stepLength = (exits[order[rank]] - entry) / stepCount;+ for (let step = 0; step < stepCount; step++) {const distance = entry + (step + jitter) * stepLength;const profile = localVolumeProfile(volume, originX + directionX * distance, originY + directionY * distance, originZ + directionZ * distance);if (profile <= 0) continue;diff --git a/tests/local-volume-step-count.test.js b/tests/local-volume-step-count.test.jsnew file mode 100644index 00000000..8e6a38c3--- /dev/null+++ b/tests/local-volume-step-count.test.js@@ -0,0 +1,32 @@+// A noisy local volume takes at least two samples per noise cell along the ray (issue 855, owner report: smoke looks pixelated).+// Fewer steps jump whole cells and the start-offset dither shows as pixel-pitch grain; the rasterizer and the CPU tracer share the rule.+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { localVolumeStepCount, resolveLocalVolumes, LOCAL_VOLUME_MAXIMUM_STEPS, LOCAL_VOLUME_STEPS_PER_NOISE_CELL } from '../src/local-volumes.js';++const resolve = fields => resolveLocalVolumes([{ shape: 'box', center: [0, 0, 0], size: [2, 2, 2], ...fields }])[0];++test('a volume without noise keeps its own step count', () => {+ const volume = resolve({ steps: 8, noiseAmount: 0, noiseScale: 20 });+ assert.equal(localVolumeStepCount(volume, 5), 8);+});++test('a noisy volume gets two steps per noise cell along the ray, never fewer than its steps', () => {+ const volume = resolve({ steps: 8, noiseAmount: 0.5, noiseScale: 2.2 });+ assert.equal(LOCAL_VOLUME_STEPS_PER_NOISE_CELL, 2);+ assert.equal(localVolumeStepCount(volume, 3.2), Math.ceil(3.2 * 2.2 * 2));+ assert.equal(localVolumeStepCount(volume, 0.5), 8, 'a short ray keeps the requested steps');+});++test('the raised count stops at the maximum', () => {+ const volume = resolve({ steps: 16, noiseAmount: 1, noiseScale: 100 });+ assert.equal(localVolumeStepCount(volume, 10), LOCAL_VOLUME_MAXIMUM_STEPS);+});++test('the post shader and the path tracer use the same rule', () => {+ const shader = readFileSync(new URL('../src/fog-shader.js', import.meta.url), 'utf8');+ assert.match(shader, /if \(noiseAmount > 0\.0\) steps = min\(\$\{LOCAL_VOLUME_MAXIMUM_STEPS\}, max\(steps, int\(ceil\(\(exitDistance - entry\) \* localVolumeEmission\[nearest\]\.w \* \$\{LOCAL_VOLUME_STEPS_PER_NOISE_CELL\.toFixed\(1\)\}\)\)\)\);/);+ const tracer = readFileSync(new URL('../src/path-tracer-volume.js', import.meta.url), 'utf8');+ assert.match(tracer, /const stepCount = localVolumeStepCount\(volume, exits\[order\[rank\]\] - entry\);/);+});