3D engine that AI agents drive
Add a light tree to the path tracer (issue #623)
Nguyen Xuan An576e035736ab
diff --git a/bench/reference/progressive-compare.mjs b/bench/reference/progressive-compare.mjsindex d4e36080..3a48780d 100644--- a/bench/reference/progressive-compare.mjs+++ b/bench/reference/progressive-compare.mjs@@ -1,5 +1,5 @@// 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|both]+// 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]// 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.@@ -25,6 +25,7 @@ const VARIANT_OPTIONS = {random: {},blue: { samplingPattern: 'blue-noise-first' },importance: { lightSelection: 'importance' },+ tree: { lightSelection: 'tree' },both: { samplingPattern: 'blue-noise-first', lightSelection: 'importance' },};const variantNames = valueAfter('--variant', 'random').split(',');diff --git a/bench/reference/scenes.js b/bench/reference/scenes.jsindex 680109ca..e3af3c61 100644--- a/bench/reference/scenes.js+++ b/bench/reference/scenes.js@@ -840,6 +840,34 @@ export const REFERENCE_SCENES = {};},+ // Issue #623: a 36 m corridor with 24 lamps (16 point, 8 spot) along the ceiling and nothing else lighting it, so most lamps are far from+ // any point and a light tree has something to choose. The lamps do not cast shadow maps (the rasterizer's atlas holds 24 tiles); the path tracer and Cycles shadow every light.+ async 'many-lights'() {+ const lighting = constantLighting(0.01);+ const cube = box(0, 1);+ const wall = { color: [0.72, 0.7, 0.66], roughness: 0.9 };+ const parts = [+ part('corridor-floor', cube, [0, -0.05, 0], [4, 0.1, 36], { color: [0.5, 0.45, 0.4], roughness: 0.6 }),+ part('corridor-ceiling', cube, [0, 3.05, 0], [4, 0.1, 36], wall),+ part('corridor-left', cube, [-2.05, 1.5, 0], [0.1, 3.2, 36], { ...wall, color: [0.6, 0.35, 0.3] }),+ part('corridor-right', cube, [2.05, 1.5, 0], [0.1, 3.2, 36], { ...wall, color: [0.3, 0.42, 0.58] }),+ part('corridor-end', cube, [0, 1.5, -18.05], [4, 3.2, 0.1], wall),+ part('pillar-near', cube, [-1.2, 0.8, 4], [0.5, 1.6, 0.5], { color: [0.6, 0.6, 0.65], roughness: 0.5 }),+ part('ball', sphere(48, 32), [0.8, 0.5, 1], [0.5, 0.5, 0.5], { color: [0.8, 0.25, 0.2], roughness: 0.3 }),+ part('block-far', cube, [0.7, 0.4, -7], [0.8, 0.8, 0.8], { color: [0.2, 0.45, 0.75], roughness: 0.6 }),+ ];+ const lampPosition = index => [index % 2 === 0 ? -0.8 : 0.8, 2.8, 15 - index * 1.4];+ const lampColor = index => (index % 3 === 0 ? [1, 0.75, 0.5] : index % 3 === 1 ? [0.85, 0.9, 1] : [1, 0.95, 0.85]);+ const lampIndices = Array.from({ length: 24 }, (_, index) => index);+ const pointLights = lampIndices.filter(index => index % 3 !== 2).map(index => ({ position: lampPosition(index), color: lampColor(index), intensity: 3, radius: 0.05, castShadow: false }));+ const spotLights = lampIndices.filter(index => index % 3 === 2).map(index => ({ position: lampPosition(index), direction: [0, -1, 0], angle: 1, penumbra: 0.5, color: lampColor(index), intensity: 6, radius: 0.05, castShadow: false }));+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { pointLights, spotLights }),+ camera: { eye: [0, 1.5, 17], target: [0, 1.2, -8], up: [0, 1, 0], fov: 55, near: 0.05, far: 80 },+ };+ },+// A street 140 m long under the sun. A single shadow map has to cover the whole street, so its texels are about 8 cm wide;// cascades give the cars and lamp posts near the camera 1 to 2 cm texels. harness.js draws it with one map by default and// with cascades when run.mjs gets --cascades <count>.diff --git a/changes/623-tree.md b/changes/623-tree.mdnew file mode 100644index 00000000..37cc88ab--- /dev/null+++ b/changes/623-tree.md@@ -0,0 +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)diff --git a/changes/623-tree.size.md b/changes/623-tree.size.mdnew file mode 100644index 00000000..5667b305--- /dev/null+++ b/changes/623-tree.size.md@@ -0,0 +1,7 @@+- entry:path-tracer: the light tree builder and walk (about 1.7 KB gzip) let the CPU reference match the GPU light tree; it is the only way to draw many lights with fewer shadow rays+- entry:path-tracer+lazy: the light tree builder and walk, plus the GLSL walk in the lazy kernel+- entry:path-tracer-progressive: the light tree builder and the GLSL walk of the GPU kernel (about 2.2 KB gzip)+- entry:path-tracer-progressive+lazy: the light tree builder and the GLSL walk of the GPU kernel+- entry:path-tracer-realtime: the shared GPU kernel source carries the light tree walk, a branch the real-time path leaves off+- entry:path-tracer-realtime+lazy: the shared GPU kernel source carries the light tree walk+- entry:light-bake-gpu+lazy: the shared GPU kernel source carries the light tree walk, a branch the bake leaves offdiff --git a/docs/path-tracer.md b/docs/path-tracer.mdindex 1990ce07..508c5196 100644--- a/docs/path-tracer.md+++ b/docs/path-tracer.md@@ -136,10 +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.-Two GPU options, both off by default, so the default pixels do not change (the CPU reference rejects them):+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):- `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 the light tree of Conty and Kulla (Cycles `light/tree.h`) nor ReSTIR; a scene with one local light or none draws the same pixels as before.+- `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.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):@@ -152,6 +153,10 @@ The still of `spot-area` took 60.5 s including 29.9 s of kernel compile. Blue noLight choice at equal samples (16 and 64) on the 16 path tracer scenes: 12 scenes have one local light or none and are identical. Better: `lit-interior` 0.0769 to 0.0572 at 64 (0.1318 to 0.0884 at 16), `spot-area` 0.0262 to 0.0224, `light-linking` 0.0291 to 0.0273 at 16. Not better: `brick-room` 0.2587 to 0.2686 at 64 and `light-linking` 0.0213 to 0.0217 at 64. In `brick-room` both choices score worse at 64 than at 16 (0.2491 and 0.2499 at 16), so the converged image is further from Cycles and the score cannot judge the noise; the criterion "no worse on every scene" is therefore not met by this measure, which is why the option stays off. `bench/reference/progressive-compare.mjs` and `progressive-score.py` made the numbers.+The light tree on the same 16 scenes (FLIP against Cycles, 16 and 64 samples, one run each, 960 by 540, denoised; `--variant random,importance,tree`): 12 scenes have one local light or none and are identical to uniform. Better or equal to uniform: `lit-interior` 0.1318 (uniform) to 0.0885 at 16 and 0.0769 to 0.0574 at 64 (importance 0.0884 and 0.0572), `spot-area` 0.0415 to 0.0340 and 0.0262 to 0.0221 (importance 0.0345 and 0.0224), `light-linking` 0.0291 to 0.0280 at 16. Worse: `brick-room` 0.2491 to 0.2506 at 16 and 0.2587 to 0.2692 at 64 (importance 0.2499 and 0.2686), and `light-linking` 0.0213 to 0.0220 at 64. So the tree is not the default: it loses on `brick-room` and by 0.0007 on `light-linking`, as the flat importance choice does. In `brick-room` the score rises with the sample count for both draws (uniform 0.2587 at 64 and 0.2751 at 256, tree 0.2692 and 0.2796), so the error against Cycles there is a difference the sampling does not fix, and the gap between the draws shrinks from 0.0105 to 0.0045 as the noise goes; that is why the tree's loss is read as the denoiser blurring noise that happened to land nearer Cycles (inferred, not isolated). `light-linking` ignores its light masks when it picks.++The scene that shows the gain is `many-lights` (`bench/reference/scenes.js`, issue #623): a 36 m corridor lit only by 24 ceiling lamps, 16 point and 8 spot. FLIP against Cycles at 960 by 540, 16 and 64 samples: uniform 0.1926 and 0.1471, importance 0.0594 and 0.0688, tree 0.0710 and 0.0617. One full size sample (median of 20 on the RTX 3060, shared machine) takes 72 ms with the uniform draw, 88 ms with importance (it sums every light at every hit) and 38 ms with the tree, because the first hit traces one shadow ray instead of 24; 64 steps took 15.7 s, 11.5 s and 12.4 s including the kernel compile and the read back of the checkpoints. Importance wins at 16 samples, the tree at 64, and the tree costs about half the time per sample.+## Real-time hybrid view (issue #624)`67js/addons/path-tracer-realtime` (`createRealtimeTracer(scene, { width, height, bounces, ... })`, then `frame(camera)` for every picture) draws the WebGL2 tracer fast enough to move the camera. It shares the WebGL2 context of the GPU still, so one render at a time owns it, and it draws to `canvas` (an `OffscreenCanvas` or a canvas element, 8 bit, ACES view transform). `readFrame()` returns the same picture as bytes. The pieces, each in its own module so they can move to the WebGPU backend:diff --git a/src/path-tracer-gpu-pack.js b/src/path-tracer-gpu-pack.jsindex e231ba44..373a8043 100644--- a/src/path-tracer-gpu-pack.js+++ b/src/path-tracer-gpu-pack.js@@ -1,4 +1,5 @@import { DATA_TEXTURE_WIDTH, TRIANGLE_TEXELS, MATERIAL_TEXELS, LIGHT_TEXELS } from './path-tracer-gpu-shader.js';+import { buildLightTree, LIGHT_TREE_NODE_TEXELS } from './path-tracer-light-tree.js';import { SUBSURFACE_TEXELS } from './path-tracer-gpu-subsurface.js';// Lays a traced scene (path-tracer-scene.js) out as the float textures the GPU kernel reads. Everything here is plain@@ -183,6 +184,14 @@ export function packLights(lights) {return { table, count: entries.length };}+/** The light tree (path-tracer-light-tree.js) as a table: four texels per node, in the node order of the tree. */+export function packLightTree(lights) {+ const tree = buildLightTree(lights);+ const table = createTable(Math.max(1, tree.nodeCount) * LIGHT_TREE_NODE_TEXELS);+ table.data.set(tree.data);+ return table;+}+/** The map as RGBA32F plus normalised cumulative tables, so the shader compares them with a unit random number. */export function packEnvironment(environment) {if (!environment) return null;diff --git a/src/path-tracer-gpu-shader.js b/src/path-tracer-gpu-shader.jsindex dca1c73f..1f3a3aa2 100644--- a/src/path-tracer-gpu-shader.js+++ b/src/path-tracer-gpu-shader.js@@ -1,4 +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 { 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@@ -62,7 +63,75 @@ const TEXEL_MAIN = `void main() {if (texelIndex >= uTexelCount) rayDirection = normal;tracePath(origin, rayDirection, pixel, sampleIndex);`;-const buildSource = (hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache) => `#version 300 es+// The light tree walk of path-tracer-light-tree.js (nodeImportance, leftChildProbability, chooseLightFromTree), four texels a node.+const LIGHT_TREE_FUNCTIONS = `+/** The maximum and the minimum importance measure of one tree node for the current hit point. */+vec2 lightTreeImportance(int node, vec3 normal) {+ int base = node * LIGHT_TREE_TEXELS;+ vec4 minimumEnergy = fetchData(uLightTree, base);+ vec4 maximumCosineO = fetchData(uLightTree, base + 1);+ vec4 axisCosineE = fetchData(uLightTree, base + 2);+ float energy = minimumEnergy.w;+ vec3 delta = 0.5 * (minimumEnergy.xyz + maximumCosineO.xyz) - hitPoint;+ float halfDiagonal = 0.5 * length(maximumCosineO.xyz - minimumEnergy.xyz);+ float centerDistance = length(delta);+ float nearest = max(max(centerDistance, halfDiagonal), 1e-4);+ float farthest = centerDistance + halfDiagonal;+ float minimumMeasure = energy / max(farthest * farthest, 1e-8);+ if (centerDistance <= halfDiagonal) return vec2(energy / (nearest * nearest), minimumMeasure);+ vec3 toward = delta / centerDistance;+ float ratio = halfDiagonal / centerDistance;+ float thetaU = acos(sqrt(max(0.0, 1.0 - ratio * ratio)));+ float theta = acos(clamp(-dot(axisCosineE.xyz, toward), -1.0, 1.0));+ float thetaO = acos(clamp(maximumCosineO.w, -1.0, 1.0));+ float thetaE = acos(clamp(axisCosineE.w, -1.0, 1.0));+ float thetaPrime = max(theta - thetaO - thetaU, 0.0);+ if (thetaPrime >= thetaE) return vec2(0.0, minimumMeasure);+ float surfaceTheta = acos(clamp(dot(normal, toward), -1.0, 1.0));+ float surfaceCosine = max(cos(max(surfaceTheta - thetaU, 0.0)), 0.0);+ return vec2(energy * cos(thetaPrime) * surfaceCosine / (nearest * nearest), minimumMeasure);+}++/**+ * Draws one emitter. The sun and the sky keep their uniform share of the draw; a local light is reached by walking the+ * light tree from the root, each step choosing a child by the mix of its two measures. Returns -1 when no light is worth+ * sampling. With one local light, or none, this is the uniform choice.+ */+int chooseEmitterByTree(vec3 normal, out float probability) {+ float uniformShare = 1.0 / float(uEmitterCount);+ int firstLightEmitter = uHasSun ? 1 : 0;+ int emitter = min(int(floor(nextRandom() * float(uEmitterCount))), uEmitterCount - 1);+ probability = uniformShare;+ int lightIndex = emitter - firstLightEmitter;+ if (lightIndex < 0 || lightIndex >= uLightCount) return emitter;+ int node = 0;+ float pathProbability = 1.0;+ for (int step = 0; step < 64; step++) {+ vec4 links = fetchData(uLightTree, node * LIGHT_TREE_TEXELS + 3);+ if (links.x < 0.0) {+ probability = float(uLightCount) * uniformShare * pathProbability;+ return firstLightEmitter + int(links.z);+ }+ vec2 left = lightTreeImportance(int(links.x), normal);+ vec2 right = lightTreeImportance(int(links.y), normal);+ float totalMaximum = left.x + right.x;+ 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 (nextRandom() < leftProbability) {+ node = int(links.x);+ pathProbability *= leftProbability;+ } else {+ node = int(links.y);+ pathProbability *= 1.0 - leftProbability;+ }+ }+ return -1;+}+`;++const buildSource = (hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache, lightTree) => `#version 300 esprecision highp float;precision highp int;precision highp sampler2D;@@ -77,6 +146,9 @@ const int LIGHT_TEXELS = ${LIGHT_TEXELS};const int STACK_SIZE = 128;const bool BLUE_NOISE_FIRST = ${blueNoise};const bool IMPORTANT_LIGHTS = ${lightImportance};+const bool LIGHT_TREE = ${lightTree};+const int LIGHT_TREE_FIRST_HIT_LIGHTS = ${LIGHT_TREE_FIRST_HIT_LIGHTS};+const int LIGHT_TREE_TEXELS = ${LIGHT_TREE_NODE_TEXELS};// The real-time kernel picks one emitter at the first hit too (the denoiser averages the choices over frames) instead of tracing a shadow ray to every emitter.const bool STOCHASTIC_FIRST_HIT = ${radianceCache};const int ALPHA_STEP_LIMIT = 8;@@ -89,6 +161,7 @@ uniform sampler2D uNodes;uniform sampler2D uTriangles;uniform sampler2D uMaterials;uniform sampler2D uLights;+${lightTree ? 'uniform sampler2D uLightTree;' : ''}uniform sampler2D uAtlas;uniform sampler2D uEnvironment;uniform sampler2D uEnvironmentRows;@@ -1017,9 +1090,11 @@ int chooseEmitterByImportance(vec3 normal, out float probability) {return chosen;}+${lightTree ? LIGHT_TREE_FUNCTIONS : ''}/** The first hit lights from every emitter; later hits draw one, and divide by the chance of drawing it. */void addLights(int depth, vec3 normal) {- if ((depth == 0 && !STOCHASTIC_FIRST_HIT) || uEmitterCount <= 1) {+ bool firstHitByTree = LIGHT_TREE && uLightCount > LIGHT_TREE_FIRST_HIT_LIGHTS;+ if ((depth == 0 && !STOCHASTIC_FIRST_HIT && !firstHitByTree) || uEmitterCount <= 1) {selectionProbability = 1.0;for (int emitter = 0; emitter < uEmitterCount; emitter++) {sampleEmitter(depth, normal, emitter);@@ -1027,7 +1102,17 @@ void addLights(int depth, vec3 normal) {}return;}- if (IMPORTANT_LIGHTS) {+${lightTree ? ` if (LIGHT_TREE) {+ int chosen = chooseEmitterByTree(normal, selectionProbability);+ 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 / float(uEmitterCount);+ return;+ }+` : ''} if (IMPORTANT_LIGHTS) {int chosen = chooseEmitterByImportance(normal, selectionProbability);sampleEmitter(depth, normal, chosen);flushShadowRay();@@ -1182,8 +1267,8 @@ ${radianceCache ? CACHE_OUTPUT : ''}* The kernel; `hasSubsurface` compiles in the random walk, which only scenes with a subsurface part need. `texelBake`* starts every path at a lightmap texel instead of the camera (see light-bake-gpu.js).*/-export function buildFragmentSource({ hasSubsurface = false, texelBake = false, blueNoise = false, lightImportance = false, radianceCache = false } = {}) {- return buildSource(hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache);+export function buildFragmentSource({ hasSubsurface = false, texelBake = false, blueNoise = false, lightImportance = false, radianceCache = false, lightTree = false } = {}) {+ return buildSource(hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache, lightTree);}export const FRAGMENT_SOURCE = buildFragmentSource();diff --git a/src/path-tracer-gpu.js b/src/path-tracer-gpu.jsindex ec90f22b..22d4200f 100644--- a/src/path-tracer-gpu.js+++ b/src/path-tracer-gpu.js@@ -1,5 +1,5 @@import { buildFragmentSource, VERTEX_SOURCE } from './path-tracer-gpu-shader.js';-import { packAtlas, packEnvironment, packLights, packMaterials, packNodes, packSubsurface, packTriangles, sceneUsesSubsurface } from './path-tracer-gpu-pack.js';+import { packAtlas, packEnvironment, packLightTree, packLights, packMaterials, packNodes, packSubsurface, packTriangles, sceneUsesSubsurface } from './path-tracer-gpu-pack.js';// The GPU backend of the path tracer: one WebGL2 fragment pass per sample draws every pixel of a band, and four float// targets add the samples up. It needs a page with WebGL2 (a canvas), EXT_color_buffer_float and EXT_float_blend. The@@ -80,6 +80,7 @@ export function uploadScene(gl, program, scene, options = {}) {const materials = packMaterials(scene.materials, atlas);const floatTables = [['uNodes', nodes], ['uTriangles', triangles], ['uMaterials', materials], ['uLights', lights.table]];if (sceneUsesSubsurface(scene.materials)) floatTables.push(['uSubsurface', packSubsurface(scene.materials)]);+ if (options.lightSelection === 'tree') floatTables.push(['uLightTree', packLightTree(scene.lights)]);let unit = 0;const bind = (name) => gl.uniform1i(gl.getUniformLocation(program, name), unit++);for (const [name, table] of floatTables) {@@ -217,11 +218,12 @@ export function getKernel(hasSubsurface, texelBake = false, options = {}) {const { gl, programs } = getContext();const blueNoise = options.samplingPattern === 'blue-noise-first';const lightImportance = options.lightSelection === 'importance';+ const lightTree = options.lightSelection === 'tree';const radianceCache = options.radianceCache === true;- const key = `${hasSubsurface}:${texelBake}:${blueNoise}:${lightImportance}:${radianceCache}`;+ const key = `${hasSubsurface}:${texelBake}:${blueNoise}:${lightImportance}:${radianceCache}:${lightTree}`;if (!programs.has(key)) {const started = performance.now();- const program = createProgram(gl, { hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache });+ const program = createProgram(gl, { hasSubsurface, texelBake, blueNoise, lightImportance, radianceCache, lightTree });gl.getProgramParameter(program, gl.LINK_STATUS);programs.set(key, { program, compileSeconds: (performance.now() - started) / 1000 });if (!texelBake) kernelCompileCount++;diff --git a/src/path-tracer-light-tree.js b/src/path-tracer-light-tree.jsnew file mode 100644index 00000000..61f56f15--- /dev/null+++ b/src/path-tracer-light-tree.js@@ -0,0 +1,237 @@+// The light tree of Conty and Kulla (2018, "Importance Sampling of Many Lights with Adaptive Tree Splitting") as Cycles+// uses it (src/kernel/light/tree.h): the point, spot and area lights sit in a binary tree whose nodes keep a bounding box,+// an orientation cone and the summed energy, and a shading point walks down it choosing the child by an importance estimate.+// The same data table and the same walk feed the CPU tracer and the GLSL kernel (path-tracer-gpu-shader.js reads the table+// as a float texture), so the CPU reference draws the lights with the same chances. The sun and the sky are not in the+// tree: like the distant lights of Cycles they keep a uniform share of the emitter choice.++export const LIGHT_TREE_NODE_FLOATS = 16;+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;++const LEAF = -1;+const HALF_PI = Math.PI / 2;++function luminance(color) {+ return 0.2126 * color[0] + 0.7152 * color[1] + 0.0722 * color[2];+}++function sphereBounds(position, radius) {+ return { minimum: position.map(value => value - radius), maximum: position.map(value => value + radius) };+}++function rectangleBounds(light) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (const acrossSign of [-0.5, 0.5]) {+ for (const alongSign of [-0.5, 0.5]) {+ for (let axis = 0; axis < 3; axis++) {+ const corner = light.position[axis] + light.across[axis] * acrossSign * light.width + light.along[axis] * alongSign * light.height;+ minimum[axis] = Math.min(minimum[axis], corner);+ maximum[axis] = Math.max(maximum[axis], corner);+ }+ }+ }+ return { minimum, maximum };+}++/** One light as a tree leaf: its box, the cone its light leaves in (axis, spread `thetaO` around it, `thetaE` beyond) and its energy. */+export function describeLight(light, type) {+ const energy = luminance(light.color) * light.intensity;+ if (type === 'area') {+ return { ...rectangleBounds(light), axis: [...light.normal], thetaO: 0, thetaE: HALF_PI, energy };+ }+ const bounds = sphereBounds(light.position, light.radius ?? 0);+ if (type === 'spot') return { ...bounds, axis: [...light.direction], thetaO: 0, thetaE: Math.acos(Math.min(1, Math.max(-1, light.cosineHalfAngle))), energy };+ return { ...bounds, axis: [0, 1, 0], thetaO: Math.PI, thetaE: HALF_PI, energy };+}++function angleBetween(first, second) {+ const cosine = first[0] * second[0] + first[1] * second[1] + first[2] * second[2];+ return Math.acos(Math.min(1, Math.max(-1, cosine)));+}++function anyPerpendicular(axis) {+ const smallest = axis.map(Math.abs).indexOf(Math.min(...axis.map(Math.abs)));+ const basis = [0, 0, 0];+ basis[smallest] = 1;+ const crossed = [axis[1] * basis[2] - axis[2] * basis[1], axis[2] * basis[0] - axis[0] * basis[2], axis[0] * basis[1] - axis[1] * basis[0]];+ const length = Math.hypot(...crossed);+ return crossed.map(value => value / length);+}++/** The smallest cone holding two cones (Conty and Kulla, section 3.2): the wider one grown just enough toward the narrower. */+export function mergeCones(first, second) {+ const [wide, narrow] = second.thetaO > first.thetaO ? [second, first] : [first, second];+ const thetaE = Math.max(first.thetaE, second.thetaE);+ const between = angleBetween(wide.axis, narrow.axis);+ if (Math.min(between + narrow.thetaO, Math.PI) <= wide.thetaO) return { axis: [...wide.axis], thetaO: wide.thetaO, thetaE };+ const thetaO = (wide.thetaO + between + narrow.thetaO) / 2;+ if (thetaO >= Math.PI) return { axis: [...wide.axis], thetaO: Math.PI, thetaE };+ const turn = thetaO - wide.thetaO;+ if (Math.sin(between) < 1e-6) return { axis: anyPerpendicular(wide.axis), thetaO, thetaE };+ const wideWeight = Math.sin(between - turn) / Math.sin(between);+ const narrowWeight = Math.sin(turn) / Math.sin(between);+ const axis = wide.axis.map((value, index) => value * wideWeight + narrow.axis[index] * narrowWeight);+ const length = Math.hypot(...axis) || 1;+ return { axis: axis.map(value => value / length), thetaO, thetaE };+}++function mergeEntries(first, second) {+ const cone = mergeCones(first, second);+ return {+ minimum: first.minimum.map((value, axis) => Math.min(value, second.minimum[axis])),+ maximum: first.maximum.map((value, axis) => Math.max(value, second.maximum[axis])),+ energy: first.energy + second.energy,+ ...cone,+ };+}++function centroidOf(entry, axis) {+ return entry.minimum[axis] + entry.maximum[axis];+}++/**+ * 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).+ * 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).+ */+export function buildLightTree(lights) {+ const entries = [+ ...lights.points.map(light => describeLight(light, 'point')),+ ...lights.spots.map(light => describeLight(light, 'spot')),+ ...lights.areas.map(light => describeLight(light, 'area')),+ ].map((entry, lightIndex) => ({ ...entry, lightIndex }));+ const nodes = [];++ function build(group) {+ const nodeIndex = nodes.length;+ const node = { left: LEAF, right: LEAF, lightIndex: LEAF };+ nodes.push(node);+ if (group.length === 1) {+ 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));+ Object.assign(node, mergeEntries(nodes[node.left], nodes[node.right]));+ return nodeIndex;+ }++ if (entries.length === 0) return { nodeCount: 0, data: new Float32Array(LIGHT_TREE_NODE_FLOATS) };+ build(entries);+ const data = new Float32Array(nodes.length * LIGHT_TREE_NODE_FLOATS);+ nodes.forEach((node, index) => {+ const base = index * LIGHT_TREE_NODE_FLOATS;+ data.set([...node.minimum, node.energy], base);+ data.set([...node.maximum, Math.cos(node.thetaO)], base + 4);+ data.set([...node.axis, Math.cos(node.thetaE)], base + 8);+ data.set([node.left, node.right, node.lightIndex, 0], base + 12);+ });+ return { nodeCount: nodes.length, data };+}++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.+ */+export function nodeImportance(data, node, px, py, pz, nx, ny, nz) {+ const base = node * LIGHT_TREE_NODE_FLOATS;+ const energy = data[base + 3];+ const centerX = (data[base] + data[base + 4]) * 0.5;+ const centerY = (data[base + 1] + data[base + 5]) * 0.5;+ const centerZ = (data[base + 2] + data[base + 6]) * 0.5;+ const halfDiagonal = 0.5 * Math.hypot(data[base + 4] - data[base], data[base + 5] - data[base + 1], data[base + 6] - data[base + 2]);+ const deltaX = centerX - px;+ const deltaY = centerY - py;+ const deltaZ = centerZ - pz;+ const distance = Math.hypot(deltaX, deltaY, deltaZ);+ const nearest = Math.max(distance, halfDiagonal, 1e-4);+ const farthest = distance + halfDiagonal;+ importance.minimum = energy / Math.max(farthest * farthest, 1e-8);+ if (distance <= halfDiagonal) {+ importance.maximum = energy / (nearest * nearest);+ return importance;+ }+ const towardX = deltaX / distance;+ const towardY = deltaY / distance;+ const towardZ = deltaZ / distance;+ const thetaU = Math.acos(Math.sqrt(Math.max(0, 1 - (halfDiagonal / distance) ** 2)));+ const axisCosine = -(data[base + 8] * towardX + data[base + 9] * towardY + data[base + 10] * towardZ);+ const theta = Math.acos(Math.min(1, Math.max(-1, axisCosine)));+ const thetaO = Math.acos(Math.min(1, Math.max(-1, data[base + 7])));+ const thetaE = Math.acos(Math.min(1, Math.max(-1, data[base + 11])));+ const thetaPrime = Math.max(theta - thetaO - thetaU, 0);+ if (thetaPrime >= thetaE) {+ importance.maximum = 0;+ return importance;+ }+ const surfaceTheta = Math.acos(Math.min(1, Math.max(-1, nx * towardX + ny * towardY + nz * towardZ)));+ const surfaceCosine = Math.max(Math.cos(Math.max(surfaceTheta - thetaU, 0)), 0);+ importance.maximum = energy * Math.cos(thetaPrime) * surfaceCosine / (nearest * nearest);+ return importance;+}++/** The chance of taking the left child, mixing the maximum and the minimum measure evenly; -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);+}++const choice = { lightIndex: -1, probability: 0 };++/**+ * Walks the tree from the root, each step drawing one child with `nextRandom()`. Returns the shared `choice`: the light+ * index (in sampling order) and the chance of that whole path, or lightIndex -1 when no light is worth sampling.+ */+export function chooseLightFromTree(tree, px, py, pz, nx, ny, nz, nextRandom) {+ choice.lightIndex = -1;+ choice.probability = 0;+ if (tree.nodeCount === 0) return choice;+ const { data } = tree;+ let node = 0;+ let probability = 1;+ while (data[node * LIGHT_TREE_NODE_FLOATS + 12] >= 0) {+ const base = node * LIGHT_TREE_NODE_FLOATS;+ const left = data[base + 12];+ const right = data[base + 13];+ nodeImportance(data, left, px, py, pz, nx, ny, nz);+ const leftMaximum = importance.maximum;+ const leftMinimum = importance.minimum;+ nodeImportance(data, right, px, py, pz, nx, ny, nz);+ const leftProbability = leftChildProbability(leftMaximum, leftMinimum, importance.maximum, importance.minimum);+ if (leftProbability < 0) return choice;+ if (nextRandom() < leftProbability) {+ node = left;+ probability *= leftProbability;+ } else {+ node = right;+ probability *= 1 - leftProbability;+ }+ }+ choice.lightIndex = data[node * LIGHT_TREE_NODE_FLOATS + 14];+ choice.probability = probability;+ return choice;+}diff --git a/src/path-tracer.js b/src/path-tracer.jsindex 2abe8e3d..3ba53726 100644--- a/src/path-tracer.js+++ b/src/path-tracer.js@@ -8,6 +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 { createRandomWalk, WALK_OUTCOME } from './path-tracer-subsurface.js';import { henyeyGreensteinPhase, sampleHenyeyGreensteinCosine, volumeInterval } from './path-tracer-volume.js';@@ -72,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']);+export const LIGHT_SELECTIONS = Object.freeze(['uniform', 'importance', 'tree']);/*** `denoise` is true (the wavelet filter) or false (none), or a name: "wavelet", "oidn" or "none". "oidn" is the optional@@ -113,8 +114,14 @@ export function normalizePathTracerOptions(options = {}) {if (!PATH_TRACER_BACKENDS.includes(result.backend)) throw new TypeError('Path tracer backend must be "cpu", "gpu" or "webgpu".');if (!SAMPLING_PATTERNS.includes(result.samplingPattern)) throw new RangeError(`Path tracer samplingPattern must be one of ${SAMPLING_PATTERNS.join(', ')}.`);if (!LIGHT_SELECTIONS.includes(result.lightSelection)) throw new RangeError(`Path tracer lightSelection must be one of ${LIGHT_SELECTIONS.join(', ')}.`);- if (result.backend !== 'gpu' && (result.samplingPattern !== 'random' || result.lightSelection !== 'uniform')) {- throw new RangeError('Path tracer samplingPattern "blue-noise-first" and lightSelection "importance" need backend "gpu"; the CPU reference and the WebGPU tracer draw random samples and pick lights uniformly.');+ if (result.backend !== 'gpu' && result.samplingPattern !== 'random') {+ 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.');}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.');@@ -626,6 +633,41 @@ function createPathTracer(scene, options) {if (environment) sampleEnvironmentLight(depth, normal);}+ const lightCount = lights.points.length + lights.spots.length + lights.areas.length;+ const useLightTree = options.lightSelection === 'tree' && lightCount > 1;+ const lightTree = useLightTree ? buildLightTree(lights) : null;+ const drawRandom = () => random.next();+ function sampleLightByIndex(depth, normal, index) {+ if (index < lights.points.length) return samplePointLight(depth, normal, lights.points[index]);+ index -= lights.points.length;+ if (index < lights.spots.length) return sampleSpotLight(depth, normal, lights.spots[index]);+ return sampleAreaLight(depth, normal, lights.areas[index - lights.spots.length]);+ }++ /** One emitter by the light tree: the sun and the sky keep a uniform share, the local lights share theirs down the tree. */+ function addOneLightByTree(depth, normal) {+ const lightsShare = lightCount / emitterCount;+ let remaining = Math.floor(random.next() * emitterCount);+ if (lights.sun) {+ if (remaining === 0) {+ selectionProbability = 1 / emitterCount;+ return sampleSun(depth, normal);+ }+ remaining--;+ }+ if (remaining >= lightCount) {+ selectionProbability = 1 / emitterCount;+ return sampleEnvironmentLight(depth, normal);+ }+ const picked = chooseLightFromTree(lightTree, hit.point[0], hit.point[1], hit.point[2], normal[0], normal[1], normal[2], drawRandom);+ selectionProbability = 1 / emitterCount;+ if (picked.lightIndex < 0) return;+ selectionProbability = lightsShare * picked.probability;+ sampleLightByIndex(depth, normal, picked.lightIndex);+ // The sky is drawn with its uniform share whatever light was chosen: that share weighs the next escape ray.+ selectionProbability = 1 / emitterCount;+ }+function addOneLight(depth, normal) {selectionProbability = 1 / emitterCount;let remaining = Math.floor(random.next() * emitterCount);@@ -642,7 +684,9 @@ function createPathTracer(scene, options) {}function addLights(depth, normal) {- if (depth === 0 || emitterCount <= 1) addEveryLight(depth, normal);+ const firstHitByTree = useLightTree && lightCount > LIGHT_TREE_FIRST_HIT_LIGHTS;+ if ((depth === 0 && !firstHitByTree) || emitterCount <= 1) addEveryLight(depth, normal);+ else if (useLightTree) addOneLightByTree(depth, normal);else addOneLight(depth, normal);}diff --git a/tests/path-tracer-light-tree.test.js b/tests/path-tracer-light-tree.test.jsnew file mode 100644index 00000000..afba9e15--- /dev/null+++ b/tests/path-tracer-light-tree.test.js@@ -0,0 +1,150 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import { box } from '../src/geometry.js';+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,+} from '../src/path-tracer-light-tree.js';++function pointLight(position, intensity = 1) {+ return { position, color: [1, 1, 1], intensity, radius: 0.1 };+}++function lightRow(count) {+ return { points: Array.from({ length: count }, (_, index) => pointLight([index * 2 - count, 1, 0])), spots: [], areas: [] };+}++function seededDraws(seed) {+ let state = seed >>> 0;+ return () => {+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;+ return state / 4294967296;+ };+}++test('the tree has one leaf per light and boxes and energy that cover the children', () => {+ const lights = {+ points: [pointLight([0, 0, 0], 2), pointLight([4, 0, 0], 3)],+ spots: [{ ...pointLight([0, 3, 0], 1), direction: [0, -1, 0], cosineHalfAngle: 0.9 }],+ areas: [{ position: [2, 5, 2], color: [1, 1, 1], intensity: 5, normal: [0, -1, 0], across: [1, 0, 0], along: [0, 0, 1], width: 2, height: 1 }],+ };+ const tree = buildLightTree(lights);+ assert.equal(tree.nodeCount, 7);+ const leafLights = [];+ for (let node = 0; node < tree.nodeCount; node++) {+ const base = node * LIGHT_TREE_NODE_FLOATS;+ const left = tree.data[base + 12];+ if (left < 0) {+ leafLights.push(tree.data[base + 14]);+ continue;+ }+ const right = tree.data[base + 13];+ const leftBase = left * LIGHT_TREE_NODE_FLOATS;+ const rightBase = right * LIGHT_TREE_NODE_FLOATS;+ assert.equal(tree.data[base + 3], tree.data[leftBase + 3] + tree.data[rightBase + 3]);+ for (let axis = 0; axis < 3; axis++) {+ assert.equal(tree.data[base + axis], Math.min(tree.data[leftBase + axis], tree.data[rightBase + axis]));+ assert.equal(tree.data[base + 4 + axis], Math.max(tree.data[leftBase + 4 + axis], tree.data[rightBase + 4 + axis]));+ }+ }+ assert.deepEqual(leafLights.sort(), [0, 1, 2, 3]);+ assert.equal(tree.data[3], 2 + 3 + 1 + 5);+});++test('merging cones keeps both inside the result', () => {+ const up = { axis: [0, 1, 0], thetaO: 0, thetaE: Math.PI / 2 };+ const same = mergeCones(up, up);+ assert.deepEqual(same.axis, [0, 1, 0]);+ assert.equal(same.thetaO, 0);+ const right = { axis: [1, 0, 0], thetaO: 0, thetaE: 0.3 };+ const merged = mergeCones(up, right);+ assert.ok(Math.abs(merged.thetaO - Math.PI / 4) < 1e-9);+ assert.ok(Math.abs(merged.axis[0] - Math.SQRT1_2) < 1e-9 && Math.abs(merged.axis[1] - Math.SQRT1_2) < 1e-9);+ assert.equal(merged.thetaE, Math.PI / 2);+ const opposite = mergeCones(up, { axis: [0, -1, 0], thetaO: 0, thetaE: 0.3 });+ assert.ok(Math.abs(opposite.thetaO - Math.PI / 2) < 1e-9);+ assert.ok(Math.abs(Math.hypot(...opposite.axis) - 1) < 1e-9 && Math.abs(opposite.axis[1]) < 1e-9);+ const wideOpposite = mergeCones({ axis: [0, 1, 0], thetaO: 2, thetaE: 1 }, { axis: [0, -1, 0], thetaO: 2, thetaE: 1 });+ assert.equal(wideOpposite.thetaO, Math.PI);+});++test('a node is worth more when it is near, bright and turned toward the point, and its minimum measure never reaches zero', () => {+ const near = buildLightTree({ points: [pointLight([0, 2, 0])], spots: [], areas: [] });+ const far = buildLightTree({ points: [pointLight([0, 20, 0])], spots: [], areas: [] });+ const bright = buildLightTree({ points: [pointLight([0, 2, 0], 4)], spots: [], areas: [] });+ const nearImportance = { ...nodeImportance(near.data, 0, 0, 0, 0, 0, 1, 0) };+ const farImportance = { ...nodeImportance(far.data, 0, 0, 0, 0, 0, 1, 0) };+ const brightImportance = { ...nodeImportance(bright.data, 0, 0, 0, 0, 0, 1, 0) };+ assert.ok(nearImportance.maximum > farImportance.maximum * 50);+ assert.ok(Math.abs(brightImportance.maximum / nearImportance.maximum - 4) < 1e-6);+ const spotAway = buildLightTree({ points: [], spots: [{ ...pointLight([0, 2, 0]), direction: [0, 1, 0], cosineHalfAngle: 0.9 }], areas: [] });+ const culled = nodeImportance(spotAway.data, 0, 0, 0, 0, 0, 1, 0);+ assert.equal(culled.maximum, 0);+ assert.ok(culled.minimum > 0);+ const belowSurface = nodeImportance(near.data, 0, 0, 4, 0, 0, 1, 0);+ assert.equal(belowSurface.maximum, 0);+});++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));+ assert.equal(leftChildProbability(0, 1, 0, 3), 0.25);+ assert.equal(leftChildProbability(0, 0, 0, 0), -1);+});++test('the walk reports the chance it took: frequencies match and the chances add up to one', () => {+ const tree = buildLightTree(lightRow(7));+ const nextRandom = seededDraws(11);+ const counts = new Map();+ const chances = new Map();+ const draws = 40000;+ for (let draw = 0; draw < draws; draw++) {+ const choice = chooseLightFromTree(tree, 0, 0, 0, 0, 1, 0, nextRandom);+ assert.ok(choice.lightIndex >= 0);+ counts.set(choice.lightIndex, (counts.get(choice.lightIndex) ?? 0) + 1);+ chances.set(choice.lightIndex, choice.probability);+ }+ let total = 0;+ for (const [lightIndex, chance] of chances) {+ total += chance;+ assert.ok(Math.abs(counts.get(lightIndex) / draws - chance) < 0.01, `light ${lightIndex}`);+ }+ assert.ok(Math.abs(total - 1) < 1e-9);+ assert.equal(chances.size, 7);+ assert.ok(chances.get(3) > chances.get(0), 'the light nearest the point is chosen more often than one 7 units away');+});++test('the light tree packs into a float table and the kernel has the walk only when asked', () => {+ const table = packLightTree(lightRow(5));+ assert.equal(table.data[3], 5);+ assert.ok(buildFragmentSource({ lightTree: true }).includes('chooseEmitterByTree'));+ assert.ok(!buildFragmentSource().includes('chooseEmitterByTree'));+ assert.ok(!buildFragmentSource().includes('uLightTree'));+});++function manyLightScene(lightCount) {+ const positions = Array.from({ length: lightCount }, (_, index) => [(index % 4) * 1.6 - 2.4, 1.2, Math.floor(index / 4) * 1.6 - 1.6]);+ return {+ parts: [{ name: 'floor', geometry: box(0, 1), matrix: new Float32Array([8, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 8, 0, 0, -0.05, 0, 1]), material: { tag: 'surface', metallic: 0, roughness: 1, emission: 0, color: [0.6, 0.6, 0.6] } }],+ environment: { keyColor: [0, 0, 0], lightDirection: [0, 1, 0], pointLights: positions.map(position => pointLight(position, 3)) },+ camera: { eye: [0, 4, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 50 },+ };+}++function meanRadiance(linear) {+ let sum = 0;+ for (const value of linear) sum += value;+ return sum / linear.length;+}++test('the CPU tracer with the light tree keeps the mean radiance of the uniform draw', async () => {+ const options = { width: 24, height: 18, samples: 48, bounces: 3, denoise: false, threads: 1 };+ for (const lightCount of [4, 20]) {+ const uniform = await renderPathTracedImage(manyLightScene(lightCount), options);+ const tree = await renderPathTracedImage(manyLightScene(lightCount), { ...options, lightSelection: 'tree' });+ const ratio = meanRadiance(tree.linear) / meanRadiance(uniform.linear);+ assert.ok(Math.abs(ratio - 1) < 0.03, `${lightCount} lights: ratio ${ratio}`);+ }+});diff --git a/tests/path-tracer-progressive.test.js b/tests/path-tracer-progressive.test.jsindex 2b6bec21..540499aa 100644--- a/tests/path-tracer-progressive.test.js+++ b/tests/path-tracer-progressive.test.js@@ -52,9 +52,11 @@ test('the options choose the sampling pattern and the light choice, and the CPUconst gpu = normalizePathTracerOptions({ backend: 'gpu', samplingPattern: 'blue-noise-first', lightSelection: 'importance' });assert.equal(gpu.samplingPattern, 'blue-noise-first');assert.equal(gpu.lightSelection, 'importance');- assert.throws(() => normalizePathTracerOptions({ samplingPattern: 'blue-noise-first' }), /need backend "gpu"/);- assert.throws(() => normalizePathTracerOptions({ lightSelection: 'importance' }), /need backend "gpu"/);- assert.throws(() => normalizePathTracerOptions({ backend: 'gpu', lightSelection: 'tree' }), /lightSelection must be one of/);+ assert.throws(() => normalizePathTracerOptions({ samplingPattern: 'blue-noise-first' }), /needs backend "gpu"/);+ 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/);});test('the kernel compiles the new paths only when asked, so the default kernel keeps its pixels', () => {