3D engine that AI agents drive
Trace offline stills on the GPU with a WebGL2 path tracer (issue #302)
Nguyen Xuan An42455e57d7d3
diff --git a/bench/reference/flip-compare.py b/bench/reference/flip-compare.pynew file mode 100644index 00000000..acdc168b--- /dev/null+++ b/bench/reference/flip-compare.py@@ -0,0 +1,57 @@+# FLIP of the GPU path tracer against the CPU path tracer (same seed) and, when the Cycles renders are at hand, of both+# against Cycles. Reads the files bench/reference/gpu-compare.mjs writes.+# uv run --no-project --python 3.12 --with flip-evaluator --with pillow --with numpy python -I bench/reference/flip-compare.py <directory> <scene id>,<scene id> [--cycles <directory with <scene>-cycles.npy>]+import json+import sys+from pathlib import Path++import flip_evaluator+import numpy as np+from PIL import Image++GAMMA = 2.2+++class score:+ """The same helpers as score.py (which runs its own main on import, so they are repeated here)."""++ @staticmethod+ def load_png(path):+ return np.asarray(Image.open(path).convert("RGB"), dtype=np.float32) / 255++ @staticmethod+ def tone_map_like_67js(linear):+ color = np.maximum(linear, 0)+ mapped = np.clip((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0, 1)+ return mapped ** (1 / GAMMA)++ @staticmethod+ def flip_score(reference, test):+ _, mean_error, _ = flip_evaluator.evaluate(reference.astype(np.float32), test.astype(np.float32), "LDR", inputsRGB=True)+ return round(float(mean_error), 4)+++def main():+ directory = Path(sys.argv[1])+ scene_ids = sys.argv[2].split(",")+ cycles_directory = Path(sys.argv[sys.argv.index("--cycles") + 1]) if "--cycles" in sys.argv else None+ timings = json.loads((directory / "timings.json").read_text(encoding="utf-8")) if (directory / "timings.json").exists() else {}+ rows = {}+ print("scene".ljust(18) + "gpu-vs-cpu".rjust(12) + "cpu-vs-cycles".rjust(15) + "gpu-vs-cycles".rjust(15) + "gpu s".rjust(9) + "cpu s".rjust(9))+ for scene_id in scene_ids:+ cpu = score.load_png(directory / f"{scene_id}-pathtracer-cpu.png")+ gpu = score.load_png(directory / f"{scene_id}-pathtracer-gpu.png")+ row = {"gpu-vs-cpu": score.flip_score(cpu, gpu)}+ if cycles_directory is not None and (cycles_directory / f"{scene_id}-cycles.npy").exists():+ cycles = score.tone_map_like_67js(np.load(cycles_directory / f"{scene_id}-cycles.npy"))+ row["cpu-vs-cycles"] = score.flip_score(cycles, cpu)+ row["gpu-vs-cycles"] = score.flip_score(cycles, gpu)+ row["gpu-seconds"] = timings.get(f"{scene_id}:gpu", {}).get("seconds")+ row["cpu-seconds"] = timings.get(f"{scene_id}:cpu", {}).get("seconds")+ rows[scene_id] = row+ cells = [row["gpu-vs-cpu"], row.get("cpu-vs-cycles"), row.get("gpu-vs-cycles"), row["gpu-seconds"], row["cpu-seconds"]]+ print(scene_id.ljust(18) + "".join(("-" if value is None else f"{value:.4f}" if index < 3 else f"{value:.1f}").rjust(width) for index, (value, width) in enumerate(zip(cells, [12, 15, 15, 9, 9]))))+ (directory / "flip-compare.json").write_text(json.dumps(rows, indent=1) + "\n", encoding="utf-8")+++main()diff --git a/bench/reference/gpu-compare.mjs b/bench/reference/gpu-compare.mjsnew file mode 100644index 00000000..0426e081--- /dev/null+++ b/bench/reference/gpu-compare.mjs@@ -0,0 +1,73 @@+// 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|both]+// [--width 960] [--height 540] [--bounces 8] [--no-denoise] [--threads 8]+// Files are <scene>-pathtracer-<backend>.png and timings.json. Run it through bash ~/.agents/tools/gpu-lock.sh: the GPU+// backend takes the whole GPU for seconds at a time.+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { resolve } from 'node:path';+import { chromium } from 'playwright';+import { createServer } from 'vite';++const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';+const argumentsGiven = process.argv.slice(2);+const outputDirectory = resolve(argumentsGiven[0]);+const sceneIds = argumentsGiven[1].split(',');+// An id ending in .json is a scene recipe file, drawn like an agent render job (for example tests/fixtures/demo-room.recipe.json).+const recipeName = id => id.replace(/^.*[\/]/, '').replace(/\.recipe\.json$|\.json$/, '');++function valueAfter(flag, fallback) {+ const index = argumentsGiven.indexOf(flag);+ return index >= 0 ? argumentsGiven[index + 1] : fallback;+}++const backendChoice = valueAfter('--backend', 'both');+const backends = backendChoice === 'both' ? ['gpu', 'cpu'] : [backendChoice];+const options = {+ width: Number(valueAfter('--width', 960)),+ height: Number(valueAfter('--height', 540)),+ samples: Number(valueAfter('--samples', 64)),+ bounces: Number(valueAfter('--bounces', 8)),+ threads: Number(valueAfter('--threads', 8)),+ denoise: !argumentsGiven.includes('--no-denoise'),+ maxSeconds: 1800,+};++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+await mkdir(outputDirectory, { recursive: true });+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });+await server.listen();+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'] });+const timings = {};+try {+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });+ page.on('pageerror', error => console.log('PAGE ERROR', error.message));+ page.setDefaultTimeout(0);+ await page.goto(`${serverUrl}/bench/reference/harness.html`, { timeout: 180000 });+ await page.waitForFunction(() => window.renderReferencePathTraced, null, { timeout: 180000 });+ for (const id of sceneIds) {+ for (const backend of backends) {+ const isRecipe = id.endsWith('.json');+ const recipe = isRecipe ? JSON.parse(await readFile(id, 'utf8')) : null;+ const name = isRecipe ? recipeName(id) : id;+ const result = isRecipe+ ? await page.evaluate(([sceneRecipe, tracerOptions]) => window.renderRecipePathTraced(sceneRecipe, tracerOptions), [recipe, { ...options, backend }])+ : await page.evaluate(([sceneId, tracerOptions]) => window.renderReferencePathTraced(sceneId, tracerOptions), [id, { ...options, backend }]);+ await writeFile(`${outputDirectory}/${name}-pathtracer-${backend}.png`, Buffer.from(result.image, 'base64'));+ const { seconds, tracedSeconds, samples, triangles, gpu, gpuCompileSeconds } = result.report;+ timings[`${name}:${backend}`] = { seconds: Number(seconds.toFixed(2)), tracedSeconds: Number(tracedSeconds.toFixed(2)), samples, triangles, gpu, compileSeconds: gpuCompileSeconds };+ console.log(name, backend, JSON.stringify(timings[`${name}:${backend}`]));+ }+ }+} finally {+ await browser.close();+ await server.close();+}+let previous = {};+try {+ previous = JSON.parse(await readFile(`${outputDirectory}/timings.json`, 'utf8'));+} catch {+ // first run in this directory+}+await writeFile(`${outputDirectory}/timings.json`, JSON.stringify({ ...previous, ...timings }, null, 1));diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex bd11d639..d1375af5 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -277,6 +277,28 @@ async function renderReferencePathTracedFeatures(id, options) {}window.renderReferencePathTracedFeatures = renderReferencePathTracedFeatures;++// Traces a scene recipe the way an agent render job does (parts, environment map and camera of the agent scene).+async function renderRecipePathTraced(recipe, options) {+ const { createAgentScene, loadAllAgentSceneModules, needsMeshBooleans, loadMeshBooleans, setManifoldModuleLoader } = await import('/src/agent-scene.js');+ const { agentEnvironmentMap } = await import('/src/agent-look.js');+ await loadAllAgentSceneModules();+ if (needsMeshBooleans(recipe)) {+ setManifoldModuleLoader(() => import(/* @vite-ignore */ '/node_modules/manifold-3d/manifold.js'));+ await loadMeshBooleans();+ }+ const scene = createAgentScene(recipe);+ const { renderPathTracedImage } = await import('/src/path-tracer.js');+ const environment = scene.environment;+ const result = await renderPathTracedImage({ parts: scene.parts, environment: { ...environment, map: agentEnvironmentMap(environment) }, camera: scene.camera }, options);+ const canvas = document.createElement('canvas');+ canvas.width = result.width;+ canvas.height = result.height;+ canvas.getContext('2d').putImageData(new ImageData(result.rgba, result.width, result.height), 0, 0);+ return { image: canvas.toDataURL('image/png').split(',')[1], report: result.report };+}++window.renderRecipePathTraced = renderRecipePathTraced;window.renderReferenceScene = renderReferenceScene;window.renderReferencePathTraced = renderReferencePathTraced;window.referenceSceneIds = Object.keys(SCENES);diff --git a/bench/reference/run.mjs b/bench/reference/run.mjsindex 6f0ad70d..3b085095 100644--- a/bench/reference/run.mjs+++ b/bench/reference/run.mjs@@ -5,7 +5,8 @@// --probes [<id>,<id>] adds reflection probes (src/reflection-probes.js) to the named scenes, on top of --bake when both are given.// --ambient <scale> multiplies the light the world gives every surface (0 removes it); with --skip-blender it measures what the world adds.// --path-tracer [--samples <n>] [--noise-threshold <n>] [--scene <id>] draws the scenes with the offline path tracer (src/path-tracer.js) instead, keeps the-// Cycles renders of an earlier run, and scores them into path-tracer.json. Nothing in baseline.json or images/ changes.+// Cycles renders of an earlier run, and scores them into path-tracer.json (--path-tracer-backend gpu draws them with the GPU tracer and+// writes path-tracer-gpu.json instead). Nothing in baseline.json or images/ changes.// Use --score-only to score existing renders, --skip-blender to keep them, and --scene <id> for one scene.import { spawnSync } from 'node:child_process';import { mkdir, writeFile } from 'node:fs/promises';@@ -89,6 +90,8 @@ const pathTracerFlag = argumentsGiven.includes('--path-tracer');const samplesFlag = argumentsGiven.indexOf('--samples');const pathTracerSamples = samplesFlag >= 0 ? Number(argumentsGiven[samplesFlag + 1]) : 64;const noiseThresholdFlag = argumentsGiven.indexOf('--noise-threshold');+const pathTracerBackendFlag = argumentsGiven.indexOf('--path-tracer-backend');+const pathTracerBackend = pathTracerBackendFlag >= 0 ? argumentsGiven[pathTracerBackendFlag + 1] : 'cpu';const pathTracerNoiseThreshold = noiseThresholdFlag >= 0 ? Number(argumentsGiven[noiseThresholdFlag + 1]) : undefined;// --scene takes one id or several separated by commas.const sceneIdsGiven = lookIds ?? (sceneFlag >= 0 ? argumentsGiven[sceneFlag + 1].split(',') : null);@@ -149,7 +152,7 @@ async function renderBackend(backend, serverUrl, graphics) {}async function renderPathTracerScenes(serverUrl) {- const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS.cpu });+ const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS[pathTracerBackend === 'gpu' ? 'gpu' : 'cpu'] });const timings = {};try {const page = await browser.newPage({ viewport: { width: WIDTH, height: HEIGHT } });@@ -159,16 +162,16 @@ async function renderPathTracerScenes(serverUrl) {const sceneIds = await page.evaluate(() => window.referenceSceneIds);for (const id of sceneIds) {if (onlyScenes && !onlyScenes.includes(id)) continue;- const options = { width: WIDTH, height: HEIGHT, samples: pathTracerSamples, maxSeconds: 1800, ...(pathTracerNoiseThreshold === undefined ? {} : { noiseThreshold: pathTracerNoiseThreshold }) };+ const options = { width: WIDTH, height: HEIGHT, samples: pathTracerSamples, maxSeconds: 1800, backend: pathTracerBackend, ...(pathTracerNoiseThreshold === undefined ? {} : { noiseThreshold: pathTracerNoiseThreshold }) };const result = await page.evaluate(([sceneId, tracerOptions]) => window.renderReferencePathTraced(sceneId, tracerOptions), [id, options]);- await writeFile(`${WORK_DIRECTORY}/${id}-pathtracer.png`, Buffer.from(result.image, 'base64'));+ await writeFile(`${WORK_DIRECTORY}/${id}-pathtracer${pathTracerBackend === 'gpu' ? '-gpu' : ''}.png`, Buffer.from(result.image, 'base64'));timings[id] = { seconds: Number(result.report.seconds.toFixed(1)), samples: result.report.samples, averageSamples: Number(result.report.averageSamples.toFixed(1)), ignored: result.report.ignored };console.log(`${id} path traced: ${timings[id].seconds} s at ${timings[id].samples} samples`);}} finally {await browser.close();}- await writeFile(`${WORK_DIRECTORY}/pathtracer-timings.json`, JSON.stringify(timings, null, 1));+ await writeFile(`${WORK_DIRECTORY}/pathtracer${pathTracerBackend === 'gpu' ? '-gpu' : ''}-timings.json`, JSON.stringify(timings, null, 1));}function runChecked(command, commandArguments) {@@ -220,7 +223,7 @@ if (viewTransform) {if ((!onlyScenes && !skipCpu) || pathTracerFlag || bakeScoreRun) {runChecked('uv', ['run', '--no-project', '--python', '3.12', '--with', 'flip-evaluator', '--with', 'pillow', '--with', 'numpy',- 'python', '-I', 'bench/reference/score.py', WORK_DIRECTORY, bakeScoreRun && !bakeScoreIsBaseline ? WORK_DIRECTORY : OUTPUT_DIRECTORY, ...(pathTracerFlag ? ['--path-tracer'] : []), ...(bakeScoreRun ? ['--bake', bakedSceneIds.join(',')] : []), ...(sceneSet ? [`--${sceneSet}`] : []),+ 'python', '-I', 'bench/reference/score.py', WORK_DIRECTORY, bakeScoreRun && !bakeScoreIsBaseline ? WORK_DIRECTORY : OUTPUT_DIRECTORY, ...(pathTracerFlag ? ['--path-tracer', ...(pathTracerBackend === 'gpu' ? ['--gpu-tracer'] : [])] : []), ...(bakeScoreRun ? ['--bake', bakedSceneIds.join(',')] : []), ...(sceneSet ? [`--${sceneSet}`] : []),]);if (bakeScoreRun && !bakeScoreIsBaseline && !bakeVariantFlags.some(flag => argumentsGiven.includes(flag))) {const comparison = spawnSync('node', ['bench/reference/compare-scores.mjs', `${WORK_DIRECTORY}/bake.json`], { stdio: 'inherit' });diff --git a/bench/reference/score.py b/bench/reference/score.pyindex c51e45e7..ebbc09eb 100644--- a/bench/reference/score.py+++ b/bench/reference/score.py@@ -117,16 +117,16 @@ def side_by_side(cycles, eevee, gpu, scores):return sheet-def score_path_tracer(work_directory, output_directory):+def score_path_tracer(work_directory, output_directory, backend_suffix=""):"""FLIP of each path traced render against the Cycles render of the same scene, with the time it took."""- timings = json.loads((work_directory / "pathtracer-timings.json").read_text(encoding="utf-8"))+ timings = json.loads((work_directory / f"pathtracer{backend_suffix}-timings.json").read_text(encoding="utf-8"))results = {}for scene_id in sorted(timings):cycles = tone_map_like_67js(np.load(work_directory / f"{scene_id}-cycles.npy"))- traced = load_png(work_directory / f"{scene_id}-pathtracer.png")+ traced = load_png(work_directory / f"{scene_id}-pathtracer{backend_suffix}.png")results[scene_id] = {"pathtracer-vs-cycles": flip_score(cycles, traced), **timings[scene_id]}report = {"metric": "FLIP (LDR), mean error against Cycles, lower is better", "scores": results}- (output_directory / "path-tracer.json").write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8")+ (output_directory / f"path-tracer{backend_suffix}.json").write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8")print("scene".ljust(20) + "pathtracer-vs-cycles".rjust(22) + "seconds".rjust(10))for scene_id, entry in results.items():print(scene_id.ljust(20) + f"{entry['pathtracer-vs-cycles']:.4f}".rjust(22) + f"{entry['seconds']:.1f}".rjust(10))@@ -177,7 +177,7 @@ def main():score_baked(Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[sys.argv.index("--bake") + 1].split(","))returnif "--path-tracer" in sys.argv:- score_path_tracer(Path(sys.argv[1]), Path(sys.argv[2]))+ score_path_tracer(Path(sys.argv[1]), Path(sys.argv[2]), "-gpu" if "--gpu-tracer" in sys.argv else "")return# Khronos assets and cloth sheets sit in front of a sky that both sides draw alike, so they also get a score over the# pixels the scene covers.diff --git a/changes/302.md b/changes/302.mdnew file mode 100644index 00000000..3eefc7bf--- /dev/null+++ b/changes/302.md@@ -0,0 +1 @@+- Add a GPU backend to the path tracer, `backend: 'gpu'` (issue #302): the same algorithm and random numbers in a WebGL2 fragment shader, with the BVH, materials, maps, lights and sky in float textures, inside the path-tracer addon only. The 1920 by 1080 demo room at 64 samples took 55.8 s against 585.9 s on the CPU tracer, and GPU against CPU FLIP was 0.0001 to 0.0018 on the 16 reference scenes. `docs/webgpu-decision.md` records WebGL2 over WebGPU for this offline work.diff --git a/docs/path-tracer.md b/docs/path-tracer.mdindex 2a4f5fae..5e1baa42 100644--- a/docs/path-tracer.md+++ b/docs/path-tracer.md@@ -45,15 +45,20 @@ Unidirectional path tracing against the triangle BVH that the [light bake](light| `noiseThreshold` | 0 | 0 to 1 (render jobs: 0 to 0.1) | 0 draws every sample. Above 0, a pixel stops once the standard error of its mean luminance, relative to that mean plus 0.05, is under this, checked from 16 samples on and after every 8 more. It costs quality on some scenes (see the table below). It reads only the pixel's own samples, so the result is the same on any thread count and band split. `report.averageSamples` says how many paths a pixel took. || `maxSeconds` | 300 | 1 to 1800 | Wall-clock limit. Passing it throws; there is never a partial image. || `denoise` | true | boolean, `"wavelet"`, `"oidn"`, `"none"` | `true` or `"wavelet"` filters the light with normal, depth and noise guides; `false` or `"none"` does not filter. `"oidn"` is [Open Image Denoise](#open-image-denoise-optional): a render job with it defaults to 16 samples. |+| `backend` | `cpu` | `cpu`, `gpu` | `gpu` traces in a WebGL2 shader (see Choosing a backend). || `fireflyClamp` | 20 | 1 to 1000 | Largest radiance one bounce may add to a sample. |Also checked before any ray is traced: samples times pixels times bounces at most 4 billion, 400,000 triangles, 1,024 parts, 32 lights, and finite numbers and in-range indices in every part. A render job limits `maxSeconds` to 600: the job runs on workers without blocking the page, and its deadline is `maxSeconds` plus 60 seconds for the page and the PNG, so a trace that reaches its limit still ends before the job does.The same scene and options give the same bytes. Random numbers come from a hash of the pixel, the sample and the seed, never from `Math.random` or the clock, and a pixel does not depend on which thread drew it.-## Choosing CPU+## Choosing a backend-A WebGL2 fragment tracer was not built. The WebGPU decision (issue #56) set no WebGPU backend for now, and a fragment path would need the BVH and every material in textures. The CPU path reuses `src/triangle-bvh.js` and `src/ray-query.js` as they are, runs in the job page next to the scene, and needs no GPU: it measured 25 to 238 seconds for a 960 by 540 still at 32 samples on a Ryzen 5 5600X with four threads, while another session also loaded the machine (table in `bench/reference/README.md`).+`backend: 'cpu'` (the default) is the reference: it reuses `src/triangle-bvh.js` and `src/ray-query.js`, runs on workers in the job page next to the scene, needs no GPU, and gives the same bytes for the same scene and options. It measured 25 to 238 seconds for a 960 by 540 still at 32 samples on a Ryzen 5 5600X with four threads, while another session also loaded the machine (table in `bench/reference/README.md`).++`backend: 'gpu'` (issue #302) runs the same algorithm in a WebGL2 fragment shader (`src/path-tracer-gpu.js`, loaded only for this backend, so a CPU render and the core bundle do not carry it). The BVH, triangles, materials, maps, lights and the environment table are packed into float textures (`src/path-tracer-gpu-pack.js`), the random numbers are the same integer hash and PCG stream as the CPU tracer and are drawn in the same order, and each sample adds into four float targets (colour and depth, albedo, normal, luminance and its square) that feed the same denoiser. Float32 maths and a 24-bit random value make the pixels differ a little from the CPU tracer: FLIP (LDR) of GPU against CPU at the same seed was 0.0001 to 0.0018 on the 16 path tracer reference scenes at 480 by 270 and 32 samples. It needs a page with WebGL2, `EXT_color_buffer_float` and `EXT_float_blend`, and throws without them, so choose it only where those exist. It traces everything the CPU tracer does (lights with linking, all materials and maps including emissive maps, glass, volume fog, the sky); it does not use `noiseThreshold` (every pixel draws every sample) or `threads`, and a sample that produced a NaN or an infinity counts as black. The first still of a page compiles the kernel (13 to 30 s), later ones reuse it.++The 1920 by 1080 still of the demo room at 64 samples took 55.8 s on the GPU (RTX 3060, including 13.0 s of compiling, the BVH build and the denoiser) against 585.9 s on the CPU tracer (measured 2026-11-03; see [the WebGPU decision](webgpu-decision.md) for the choice of WebGL2 over WebGPU). `node bench/reference/gpu-compare.mjs <directory> <scene or recipe.json> --backend both` draws a scene with both backends, and `bench/reference/flip-compare.py` scores them against each other and against Cycles. Render jobs do not select the GPU backend yet.## Speeddiff --git a/docs/webgpu-decision.md b/docs/webgpu-decision.mdindex 99f25032..a0859e15 100644--- a/docs/webgpu-decision.md+++ b/docs/webgpu-decision.md@@ -1,6 +1,20 @@# WebGPU decision (issue #56)-Decision: wait. WebGL2 stays the only backend. Revisit when a feature needs compute and the CPU path has been measured as the bottleneck, not before.+Decision: wait. WebGL2 stays the only backend of the real-time renderer; the offline path tracer runs on the GPU through WebGL2 too (see the update below). Revisit when a feature needs compute and the CPU path has been measured as the bottleneck, not before.++## Update for the offline path tracer (issue #302)++The trigger named below ("a feature measured as too slow on the CPU") was met by the path tracer, so it got a GPU backend. Choice: **WebGL2 fragment shader, not WebGPU compute**, for an offline-only tracer. The real-time renderer is unchanged: WebGL2 only, no WebGPU backend.++Why WebGL2 fragment (measured on this machine, 2026-11-03, RTX 3060 shared with other sessions, Chrome with ANGLE on Direct3D 11, headless):++- It reached the target without compute. The 1920 by 1080 still of `tests/fixtures/demo-room.recipe.json` (181,708 triangles, 64 samples, 8 bounces, the 8-thread CPU tracer took 585.9 s) took 55.8 s end to end on the GPU in the first full run, of which 13.0 s was compiling the kernel and about 12 s was the denoiser and the BVH build (the log of that run: `seconds` 55.81, `tracedSeconds` 43.80, `compileSeconds` 13.03).+- The same kernel, in the same random-number order as the CPU tracer, gives the same picture: GPU against CPU FLIP (LDR, mean) was 0.0001 to 0.0018 on all 16 path tracer reference scenes at 480 by 270 and 32 samples (measured; `bench/reference/gpu-compare.mjs` and `flip-compare.py`). Float32 against float64 and a 24-bit random value are the only differences.+- On those 16 scenes the GPU tracer took 0.5 to 1.8 s against 1.6 to 9.0 s for the CPU tracer on 8 threads, both including the denoiser (measured).+- It needs no new API surface: WebGL2 is what the job pages already use, `EXT_color_buffer_float` and `EXT_float_blend` are present on the RTX 3060 in headless Chrome, and a page without them falls back to the CPU tracer by choosing `backend: "cpu"` (the default).+- Cost: the kernel takes 13 to 30 s to compile on ANGLE's Direct3D 11 backend (the first version, with one copy of the traversal for every light type, did not finish in 4 minutes). It compiles once per page and is reused by later stills. Keeping a single copy of the shadow-ray traversal (shadow rays are recorded and traced after each light sample) is what made it compile.++Not built: a WGSL compute version. It was not needed to meet the target, and the open questions that made WebGPU attractive (storage buffers for the BVH, no texture size limits, subgroup tricks) did not block the fragment path: the scene tables fit in 2048-wide float textures (the demo room is 1.6 million triangle texels, 800 rows). This is a decision on what was measured, not a measurement of WebGPU compute: a compute path could be faster per ray, and it was not run. If the compile time or the texture-table limits become the bottleneck, the packing in `src/path-tracer-gpu-pack.js` is the part that would move to storage buffers.Each claim carries a tag: **measured** (run on this machine on 2026-10-31), **inferred** (follows from a measurement or a source) or **guessed** (an estimate nobody ran).diff --git a/src/path-tracer-gpu-pack.js b/src/path-tracer-gpu-pack.jsnew file mode 100644index 00000000..9f67454d--- /dev/null+++ b/src/path-tracer-gpu-pack.js@@ -0,0 +1,181 @@+import { DATA_TEXTURE_WIDTH, TRIANGLE_TEXELS, MATERIAL_TEXELS, LIGHT_TEXELS } from './path-tracer-gpu-shader.js';++// Lays a traced scene (path-tracer-scene.js) out as the float textures the GPU kernel reads. Everything here is plain+// typed arrays, so it runs and is tested without a GPU. Each table is a run of RGBA texels, DATA_TEXTURE_WIDTH to a row.++export const ATLAS_WIDTH = 4096;+const MAXIMUM_TEXTURE_SIZE = 16384;++/** A table of `texelCount` RGBA texels, padded to whole rows. */+function createTable(texelCount, channels = 4) {+ const rows = Math.max(1, Math.ceil(texelCount / DATA_TEXTURE_WIDTH));+ if (rows > MAXIMUM_TEXTURE_SIZE) throw new RangeError('The scene is too large for the GPU path tracer tables.');+ return { width: DATA_TEXTURE_WIDTH, height: rows, channels, data: new Float32Array(DATA_TEXTURE_WIDTH * rows * channels) };+}++/** Two texels per node: (minimum, -leaf triangle count or right child) and (maximum, first triangle slot). */+export function packNodes(bvh) {+ const table = createTable(bvh.nodeCount * 2);+ const { data } = table;+ for (let node = 0; node < bvh.nodeCount; node++) {+ const target = node * 8;+ for (let axis = 0; axis < 3; axis++) {+ data[target + axis] = bvh.nodeBounds[node * 6 + axis];+ data[target + 4 + axis] = bvh.nodeBounds[node * 6 + 3 + axis];+ }+ const right = bvh.rightChild[node];+ data[target + 3] = right < 0 ? -bvh.rangeCount[node] : right;+ data[target + 7] = bvh.rangeStart[node];+ }+ return table;+}++/** Nine texels per triangle in leaf order: corner and material, two edges, three normals with u, three colours with v. */+export function packTriangles(scene) {+ const { positions, normals, uvs, colors, indices, triangleMaterial, bvh } = scene;+ const order = bvh.triangleOrder;+ const table = createTable(order.length * TRIANGLE_TEXELS);+ const { data } = table;+ for (let slot = 0; slot < order.length; slot++) {+ const triangle = order[slot];+ const base = slot * TRIANGLE_TEXELS * 4;+ const corners = [indices[triangle * 3], indices[triangle * 3 + 1], indices[triangle * 3 + 2]];+ for (let axis = 0; axis < 3; axis++) {+ const origin = positions[corners[0] * 3 + axis];+ data[base + axis] = origin;+ data[base + 4 + axis] = positions[corners[1] * 3 + axis] - origin;+ data[base + 8 + axis] = positions[corners[2] * 3 + axis] - origin;+ }+ data[base + 3] = triangleMaterial[triangle];+ for (let corner = 0; corner < 3; corner++) {+ const vertex = corners[corner];+ for (let axis = 0; axis < 3; axis++) {+ data[base + (3 + corner) * 4 + axis] = normals[vertex * 3 + axis];+ data[base + (6 + corner) * 4 + axis] = colors[vertex * 3 + axis];+ }+ data[base + (3 + corner) * 4 + 3] = uvs[vertex * 2];+ data[base + (6 + corner) * 4 + 3] = uvs[vertex * 2 + 1];+ }+ }+ return table;+}++/** Shelf-packs the distinct material textures into one RGBA8 atlas; returns where each one went. */+export function packAtlas(materials) {+ const fields = ['texture', 'normalTexture', 'surfaceTexture', 'emissiveTexture'];+ const placements = new Map();+ const textures = [];+ for (const material of materials) {+ for (const field of fields) {+ const texture = material[field];+ if (texture && !placements.has(texture.data)) {+ placements.set(texture.data, null);+ textures.push(texture);+ }+ }+ }+ if (textures.length === 0) return { placements, width: 1, height: 1, data: new Uint8Array(4) };+ textures.sort((first, second) => second.height - first.height);+ let shelfX = 0;+ let shelfY = 0;+ let shelfHeight = 0;+ for (const texture of textures) {+ if (texture.width > ATLAS_WIDTH) throw new RangeError('A material texture is wider than the GPU atlas.');+ if (shelfX + texture.width > ATLAS_WIDTH) {+ shelfY += shelfHeight;+ shelfX = 0;+ shelfHeight = 0;+ }+ placements.set(texture.data, { x: shelfX, y: shelfY });+ shelfX += texture.width;+ shelfHeight = Math.max(shelfHeight, texture.height);+ }+ const height = shelfY + shelfHeight;+ if (height > MAXIMUM_TEXTURE_SIZE) throw new RangeError('The material textures do not fit the GPU atlas.');+ const data = new Uint8Array(ATLAS_WIDTH * height * 4);+ for (const texture of textures) {+ const { x, y } = placements.get(texture.data);+ for (let row = 0; row < texture.height; row++) {+ data.set(texture.data.subarray(row * texture.width * 4, (row + 1) * texture.width * 4), ((y + row) * ATLAS_WIDTH + x) * 4);+ }+ }+ return { placements, width: ATLAS_WIDTH, height, data };+}++function textureFlags(texture) {+ return (texture.repeat ? 1 : 0) + (texture.colorLookup ? 2 : 0);+}++/** Ten texels per material: surface values, texture flags, then one atlas rectangle per map. */+export function packMaterials(materials, atlas) {+ const table = createTable(materials.length * MATERIAL_TEXELS);+ const { data } = table;+ const fields = ['texture', 'normalTexture', 'surfaceTexture', 'emissiveTexture'];+ materials.forEach((material, index) => {+ const base = index * MATERIAL_TEXELS * 4;+ const mask = material.lightMask < 0 ? 0xffffffff : material.lightMask >>> 0;+ data.set([...material.color, material.metallic], base);+ data.set([...material.emission, material.roughness], base + 4);+ data.set([material.clearcoat, material.clearcoatRoughness, material.transmission, material.ior], base + 8);+ data.set([material.normalScale[0], material.normalScale[1], material.alphaCutoff, mask & 0xffff], base + 12);+ data[base + 16] = (mask >>> 16) & 0xffff;+ fields.forEach((field, fieldIndex) => {+ const texture = material[field];+ if (!texture) return;+ const place = atlas.placements.get(texture.data);+ data[base + 17 + fieldIndex] = textureFlags(texture);+ data.set([place.x, place.y, texture.width, texture.height], base + (6 + fieldIndex) * 4);+ });+ });+ return table;+}++const LIGHT_TYPES = { point: 0, spot: 1, area: 2 };++/** Six texels per point, spot or area light, in the order the tracer samples them. */+export function packLights(lights) {+ const entries = [+ ...lights.points.map(light => ({ light, type: LIGHT_TYPES.point })),+ ...lights.spots.map(light => ({ light, type: LIGHT_TYPES.spot })),+ ...lights.areas.map(light => ({ light, type: LIGHT_TYPES.area })),+ ];+ const table = createTable(Math.max(1, entries.length) * LIGHT_TEXELS);+ const { data } = table;+ entries.forEach(({ light, type }, index) => {+ const base = index * LIGHT_TEXELS * 4;+ data.set([...light.position, type], base);+ data.set([...light.color, light.bit], base + 4);+ if (type === LIGHT_TYPES.area) {+ data.set([...light.normal, light.width], base + 8);+ data.set([...light.across, light.height], base + 12);+ data.set([...light.along, 0], base + 16);+ data.set([light.intensity, 0, 0, 0], base + 20);+ return;+ }+ data.set([...(light.direction ?? [0, 0, 0]), light.radius], base + 8);+ data.set([0, 0, 0, light.cosineHalfAngle ?? 0], base + 12);+ data.set([0, 0, 0, light.blend ?? 0], base + 16);+ data.set([light.intensity, light.range, 0, 0], base + 20);+ });+ return { table, count: entries.length };+}++/** 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;+ const { width, height, channels, data: source } = environment;+ const colors = new Float32Array(width * height * 4);+ for (let pixel = 0; pixel < width * height; pixel++) {+ for (let channel = 0; channel < 3; channel++) colors[pixel * 4 + channel] = source[pixel * channels + channel];+ colors[pixel * 4 + 3] = 1;+ }+ const rows = createTable(height, 1);+ const pixels = createTable(width * height, 1);+ const rowTotal = environment.rowCumulative[height - 1];+ for (let row = 0; row < height; row++) rows.data[row] = environment.rowCumulative[row] / rowTotal;+ for (let row = 0; row < height; row++) {+ const rowEnd = environment.pixelCumulative[row * width + width - 1];+ for (let column = 0; column < width; column++) pixels.data[row * width + column] = environment.pixelCumulative[row * width + column] / rowEnd;+ }+ return { colors, width, height, rows, pixels };+}diff --git a/src/path-tracer-gpu-shader.js b/src/path-tracer-gpu-shader.jsnew file mode 100644index 00000000..98303599--- /dev/null+++ b/src/path-tracer-gpu-shader.js@@ -0,0 +1,1045 @@+// The GPU path tracer kernel: a WebGL2 fragment shader that follows the same paths as the CPU tracer in+// path-tracer.js. It reads the BVH, triangles, materials, lights and environment from float textures+// (path-tracer-gpu-pack.js), draws the same random numbers in the same order, and writes one sample per pixel into four+// additive render targets: radiance and depth, albedo, normal, and luminance with its square.++export const DATA_TEXTURE_SHIFT = 11;+export const DATA_TEXTURE_WIDTH = 1 << DATA_TEXTURE_SHIFT;+export const TRIANGLE_TEXELS = 9;+export const MATERIAL_TEXELS = 10;+export const LIGHT_TEXELS = 6;++export const VERTEX_SOURCE = `#version 300 es+void main() {+ vec2 corner = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));+ gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0);+}`;++const SHARED_SOURCE = `#version 300 es+precision highp float;+precision highp int;+precision highp sampler2D;++const float PI = 3.14159265358979;+const float TWO_PI = 6.28318530717959;+const int TEXTURE_SHIFT = ${DATA_TEXTURE_SHIFT};+const int TEXTURE_MASK = ${DATA_TEXTURE_WIDTH - 1};+const int TRIANGLE_TEXELS = ${TRIANGLE_TEXELS};+const int MATERIAL_TEXELS = ${MATERIAL_TEXELS};+const int LIGHT_TEXELS = ${LIGHT_TEXELS};+const int STACK_SIZE = 128;+const int ALPHA_STEP_LIMIT = 8;+const int RUSSIAN_ROULETTE_START = 3;+const float MINIMUM_ALPHA = 1e-3;+const float MIRROR_ALPHA = 2e-3;+const float DIELECTRIC_COAT_REFLECTANCE = 0.04;++uniform sampler2D uNodes;+uniform sampler2D uTriangles;+uniform sampler2D uMaterials;+uniform sampler2D uLights;+uniform sampler2D uAtlas;+uniform sampler2D uEnvironment;+uniform sampler2D uEnvironmentRows;+uniform sampler2D uEnvironmentPixels;++uniform vec3 uEye;+uniform vec3 uForward;+uniform vec3 uRight;+uniform vec3 uAbove;+uniform vec2 uHalfSize;+uniform ivec2 uSize;+uniform int uSample;+uniform uint uSeed;+uniform int uBounces;+uniform float uFireflyClamp;+uniform float uSurfaceOffset;+uniform float uFarDistance;+uniform int uLightCount;+uniform int uEmitterCount;+uniform bool uHasSun;+uniform vec3 uSunDirection;+uniform vec3 uSunColor;+uniform float uSunCosineMax;+uniform bool uHasEnvironment;+uniform vec4 uEnvironmentShape;+uniform vec2 uEnvironmentRotation;+uniform bool uHasVolume;+uniform vec3 uVolumeMinimum;+uniform vec3 uVolumeMaximum;+uniform vec3 uVolumeAlbedo;+uniform vec3 uVolumeShape;++layout(location = 0) out vec4 outRadiance;+layout(location = 1) out vec4 outAlbedo;+layout(location = 2) out vec4 outNormal;+layout(location = 3) out vec4 outStatistics;++vec4 fetchData(sampler2D source, int index) {+ return texelFetch(source, ivec2(index & TEXTURE_MASK, index >> TEXTURE_SHIFT), 0);+}++float fetchScalar(sampler2D source, int index) {+ return texelFetch(source, ivec2(index & TEXTURE_MASK, index >> TEXTURE_SHIFT), 0).r;+}++// ---- Random numbers (the same integer arithmetic as the CPU tracer) ----++uint rngState = 1u;++void resetRandom(uint pixel, uint sampleIndex, uint seed) {+ uint mixed = ((pixel + 0x9e3779b9u) * 0x85ebca6bu) ^ ((sampleIndex + 0x7f4a7c15u) * 0xc2b2ae35u) ^ ((seed + 0x165667b1u) * 0x27d4eb2fu);+ mixed = (mixed ^ (mixed >> 15)) * 0x2c1b3c6du;+ mixed = (mixed ^ (mixed >> 12)) * 0x297a2d39u;+ mixed ^= mixed >> 15;+ rngState = mixed == 0u ? 1u : mixed;+}++float nextRandom() {+ rngState = rngState * 747796405u + 2891336453u;+ uint word = ((rngState >> ((rngState >> 28) + 4u)) ^ rngState) * 277803737u;+ word = (word >> 22) ^ word;+ return float(word >> 8) / 16777216.0;+}++float hashJitter(uint pixel, uint sampleIndex, uint seed, uint dimension) {+ uint mixed = ((pixel ^ 0x51ed270bu) * 0x9e3779b1u) ^ ((sampleIndex + dimension * 0x632be5abu) * 0x85ebca6bu) ^ ((seed + 0x1b873593u) * 0xc2b2ae35u);+ mixed = (mixed ^ (mixed >> 16)) * 0x7feb352du;+ mixed = (mixed ^ (mixed >> 15)) * 0x846ca68bu;+ mixed ^= mixed >> 16;+ return float(mixed >> 8) / 16777216.0;+}++float luminance(vec3 color) {+ return dot(color, vec3(0.2126, 0.7152, 0.0722));+}++// ---- Ray queries ----++float nearestDistance;+int nearestSlot;+float nearestU;+float nearestV;++float safeInverseComponent(float component) {+ if (abs(component) > 1e-20) return 1.0 / component;+ return component < 0.0 ? -1e20 : 1e20;+}++vec3 safeInverse(vec3 direction) {+ return vec3(safeInverseComponent(direction.x), safeInverseComponent(direction.y), safeInverseComponent(direction.z));+}++float boxEntry(int node, vec3 origin, vec3 inverse) {+ vec4 low = fetchData(uNodes, node * 2);+ vec4 high = fetchData(uNodes, node * 2 + 1);+ vec3 first = (low.xyz - origin) * inverse;+ vec3 second = (high.xyz - origin) * inverse;+ vec3 nearest = min(first, second);+ vec3 farthest = max(first, second);+ float entry = max(max(max(nearest.x, nearest.y), nearest.z), 0.0);+ float exitDistance = min(min(farthest.x, farthest.y), farthest.z);+ return entry <= exitDistance * (1.0 + 1e-6) + 1e-6 ? entry : 1e30;+}++bool visitLeaf(int node, vec3 origin, vec3 direction, bool anyHit) {+ vec4 range = fetchData(uNodes, node * 2 + 1);+ vec4 header = fetchData(uNodes, node * 2);+ int start = int(range.w);+ int end = start + int(-header.w);+ for (int slot = start; slot < end; slot++) {+ int base = slot * TRIANGLE_TEXELS;+ vec3 corner = fetchData(uTriangles, base).xyz;+ vec3 edgeFirst = fetchData(uTriangles, base + 1).xyz;+ vec3 edgeSecond = fetchData(uTriangles, base + 2).xyz;+ vec3 pivot = cross(direction, edgeSecond);+ float determinant = dot(edgeFirst, pivot);+ if (determinant == 0.0) continue;+ vec3 offset = origin - corner;+ float firstWeight = dot(offset, pivot) / determinant;+ if (firstWeight < 0.0 || firstWeight > 1.0) continue;+ vec3 query = cross(offset, edgeFirst);+ float secondWeight = dot(direction, query) / determinant;+ if (secondWeight < 0.0 || firstWeight + secondWeight > 1.0) continue;+ float distance = dot(edgeSecond, query) / determinant;+ if (distance < 0.0 || distance >= nearestDistance) continue;+ nearestDistance = distance;+ nearestSlot = slot;+ nearestU = firstWeight;+ nearestV = secondWeight;+ if (anyHit) return true;+ }+ return false;+}++void traceRay(vec3 origin, vec3 direction, float limit, bool anyHit) {+ nearestDistance = limit;+ nearestSlot = -1;+ vec3 inverse = safeInverse(direction);+ int nodeStack[STACK_SIZE];+ float entryStack[STACK_SIZE];+ int stackSize = 1;+ nodeStack[0] = 0;+ entryStack[0] = 0.0;+ while (stackSize > 0) {+ stackSize--;+ int node = nodeStack[stackSize];+ if (!(entryStack[stackSize] < nearestDistance)) continue;+ vec4 header = fetchData(uNodes, node * 2);+ if (header.w < 0.0) {+ if (visitLeaf(node, origin, direction, anyHit)) return;+ continue;+ }+ int left = node + 1;+ int right = int(header.w);+ float leftEntry = boxEntry(left, origin, inverse);+ float rightEntry = boxEntry(right, origin, inverse);+ bool nearFirst = leftEntry <= rightEntry;+ nodeStack[stackSize] = nearFirst ? right : left;+ entryStack[stackSize] = nearFirst ? rightEntry : leftEntry;+ nodeStack[stackSize + 1] = nearFirst ? left : right;+ entryStack[stackSize + 1] = nearFirst ? leftEntry : rightEntry;+ stackSize += 2;+ }+}++// ---- Hits ----++float hitDistance;+vec3 hitPoint;+vec3 hitNormal;+vec3 hitColor;+vec3 hitEmission;+float hitMetallic;+float hitRoughness;+float hitClearcoat;+float hitClearcoatRoughness;+float hitTransmission;+float hitIor;+float hitCutoff;+uint hitMask;++vec3 srgbToLinear(vec3 encoded) {+ return mix(pow((encoded + 0.055) / 1.055, vec3(2.4)), encoded / 12.92, lessThanEqual(encoded, vec3(0.04045)));+}++vec4 sampleAtlas(vec4 rectangle, float flags, vec2 uv) {+ if (rectangle.z <= 0.0) return vec4(1.0);+ int width = int(rectangle.z);+ int height = int(rectangle.w);+ bool repeat = mod(flags, 2.0) >= 1.0;+ bool encoded = flags >= 2.0;+ float x = uv.x * rectangle.z - 0.5;+ float y = uv.y * rectangle.w - 0.5;+ float left = floor(x);+ float top = floor(y);+ float shareX = x - left;+ float shareY = y - top;+ vec4 total = vec4(0.0);+ for (int corner = 0; corner < 4; corner++) {+ int column = int(left) + (corner & 1);+ int row = int(top) + (corner >> 1);+ if (repeat) {+ column = ((column % width) + width) % width;+ row = ((row % height) + height) % height;+ } else {+ column = clamp(column, 0, width - 1);+ row = clamp(row, 0, height - 1);+ }+ float weight = (((corner & 1) == 1) ? shareX : 1.0 - shareX) * (((corner >> 1) == 1) ? shareY : 1.0 - shareY);+ vec4 texel = texelFetch(uAtlas, ivec2(int(rectangle.x) + column, int(rectangle.y) + row), 0);+ vec3 color = encoded ? srgbToLinear(texel.rgb) : texel.rgb;+ total += weight * vec4(color, texel.a);+ }+ return total;+}++void applyNormalMap(vec4 rectangle, float flags, vec2 scale, vec3 edgeOne, vec3 edgeTwo, vec2 uvOne, vec2 uvTwo, vec2 uv) {+ float determinant = uvOne.x * uvTwo.y - uvTwo.x * uvOne.y;+ if (abs(determinant) < 1e-12) return;+ vec3 normal = hitNormal;+ vec3 tangent = (edgeOne * uvTwo.y - edgeTwo * uvOne.y) / determinant;+ vec3 bitangent = (edgeTwo * uvOne.x - edgeOne * uvTwo.x) / determinant;+ tangent -= normal * dot(tangent, normal);+ float tangentLength = length(tangent);+ if (tangentLength == 0.0) return;+ tangent /= tangentLength;+ vec3 across = cross(normal, tangent);+ float acrossLength = length(across);+ if (acrossLength == 0.0) acrossLength = 1.0;+ float handedness = dot(across, bitangent) < 0.0 ? -1.0 : 1.0;+ across *= handedness / acrossLength;+ vec3 texel = sampleAtlas(rectangle, flags, uv).rgb;+ float sideways = (texel.x * 2.0 - 1.0) * scale.x;+ float forwards = (texel.y * 2.0 - 1.0) * scale.y;+ float outwards = texel.z * 2.0 - 1.0;+ vec3 mapped = tangent * sideways + across * forwards + normal * outwards;+ float mappedLength = length(mapped);+ if (!(mappedLength > 1e-6)) return;+ hitNormal = mapped / mappedLength;+}++/** Fills the hit globals from the triangle in \`nearestSlot\`; returns the alpha of the colour map. */+float fillHit(vec3 origin, vec3 direction, float distance) {+ int base = nearestSlot * TRIANGLE_TEXELS;+ vec4 cornerData = fetchData(uTriangles, base);+ vec3 edgeOne = fetchData(uTriangles, base + 1).xyz;+ vec3 edgeTwo = fetchData(uTriangles, base + 2).xyz;+ vec4 normalOneData = fetchData(uTriangles, base + 3);+ vec4 normalTwoData = fetchData(uTriangles, base + 4);+ vec4 normalThreeData = fetchData(uTriangles, base + 5);+ vec4 colorOneData = fetchData(uTriangles, base + 6);+ vec4 colorTwoData = fetchData(uTriangles, base + 7);+ vec4 colorThreeData = fetchData(uTriangles, base + 8);+ float secondWeight = nearestU;+ float thirdWeight = nearestV;+ float firstWeight = 1.0 - secondWeight - thirdWeight;+ hitDistance = distance;+ hitPoint = origin + direction * distance;+ vec3 normal = firstWeight * normalOneData.xyz + secondWeight * normalTwoData.xyz + thirdWeight * normalThreeData.xyz;+ float normalLength = length(normal);+ hitNormal = normal / (normalLength == 0.0 ? 1.0 : normalLength);+ vec3 vertexColor = firstWeight * colorOneData.xyz + secondWeight * colorTwoData.xyz + thirdWeight * colorThreeData.xyz;+ vec2 uv = firstWeight * vec2(normalOneData.w, colorOneData.w) + secondWeight * vec2(normalTwoData.w, colorTwoData.w) + thirdWeight * vec2(normalThreeData.w, colorThreeData.w);+ int material = int(cornerData.w) * MATERIAL_TEXELS;+ vec4 colorMetallic = fetchData(uMaterials, material);+ vec4 emissionRoughness = fetchData(uMaterials, material + 1);+ vec4 coating = fetchData(uMaterials, material + 2);+ vec4 shape = fetchData(uMaterials, material + 3);+ vec4 flagsOne = fetchData(uMaterials, material + 4);+ vec4 flagsTwo = fetchData(uMaterials, material + 5);+ hitColor = colorMetallic.rgb * vertexColor;+ hitEmission = emissionRoughness.rgb;+ hitMetallic = colorMetallic.w;+ hitRoughness = emissionRoughness.w;+ hitClearcoat = coating.x;+ hitClearcoatRoughness = coating.y;+ hitTransmission = coating.z;+ hitIor = coating.w;+ hitCutoff = shape.z;+ hitMask = uint(shape.w) | (uint(flagsOne.x) << 16);+ float alpha = 1.0;+ vec4 mapRectangle = fetchData(uMaterials, material + 6);+ if (mapRectangle.z > 0.0) {+ vec4 texel = sampleAtlas(mapRectangle, flagsOne.y, uv);+ hitColor *= texel.rgb;+ alpha = texel.a;+ }+ vec4 emissiveRectangle = fetchData(uMaterials, material + 9);+ if (emissiveRectangle.z > 0.0) hitEmission *= sampleAtlas(emissiveRectangle, flagsTwo.x, uv).rgb;+ vec4 surfaceRectangle = fetchData(uMaterials, material + 8);+ if (surfaceRectangle.z > 0.0) {+ vec4 texel = sampleAtlas(surfaceRectangle, flagsOne.w, uv);+ hitRoughness *= texel.g;+ hitMetallic *= texel.b;+ }+ vec4 normalRectangle = fetchData(uMaterials, material + 7);+ if (normalRectangle.z > 0.0) {+ vec2 uvOne = vec2(normalTwoData.w - normalOneData.w, colorTwoData.w - colorOneData.w);+ vec2 uvTwo = vec2(normalThreeData.w - normalOneData.w, colorThreeData.w - colorOneData.w);+ applyNormalMap(normalRectangle, flagsOne.z, shape.xy, edgeOne, edgeTwo, uvOne, uvTwo, uv);+ }+ return alpha;+}++/** The nearest solid hit, stepping through the transparent texels of cutout materials. */+bool intersectScene(vec3 origin, vec3 direction) {+ vec3 start = origin;+ float travelled = 0.0;+ for (int attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {+ traceRay(start, direction, uFarDistance, false);+ if (nearestSlot < 0) return false;+ float foundDistance = nearestDistance;+ float alpha = fillHit(start, direction, foundDistance);+ if (hitCutoff == 0.0 || alpha >= hitCutoff) {+ hitDistance += travelled;+ return true;+ }+ float advance = foundDistance + uSurfaceOffset;+ travelled += advance;+ start += direction * advance;+ }+ return false;+}++/** The alpha of the colour map at the nearest hit, without touching the hit globals a shadow ray must not disturb. */+float alphaAtNearestHit() {+ int base = nearestSlot * TRIANGLE_TEXELS;+ float secondWeight = nearestU;+ float thirdWeight = nearestV;+ float firstWeight = 1.0 - secondWeight - thirdWeight;+ vec4 first = fetchData(uTriangles, base + 3);+ vec4 second = fetchData(uTriangles, base + 4);+ vec4 third = fetchData(uTriangles, base + 5);+ vec2 uv = firstWeight * vec2(first.w, fetchData(uTriangles, base + 6).w) + secondWeight * vec2(second.w, fetchData(uTriangles, base + 7).w) + thirdWeight * vec2(third.w, fetchData(uTriangles, base + 8).w);+ int material = int(fetchData(uTriangles, base).w) * MATERIAL_TEXELS;+ vec4 mapRectangle = fetchData(uMaterials, material + 6);+ if (mapRectangle.z <= 0.0) return 1.0;+ return sampleAtlas(mapRectangle, fetchData(uMaterials, material + 4).y, uv).a;+}++bool occluded(vec3 origin, vec3 direction, float limit) {+ vec3 start = origin;+ float remaining = limit;+ for (int attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {+ traceRay(start, direction, remaining, true);+ if (nearestSlot < 0) return false;+ int material = int(fetchData(uTriangles, nearestSlot * TRIANGLE_TEXELS).w) * MATERIAL_TEXELS;+ float cutoff = fetchData(uMaterials, material + 3).z;+ if (cutoff == 0.0) return true;+ if (alphaAtNearestHit() >= cutoff) return true;+ float advance = nearestDistance + uSurfaceOffset;+ remaining -= advance;+ if (remaining <= 0.0) return false;+ start += direction * advance;+ }+ return true;+}++// ---- Frames ----++mat3 buildFrame(vec3 normal) {+ bool helperIsX = abs(normal.x) < 0.9;+ float helperX = helperIsX ? 1.0 : 0.0;+ float helperY = helperIsX ? 0.0 : 1.0;+ vec3 tangent = vec3(-normal.z * helperY, normal.z * helperX, normal.x * helperY - normal.y * helperX);+ tangent = normalize(tangent);+ return mat3(tangent, cross(normal, tangent), normal);+}++vec3 localToWorld(mat3 frame, vec3 local) {+ return frame * local;+}++vec3 worldToLocal(mat3 frame, vec3 world) {+ return transpose(frame) * world;+}++// ---- Environment map ----++vec3 environmentRadiance(vec3 direction) {+ float width = uEnvironmentShape.x;+ float height = uEnvironmentShape.y;+ float mapX = uEnvironmentRotation.x * direction.x - uEnvironmentRotation.y * direction.z;+ float mapZ = uEnvironmentRotation.y * direction.x + uEnvironmentRotation.x * direction.z;+ float column = (atan(mapX, -mapZ) / TWO_PI + 0.5) * width - 0.5;+ float row = acos(clamp(direction.y, -1.0, 1.0)) / PI * height - 0.5;+ float left = floor(column);+ float top = floor(row);+ float shareX = column - left;+ float shareY = row - top;+ int columns = int(width);+ int rows = int(height);+ vec3 total = vec3(0.0);+ for (int corner = 0; corner < 4; corner++) {+ int cornerColumn = ((int(left) + (corner & 1)) % columns + columns) % columns;+ int cornerRow = clamp(int(top) + (corner >> 1), 0, rows - 1);+ float weight = (((corner & 1) == 1) ? shareX : 1.0 - shareX) * (((corner >> 1) == 1) ? shareY : 1.0 - shareY);+ total += weight * texelFetch(uEnvironment, ivec2(cornerColumn, cornerRow), 0).rgb * uEnvironmentShape.z;+ }+ return total;+}++float environmentPdf(vec3 direction) {+ float width = uEnvironmentShape.x;+ float height = uEnvironmentShape.y;+ float mapX = uEnvironmentRotation.x * direction.x - uEnvironmentRotation.y * direction.z;+ float mapZ = uEnvironmentRotation.y * direction.x + uEnvironmentRotation.x * direction.z;+ int column = min(int(width) - 1, int(floor((atan(mapX, -mapZ) / TWO_PI + 0.5) * width)));+ float polar = acos(clamp(direction.y, -1.0, 1.0));+ int row = min(int(height) - 1, int(floor(polar / PI * height)));+ float sinePolar = max(sin(polar), 1e-6);+ float rowWeight = sin(PI * (float(row) + 0.5) / height);+ vec3 texel = texelFetch(uEnvironment, ivec2(column, row), 0).rgb;+ float weight = (luminance(texel) + 1e-6) * rowWeight;+ return weight / uEnvironmentShape.w * width * height / (TWO_PI * PI * sinePolar);+}++int firstIndexAbove(sampler2D cumulative, int start, int end, float target) {+ int low = start;+ int high = end - 1;+ for (int step = 0; step < 24; step++) {+ if (low >= high) break;+ int middle = (low + high) >> 1;+ if (fetchScalar(cumulative, middle) < target) low = middle + 1;+ else high = middle;+ }+ return low;+}++/** Draws a direction in proportion to the map's light; returns its pdf. */+float sampleEnvironment(float rowUnit, float columnUnit, float columnJitter, float rowJitter, out vec3 direction) {+ int width = int(uEnvironmentShape.x);+ int height = int(uEnvironmentShape.y);+ int row = firstIndexAbove(uEnvironmentRows, 0, height, rowUnit);+ int rowBase = row * width;+ int column = firstIndexAbove(uEnvironmentPixels, rowBase, rowBase + width, columnUnit) - rowBase;+ float polar = PI * (float(row) + rowJitter) / float(height);+ float azimuth = ((float(column) + columnJitter) / float(width) - 0.5) * TWO_PI;+ float sinePolar = sin(polar);+ float mapX = sinePolar * sin(azimuth);+ float mapZ = -sinePolar * cos(azimuth);+ direction = vec3(+ uEnvironmentRotation.x * mapX + uEnvironmentRotation.y * mapZ,+ cos(polar),+ -uEnvironmentRotation.y * mapX + uEnvironmentRotation.x * mapZ+ );+ return environmentPdf(direction);+}++// ---- Microfacet pieces ----++float ggxDistribution(float alpha, float cosineHalf) {+ float alphaSquared = alpha * alpha;+ float denominator = cosineHalf * cosineHalf * (alphaSquared - 1.0) + 1.0;+ return alphaSquared / (PI * denominator * denominator);+}++float smithMasking(float alpha, float cosine) {+ float alphaSquared = alpha * alpha;+ return 2.0 * cosine / (cosine + sqrt(alphaSquared + (1.0 - alphaSquared) * cosine * cosine));+}++float schlick(float reflectanceAtNormal, float cosine) {+ float weight = pow(1.0 - clamp(cosine, 0.0, 1.0), 5.0);+ return reflectanceAtNormal + (1.0 - reflectanceAtNormal) * weight;+}++vec3 schlickColor(vec3 reflectanceAtNormal, float cosine) {+ float weight = pow(1.0 - clamp(cosine, 0.0, 1.0), 5.0);+ return reflectanceAtNormal + (1.0 - reflectanceAtNormal) * weight;+}++vec3 sampleVisibleNormal(vec3 view, float alpha, float firstUnit, float secondUnit) {+ vec3 stretched = vec3(alpha * view.x, alpha * view.y, view.z);+ float stretchedLength = length(stretched);+ stretched /= stretchedLength;+ float heightAxis = stretched.z;+ float planeLength = length(stretched.xy);+ vec2 planeDirection = planeLength > 0.0 ? stretched.xy / planeLength : vec2(0.0);+ vec2 tangent = planeLength > 0.0 ? vec2(-stretched.y, stretched.x) / planeLength : vec2(1.0, 0.0);+ vec3 bitangent = vec3(-heightAxis * planeDirection, planeLength);+ float radius = sqrt(firstUnit);+ float angle = TWO_PI * secondUnit;+ float diskX = radius * cos(angle);+ float diskY = radius * sin(angle);+ float blend = 0.5 * (1.0 + heightAxis);+ diskY = (1.0 - blend) * sqrt(1.0 - diskX * diskX) + blend * diskY;+ float lift = sqrt(max(0.0, 1.0 - diskX * diskX - diskY * diskY));+ vec3 normal = vec3(diskX * tangent + diskY * bitangent.xy + lift * stretched.xy, diskY * bitangent.z + lift * heightAxis);+ vec3 unstretched = vec3(alpha * normal.x, alpha * normal.y, max(0.0, normal.z));+ return unstretched / length(unstretched);+}++float roughnessToAlpha(float roughness) {+ return max(roughness * roughness, MINIMUM_ALPHA);+}++// ---- The layered surface ----++mat3 surfaceFrame;+vec3 surfaceView;+float surfaceViewCosine;+vec3 surfaceDiffuse;+vec3 surfaceSpecularNormal;+float surfaceSpecularWeight;+float surfaceSpecularAlpha;+float surfaceCoatWeight;+float surfaceCoatChance;+bool surfaceSampledCoat;+float surfaceCoatAlpha;+float surfaceDiffuseChance;+float surfaceSpecularChance;+vec3 surfaceValue;+float surfacePdf;++float dielectricSpecularAlbedo(float normalReflectance, float roughness, float viewCosine) {+ float smoothness = 1.0 - roughness;+ float slope = min(smoothness * smoothness, exp2(-9.28 * viewCosine)) * smoothness + (0.0425 - 0.0275 * roughness);+ float scale = 1.04 - 0.572 * roughness - 1.04 * slope;+ float offset = 1.04 * slope + 0.022 * roughness - 0.04;+ return clamp(normalReflectance * scale + offset, 0.0, 1.0);+}++void prepareSurface(vec3 normal, vec3 view) {+ surfaceFrame = buildFrame(normal);+ surfaceView = view;+ float viewCosine = max(dot(normal, view), 1e-4);+ surfaceViewCosine = viewCosine;+ float ratio = (hitIor - 1.0) / (hitIor + 1.0);+ float dielectricNormalReflectance = ratio * ratio;+ float dielectricFresnel = dielectricSpecularAlbedo(dielectricNormalReflectance, hitRoughness, viewCosine);+ surfaceCoatWeight = hitClearcoat > 0.0 ? hitClearcoat * schlick(DIELECTRIC_COAT_REFLECTANCE, viewCosine) : 0.0;+ float underCoat = 1.0 - surfaceCoatWeight;+ float diffuseShare = (1.0 - hitMetallic) * (1.0 - dielectricFresnel) * underCoat;+ surfaceDiffuse = hitColor * diffuseShare;+ surfaceSpecularNormal = vec3(dielectricNormalReflectance * (1.0 - hitMetallic)) + hitColor * hitMetallic;+ float specularLuminance = luminance(surfaceSpecularNormal);+ surfaceSpecularWeight = underCoat;+ surfaceSpecularAlpha = roughnessToAlpha(hitRoughness);+ surfaceCoatAlpha = roughnessToAlpha(hitClearcoatRoughness);+ float diffuseLuminance = luminance(surfaceDiffuse);+ float specularChance = schlick(specularLuminance, viewCosine) * underCoat;+ float coatChance = surfaceCoatWeight;+ float sum = diffuseLuminance + specularChance + coatChance;+ surfaceDiffuseChance = sum > 0.0 ? diffuseLuminance / sum : 1.0;+ surfaceSpecularChance = sum > 0.0 ? specularChance / sum : 0.0;+ surfaceCoatChance = sum > 0.0 ? coatChance / sum : 0.0;+}++float microfacetTerm(float alpha, float viewCosine, float lightCosine, float halfCosine) {+ return ggxDistribution(alpha, halfCosine) * smithMasking(alpha, viewCosine) * smithMasking(alpha, lightCosine) / (4.0 * viewCosine * lightCosine);+}++void evaluateSurface(vec3 lightDirection) {+ surfaceValue = vec3(0.0);+ surfacePdf = 0.0;+ vec3 normal = surfaceFrame[2];+ float lightCosine = dot(normal, lightDirection);+ if (lightCosine <= 0.0) return;+ vec3 halfVector = surfaceView + lightDirection;+ float halfLength = length(halfVector);+ halfVector /= halfLength == 0.0 ? 1.0 : halfLength;+ float halfCosine = dot(normal, halfVector);+ float viewHalfCosine = max(dot(surfaceView, halfVector), 0.0);+ float viewCosine = surfaceViewCosine;+ surfacePdf += surfaceDiffuseChance * lightCosine / PI;+ surfaceValue += surfaceDiffuse / PI;+ if (surfaceSpecularChance > 0.0 && surfaceSpecularAlpha > MIRROR_ALPHA) {+ float alpha = surfaceSpecularAlpha;+ float term = microfacetTerm(alpha, viewCosine, lightCosine, halfCosine) * surfaceSpecularWeight;+ surfaceValue += schlickColor(surfaceSpecularNormal, viewHalfCosine) * term;+ surfacePdf += surfaceSpecularChance * smithMasking(alpha, viewCosine) * ggxDistribution(alpha, halfCosine) / (4.0 * viewCosine);+ }+ if (surfaceCoatChance > 0.0 && surfaceCoatAlpha > MIRROR_ALPHA) {+ float alpha = surfaceCoatAlpha;+ float reflectance = schlick(DIELECTRIC_COAT_REFLECTANCE, viewHalfCosine) * microfacetTerm(alpha, viewCosine, lightCosine, halfCosine) * (surfaceCoatWeight / max(schlick(DIELECTRIC_COAT_REFLECTANCE, viewCosine), 1e-6));+ surfaceValue += vec3(reflectance);+ surfacePdf += surfaceCoatChance * smithMasking(alpha, viewCosine) * ggxDistribution(alpha, halfCosine) / (4.0 * viewCosine);+ }+}++/** The next direction of a path; returns true for a mirror lobe, which is followed exactly. */+bool sampleSurface(float lobeUnit, float firstUnit, float secondUnit, out vec3 direction) {+ if (lobeUnit < surfaceDiffuseChance) {+ float radius = sqrt(firstUnit);+ float angle = TWO_PI * secondUnit;+ direction = localToWorld(surfaceFrame, vec3(radius * cos(angle), radius * sin(angle), sqrt(max(0.0, 1.0 - firstUnit))));+ return false;+ }+ bool isCoat = lobeUnit >= surfaceDiffuseChance + surfaceSpecularChance;+ surfaceSampledCoat = isCoat;+ float alpha = isCoat ? surfaceCoatAlpha : surfaceSpecularAlpha;+ vec3 localView = worldToLocal(surfaceFrame, surfaceView);+ if (alpha <= MIRROR_ALPHA) {+ direction = 2.0 * surfaceViewCosine * surfaceFrame[2] - surfaceView;+ return true;+ }+ vec3 localHalf = sampleVisibleNormal(localView, alpha, firstUnit, secondUnit);+ vec3 localLight = 2.0 * dot(localView, localHalf) * localHalf - localView;+ direction = localToWorld(surfaceFrame, localLight);+ return false;+}++vec3 mirrorWeight() {+ if (surfaceSampledCoat) return vec3(surfaceCoatWeight / surfaceCoatChance);+ return schlickColor(surfaceSpecularNormal, surfaceViewCosine) * surfaceSpecularWeight / surfaceSpecularChance;+}++float dielectricFresnelTerm(float cosineIncident, float relativeIndex) {+ float sineSquared = relativeIndex * relativeIndex * (1.0 - cosineIncident * cosineIncident);+ if (sineSquared >= 1.0) return 1.0;+ float cosineTransmitted = sqrt(1.0 - sineSquared);+ float parallel = (relativeIndex * cosineIncident - cosineTransmitted) / (relativeIndex * cosineIncident + cosineTransmitted);+ float perpendicular = (cosineIncident - relativeIndex * cosineTransmitted) / (cosineIncident + relativeIndex * cosineTransmitted);+ return 0.5 * (parallel * parallel + perpendicular * perpendicular);+}++bool sampleGlass(vec3 normal, vec3 view, bool entering, float ior, float alpha, float selectionUnit, float firstUnit, float secondUnit, out vec3 direction) {+ mat3 frame = buildFrame(normal);+ vec3 halfVector = normal;+ if (alpha > MIRROR_ALPHA) {+ vec3 localView = worldToLocal(frame, view);+ halfVector = localToWorld(frame, sampleVisibleNormal(localView, alpha, firstUnit, secondUnit));+ }+ float relativeIndex = entering ? 1.0 / ior : ior;+ float cosineIncident = max(dot(view, halfVector), 1e-6);+ float reflectChance = dielectricFresnelTerm(cosineIncident, relativeIndex);+ if (selectionUnit < reflectChance) {+ direction = 2.0 * dot(view, halfVector) * halfVector - view;+ return dot(direction, normal) > 0.0;+ }+ float cosineTransmitted = sqrt(max(0.0, 1.0 - relativeIndex * relativeIndex * (1.0 - cosineIncident * cosineIncident)));+ float bend = relativeIndex * cosineIncident - cosineTransmitted;+ direction = bend * halfVector - relativeIndex * view;+ return dot(direction, normal) < 0.0;+}++// ---- Fog ----++/** Narrows [entry, exit] to where the ray is inside the slab of one axis; false when it misses the box on that axis. */+bool clipAxis(float origin, float direction, float minimum, float maximum, inout float entry, inout float exitDistance) {+ if (direction == 0.0) return origin >= minimum && origin <= maximum;+ float first = (minimum - origin) / direction;+ float second = (maximum - origin) / direction;+ entry = max(entry, min(first, second));+ exitDistance = min(exitDistance, max(first, second));+ return true;+}++bool volumeInterval(vec3 origin, vec3 direction, float limit, out vec2 span) {+ float entry = 0.0;+ float exitDistance = min(limit, uVolumeShape.z);+ if (!clipAxis(origin.x, direction.x, uVolumeMinimum.x, uVolumeMaximum.x, entry, exitDistance)) return false;+ if (!clipAxis(origin.y, direction.y, uVolumeMinimum.y, uVolumeMaximum.y, entry, exitDistance)) return false;+ if (!clipAxis(origin.z, direction.z, uVolumeMinimum.z, uVolumeMaximum.z, entry, exitDistance)) return false;+ if (!(entry < exitDistance)) return false;+ span = vec2(entry, exitDistance);+ return true;+}++float henyeyGreensteinPhase(float anisotropy, float cosine) {+ float squared = anisotropy * anisotropy;+ return (1.0 - squared) / (4.0 * PI * pow(1.0 + squared - 2.0 * anisotropy * cosine, 1.5));+}++float sampleHenyeyGreensteinCosine(float anisotropy, float unit) {+ if (abs(anisotropy) < 1e-3) return 1.0 - 2.0 * unit;+ float squared = anisotropy * anisotropy;+ float ratio = (1.0 - squared) / (1.0 - anisotropy + 2.0 * anisotropy * unit);+ return clamp((1.0 + squared - ratio * ratio) / (2.0 * anisotropy), -1.0, 1.0);+}++// ---- One path ----++vec3 throughput;+vec3 radiance;+vec3 direction;+vec3 lightDirection;+vec3 lightRadiance;+bool inMedium = false;+float selectionProbability = 1.0;+float environmentSampledPdf = 0.0;+mat3 sunFrame;+vec3 featureAlbedo;+vec3 featureNormal;+float featureDepth;++void addRadiance(int depth, vec3 amount) {+ if (depth > 0) {+ float peak = max(amount.x, max(amount.y, amount.z));+ if (peak > uFireflyClamp) amount *= uFireflyClamp / peak;+ }+ radiance += amount;+}++float fogTransmittance(vec3 origin, float distance) {+ if (!uHasVolume) return 1.0;+ vec2 span;+ if (!volumeInterval(origin, lightDirection, distance, span)) return 1.0;+ return exp(-uVolumeShape.x * (span.y - span.x));+}++float environmentWeight(float candidatePdf) {+ float lightPdf = environmentSampledPdf * selectionProbability;+ float total = lightPdf * lightPdf + candidatePdf * candidatePdf;+ return lightPdf * lightPdf / total / lightPdf;+}++float directWeight(int mode, float candidatePdf) {+ if (mode == 1) return environmentWeight(candidatePdf);+ return 1.0 / selectionProbability;+}++// A shadow ray is recorded by addDirect and traced by flushShadowRay, so the whole shader holds one copy of the+// shadow-ray traversal (a compiler inlines every call, and a copy per light type took minutes to compile).+vec3 shadowOrigin;+vec3 shadowDirection;+float shadowLimit;+vec3 shadowAmount;+int shadowDepth;+bool shadowPending = false;++void addDirect(int depth, vec3 normal, float distance, int weightMode) {+ if (inMedium) {+ float cosine = dot(lightDirection, direction);+ float phase = henyeyGreensteinPhase(uVolumeShape.y, cosine);+ float scale = phase * fogTransmittance(hitPoint, distance) * directWeight(weightMode, phase);+ shadowOrigin = hitPoint;+ shadowAmount = throughput * lightRadiance * scale;+ shadowDepth = depth + 1;+ } else {+ float cosine = dot(normal, lightDirection);+ if (cosine <= 0.0) return;+ evaluateSurface(lightDirection);+ vec3 value = surfaceValue;+ if (value.x + value.y + value.z <= 0.0) return;+ shadowOrigin = hitPoint + normal * uSurfaceOffset;+ float scale = cosine * directWeight(weightMode, surfacePdf) * fogTransmittance(shadowOrigin, distance);+ shadowAmount = throughput * value * lightRadiance * scale;+ shadowDepth = depth;+ }+ shadowDirection = lightDirection;+ shadowLimit = distance;+ shadowPending = true;+}++void flushShadowRay() {+ if (!shadowPending) return;+ shadowPending = false;+ if (!occluded(shadowOrigin, shadowDirection, shadowLimit)) addRadiance(shadowDepth, shadowAmount);+}++bool reaches(int bit) {+ return inMedium || ((hitMask >> uint(bit)) & 1u) == 1u;+}++float aimAt(vec3 target, out float distanceSquared) {+ vec3 delta = target - hitPoint;+ distanceSquared = dot(delta, delta);+ float distance = sqrt(distanceSquared);+ lightDirection = delta / distance;+ return distance;+}++vec3 randomOnSphere(float radius) {+ float height = 2.0 * nextRandom() - 1.0;+ float angle = TWO_PI * nextRandom();+ float ring = sqrt(1.0 - height * height);+ return vec3(radius * ring * cos(angle), radius * height, radius * ring * sin(angle));+}++float pointLightFalloff(float distanceSquared, float range, float radius) {+ float cutoff = 1.0;+ if (range > 0.0) {+ float ratio = distanceSquared / (range * range);+ float fade = max(1.0 - ratio * ratio, 0.0);+ cutoff = fade * fade;+ }+ return cutoff / max(distanceSquared, radius * radius);+}++/** 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. */+void sampleEmitter(int depth, vec3 normal, int emitter) {+ float distance = 0.0;+ int weightMode = 0;+ if (uHasSun && emitter == 0) {+ if (!reaches(0)) return;+ float cosineTheta = 1.0 - nextRandom() * (1.0 - uSunCosineMax);+ float sineTheta = sqrt(max(0.0, 1.0 - cosineTheta * cosineTheta));+ float phi = TWO_PI * nextRandom();+ lightDirection = sunFrame[0] * (sineTheta * cos(phi)) + sunFrame[1] * (sineTheta * sin(phi)) + sunFrame[2] * cosineTheta;+ lightRadiance = uSunColor;+ distance = uFarDistance;+ } else {+ int index = emitter - (uHasSun ? 1 : 0);+ if (index < uLightCount) {+ int base = index * LIGHT_TEXELS;+ vec4 positionType = fetchData(uLights, base);+ vec4 colorBit = fetchData(uLights, base + 1);+ vec4 directionRadius = fetchData(uLights, base + 2);+ vec4 acrossCone = fetchData(uLights, base + 3);+ vec4 alongBlend = fetchData(uLights, base + 4);+ vec4 intensityRange = fetchData(uLights, base + 5);+ int type = int(positionType.w);+ if (!reaches(int(colorBit.w))) return;+ float distanceSquared;+ if (type == 2) {+ float across = (nextRandom() - 0.5) * directionRadius.w;+ float along = (nextRandom() - 0.5) * acrossCone.w;+ vec3 point = positionType.xyz + acrossCone.xyz * across + alongBlend.xyz * along;+ distance = aimAt(point, distanceSquared);+ float emitCosine = -dot(directionRadius.xyz, lightDirection);+ if (distance < 1e-6 || emitCosine <= 0.0) return;+ lightRadiance = colorBit.rgb * (intensityRange.x * emitCosine / distanceSquared);+ } else {+ vec3 jitter = randomOnSphere(directionRadius.w);+ distance = aimAt(positionType.xyz + jitter, distanceSquared);+ if (distance < 1e-6) return;+ float mask = 1.0;+ if (type == 1) {+ float inside = -dot(directionRadius.xyz, lightDirection) - acrossCone.w;+ if (inside <= 0.0) return;+ if (alongBlend.w > 0.0 && inside < alongBlend.w) {+ float unit = inside / alongBlend.w;+ mask = unit * unit * (3.0 - 2.0 * unit);+ }+ }+ lightRadiance = colorBit.rgb * (intensityRange.x * pointLightFalloff(distanceSquared, intensityRange.y, directionRadius.w) * mask);+ }+ distance -= uSurfaceOffset;+ } else {+ vec3 sampled;+ float rowUnit = nextRandom();+ float columnUnit = nextRandom();+ float columnJitter = nextRandom();+ float rowJitter = nextRandom();+ environmentSampledPdf = sampleEnvironment(rowUnit, columnUnit, columnJitter, rowJitter, sampled);+ lightDirection = sampled;+ if (!(environmentSampledPdf > 0.0)) return;+ lightRadiance = environmentRadiance(lightDirection);+ distance = uFarDistance;+ weightMode = 1;+ }+ }+ addDirect(depth, normal, distance, weightMode);+}++/** 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 || uEmitterCount <= 1) {+ selectionProbability = 1.0;+ for (int emitter = 0; emitter < uEmitterCount; emitter++) {+ sampleEmitter(depth, normal, emitter);+ flushShadowRay();+ }+ return;+ }+ selectionProbability = 1.0 / float(uEmitterCount);+ sampleEmitter(depth, normal, int(floor(nextRandom() * float(uEmitterCount))));+ flushShadowRay();+}++void addEscape(int depth, float previousPdf, bool afterMirror) {+ if (!uHasEnvironment) return;+ vec3 sky = environmentRadiance(direction);+ float weight = 1.0;+ if (!afterMirror) {+ float environmentSide = environmentPdf(direction) * selectionProbability;+ weight = previousPdf * previousPdf / (previousPdf * previousPdf + environmentSide * environmentSide);+ }+ addRadiance(depth, throughput * sky * weight);+}++bool survivesRoulette(int depth) {+ if (depth < RUSSIAN_ROULETTE_START) return true;+ float survival = min(0.95, max(0.05, max(throughput.x, max(throughput.y, throughput.z))));+ if (nextRandom() >= survival) return false;+ throughput /= survival;+ return true;+}++bool scatterInFog(vec3 origin, float segmentLength) {+ vec2 span;+ if (!volumeInterval(origin, direction, segmentLength, span)) return false;+ float eventDistance = span.x - log(1.0 - nextRandom()) / uVolumeShape.x;+ if (eventDistance >= span.y) return false;+ hitPoint = origin + direction * eventDistance;+ return true;+}++void tracePath(vec3 origin, vec3 startDirection, uint pixel, uint sampleIndex) {+ resetRandom(pixel, sampleIndex, uSeed);+ radiance = vec3(0.0);+ throughput = vec3(1.0);+ featureAlbedo = vec3(1.0);+ featureNormal = vec3(0.0, 0.0, 1.0);+ featureDepth = 0.0;+ bool featuresRecorded = false;+ direction = startDirection;+ vec3 position = origin;+ float previousPdf = 0.0;+ bool afterMirror = true;+ vec3 normal = vec3(0.0, 1.0, 0.0);+ for (int depth = 0; depth <= uBounces; depth++) {+ bool found = intersectScene(position, direction);+ bool inFog = uHasVolume && scatterInFog(position, found ? hitDistance : uFarDistance);+ if (!inFog && !found) {+ addEscape(depth, previousPdf, afterMirror);+ break;+ }+ bool isGlass = false;+ bool entering = true;+ bool needsLights = true;+ if (inFog) {+ throughput *= uVolumeAlbedo;+ inMedium = true;+ } else {+ entering = dot(hitNormal, direction) < 0.0;+ normal = entering ? hitNormal : -hitNormal;+ isGlass = hitTransmission > 0.0 && nextRandom() < hitTransmission;+ if (!featuresRecorded) {+ featureAlbedo = isGlass ? vec3(1.0) : hitColor;+ featureNormal = normal;+ featureDepth = hitDistance;+ featuresRecorded = true;+ }+ addRadiance(depth, throughput * hitEmission);+ needsLights = !isGlass;+ if (needsLights) prepareSurface(normal, -direction);+ }+ if (needsLights) addLights(depth, normal);+ inMedium = false;+ if (inFog) {+ float cosine = sampleHenyeyGreensteinCosine(uVolumeShape.y, nextRandom());+ float sine = sqrt(max(0.0, 1.0 - cosine * cosine));+ float azimuth = TWO_PI * nextRandom();+ mat3 frame = buildFrame(direction);+ direction = frame[0] * sine * cos(azimuth) + frame[1] * sine * sin(azimuth) + frame[2] * cosine;+ previousPdf = henyeyGreensteinPhase(uVolumeShape.y, cosine);+ afterMirror = false;+ position = hitPoint;+ if (!survivesRoulette(depth)) break;+ continue;+ }+ if (isGlass) {+ float alpha = roughnessToAlpha(hitRoughness);+ float selectionUnit = nextRandom();+ float firstUnit = nextRandom();+ float secondUnit = nextRandom();+ vec3 glassDirection;+ if (!sampleGlass(normal, -direction, entering, hitIor, alpha, selectionUnit, firstUnit, secondUnit, glassDirection)) break;+ direction = glassDirection;+ if (dot(direction, normal) < 0.0) throughput *= hitColor;+ afterMirror = true;+ } else {+ float lobeUnit = nextRandom();+ float firstUnit = nextRandom();+ float secondUnit = nextRandom();+ vec3 sampledDirection;+ bool isMirror = sampleSurface(lobeUnit, firstUnit, secondUnit, sampledDirection);+ direction = sampledDirection;+ float cosine = dot(direction, normal);+ if (cosine <= 0.0) break;+ if (isMirror) {+ throughput *= mirrorWeight();+ afterMirror = true;+ } else {+ evaluateSurface(direction);+ if (!(surfacePdf > 0.0)) break;+ throughput *= surfaceValue * cosine / surfacePdf;+ previousPdf = surfacePdf;+ afterMirror = false;+ }+ }+ position = hitPoint + direction * uSurfaceOffset;+ if (!survivesRoulette(depth)) break;+ }+}++void main() {+ ivec2 pixelCoordinate = ivec2(gl_FragCoord.xy);+ int row = pixelCoordinate.y;+ uint pixel = uint(row * uSize.x + pixelCoordinate.x);+ uint sampleIndex = uint(uSample);+ if (uHasSun) sunFrame = buildFrame(uSunDirection);+ float jitterX = hashJitter(pixel, sampleIndex, uSeed, 1u);+ float jitterY = hashJitter(pixel, sampleIndex, uSeed, 2u);+ float screenX = ((float(pixelCoordinate.x) + jitterX) / float(uSize.x) * 2.0 - 1.0) * uHalfSize.x;+ float screenY = (1.0 - (float(row) + jitterY) / float(uSize.y) * 2.0) * uHalfSize.y;+ vec3 rayDirection = normalize(uForward + uRight * screenX + uAbove * screenY);+ tracePath(uEye, rayDirection, pixel, sampleIndex);+ // A sample that went through a NaN or an infinity (a grazing ray, a zero pdf) counts as black, so it cannot spread through the denoiser.+ if (!(all(greaterThanEqual(radiance, vec3(0.0))) && all(lessThan(radiance, vec3(1e30))))) radiance = vec3(0.0);+ if (!(featureDepth >= 0.0 && featureDepth < 1e30)) featureDepth = 0.0;+ if (!(all(greaterThanEqual(featureNormal, vec3(-1.5))) && all(lessThan(featureNormal, vec3(1.5))))) featureNormal = vec3(0.0, 0.0, 1.0);+ if (!(all(greaterThanEqual(featureAlbedo, vec3(0.0))) && all(lessThan(featureAlbedo, vec3(1e30))))) featureAlbedo = vec3(1.0);+ float sampleLuminance = luminance(radiance);+ outRadiance = vec4(radiance, featureDepth);+ outAlbedo = vec4(featureAlbedo, 0.0);+ outNormal = vec4(featureNormal, 0.0);+ outStatistics = vec4(sampleLuminance, sampleLuminance * sampleLuminance, 0.0, 0.0);+}+`;++export const FRAGMENT_SOURCE = SHARED_SOURCE;diff --git a/src/path-tracer-gpu.js b/src/path-tracer-gpu.jsnew file mode 100644index 00000000..c05ccf2a--- /dev/null+++ b/src/path-tracer-gpu.js@@ -0,0 +1,243 @@+import { FRAGMENT_SOURCE, VERTEX_SOURCE } from './path-tracer-gpu-shader.js';+import { packAtlas, packEnvironment, packLights, packMaterials, packNodes, packTriangles } 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+// CPU tracer stays the reference: the same scene, camera, options and random numbers go in, the same buffers come out.++const TARGET_COUNT = 4;+const DRAW_SECONDS_TARGET = 0.08;+const MINIMUM_BAND_ROWS = 4;+const YIELD_SECONDS = 0.25;++function createCanvas() {+ if (typeof OffscreenCanvas === 'function') return new OffscreenCanvas(1, 1);+ if (typeof document !== 'undefined') return document.createElement('canvas');+ return null;+}++/** True when this page can run the GPU tracer. */+export function isGpuTracerAvailable() {+ const canvas = createCanvas();+ const context = canvas?.getContext('webgl2');+ if (!context) return false;+ return Boolean(context.getExtension('EXT_color_buffer_float') && context.getExtension('EXT_float_blend'));+}++function compileShader(gl, type, source) {+ const shader = gl.createShader(type);+ gl.shaderSource(shader, source);+ gl.compileShader(shader);+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {+ throw new Error(`The GPU path tracer shader did not compile: ${gl.getShaderInfoLog(shader)}`);+ }+ return shader;+}++function createProgram(gl) {+ const program = gl.createProgram();+ gl.attachShader(program, compileShader(gl, gl.VERTEX_SHADER, VERTEX_SOURCE));+ gl.attachShader(program, compileShader(gl, gl.FRAGMENT_SHADER, FRAGMENT_SOURCE));+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(`The GPU path tracer program did not link: ${gl.getProgramInfoLog(program)}`);+ return program;+}++// Textures and targets of the render in progress; the context and program outlive it (compiling the kernel takes seconds).+const resources = [];+let session = null;++function createTexture(gl, unit, internalFormat, format, type, width, height, data) {+ const texture = gl.createTexture();+ resources.push(texture);+ gl.activeTexture(gl.TEXTURE0 + unit);+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);+ gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, data);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ return texture;+}++function uploadScene(gl, program, scene) {+ const atlas = packAtlas(scene.materials);+ const lights = packLights(scene.lights);+ const environment = packEnvironment(scene.environment);+ const nodes = packNodes(scene.bvh);+ const triangles = packTriangles(scene);+ const materials = packMaterials(scene.materials, atlas);+ const floatTables = [['uNodes', nodes], ['uTriangles', triangles], ['uMaterials', materials], ['uLights', lights.table]];+ let unit = 0;+ const bind = (name) => gl.uniform1i(gl.getUniformLocation(program, name), unit++);+ for (const [name, table] of floatTables) {+ createTexture(gl, unit, gl.RGBA32F, gl.RGBA, gl.FLOAT, table.width, table.height, table.data);+ bind(name);+ }+ createTexture(gl, unit, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, atlas.width, atlas.height, atlas.data);+ bind('uAtlas');+ const colors = environment?.colors ?? new Float32Array(4);+ createTexture(gl, unit, gl.RGBA32F, gl.RGBA, gl.FLOAT, environment?.width ?? 1, environment?.height ?? 1, colors);+ bind('uEnvironment');+ const empty = { width: 1, height: 1, data: new Float32Array(1) };+ for (const [name, table] of [['uEnvironmentRows', environment?.rows ?? empty], ['uEnvironmentPixels', environment?.pixels ?? empty]]) {+ createTexture(gl, unit, gl.R32F, gl.RED, gl.FLOAT, table.width, table.height, table.data);+ bind(name);+ }+ return { lightCount: lights.count };+}++function setSceneUniforms(gl, program, scene, camera, options, lightCount) {+ const location = name => gl.getUniformLocation(program, name);+ const { sun } = scene.lights;+ const { environment, volume } = scene;+ gl.uniform3fv(location('uEye'), camera.eye);+ gl.uniform3fv(location('uForward'), camera.forward);+ gl.uniform3fv(location('uRight'), camera.right);+ gl.uniform3fv(location('uAbove'), camera.above);+ gl.uniform2f(location('uHalfSize'), camera.halfWidth, camera.halfHeight);+ gl.uniform2i(location('uSize'), options.width, options.height);+ gl.uniform1ui(location('uSeed'), options.seed >>> 0);+ gl.uniform1i(location('uBounces'), options.bounces);+ gl.uniform1f(location('uFireflyClamp'), options.fireflyClamp);+ gl.uniform1f(location('uSurfaceOffset'), scene.surfaceOffset);+ gl.uniform1f(location('uFarDistance'), scene.farDistance);+ gl.uniform1i(location('uLightCount'), lightCount);+ gl.uniform1i(location('uEmitterCount'), (sun ? 1 : 0) + lightCount + (environment ? 1 : 0));+ gl.uniform1i(location('uHasSun'), sun ? 1 : 0);+ gl.uniform3fv(location('uSunDirection'), sun?.direction ?? [0, 1, 0]);+ gl.uniform3fv(location('uSunColor'), sun?.color ?? [0, 0, 0]);+ gl.uniform1f(location('uSunCosineMax'), Math.cos(Math.PI / 360));+ gl.uniform1i(location('uHasEnvironment'), environment ? 1 : 0);+ gl.uniform4f(location('uEnvironmentShape'), environment?.width ?? 1, environment?.height ?? 1, environment?.intensity ?? 1, environment?.total ?? 1);+ gl.uniform2f(location('uEnvironmentRotation'), environment?.cosine ?? 1, environment?.sine ?? 0);+ gl.uniform1i(location('uHasVolume'), volume ? 1 : 0);+ gl.uniform3fv(location('uVolumeMinimum'), volume?.minimum ?? [0, 0, 0]);+ gl.uniform3fv(location('uVolumeMaximum'), volume?.maximum ?? [0, 0, 0]);+ gl.uniform3fv(location('uVolumeAlbedo'), volume?.albedo ?? [1, 1, 1]);+ gl.uniform3f(location('uVolumeShape'), volume?.density ?? 0, volume?.anisotropy ?? 0, volume?.maxDistance ?? 0);+}++function createTargets(gl, width, height) {+ const framebuffer = gl.createFramebuffer();+ resources.push(framebuffer);+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);+ const attachments = [];+ for (let index = 0; index < TARGET_COUNT; index++) {+ const texture = gl.createTexture();+ resources.push(texture);+ gl.activeTexture(gl.TEXTURE15);+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, width, height, 0, gl.RGBA, gl.FLOAT, null);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + index, gl.TEXTURE_2D, texture, 0);+ attachments.push(gl.COLOR_ATTACHMENT0 + index);+ }+ gl.drawBuffers(attachments);+ if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) throw new Error('The GPU path tracer cannot render to float targets here.');+ gl.clearBufferfv(gl.COLOR, 0, [0, 0, 0, 0]);+ for (let index = 1; index < TARGET_COUNT; index++) gl.clearBufferfv(gl.COLOR, index, [0, 0, 0, 0]);+ return attachments;+}++function readTarget(gl, index, width, height) {+ const pixels = new Float32Array(width * height * 4);+ gl.readBuffer(gl.COLOR_ATTACHMENT0 + index);+ gl.readPixels(0, 0, width, height, gl.RGBA, gl.FLOAT, pixels);+ return pixels;+}++function averageBuffers(gl, width, height, samples) {+ const pixelCount = width * height;+ const radiance = readTarget(gl, 0, width, height);+ const albedo = readTarget(gl, 1, width, height);+ const normal = readTarget(gl, 2, width, height);+ const statistics = readTarget(gl, 3, width, height);+ const buffers = {+ color: new Float32Array(pixelCount * 3), albedo: new Float32Array(pixelCount * 3), normal: new Float32Array(pixelCount * 3),+ depth: new Float32Array(pixelCount), variance: new Float32Array(pixelCount), samplesTaken: new Uint16Array(pixelCount).fill(samples),+ };+ for (let pixel = 0; pixel < pixelCount; pixel++) {+ for (let channel = 0; channel < 3; channel++) {+ buffers.color[pixel * 3 + channel] = radiance[pixel * 4 + channel] / samples;+ buffers.albedo[pixel * 3 + channel] = albedo[pixel * 4 + channel] / samples;+ buffers.normal[pixel * 3 + channel] = normal[pixel * 4 + channel] / samples;+ }+ buffers.depth[pixel] = radiance[pixel * 4 + 3] / samples;+ const mean = statistics[pixel * 4] / samples;+ buffers.variance[pixel] = Math.max(0, statistics[pixel * 4 + 1] / samples - mean * mean) / Math.max(samples - 1, 1);+ }+ return buffers;+}++const nextTask = () => new Promise(resolve => setTimeout(resolve, 0));++/**+ * Traces `options.samples` paths for every pixel and resolves with the same buffers as the CPU tracer+ * (color, albedo, normal, depth, variance, samplesTaken) plus a `gpu` note. `noiseThreshold` is not used: every pixel+ * draws all its samples. `shouldStop` throws when the time limit passes.+ */+function getSession() {+ if (session) return session;+ const canvas = createCanvas();+ const gl = canvas?.getContext('webgl2', { antialias: false, depth: false, stencil: false, alpha: false, powerPreference: 'high-performance' });+ if (!gl) throw new Error('The GPU path tracer needs WebGL2.');+ if (!gl.getExtension('EXT_color_buffer_float') || !gl.getExtension('EXT_float_blend')) throw new Error('The GPU path tracer needs float render targets with blending.');+ const started = performance.now();+ const program = createProgram(gl);+ gl.getProgramParameter(program, gl.LINK_STATUS);+ const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');+ session = { gl, program, compileSeconds: (performance.now() - started) / 1000, gpu: debugInfo ? gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : 'unknown' };+ return session;+}++function releaseResources(gl) {+ for (const resource of resources) {+ if (resource instanceof WebGLFramebuffer) gl.deleteFramebuffer(resource);+ else gl.deleteTexture(resource);+ }+ resources.length = 0;+}++export async function traceOnGpu(scene, camera, options, shouldStop) {+ const { gl, program, compileSeconds, gpu } = getSession();+ const { width, height, samples } = options;+ gl.useProgram(program);+ const { lightCount } = uploadScene(gl, program, scene);+ setSceneUniforms(gl, program, scene, camera, options, lightCount);+ createTargets(gl, width, height);+ gl.viewport(0, 0, width, height);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.ONE, gl.ONE);+ gl.enable(gl.SCISSOR_TEST);+ const sampleLocation = gl.getUniformLocation(program, 'uSample');+ let bandRows = Math.min(height, 32);+ let lastYield = performance.now();+ for (let sample = 0; sample < samples; sample++) {+ gl.uniform1i(sampleLocation, sample);+ let rowStart = 0;+ while (rowStart < height) {+ const rows = Math.min(bandRows, height - rowStart);+ const firstRow = rowStart;+ rowStart += rows;+ const started = performance.now();+ gl.scissor(0, firstRow, width, rows);+ gl.drawArrays(gl.TRIANGLES, 0, 3);+ gl.finish();+ const seconds = (performance.now() - started) / 1000;+ const scale = Math.min(2, DRAW_SECONDS_TARGET / Math.max(seconds, 1e-4));+ bandRows = Math.max(MINIMUM_BAND_ROWS, Math.min(height, Math.round(rows * scale)));+ shouldStop();+ if ((performance.now() - lastYield) / 1000 > YIELD_SECONDS) {+ await nextTask();+ lastYield = performance.now();+ }+ }+ }+ gl.disable(gl.SCISSOR_TEST);+ const buffers = averageBuffers(gl, width, height, samples);+ releaseResources(gl);+ return Object.assign(buffers, { gpu, compileSeconds });+}diff --git a/src/path-tracer.js b/src/path-tracer.jsindex a31b7547..884e8375 100644--- a/src/path-tracer.js+++ b/src/path-tracer.js@@ -97,9 +97,11 @@ export function normalizePathTracerOptions(options = {}) {denoiser: denoiserNamed(options.denoise ?? true),viewTransform: options.viewTransform ?? 'aces',look: options.look ?? null,+ backend: options.backend ?? 'cpu',};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(', ')}.`);+ if (result.backend !== 'cpu' && result.backend !== 'gpu') throw new TypeError('Path tracer backend must be "cpu" or "gpu".');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.');return result;@@ -994,7 +996,15 @@ export async function renderPathTracedImage({ parts, environment = {}, camera },depth: new Float32Array(pixelCount), variance: new Float32Array(pixelCount), samplesTaken: new Uint16Array(pixelCount),};const threads = typeof Worker === 'function' ? options.threads : 1;- if (threads > 1) {+ let gpuName = null;+ let gpuCompileSeconds = 0;+ if (options.backend === 'gpu') {+ const { traceOnGpu } = await import('./path-tracer-gpu.js');+ const traced = await traceOnGpu(scene, view, options, shouldStop);+ gpuName = traced.gpu;+ gpuCompileSeconds = traced.compileSeconds;+ copyBand(buffers, traced, 0, width);+ } else if (threads > 1) {await renderBandsInWorkers(scene, view, { ...options, threads }, buffers, shouldStop);} else {copyBand(buffers, renderBand(scene, view, options, 0, height, shouldStop), 0, width);@@ -1009,6 +1019,7 @@ export async function renderPathTracedImage({ parts, environment = {}, camera },report: {width, height, samples: options.samples, bounces: options.bounces, seed: options.seed, denoised: options.denoiser === 'wavelet',denoiser: options.denoiser, threads,+ backend: options.backend, ...(gpuName ? { gpu: gpuName, gpuCompileSeconds } : {}),averageSamples: totalSamples(samplesTaken) / pixelCount, noiseThreshold: options.noiseThreshold,triangles: scene.indices.length / 3, tracedSeconds, seconds: (performance.now() - started) / 1000,ignored: describeIgnoredFeatures(parts, environment),diff --git a/tests/path-tracer-gpu-pack.test.js b/tests/path-tracer-gpu-pack.test.jsnew file mode 100644index 00000000..7dd460e8--- /dev/null+++ b/tests/path-tracer-gpu-pack.test.js@@ -0,0 +1,92 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import { buildTraceScene } from '../src/path-tracer-scene.js';+import { packAtlas, packLights, packMaterials, packNodes, packTriangles } from '../src/path-tracer-gpu-pack.js';+import { LIGHT_TEXELS, MATERIAL_TEXELS, TRIANGLE_TEXELS } from '../src/path-tracer-gpu-shader.js';++function quad(offset) {+ return {+ positions: new Float32Array([-1, offset, 1, 1, offset, 1, 1, offset, -1, -1, offset, -1]),+ normals: new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]),+ uvs: new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ };+}++const texture = { image: { data: new Uint8Array([255, 0, 0, 255, 0, 255, 0, 128]), width: 2, height: 1 }, colorSpace: 'srgb', wrapS: 10497 };++function sampleScene() {+ const parts = [+ { name: 'floor', geometry: quad(0), material: { color: [0.5, 0.25, 0.125], metallic: 0.5, roughness: 0.3, map: texture } },+ { name: 'ceiling', geometry: quad(2), material: { color: [1, 1, 1], emission: 3, lightMask: 0b101 } },+ ];+ const environment = {+ keyColor: [1, 1, 1],+ lightDirection: [0, 1, 0],+ pointLights: [{ position: [0, 1, 0], color: [1, 0.5, 0.25], intensity: 4, radius: 0.1, range: 5 }],+ areaLights: [{ position: [0, 1.9, 0], color: [1, 1, 1], intensity: 2, width: 0.5, height: 0.25, direction: [0, -1, 0] }],+ };+ return buildTraceScene(parts, environment);+}++test('triangles are packed in leaf order with their corner, edges and material', () => {+ const scene = sampleScene();+ const table = packTriangles(scene);+ const order = scene.bvh.triangleOrder;+ assert.equal(order.length, 4);+ for (let slot = 0; slot < order.length; slot++) {+ const triangle = order[slot];+ const base = slot * TRIANGLE_TEXELS * 4;+ const first = scene.indices[triangle * 3];+ const second = scene.indices[triangle * 3 + 1];+ assert.equal(table.data[base + 1], scene.positions[first * 3 + 1]);+ assert.equal(table.data[base + 4], scene.positions[second * 3] - scene.positions[first * 3]);+ assert.equal(table.data[base + 3], scene.triangleMaterial[triangle]);+ }+});++test('nodes mark a leaf with a negative triangle count and an inner node with its right child', () => {+ const scene = sampleScene();+ const table = packNodes(scene.bvh);+ for (let node = 0; node < scene.bvh.nodeCount; node++) {+ const header = table.data[node * 8 + 3];+ if (scene.bvh.rightChild[node] < 0) assert.equal(header, -scene.bvh.rangeCount[node]);+ else assert.equal(header, scene.bvh.rightChild[node]);+ assert.equal(table.data[node * 8 + 7], scene.bvh.rangeStart[node]);+ }+});++test('materials carry values, the light mask in two halves and an atlas rectangle with its flags', () => {+ const scene = sampleScene();+ const atlas = packAtlas(scene.materials);+ const table = packMaterials(scene.materials, atlas);+ const floor = 0;+ const ceiling = MATERIAL_TEXELS * 4;+ assert.deepEqual([...table.data.subarray(floor, floor + 4)], [0.5, 0.25, 0.125, 0.5]);+ assert.equal(table.data[floor + 12 + 3], 0xffff);+ assert.equal(table.data[floor + 16], 0xffff);+ assert.equal(table.data[ceiling + 12 + 3], 0b101);+ assert.equal(table.data[ceiling + 16], 0);+ assert.equal(table.data[floor + 17], 3, 'repeat and sRGB flags');+ assert.deepEqual([...table.data.subarray(floor + 24, floor + 28)], [0, 0, 2, 1]);+ assert.equal(table.data[ceiling + 24 + 2], 0, 'no map, no rectangle');+ assert.deepEqual([...atlas.data.subarray(0, 8)], [...texture.image.data]);+});++test('the backend option is cpu unless asked, and refuses other names', async () => {+ const { normalizePathTracerOptions } = await import('../src/path-tracer.js');+ assert.equal(normalizePathTracerOptions({}).backend, 'cpu');+ assert.equal(normalizePathTracerOptions({ backend: 'gpu' }).backend, 'gpu');+ assert.throws(() => normalizePathTracerOptions({ backend: 'cuda' }), /backend/);+});++test('lights are packed as points, then spots, then areas', () => {+ const scene = sampleScene();+ const { table, count } = packLights(scene.lights);+ assert.equal(count, 2);+ assert.equal(table.data[3], 0, 'point type');+ assert.equal(table.data[LIGHT_TEXELS * 4 + 3], 2, 'area type');+ assert.equal(table.data[LIGHT_TEXELS * 4 + 11], 0.5, 'area width');+ assert.equal(table.data[20], 4, 'point intensity');+});