Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Path tracer: stop converged pixels, box-projected maps, 1080p still (part of #129)

Nguyen Xuan An09ea7771612b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2fb1a082..35074dd7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Let the path tracer stop converged pixels, draw normal and roughness maps on box-projected materials, and finish a 1080p still (part of issue #129, which stays open). `noiseThreshold` (0 to 1, default 0.03, 0 draws every sample) stops a pixel once the standard error of its mean luminance is under that share of the mean plus 0.05, checked from 16 samples on and after every 8 more; the decision reads only the pixel's own samples, so bands and thread counts still give the same bytes, and `report.averageSamples` says what was used. Shadow rays no longer interpolate the surface they hit unless it is a cutout (pixels unchanged, 1.23 to 1.36 times faster per thread on the demo room). Box-projected parts are traced with the UVs of their projection (`boxProjectedGeometry`, with `columnLengths` now exported from `src/export-box-uv.js`), so their colour, normal and metallic-roughness maps are all read (before, a box-projected colour map read one texel); `report.ignored` no longer lists them. Render jobs may set `maxSeconds` up to 600 (was 240; the deadline is `maxSeconds` plus 60 s): the 1920 by 1080, 64 sample still of `tests/fixtures/demo-room.recipe.json` took 246.4 s in the tracer (30.7 samples per pixel on average, 8 threads, 257 s per job), 6 s past the old limit. Measured, and not all good: at 24 fixed samples with the filter `brick-graph` is 0.0024 and `character` 0.0048 worse than at 64; adaptive sampling costs `spot-area` 0.0658 to 0.0900 against Cycles at the default threshold; drawing one light at the first hit was tried and dropped (twice as fast, 66 percent more error). `brick-graph` did not improve against the same tracer at 64 samples (0.1370 to 0.1373); the darker floor of `character` and `outdoor-hdri` was narrowed but not found. `bench/reference/run.mjs` takes `--noise-threshold` and records `averageSamples`. Core did not change.
+
- Read the textures inside glTF layer extensions and accept TEXCOORD_1 (part of issue #51). `clearcoatTexture`, `clearcoatRoughnessTexture`, `clearcoatNormalTexture`, `anisotropyTexture`, `sheenColorTexture` and `sheenRoughnessTexture` load into `material.layerMaps` and draw through shader features in `material-layer-shaders`, and `exportGlb` writes them back. Occlusion, emissive and metallic-roughness textures may read TEXCOORD_1. Against Cycles, `AnisotropyBarnLamp` goes from 0.4758 to 0.3584, `AnisotropyDiscTest` from 0.3481 to 0.2808 and `ClearCoatTest` from 0.2344 to 0.2306; `TransmissionTest` is unchanged and `SheenChair` still waits on per-map texture transforms. The core entry grows by about 345 bytes gzip.
- Score material scenes and Khronos sample assets against their baseline (parts of issues #50 and #51). `brick-flat` is the control for `brick-graph`: the same wall in the graph's average colour with no maps. `npm run reference -- --khronos` draws Khronos sample assets downloaded into gitignored `artifacts/khronos/` and scores them against Cycles reading the same GLB, on the pixels the asset covers (`khronos.json`, `images/khronos-*.jpg`; `baseline.json` is unchanged). The brick bump is not weaker than Blender's: its bright edge is stronger and bump 0 would score better (0.2065 against 0.2269), so no engine change. The assets found two importer faults, fixed in `src/gltf.js`: `KHR_xmp` and `KHR_xmp_json_ld` metadata refused the whole file, and `KHR_materials_variants` is now accepted with a warning. Still open: texture slots in layer extensions (the anisotropy textures matter, both anisotropy assets score worse with the factor than with none) and occlusion on TEXCOORD_1 (`SheenChair`).
- Let recipes reach cascaded sun shadows and light linking (part of issue #52; the lit-interior score goal is still open). `environment.shadowCascades` (0 to 4) and `affects` on point, spot and area lights plus `environment.keyAffects` name nodes; both addons load on demand through `src/agent-scene-modules.js`, `scene_capabilities` now reports `lightLinking` and `shadowCascades`, unknown node IDs are refused with the next action, and `set-environment` and `scene_export_recipe` carry the fields. The light bake honours `affects` (a linked light adds nothing at a part it skips, even as a bounce) and the path tracer lists linking in `report.ignored`. Default: a scene without `shadowCascades` whose `shadow.extent` is above 40 gets three cascades (the single map is then 4 cm per texel or coarser; `long-street` scores 0.1555 with one map and 0.1398 with three, for about 0.2 ms on an RTX 3060); every scene at or below 40 draws as before, and `shadowCascades: 0` keeps one map. `node scripts/smoke-mcp-linking.mjs` proves one recipe with both through the MCP server, with a seek giving identical PNG bytes. The MCP schema total stays at its budget by shortening environment descriptions.
diff --git a/bench/reference/README.md b/bench/reference/README.md
index 4f6fe81e..055edffa 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -96,3 +96,26 @@ Path tracer (issue #57): `npm run reference -- --path-tracer [--samples 32]` dra
| `spot-area` | 0.1242 | 0.0639 | 71.6 | |
The mean against Cycles is 0.171 for the path tracer and 0.189 for the rasterizer (the light bake gets `lit-interior` to 0.1444, better than the tracer's 0.1993). The tracer is worse on `outdoor-hdri` and `character`: in the images the floor is darker than in Cycles (the cause is not found), and `fog` shows the missing volume. The denoiser blurs some soft shadows. Cycles used 256 samples. See `docs/path-tracer.md` for what the tracer draws and skips.
+
+Path tracer, second pass (issue #129, measured 2026-11-01, 64 samples at most, `noiseThreshold` 0.03, four threads, 960 by 540; seconds are wall time and include scene setup). Scores against Cycles, all 17 scenes in `path-tracer.json`:
+
+| Scene | Score | Seconds | | Scene | Score | Seconds |
+| --- | --- | --- | --- | --- | --- | --- |
+| `brick-flat` | 0.1117 | 24.2 | | `lit-interior` | 0.2214 | 106.7 |
+| `brick-graph` | 0.1373 | 26.8 | | `long-street` | 0.1838 | 50.2 |
+| `brick-room` | 0.2743 | 125.9 | | `material-spheres` | 0.1187 | 52.3 |
+| `brushed-film` | 0.1462 | 47.2 | | `metal` | 0.1435 | 43.5 |
+| `car-paint` | 0.1337 | 46.5 | | `outdoor-hdri` | 0.1016 | 24.8 |
+| `character` | 0.1120 | 35.1 | | `spot-area` | 0.0900 | 21.3 |
+| `fog` | 0.5628 | 26.4 | | `light-linking` | 0.6191 | 33.9 |
+| `foliage` | 0.1577 | 69.5 | | `glass` | 0.1220 | 41.2 |
+
+The mean over the 11 scenes of the first table is 0.1728 (0.171 at 32 samples before). `light-linking` scores 0.6191 because the tracer does not trace light linking (every light lights every part).
+
+Before and after on four scenes, 64 samples: every sample drawn without the box-projection and shadow-ray changes (the state of `main`), then the defaults of this change. `brick-graph` 0.1370 then 0.1373, `brick-room` 0.2794 then 0.2743 (seconds 121.2 then 126.7, the box-projected walls now read their projected UVs), `character` 0.1116 then 0.1120, `outdoor-hdri` 0.1014 then 0.1016. `brick-graph` is a UV-mapped wall, so it already drew its bump and nothing in this change touches it: against the 0.1538 of the table above (32 samples) it improved, against the same tracer at 64 samples it did not move (0.0003 worse, inside the noise). `brick-room` is the scene with box-projected materials; its normal and roughness maps used to be ignored.
+
+Adaptive sampling is not free in quality. On `spot-area` the score is 0.0658 with every sample drawn (37.1 s), 0.0748 at `noiseThreshold` 0.008 (31.3 s), 0.0847 at 0.015 (25.1 s) and 0.0900 at 0.03 (21.3 s). `lit-interior` went from 0.1993 (32 samples, before) to 0.2214 and was not re-run with every sample drawn. `spot-area` is a hard scene for the stop rule (narrow cone, sharp penumbra); a cause was not isolated. Set `noiseThreshold: 0` to draw every sample.
+
+Denoising a lower sample count (fixed 24 samples with the tracer's filter, threshold 0, against the 64 sample score before the change): `brick-graph` 0.1394 against 0.1370 (0.0024 worse, 17.1 s against 37.3 s) and `character` 0.1164 against 0.1116 (0.0048 worse, 17.2 s against 39.3 s). Both are within 0.005, so a 24 sample still with the filter is a good still on these two scenes at about 45 percent of the time; two scenes are not proof for all.
+
+Darker floor in `character` and `outdoor-hdri`: not found, but narrowed. In `outdoor-hdri` the mean display value of the bottom third (the floor) is 225.5 in Cycles, 225.4 in EEVEE, 224.8 in the rasterizer and 217.1 in the tracer, so the rasterizer agrees with Cycles and the tracer alone is darker, by 8.4 of 255 (the scene is bright, so the display curve compresses it; the linear gap is larger). A white furnace test (a diffuse floor of albedo 0.4 under a sky of radiance 1) gives 0.3955 straight down (1 percent low) and 0.588 at a grazing view with the sky reflection, so sampling the environment and the diffuse lobe is not what loses the light. What is left: the sun together with the HDRI, the clamp of 20 on bounced light (`fireflyClamp`), the grazing-angle specular and light from the other parts, none of which was isolated.
diff --git a/bench/reference/path-tracer.json b/bench/reference/path-tracer.json
index c6494d6d..cf4ed3ed 100644
--- a/bench/reference/path-tracer.json
+++ b/bench/reference/path-tracer.json
@@ -1,78 +1,122 @@
{
"metric": "FLIP (LDR), mean error against Cycles, lower is better",
"scores": {
+ "brick-flat": {
+ "pathtracer-vs-cycles": 0.1117,
+ "seconds": 24.2,
+ "samples": 64,
+ "averageSamples": 45.7,
+ "ignored": []
+ },
"brick-graph": {
- "pathtracer-vs-cycles": 0.1538,
- "seconds": 34.2,
- "samples": 32,
- "ignored": [
- "normalMap is ignored."
- ]
+ "pathtracer-vs-cycles": 0.1373,
+ "seconds": 26.8,
+ "samples": 64,
+ "averageSamples": 45.6,
+ "ignored": []
+ },
+ "brick-room": {
+ "pathtracer-vs-cycles": 0.2743,
+ "seconds": 125.9,
+ "samples": 64,
+ "averageSamples": 61.9,
+ "ignored": []
+ },
+ "brushed-film": {
+ "pathtracer-vs-cycles": 0.1462,
+ "seconds": 47.2,
+ "samples": 64,
+ "averageSamples": 47.4,
+ "ignored": []
},
"car-paint": {
- "pathtracer-vs-cycles": 0.1372,
- "seconds": 44.5,
- "samples": 32,
+ "pathtracer-vs-cycles": 0.1337,
+ "seconds": 46.5,
+ "samples": 64,
+ "averageSamples": 47.7,
"ignored": []
},
"character": {
- "pathtracer-vs-cycles": 0.1143,
- "seconds": 35.5,
- "samples": 32,
+ "pathtracer-vs-cycles": 0.112,
+ "seconds": 35.1,
+ "samples": 64,
+ "averageSamples": 43,
"ignored": [
"gltf materials are traced as plain surfaces."
]
},
"fog": {
- "pathtracer-vs-cycles": 0.5622,
- "seconds": 33.5,
- "samples": 32,
+ "pathtracer-vs-cycles": 0.5628,
+ "seconds": 26.4,
+ "samples": 64,
+ "averageSamples": 38,
"ignored": [
"volumeFog is not traced."
]
},
"foliage": {
- "pathtracer-vs-cycles": 0.1597,
- "seconds": 126.1,
- "samples": 32,
+ "pathtracer-vs-cycles": 0.1577,
+ "seconds": 69.5,
+ "samples": 64,
+ "averageSamples": 38.8,
"ignored": [
"foliage materials are traced as plain surfaces."
]
},
"glass": {
- "pathtracer-vs-cycles": 0.1237,
- "seconds": 50.3,
- "samples": 32,
+ "pathtracer-vs-cycles": 0.122,
+ "seconds": 41.2,
+ "samples": 64,
+ "averageSamples": 47.7,
+ "ignored": []
+ },
+ "light-linking": {
+ "pathtracer-vs-cycles": 0.6191,
+ "seconds": 33.9,
+ "samples": 64,
+ "averageSamples": 36.1,
"ignored": []
},
"lit-interior": {
- "pathtracer-vs-cycles": 0.1993,
- "seconds": 238,
- "samples": 32,
+ "pathtracer-vs-cycles": 0.2214,
+ "seconds": 106.7,
+ "samples": 64,
+ "averageSamples": 62.2,
+ "ignored": []
+ },
+ "long-street": {
+ "pathtracer-vs-cycles": 0.1838,
+ "seconds": 50.2,
+ "samples": 64,
+ "averageSamples": 48.7,
"ignored": []
},
"material-spheres": {
- "pathtracer-vs-cycles": 0.1215,
- "seconds": 66.8,
- "samples": 32,
+ "pathtracer-vs-cycles": 0.1187,
+ "seconds": 52.3,
+ "samples": 64,
+ "averageSamples": 59.5,
"ignored": []
},
"metal": {
- "pathtracer-vs-cycles": 0.1467,
- "seconds": 43.2,
- "samples": 32,
+ "pathtracer-vs-cycles": 0.1435,
+ "seconds": 43.5,
+ "samples": 64,
+ "averageSamples": 48.8,
"ignored": []
},
"outdoor-hdri": {
- "pathtracer-vs-cycles": 0.1036,
- "seconds": 25.1,
- "samples": 32,
+ "pathtracer-vs-cycles": 0.1016,
+ "seconds": 24.8,
+ "samples": 64,
+ "averageSamples": 40.3,
"ignored": []
},
"spot-area": {
- "pathtracer-vs-cycles": 0.0639,
- "seconds": 71.6,
- "samples": 32,
+ "pathtracer-vs-cycles": 0.09,
+ "seconds": 21.3,
+ "samples": 64,
+ "averageSamples": 27.8,
"ignored": []
}
}
diff --git a/bench/reference/run.mjs b/bench/reference/run.mjs
index c07053ab..8c3e7ccf 100644
--- a/bench/reference/run.mjs
+++ b/bench/reference/run.mjs
@@ -2,7 +2,7 @@
// --ambient-occlusion <strength> [--ambient-occlusion-radius <units>] turns occlusion on (off by default).
// --bake [<id>,<id>] bakes bounced light into the named scenes (every scene when no ids follow) before 67js draws them;
// Blender still gets the plain scene.
-// --path-tracer [--samples <n>] draws the scenes with the offline path tracer (src/path-tracer.js) instead, keeps the
+// --path-tracer [--samples <n>] [--noise-threshold <n>] [--scene <id>] draws the scenes with the offline path tracer (src/path-tracer.js) instead, keeps the
// Cycles renders of an earlier run, and scores them into path-tracer.json. Nothing in baseline.json or images/ changes.
// Use --score-only to score existing renders, --skip-blender to keep them, and --scene <id> for one scene.
import { spawnSync } from 'node:child_process';
@@ -45,6 +45,8 @@ const cascades = cascadesFlag >= 0 ? Number(argumentsGiven[cascadesFlag + 1]) :
const pathTracerFlag = argumentsGiven.includes('--path-tracer');
const samplesFlag = argumentsGiven.indexOf('--samples');
const pathTracerSamples = samplesFlag >= 0 ? Number(argumentsGiven[samplesFlag + 1]) : 64;
+const noiseThresholdFlag = argumentsGiven.indexOf('--noise-threshold');
+const pathTracerNoiseThreshold = noiseThresholdFlag >= 0 ? Number(argumentsGiven[noiseThresholdFlag + 1]) : undefined;
const onlyScene = sceneFlag >= 0 ? argumentsGiven[sceneFlag + 1] : null;
async function renderBackend(backend, serverUrl, graphics) {
@@ -91,10 +93,10 @@ async function renderPathTracerScenes(serverUrl) {
const sceneIds = await page.evaluate(() => window.referenceSceneIds);
for (const id of sceneIds) {
if (onlyScene && id !== onlyScene) continue;
- const options = { width: WIDTH, height: HEIGHT, samples: pathTracerSamples, maxSeconds: 1800 };
+ const options = { width: WIDTH, height: HEIGHT, samples: pathTracerSamples, maxSeconds: 1800, ...(pathTracerNoiseThreshold === undefined ? {} : { noiseThreshold: pathTracerNoiseThreshold }) };
const result = await page.evaluate(([sceneId, tracerOptions]) => window.renderReferencePathTraced(sceneId, tracerOptions), [id, options]);
await writeFile(`${WORK_DIRECTORY}/${id}-pathtracer.png`, Buffer.from(result.image, 'base64'));
- timings[id] = { seconds: Number(result.report.seconds.toFixed(1)), samples: result.report.samples, ignored: result.report.ignored };
+ timings[id] = { seconds: Number(result.report.seconds.toFixed(1)), samples: result.report.samples, averageSamples: Number(result.report.averageSamples.toFixed(1)), ignored: result.report.ignored };
console.log(`${id} path traced: ${timings[id].seconds} s at ${timings[id].samples} samples`);
}
} finally {
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 1541bc02..bfc45622 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -30,7 +30,7 @@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:light-bake": 27300,
- "entry:path-tracer": 13800,
+ "entry:path-tracer": 14400,
"entry:texture-set": 900,
"entry:agent-scene": 68300,
"entry:agent-scene+lazy": 238500,
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index 67614b61..606b6979 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -121,7 +121,7 @@ An `image` job can ask for the offline [path tracer](path-tracer.md) with `setti
"renderer": { "type": "pathTracer", "samples": 64, "bounces": 8, "denoise": true, "seed": 0, "maxSeconds": 120 } }
```
-Every field after `type` is optional. Limits: `samples` 1 to 1024, `bounces` 1 to 16, `seed` 0 to 2147483647, `maxSeconds` 1 to 240 (the job also keeps its own five minute deadline). `passes` and the other kinds are refused with it. The tracer loads in the job page on demand, uses four threads, and writes `render.png`; `scene_render_result` metrics carry `pathTracer` with the samples, threads, seconds and what the scene asked for that was not drawn. The same recipe and seed give the same PNG. A job that passes `maxSeconds` fails and writes no image.
+Every field after `type` is optional. Limits: `samples` 1 to 1024, `bounces` 1 to 16, `seed` 0 to 2147483647, `maxSeconds` 1 to 600 (the job's deadline is `maxSeconds` plus 60 seconds; a 1920 by 1080 still of a 180,000 triangle room at 64 samples took 246 s, so give a large still `maxSeconds` 600). `passes` and the other kinds are refused with it. The tracer loads in the job page on demand, uses eight threads at below-normal priority, stops pixels that have converged (`report.averageSamples`), and writes `render.png`; `scene_render_result` metrics carry `pathTracer` with the samples, threads, seconds and what the scene asked for that was not drawn. The same recipe and seed give the same PNG. A job that passes `maxSeconds` fails and writes no image.
## Controller API
diff --git a/docs/parity.md b/docs/parity.md
index 1c900e27..d2f0ac05 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -187,7 +187,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Physics > Baking Physics Simulations | partial | Physics records to a timeline in code or when a recipe scene is created, on the main thread. | [film-physics](../tests/film-physics.test.js) | #61 |
| Physics > Simulation Nodes | missing | No node graph. | | #43 |
| Rendering > Render Engines > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 8 point lights, fog and bloom. There are no light probes. | [renderer](../tests/renderer.test.js), [scores against EEVEE](../bench/reference/baseline.json) | #52, #53, #55, #56 |
-| Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It draws normal and metallic-roughness maps on UV-mapped materials (issue #129) and runs about 2.8 times faster per thread than at that table, so its scores and seconds there predate both; it does not trace volume fog, translucent leaves or maps on box-projected materials, a 1080p still of a 181,708 triangle room at 64 samples still does not finish inside the 240 s job limit, and it is not Cycles parity. `addons/light-bake` bakes bounced light from point, spot and area lights and the sun into a lightmap for each part, on the CPU with ray tracing; recipes reach it through the `bake` section and `set-bake` (draft, standard or fine presets, shrunk deterministically to a ray work budget of 10 million so a preset finishes on a 56 part room; scene_inspect reports what it used, whether it reduced, bake seconds and skipped parts, which include hair, particle and cloth nodes), patterned, textured and emissive parts bake through a second UV set and a `lightMap` slot, GLB export writes the map approximately as `TEXCOORD_1` emissive, but there are no reflection probes and no baked AO. On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [path-tracer](../tests/path-tracer.test.js), [recipe bake](../tests/agent-bake.test.js), [frame time](../bench/reference/frame-time.mjs), [lit-interior scene](../bench/reference/scenes.js) | #55, #57, #128 |
+| Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It draws normal and metallic-roughness maps (issue #129) and runs about 2.8 times faster per thread, and 3.5 to 3.9 times with the shadow-ray change (inferred from 8,360 to about 30,000 paths per second on the demo room), than at that table, whose scores and seconds predate both (the second table in the reference README has the current ones); it draws them on box-projected materials too, stops converged pixels (`noiseThreshold`, which costs `spot-area` some score, see the reference README), and finishes a 1920 by 1080 still of a 181,708 triangle room at 64 samples in 246 s on 8 threads under a job limit now 600 s (it would have missed the old 240 s by 6 s); it does not trace volume fog, translucent leaves, occlusion or emissive maps or light linking, and it is not Cycles parity (its floor is darker than Cycles' in `character` and `outdoor-hdri`, cause not found). `addons/light-bake` bakes bounced light from point, spot and area lights and the sun into a lightmap for each part, on the CPU with ray tracing; recipes reach it through the `bake` section and `set-bake` (draft, standard or fine presets, shrunk deterministically to a ray work budget of 10 million so a preset finishes on a 56 part room; scene_inspect reports what it used, whether it reduced, bake seconds and skipped parts, which include hair, particle and cloth nodes), patterned, textured and emissive parts bake through a second UV set and a `lightMap` slot, GLB export writes the map approximately as `TEXCOORD_1` emissive, but there are no reflection probes and no baked AO. On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [path-tracer](../tests/path-tracer.test.js), [recipe bake](../tests/agent-bake.test.js), [frame time](../bench/reference/frame-time.mjs), [lit-interior scene](../bench/reference/scenes.js) | #55, #57, #128 |
| Rendering > Render Engines > Workbench | out of scope | A viewport engine for working by hand. | | |
| Rendering > Cameras | partial | Perspective, orthographic views, focal length, animated paths, depth of field from depth and camera motion blur, both repeatable per frame. Object motion blur and bokeh shapes are missing. | [camera-path](../tests/camera-path.test.js), [camera](../tests/camera.test.js), [render-passes](../tests/render-passes.test.js) | #54 |
| Rendering > Lights > Light Objects | partial | One directional light with a shadow, 8 point lights, 8 spot lights and 4 rectangular area lights. Point and spot lights can cast shadows from one 24-tile atlas (a point light takes 6 tiles, a spot light 1). Area lights use a representative point and cast no shadow. The directional shadow is a single map, or up to four cascades through `addons/cascaded-shadows` (`shadowCascades` on the renderer and `environment.shadowCascades` in recipes, three by themselves when `shadow.extent` is above 40): scene `long-street` scores 0.1555 against Cycles with one map and 0.1398 with three cascades, for about 0.2 ms more a frame on an RTX 3060 when the camera moves. | [lighting](../tests/lighting.test.js), [cascades](../tests/cascaded-shadows.test.js), `npm run reference` scenes `spot-area` and `long-street` | #52 |
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index c218fe01..5d688f9f 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -7,7 +7,7 @@ import { renderPathTracedImage } from '67js/addons/path-tracer';
const { rgba, linear, report } = await renderPathTracedImage(
{ parts, environment, camera }, // the same objects the rasterizer takes
- { width: 960, height: 540, samples: 64, bounces: 8, seed: 0, denoise: true, threads: 4, maxSeconds: 300 },
+ { width: 960, height: 540, samples: 64, bounces: 8, seed: 0, denoise: true, threads: 4, maxSeconds: 300, noiseThreshold: 0.03 },
);
```
@@ -17,7 +17,7 @@ From an agent, submit an `image` render job with `settings.renderer` (see [rende
Unidirectional path tracing against the triangle BVH that the [light bake](light-bake.md) uses, with next-event estimation and the environment map drawn by importance, then a wavelet denoiser. The first hit of every path samples every light. Later hits draw one light at random and divide by its chance, so the average is the same and a scene with eleven lights costs one shadow ray per bounce instead of eleven.
-- Surfaces: diffuse, GGX specular with metals, clear coat, glass (`transmission`, `ior`, rough glass), emission, image maps (`map`, with `alphaMode: "mask"` cutouts, `normalMap` with `normalScale`, and `metallicRoughnessMap`, whose green channel scales roughness and blue scales metallic as in the rasterizer) and vertex colour. Skinned parts are drawn at their current pose.
+- Surfaces: diffuse, GGX specular with metals, clear coat, glass (`transmission`, `ior`, rough glass), emission, image maps (`map`, with `alphaMode: "mask"` cutouts, `normalMap` with `normalScale`, and `metallicRoughnessMap`, whose green channel scales roughness and blue scales metallic as in the rasterizer; box-projected materials read all of them through the UVs of their projection, the same ones the glTF export writes) and vertex colour. Skinned parts are drawn at their current pose.
- Lights: the sun (`keyColor`, `lightDirection`, as a 1 degree disk), point lights with a radius, spot lights with a soft cone, rectangular area lights, and the environment map with its rotation. All of them cast soft shadows, whatever their `castShadow` says, as in Cycles.
- Light that bounces between surfaces, and the sky seen in mirrors and through glass.
@@ -26,7 +26,7 @@ Unidirectional path tracing against the triangle BVH that the [light bake](light
`report.ignored` lists the ones this scene asks for.
- Volume fog (`volumeFog`), and the procedural sky when there is no environment map (the sky is black).
-- Occlusion maps and emissive maps, and normal and metallic-roughness maps on box-projected materials (`boxMapScale`, which has no UVs to read them with). Normal maps and metallic-roughness maps on UV-mapped materials are drawn. Material graphs and patterns are drawn through the colour map they bake.
+- Occlusion maps and emissive maps. Normal and metallic-roughness maps are drawn on UV-mapped and on box-projected materials. Material graphs and patterns are drawn through the colour map they bake.
- Translucent leaves (foliage looks darker than in the rasterizer), liquids, foam and blended transparency (traced as plain or opaque surfaces).
- Lights seen in mirrors (area lights and spot lights are lit but not visible), caustics, subsurface scattering, motion blur, depth of field, bloom and colour grade.
- Multiple-scattering GGX: rough metal is a little darker than in Blender.
@@ -36,15 +36,16 @@ Unidirectional path tracing against the triangle BVH that the [light bake](light
| Option | Default | Range | Meaning |
| --- | --- | --- | --- |
| `width`, `height` | 960, 540 | 16 to 4096 | Output size, at most 2,073,600 pixels. |
-| `samples` | 64 | 1 to 1024 | Paths per pixel. |
+| `samples` | 64 | 1 to 1024 | Most paths per pixel. A pixel stops earlier when it has converged (`noiseThreshold`). |
| `bounces` | 8 | 1 to 16 | Reflections followed by each path. |
| `seed` | 0 | 0 to 2147483647 | Changes the noise. |
| `threads` | 4 | 1 to 8 | Module workers; the pixels are the same for any count. Without `Worker` it runs on one thread. |
+| `noiseThreshold` | 0.03 | 0 to 1 | A pixel stops once the standard error of its mean luminance, relative to that mean plus 0.05, is under this, checked from 16 samples on and after every 8 more. 0 draws every sample. It reads only the pixel's own samples, so the result is the same on any thread count and band split. `report.averageSamples` says how many paths a pixel took. |
| `maxSeconds` | 300 | 1 to 1800 | Wall-clock limit. Passing it throws; there is never a partial image. |
| `denoise` | true | boolean | Filters the light with normal, depth and noise guides. |
| `fireflyClamp` | 20 | 1 to 1000 | Largest radiance one bounce may add to a sample. |
-Also checked before any ray is traced: samples times pixels times bounces at most 4 billion, 400,000 triangles, 1,024 parts, 32 lights, and finite numbers and in-range indices in every part. A render job limits `maxSeconds` to 240 so that it ends before the job deadline.
+Also checked before any ray is traced: samples times pixels times bounces at most 4 billion, 400,000 triangles, 1,024 parts, 32 lights, and finite numbers and in-range indices in every part. A render job limits `maxSeconds` to 600: the job runs on workers without blocking the page, and its deadline is `maxSeconds` plus 60 seconds for the page and the PNG, so a trace that reaches its limit still ends before the job does.
The same scene and options give the same bytes. Random numbers come from a hash of the pixel, the sample and the seed, never from `Math.random` or the clock, and a pixel does not depend on which thread drew it.
@@ -62,7 +63,20 @@ Where the time went on the 181,708 triangle demo room (issue #129; one thread, C
| Typed-stack ray query, same pixels bit for bit | 9,756 (1.2 times) |
| One light drawn at random past the first hit (11 light sources) | 23,300 (2.4 times more, 2.8 in all) |
-At 23,300 paths a second, a 1920 by 1080 still at 64 samples is 133 million paths: about 5,700 thread-seconds, or roughly 12 minutes on eight threads that have the machine to themselves (inferred, not measured end to end). That is above the 240 s limit of a render job, so such a still needs about 16 samples inside the limit, or a longer `maxSeconds` on a call that is not a job. The hair strands were not the cost by themselves: the time was per ray, and every ray was slow. Ideas not done: adaptive sampling that stops converged pixels, and a lighter BVH for hair tubes.
+Adaptive sampling, a shadow-ray shortcut and the demo-room still (issue #129, second pass; same 181,708 triangle room, one thread, 160 by 90, seed 7, error is the RMSE of the 8-bit image against a 256 sample render of seed 0, on an idle machine):
+
+| Step | Seconds | Average samples | Error |
+| --- | --- | --- | --- |
+| 64 samples, every pixel | 25.9 | 64 | 4.38 |
+| Same, shadow rays skip the surface lookup unless the material is a cutout | 21.0 and 19.1 (1.23 to 1.36 times) | 64 | 4.38, pixels unchanged |
+| 24 samples, every pixel | 9.5 | 24 | 5.53 |
+| `noiseThreshold` 0.05 | 11.3 | 26.1 | 4.87 |
+| `noiseThreshold` 0.03 (the default) | 14.1 | 34.4 | 4.77 |
+| One light drawn at random at the first hit too | 12.9 | 64 | 7.26 |
+
+Adaptive sampling beats fewer samples at the same cost (4.87 at 11.3 s against 5.53 at 9.5 s) and keeps most of the quality of 64 (4.77 against 4.38 in about half the time, measured before the shadow-ray change). Drawing one light at the first hit halves the time but makes the image noisier than 24 samples cost, so it was not kept.
+
+The 1920 by 1080 still of `tests/fixtures/demo-room.recipe.json` at `samples: 64`, through an MCP image job with 8 threads: 246.4 s in the tracer (229.4 s tracing, the rest the filter), 30.7 samples per pixel on average, 257 s for the whole job (measured, once). That is 6 seconds over the old 240 s job limit, so the limit is now 600. The hair strands were not the cost by themselves: the time was per ray, and every ray was slow.
## Measured
diff --git a/src/export-box-uv.js b/src/export-box-uv.js
index f26a2993..bfbf423a 100644
--- a/src/export-box-uv.js
+++ b/src/export-box-uv.js
@@ -2,6 +2,11 @@
// TEXCOORD_0: every triangle takes the object axis its normal is closest to, as the shader's blend weights do on a
// face, and vertices are split only where neighbouring triangles pick different axes.
+/** The lengths of a part matrix's three columns: the shader projects scaled object positions. */
+export function columnLengths(matrix) {
+ return [0, 4, 8].map(offset => Math.hypot(matrix[offset], matrix[offset + 1], matrix[offset + 2]));
+}
+
function swapAxes(values, boxMapAxis) {
if (boxMapAxis === 0) return [values[1], values[0], values[2]];
if (boxMapAxis === 2) return [values[0], values[2], values[1]];
diff --git a/src/export.js b/src/export.js
index 5c93625f..315c5ed3 100644
--- a/src/export.js
+++ b/src/export.js
@@ -1,7 +1,7 @@
import { validateMorphGeometry, validateMorphPose } from './morph.js';
import { gltfExtensionsFromLayers, LAYER_TEXTURE_SLOTS } from './gltf-layers.js';
import { validateSkinGeometry } from './skinning.js';
-import { boxProjectedGeometry } from './export-box-uv.js';
+import { boxProjectedGeometry, columnLengths } from './export-box-uv.js';
import { createTextureWriter } from './export-textures.js';
import { createGlbWriter } from './export-writer.js';
import { buildHierarchy, decomposeMatrix, hierarchyNodeFields, hostOfPart, normalizedWeights, relativeMatrix, writeAnimations, writeSkin } from './export-skeleton.js';
@@ -124,10 +124,6 @@ function validateSkinnedPart(part) {
validateSkinGeometry(part.geometry, part.skin);
}
-function columnLengths(matrix) {
- return [0, 4, 8].map(offset => Math.hypot(matrix[offset], matrix[offset + 1], matrix[offset + 2]));
-}
-
function createIdentityTracker() {
const identities = new WeakMap();
let next = 0;
diff --git a/src/path-tracer-capabilities.js b/src/path-tracer-capabilities.js
index 1a0b2b40..720c6c8e 100644
--- a/src/path-tracer-capabilities.js
+++ b/src/path-tracer-capabilities.js
@@ -5,12 +5,12 @@
export const PATH_TRACER_JOB_LIMITS = Object.freeze({
samples: Object.freeze({ minimum: 1, maximum: 1024, default: 64 }),
bounces: Object.freeze({ minimum: 1, maximum: 16, default: 8 }),
- maxSeconds: Object.freeze({ minimum: 1, maximum: 240, default: 120 }),
+ maxSeconds: Object.freeze({ minimum: 1, maximum: 600, default: 120 }),
seed: Object.freeze({ minimum: 0, maximum: 2147483647, default: 0 }),
});
export const PATH_TRACER_CAPABILITIES = Object.freeze({
setting: 'settings.renderer { type: "pathTracer", samples, bounces, denoise, seed, maxSeconds }; image jobs only, no passes. Past maxSeconds the job fails.',
- skips: 'volume fog, normal and roughness maps, translucent leaves, liquids, caustics, depth of field, bloom; the job result lists what the scene asked for.',
+ skips: 'volume fog, occlusion and emissive maps, translucent leaves, liquids, caustics, depth of field, bloom; the job result lists what the scene asked for.',
limits: PATH_TRACER_JOB_LIMITS,
});
diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.js
index ddb4689a..2313f96b 100644
--- a/src/path-tracer-scene.js
+++ b/src/path-tracer-scene.js
@@ -1,5 +1,6 @@
import { buildTriangleBvh } from './triangle-bvh.js';
import { createTracer } from './ray-query.js';
+import { boxProjectedGeometry, columnLengths } from './export-box-uv.js';
// The scene a path trace reads: every part flattened into one world-space triangle soup with per-vertex normals, UVs
// and colours, one resolved material per part, the lights in plain arrays, and the environment map as a sampling table.
@@ -90,10 +91,9 @@ function resolveMaterial(material) {
transmission: material.transmission ?? 0,
ior: material.ior ?? 1.5,
texture: resolveTexture(material.map),
- // Box-projected materials (boxMapScale) have no UVs to read these maps with; describeIgnoredFeatures says so.
- normalTexture: material.boxMapScale > 0 ? null : resolveTexture(material.normalMap),
+ normalTexture: resolveTexture(material.normalMap),
normalScale: material.normalScale ?? [1, 1],
- surfaceTexture: material.boxMapScale > 0 ? null : resolveTexture(material.metallicRoughnessMap),
+ surfaceTexture: resolveTexture(material.metallicRoughnessMap),
alphaCutoff: material.alphaMode === 'mask' ? material.alphaCutoff ?? 0.5 : 0,
};
}
@@ -120,10 +120,21 @@ function validatePart(part, geometry) {
if (geometry.colors && geometry.colors.length !== vertexCount * 3) throw new RangeError(`${label} needs one colour for every position.`);
}
+/**
+ * The geometry a part is traced with. A box-projected material has no UVs, so it gets the UVs of its projection (the
+ * ones the glTF export writes), and every map then reads them like those of an authored material.
+ */
+function traceGeometry(part) {
+ const geometry = part.skin ? skinnedGeometry(part) : part.geometry;
+ const { boxMapScale = 0, boxMapAxis = 1 } = part.material ?? {};
+ if (!(boxMapScale > 0)) return geometry;
+ return boxProjectedGeometry(geometry, columnLengths(part.matrix ?? IDENTITY_MATRIX), boxMapScale, boxMapAxis);
+}
+
function flattenParts(parts) {
let vertexTotal = 0;
let indexTotal = 0;
- const geometries = parts.map(part => (part.skin ? skinnedGeometry(part) : part.geometry));
+ const geometries = parts.map(traceGeometry);
parts.forEach((part, index) => validatePart(part, geometries[index]));
for (const geometry of geometries) {
vertexTotal += geometry.positions.length / 3;
diff --git a/src/path-tracer.js b/src/path-tracer.js
index dc3cf51e..d6ed178d 100644
--- a/src/path-tracer.js
+++ b/src/path-tracer.js
@@ -18,6 +18,7 @@ export const PATH_TRACER_LIMITS = Object.freeze({
bounces: Object.freeze({ minimum: 1, maximum: 16, fallback: 8 }),
maxSeconds: Object.freeze({ minimum: 1, maximum: 1800, fallback: 300 }),
fireflyClamp: Object.freeze({ minimum: 1, maximum: 1000, fallback: 20 }),
+ noiseThreshold: Object.freeze({ minimum: 0, maximum: 1, fallback: 0.03 }),
seed: Object.freeze({ minimum: 0, maximum: 2 ** 31 - 1, fallback: 0 }),
threads: Object.freeze({ minimum: 1, maximum: 8, fallback: 4 }),
});
@@ -28,8 +29,12 @@ const WORKER_BAND_ROWS = 8;
// Held in a constant so the bundler leaves the URL alone: the worker is its own package entry, built beside this file.
const WORKER_FILE = './path-tracer-worker.js';
const RUSSIAN_ROULETTE_START = 3;
+// A pixel is checked for convergence from this many samples on, then after every batch of samples.
+const ADAPTIVE_MINIMUM_SAMPLES = 16;
+const ADAPTIVE_BATCH_SAMPLES = 8;
+// Mean luminance added to the standard error's reference, so very dark pixels are not held to a relative error.
+const CONVERGENCE_LUMINANCE_FLOOR = 0.05;
const IGNORED_MAP_FIELDS = ['occlusionMap', 'emissiveMap'];
-const UV_ONLY_MAP_FIELDS = ['normalMap', 'metallicRoughnessMap'];
function boundedInteger(options, name) {
const limit = PATH_TRACER_LIMITS[name];
@@ -60,6 +65,7 @@ export function normalizePathTracerOptions(options = {}) {
threads: boundedInteger(options, 'threads'),
maxSeconds: boundedNumber(options, 'maxSeconds'),
fireflyClamp: boundedNumber(options, 'fireflyClamp'),
+ noiseThreshold: boundedNumber(options, 'noiseThreshold'),
denoise: options.denoise ?? true,
};
if (typeof result.denoise !== 'boolean') throw new TypeError('Path tracer denoise must be a boolean.');
@@ -339,8 +345,10 @@ function occluded(scene, originX, originY, originZ, directionX, directionY, dire
for (let attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {
const found = scene.tracer.trace(startX, startY, startZ, directionX, directionY, directionZ, remaining, true);
if (found.nearestTriangle < 0) return false;
+ // Only a cutout material needs its texture read to know whether the ray passes through: skip the interpolation for the rest.
+ if (scene.materials[scene.triangleMaterial[found.nearestTriangle]].alphaCutoff === 0) return true;
const alpha = fillHit(scene, found.nearestTriangle, startX, startY, startZ, directionX, directionY, directionZ, found.nearestDistance, hit);
- if (hit.material.alphaCutoff === 0 || alpha >= hit.material.alphaCutoff) return true;
+ if (alpha >= hit.material.alphaCutoff) return true;
const advance = found.nearestDistance + scene.surfaceOffset;
remaining -= advance;
if (remaining <= 0) return false;
@@ -665,9 +673,6 @@ export function describeIgnoredFeatures(parts, environment) {
for (const part of parts) {
const material = part.material ?? {};
for (const field of IGNORED_MAP_FIELDS) if (material[field]) notes.add(`${field} is ignored.`);
- if (material.boxMapScale > 0) {
- for (const field of UV_ONLY_MAP_FIELDS) if (material[field]) notes.add(`${field} is ignored on box-projected materials.`);
- }
if (material.tag && material.tag !== 'surface') notes.add(`${material.tag} materials are traced as plain surfaces.`);
if (material.alphaMode === 'blend') notes.add('Blended transparency is traced as opaque.');
if (material.lightMask !== undefined) notes.add('Light linking (affects) is not traced: every light lights every part.');
@@ -680,6 +685,24 @@ export function describeIgnoredFeatures(parts, environment) {
* major from the band's first row. A pixel's random numbers depend only on its place in the whole image, so bands
* can be drawn in any order, on any thread, and give the same pixels.
*/
+/**
+ * True when the mean luminance of a pixel is known well enough: its standard error, relative to the mean plus a small
+ * floor so that near-black pixels do not ask for endless samples, is under `threshold`. It reads only the pixel's own
+ * samples, so the decision is the same on any thread and in any band split.
+ */
+function hasConverged(sumLuminance, sumLuminanceSquares, sampleCount, threshold) {
+ const mean = sumLuminance / sampleCount;
+ const sampleVariance = Math.max(0, sumLuminanceSquares / sampleCount - mean * mean) * sampleCount / (sampleCount - 1);
+ const standardError = Math.sqrt(sampleVariance / sampleCount);
+ return standardError < threshold * (mean + CONVERGENCE_LUMINANCE_FLOOR);
+}
+
+function isConvergenceCheckDue(sampleCount, options) {
+ if (!(options.noiseThreshold > 0)) return false;
+ if (sampleCount < ADAPTIVE_MINIMUM_SAMPLES) return false;
+ return (sampleCount - ADAPTIVE_MINIMUM_SAMPLES) % ADAPTIVE_BATCH_SAMPLES === 0;
+}
+
export function renderBand(scene, camera, options, rowStart, rowEnd, shouldStop = () => {}) {
const tracer = createPathTracer(scene, options);
const { width, height, samples } = options;
@@ -689,6 +712,7 @@ export function renderBand(scene, camera, options, rowStart, rowEnd, shouldStop
const normal = new Float32Array(pixelCount * 3);
const depth = new Float32Array(pixelCount);
const variance = new Float32Array(pixelCount);
+ const samplesTaken = new Uint16Array(pixelCount);
for (let row = rowStart; row < rowEnd; row++) {
shouldStop();
for (let column = 0; column < width; column++) {
@@ -696,7 +720,9 @@ export function renderBand(scene, camera, options, rowStart, rowEnd, shouldStop
const slot = (row - rowStart) * width + column;
let sumLuminance = 0;
let sumLuminanceSquares = 0;
- for (let sample = 0; sample < samples; sample++) {
+ let taken = 0;
+ while (taken < samples) {
+ const sample = taken;
const jitterX = hashJitter(pixel, sample, options.seed, 1);
const jitterY = hashJitter(pixel, sample, options.seed, 2);
const screenX = ((column + jitterX) / width * 2 - 1) * camera.halfWidth;
@@ -716,18 +742,21 @@ export function renderBand(scene, camera, options, rowStart, rowEnd, shouldStop
normal[slot * 3 + channel] += features.normal[channel];
}
depth[slot] += features.depth;
+ taken++;
+ if (isConvergenceCheckDue(taken, options) && hasConverged(sumLuminance, sumLuminanceSquares, taken, options.noiseThreshold)) break;
}
for (let channel = 0; channel < 3; channel++) {
- color[slot * 3 + channel] /= samples;
- albedo[slot * 3 + channel] /= samples;
- normal[slot * 3 + channel] /= samples;
+ color[slot * 3 + channel] /= taken;
+ albedo[slot * 3 + channel] /= taken;
+ normal[slot * 3 + channel] /= taken;
}
- depth[slot] /= samples;
- const meanLuminance = sumLuminance / samples;
- variance[slot] = Math.max(0, sumLuminanceSquares / samples - meanLuminance * meanLuminance) / Math.max(samples - 1, 1);
+ depth[slot] /= taken;
+ const meanLuminance = sumLuminance / taken;
+ variance[slot] = Math.max(0, sumLuminanceSquares / taken - meanLuminance * meanLuminance) / Math.max(taken - 1, 1);
+ samplesTaken[slot] = taken;
}
}
- return { color, albedo, normal, depth, variance };
+ return { color, albedo, normal, depth, variance, samplesTaken };
}
function hashJitter(pixel, sample, seed, dimension) {
@@ -738,6 +767,12 @@ function hashJitter(pixel, sample, seed, dimension) {
return (mixed >>> 0) / 4294967296;
}
+function totalSamples(samplesTaken) {
+ let total = 0;
+ for (let pixel = 0; pixel < samplesTaken.length; pixel++) total += samplesTaken[pixel];
+ return total;
+}
+
function normalizeNormals(normal, pixelCount) {
for (let pixel = 0; pixel < pixelCount; pixel++) {
const length = Math.hypot(normal[pixel * 3], normal[pixel * 3 + 1], normal[pixel * 3 + 2]);
@@ -749,7 +784,7 @@ function normalizeNormals(normal, pixelCount) {
function copyBand(buffers, band, rowStart, width) {
const pixelOffset = rowStart * width;
for (const name of ['color', 'albedo', 'normal']) buffers[name].set(band[name], pixelOffset * 3);
- for (const name of ['depth', 'variance']) buffers[name].set(band[name], pixelOffset);
+ for (const name of ['depth', 'variance', 'samplesTaken']) buffers[name].set(band[name], pixelOffset);
}
/** Draws bands on a pool of module workers, handing the next band to whichever worker finishes first. */
@@ -819,7 +854,7 @@ export async function renderPathTracedImage({ parts, environment = {}, camera },
const pixelCount = width * height;
const buffers = {
color: new Float32Array(pixelCount * 3), albedo: new Float32Array(pixelCount * 3), normal: new Float32Array(pixelCount * 3),
- depth: new Float32Array(pixelCount), variance: new Float32Array(pixelCount),
+ depth: new Float32Array(pixelCount), variance: new Float32Array(pixelCount), samplesTaken: new Uint16Array(pixelCount),
};
const threads = typeof Worker === 'function' ? options.threads : 1;
if (threads > 1) {
@@ -830,11 +865,13 @@ export async function renderPathTracedImage({ parts, environment = {}, camera },
shouldStop();
const tracedSeconds = (performance.now() - started) / 1000;
normalizeNormals(buffers.normal, pixelCount);
- const linear = options.denoise ? denoiseRadiance({ width, height, ...buffers }) : buffers.color;
+ const { samplesTaken, ...denoiseInputs } = buffers;
+ const linear = options.denoise ? denoiseRadiance({ width, height, ...denoiseInputs }) : buffers.color;
return {
width, height, linear, rgba: toneMapToRgba8(linear, width, height),
report: {
width, height, samples: options.samples, bounces: options.bounces, seed: options.seed, denoised: options.denoise, threads,
+ averageSamples: totalSamples(samplesTaken) / pixelCount, noiseThreshold: options.noiseThreshold,
triangles: scene.indices.length / 3, tracedSeconds, seconds: (performance.now() - started) / 1000,
ignored: describeIgnoredFeatures(parts, environment),
},
diff --git a/tests/path-tracer.test.js b/tests/path-tracer.test.js
index a83277a6..3c8744aa 100644
--- a/tests/path-tracer.test.js
+++ b/tests/path-tracer.test.js
@@ -211,11 +211,18 @@ test('a metallic-roughness map scales the metallic and roughness of the material
assert.notEqual(smoothed, plain, 'green channel 0 makes the surface smooth');
});
-test('maps on box-projected materials are named as ignored, the others are drawn', () => {
- const notes = describeIgnoredFeatures([{ material: { normalMap: {}, metallicRoughnessMap: {} } }], {});
- assert.ok(!notes.some(note => note.includes('normalMap')));
- const boxed = describeIgnoredFeatures([{ material: { normalMap: {}, boxMapScale: 2 } }], {});
- assert.ok(boxed.some(note => note.includes('normalMap') && note.includes('box-projected')));
+test('normal and roughness maps on box-projected materials are drawn through the projection UVs', async () => {
+ const notes = describeIgnoredFeatures([{ material: { normalMap: {}, metallicRoughnessMap: {}, boxMapScale: 2 } }], {});
+ assert.ok(!notes.some(note => note.includes('normalMap') || note.includes('metallicRoughnessMap')), notes.join(' '));
+ const boxed = { boxMapScale: 2, boxMapAxis: 1 };
+ const flat = await renderMappedFloor({ ...boxed });
+ const towardSun = await renderMappedFloor({ ...boxed, normalMap: singleTexel(204, 128, 230) });
+ const awayFromSun = await renderMappedFloor({ ...boxed, normalMap: singleTexel(51, 128, 230) });
+ assert.ok(towardSun > flat * 1.2, `tilted toward the sun ${towardSun} against flat ${flat}`);
+ assert.ok(awayFromSun < flat * 0.5, `tilted away ${awayFromSun} against flat ${flat}`);
+ const plain = await renderMappedFloor({ ...boxed, metallic: 0 });
+ const metalMasked = await renderMappedFloor({ ...boxed, metallic: 1, metallicRoughnessMap: singleTexel(0, 255, 0) });
+ assert.equal(metalMasked, plain, 'blue channel 0 removes the metal on a box-projected material');
});
test('drawing one light at random past the first hit keeps the average', async () => {
@@ -257,3 +264,36 @@ test('a scene sent to a worker gets its ray query back from the arrays', () => {
const hit = revived.tracer.trace(0, 5, 0, 0, -1, 0, 100, false);
assert.ok(hit.nearestTriangle >= 0);
});
+
+// ---- Adaptive sampling (issue #129) ----
+
+const NOISY_AND_QUIET = { width: 24, height: 18, samples: 48, bounces: 3, threads: 1, denoise: false };
+
+test('a threshold of zero draws every sample, and a threshold stops the pixels that have converged', async () => {
+ const fixed = await renderPathTracedImage(checkerScene(), { ...NOISY_AND_QUIET, noiseThreshold: 0 });
+ assert.equal(fixed.report.averageSamples, 48);
+ const adaptive = await renderPathTracedImage(checkerScene(), { ...NOISY_AND_QUIET, noiseThreshold: 0.05 });
+ assert.ok(adaptive.report.averageSamples < 48, `average ${adaptive.report.averageSamples}`);
+ assert.ok(adaptive.report.averageSamples >= 16, 'no pixel stops before its minimum');
+ const mean = image => image.linear.reduce((sum, value) => sum + value, 0) / image.linear.length;
+ assert.ok(Math.abs(mean(adaptive) - mean(fixed)) / mean(fixed) < 0.05, `mean ${mean(adaptive)} against ${mean(fixed)}`);
+});
+
+test('adaptive bands split anywhere give the pixels of the whole image', () => {
+ const { parts, environment, camera } = checkerScene();
+ const options = normalizePathTracerOptions({ ...NOISY_AND_QUIET, noiseThreshold: 0.05 });
+ const scene = buildTraceScene(parts, environment);
+ const view = createCamera(camera, options.width, options.height);
+ const whole = renderBand(scene, view, options, 0, options.height);
+ assert.ok(new Set(whole.samplesTaken).size > 1, 'the pixels stop at different sample counts');
+ const rowFloats = options.width * 3;
+ for (const [start, end] of [[7, 18], [0, 9]]) {
+ const band = renderBand(scene, view, options, start, end);
+ assert.deepEqual(band.color, whole.color.slice(start * rowFloats, end * rowFloats), `rows ${start} to ${end}`);
+ assert.deepEqual(band.samplesTaken, whole.samplesTaken.slice(start * options.width, end * options.width));
+ }
+});
+
+test('the noise threshold is validated', () => {
+ for (const noiseThreshold of [-0.1, 1.5, Number.NaN, '0.1']) assert.throws(() => normalizePathTracerOptions({ noiseThreshold }), /noiseThreshold/);
+});