3D engine that AI agents drive
Spike: WGSL compute path tracer against the WebGL2 kernel (issue #625)
Nguyen Xuan An821fc276ce26
diff --git a/bench/webgpu-tracer/compare.sh b/bench/webgpu-tracer/compare.shnew file mode 100644index 00000000..38fbee56--- /dev/null+++ b/bench/webgpu-tracer/compare.sh@@ -0,0 +1,12 @@+#!/usr/bin/env bash+# Alternates the two backends three times at 1920 by 1080 and 64 samples, each trace as its own gpu-lock job (a light job).+# The first pair runs in fresh Chrome profiles (cold shader caches), the later pairs reuse them (warm).+# bash bench/webgpu-tracer/compare.sh <output directory>+set -u+OUT="${1:?output directory}"+rm -rf "$OUT/profile-webgl" "$OUT/profile-webgpu"+for RUN in 1 2 3; do+ for VARIANT in webgpu webgl; do+ bash ~/.agents/tools/gpu-lock.sh node bench/webgpu-tracer/run.mjs "$OUT" "$VARIANT" --label "run$RUN" 2>&1 | cut -c1-1500+ done+donediff --git a/bench/webgpu-tracer/flip.py b/bench/webgpu-tracer/flip.pynew file mode 100644index 00000000..ecd7c73f--- /dev/null+++ b/bench/webgpu-tracer/flip.py@@ -0,0 +1,17 @@+# Mean FLIP (LDR) between two tone mapped PNGs: the WebGL2 reference and the WGSL trace.+# uv run --no-project --python 3.12 --with flip-evaluator --with pillow --with numpy python -I bench/webgpu-tracer/flip.py <reference.png> <test.png>+import sys++import flip_evaluator+import numpy as np+from PIL import Image+++def load(path):+ return np.asarray(Image.open(path).convert("RGB"), dtype=np.float32) / 255+++reference = load(sys.argv[1])+test = load(sys.argv[2])+_, mean_error, _ = flip_evaluator.evaluate(reference, test, "LDR", inputsRGB=True)+print(round(float(mean_error), 4))diff --git a/bench/webgpu-tracer/harness.html b/bench/webgpu-tracer/harness.htmlnew file mode 100644index 00000000..38499a6e--- /dev/null+++ b/bench/webgpu-tracer/harness.html@@ -0,0 +1,6 @@+<!doctype html>+<html>+<body>+<script type="module" src="./harness.js"></script>+</body>+</html>diff --git a/bench/webgpu-tracer/harness.js b/bench/webgpu-tracer/harness.jsnew file mode 100644index 00000000..52a03ae8--- /dev/null+++ b/bench/webgpu-tracer/harness.js@@ -0,0 +1,175 @@+// Page side of the issue #625 spike: builds the demo room trace scene once, then traces it with the WGSL megakernel+// (traceWithWebGpu) or with the shipped WebGL2 kernel (traceWithWebGl), undenoised, and returns timings and a tone mapped PNG.+import { KERNEL_SOURCE, WORKGROUP_SIZE } from './kernel.js';+import { packAtlas, packEnvironment, packLights, packMaterials, packNodes, packTriangles } from '/src/path-tracer-gpu-pack.js';+import { createCamera, toneMapToRgba8 } from '/src/path-tracer.js';+import { buildTraceScene } from '/src/path-tracer-scene.js';++let prepared = null;++async function prepareScene(recipe, width, height) {+ 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 agentScene = createAgentScene(recipe);+ const environment = { ...agentScene.environment, map: agentEnvironmentMap(agentScene.environment) };+ const started = performance.now();+ const scene = buildTraceScene(agentScene.parts, environment);+ const camera = createCamera(agentScene.camera, width, height);+ prepared = { scene, camera, width, height };+ return { triangles: scene.indices.length / 3, buildSeconds: (performance.now() - started) / 1000 };+}++function median(values) {+ const sorted = [...values].sort((first, second) => first - second);+ return sorted[Math.floor(sorted.length / 2)];+}++async function pngBase64(linear, width, height) {+ const rgba = toneMapToRgba8(linear, width, height, { viewTransform: 'aces', look: null });+ const canvas = document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;+ canvas.getContext('2d').putImageData(new ImageData(rgba, width, height), 0, 0);+ return canvas.toDataURL('image/png').split(',')[1];+}++// The first call compiles the kernel (its compileSeconds), so tracedSeconds is taken from a second, warm call.+async function traceWithWebGl(options) {+ const { traceOnGpu } = await import('/src/path-tracer-gpu.js');+ const { scene, camera } = prepared;+ const firstStarted = performance.now();+ const first = await traceOnGpu(scene, camera, options, () => {});+ const firstTotalSeconds = (performance.now() - firstStarted) / 1000;+ const started = performance.now();+ const traced = await traceOnGpu(scene, camera, options, () => {});+ const tracedSeconds = (performance.now() - started) / 1000;+ return { gpu: traced.gpu, compileSeconds: first.compileSeconds, firstTotalSeconds, tracedSeconds, image: await pngBase64(traced.color, options.width, options.height) };+}++function createStorageBuffer(device, data, label) {+ const buffer = device.createBuffer({ label, size: Math.max(16, Math.ceil(data.byteLength / 4) * 4), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });+ device.queue.writeBuffer(buffer, 0, data.buffer, data.byteOffset, data.byteLength);+ return buffer;+}++function packAtlasWords(atlas) {+ return new Uint32Array(atlas.data.buffer, atlas.data.byteOffset, Math.floor(atlas.data.byteLength / 4));+}++function writeParams(scene, camera, options, lightCount, atlas, sampleIndex) {+ const buffer = new ArrayBuffer(12 * 16);+ const floats = new Float32Array(buffer);+ const ints = new Int32Array(buffer);+ const words = new Uint32Array(buffer);+ const { sun } = scene.lights;+ const { environment } = scene;+ floats.set([...camera.eye, 0], 0);+ floats.set([...camera.forward, 0], 4);+ floats.set([...camera.right, 0], 8);+ floats.set([...camera.above, 0], 12);+ floats.set([...(sun?.direction ?? [0, 1, 0]), 0], 16);+ floats.set([...(sun?.color ?? [0, 0, 0]), Math.cos(Math.PI / 360)], 20);+ floats.set([environment?.width ?? 1, environment?.height ?? 1, environment?.intensity ?? 1, environment?.total ?? 1], 24);+ floats.set([environment?.cosine ?? 1, environment?.sine ?? 0, scene.surfaceOffset, scene.farDistance], 28);+ floats.set([camera.halfWidth, camera.halfHeight, options.fireflyClamp, 0], 32);+ ints.set([options.width, options.height, options.bounces, lightCount], 36);+ ints.set([(sun ? 1 : 0) + lightCount + (environment ? 1 : 0), sun ? 1 : 0, environment ? 1 : 0, sampleIndex], 40);+ words.set([options.seed >>> 0, atlas.width, 0, 0], 44);+ return buffer;+}++async function traceWithWebGpu(options) {+ const { scene, camera } = prepared;+ const { width, height, samples } = options;+ const pixelCount = width * height;+ const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });+ const device = await adapter.requestDevice({+ requiredLimits: {+ maxStorageBufferBindingSize: Math.min(adapter.limits.maxStorageBufferBindingSize, 1 << 30),+ maxBufferSize: Math.min(adapter.limits.maxBufferSize, 1 << 30),+ },+ });+ device.addEventListener('uncapturederror', event => console.log('WEBGPU ERROR', event.error.message));+ const compileStarted = performance.now();+ const module = device.createShaderModule({ label: 'path tracer', code: KERNEL_SOURCE });+ const info = await module.getCompilationInfo();+ const errors = info.messages.filter(message => message.type === 'error').map(message => `${message.lineNum}: ${message.message}`);+ if (errors.length > 0) throw new Error(`WGSL did not compile:\n${errors.slice(0, 12).join('\n')}`);+ const pipeline = await device.createComputePipelineAsync({ layout: 'auto', compute: { module, entryPoint: 'main' } });+ const compileSeconds = (performance.now() - compileStarted) / 1000;+ // Building the same pipeline again measures the in-process cache, not the driver compile.+ const secondStarted = performance.now();+ await device.createComputePipelineAsync({ layout: 'auto', compute: { module, entryPoint: 'main' } });+ const secondCompileSeconds = (performance.now() - secondStarted) / 1000;++ const uploadStarted = performance.now();+ const atlas = packAtlas(scene.materials);+ const lights = packLights(scene.lights);+ const environment = packEnvironment(scene.environment);+ const environmentTables = new Float32Array(environment ? environment.height + environment.width * environment.height : 4);+ if (environment) {+ environmentTables.set(environment.rows.data.subarray(0, environment.height), 0);+ environmentTables.set(environment.pixels.data.subarray(0, environment.width * environment.height), environment.height);+ }+ const buffers = [+ createStorageBuffer(device, packNodes(scene.bvh).data, 'nodes'),+ createStorageBuffer(device, packTriangles(scene).data, 'triangles'),+ createStorageBuffer(device, packMaterials(scene.materials, atlas).data, 'materials'),+ createStorageBuffer(device, lights.table.data, 'lights'),+ createStorageBuffer(device, packAtlasWords(atlas), 'atlas'),+ createStorageBuffer(device, environment?.colors ?? new Float32Array(4), 'environment colors'),+ createStorageBuffer(device, environmentTables, 'environment tables'),+ ];+ const accumulation = device.createBuffer({ label: 'accumulation', size: pixelCount * 4 * 16, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC });+ const parameters = device.createBuffer({ label: 'parameters', size: 12 * 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });+ const bindGroup = device.createBindGroup({+ layout: pipeline.getBindGroupLayout(0),+ entries: [parameters, ...buffers, accumulation].map((buffer, binding) => ({ binding, resource: { buffer } })),+ });+ await device.queue.onSubmittedWorkDone();+ const uploadSeconds = (performance.now() - uploadStarted) / 1000;++ const traceStarted = performance.now();+ const sampleSeconds = [];+ for (let sampleIndex = 0; sampleIndex < samples; sampleIndex++) {+ const sampleStarted = performance.now();+ device.queue.writeBuffer(parameters, 0, writeParams(scene, camera, options, lights.count, atlas, sampleIndex));+ const encoder = device.createCommandEncoder();+ const pass = encoder.beginComputePass();+ pass.setPipeline(pipeline);+ pass.setBindGroup(0, bindGroup);+ pass.dispatchWorkgroups(Math.ceil(width / WORKGROUP_SIZE), Math.ceil(height / WORKGROUP_SIZE));+ pass.end();+ device.queue.submit([encoder.finish()]);+ await device.queue.onSubmittedWorkDone();+ sampleSeconds.push((performance.now() - sampleStarted) / 1000);+ }+ const dispatchSeconds = (performance.now() - traceStarted) / 1000;++ const readback = device.createBuffer({ size: pixelCount * 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });+ const encoder = device.createCommandEncoder();+ encoder.copyBufferToBuffer(accumulation, 0, readback, 0, pixelCount * 16);+ device.queue.submit([encoder.finish()]);+ await readback.mapAsync(GPUMapMode.READ);+ const sums = new Float32Array(readback.getMappedRange());+ const color = new Float32Array(pixelCount * 3);+ for (let pixel = 0; pixel < pixelCount; pixel++) {+ for (let channel = 0; channel < 3; channel++) color[pixel * 3 + channel] = sums[pixel * 4 + channel] / samples;+ }+ const tracedSeconds = (performance.now() - traceStarted) / 1000;+ const image = await pngBase64(color, width, height);+ return {+ gpu: `${adapter.info.vendor} ${adapter.info.architecture}`, compileSeconds, secondCompileSeconds, uploadSeconds, dispatchSeconds, tracedSeconds,+ firstSampleSeconds: sampleSeconds[0], medianSampleSeconds: median(sampleSeconds), image,+ };+}++window.prepareScene = prepareScene;+window.traceWithWebGl = traceWithWebGl;+window.traceWithWebGpu = traceWithWebGpu;+window.harnessReady = true;diff --git a/bench/webgpu-tracer/kernel.js b/bench/webgpu-tracer/kernel.jsnew file mode 100644index 00000000..79deb948--- /dev/null+++ b/bench/webgpu-tracer/kernel.js@@ -0,0 +1,944 @@+// Spike for issue #625: the GPU path tracer kernel of src/path-tracer-gpu-shader.js written as one WGSL compute shader (a+// megakernel: one invocation traces one pixel's whole path for one sample). The scene tables are the same packed arrays+// (src/path-tracer-gpu-pack.js) bound as storage buffers instead of float textures, and the random numbers, light sampling+// order and shading follow the GLSL line by line, so one seed gives the same picture. Left out on purpose: fog and+// subsurface (the demo room has neither) and the texel bake entry point.++export const WORKGROUP_SIZE = 8;++export const KERNEL_SOURCE = /* wgsl */ `+const PI: f32 = 3.14159265358979;+const TWO_PI: f32 = 6.28318530717959;+const TRIANGLE_TEXELS: i32 = 9;+const MATERIAL_TEXELS: i32 = 10;+const LIGHT_TEXELS: i32 = 6;+const STACK_SIZE: i32 = 128;+const ALPHA_STEP_LIMIT: i32 = 8;+const RUSSIAN_ROULETTE_START: i32 = 3;+const MINIMUM_ALPHA: f32 = 1e-3;+const MIRROR_ALPHA: f32 = 2e-3;+const DIELECTRIC_COAT_REFLECTANCE: f32 = 0.04;++struct Params {+ eye: vec4<f32>,+ forward: vec4<f32>,+ right: vec4<f32>,+ above: vec4<f32>,+ sunDirection: vec4<f32>,+ sunColorAndCosine: vec4<f32>,+ environmentShape: vec4<f32>,+ environmentRotationAndRays: vec4<f32>,+ cameraAndClamp: vec4<f32>,+ sizeBouncesLights: vec4<i32>,+ emittersFlagsSample: vec4<i32>,+ seedAndAtlas: vec4<u32>,+}++@group(0) @binding(0) var<uniform> params: Params;+@group(0) @binding(1) var<storage, read> nodes: array<vec4<f32>>;+@group(0) @binding(2) var<storage, read> triangles: array<vec4<f32>>;+@group(0) @binding(3) var<storage, read> materials: array<vec4<f32>>;+@group(0) @binding(4) var<storage, read> lights: array<vec4<f32>>;+@group(0) @binding(5) var<storage, read> atlas: array<u32>;+@group(0) @binding(6) var<storage, read> environmentColors: array<vec4<f32>>;+@group(0) @binding(7) var<storage, read> environmentTables: array<f32>;+// Four planes of pixelCount vec4 each: radiance and depth, albedo, normal, luminance statistics.+@group(0) @binding(8) var<storage, read_write> accumulation: array<vec4<f32>>;++var<private> rngState: u32 = 1u;++fn resetRandom(pixel: u32, sampleIndex: u32, seed: u32) {+ var mixed = ((pixel + 0x9e3779b9u) * 0x85ebca6bu) ^ ((sampleIndex + 0x7f4a7c15u) * 0xc2b2ae35u) ^ ((seed + 0x165667b1u) * 0x27d4eb2fu);+ mixed = (mixed ^ (mixed >> 15u)) * 0x2c1b3c6du;+ mixed = (mixed ^ (mixed >> 12u)) * 0x297a2d39u;+ mixed ^= mixed >> 15u;+ rngState = select(mixed, 1u, mixed == 0u);+}++fn nextRandom() -> f32 {+ rngState = rngState * 747796405u + 2891336453u;+ var word = ((rngState >> ((rngState >> 28u) + 4u)) ^ rngState) * 277803737u;+ word = (word >> 22u) ^ word;+ return f32(word >> 8u) / 16777216.0;+}++fn hashJitter(pixel: u32, sampleIndex: u32, seed: u32, dimension: u32) -> f32 {+ var mixed = ((pixel ^ 0x51ed270bu) * 0x9e3779b1u) ^ ((sampleIndex + dimension * 0x632be5abu) * 0x85ebca6bu) ^ ((seed + 0x1b873593u) * 0xc2b2ae35u);+ mixed = (mixed ^ (mixed >> 16u)) * 0x7feb352du;+ mixed = (mixed ^ (mixed >> 15u)) * 0x846ca68bu;+ mixed ^= mixed >> 16u;+ return f32(mixed >> 8u) / 16777216.0;+}++fn luminance(color: vec3<f32>) -> f32 {+ return dot(color, vec3<f32>(0.2126, 0.7152, 0.0722));+}++// ---- Ray queries ----++var<private> nearestDistance: f32;+var<private> nearestSlot: i32;+var<private> nearestU: f32;+var<private> nearestV: f32;+var<private> nodeStack: array<i32, 128>;+var<private> entryStack: array<f32, 128>;++fn safeInverseComponent(component: f32) -> f32 {+ if (abs(component) > 1e-20) { return 1.0 / component; }+ return select(1e20, -1e20, component < 0.0);+}++fn safeInverse(direction: vec3<f32>) -> vec3<f32> {+ return vec3<f32>(safeInverseComponent(direction.x), safeInverseComponent(direction.y), safeInverseComponent(direction.z));+}++fn boxEntry(node: i32, origin: vec3<f32>, inverse: vec3<f32>) -> f32 {+ let low = nodes[node * 2];+ let high = nodes[node * 2 + 1];+ let first = (low.xyz - origin) * inverse;+ let second = (high.xyz - origin) * inverse;+ let nearest = min(first, second);+ let farthest = max(first, second);+ let entry = max(max(max(nearest.x, nearest.y), nearest.z), 0.0);+ let exitDistance = min(min(farthest.x, farthest.y), farthest.z);+ return select(1e30, entry, entry <= exitDistance * (1.0 + 1e-6) + 1e-6);+}++fn visitLeaf(node: i32, origin: vec3<f32>, direction: vec3<f32>, anyHit: bool) -> bool {+ let range = nodes[node * 2 + 1];+ let header = nodes[node * 2];+ let start = i32(range.w);+ let end = start + i32(-header.w);+ for (var slot = start; slot < end; slot++) {+ let base = slot * TRIANGLE_TEXELS;+ let corner = triangles[base].xyz;+ let edgeFirst = triangles[base + 1].xyz;+ let edgeSecond = triangles[base + 2].xyz;+ let pivot = cross(direction, edgeSecond);+ let determinant = dot(edgeFirst, pivot);+ if (determinant == 0.0) { continue; }+ let offset = origin - corner;+ let firstWeight = dot(offset, pivot) / determinant;+ if (firstWeight < 0.0 || firstWeight > 1.0) { continue; }+ let query = cross(offset, edgeFirst);+ let secondWeight = dot(direction, query) / determinant;+ if (secondWeight < 0.0 || firstWeight + secondWeight > 1.0) { continue; }+ let 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;+}++fn traceRay(origin: vec3<f32>, direction: vec3<f32>, limit: f32, anyHit: bool) {+ nearestDistance = limit;+ nearestSlot = -1;+ let inverse = safeInverse(direction);+ var stackSize = 1;+ nodeStack[0] = 0;+ entryStack[0] = 0.0;+ while (stackSize > 0) {+ stackSize--;+ let node = nodeStack[stackSize];+ if (!(entryStack[stackSize] < nearestDistance)) { continue; }+ let header = nodes[node * 2];+ if (header.w < 0.0) {+ if (visitLeaf(node, origin, direction, anyHit)) { return; }+ continue;+ }+ let left = node + 1;+ let right = i32(header.w);+ let leftEntry = boxEntry(left, origin, inverse);+ let rightEntry = boxEntry(right, origin, inverse);+ let nearFirst = leftEntry <= rightEntry;+ nodeStack[stackSize] = select(left, right, nearFirst);+ entryStack[stackSize] = select(leftEntry, rightEntry, nearFirst);+ nodeStack[stackSize + 1] = select(right, left, nearFirst);+ entryStack[stackSize + 1] = select(rightEntry, leftEntry, nearFirst);+ stackSize += 2;+ }+}++// ---- Hits ----++var<private> hitDistance: f32;+var<private> hitPoint: vec3<f32>;+var<private> hitNormal: vec3<f32>;+var<private> hitColor: vec3<f32>;+var<private> hitEmission: vec3<f32>;+var<private> hitMetallic: f32;+var<private> hitRoughness: f32;+var<private> hitClearcoat: f32;+var<private> hitClearcoatRoughness: f32;+var<private> hitTransmission: f32;+var<private> hitIor: f32;+var<private> hitCutoff: f32;+var<private> hitMask: u32;++fn srgbToLinear(encoded: vec3<f32>) -> vec3<f32> {+ return select(pow((encoded + 0.055) / 1.055, vec3<f32>(2.4)), encoded / 12.92, encoded <= vec3<f32>(0.04045));+}++fn atlasTexel(x: i32, y: i32) -> vec4<f32> {+ return unpack4x8unorm(atlas[u32(y) * params.seedAndAtlas.y + u32(x)]);+}++fn sampleAtlas(rectangle: vec4<f32>, flags: f32, uv: vec2<f32>) -> vec4<f32> {+ if (rectangle.z <= 0.0) { return vec4<f32>(1.0); }+ let width = i32(rectangle.z);+ let height = i32(rectangle.w);+ let repeat = (flags % 2.0) >= 1.0;+ let encoded = flags >= 2.0;+ let x = uv.x * rectangle.z - 0.5;+ let y = uv.y * rectangle.w - 0.5;+ let left = floor(x);+ let top = floor(y);+ let shareX = x - left;+ let shareY = y - top;+ var total = vec4<f32>(0.0);+ for (var corner = 0; corner < 4; corner++) {+ var column = i32(left) + (corner & 1);+ var row = i32(top) + (corner >> 1u);+ 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);+ }+ let weight = select(1.0 - shareX, shareX, (corner & 1) == 1) * select(1.0 - shareY, shareY, (corner >> 1u) == 1);+ let texel = atlasTexel(i32(rectangle.x) + column, i32(rectangle.y) + row);+ let color = select(texel.rgb, srgbToLinear(texel.rgb), encoded);+ total += weight * vec4<f32>(color, texel.a);+ }+ return total;+}++fn applyNormalMap(rectangle: vec4<f32>, flags: f32, scale: vec2<f32>, edgeOne: vec3<f32>, edgeTwo: vec3<f32>, uvOne: vec2<f32>, uvTwo: vec2<f32>, uv: vec2<f32>) {+ let determinant = uvOne.x * uvTwo.y - uvTwo.x * uvOne.y;+ if (abs(determinant) < 1e-12) { return; }+ let normal = hitNormal;+ var tangent = (edgeOne * uvTwo.y - edgeTwo * uvOne.y) / determinant;+ let bitangent = (edgeTwo * uvOne.x - edgeOne * uvTwo.x) / determinant;+ tangent -= normal * dot(tangent, normal);+ let tangentLength = length(tangent);+ if (tangentLength == 0.0) { return; }+ tangent /= tangentLength;+ var across = cross(normal, tangent);+ var acrossLength = length(across);+ if (acrossLength == 0.0) { acrossLength = 1.0; }+ let handedness = select(1.0, -1.0, dot(across, bitangent) < 0.0);+ across *= handedness / acrossLength;+ let texel = sampleAtlas(rectangle, flags, uv).rgb;+ let sideways = (texel.x * 2.0 - 1.0) * scale.x;+ let forwards = (texel.y * 2.0 - 1.0) * scale.y;+ let outwards = texel.z * 2.0 - 1.0;+ let mapped = tangent * sideways + across * forwards + normal * outwards;+ let 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.+fn fillHit(origin: vec3<f32>, direction: vec3<f32>, distance: f32) -> f32 {+ let base = nearestSlot * TRIANGLE_TEXELS;+ let cornerData = triangles[base];+ let edgeOne = triangles[base + 1].xyz;+ let edgeTwo = triangles[base + 2].xyz;+ let normalOneData = triangles[base + 3];+ let normalTwoData = triangles[base + 4];+ let normalThreeData = triangles[base + 5];+ let colorOneData = triangles[base + 6];+ let colorTwoData = triangles[base + 7];+ let colorThreeData = triangles[base + 8];+ let secondWeight = nearestU;+ let thirdWeight = nearestV;+ let firstWeight = 1.0 - secondWeight - thirdWeight;+ hitDistance = distance;+ hitPoint = origin + direction * distance;+ let normal = firstWeight * normalOneData.xyz + secondWeight * normalTwoData.xyz + thirdWeight * normalThreeData.xyz;+ let normalLength = length(normal);+ hitNormal = normal / select(normalLength, 1.0, normalLength == 0.0);+ let vertexColor = firstWeight * colorOneData.xyz + secondWeight * colorTwoData.xyz + thirdWeight * colorThreeData.xyz;+ let uv = firstWeight * vec2<f32>(normalOneData.w, colorOneData.w) + secondWeight * vec2<f32>(normalTwoData.w, colorTwoData.w) + thirdWeight * vec2<f32>(normalThreeData.w, colorThreeData.w);+ let material = i32(cornerData.w) * MATERIAL_TEXELS;+ let colorMetallic = materials[material];+ let emissionRoughness = materials[material + 1];+ let coating = materials[material + 2];+ let shape = materials[material + 3];+ let flagsOne = materials[material + 4];+ let flagsTwo = materials[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 = u32(shape.w) | (u32(flagsOne.x) << 16u);+ var alpha = 1.0;+ let mapRectangle = materials[material + 6];+ if (mapRectangle.z > 0.0) {+ let texel = sampleAtlas(mapRectangle, flagsOne.y, uv);+ hitColor *= texel.rgb;+ alpha = texel.a;+ }+ let emissiveRectangle = materials[material + 9];+ if (emissiveRectangle.z > 0.0) { hitEmission *= sampleAtlas(emissiveRectangle, flagsTwo.x, uv).rgb; }+ let surfaceRectangle = materials[material + 8];+ if (surfaceRectangle.z > 0.0) {+ let texel = sampleAtlas(surfaceRectangle, flagsOne.w, uv);+ hitRoughness *= texel.g;+ hitMetallic *= texel.b;+ }+ let normalRectangle = materials[material + 7];+ if (normalRectangle.z > 0.0) {+ let uvOne = vec2<f32>(normalTwoData.w - normalOneData.w, colorTwoData.w - colorOneData.w);+ let uvTwo = vec2<f32>(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.+fn intersectScene(origin: vec3<f32>, direction: vec3<f32>) -> bool {+ var start = origin;+ var travelled = 0.0;+ let farDistance = params.environmentRotationAndRays.w;+ let surfaceOffset = params.environmentRotationAndRays.z;+ for (var attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {+ traceRay(start, direction, farDistance, false);+ if (nearestSlot < 0) { return false; }+ let foundDistance = nearestDistance;+ let alpha = fillHit(start, direction, foundDistance);+ if (hitCutoff == 0.0 || alpha >= hitCutoff) {+ hitDistance += travelled;+ return true;+ }+ let advance = foundDistance + surfaceOffset;+ 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.+fn alphaAtNearestHit() -> f32 {+ let base = nearestSlot * TRIANGLE_TEXELS;+ let secondWeight = nearestU;+ let thirdWeight = nearestV;+ let firstWeight = 1.0 - secondWeight - thirdWeight;+ let first = triangles[base + 3];+ let second = triangles[base + 4];+ let third = triangles[base + 5];+ let uv = firstWeight * vec2<f32>(first.w, triangles[base + 6].w) + secondWeight * vec2<f32>(second.w, triangles[base + 7].w) + thirdWeight * vec2<f32>(third.w, triangles[base + 8].w);+ let material = i32(triangles[base].w) * MATERIAL_TEXELS;+ let mapRectangle = materials[material + 6];+ if (mapRectangle.z <= 0.0) { return 1.0; }+ return sampleAtlas(mapRectangle, materials[material + 4].y, uv).a;+}++fn occluded(origin: vec3<f32>, direction: vec3<f32>, limit: f32) -> bool {+ var start = origin;+ var remaining = limit;+ let surfaceOffset = params.environmentRotationAndRays.z;+ for (var attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {+ traceRay(start, direction, remaining, true);+ if (nearestSlot < 0) { return false; }+ let material = i32(triangles[nearestSlot * TRIANGLE_TEXELS].w) * MATERIAL_TEXELS;+ let cutoff = materials[material + 3].z;+ if (cutoff == 0.0) { return true; }+ if (alphaAtNearestHit() >= cutoff) { return true; }+ let advance = nearestDistance + surfaceOffset;+ remaining -= advance;+ if (remaining <= 0.0) { return false; }+ start += direction * advance;+ }+ return true;+}++// ---- Frames ----++fn buildFrame(normal: vec3<f32>) -> mat3x3<f32> {+ let helperIsX = abs(normal.x) < 0.9;+ let helperX = select(0.0, 1.0, helperIsX);+ let helperY = select(1.0, 0.0, helperIsX);+ let tangent = normalize(vec3<f32>(-normal.z * helperY, normal.z * helperX, normal.x * helperY - normal.y * helperX));+ return mat3x3<f32>(tangent, cross(normal, tangent), normal);+}++fn localToWorld(frame: mat3x3<f32>, local: vec3<f32>) -> vec3<f32> {+ return frame * local;+}++fn worldToLocal(frame: mat3x3<f32>, world: vec3<f32>) -> vec3<f32> {+ return transpose(frame) * world;+}++// ---- Environment map ----++fn environmentRadiance(direction: vec3<f32>) -> vec3<f32> {+ let width = params.environmentShape.x;+ let height = params.environmentShape.y;+ let cosine = params.environmentRotationAndRays.x;+ let sine = params.environmentRotationAndRays.y;+ let mapX = cosine * direction.x - sine * direction.z;+ let mapZ = sine * direction.x + cosine * direction.z;+ let column = (atan2(mapX, -mapZ) / TWO_PI + 0.5) * width - 0.5;+ let row = acos(clamp(direction.y, -1.0, 1.0)) / PI * height - 0.5;+ let left = floor(column);+ let top = floor(row);+ let shareX = column - left;+ let shareY = row - top;+ let columns = i32(width);+ let rows = i32(height);+ var total = vec3<f32>(0.0);+ for (var corner = 0; corner < 4; corner++) {+ let cornerColumn = ((i32(left) + (corner & 1)) % columns + columns) % columns;+ let cornerRow = clamp(i32(top) + (corner >> 1u), 0, rows - 1);+ let weight = select(1.0 - shareX, shareX, (corner & 1) == 1) * select(1.0 - shareY, shareY, (corner >> 1u) == 1);+ total += weight * environmentColors[cornerRow * columns + cornerColumn].rgb * params.environmentShape.z;+ }+ return total;+}++fn environmentPdf(direction: vec3<f32>) -> f32 {+ let width = params.environmentShape.x;+ let height = params.environmentShape.y;+ let cosine = params.environmentRotationAndRays.x;+ let sine = params.environmentRotationAndRays.y;+ let mapX = cosine * direction.x - sine * direction.z;+ let mapZ = sine * direction.x + cosine * direction.z;+ let column = min(i32(width) - 1, i32(floor((atan2(mapX, -mapZ) / TWO_PI + 0.5) * width)));+ let polar = acos(clamp(direction.y, -1.0, 1.0));+ let row = min(i32(height) - 1, i32(floor(polar / PI * height)));+ let sinePolar = max(sin(polar), 1e-6);+ let rowWeight = sin(PI * (f32(row) + 0.5) / height);+ let texel = environmentColors[row * i32(width) + column].rgb;+ let weight = (luminance(texel) + 1e-6) * rowWeight;+ return weight / params.environmentShape.w * width * height / (TWO_PI * PI * sinePolar);+}++// The cumulative row table sits first in environmentTables, the per-pixel tables follow it.+fn firstIndexAbove(tableOffset: i32, start: i32, end: i32, threshold: f32) -> i32 {+ var low = start;+ var high = end - 1;+ for (var step = 0; step < 24; step++) {+ if (low >= high) { break; }+ let middle = (low + high) >> 1u;+ if (environmentTables[tableOffset + middle] < threshold) { low = middle + 1; } else { high = middle; }+ }+ return low;+}++var<private> sampledDirection: vec3<f32>;++// Draws a direction in proportion to the map's light into sampledDirection; returns its pdf.+fn sampleEnvironment(rowUnit: f32, columnUnit: f32, columnJitter: f32, rowJitter: f32) -> f32 {+ let width = i32(params.environmentShape.x);+ let height = i32(params.environmentShape.y);+ let row = firstIndexAbove(0, 0, height, rowUnit);+ let rowBase = row * width;+ let column = firstIndexAbove(height, rowBase, rowBase + width, columnUnit) - rowBase;+ let polar = PI * (f32(row) + rowJitter) / f32(height);+ let azimuth = ((f32(column) + columnJitter) / f32(width) - 0.5) * TWO_PI;+ let sinePolar = sin(polar);+ let mapX = sinePolar * sin(azimuth);+ let mapZ = -sinePolar * cos(azimuth);+ let cosine = params.environmentRotationAndRays.x;+ let sine = params.environmentRotationAndRays.y;+ sampledDirection = vec3<f32>(cosine * mapX + sine * mapZ, cos(polar), -sine * mapX + cosine * mapZ);+ return environmentPdf(sampledDirection);+}++// ---- Microfacet pieces ----++fn ggxDistribution(alpha: f32, cosineHalf: f32) -> f32 {+ let alphaSquared = alpha * alpha;+ let denominator = cosineHalf * cosineHalf * (alphaSquared - 1.0) + 1.0;+ return alphaSquared / (PI * denominator * denominator);+}++fn smithMasking(alpha: f32, cosine: f32) -> f32 {+ let alphaSquared = alpha * alpha;+ return 2.0 * cosine / (cosine + sqrt(alphaSquared + (1.0 - alphaSquared) * cosine * cosine));+}++fn schlick(reflectanceAtNormal: f32, cosine: f32) -> f32 {+ let weight = pow(1.0 - clamp(cosine, 0.0, 1.0), 5.0);+ return reflectanceAtNormal + (1.0 - reflectanceAtNormal) * weight;+}++fn schlickColor(reflectanceAtNormal: vec3<f32>, cosine: f32) -> vec3<f32> {+ let weight = pow(1.0 - clamp(cosine, 0.0, 1.0), 5.0);+ return reflectanceAtNormal + (1.0 - reflectanceAtNormal) * weight;+}++fn sampleVisibleNormal(view: vec3<f32>, alpha: f32, firstUnit: f32, secondUnit: f32) -> vec3<f32> {+ var stretched = vec3<f32>(alpha * view.x, alpha * view.y, view.z);+ let stretchedLength = length(stretched);+ stretched /= stretchedLength;+ let heightAxis = stretched.z;+ let planeLength = length(stretched.xy);+ let planeDirection = select(vec2<f32>(0.0), stretched.xy / planeLength, planeLength > 0.0);+ let tangent = select(vec2<f32>(1.0, 0.0), vec2<f32>(-stretched.y, stretched.x) / planeLength, planeLength > 0.0);+ let bitangentXY = -heightAxis * planeDirection;+ let bitangentZ = planeLength;+ let radius = sqrt(firstUnit);+ let angle = TWO_PI * secondUnit;+ let diskX = radius * cos(angle);+ var diskY = radius * sin(angle);+ let blend = 0.5 * (1.0 + heightAxis);+ diskY = (1.0 - blend) * sqrt(1.0 - diskX * diskX) + blend * diskY;+ let lift = sqrt(max(0.0, 1.0 - diskX * diskX - diskY * diskY));+ let normalXY = diskX * tangent + diskY * bitangentXY + lift * stretched.xy;+ let normalZ = diskY * bitangentZ + lift * heightAxis;+ let unstretched = vec3<f32>(alpha * normalXY.x, alpha * normalXY.y, max(0.0, normalZ));+ return unstretched / length(unstretched);+}++fn roughnessToAlpha(roughness: f32) -> f32 {+ return max(roughness * roughness, MINIMUM_ALPHA);+}++// ---- The layered surface ----++var<private> surfaceFrame: mat3x3<f32>;+var<private> surfaceView: vec3<f32>;+var<private> surfaceViewCosine: f32;+var<private> surfaceDiffuse: vec3<f32>;+var<private> surfaceSpecularNormal: vec3<f32>;+var<private> surfaceSpecularWeight: f32;+var<private> surfaceSpecularAlpha: f32;+var<private> surfaceCoatWeight: f32;+var<private> surfaceCoatChance: f32;+var<private> surfaceSampledCoat: bool;+var<private> surfaceCoatAlpha: f32;+var<private> surfaceDiffuseChance: f32;+var<private> surfaceSpecularChance: f32;+var<private> surfaceValue: vec3<f32>;+var<private> surfacePdf: f32;++fn dielectricSpecularAlbedo(normalReflectance: f32, roughness: f32, viewCosine: f32) -> f32 {+ let smoothness = 1.0 - roughness;+ let slope = min(smoothness * smoothness, exp2(-9.28 * viewCosine)) * smoothness + (0.0425 - 0.0275 * roughness);+ let scale = 1.04 - 0.572 * roughness - 1.04 * slope;+ let offset = 1.04 * slope + 0.022 * roughness - 0.04;+ return clamp(normalReflectance * scale + offset, 0.0, 1.0);+}++fn prepareSurface(normal: vec3<f32>, view: vec3<f32>) {+ surfaceFrame = buildFrame(normal);+ surfaceView = view;+ let viewCosine = max(dot(normal, view), 1e-4);+ surfaceViewCosine = viewCosine;+ let ratio = (hitIor - 1.0) / (hitIor + 1.0);+ let dielectricNormalReflectance = ratio * ratio;+ let dielectricFresnel = dielectricSpecularAlbedo(dielectricNormalReflectance, hitRoughness, viewCosine);+ surfaceCoatWeight = select(0.0, hitClearcoat * schlick(DIELECTRIC_COAT_REFLECTANCE, viewCosine), hitClearcoat > 0.0);+ let underCoat = 1.0 - surfaceCoatWeight;+ let diffuseShare = (1.0 - hitMetallic) * (1.0 - dielectricFresnel) * underCoat;+ surfaceDiffuse = hitColor * diffuseShare;+ surfaceSpecularNormal = vec3<f32>(dielectricNormalReflectance * (1.0 - hitMetallic)) + hitColor * hitMetallic;+ let specularLuminance = luminance(surfaceSpecularNormal);+ surfaceSpecularWeight = underCoat;+ surfaceSpecularAlpha = roughnessToAlpha(hitRoughness);+ surfaceCoatAlpha = roughnessToAlpha(hitClearcoatRoughness);+ let diffuseLuminance = luminance(surfaceDiffuse);+ let specularChance = schlick(specularLuminance, viewCosine) * underCoat;+ let coatChance = surfaceCoatWeight;+ let sum = diffuseLuminance + specularChance + coatChance;+ surfaceDiffuseChance = select(1.0, diffuseLuminance / sum, sum > 0.0);+ surfaceSpecularChance = select(0.0, specularChance / sum, sum > 0.0);+ surfaceCoatChance = select(0.0, coatChance / sum, sum > 0.0);+}++fn microfacetTerm(alpha: f32, viewCosine: f32, lightCosine: f32, halfCosine: f32) -> f32 {+ return ggxDistribution(alpha, halfCosine) * smithMasking(alpha, viewCosine) * smithMasking(alpha, lightCosine) / (4.0 * viewCosine * lightCosine);+}++fn evaluateSurface(lightDirection: vec3<f32>) {+ surfaceValue = vec3<f32>(0.0);+ surfacePdf = 0.0;+ let normal = surfaceFrame[2];+ let lightCosine = dot(normal, lightDirection);+ if (lightCosine <= 0.0) { return; }+ var halfVector = surfaceView + lightDirection;+ let halfLength = length(halfVector);+ halfVector /= select(halfLength, 1.0, halfLength == 0.0);+ let halfCosine = dot(normal, halfVector);+ let viewHalfCosine = max(dot(surfaceView, halfVector), 0.0);+ let viewCosine = surfaceViewCosine;+ surfacePdf += surfaceDiffuseChance * lightCosine / PI;+ surfaceValue += surfaceDiffuse / PI;+ if (surfaceSpecularChance > 0.0 && surfaceSpecularAlpha > MIRROR_ALPHA) {+ let alpha = surfaceSpecularAlpha;+ let 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) {+ let alpha = surfaceCoatAlpha;+ let reflectance = schlick(DIELECTRIC_COAT_REFLECTANCE, viewHalfCosine) * microfacetTerm(alpha, viewCosine, lightCosine, halfCosine) * (surfaceCoatWeight / max(schlick(DIELECTRIC_COAT_REFLECTANCE, viewCosine), 1e-6));+ surfaceValue += vec3<f32>(reflectance);+ surfacePdf += surfaceCoatChance * smithMasking(alpha, viewCosine) * ggxDistribution(alpha, halfCosine) / (4.0 * viewCosine);+ }+}++// The next direction of a path goes into sampledDirection; returns true for a mirror lobe, which is followed exactly.+fn sampleSurface(lobeUnit: f32, firstUnit: f32, secondUnit: f32) -> bool {+ if (lobeUnit < surfaceDiffuseChance) {+ let radius = sqrt(firstUnit);+ let angle = TWO_PI * secondUnit;+ sampledDirection = localToWorld(surfaceFrame, vec3<f32>(radius * cos(angle), radius * sin(angle), sqrt(max(0.0, 1.0 - firstUnit))));+ return false;+ }+ let isCoat = lobeUnit >= surfaceDiffuseChance + surfaceSpecularChance;+ surfaceSampledCoat = isCoat;+ let alpha = select(surfaceSpecularAlpha, surfaceCoatAlpha, isCoat);+ let localView = worldToLocal(surfaceFrame, surfaceView);+ if (alpha <= MIRROR_ALPHA) {+ sampledDirection = 2.0 * surfaceViewCosine * surfaceFrame[2] - surfaceView;+ return true;+ }+ let localHalf = sampleVisibleNormal(localView, alpha, firstUnit, secondUnit);+ let localLight = 2.0 * dot(localView, localHalf) * localHalf - localView;+ sampledDirection = localToWorld(surfaceFrame, localLight);+ return false;+}++fn mirrorWeight() -> vec3<f32> {+ if (surfaceSampledCoat) { return vec3<f32>(surfaceCoatWeight / surfaceCoatChance); }+ return schlickColor(surfaceSpecularNormal, surfaceViewCosine) * surfaceSpecularWeight / surfaceSpecularChance;+}++fn dielectricFresnelTerm(cosineIncident: f32, relativeIndex: f32) -> f32 {+ let sineSquared = relativeIndex * relativeIndex * (1.0 - cosineIncident * cosineIncident);+ if (sineSquared >= 1.0) { return 1.0; }+ let cosineTransmitted = sqrt(1.0 - sineSquared);+ let parallel = (relativeIndex * cosineIncident - cosineTransmitted) / (relativeIndex * cosineIncident + cosineTransmitted);+ let perpendicular = (cosineIncident - relativeIndex * cosineTransmitted) / (cosineIncident + relativeIndex * cosineTransmitted);+ return 0.5 * (parallel * parallel + perpendicular * perpendicular);+}++// The glass direction goes into sampledDirection; returns false when the path must end.+fn sampleGlass(normal: vec3<f32>, view: vec3<f32>, entering: bool, ior: f32, alpha: f32, selectionUnit: f32, firstUnit: f32, secondUnit: f32) -> bool {+ let frame = buildFrame(normal);+ var halfVector = normal;+ if (alpha > MIRROR_ALPHA) {+ let localView = worldToLocal(frame, view);+ halfVector = localToWorld(frame, sampleVisibleNormal(localView, alpha, firstUnit, secondUnit));+ }+ let relativeIndex = select(ior, 1.0 / ior, entering);+ let cosineIncident = max(dot(view, halfVector), 1e-6);+ let reflectChance = dielectricFresnelTerm(cosineIncident, relativeIndex);+ if (selectionUnit < reflectChance) {+ sampledDirection = 2.0 * dot(view, halfVector) * halfVector - view;+ return dot(sampledDirection, normal) > 0.0;+ }+ let cosineTransmitted = sqrt(max(0.0, 1.0 - relativeIndex * relativeIndex * (1.0 - cosineIncident * cosineIncident)));+ let bend = relativeIndex * cosineIncident - cosineTransmitted;+ sampledDirection = bend * halfVector - relativeIndex * view;+ return dot(sampledDirection, normal) < 0.0;+}++// ---- One path ----++var<private> throughput: vec3<f32>;+var<private> radiance: vec3<f32>;+var<private> direction: vec3<f32>;+var<private> lightDirection: vec3<f32>;+var<private> lightRadiance: vec3<f32>;+var<private> selectionProbability: f32 = 1.0;+var<private> environmentSampledPdf: f32 = 0.0;+var<private> sunFrame: mat3x3<f32>;+var<private> featureAlbedo: vec3<f32>;+var<private> featureNormal: vec3<f32>;+var<private> featureDepth: f32;+var<private> firstLegEscaped: f32 = 0.0;++fn addRadiance(depth: i32, amountIn: vec3<f32>) {+ var amount = amountIn;+ if (depth > 0) {+ let peak = max(amount.x, max(amount.y, amount.z));+ if (peak > params.cameraAndClamp.z) { amount *= params.cameraAndClamp.z / peak; }+ }+ radiance += amount;+}++fn environmentWeight(candidatePdf: f32) -> f32 {+ let lightPdf = environmentSampledPdf * selectionProbability;+ let total = lightPdf * lightPdf + candidatePdf * candidatePdf;+ return lightPdf * lightPdf / total / lightPdf;+}++fn directWeight(mode: i32, candidatePdf: f32) -> f32 {+ if (mode == 1) { return environmentWeight(candidatePdf); }+ return 1.0 / selectionProbability;+}++// Same shape as the GLSL: addDirect records one shadow ray and flushShadowRay traces it, so the shader holds one copy of the+// shadow-ray traversal.+var<private> shadowOrigin: vec3<f32>;+var<private> shadowDirection: vec3<f32>;+var<private> shadowLimit: f32;+var<private> shadowAmount: vec3<f32>;+var<private> shadowDepth: i32;+var<private> shadowPending: bool = false;++fn addDirect(depth: i32, normal: vec3<f32>, distance: f32, weightMode: i32) {+ let cosine = dot(normal, lightDirection);+ if (cosine <= 0.0) { return; }+ evaluateSurface(lightDirection);+ let value = surfaceValue;+ if (value.x + value.y + value.z <= 0.0) { return; }+ shadowOrigin = hitPoint + normal * params.environmentRotationAndRays.z;+ let scale = cosine * directWeight(weightMode, surfacePdf);+ shadowAmount = throughput * value * lightRadiance * scale;+ shadowDepth = depth;+ shadowDirection = lightDirection;+ shadowLimit = distance;+ shadowPending = true;+}++fn flushShadowRay() {+ if (!shadowPending) { return; }+ shadowPending = false;+ if (!occluded(shadowOrigin, shadowDirection, shadowLimit)) { addRadiance(shadowDepth, shadowAmount); }+}++fn reaches(bit: i32) -> bool {+ return ((hitMask >> u32(bit)) & 1u) == 1u;+}++// Aims lightDirection at the target and returns the distance; distanceSquared goes into aimedDistanceSquared.+var<private> aimedDistanceSquared: f32;++fn aimAt(aimPoint: vec3<f32>) -> f32 {+ let delta = aimPoint - hitPoint;+ aimedDistanceSquared = dot(delta, delta);+ let distance = sqrt(aimedDistanceSquared);+ lightDirection = delta / distance;+ return distance;+}++fn randomOnSphere(radius: f32) -> vec3<f32> {+ let height = 2.0 * nextRandom() - 1.0;+ let angle = TWO_PI * nextRandom();+ let ring = sqrt(1.0 - height * height);+ return vec3<f32>(radius * ring * cos(angle), radius * height, radius * ring * sin(angle));+}++fn pointLightFalloff(distanceSquared: f32, range: f32, radius: f32) -> f32 {+ var cutoff = 1.0;+ if (range > 0.0) {+ let ratio = distanceSquared / (range * range);+ let 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.+fn sampleEmitter(depth: i32, normal: vec3<f32>, emitter: i32) {+ var distance = 0.0;+ var weightMode = 0;+ let hasSun = params.emittersFlagsSample.y != 0;+ let lightCount = params.sizeBouncesLights.w;+ if (hasSun && emitter == 0) {+ if (!reaches(0)) { return; }+ let cosineTheta = 1.0 - nextRandom() * (1.0 - params.sunColorAndCosine.w);+ let sineTheta = sqrt(max(0.0, 1.0 - cosineTheta * cosineTheta));+ let phi = TWO_PI * nextRandom();+ lightDirection = sunFrame[0] * (sineTheta * cos(phi)) + sunFrame[1] * (sineTheta * sin(phi)) + sunFrame[2] * cosineTheta;+ lightRadiance = params.sunColorAndCosine.rgb;+ distance = params.environmentRotationAndRays.w;+ } else {+ let index = emitter - select(0, 1, hasSun);+ if (index < lightCount) {+ let base = index * LIGHT_TEXELS;+ let positionType = lights[base];+ let colorBit = lights[base + 1];+ let directionRadius = lights[base + 2];+ let acrossCone = lights[base + 3];+ let alongBlend = lights[base + 4];+ let intensityRange = lights[base + 5];+ let lightType = i32(positionType.w);+ if (!reaches(i32(colorBit.w))) { return; }+ if (lightType == 2) {+ let across = (nextRandom() - 0.5) * directionRadius.w;+ let along = (nextRandom() - 0.5) * acrossCone.w;+ let point = positionType.xyz + acrossCone.xyz * across + alongBlend.xyz * along;+ distance = aimAt(point);+ let emitCosine = -dot(directionRadius.xyz, lightDirection);+ if (distance < 1e-6 || emitCosine <= 0.0) { return; }+ lightRadiance = colorBit.rgb * (intensityRange.x * emitCosine / aimedDistanceSquared);+ } else {+ let jitter = randomOnSphere(directionRadius.w);+ distance = aimAt(positionType.xyz + jitter);+ if (distance < 1e-6) { return; }+ var mask = 1.0;+ if (lightType == 1) {+ let inside = -dot(directionRadius.xyz, lightDirection) - acrossCone.w;+ if (inside <= 0.0) { return; }+ if (alongBlend.w > 0.0 && inside < alongBlend.w) {+ let unit = inside / alongBlend.w;+ mask = unit * unit * (3.0 - 2.0 * unit);+ }+ }+ lightRadiance = colorBit.rgb * (intensityRange.x * pointLightFalloff(aimedDistanceSquared, intensityRange.y, directionRadius.w) * mask);+ }+ distance -= params.environmentRotationAndRays.z;+ } else {+ let rowUnit = nextRandom();+ let columnUnit = nextRandom();+ let columnJitter = nextRandom();+ let rowJitter = nextRandom();+ environmentSampledPdf = sampleEnvironment(rowUnit, columnUnit, columnJitter, rowJitter);+ lightDirection = sampledDirection;+ if (!(environmentSampledPdf > 0.0)) { return; }+ lightRadiance = environmentRadiance(lightDirection);+ distance = params.environmentRotationAndRays.w;+ 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.+fn addLights(depth: i32, normal: vec3<f32>) {+ let emitterCount = params.emittersFlagsSample.x;+ if (depth == 0 || emitterCount <= 1) {+ selectionProbability = 1.0;+ for (var emitter = 0; emitter < emitterCount; emitter++) {+ sampleEmitter(depth, normal, emitter);+ flushShadowRay();+ }+ return;+ }+ selectionProbability = 1.0 / f32(emitterCount);+ sampleEmitter(depth, normal, i32(floor(nextRandom() * f32(emitterCount))));+ flushShadowRay();+}++fn addEscape(depth: i32, previousPdf: f32, afterMirror: bool) {+ if (params.emittersFlagsSample.z == 0) { return; }+ let sky = environmentRadiance(direction);+ var weight = 1.0;+ if (!afterMirror) {+ let environmentSide = environmentPdf(direction) * selectionProbability;+ weight = previousPdf * previousPdf / (previousPdf * previousPdf + environmentSide * environmentSide);+ }+ addRadiance(depth, throughput * sky * weight);+}++fn survivesRoulette(depth: i32) -> bool {+ if (depth < RUSSIAN_ROULETTE_START) { return true; }+ let survival = min(0.95, max(0.05, max(throughput.x, max(throughput.y, throughput.z))));+ if (nextRandom() >= survival) { return false; }+ throughput /= survival;+ return true;+}++fn tracePath(origin: vec3<f32>, startDirection: vec3<f32>, pixel: u32, sampleIndex: u32) {+ resetRandom(pixel, sampleIndex, params.seedAndAtlas.x);+ radiance = vec3<f32>(0.0);+ throughput = vec3<f32>(1.0);+ featureAlbedo = vec3<f32>(1.0);+ featureNormal = vec3<f32>(0.0, 0.0, 1.0);+ featureDepth = 0.0;+ var featuresRecorded = false;+ direction = startDirection;+ var position = origin;+ var previousPdf = 0.0;+ var afterMirror = true;+ var normal = vec3<f32>(0.0, 1.0, 0.0);+ let bounces = params.sizeBouncesLights.z;+ let surfaceOffset = params.environmentRotationAndRays.z;+ for (var depth = 0; depth <= bounces; depth++) {+ let found = intersectScene(position, direction);+ if (!found) {+ if (depth == 0) { firstLegEscaped = 1.0; }+ addEscape(depth, previousPdf, afterMirror);+ break;+ }+ let entering = dot(hitNormal, direction) < 0.0;+ normal = select(-hitNormal, hitNormal, entering);+ let isGlass = hitTransmission > 0.0 && nextRandom() < hitTransmission;+ if (!featuresRecorded) {+ featureAlbedo = select(hitColor, vec3<f32>(1.0), isGlass);+ featureNormal = normal;+ featureDepth = hitDistance;+ featuresRecorded = true;+ }+ addRadiance(depth, throughput * hitEmission);+ if (!isGlass) {+ prepareSurface(normal, -direction);+ addLights(depth, normal);+ }+ if (isGlass) {+ let alpha = roughnessToAlpha(hitRoughness);+ let selectionUnit = nextRandom();+ let firstUnit = nextRandom();+ let secondUnit = nextRandom();+ if (!sampleGlass(normal, -direction, entering, hitIor, alpha, selectionUnit, firstUnit, secondUnit)) { break; }+ direction = sampledDirection;+ if (dot(direction, normal) < 0.0) { throughput *= hitColor; }+ afterMirror = true;+ } else {+ let lobeUnit = nextRandom();+ let firstUnit = nextRandom();+ let secondUnit = nextRandom();+ let isMirror = sampleSurface(lobeUnit, firstUnit, secondUnit);+ direction = sampledDirection;+ let 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 * surfaceOffset;+ if (!survivesRoulette(depth)) { break; }+ }+}++@compute @workgroup_size(${WORKGROUP_SIZE}, ${WORKGROUP_SIZE}, 1)+fn main(@builtin(global_invocation_id) id: vec3<u32>) {+ let width = params.sizeBouncesLights.x;+ let height = params.sizeBouncesLights.y;+ if (i32(id.x) >= width || i32(id.y) >= height) { return; }+ let pixel = id.y * u32(width) + id.x;+ let sampleIndex = u32(params.emittersFlagsSample.w);+ let seed = params.seedAndAtlas.x;+ if (params.emittersFlagsSample.y != 0) { sunFrame = buildFrame(params.sunDirection.xyz); }+ let jitterX = hashJitter(pixel, sampleIndex, seed, 1u);+ let jitterY = hashJitter(pixel, sampleIndex, seed, 2u);+ let screenX = ((f32(id.x) + jitterX) / f32(width) * 2.0 - 1.0) * params.cameraAndClamp.x;+ let screenY = (1.0 - (f32(id.y) + jitterY) / f32(height) * 2.0) * params.cameraAndClamp.y;+ let rayDirection = normalize(params.forward.xyz + params.right.xyz * screenX + params.above.xyz * screenY);+ tracePath(params.eye.xyz, rayDirection, pixel, sampleIndex);+ if (!(all(radiance >= vec3<f32>(0.0)) && all(radiance < vec3<f32>(1e30)))) { radiance = vec3<f32>(0.0); }+ if (!(featureDepth >= 0.0 && featureDepth < 1e30)) { featureDepth = 0.0; }+ if (!(all(featureNormal >= vec3<f32>(-1.5)) && all(featureNormal < vec3<f32>(1.5)))) { featureNormal = vec3<f32>(0.0, 0.0, 1.0); }+ if (!(all(featureAlbedo >= vec3<f32>(0.0)) && all(featureAlbedo < vec3<f32>(1e30)))) { featureAlbedo = vec3<f32>(1.0); }+ let sampleLuminance = luminance(radiance);+ let pixelCount = u32(width * height);+ accumulation[pixel] += vec4<f32>(radiance, featureDepth);+ accumulation[pixelCount + pixel] += vec4<f32>(featureAlbedo, 0.0);+ accumulation[2u * pixelCount + pixel] += vec4<f32>(featureNormal, 0.0);+ accumulation[3u * pixelCount + pixel] += vec4<f32>(sampleLuminance, sampleLuminance * sampleLuminance, firstLegEscaped, 0.0);+}+`;diff --git a/bench/webgpu-tracer/run.mjs b/bench/webgpu-tracer/run.mjsnew file mode 100644index 00000000..def8a08a--- /dev/null+++ b/bench/webgpu-tracer/run.mjs@@ -0,0 +1,61 @@+// One timed trace of the demo room with one backend, in a headless Chrome whose profile persists per backend (so the first+// run in a fresh profile is the cold compile and later runs are warm). Run it through bash ~/.agents/tools/gpu-lock.sh.+// node bench/webgpu-tracer/run.mjs <output directory> <webgl|webgpu> [--samples 64] [--width 1920] [--height 1080] [--label run1]+// Writes <variant>-<label>.png and <variant>-<label>.json; the profile lives in <output directory>/profile-<variant>.+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 variant = argumentsGiven[1];++function valueAfter(flag, fallback) {+ const index = argumentsGiven.indexOf(flag);+ return index >= 0 ? argumentsGiven[index + 1] : fallback;+}++const options = {+ width: Number(valueAfter('--width', 1920)),+ height: Number(valueAfter('--height', 1080)),+ samples: Number(valueAfter('--samples', 64)),+ bounces: 8,+ seed: 0,+ fireflyClamp: 20,+};+const label = valueAfter('--label', 'run1');++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+await mkdir(outputDirectory, { recursive: true });+const server = await createServer({ server: { host: '127.0.0.1', port: 0, fs: { strict: false } }, logLevel: 'silent' });+await server.listen();+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;+const context = await chromium.launchPersistentContext(`${outputDirectory}/profile-${variant}`, {+ executablePath: CHROME,+ headless: true,+ viewport: { width: 960, height: 540 },+ args: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'],+});+try {+ const page = context.pages()[0] ?? await context.newPage();+ page.on('pageerror', error => console.log('PAGE ERROR', error.message));+ page.on('console', message => { if (message.text().startsWith('WEBGPU ERROR')) console.log(message.text()); });+ page.setDefaultTimeout(0);+ await page.goto(`${serverUrl}/bench/webgpu-tracer/harness.html`, { timeout: 180000 });+ await page.waitForFunction(() => window.harnessReady, null, { timeout: 180000 });+ const recipe = JSON.parse(await readFile('tests/fixtures/demo-room.recipe.json', 'utf8'));+ const scene = await page.evaluate(([sceneRecipe, width, height]) => window.prepareScene(sceneRecipe, width, height), [recipe, options.width, options.height]);+ const result = await page.evaluate(([name, tracerOptions]) => (name === 'webgl' ? window.traceWithWebGl(tracerOptions) : window.traceWithWebGpu(tracerOptions)), [variant, options]);+ const { image, ...numbers } = result;+ await writeFile(`${outputDirectory}/${variant}-${label}.png`, Buffer.from(image, 'base64'));+ const record = { variant, label, ...options, ...scene, ...numbers };+ record.pathsPerSecond = (options.width * options.height * options.samples) / record.tracedSeconds;+ await writeFile(`${outputDirectory}/${variant}-${label}.json`, JSON.stringify(record, null, 1));+ console.log(JSON.stringify(record));+} finally {+ await context.close();+ await server.close();+}diff --git a/bench/webgpu-tracer/validate.mjs b/bench/webgpu-tracer/validate.mjsnew file mode 100644index 00000000..14fbe141--- /dev/null+++ b/bench/webgpu-tracer/validate.mjs@@ -0,0 +1,25 @@+// Compiles the WGSL kernel on SwiftShader's Vulkan adapter (CPU only, no GPU queue) and prints every error with its line.+// node bench/webgpu-tracer/validate.mjs+import { chromium } from 'playwright';+import { createServer } from 'vite';++const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });+await server.listen();+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: ['--enable-unsafe-webgpu', '--enable-unsafe-swiftshader', '--use-webgpu-adapter=swiftshader'] });+try {+ const page = await browser.newPage();+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/bench/webgpu-tracer/harness.html`);+ const messages = await page.evaluate(async () => {+ const { KERNEL_SOURCE } = await import('/bench/webgpu-tracer/kernel.js');+ const adapter = await navigator.gpu.requestAdapter();+ const device = await adapter.requestDevice();+ const module = device.createShaderModule({ code: KERNEL_SOURCE });+ const info = await module.getCompilationInfo();+ return info.messages.map(message => `${message.type} ${message.lineNum}:${message.linePos} ${message.message}`);+ });+ console.log(messages.length === 0 ? 'WGSL ok' : messages.join('\n'));+} finally {+ await browser.close();+ await server.close();+}diff --git a/docs/webgpu-decision.md b/docs/webgpu-decision.mdindex 86a3ba53..1474a3fc 100644--- a/docs/webgpu-decision.md+++ b/docs/webgpu-decision.md@@ -128,3 +128,33 @@ When to look again:- a three.js WebGPU frame beats WebGL2 on the same scenes on the 3060 on a quiet GPU.Not verified: a WGSL port of the 67js shaders; WebGPU timing on a quiet GPU (the RTX 3060 was shared); Firefox, Safari and Android behaviour (support facts only come from MDN and web.dev); the bundle growth of a real second backend.++## Spike for the path tracer: WGSL compute against the WebGL2 kernel (issue #625, 2026-11-08)++The question the first update left open: is a WGSL compute path tracer faster per path than the WebGL2 fragment kernel, and how long does it compile. The spike is `bench/webgpu-tracer/` (not in `src/`, no package export): `kernel.js` is `src/path-tracer-gpu-shader.js` ported to one WGSL megakernel (one invocation traces one pixel's whole path for one sample), `harness.js` and `run.mjs` time it and the shipped WebGL2 kernel on the same scene, `compare.sh` alternates them, `flip.py` scores the pictures.++What the kernel covers: BVH traversal and triangle tests in storage buffers (the same packed tables as the textures, bound as is), the atlas for colour, normal, surface and emissive maps, diffuse, GGX metal, clearcoat and glass, sun, point, spot and area lights with shadow rays, the environment map with importance sampling, 8 bounces, Russian roulette, and the same PCG and hash random numbers in the same order. Left out: fog, subsurface and the texel bake entry point (the demo room uses none of them). It is a megakernel; the wavefront variant (extend, shade, shadow) was not built (see "Not measured").++Setup (measured): `tests/fixtures/demo-room.recipe.json`, 181,708 triangles, 1920 by 1080, 64 samples, 8 bounces, seed 0, firefly clamp 20, no denoiser, headless Chrome 156 with no WebGPU flags, RTX 3060 (adapter `nvidia ampere`; WebGL2 through ANGLE on Direct3D 11), served from localhost, every trace its own `gpu-lock` job, the two backends alternated. The GPU was shared with other sessions (the card sat at 20 to 96 percent use during runs), so the spread below is mostly load. Time is the trace only: BVH build and tone mapping are outside both; WebGL2 time includes its texture upload and readback, WGSL time excludes its buffer upload (0.12 to 0.14 s, under 2 percent) and includes the readback. The WebGL2 number is a second, warm call in the same page, because the first call includes the compile.++| | WebGL2 fragment | WGSL megakernel |+| --- | --- | --- |+| Trace seconds, 4 runs | 15.4, 15.4, 15.6, 16.3 | 8.2, 12.5, 13.0, 17.6 |+| Paths per second (132.7 million paths) | 8.1 to 8.6 million | 7.5 to 16.3 million, median 10.4 million |+| Compile seconds, cold profile (first run) | 19.5 (14.0 in the 480 by 270 check) | 0.75 (1.3 in the 480 by 270 check) |+| Compile seconds, warm profile (runs 2 to 4) | 0.014 to 0.016 | 0.004 to 0.006 |+| Mean FLIP (LDR) against the WebGL2 picture | 0 (same render twice) | 0.0035 at 1080p and 64 samples, 0.0041 at 480 by 270 and 4 samples |++Every row is measured. The cold compile is one sample per backend per size, taken with a fresh Chrome profile; the warm numbers are the profile's disk cache and say nothing about a first visit. The WGSL kernel took `createComputePipelineAsync` 0.75 s cold; a second identical pipeline in the same page took 2 ms (in-process cache).++What this says:++- On the quietest run the megakernel traced 1.9 times as many paths per second as the WebGL2 kernel (8.2 s against 15.4 s), and on the most loaded run it was 1.14 times as slow (17.6 s against 15.4 s). The medians are 12.8 s and 15.5 s, about 1.2 times (measured, load-limited). Whether the quiet-card gap of 1.9 times is the real one needs a card with nothing else on it (guessed; the per-sample time of the quietest run was 0.125 s against 0.29 s of the loudest).+- The compile cost is the clear win: 0.75 s against 19.5 s cold, 26 times less (measured; one sample each, a compile of 13 to 30 s on ANGLE was already known from the first update). The WGSL kernel needed no change to compile fast: it keeps the single shadow-ray traversal, and Dawn on Direct3D 12 builds a megakernel of this size without the minutes ANGLE spends on the unrolled GLSL (inferred).+- The picture is the same scene: FLIP 0.0035 against the WebGL2 output, inside the 0.005 bar the issue sets, with no restricted feature set needed, because the demo room uses only features the kernel covers (measured). The small remainder is float arithmetic order and fast-math differences (inferred).+- Both backends are far under the 40.67 s of the first update at the same size and samples. That number was end to end with the BVH build and the machine in another state, so this run does not show a regression or a gain against it (measured now; the earlier gap is unexplained).+- The 8 storage buffers the kernel binds equal the default `maxStorageBuffersPerShaderStage`, so the scene tables fit with no limit request; the 1080p accumulation buffer is 132.7 MB, just under the 134.2 MB default `maxStorageBufferBindingSize` (measured; the spike asks for larger limits and a real backend should keep the planes in separate buffers).++Go or no-go: **go, for an offline WebGPU tracer backend behind `navigator.gpu`, with WebGL2 kept as the fallback.** Basis: it matches the picture within the issue's FLIP bar, compiles in under a second instead of 14 to 20, and traces about 1.2 times as many paths per second at the median of 4 runs (1.9 times on the quietest, 0.88 times on the most loaded; all measured). The speed gain alone is modest, so the case for a backend rests on the compile time and on the wavefront work the issue wants (shading sorted by material, reservoirs), which this megakernel cannot show and no measurement here supports yet (guessed). The issue's own bar for a go on speed, "traces in less than 40.67 s", is met by both kernels now.++Not measured: the wavefront variant (extend, shade, shadow kernels with sorted shading), which is where a larger gain would have to come from; the 16 path tracer reference scenes (only the demo room and a 480 by 270 check of it were scored); the volume and subsurface features; adapters other than the RTX 3060 and Chrome other than 156; a quiet card; WebGPU timestamp queries (the times are wall clock around `onSubmittedWorkDone`).