Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Light tree: SAOH split, 90/10 measure mix, WebGPU tree, auto default past 8 lights (issue #623)

Nguyen Xuan An6241d7b46c9d
diff --git a/bench/reference/gpu-compare.mjs b/bench/reference/gpu-compare.mjs
index 59b6bff8..295063b0 100644
--- a/bench/reference/gpu-compare.mjs
+++ b/bench/reference/gpu-compare.mjs
@@ -1,6 +1,6 @@
// Draws reference scenes with the path tracer on the CPU and on the GPU, same seed, and writes the images and timings.
// node bench/reference/gpu-compare.mjs <output directory> <scene id>,<scene id> [--samples 64] [--backend cpu|gpu|webgpu|both]
-// [--width 960] [--height 540] [--bounces 8] [--no-denoise] [--threads 8]
+// [--light-selection uniform|importance|tree] [--width 960] [--height 540] [--bounces 8] [--no-denoise] [--threads 8]
// Files are <scene>-pathtracer-<backend>.png and timings.json. Run it through the GPU lock script (gpu-lock.sh): the GPU
// backend takes the whole GPU for seconds at a time.
import { mkdir, readFile, writeFile } from 'node:fs/promises';
@@ -27,6 +27,7 @@ const options = {
width: Number(valueAfter('--width', 960)),
height: Number(valueAfter('--height', 540)),
samples: Number(valueAfter('--samples', 64)),
+ lightSelection: valueAfter('--light-selection', 'uniform'),
bounces: Number(valueAfter('--bounces', 8)),
threads: Number(valueAfter('--threads', 8)),
denoise: !argumentsGiven.includes('--no-denoise'),
diff --git a/bench/reference/progressive-compare.mjs b/bench/reference/progressive-compare.mjs
index 3a48780d..321b47c8 100644
--- a/bench/reference/progressive-compare.mjs
+++ b/bench/reference/progressive-compare.mjs
@@ -1,6 +1,6 @@
// Draws reference scenes progressively (issue #623) and measures the time against the 64 sample still.
// node bench/reference/progressive-compare.mjs <output directory> <scene id or recipe.json>,... [--variant random|blue|importance|tree|both]
-// [--checkpoints 1,2,4,8,16,32,64] [--width 960] [--height 540] [--still] [--frames 200]
+// [--checkpoints 1,2,4,8,16,32,64] [--firefly-clamp 1e9] [--width 960] [--height 540] [--still] [--frames 200]
// Files are <scene>@<variant>-<samples>.png, <scene>@still-64.png and timings.json; bench/reference/progressive-score.py scores them against Cycles.
// With --frames the script also prints the median time of one full size sample (1 sample per pixel) for each scene.
// Run it behind a GPU lock when other jobs share the GPU: it takes the whole GPU for seconds at a time.
@@ -36,6 +36,7 @@ const baseOptions = {
height: Number(valueAfter('--height', 540)),
bounces: Number(valueAfter('--bounces', 8)),
denoise: !argumentsGiven.includes('--no-denoise'),
+ ...(argumentsGiven.includes('--firefly-clamp') ? { fireflyClamp: Number(valueAfter('--firefly-clamp', 0)) } : {}),
maxSeconds: 1800,
};
diff --git a/bench/reference/progressive-score.py b/bench/reference/progressive-score.py
index 0984490e..86f533a5 100644
--- a/bench/reference/progressive-score.py
+++ b/bench/reference/progressive-score.py
@@ -32,6 +32,8 @@ def split_name(stem):
if "@" in stem:
scene_id, label = stem.split("@", 1)
return scene_id, label
+ if stem.endswith("-pathtracer-webgpu"):
+ return stem.removesuffix("-pathtracer-webgpu"), "webgpu"
return stem.removesuffix("-pathtracer-gpu"), "gpu"
diff --git a/changes/623-tree.md b/changes/623-tree.md
index 37cc88ab..43563209 100644
--- a/changes/623-tree.md
+++ b/changes/623-tree.md
@@ -1 +1 @@
-- Path tracer `lightSelection: "tree"`: a light tree after Conty and Kulla (2018) as Cycles builds it, on the CPU reference and the WebGL2 kernel. On the new 24 lamp `many-lights` scene it scores 0.0617 against Cycles at 64 samples (uniform 0.1471) and takes 38 ms per full size sample against 72 ms; it stays off by default because it scores worse than uniform on `brick-room` and `light-linking` (issue #623)
+- The light tree splits by the surface area orientation heuristic, draws 90 percent by the angle-aware measure, runs on the WebGPU tracer (megakernel and wavefront), and `lightSelection` defaults to `"auto"`: the tree for a scene with more than 8 local lights, uniform otherwise (#623)
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index 133cfc2c..57ed2100 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -136,11 +136,11 @@ Scores and times are in the table of `bench/reference/README.md`. Cycles used 25
`67js/addons/path-tracer-progressive` (`createProgressiveTracer(scene, options)`) draws the GPU tracer one sample per pixel per `step()`. The first two steps draw at a quarter and a half of the size, one sample each, then every step adds a sample at full size; `update({ camera, parts, environment })` starts the image over, and `snapshot()` reads the image back (filtered unless `denoise` is off). It shares the WebGL2 context of the GPU still, so one render at a time owns it. The core bundle does not carry it.
-Three options, all off by default, so the default pixels do not change (`samplingPattern: "blue-noise-first"` and `lightSelection: "importance"` need the GPU backend, `lightSelection: "tree"` runs on the CPU reference and the GPU, not on WebGPU):
+Three options (`samplingPattern: "blue-noise-first"` and `lightSelection: "importance"` need the GPU backend, `lightSelection: "tree"` runs on the CPU reference, the WebGL2 GPU and the WebGPU tracer). `samplingPattern` and `importance` are off by default; `lightSelection` defaults to `"auto"`, which is `"tree"` for a scene with more than 8 local lights and `"uniform"` for the rest, so scenes with a handful of lights draw the same pixels as before:
- `samplingPattern: "blue-noise-first"` uses a 64 by 64 void-and-cluster tile (`src/path-tracer-blue-noise.js`, same bytes for the same seed) for the pixel jitter and the first two random numbers of sample 0, as `SAMPLING_PATTERN_BLUE_NOISE_FIRST` does in Cycles. Later samples are random.
- `lightSelection: "importance"` replaces the uniform light draw past the first hit: the sun and the sky keep their uniform share, and the local lights split theirs by power over squared distance, surface cosine and spot cone, mixed 10 percent with a uniform part. It ignores shadows and is a flat sum over the lights, not a tree (that is `lightSelection: "tree"`) nor ReSTIR; a scene with one local light or none draws the same pixels as before.
-- `lightSelection: "tree"` is the light tree of Conty and Kulla (2018) as Cycles builds it (`src/kernel/light/tree.h`), in `src/path-tracer-light-tree.js`, the same code and table on the CPU reference and in the GLSL kernel. The point, spot and area lights are leaves of a balanced binary tree (split at the median of the longest centroid axis; Cycles splits with a surface-area-orientation heuristic, which this does not). Each node keeps its box, an orientation cone (merged as in the paper) and the sum of its energy. A shading point walks down from the root and picks a child at each step by the importance of its box and cone: energy times the cosine of the best angle the box and cone allow, times the surface cosine, over the squared distance to the nearest point of the box. The step takes the chance 0.5 of the child's share of the maximum measure plus 0.5 of its share of a minimum measure (energy over the squared farthest distance, no angles), as Cycles does, so a node the angle test culls keeps a chance and the image stays unbiased; the chance of the whole path is divided out. The sun and the sky are the distant emitters and keep their uniform share of the emitter draw. It ignores shadows, light linking and spot blend. With more than 16 local lights the first hit draws one light by the tree too, where every other selection traces a shadow ray to each light there. A scene with one local light or none draws the same pixels as the uniform choice.
+- `lightSelection: "tree"` is the light tree of Conty and Kulla (2018) as Cycles builds it (`src/kernel/light/tree.h`), in `src/path-tracer-light-tree.js`, the same code and table on the CPU reference and in the GLSL kernel. The point, spot and area lights are leaves of a binary tree built with the surface area orientation heuristic of the paper (12 buckets per axis, cost = energy times box area times orientation measure of both sides, as Cycles builds it). Each node keeps its box, an orientation cone (merged as in the paper) and the sum of its energy. A shading point walks down from the root and picks a child at each step by the importance of its box and cone: energy times the cosine of the best angle the box and cone allow, times the surface cosine, over the squared distance to the nearest point of the box. The step takes the chance 0.9 of the child's share of the maximum measure plus 0.1 of its share of a minimum measure (energy over the squared farthest distance, no angles; Cycles mixes them half and half), so a node the angle test culls keeps a chance and the image stays unbiased while little of the draw goes to lights that cannot reach the point; the chance of the whole path is divided out. The sun and the sky are the distant emitters and keep their uniform share of the emitter draw. It ignores shadows, light linking and spot blend. With more than 16 local lights the first hit draws one light by the tree too, where every other selection traces a shadow ray to each light there. A scene with one local light or none draws the same pixels as the uniform choice.
Measured on the RTX 3060, 960 by 540, FLIP against Cycles of the denoised image, machine shared with other jobs (times are ranges of repeated runs: GPU steps only, without the first step's kernel compile and without the read back, which took 1.8 to 2.6 s with the filter):
diff --git a/src/path-tracer-gpu-shader.js b/src/path-tracer-gpu-shader.js
index 15e25e1e..17e901cd 100644
--- a/src/path-tracer-gpu-shader.js
+++ b/src/path-tracer-gpu-shader.js
@@ -1,5 +1,5 @@
import { CACHE_DECLARATIONS, CACHE_OUTPUT, CACHE_RECORD, CACHE_TERMINAL } from './path-tracer-radiance-cache.js';
-import { LIGHT_TREE_FIRST_HIT_LIGHTS, LIGHT_TREE_NODE_TEXELS } from './path-tracer-light-tree.js';
+import { LIGHT_TREE_FIRST_HIT_LIGHTS, LIGHT_TREE_MINIMUM_SHARE, LIGHT_TREE_NODE_TEXELS } from './path-tracer-light-tree.js';
import { SUBSURFACE_FUNCTIONS, SUBSURFACE_LOBE, SUBSURFACE_SPLIT, SUBSURFACE_UNIFORM } from './path-tracer-gpu-subsurface.js';
// The GPU path tracer kernel: a WebGL2 fragment shader that follows the same paths as the CPU tracer in
@@ -118,7 +118,7 @@ int chooseEmitterByTree(vec3 normal, out float probability) {
float totalMinimum = left.y + right.y;
if (!(totalMinimum > 0.0)) return -1;
float leftProbability = left.y / totalMinimum;
- if (totalMaximum > 0.0) leftProbability = 0.5 * (left.x / totalMaximum + leftProbability);
+ if (totalMaximum > 0.0) leftProbability = ${(1 - LIGHT_TREE_MINIMUM_SHARE).toFixed(4)} * (left.x / totalMaximum) + ${LIGHT_TREE_MINIMUM_SHARE.toFixed(4)} * leftProbability;
if (nextRandom() < leftProbability) {
node = int(links.x);
pathProbability *= leftProbability;
diff --git a/src/path-tracer-gpu.js b/src/path-tracer-gpu.js
index 22d4200f..5ca8b2a4 100644
--- a/src/path-tracer-gpu.js
+++ b/src/path-tracer-gpu.js
@@ -1,3 +1,4 @@
+import { resolveLightSelection } from './path-tracer-light-tree.js';
import { buildFragmentSource, VERTEX_SOURCE } from './path-tracer-gpu-shader.js';
import { packAtlas, packEnvironment, packLightTree, packLights, packMaterials, packNodes, packSubsurface, packTriangles, sceneUsesSubsurface } from './path-tracer-gpu-pack.js';
@@ -278,7 +279,8 @@ async function drawSamples(gl, program, width, height, samples, shouldStop) {
}
export async function traceOnGpu(scene, camera, rawOptions, shouldStop) {
- const options = await withBlueNoiseTile(rawOptions);
+ const tiledOptions = await withBlueNoiseTile(rawOptions);
+ const options = { ...tiledOptions, lightSelection: resolveLightSelection(tiledOptions.lightSelection, scene.lights) };
const { gl, gpu } = getContext();
const { program, compileSeconds } = getKernel(sceneUsesSubsurface(scene.materials), false, options);
const { width, height, samples } = options;
diff --git a/src/path-tracer-light-tree.js b/src/path-tracer-light-tree.js
index 61f56f15..69f3669e 100644
--- a/src/path-tracer-light-tree.js
+++ b/src/path-tracer-light-tree.js
@@ -10,6 +10,19 @@ export const LIGHT_TREE_NODE_TEXELS = 4;
// Past this many local lights the tree also draws one light at the first hit; below it the first hit lights from every
// light, as the other selections do.
export const LIGHT_TREE_FIRST_HIT_LIGHTS = 16;
+// The share of a walk step that follows the minimum measure (no angles): it keeps a node the angle test culls reachable, so the
+// choice stays unbiased, but every bit of it is spent on lights that cannot reach the point. The rest follows the maximum measure.
+export const LIGHT_TREE_MINIMUM_SHARE = 0.1;
+
+// With lightSelection "auto" (the default) the tree draws the lights of a scene with more than this many local lights.
+export const LIGHT_TREE_AUTO_LIGHTS = 8;
+
+/** "auto" becomes "tree" for a scene with more than LIGHT_TREE_AUTO_LIGHTS local lights and "uniform" otherwise; other choices stay. */
+export function resolveLightSelection(selection, lights) {
+ if (selection !== 'auto') return selection;
+ const lightCount = lights.points.length + lights.spots.length + lights.areas.length;
+ return lightCount > LIGHT_TREE_AUTO_LIGHTS ? 'tree' : 'uniform';
+}
const LEAF = -1;
const HALF_PI = Math.PI / 2;
@@ -93,9 +106,83 @@ function centroidOf(entry, axis) {
return entry.minimum[axis] + entry.maximum[axis];
}
+const BUCKET_COUNT = 12;
+
+function boxArea(minimum, maximum) {
+ const extent = maximum.map((value, axis) => value - minimum[axis]);
+ const longest = Math.max(...extent, 1e-6);
+ // A point light has a flat or empty box: pad it a little so the area never reaches zero.
+ const padded = extent.map(value => value + longest * 1e-3);
+ return padded[0] * padded[1] + padded[1] * padded[2] + padded[2] * padded[0];
+}
+
+/** The orientation measure M_Omega of Conty and Kulla (equation 4): how much solid angle a cone of spread thetaO, thetaE lights. */
+export function orientationMeasure(thetaO, thetaE) {
+ const thetaW = Math.min(thetaO + thetaE, Math.PI);
+ const wide = 2 * Math.PI * (1 - Math.cos(thetaO));
+ const rim = 0.5 * Math.PI * (2 * thetaW * Math.sin(thetaO) - Math.cos(thetaO - 2 * thetaW) - 2 * thetaO * Math.sin(thetaO) + Math.cos(thetaO));
+ return wide + rim;
+}
+
+function mergeAll(entries) {
+ return entries.reduce((merged, entry) => (merged ? mergeEntries(merged, entry) : entry), null);
+}
+
+function saohCost(entry) {
+ return entry.energy * boxArea(entry.minimum, entry.maximum) * orientationMeasure(entry.thetaO, entry.thetaE);
+}
+
+/**
+ * Splits a group with the surface area orientation heuristic (Conty and Kulla, section 4.2): on each axis the centroids go in
+ * buckets, every bucket boundary is costed as energy times box area times orientation measure of both sides (scaled so a
+ * split across the longest axis is favoured), and the cheapest wins. Returns [left, right]; a degenerate cost falls back to the median.
+ */
+function splitGroup(group) {
+ const bounds = group.reduce((box, entry) => ({
+ minimum: box.minimum.map((value, axis) => Math.min(value, entry.minimum[axis])),
+ maximum: box.maximum.map((value, axis) => Math.max(value, entry.maximum[axis])),
+ }), { minimum: [Infinity, Infinity, Infinity], maximum: [-Infinity, -Infinity, -Infinity] });
+ const longestExtent = Math.max(...bounds.maximum.map((value, axis) => value - bounds.minimum[axis]), 1e-9);
+ let best = null;
+ for (let axis = 0; axis < 3; axis++) {
+ const centroids = group.map(entry => centroidOf(entry, axis));
+ const low = Math.min(...centroids);
+ const high = Math.max(...centroids);
+ if (!(high - low > 1e-9)) continue;
+ const buckets = Array.from({ length: BUCKET_COUNT }, () => []);
+ group.forEach((entry, index) => {
+ const slot = Math.min(BUCKET_COUNT - 1, Math.floor(((centroids[index] - low) / (high - low)) * BUCKET_COUNT));
+ buckets[slot].push(entry);
+ });
+ const extent = bounds.maximum[axis] - bounds.minimum[axis];
+ const lengthScale = longestExtent / Math.max(extent, longestExtent * 1e-3);
+ for (let boundary = 1; boundary < BUCKET_COUNT; boundary++) {
+ const left = buckets.slice(0, boundary).flat();
+ const right = buckets.slice(boundary).flat();
+ if (left.length === 0 || right.length === 0) continue;
+ const cost = lengthScale * (saohCost(mergeAll(left)) + saohCost(mergeAll(right)));
+ if (!best || cost < best.cost) best = { cost, left, right };
+ }
+ }
+ if (best && Number.isFinite(best.cost)) return [best.left, best.right];
+ let splitAxis = 0;
+ let longest = -1;
+ for (let axis = 0; axis < 3; axis++) {
+ const values = group.map(entry => centroidOf(entry, axis));
+ const extent = Math.max(...values) - Math.min(...values);
+ if (extent > longest) {
+ longest = extent;
+ splitAxis = axis;
+ }
+ }
+ const sorted = [...group].sort((first, second) => centroidOf(first, splitAxis) - centroidOf(second, splitAxis));
+ const middle = sorted.length >> 1;
+ return [sorted.slice(0, middle), sorted.slice(middle)];
+}
+
/**
* The tree over `lights` ({ points, spots, areas }), leaves numbered in the order the tracers sample the lights (points,
- * spots, areas). Nodes split the longest centroid axis at the median, so the tree is balanced: depth about log2(count).
+ * spots, areas). Nodes split by the surface area orientation heuristic (splitGroup), so the tree is not balanced: nodes join lights that are near and face the same way.
* Returns { nodeCount, data } where each node is LIGHT_TREE_NODE_FLOATS floats:
* (box minimum, energy) (box maximum, cos thetaO) (cone axis, cos thetaE) (left child or -1, right child, light index, 0).
*/
@@ -115,20 +202,9 @@ export function buildLightTree(lights) {
Object.assign(node, group[0]);
return nodeIndex;
}
- let splitAxis = 0;
- let longest = -1;
- for (let axis = 0; axis < 3; axis++) {
- const values = group.map(entry => centroidOf(entry, axis));
- const extent = Math.max(...values) - Math.min(...values);
- if (extent > longest) {
- longest = extent;
- splitAxis = axis;
- }
- }
- const sorted = [...group].sort((first, second) => centroidOf(first, splitAxis) - centroidOf(second, splitAxis));
- const middle = sorted.length >> 1;
- node.left = build(sorted.slice(0, middle));
- node.right = build(sorted.slice(middle));
+ const [leftGroup, rightGroup] = splitGroup(group);
+ node.left = build(leftGroup);
+ node.right = build(rightGroup);
Object.assign(node, mergeEntries(nodes[node.left], nodes[node.right]));
return nodeIndex;
}
@@ -152,7 +228,7 @@ const importance = { maximum: 0, minimum: 0 };
* What a node is worth to the shading point at (px, py, pz) with surface normal (nx, ny, nz), as two measures: the
* maximum one (energy times the cosines of the best angles the box and cone allow, over the squared distance to the
* nearest point the box may hold) and the minimum one (energy over the squared distance to the farthest, no angles). The
- * walk mixes them half and half, so a node the angle test culls still keeps a chance and the choice stays unbiased.
+ * walk mixes them by LIGHT_TREE_MINIMUM_SHARE, so a node the angle test culls still keeps a chance and the choice stays unbiased.
*/
export function nodeImportance(data, node, px, py, pz, nx, ny, nz) {
const base = node * LIGHT_TREE_NODE_FLOATS;
@@ -191,13 +267,13 @@ export function nodeImportance(data, node, px, py, pz, nx, ny, nz) {
return importance;
}
-/** The chance of taking the left child, mixing the maximum and the minimum measure evenly; -1 when both children are worth nothing. */
+/** The chance of taking the left child, mixing the maximum and the minimum measure; -1 when both children are worth nothing. */
export function leftChildProbability(leftMaximum, leftMinimum, rightMaximum, rightMinimum) {
const totalMaximum = leftMaximum + rightMaximum;
const totalMinimum = leftMinimum + rightMinimum;
if (!(totalMinimum > 0)) return -1;
if (!(totalMaximum > 0)) return leftMinimum / totalMinimum;
- return 0.5 * (leftMaximum / totalMaximum + leftMinimum / totalMinimum);
+ return (1 - LIGHT_TREE_MINIMUM_SHARE) * (leftMaximum / totalMaximum) + LIGHT_TREE_MINIMUM_SHARE * (leftMinimum / totalMinimum);
}
const choice = { lightIndex: -1, probability: 0 };
diff --git a/src/path-tracer-progressive.js b/src/path-tracer-progressive.js
index af4d67b6..c0aeb301 100644
--- a/src/path-tracer-progressive.js
+++ b/src/path-tracer-progressive.js
@@ -1,5 +1,6 @@
import { buildTraceScene } from './path-tracer-scene.js';
import { denoiseRadiance } from './path-tracer-denoise.js';
+import { resolveLightSelection } from './path-tracer-light-tree.js';
import { createCamera, normalizePathTracerOptions, toneMapToRgba8 } from './path-tracer.js';
import {
averageBuffers, createBandState, createTargets, drawOneSample, getContext, getKernel, releaseResources, setSceneUniforms, uploadScene, withBlueNoiseTile,
@@ -23,6 +24,7 @@ export async function createProgressiveTracer(scene, rawOptions = {}, { resoluti
const { gl, gpu } = getContext();
const { width, height } = options;
let traceScene = null;
+ let sceneOptions = options;
let program = null;
let compileSeconds = 0;
let lightCount = 0;
@@ -41,17 +43,18 @@ export async function createProgressiveTracer(scene, rawOptions = {}, { resoluti
const loadScene = (parts, environment) => {
releaseResources(gl);
traceScene = buildTraceScene(parts, environment);
- const kernel = getKernel(sceneUsesSubsurface(traceScene.materials), false, options);
+ sceneOptions = { ...options, lightSelection: resolveLightSelection(options.lightSelection, traceScene.lights) };
+ const kernel = getKernel(sceneUsesSubsurface(traceScene.materials), false, sceneOptions);
program = kernel.program;
compileSeconds = kernel.compileSeconds;
gl.useProgram(program);
- lightCount = uploadScene(gl, program, traceScene, options).lightCount;
+ lightCount = uploadScene(gl, program, traceScene, sceneOptions).lightCount;
createTargets(gl, width, height);
};
const loadCamera = camera => {
const view = createCamera(camera, width, height);
- setSceneUniforms(gl, program, traceScene, view, options, lightCount);
+ setSceneUniforms(gl, program, traceScene, view, sceneOptions, lightCount);
};
const clearTargets = () => {
diff --git a/src/path-tracer-webgpu-kernel.js b/src/path-tracer-webgpu-kernel.js
index 251c20a0..19307f16 100644
--- a/src/path-tracer-webgpu-kernel.js
+++ b/src/path-tracer-webgpu-kernel.js
@@ -7,6 +7,7 @@
// Volume fog and the subsurface walk (path-tracer-webgpu-medium.js) are spliced into the megakernel only for a scene that uses them.
// The megakernel has a texel entry point (`bakeTexels`) that starts a path at every lightmap texel, for the light bake.
+import { LIGHT_TREE_FIRST_HIT_LIGHTS, LIGHT_TREE_MINIMUM_SHARE } from './path-tracer-light-tree.js';
import { SUBSURFACE_FUNCTIONS, VOLUME_FUNCTIONS } from './path-tracer-webgpu-medium.js';
export const WORKGROUP_SIZE = 8;
@@ -779,6 +780,93 @@ fn pointLightFalloff(distanceSquared: f32, range: f32, radius: f32) -> f32 {
return cutoff / max(distanceSquared, radius * radius);
}
+// The light tree (path-tracer-light-tree.js) follows the light table in the same buffer, four vectors a node; the word
+// params.cameraAndClamp.w holds the index of its first vector, 0 when the scene draws lights uniformly.
+const LIGHT_TREE_TEXELS: i32 = 4;
+const LIGHT_TREE_FIRST_HIT_LIGHTS: i32 = ${LIGHT_TREE_FIRST_HIT_LIGHTS};
+const LIGHT_TREE_MINIMUM_SHARE: f32 = ${LIGHT_TREE_MINIMUM_SHARE.toFixed(4)};
+var<private> treeChoiceProbability: f32 = 1.0;
+
+fn lightTreeActive() -> bool {
+ return params.cameraAndClamp.w > 0.0;
+}
+
+// Past this many lights the tree also draws one light at the first hit; below it the first hit lights from every emitter.
+fn firstHitByTree() -> bool {
+ return lightTreeActive() && params.sizeBouncesLights.w > LIGHT_TREE_FIRST_HIT_LIGHTS;
+}
+
+// The maximum and the minimum importance measure of one tree node for the current hit point.
+fn lightTreeImportance(node: i32, normal: vec3<f32>) -> vec2<f32> {
+ let base = i32(params.cameraAndClamp.w) + node * LIGHT_TREE_TEXELS;
+ let minimumEnergy = lights[base];
+ let maximumCosineO = lights[base + 1];
+ let axisCosineE = lights[base + 2];
+ let energy = minimumEnergy.w;
+ let delta = 0.5 * (minimumEnergy.xyz + maximumCosineO.xyz) - hitPoint;
+ let halfDiagonal = 0.5 * length(maximumCosineO.xyz - minimumEnergy.xyz);
+ let centerDistance = length(delta);
+ let nearest = max(max(centerDistance, halfDiagonal), 1e-4);
+ let farthest = centerDistance + halfDiagonal;
+ let minimumMeasure = energy / max(farthest * farthest, 1e-8);
+ if (centerDistance <= halfDiagonal) { return vec2<f32>(energy / (nearest * nearest), minimumMeasure); }
+ let toward = delta / centerDistance;
+ let ratio = halfDiagonal / centerDistance;
+ let thetaU = acos(sqrt(max(0.0, 1.0 - ratio * ratio)));
+ let theta = acos(clamp(-dot(axisCosineE.xyz, toward), -1.0, 1.0));
+ let thetaO = acos(clamp(maximumCosineO.w, -1.0, 1.0));
+ let thetaE = acos(clamp(axisCosineE.w, -1.0, 1.0));
+ let thetaPrime = max(theta - thetaO - thetaU, 0.0);
+ if (thetaPrime >= thetaE) { return vec2<f32>(0.0, minimumMeasure); }
+ let surfaceTheta = acos(clamp(dot(normal, toward), -1.0, 1.0));
+ let surfaceCosine = max(cos(max(surfaceTheta - thetaU, 0.0)), 0.0);
+ return vec2<f32>(energy * cos(thetaPrime) * surfaceCosine / (nearest * nearest), minimumMeasure);
+}
+
+// Draws the emitter of a later hit and sets selectionProbability to the chance of the draw. Without a tree it is the uniform
+// choice; with one the sun and the sky keep their uniform share and a local light is reached by walking the tree from the
+// root. Returns -1 when no light is worth sampling.
+fn chooseEmitter(normal: vec3<f32>) -> i32 {
+ let emitterCount = params.emittersFlagsSample.x;
+ let uniformShare = 1.0 / f32(emitterCount);
+ let emitter = min(i32(floor(nextRandom() * f32(emitterCount))), emitterCount - 1);
+ selectionProbability = uniformShare;
+ if (!lightTreeActive()) { return emitter; }
+ let firstLightEmitter = select(0, 1, params.emittersFlagsSample.y != 0);
+ let lightIndex = emitter - firstLightEmitter;
+ let lightCount = params.sizeBouncesLights.w;
+ if (lightIndex < 0 || lightIndex >= lightCount) { return emitter; }
+ var node = 0;
+ var pathProbability = 1.0;
+ for (var step = 0; step < 64; step++) {
+ let links = lights[i32(params.cameraAndClamp.w) + node * LIGHT_TREE_TEXELS + 3];
+ if (links.x < 0.0) {
+ selectionProbability = f32(lightCount) * uniformShare * pathProbability;
+ return firstLightEmitter + i32(links.z);
+ }
+ let left = lightTreeImportance(i32(links.x), normal);
+ let right = lightTreeImportance(i32(links.y), normal);
+ let totalMaximum = left.x + right.x;
+ let totalMinimum = left.y + right.y;
+ if (!(totalMinimum > 0.0)) { return -1; }
+ var leftProbability = left.y / totalMinimum;
+ if (totalMaximum > 0.0) { leftProbability = (1.0 - LIGHT_TREE_MINIMUM_SHARE) * (left.x / totalMaximum) + LIGHT_TREE_MINIMUM_SHARE * leftProbability; }
+ if (nextRandom() < leftProbability) {
+ node = i32(links.x);
+ pathProbability *= leftProbability;
+ } else {
+ node = i32(links.y);
+ pathProbability *= 1.0 - leftProbability;
+ }
+ }
+ return -1;
+}
+
+// True when the hit lights from every emitter: the first hit, unless the tree draws one there too, and any hit with one emitter.
+fn lightsFromEveryEmitter(depth: i32, emitterCount: i32) -> bool {
+ return (depth == 0 && !firstHitByTree()) || emitterCount <= 1;
+}
+
// Draws one emitter's contribution into the pending shadow ray: emitter 0 is the sun when there is one, then the lights, then the sky.
fn sampleEmitter(depth: i32, normal: vec3<f32>, emitter: i32) {
var distance = 0.0;
@@ -931,7 +1019,7 @@ export const buildMegakernelSource = ({ hasVolume = false, hasSubsurface = false
${realtime ? realtime.declarations + realtime.addLights : `// The first hit lights from every emitter; later hits draw one, and divide by the chance of drawing it.
fn addLights(depth: i32, normal: vec3<f32>) {
let emitterCount = params.emittersFlagsSample.x;
- if (depth == 0 || emitterCount <= 1) {
+ if (lightsFromEveryEmitter(depth, emitterCount)) {
selectionProbability = 1.0;
for (var emitter = 0; emitter < emitterCount; emitter++) {
sampleEmitter(depth, normal, emitter);
@@ -939,9 +1027,13 @@ fn addLights(depth: i32, normal: vec3<f32>) {
}
return;
}
+ let chosen = chooseEmitter(normal);
+ if (chosen >= 0) {
+ sampleEmitter(depth, normal, chosen);
+ flushShadowRay();
+ }
+ // The sky is drawn with its uniform share whatever light was chosen: that share weighs the next escape ray.
selectionProbability = 1.0 / f32(emitterCount);
- sampleEmitter(depth, normal, i32(floor(nextRandom() * f32(emitterCount))));
- flushShadowRay();
}`}
${hasSubsurface ? SUBSURFACE_FUNCTIONS : ''}
fn tracePath(origin: vec3<f32>, startDirection: vec3<f32>, pixel: u32, sampleIndex: u32) {
@@ -1094,7 +1186,7 @@ fn materialCount() -> u32 {
// How many shadow rays a path casts at this depth: every emitter at the first hit, one afterwards.
fn emitterSlotCount(depth: i32) -> u32 {
let emitterCount = u32(max(params.emittersFlagsSample.x, 0));
- if (depth == 0 || emitterCount <= 1u) { return emitterCount; }
+ if (lightsFromEveryEmitter(depth, i32(emitterCount))) { return emitterCount; }
return 1u;
}
@@ -1283,7 +1375,7 @@ fn shadePaths(@builtin(global_invocation_id) id: vec3<u32>) {
} else {
prepareSurface(normal, -direction);
let emitterCount = params.emittersFlagsSample.x;
- if (depth == 0 || emitterCount <= 1) {
+ if (lightsFromEveryEmitter(depth, emitterCount)) {
selectionProbability = 1.0;
for (var emitter = 0; emitter < emitterCount; emitter++) {
shadowPending = false;
@@ -1291,10 +1383,11 @@ fn shadePaths(@builtin(global_invocation_id) id: vec3<u32>) {
storeShadowRecord(path, u32(emitter));
}
} else {
- selectionProbability = 1.0 / f32(emitterCount);
+ let chosen = chooseEmitter(normal);
shadowPending = false;
- sampleEmitter(depth, normal, i32(floor(nextRandom() * f32(emitterCount))));
+ if (chosen >= 0) { sampleEmitter(depth, normal, chosen); }
storeShadowRecord(path, 0u);
+ selectionProbability = 1.0 / f32(emitterCount);
}
}
var alive = depth < params.sizeBouncesLights.z;
diff --git a/src/path-tracer-webgpu.js b/src/path-tracer-webgpu.js
index 8fe25e92..15e95c37 100644
--- a/src/path-tracer-webgpu.js
+++ b/src/path-tracer-webgpu.js
@@ -1,5 +1,6 @@
import { buildMegakernelSource, PATH_STATE_VECTORS, WAVEFRONT_SOURCE, WAVEFRONT_WORKGROUP_SIZE, WORKGROUP_SIZE } from './path-tracer-webgpu-kernel.js';
-import { packAtlas, packEnvironment, packLights, packMaterials, packNodes, packSubsurface, packTriangles, sceneUsesSubsurface } from './path-tracer-gpu-pack.js';
+import { resolveLightSelection } from './path-tracer-light-tree.js';
+import { packAtlas, packEnvironment, packLightTree, packLights, packMaterials, packNodes, packSubsurface, packTriangles, sceneUsesSubsurface } from './path-tracer-gpu-pack.js';
// The WebGPU backend of the path tracer (issue #625): the same scene tables, camera, options and random numbers as the
// WebGL2 backend (path-tracer-gpu.js) go in, the same buffers come out. The tracer is WGSL compute, so a page needs
@@ -114,9 +115,17 @@ function atlasWords(atlas) {
return new Uint32Array(atlas.data.buffer, atlas.data.byteOffset, Math.floor(atlas.data.byteLength / 4));
}
-function uploadScene(device, scene) {
+function uploadScene(device, scene, requestedLightSelection = 'uniform') {
const atlas = packAtlas(scene.materials);
const lights = packLights(scene.lights);
+ // With the light tree the node table follows the light table in the same buffer; treeBase is the vector index of its first node.
+ const useLightTree = resolveLightSelection(requestedLightSelection, scene.lights) === 'tree' && lights.count > 1;
+ const lightTableData = lights.table.data;
+ const lightTreeBase = useLightTree ? lightTableData.length / 4 : 0;
+ const lightTreeData = useLightTree ? packLightTree(scene.lights).data : new Float32Array(0);
+ const lightsWithTree = new Float32Array(lightTableData.length + lightTreeData.length);
+ lightsWithTree.set(lightTableData);
+ lightsWithTree.set(lightTreeData, lightTableData.length);
const environment = packEnvironment(scene.environment);
const environmentTables = new Float32Array(environment ? environment.height + environment.width * environment.height : 4);
if (environment) {
@@ -134,12 +143,12 @@ function uploadScene(device, scene) {
createStorageBuffer(device, packNodes(scene.bvh).data, 'bvh nodes'),
createStorageBuffer(device, packTriangles(scene).data, 'triangles'),
createStorageBuffer(device, materialsWithSubsurface, 'materials'),
- createStorageBuffer(device, lights.table.data, 'lights'),
+ createStorageBuffer(device, lightsWithTree, 'lights'),
createStorageBuffer(device, atlasWords(atlas), 'texture atlas'),
createStorageBuffer(device, environment?.colors ?? new Float32Array(4), 'environment colors'),
createStorageBuffer(device, environmentTables, 'environment tables'),
];
- return { buffers, lightCount: lights.count, atlasWidth: atlas.width, subsurfaceOffset };
+ return { buffers, lightCount: lights.count, lightTreeBase, atlasWidth: atlas.width, subsurfaceOffset };
}
/** The words of one uniform block: the 12 vectors of the megakernel parameters, then the tile and shadow slot words. */
@@ -158,7 +167,7 @@ function createParameterTemplate(scene, camera, options, uploaded, emitterCount)
floats.set([...(sun?.color ?? [0, 0, 0]), Math.cos(Math.PI / 360)], 20);
floats.set([environment?.width ?? 1, environment?.height ?? 1, environment?.intensity ?? 1, environment?.total ?? 1], 24);
floats.set([environment?.cosine ?? 1, environment?.sine ?? 0, scene.surfaceOffset, scene.farDistance], 28);
- floats.set([camera.halfWidth, camera.halfHeight, options.fireflyClamp, 0], 32);
+ floats.set([camera.halfWidth, camera.halfHeight, options.fireflyClamp, uploaded.lightTreeBase], 32);
integers.set([options.width, options.height, options.bounces, uploaded.lightCount], 36);
integers.set([emitterCount, sun ? 1 : 0, environment ? 1 : 0, 0], 40);
unsigned.set([options.seed >>> 0, uploaded.atlasWidth, uploaded.subsurfaceOffset, 0], 44);
@@ -271,7 +280,7 @@ export async function traceOnWebGpu(scene, camera, options, shouldStop) {
if (planeBytes * 4 > device.limits.maxStorageBufferBindingSize) {
throw new RangeError(`A ${width} by ${height} image is too large for this WebGPU adapter. Lower the size or use backend "gpu".`);
}
- const uploaded = uploadScene(device, scene);
+ const uploaded = uploadScene(device, scene, options.lightSelection);
const emitterCount = (scene.lights.sun ? 1 : 0) + uploaded.lightCount + (scene.environment ? 1 : 0);
const shadowSlots = Math.max(emitterCount, 1);
const materialCount = scene.materials.length;
diff --git a/src/path-tracer.js b/src/path-tracer.js
index f5721f48..3180da1b 100644
--- a/src/path-tracer.js
+++ b/src/path-tracer.js
@@ -8,7 +8,7 @@ import {
buildFrame, createSurface, environmentPdf, environmentRadiance, evaluateSurface, luminance, mirrorWeight, prepareSurface,
roughnessToAlpha, sampleEnvironment, sampleGlass, sampleSurface, setWhiteDiffuse, splitSubsurface,
} from './path-tracer-shading.js';
-import { buildLightTree, chooseLightFromTree, LIGHT_TREE_FIRST_HIT_LIGHTS } from './path-tracer-light-tree.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';
@@ -73,7 +73,7 @@ function boundedNumber(options, name) {
// capabilities file stays out of this bundle.
export const PATH_TRACER_DENOISERS = Object.freeze(['wavelet', 'oidn', 'none']);
export const SAMPLING_PATTERNS = Object.freeze(['random', 'blue-noise-first']);
-export const LIGHT_SELECTIONS = Object.freeze(['uniform', 'importance', 'tree']);
+export const LIGHT_SELECTIONS = Object.freeze(['auto', 'uniform', 'importance', 'tree']);
/**
* `denoise` is true (the wavelet filter) or false (none), or a name: "wavelet", "oidn" or "none". "oidn" is the optional
@@ -107,7 +107,7 @@ export function normalizePathTracerOptions(options = {}) {
look: options.look ?? null,
backend: options.backend ?? 'cpu',
samplingPattern: options.samplingPattern ?? 'random',
- lightSelection: options.lightSelection ?? 'uniform',
+ lightSelection: options.lightSelection ?? 'auto',
};
result.denoise = result.denoiser !== 'none';
if (!VIEW_TRANSFORM_NAMES.includes(result.viewTransform)) throw new RangeError(`Path tracer viewTransform must be one of ${VIEW_TRANSFORM_NAMES.join(', ')}.`);
@@ -118,10 +118,7 @@ export function normalizePathTracerOptions(options = {}) {
throw new RangeError('Path tracer samplingPattern "blue-noise-first" needs backend "gpu"; the CPU reference and the WebGPU tracer draw random samples.');
}
if (result.lightSelection === 'importance' && result.backend !== 'gpu') {
- throw new RangeError('Path tracer lightSelection "importance" needs backend "gpu"; the CPU reference and the WebGPU tracer pick lights uniformly.');
- }
- if (result.lightSelection === 'tree' && result.backend === 'webgpu') {
- throw new RangeError('Path tracer lightSelection "tree" needs backend "cpu" or "gpu"; the WebGPU tracer picks lights uniformly.');
+ throw new RangeError('Path tracer lightSelection "importance" needs backend "gpu"; the CPU reference and the WebGPU tracer pick lights uniformly; "tree" also runs on the WebGPU tracer.');
}
if (result.width * result.height > MAX_TRACE_PIXELS) throw new RangeError(`A path trace takes at most ${MAX_TRACE_PIXELS} pixels.`);
if (result.width * result.height * result.samples * (result.bounces + 1) > MAX_TRACE_RAY_WORK) throw new RangeError('This path trace would need too much ray work: lower the size, samples or bounces.');
@@ -641,7 +638,7 @@ function createPathTracer(scene, options) {
}
const lightCount = lights.points.length + lights.spots.length + lights.areas.length;
- const useLightTree = options.lightSelection === 'tree' && lightCount > 1;
+ const useLightTree = resolveLightSelection(options.lightSelection, lights) === 'tree' && lightCount > 1;
const lightTree = useLightTree ? buildLightTree(lights) : null;
const drawRandom = () => random.next();
function sampleLightByIndex(depth, normal, index) {
diff --git a/tests/path-tracer-light-tree.test.js b/tests/path-tracer-light-tree.test.js
index afba9e15..04089f6e 100644
--- a/tests/path-tracer-light-tree.test.js
+++ b/tests/path-tracer-light-tree.test.js
@@ -6,7 +6,7 @@ import { renderPathTracedImage } from '../src/path-tracer.js';
import { packLightTree } from '../src/path-tracer-gpu-pack.js';
import { buildFragmentSource } from '../src/path-tracer-gpu-shader.js';
import {
- buildLightTree, chooseLightFromTree, leftChildProbability, LIGHT_TREE_NODE_FLOATS, mergeCones, nodeImportance,
+ buildLightTree, chooseLightFromTree, leftChildProbability, LIGHT_TREE_MINIMUM_SHARE, LIGHT_TREE_NODE_FLOATS, mergeCones, nodeImportance,
} from '../src/path-tracer-light-tree.js';
function pointLight(position, intensity = 1) {
@@ -89,7 +89,8 @@ test('a node is worth more when it is near, bright and turned toward the point,
});
test('the left chance mixes the two measures and falls back to the minimum measure', () => {
- assert.equal(leftChildProbability(3, 1, 1, 1), 0.5 * (0.75 + 0.5));
+ const minimumShare = LIGHT_TREE_MINIMUM_SHARE;
+ assert.ok(Math.abs(leftChildProbability(3, 1, 1, 1) - ((1 - minimumShare) * 0.75 + minimumShare * 0.5)) < 1e-12);
assert.equal(leftChildProbability(0, 1, 0, 3), 0.25);
assert.equal(leftChildProbability(0, 0, 0, 0), -1);
});
@@ -148,3 +149,23 @@ test('the CPU tracer with the light tree keeps the mean radiance of the uniform
assert.ok(Math.abs(ratio - 1) < 0.03, `${lightCount} lights: ratio ${ratio}`);
}
});
+
+test('the surface area orientation split keeps two far apart clusters of lights in separate subtrees', () => {
+ const near = Array.from({ length: 4 }, (_, index) => pointLight([index * 0.3, 1, 0], 2));
+ const far = Array.from({ length: 4 }, (_, index) => pointLight([40 + index * 0.3, 1, 0], 2));
+ const tree = buildLightTree({ points: [...near, ...far], spots: [], areas: [] });
+ const base = node => node * LIGHT_TREE_NODE_FLOATS;
+ const left = tree.data[base(0) + 12];
+ const right = tree.data[base(0) + 13];
+ const leftMaximumX = tree.data[base(left) + 4];
+ const rightMinimumX = tree.data[base(right)];
+ assert.ok(leftMaximumX < 10 && rightMinimumX > 30, `children split at ${leftMaximumX} and ${rightMinimumX}`);
+});
+
+test('the WebGPU kernels carry the tree walk', async () => {
+ const { buildMegakernelSource, WAVEFRONT_SOURCE } = await import('../src/path-tracer-webgpu-kernel.js');
+ for (const source of [buildMegakernelSource(), WAVEFRONT_SOURCE]) {
+ assert.ok(source.includes('fn chooseEmitter'));
+ assert.ok(source.includes('lightsFromEveryEmitter'));
+ }
+});
diff --git a/tests/path-tracer-progressive.test.js b/tests/path-tracer-progressive.test.js
index 540499aa..c17732e0 100644
--- a/tests/path-tracer-progressive.test.js
+++ b/tests/path-tracer-progressive.test.js
@@ -48,7 +48,7 @@ test('every channel of the tile holds each value equally often, and its blurred
test('the options choose the sampling pattern and the light choice, and the CPU reference keeps its defaults', () => {
const defaults = normalizePathTracerOptions({});
assert.equal(defaults.samplingPattern, 'random');
- assert.equal(defaults.lightSelection, 'uniform');
+ assert.equal(defaults.lightSelection, 'auto');
const gpu = normalizePathTracerOptions({ backend: 'gpu', samplingPattern: 'blue-noise-first', lightSelection: 'importance' });
assert.equal(gpu.samplingPattern, 'blue-noise-first');
assert.equal(gpu.lightSelection, 'importance');
@@ -56,7 +56,8 @@ test('the options choose the sampling pattern and the light choice, and the CPU
assert.throws(() => normalizePathTracerOptions({ lightSelection: 'importance' }), /needs backend "gpu"/);
assert.throws(() => normalizePathTracerOptions({ backend: 'gpu', lightSelection: 'bogus' }), /lightSelection must be one of/);
assert.equal(normalizePathTracerOptions({ lightSelection: 'tree' }).lightSelection, 'tree');
- assert.throws(() => normalizePathTracerOptions({ backend: 'webgpu', lightSelection: 'tree' }), /needs backend/);
+ assert.throws(() => normalizePathTracerOptions({ backend: 'webgpu', lightSelection: 'importance' }), /needs backend/);
+ assert.equal(normalizePathTracerOptions({ backend: 'webgpu', lightSelection: 'tree' }).lightSelection, 'tree');
});
test('the kernel compiles the new paths only when asked, so the default kernel keeps its pixels', () => {