Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Start local volume marches from interleaved gradient noise, not a sine hash (#855)

Nguyen Xuan Anfa8e5d82a83d
diff --git a/changes/855-lit-local-volumes.md b/changes/855-lit-local-volumes.md
index 09972f23..55e34540 100644
--- a/changes/855-lit-local-volumes.md
+++ b/changes/855-lit-local-volumes.md
@@ -1 +1,2 @@
- `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)
diff --git a/docs/volumetric.md b/docs/volumetric.md
index 9742f3c4..542c2185 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 |
+| `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 |
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 jitters each pixel's steps with a hash 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) 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.js
index f4aed107..113dd4e8 100644
--- a/src/fog-shader.js
+++ b/src/fog-shader.js
@@ -150,6 +150,11 @@ uniform highp sampler2D localMeshVolumes;
// 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 = `
+// Interleaved gradient noise (Jimenez 2014): the start offsets of neighbouring pixels stay far apart, so the march error is a fine, even dither
+// and not the clumps a white-noise hash leaves, which read as grain at 8 to 16 steps.
+float localVolumeJitter() {
+ return fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
+}
// Value noise on a hash of plain multiplies, adds and fract, which rounds the same way on SwiftShader, where it was measured, and is unchecked on hardware GPUs (a sine hash does not: its error
// grows with the argument). local-volume-noise.js repeats it for the CPU path tracer, so keep the two in step.
float localVolumeCellHash(vec3 cell) {
@@ -311,7 +316,7 @@ vec3 localVolumes(vec3 background) {
}
int steps = int(localVolumeSteps[nearest].x);
float stepSize = (exitDistance - entry) / float(steps);
- float jitter = hash(vec3(gl_FragCoord.xy, float(nearest) + 1.0));
+ float jitter = fract(localVolumeJitter() + float(nearest) * 0.618034);
float scatterAlbedo = localVolumeSteps[nearest].z;
for (int step = 0; step < 32; step++) {
if (step >= steps) break;
diff --git a/tests/local-volume-jitter.test.js b/tests/local-volume-jitter.test.js
new file mode 100644
index 00000000..3f0652a3
--- /dev/null
+++ b/tests/local-volume-jitter.test.js
@@ -0,0 +1,42 @@
+// The start offset of a local volume's march (issue 855, owner report: smoke looks pixelated). A white-noise offset leaves clumps of
+// error that read as grain at low step counts; interleaved gradient noise keeps neighbouring offsets apart. The shader repeats the
+// formula below, so the test checks the shader source uses it and that the formula is the evenly spread one.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+
+const fract = value => value - Math.floor(value);
+const interleavedGradientNoise = (x, y) => fract(52.9829189 * fract(x * 0.06711056 + y * 0.00583715));
+const whiteHash = (x, y) => fract(Math.sin(x * 127.1 + y * 311.7 + 74.7) * 43758.5453);
+
+function blockMeanSpread(offsetAt, blockSize) {
+ const size = 64;
+ const means = [];
+ for (let blockY = 0; blockY < size; blockY += blockSize) {
+ for (let blockX = 0; blockX < size; blockX += blockSize) {
+ let total = 0;
+ for (let y = blockY; y < blockY + blockSize; y++) for (let x = blockX; x < blockX + blockSize; x++) total += offsetAt(x + 0.5, y + 0.5);
+ means.push(total / (blockSize * blockSize));
+ }
+ }
+ const average = means.reduce((sum, value) => sum + value, 0) / means.length;
+ return Math.sqrt(means.reduce((sum, value) => sum + (value - average) ** 2, 0) / means.length);
+}
+
+test('interleaved gradient noise covers 0 to 1 evenly and clumps less than white noise in 4 by 4 blocks', () => {
+ const values = [];
+ for (let y = 0; y < 64; y++) for (let x = 0; x < 64; x++) values.push(interleavedGradientNoise(x + 0.5, y + 0.5));
+ assert.ok(values.every(value => value >= 0 && value < 1));
+ const mean = values.reduce((sum, value) => sum + value, 0) / values.length;
+ assert.ok(Math.abs(mean - 0.5) < 0.02, `mean ${mean}`);
+ const gradientSpread = blockMeanSpread(interleavedGradientNoise, 4);
+ const whiteSpread = blockMeanSpread(whiteHash, 4);
+ assert.ok(gradientSpread < 0.5 * whiteSpread, `block spread ${gradientSpread} against white ${whiteSpread}`);
+});
+
+test('the local volume march starts from the interleaved gradient offset, not the sine hash', () => {
+ const source = readFileSync(new URL('../src/fog-shader.js', import.meta.url), 'utf8');
+ assert.match(source, /float localVolumeJitter\(\)[\s\S]*?52\.9829189[\s\S]*?0\.06711056, 0\.00583715/);
+ assert.match(source, /float jitter = fract\(localVolumeJitter\(\) \+ float\(nearest\) \* 0\.618034\);/);
+ assert.doesNotMatch(source, /hash\(vec3\(gl_FragCoord\.xy, float\(nearest\)/);
+});