3D engine that AI agents drive
Trace fog, subsurface and the texel bake on WebGPU (issue #625)
Nguyen Xuan An5e2702eca50c
diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex 9e716634..420d7ecb 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -335,7 +335,7 @@ async function compareBakeBackends(id, variants) {const results = {};let reference = null;for (const [name, bakeOptions] of Object.entries(variants)) {- if (bakeOptions.backend === 'gpu') await bakeScene(scene, { ...bakeOptions, samples: 1 });+ if (bakeOptions.backend !== 'cpu') await bakeScene(scene, { ...bakeOptions, samples: 1 });const baked = await bakeScene(scene, bakeOptions);const radiance = baked.parts.map(lightmapRadiance);reference ??= radiance;diff --git a/changes/625-parity.md b/changes/625-parity.mdnew file mode 100644index 00000000..14f99b28--- /dev/null+++ b/changes/625-parity.md@@ -0,0 +1 @@+- The WebGPU path tracer (`backend: 'webgpu'`) now traces volume fog and subsurface scattering, compiled into the megakernel only for a scene that uses them, and `bakeLightmapsAsync(..., { backend: 'webgpu' })` bakes lightmap texels on WebGPU with the same report fields. On the `fog` and `subsurface` reference scenes it is within 0.0039 FLIP of WebGL2 (480 by 270, 32 samples, no denoiser), and the `lit-interior` bake gives the same light as WebGL2 in 0.54 s against 0.76 s. The wavefront kernel still refuses fog and subsurface with a clear error. No default changes (#625)diff --git a/changes/625-parity.size.md b/changes/625-parity.size.mdnew file mode 100644index 00000000..4669b538--- /dev/null+++ b/changes/625-parity.size.md@@ -0,0 +1,3 @@+- entry:light-bake-gpu+lazy: the WGSL texel bake chunk (loaded only for backend 'webgpu') holds the WebGPU tracer with fog and the subsurface walk, so a bake on WebGPU is possible without WebGL2; the WebGL2 bake loads none of it.+- entry:path-tracer+lazy: the WGSL fog and subsurface walk (3.9 KB gzip, in the lazy chunk loaded only for backend 'webgpu') so scenes with fog or subsurface no longer need the WebGL2 backend.+- entry:path-tracer-progressive+lazy: the same lazy WebGPU chunk (3.9 KB gzip), shared with the progressive tracer.diff --git a/docs/light-bake.md b/docs/light-bake.mdindex b5c69f45..84469c95 100644--- a/docs/light-bake.md+++ b/docs/light-bake.md@@ -47,7 +47,7 @@ import { bakeLightmapsAsync } from '67js/addons/light-bake-gpu';const { parts: bakedParts, report } = await bakeLightmapsAsync(parts, lighting, { backend: 'gpu', samples: 512, bounces: 2 });```-`backend` is `cpu` (the default and the reference) or `gpu`, named as for the path tracer's `backend`. `bakeLightmapsAsync` takes the same arguments and options as `bakeLightmaps` and resolves with the same `{ parts, report }`; the synchronous `bakeLightmaps` throws a `TypeError` for `gpu` and names this addon. A GPU bake rasterizes the texels as the CPU bake does, then sends all covered texels of all parts to the path tracer's kernel in one batch (`src/light-bake-gpu.js`, `src/path-tracer-gpu.js`): the kernel starts a cosine weighted path at each texel, follows `bounces` hits with the tracer's own lights, materials and maps, and returns the light that arrives. The albedo, smoothing, dilation, sky visibility and the baked parts then come from the same code as on the CPU. It is its own addon (`67js/addons/light-bake-gpu`), so the CPU bake and the core bundle do not carry it. It needs a page with WebGL2 and float render targets (`EXT_color_buffer_float`, `EXT_float_blend`) and throws without them. It takes up to 1,024 parts where the CPU bake takes 256 (`MAX_GPU_BAKE_PARTS`; the texel and ray work limits are the same). It does not take a light with `affects` (the kernel has no light linking) or `skyOnly`, and `report` adds `gpu` and `gpuCompileSeconds` (the kernel compiles once per page). The GPU result is not byte identical to the CPU one: the CPU gatherer treats every part as a diffuse surface, while the kernel also follows specular lobes, clear coat and glass, and it draws other random numbers. On a room of diffuse surfaces the two agree to about 1 percent; a rough dielectric adds about 3 percent of light on the GPU and a glossy floor about 5 (see "Why the GPU light is brighter").+`backend` is `cpu` (the default and the reference), `gpu` or `webgpu`, named as for the path tracer's `backend`. `webgpu` runs the same texel bake as WGSL compute (the `bakeTexels` entry of `src/path-tracer-webgpu-kernel.js`, loaded only for this backend), needs `navigator.gpu` instead of WebGL2, takes the same options, limits and report fields (`gpu`, `gpuCompileSeconds`), and gives the same light as `gpu` to within float rounding. Measured on the RTX 3060 (2026-11-09, one run on a loaded machine, \lit-interior\, 28,784 texels, 512 samples, \ench/reference/bake-compare.mjs\): the WebGPU bake takes 0.54 s against 0.76 s on WebGL2 once compiled, its kernel compiles in 0.39 s against 9.1 s, and the mean light differs by 0.0004 percent (gap share 0.0000035). `bakeLightmapsAsync` takes the same arguments and options as `bakeLightmaps` and resolves with the same `{ parts, report }`; the synchronous `bakeLightmaps` throws a `TypeError` for `gpu` and names this addon. A GPU bake rasterizes the texels as the CPU bake does, then sends all covered texels of all parts to the path tracer's kernel in one batch (`src/light-bake-gpu.js`, `src/path-tracer-gpu.js`): the kernel starts a cosine weighted path at each texel, follows `bounces` hits with the tracer's own lights, materials and maps, and returns the light that arrives. The albedo, smoothing, dilation, sky visibility and the baked parts then come from the same code as on the CPU. It is its own addon (`67js/addons/light-bake-gpu`), so the CPU bake and the core bundle do not carry it. It needs a page with WebGL2 and float render targets (`EXT_color_buffer_float`, `EXT_float_blend`) and throws without them. It takes up to 1,024 parts where the CPU bake takes 256 (`MAX_GPU_BAKE_PARTS`; the texel and ray work limits are the same). It does not take a light with `affects` (the kernel has no light linking) or `skyOnly`, and `report` adds `gpu` and `gpuCompileSeconds` (the kernel compiles once per page). The GPU result is not byte identical to the CPU one: the CPU gatherer treats every part as a diffuse surface, while the kernel also follows specular lobes, clear coat and glass, and it draws other random numbers. On a room of diffuse surfaces the two agree to about 1 percent; a rough dielectric adds about 3 percent of light on the GPU and a glossy floor about 5 (see "Why the GPU light is brighter").The bake traces cosine-weighted paths from each texel through up to `bounces` reflections. Each hit adds its own emission and the direct light it receives from the point lights and the sun, with shadow rays. A texel stores that light times its own albedo. Direct light is not baked: it stays live, so shadows and moving lights keep working. The stored light is only what has bounced at least once, so a scene needs the same lights at run time that it gave the bake.diff --git a/docs/path-tracer.md b/docs/path-tracer.mdindex 5508d226..533c73fc 100644--- a/docs/path-tracer.md+++ b/docs/path-tracer.md@@ -64,7 +64,7 @@ The same scene and options give the same bytes. Random numbers come from a hashThe 1920 by 1080 still of the demo room at 64 samples took 58.15 s on the GPU (RTX 3060, clean image, including 10.3 s of compiling with a warm shader cache, the BVH build and the denoiser; a cold compile measured 30 s on an earlier version of the kernel, which would have put it over 60 s; remeasured 2026-11-04 below) against 585.9 s on the CPU tracer (measured 2026-11-03; remeasured 2026-11-04 at 38.7 s for a first compile of a kernel text the driver had not seen, 7.0 s of it compiling, and 41.0 s for the same kernel again, 7.3 s compiling, each in a fresh headless Chrome profile, so the 60 s bound holds cold: the compile no longer differs between cold and warm on this machine, and `gpuCompileSeconds` in the job report records it; a scene with a subsurface part compiles a larger kernel, 42.8 s cold in the same setup, which adds that to its still; see [the WebGPU decision](webgpu-decision.md) for the choice of WebGL2 over WebGPU). Against Cycles (FLIP, 960 by 540, 64 samples, 16 scenes, `bench/reference/path-tracer.json` for the CPU and `path-tracer-gpu.json` for the GPU), the two backends scored within 0.0002 of each other on every scene (largest gap 0.0001 to 0.0002 on `foliage`, `glass`, `character`), so each keeps its score within the 0.005 bound (measured 2026-11-04). The GPU run took 4 to 13 s per scene after the first scene's compile. `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. A render job selects it with `settings.renderer.backend: "gpu"` (see `docs/agent-render-jobs.md`); the job default stays `cpu`.-`backend: 'webgpu'` (issue #625) runs the same algorithm as WGSL compute (`src/path-tracer-webgpu.js` and `src/path-tracer-webgpu-kernel.js`, loaded only for this backend). It takes the same packed scene tables as storage buffers, draws the same random numbers in the same order and returns the same buffers, so the denoiser and tone mapping are unchanged. It needs `navigator.gpu` and an adapter with 10 storage buffers per shader stage; without them it throws an error that names `gpu` and `cpu` (the MCP `cpu` runtime has no WebGPU). It does not trace volume fog or subsurface scattering yet: a scene that uses either throws an error that names it, so call it with `backend: 'gpu'` instead. Measured on the RTX 3060 (2026-11-09, `docs/webgpu-decision.md`): the kernel compiles in 0.5 s cold against 29 s for the WebGL2 kernel, the demo room at 1920 by 1080 and 64 samples traces in 8.0 to 8.5 s against 15.2 s (three alternating runs), and FLIP against the WebGL2 backend is 0.0000 to 0.0019 on 15 of the 16 reference scenes (the sixteenth, `fog`, is not supported). The default kernel is a megakernel; a wavefront kernel (generate, extend, shade, shadow, with optional sorting by material) is built and was slower on this scene (17.3 to 18.1 s), so it is opt-in through `traceOnWebGpu` only. The default backend stays `cpu`.+`backend: 'webgpu'` (issue #625) runs the same algorithm as WGSL compute (`src/path-tracer-webgpu.js` and `src/path-tracer-webgpu-kernel.js`, loaded only for this backend). It takes the same packed scene tables as storage buffers, draws the same random numbers in the same order and returns the same buffers, so the denoiser and tone mapping are unchanged. It needs `navigator.gpu` and an adapter with 10 storage buffers per shader stage; without them it throws an error that names `gpu` and `cpu` (the MCP `cpu` runtime has no WebGPU). Volume fog and subsurface scattering are traced too (`src/path-tracer-webgpu-medium.js`, the WGSL form of the WebGL2 pieces with the same random numbers): they are compiled into the megakernel only for a scene that uses them, and the subsurface table rides in the materials buffer, so a scene without them compiles the kernel it always did. The wavefront kernel does not trace them and throws a `RangeError` that names the megakernel. The same kernel starts paths at lightmap texels for the light bake (`bakeLightmapsAsync(..., { backend: 'webgpu' })`, see `docs/light-bake.md`). Measured on the RTX 3060 (2026-11-09, `docs/webgpu-decision.md`): the kernel compiles in 0.5 s cold against 29 s for the WebGL2 kernel, the demo room at 1920 by 1080 and 64 samples traces in 8.0 to 8.5 s against 15.2 s (three alternating runs), and FLIP against the WebGL2 backend is 0.0000 to 0.0019 on 15 of the 16 reference scenes (the sixteenth, `fog`, was not supported then; with fog and subsurface ported, 480 by 270 at 32 samples without the denoiser, RTX 3060, one run on a loaded machine, 2026-11-09: `fog` 0.0000 FLIP against WebGL2 in 1.35 s against 33.8 s, `subsurface` 0.0039 in 2.28 s against 174 s; the WebGL2 numbers are mostly the 17 and 106 s kernel compile, which is 1.0 and 1.9 s on WebGPU). The default kernel is a megakernel; a wavefront kernel (generate, extend, shade, shadow, with optional sorting by material) is built and was slower on this scene (17.3 to 18.1 s), so it is opt-in through `traceOnWebGpu` only. The default backend stays `cpu`.## Speeddiff --git a/src/light-bake-gpu.js b/src/light-bake-gpu.jsindex 31693881..46e70b1b 100644--- a/src/light-bake-gpu.js+++ b/src/light-bake-gpu.js@@ -1,5 +1,4 @@import { buildTraceScene } from './path-tracer-scene.js';-import { traceTexelsOnGpu } from './path-tracer-gpu.js';import { checkBudget, checkedBakeSize, finishLightmaps, planLightmaps, rasterizeEntries, traceLightmaps } from './light-bake.js';// The GPU side of the light bake: the texels of every part go to the path tracer's kernel in one batch, which starts a@@ -49,11 +48,18 @@ function packCoveredTexels(rasterized) {* Traces every covered texel on the GPU and resolves with `entries` (per rasterized part, `light` and `escaped` in the* layout the CPU gatherer returns), the `gpu` name and the kernel's `compileSeconds`.*/+/** The texel tracer of the backend; each is loaded only when a bake asks for it. */+async function loadTexelTracer(backend) {+ if (backend === 'webgpu') return (await import('./path-tracer-webgpu.js')).traceTexelsOnWebGpu;+ return (await import('./path-tracer-gpu.js')).traceTexelsOnGpu;+}+async function gatherOnGpu(plan, settings, rasterized, shouldStop) {const environment = traceEnvironment(plan);const texels = packCoveredTexels(rasterized);const scene = buildTraceScene(plan.parts, environment);- const traced = await traceTexelsOnGpu(scene, texels, { samples: settings.samples, bounces: settings.bounces, seed: BAKE_SEED, fireflyClamp: NO_FIREFLY_CLAMP }, shouldStop);+ const traceTexels = await loadTexelTracer(settings.backend);+ const traced = await traceTexels(scene, texels, { samples: settings.samples, bounces: settings.bounces, seed: BAKE_SEED, fireflyClamp: NO_FIREFLY_CLAMP }, shouldStop);let next = 0;const entries = rasterized.map(({ resolution }, entryNumber) => {const light = new Float32Array(resolution * resolution * 3);@@ -82,8 +88,8 @@ export async function traceLightmapsAsync(plan, tracedSettings) {/*** `bakeLightmaps` with a choice of tracer: `options.backend` is "cpu" (the default, the reference) or "gpu", which traces the- * texels with the GPU path tracer's kernel and needs a page with WebGL2. Resolves with the same `{ parts, report }`;- * `report.backend` names the tracer, and a GPU bake adds `gpu` and `gpuCompileSeconds`.+ * texels with the GPU path tracer's kernel and needs a page with WebGL2, or "webgpu", which runs the WGSL kernel and needs `navigator.gpu`. Resolves with the same `{ parts, report }`;+ * `report.backend` names the tracer, and a GPU or WebGPU bake adds `gpu` and `gpuCompileSeconds`.*/export async function bakeLightmapsAsync(parts, lighting, options = {}) {const plan = planLightmaps(parts, lighting, options);diff --git a/src/light-bake.js b/src/light-bake.jsindex 2a94f08c..306cfbee 100644--- a/src/light-bake.js+++ b/src/light-bake.js@@ -26,6 +26,7 @@ export const MAX_BAKE_TRIANGLES = 200_000;export const MAX_BAKE_PARTS = 256;// The GPU tracer takes as many parts as the path tracer does (MAX_TRACE_PARTS); the CPU bake keeps 256.export const MAX_GPU_BAKE_PARTS = 1024;+const BAKE_BACKENDS = ['cpu', 'gpu', 'webgpu'];export const MAX_BAKE_POINT_LIGHTS = MAX_POINT_LIGHTS;export const MAX_BAKE_SPOT_LIGHTS = MAX_SPOT_LIGHTS;export const MAX_BAKE_AREA_LIGHTS = MAX_AREA_LIGHTS;@@ -65,7 +66,7 @@ export function normalizeBakeOptions(options = {}) {const normalized = {};for (const name of Object.keys(BAKE_LIMITS)) normalized[name] = boundedNumber(options, name);normalized.backend = options.backend ?? 'cpu';- if (normalized.backend !== 'cpu' && normalized.backend !== 'gpu') throw new TypeError('Light bake backend must be "cpu" or "gpu".');+ if (!BAKE_BACKENDS.includes(normalized.backend)) throw new TypeError('Light bake backend must be "cpu", "gpu" or "webgpu".');return normalized;}@@ -887,7 +888,7 @@ function createSkyVisibilityGatherer({ tracer, offset, samples }) {export function planLightmaps(parts, lighting, options = {}) {const settings = normalizeBakeOptions(options);const lights = normalizeLights(lighting);- const maximumParts = settings.backend === 'gpu' ? MAX_GPU_BAKE_PARTS : MAX_BAKE_PARTS;+ const maximumParts = settings.backend !== 'cpu' ? MAX_GPU_BAKE_PARTS : MAX_BAKE_PARTS;if (!Array.isArray(parts) || parts.length === 0 || parts.length > maximumParts) throw new RangeError(`Light bake takes from 1 to ${maximumParts} parts.`);parts.forEach(validatePart);const triangleTotal = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);@@ -1030,7 +1031,7 @@ export function finishLightmaps(plan, settings, rasterized, gathered, sizes) {/** Traces a plan with the given settings (samples, bounces, texelsPerUnit, maxSeconds) and returns the baked parts and the report. */export function traceLightmaps(plan, tracedSettings) {const settings = { ...plan.settings, ...tracedSettings };- if (settings.backend !== 'cpu') throw new TypeError('Light bake backend "gpu" is asynchronous: use bakeLightmapsAsync from light-bake-gpu.js.');+ if (settings.backend !== 'cpu') throw new TypeError(`Light bake backend "${settings.backend}" is asynchronous: use bakeLightmapsAsync from light-bake-gpu.js.`);const sizes = checkedBakeSize(plan, settings);const rasterized = rasterizeEntries(plan, settings);return finishLightmaps(plan, settings, rasterized, gatherOnCpu(plan, settings, rasterized), sizes);diff --git a/src/path-tracer-webgpu-kernel.js b/src/path-tracer-webgpu-kernel.jsindex 7ec5883a..16aa8428 100644--- a/src/path-tracer-webgpu-kernel.js+++ b/src/path-tracer-webgpu-kernel.js@@ -4,14 +4,17 @@// MEGAKERNEL_SOURCE: one invocation traces one pixel's whole path (entry point `main`).// WAVEFRONT_SOURCE: path state lives in a storage buffer and the path is split into kernels (generate, extend, shade,// shadow, resolve); after extend the hits are binned by material so that neighbouring invocations of shade run the same material.-// Left out: volume fog, subsurface and the texel bake (the host throws a clear error for the first two).+// Volume fog and the subsurface walk (path-tracer-webgpu-medium.js) are spliced into the megakernel only for a scene that uses them.+// The megakernel has a texel entry point (`bakeTexels`) that starts a path at every lightmap texel, for the light bake.++import { SUBSURFACE_FUNCTIONS, VOLUME_FUNCTIONS } from './path-tracer-webgpu-medium.js';export const WORKGROUP_SIZE = 8;export const WAVEFRONT_WORKGROUP_SIZE = 64;/** vec4 slots of path state per path; the wavefront section below names each one. */export const PATH_STATE_VECTORS = 9;-const COMMON_SOURCE = /* wgsl */ `+const buildCommonSource = ({ hasVolume = false } = {}) => /* wgsl */ `const PI: f32 = 3.14159265358979;const TWO_PI: f32 = 6.28318530717959;const TRIANGLE_TEXELS: i32 = 9;@@ -39,6 +42,9 @@ struct Params {seedAndAtlas: vec4<u32>,tileAndDepth: vec4<u32>,shadowSlots: vec4<u32>,+ volumeMinimumDensity: vec4<f32>,+ volumeMaximumAnisotropy: vec4<f32>,+ volumeAlbedoDistance: vec4<f32>,}@group(0) @binding(0) var<uniform> params: Params;@@ -185,6 +191,7 @@ var<private> hitTransmission: f32;var<private> hitIor: f32;var<private> hitCutoff: f32;var<private> hitMask: u32;+var<private> hitMaterialIndex: i32;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));@@ -272,7 +279,8 @@ fn fillHit(origin: vec3<f32>, direction: vec3<f32>, distance: f32) -> f32 {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;+ hitMaterialIndex = i32(cornerData.w);+ let material = hitMaterialIndex * MATERIAL_TEXELS;let colorMetallic = materials[material];let emissionRoughness = materials[material + 1];let coating = materials[material + 2];@@ -528,6 +536,7 @@ var<private> surfaceCoatChance: f32;var<private> surfaceSampledCoat: bool;var<private> surfaceCoatAlpha: f32;var<private> surfaceDiffuseChance: f32;+var<private> surfaceDiffuseShare: f32;var<private> surfaceSpecularChance: f32;var<private> surfaceValue: vec3<f32>;var<private> surfacePdf: f32;@@ -552,6 +561,7 @@ fn prepareSurface(normal: vec3<f32>, view: vec3<f32>) {let underCoat = 1.0 - surfaceCoatWeight;let diffuseShare = (1.0 - hitMetallic) * (1.0 - dielectricFresnel) * underCoat;surfaceDiffuse = hitColor * diffuseShare;+ surfaceDiffuseShare = diffuseShare;surfaceSpecularNormal = vec3<f32>(dielectricNormalReflectance * (1.0 - hitMetallic)) + hitColor * hitMetallic;let specularLuminance = luminance(surfaceSpecularNormal);surfaceSpecularWeight = underCoat;@@ -669,6 +679,7 @@ var<private> featureAlbedo: vec3<f32>;var<private> featureNormal: vec3<f32>;var<private> featureDepth: f32;var<private> firstLegEscaped: f32 = 0.0;+var<private> inMedium: bool = false;fn addRadiance(depth: i32, amountIn: vec3<f32>) {var amount = amountIn;@@ -700,20 +711,30 @@ 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;+ ${hasVolume ? `if (inMedium) {+ let phase = henyeyGreensteinPhase(params.volumeMaximumAnisotropy.w, dot(lightDirection, direction));+ let scale = phase * fogTransmittance(hitPoint, distance) * directWeight(weightMode, phase);+ shadowOrigin = hitPoint;+ shadowAmount = throughput * lightRadiance * scale;+ shadowDepth = depth + 1;+ } else {` : '{'}+ 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;+ ${hasVolume ? `let transmittance = fogTransmittance(shadowOrigin, distance);` : `let transmittance = 1.0;`}+ let scale = cosine * directWeight(weightMode, surfacePdf) * transmittance;+ shadowAmount = throughput * value * lightRadiance * scale;+ shadowDepth = depth;+ }shadowDirection = lightDirection;shadowLimit = distance;shadowPending = true;}+${hasVolume ? VOLUME_FUNCTIONS : ''}fn flushShadowRay() {if (!shadowPending) { return; }shadowPending = false;@@ -721,7 +742,7 @@ fn flushShadowRay() {}fn reaches(bit: i32) -> bool {- return ((hitMask >> u32(bit)) & 1u) == 1u;+ return inMedium || ((hitMask >> u32(bit)) & 1u) == 1u;}// Aims lightDirection at the target and returns the distance; distanceSquared goes into aimedDistanceSquared.@@ -837,8 +858,69 @@ fn survivesRoulette(depth: i32) -> bool {return true;}`;+const COMMON_SOURCE = buildCommonSource();-export const MEGAKERNEL_SOURCE = COMMON_SOURCE + /* wgsl */ `+// One invocation per pixel of the image.+const CAMERA_MAIN = /* wgsl */ `+@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);+}+`;++// Texel mode: one invocation is one lightmap texel (params.sizeBouncesLights.x is the texel count, shadowSlots.z the sample+// count). The path starts on the texel's surface with a cosine weighted direction, so the radiance it returns is the light+// that arrives at the texel; the bake multiplies by the albedo. Plane 0 of the accumulation holds the radiance sums, plane 1+// the sums of first rays that left the scene.+const TEXEL_MAIN = /* wgsl */ `+@group(0) @binding(9) var<storage, read_write> texelPoints: array<vec4<f32>>;+@group(0) @binding(10) var<storage, read_write> texelNormals: array<vec4<f32>>;++@compute @workgroup_size(${WAVEFRONT_WORKGROUP_SIZE})+fn bakeTexels(@builtin(global_invocation_id) id: vec3<u32>, @builtin(num_workgroups) groups: vec3<u32>) {+ let texelCount = u32(params.sizeBouncesLights.x);+ let texelIndex = id.y * groups.x * ${WAVEFRONT_WORKGROUP_SIZE}u + id.x;+ if (texelIndex >= texelCount) { return; }+ let sampleIndex = u32(params.emittersFlagsSample.w);+ let seed = params.seedAndAtlas.x;+ if (params.emittersFlagsSample.y != 0) { sunFrame = buildFrame(params.sunDirection.xyz); }+ let normal = texelNormals[texelIndex].xyz;+ let origin = texelPoints[texelIndex].xyz + normal * params.environmentRotationAndRays.z;+ let firstUnit = (f32(sampleIndex) + hashJitter(texelIndex, sampleIndex, seed, 1u)) / f32(params.shadowSlots.z);+ let secondUnit = hashJitter(texelIndex, sampleIndex, seed, 2u);+ let coneRadius = sqrt(firstUnit);+ let angle = TWO_PI * secondUnit;+ let rayDirection = buildFrame(normal) * vec3<f32>(coneRadius * cos(angle), coneRadius * sin(angle), sqrt(max(0.0, 1.0 - firstUnit)));+ tracePath(origin, rayDirection, texelIndex, sampleIndex);+ if (!(all(radiance >= vec3<f32>(0.0)) && all(radiance < vec3<f32>(1e30)))) { radiance = vec3<f32>(0.0); }+ accumulation[texelIndex] += vec4<f32>(radiance, 0.0);+ accumulation[texelCount + texelIndex] += vec4<f32>(firstLegEscaped, 0.0, 0.0, 0.0);+}+`;++export const buildMegakernelSource = ({ hasVolume = false, hasSubsurface = false, texelBake = false } = {}) => buildCommonSource({ hasVolume }) + /* wgsl */ `// 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;@@ -854,6 +936,7 @@ fn addLights(depth: i32, normal: vec3<f32>) {sampleEmitter(depth, normal, i32(floor(nextRandom() * f32(emitterCount))));flushShadowRay();}+${hasSubsurface ? SUBSURFACE_FUNCTIONS : ''}fn tracePath(origin: vec3<f32>, startDirection: vec3<f32>, pixel: u32, sampleIndex: u32) {resetRandom(pixel, sampleIndex, params.seedAndAtlas.x);radiance = vec3<f32>(0.0);@@ -871,25 +954,49 @@ fn tracePath(origin: vec3<f32>, startDirection: vec3<f32>, pixel: u32, sampleIndlet surfaceOffset = params.environmentRotationAndRays.z;for (var depth = 0; depth <= bounces; depth++) {let found = intersectScene(position, direction);- if (!found) {+ ${hasVolume ? 'let inFog = scatterInFog(position, select(params.environmentRotationAndRays.w, hitDistance, found));' : 'let inFog = false;'}+ if (!inFog && !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);+ var isGlass = false;+ var entering = true;+ var needsLights = true;+ if (inFog) {+ throughput *= params.volumeAlbedoDistance.xyz;+ inMedium = true;+ } else {+ entering = dot(hitNormal, direction) < 0.0;+ normal = select(-hitNormal, hitNormal, entering);+ 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);+ needsLights = !isGlass;+ if (needsLights) {+ prepareSurface(normal, -direction);+ ${hasSubsurface ? 'subsurfaceWeight = splitSubsurface();' : ''}+ }}+ if (needsLights) { addLights(depth, normal); }+ inMedium = false;+ ${hasVolume ? `if (inFog) {+ let phaseCosine = sampleHenyeyGreensteinCosine(params.volumeMaximumAnisotropy.w, nextRandom());+ let phaseSine = sqrt(max(0.0, 1.0 - phaseCosine * phaseCosine));+ let azimuth = TWO_PI * nextRandom();+ let frame = buildFrame(direction);+ direction = frame[0] * phaseSine * cos(azimuth) + frame[1] * phaseSine * sin(azimuth) + frame[2] * phaseCosine;+ previousPdf = henyeyGreensteinPhase(params.volumeMaximumAnisotropy.w, phaseCosine);+ afterMirror = false;+ position = hitPoint;+ if (!survivesRoulette(depth)) { break; }+ continue;+ }` : ''}if (isGlass) {let alpha = roughnessToAlpha(hitRoughness);let selectionUnit = nextRandom();@@ -900,7 +1007,16 @@ fn tracePath(origin: vec3<f32>, startDirection: vec3<f32>, pixel: u32, sampleIndif (dot(direction, normal) < 0.0) { throughput *= hitColor; }afterMirror = true;} else {- let lobeUnit = nextRandom();+ var lobeUnit = nextRandom();+ ${hasSubsurface ? `if (subsurfaceWeight > 0.0) {+ if (lobeUnit < surfaceSubsurfaceChance) {+ if (!enterSubsurface(depth, normal)) { break; }+ normal = subsurfaceNormal;+ lobeUnit = 0.0;+ } else {+ lobeUnit -= surfaceSubsurfaceChance;+ }+ }` : ''}let firstUnit = nextRandom();let secondUnit = nextRandom();let isMirror = sampleSurface(lobeUnit, firstUnit, secondUnit);@@ -923,34 +1039,11 @@ fn tracePath(origin: vec3<f32>, startDirection: vec3<f32>, pixel: u32, sampleInd}}-@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);-}+${texelBake ? TEXEL_MAIN : CAMERA_MAIN}`;+export const MEGAKERNEL_SOURCE = buildMegakernelSource();+export const WAVEFRONT_SOURCE = COMMON_SOURCE + /* wgsl */ `// Path state: PATH_STATE_VECTORS vec4<u32> per path (floats are stored as their bits, so nothing is ever rounded or// canonicalised on the way through memory), then the shadow records, three vec4 per emitter slot of a path.diff --git a/src/path-tracer-webgpu-medium.js b/src/path-tracer-webgpu-medium.jsnew file mode 100644index 00000000..bcad7e9e--- /dev/null+++ b/src/path-tracer-webgpu-medium.js@@ -0,0 +1,170 @@+import { SUBSURFACE_TEXELS } from './path-tracer-gpu-subsurface.js';+import { SUBSURFACE_WALK_STEPS } from './path-tracer-subsurface.js';++// The two optional parts of the WGSL path tracer (issue #625): homogeneous volume fog and the subsurface random walk.+// They are the WGSL form of the GLSL pieces in path-tracer-gpu-shader.js (fog) and path-tracer-gpu-subsurface.js, with the+// same random numbers drawn in the same order, and the kernel splices them in only for a scene that uses them.+// The fog box and medium sit in the last three vectors of the parameter block: minimum and density, maximum and anisotropy,+// albedo and the longest distance. The subsurface table (two vectors per material) follows the material table in the+// materials buffer; params.seedAndAtlas.z is the vector index where it starts.++/** The fog functions that the shared part of the kernel calls from addDirect. */+export const VOLUME_FUNCTIONS = /* wgsl */ `+var<private> volumeSpan: vec2<f32>;++fn clipAxis(origin: f32, axisDirection: f32, minimum: f32, maximum: f32, span: ptr<function, vec2<f32>>) -> bool {+ if (axisDirection == 0.0) { return origin >= minimum && origin <= maximum; }+ let first = (minimum - origin) / axisDirection;+ let second = (maximum - origin) / axisDirection;+ (*span).x = max((*span).x, min(first, second));+ (*span).y = min((*span).y, max(first, second));+ return true;+}++fn volumeInterval(origin: vec3<f32>, rayDirection: vec3<f32>, limit: f32) -> bool {+ var span = vec2<f32>(0.0, min(limit, params.volumeAlbedoDistance.w));+ let minimum = params.volumeMinimumDensity.xyz;+ let maximum = params.volumeMaximumAnisotropy.xyz;+ if (!clipAxis(origin.x, rayDirection.x, minimum.x, maximum.x, &span)) { return false; }+ if (!clipAxis(origin.y, rayDirection.y, minimum.y, maximum.y, &span)) { return false; }+ if (!clipAxis(origin.z, rayDirection.z, minimum.z, maximum.z, &span)) { return false; }+ if (!(span.x < span.y)) { return false; }+ volumeSpan = span;+ return true;+}++fn henyeyGreensteinPhase(anisotropy: f32, cosine: f32) -> f32 {+ let squared = anisotropy * anisotropy;+ return (1.0 - squared) / (4.0 * PI * pow(1.0 + squared - 2.0 * anisotropy * cosine, 1.5));+}++fn sampleHenyeyGreensteinCosine(anisotropy: f32, unit: f32) -> f32 {+ if (abs(anisotropy) < 1e-3) { return 1.0 - 2.0 * unit; }+ let squared = anisotropy * anisotropy;+ let 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);+}++fn fogTransmittance(origin: vec3<f32>, distance: f32) -> f32 {+ if (!volumeInterval(origin, lightDirection, distance)) { return 1.0; }+ return exp(-params.volumeMinimumDensity.w * (volumeSpan.y - volumeSpan.x));+}++// Draws the next scattering event along the segment; when there is one it becomes hitPoint.+fn scatterInFog(origin: vec3<f32>, segmentLength: f32) -> bool {+ if (!volumeInterval(origin, direction, segmentLength)) { return false; }+ let eventDistance = volumeSpan.x - log(1.0 - nextRandom()) / params.volumeMinimumDensity.w;+ if (eventDistance >= volumeSpan.y) { return false; }+ hitPoint = origin + direction * eventDistance;+ return true;+}+`;++/** The subsurface random walk; it runs right after addLights is defined, so it can light the point where the walk leaves. */+export const SUBSURFACE_FUNCTIONS = /* wgsl */ `+const WALK_STEPS: i32 = ${SUBSURFACE_WALK_STEPS};+const WALK_EXIT: i32 = 0;+const WALK_THIN: i32 = 1;+const WALK_LOST: i32 = 2;+const SUBSURFACE_TEXELS: i32 = ${SUBSURFACE_TEXELS};++var<private> subsurfaceWeight: f32 = 0.0;+var<private> surfaceSubsurfaceChance: f32 = 0.0;+var<private> walkWeight: vec3<f32>;+var<private> walkDirection: vec3<f32>;+var<private> subsurfaceNormal: vec3<f32>;++fn subsurfaceVector(material: i32, offset: i32) -> vec4<f32> {+ return materials[i32(params.seedAndAtlas.z) + material * SUBSURFACE_TEXELS + offset];+}++// Moves the subsurface share of the diffuse lobe to the walk; returns the material's weight.+fn splitSubsurface() -> f32 {+ let weight = subsurfaceVector(hitMaterialIndex, 0).x;+ surfaceSubsurfaceChance = surfaceDiffuseChance * weight;+ surfaceDiffuseChance -= surfaceSubsurfaceChance;+ surfaceDiffuse *= 1.0 - weight;+ return weight;+}++fn singleScatterAlbedo(multipleScatterAlbedo: f32) -> f32 {+ let albedo = clamp(multipleScatterAlbedo, 0.0, 1.0);+ let root = sqrt(9.59217 + 41.6808 * albedo + 17.7126 * albedo * albedo);+ let offset = 4.09712 + 4.20863 * albedo - root;+ return clamp(1.0 - offset * offset, 0.0, 1.0);+}++// Walks inward from the entry point until the walk meets the part's own surface; leaves its throughput in walkWeight.+fn randomWalk(point: vec3<f32>, normal: vec3<f32>, meanFreePath: vec3<f32>, color: vec3<f32>, material: i32) -> i32 {+ let extinction = 1.0 / meanFreePath;+ let albedo = vec3<f32>(singleScatterAlbedo(color.r), singleScatterAlbedo(color.g), singleScatterAlbedo(color.b));+ var position = point - normal * params.environmentRotationAndRays.z;+ let frame = buildFrame(normal);+ let radius = sqrt(nextRandom());+ let angle = TWO_PI * nextRandom();+ let height = sqrt(max(0.0, 1.0 - radius * radius));+ walkDirection = frame[0] * (radius * cos(angle)) + frame[1] * (radius * sin(angle)) - normal * height;+ for (var scatters = 0; scatters <= WALK_STEPS; scatters++) {+ let found = intersectScene(position, walkDirection);+ if (!found || hitMaterialIndex != material) { return select(WALK_LOST, WALK_THIN, scatters == 0); }+ // One channel draws the distance; weighting by the mean density over the three channels keeps every channel unbiased.+ let hero = min(2, i32(floor(nextRandom() * 3.0)));+ let distance = -log(1.0 - nextRandom()) / extinction[hero];+ if (distance >= hitDistance) {+ let attenuation = exp(-extinction * hitDistance);+ let survival = (attenuation.x + attenuation.y + attenuation.z) / 3.0;+ if (!(survival > 0.0)) { return WALK_LOST; }+ walkWeight *= attenuation / survival;+ return WALK_EXIT;+ }+ if (scatters == WALK_STEPS) { return WALK_LOST; }+ let falloff = exp(-extinction * distance);+ let scatterDensity = extinction * falloff;+ let density = (scatterDensity.x + scatterDensity.y + scatterDensity.z) / 3.0;+ if (!(density > 0.0)) { return WALK_LOST; }+ walkWeight *= albedo * scatterDensity / density;+ position += walkDirection * distance;+ let up = 2.0 * nextRandom() - 1.0;+ let azimuth = TWO_PI * nextRandom();+ let ring = sqrt(max(0.0, 1.0 - up * up));+ walkDirection = vec3<f32>(ring * cos(azimuth), up, ring * sin(azimuth));+ }+ return WALK_LOST;+}++// Sends the diffuse light of the hit through its walk. On success the path stands where the walk left, subsurfaceNormal+// faces out of that point, the surface is white diffuse there with its lights added, and the throughput carries the walk.+// False when the walk ended inside the part.+fn enterSubsurface(depth: i32, entryNormal: vec3<f32>) -> bool {+ let block = subsurfaceVector(hitMaterialIndex, 0);+ let colorBlock = subsurfaceVector(hitMaterialIndex, 1);+ let color = select(colorBlock.rgb, hitColor, colorBlock.x < 0.0);+ let material = hitMaterialIndex;+ let entryPoint = hitPoint;+ let entryMask = hitMask;+ let entryScale = surfaceDiffuseShare * block.x / surfaceSubsurfaceChance;+ walkWeight = vec3<f32>(1.0);+ subsurfaceNormal = entryNormal;+ let outcome = randomWalk(entryPoint, entryNormal, block.yzw, color, material);+ if (outcome == WALK_LOST) { return false; }+ if (outcome == WALK_EXIT) {+ subsurfaceNormal = hitNormal * select(1.0, -1.0, dot(hitNormal, walkDirection) < 0.0);+ throughput *= walkWeight * entryScale;+ } else {+ // A card: half of the colour is reflected on the side the ray came from and half is transmitted diffusely through it.+ hitPoint = entryPoint;+ hitMask = entryMask;+ if (nextRandom() < 0.5) { subsurfaceNormal = -entryNormal; }+ throughput *= color * entryScale;+ }+ surfaceFrame = buildFrame(subsurfaceNormal);+ surfaceDiffuse = vec3<f32>(1.0);+ surfaceDiffuseChance = 1.0;+ surfaceSubsurfaceChance = 0.0;+ surfaceSpecularChance = 0.0;+ surfaceCoatChance = 0.0;+ surfaceCoatWeight = 0.0;+ addLights(depth, subsurfaceNormal);+ return true;+}+`;diff --git a/src/path-tracer-webgpu.js b/src/path-tracer-webgpu.jsindex 1f3e6fb9..fb0f02ba 100644--- a/src/path-tracer-webgpu.js+++ b/src/path-tracer-webgpu.js@@ -1,10 +1,11 @@-import { MEGAKERNEL_SOURCE, PATH_STATE_VECTORS, WAVEFRONT_SOURCE, WAVEFRONT_WORKGROUP_SIZE, WORKGROUP_SIZE } from './path-tracer-webgpu-kernel.js';-import { packAtlas, packEnvironment, packLights, packMaterials, packNodes, packTriangles, sceneUsesSubsurface } from './path-tracer-gpu-pack.js';+import { buildMegakernelSource, PATH_STATE_VECTORS, WAVEFRONT_SOURCE, WAVEFRONT_WORKGROUP_SIZE, WORKGROUP_SIZE } from './path-tracer-webgpu-kernel.js';+import { packAtlas, packEnvironment, packLights, packMaterials, packNodes, packSubsurface, packTriangles, sceneUsesSubsurface } from './path-tracer-gpu-pack.js';// The WebGPU backend of the path tracer (issue #625): the same scene tables, camera, options and random numbers as the// WebGL2 backend (path-tracer-gpu.js) go in, the same buffers come out. The tracer is WGSL compute, so a page needs-// navigator.gpu; without it traceOnWebGpu throws and the caller falls back to the "gpu" or "cpu" backend. Fog, subsurface and-// the texel bake are not ported: a scene that uses fog or subsurface throws an error that names it.+// navigator.gpu; without it traceOnWebGpu throws and the caller falls back to the "gpu" or "cpu" backend. Volume fog and+// subsurface scattering compile into the megakernel only for a scene that uses them, and traceTexelsOnWebGpu is the texel+// entry of the light bake (light-bake-gpu.js). The wavefront kernel traces neither fog nor subsurface./** `megakernel`: one invocation per path (the default, faster on the demo room). `wavefront`: generate, extend, shade, shadow kernels with the path state in a buffer. */export const WEBGPU_KERNELS = ['megakernel', 'wavefront'];@@ -12,9 +13,9 @@ export const DEFAULT_WEBGPU_KERNEL = 'megakernel';/** Whether the wavefront bins the hits by material before shading them (decided by the measurement in docs/webgpu-decision.md). */export const DEFAULT_SORT_BY_MATERIAL = false;-const PARAMETER_BYTES = 14 * 16;-// Dynamic uniform offsets must be a multiple of minUniformBufferOffsetAlignment, which is 256 on every adapter.-const PARAMETER_SLOT_BYTES = 256;+const PARAMETER_BYTES = 17 * 16;+// Dynamic uniform offsets must be a multiple of minUniformBufferOffsetAlignment, which is 256 on every adapter; a slot holds the parameter block.+const PARAMETER_SLOT_BYTES = 512;const STORAGE_BUFFER_COUNT = 10;const MAXIMUM_TILE_PATHS = 1 << 19;// The path state of one tile stays under the default maxStorageBufferBindingSize.@@ -71,22 +72,34 @@ async function getSession() {return session;}-async function compileKernel(current, kernel) {+/** The WGSL and entry points of a kernel variant; a variant is one of the two kernels, with the optional parts a scene needs. */+function describeVariant({ kernel, hasVolume, hasSubsurface, texelBake }) {+ if (kernel === 'wavefront') return { code: WAVEFRONT_SOURCE, entryPoints: WAVEFRONT_ENTRY_POINTS };+ return { code: buildMegakernelSource({ hasVolume, hasSubsurface, texelBake }), entryPoints: [texelBake ? 'bakeTexels' : 'main'] };+}++async function compileKernel(current, variant) {const { device, pipelineLayout } = current;const started = performance.now();- const module = device.createShaderModule({ label: `path tracer ${kernel}`, code: kernel === 'wavefront' ? WAVEFRONT_SOURCE : MEGAKERNEL_SOURCE });+ const { code, entryPoints } = describeVariant(variant);+ const module = device.createShaderModule({ label: `path tracer ${variant.kernel}`, code });const info = await module.getCompilationInfo();const errors = info.messages.filter(message => message.type === 'error');if (errors.length > 0) throw new Error(`The WebGPU path tracer shader did not compile: ${errors.slice(0, 8).map(message => `${message.lineNum}: ${message.message}`).join('; ')}`);- const entryPoints = kernel === 'wavefront' ? WAVEFRONT_ENTRY_POINTS : ['main'];const pipelines = await Promise.all(entryPoints.map(entryPoint => device.createComputePipelineAsync({ layout: pipelineLayout, compute: { module, entryPoint } })));kernelCompileCount++;return { pipelines: Object.fromEntries(entryPoints.map((entryPoint, index) => [entryPoint, pipelines[index]])), compileSeconds: (performance.now() - started) / 1000 };}-async function getKernel(current, kernel) {- if (!current.kernels.has(kernel)) current.kernels.set(kernel, compileKernel(current, kernel));- return current.kernels.get(kernel);+async function getKernel(current, variant) {+ const key = [variant.kernel, variant.hasVolume, variant.hasSubsurface, variant.texelBake].join(':');+ if (!current.kernels.has(key)) current.kernels.set(key, compileKernel(current, variant));+ return current.kernels.get(key);+}++/** The optional parts the scene needs, as the kernel variant flags. */+function sceneFeatures(scene) {+ return { hasVolume: Boolean(scene.volume), hasSubsurface: sceneUsesSubsurface(scene.materials), texelBake: false };}function createStorageBuffer(device, data, label) {@@ -109,24 +122,23 @@ function uploadScene(device, scene) {environmentTables.set(environment.rows.data.subarray(0, environment.height), 0);environmentTables.set(environment.pixels.data.subarray(0, environment.width * environment.height), environment.height);}+ // The subsurface table (two vectors per material) follows the material table in the same buffer.+ const materialData = packMaterials(scene.materials, atlas).data;+ const subsurfaceOffset = materialData.length / 4;+ const subsurfaceData = sceneUsesSubsurface(scene.materials) ? packSubsurface(scene.materials).data : new Float32Array(0);+ const materialsWithSubsurface = new Float32Array(materialData.length + subsurfaceData.length);+ materialsWithSubsurface.set(materialData);+ materialsWithSubsurface.set(subsurfaceData, materialData.length);const buffers = [createStorageBuffer(device, packNodes(scene.bvh).data, 'bvh nodes'),createStorageBuffer(device, packTriangles(scene).data, 'triangles'),- createStorageBuffer(device, packMaterials(scene.materials, atlas).data, 'materials'),+ createStorageBuffer(device, materialsWithSubsurface, 'materials'),createStorageBuffer(device, lights.table.data, 'lights'),createStorageBuffer(device, atlasWords(atlas), 'texture atlas'),createStorageBuffer(device, environment?.colors ?? new Float32Array(4), 'environment colors'),createStorageBuffer(device, environmentTables, 'environment tables'),];- return { buffers, lightCount: lights.count, atlasWidth: atlas.width };-}--/** The scene features this backend does not trace; the caller can fall back to the "gpu" backend. */-export function unsupportedWebGpuFeatures(scene) {- const unsupported = [];- if (scene.volume) unsupported.push('volume fog');- if (sceneUsesSubsurface(scene.materials)) unsupported.push('subsurface scattering');- return unsupported;+ return { buffers, lightCount: lights.count, atlasWidth: atlas.width, subsurfaceOffset };}/** The words of one uniform block: the 12 vectors of the megakernel parameters, then the tile and shadow slot words. */@@ -148,7 +160,11 @@ function createParameterTemplate(scene, camera, options, uploaded, emitterCount)floats.set([camera.halfWidth, camera.halfHeight, options.fireflyClamp, 0], 32);integers.set([options.width, options.height, options.bounces, uploaded.lightCount], 36);integers.set([emitterCount, sun ? 1 : 0, environment ? 1 : 0, 0], 40);- unsigned.set([options.seed >>> 0, uploaded.atlasWidth, 0, 0], 44);+ unsigned.set([options.seed >>> 0, uploaded.atlasWidth, uploaded.subsurfaceOffset, 0], 44);+ const { volume } = scene;+ floats.set([...(volume?.minimum ?? [0, 0, 0]), volume?.density ?? 0], 56);+ floats.set([...(volume?.maximum ?? [0, 0, 0]), volume?.anisotropy ?? 0], 60);+ floats.set([...(volume?.albedo ?? [1, 1, 1]), volume?.maxDistance ?? 0], 64);return { unsigned, integers };}@@ -156,6 +172,8 @@ const SAMPLE_INDEX_WORD = 43;const TILE_WORD = 48;const SHADOW_SLOT_WORD = 52;const SORT_FLAG_WORD = 53;+// The texel kernel keeps the sample count in a shadow slot word the megakernel leaves unused.+const SAMPLE_COUNT_WORD = 54;/** Fills one 256 byte slot per (tile, depth) of a sample; the kernels find their tile and depth in the slot they are bound to. */function writeParameterSlots(template, sampleIndex, tiles, depthCount, materialCount, shadowSlots, sortByMaterial) {@@ -237,13 +255,15 @@ function encodeWavefrontSample(pass, pipelines, bindGroup, tiles, depthCount, ma* samples. `shouldStop` throws when the time limit passes; it runs between samples.*/export async function traceOnWebGpu(scene, camera, options, shouldStop) {- const unsupported = unsupportedWebGpuFeatures(scene);- if (unsupported.length > 0) throw new Error(`The WebGPU path tracer does not trace ${unsupported.join(' or ')} yet. Use backend "gpu" for this scene.`);const kernel = options.kernel ?? DEFAULT_WEBGPU_KERNEL;if (!WEBGPU_KERNELS.includes(kernel)) throw new RangeError(`The WebGPU path tracer kernel must be one of ${WEBGPU_KERNELS.join(', ')}.`);+ const features = sceneFeatures(scene);+ if (kernel === 'wavefront' && (features.hasVolume || features.hasSubsurface)) {+ throw new RangeError('The WebGPU wavefront kernel does not trace volume fog or subsurface scattering. Use the megakernel, the default.');+ }const current = await getSession();const { device } = current;- const { pipelines, compileSeconds } = await getKernel(current, kernel);+ const { pipelines, compileSeconds } = await getKernel(current, { kernel, ...features });const { width, height, samples } = options;const pixelCount = width * height;const planeBytes = pixelCount * 16;@@ -300,5 +320,80 @@ export async function traceOnWebGpu(scene, camera, options, shouldStop) {return Object.assign(buffers, { gpu: current.gpu, compileSeconds });}+const TEXEL_GROUPS_PER_ROW = 4096;+const TEXEL_SAMPLES_PER_WAIT = 16;++function padVectors(vectors, count) {+ const padded = new Float32Array(Math.max(count, 1) * 4);+ for (let index = 0; index < count; index++) padded.set(vectors.subarray(index * 3, index * 3 + 3), index * 4);+ return padded;+}++/**+ * The texel entry of the light bake, the WebGPU form of `traceTexelsOnGpu` in path-tracer-gpu.js: traces `options.samples`+ * cosine weighted paths from every texel in `texels` (`count`, `points` and `normals`, three floats each) and resolves with+ * the mean `radiance` that arrives (three floats per texel), the share of first rays that `escaped`, the `gpu` name and the+ * `compileSeconds` of the kernel. `options.bounces` counts hits, as in the CPU bake.+ */+export async function traceTexelsOnWebGpu(scene, texels, options, shouldStop) {+ const current = await getSession();+ const { device } = current;+ const { count, points, normals } = texels;+ const { samples, seed } = options;+ const features = { ...sceneFeatures(scene), texelBake: true };+ const { pipelines, compileSeconds } = await getKernel(current, { kernel: 'megakernel', ...features });+ const accumulationBytes = Math.max(count, 1) * 16 * 2;+ if (accumulationBytes > device.limits.maxStorageBufferBindingSize) {+ throw new RangeError(`${count} lightmap texels are too many for this WebGPU adapter. Lower the lightmap resolution or use backend "gpu".`);+ }+ const uploaded = uploadScene(device, scene);+ const emitterCount = (scene.lights.sun ? 1 : 0) + uploaded.lightCount + (scene.environment ? 1 : 0);+ const camera = { eye: [0, 0, 0], forward: [0, 0, 1], right: [1, 0, 0], above: [0, 1, 0], halfWidth: 1, halfHeight: 1 };+ const template = createParameterTemplate(scene, camera, { width: count, height: 1, seed, bounces: options.bounces - 1, fireflyClamp: options.fireflyClamp }, uploaded, emitterCount);+ template.unsigned[SAMPLE_COUNT_WORD] = samples;+ const accumulation = device.createBuffer({ label: 'accumulation', size: accumulationBytes, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC });+ const parameters = device.createBuffer({ label: 'parameters', size: PARAMETER_SLOT_BYTES, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });+ const texelBuffers = [padVectors(points, count), padVectors(normals, count)].map((vectors, index) => createStorageBuffer(device, vectors, index === 0 ? 'texel points' : 'texel normals'));+ const bindGroup = device.createBindGroup({+ layout: current.bindGroupLayout,+ entries: [+ { binding: 0, resource: { buffer: parameters, size: PARAMETER_BYTES } },+ ...[...uploaded.buffers, accumulation, ...texelBuffers].map((buffer, index) => ({ binding: index + 1, resource: { buffer } })),+ ],+ });+ const groups = Math.max(1, Math.ceil(count / WAVEFRONT_WORKGROUP_SIZE));+ const groupsAcross = Math.min(groups, TEXEL_GROUPS_PER_ROW);+ for (let sample = 0; sample < samples; sample++) {+ device.queue.writeBuffer(parameters, 0, writeParameterSlots(template, sample, [{ start: 0, count }], 1, 0, 1, false));+ const encoder = device.createCommandEncoder();+ const pass = encoder.beginComputePass();+ pass.setPipeline(pipelines.bakeTexels);+ pass.setBindGroup(0, bindGroup, [0]);+ pass.dispatchWorkgroups(groupsAcross, Math.ceil(groups / groupsAcross));+ pass.end();+ device.queue.submit([encoder.finish()]);+ // A texel pass is short, so the queue is awaited every few samples: one round trip per sample would dominate the bake.+ if ((sample + 1) % TEXEL_SAMPLES_PER_WAIT === 0 || sample === samples - 1) {+ await device.queue.onSubmittedWorkDone();+ shouldStop();+ }+ }+ const readback = device.createBuffer({ size: accumulationBytes, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });+ const encoder = device.createCommandEncoder();+ encoder.copyBufferToBuffer(accumulation, 0, readback, 0, accumulationBytes);+ device.queue.submit([encoder.finish()]);+ await readback.mapAsync(GPUMapMode.READ);+ const sums = new Float32Array(readback.getMappedRange());+ const radiance = new Float32Array(count * 3);+ const escaped = new Float32Array(count);+ for (let texel = 0; texel < count; texel++) {+ for (let channel = 0; channel < 3; channel++) radiance[texel * 3 + channel] = sums[texel * 4 + channel] / samples;+ escaped[texel] = sums[(count + texel) * 4] / samples;+ }+ readback.destroy();+ for (const buffer of [...uploaded.buffers, accumulation, parameters, ...texelBuffers]) buffer.destroy();+ return { radiance, escaped, gpu: current.gpu, compileSeconds };+}+// The names path-tracer.js looks for in a backend module, the same as path-tracer-gpu.js.export { traceOnWebGpu as traceOnGpu, webGpuKernelCompileCount as gpuKernelCompileCount };diff --git a/tests/light-bake.test.js b/tests/light-bake.test.jsindex aae07142..6467fcb1 100644--- a/tests/light-bake.test.js+++ b/tests/light-bake.test.js@@ -258,9 +258,11 @@ test('the default bounces follow most of the light that a closed room keeps, whiassert.equal(BAKE_LIMITS.bounces.fallback, 3);});-test('the backend option is cpu or gpu, and the synchronous bake refuses the GPU', async () => {+test('the backend option is cpu, gpu or webgpu, and the synchronous bake refuses the GPU ones', async () => {assert.equal(normalizeBakeOptions({ backend: 'gpu' }).backend, 'gpu');- for (const bad of ['webgpu', 'GPU', 1]) assert.throws(() => normalizeBakeOptions({ backend: bad }), { name: 'TypeError', message: /backend/ }, String(bad));+ assert.equal(normalizeBakeOptions({ backend: 'webgpu' }).backend, 'webgpu');+ assert.throws(() => bakeLightmaps(smallRoom(), lamp, { ...fastOptions, backend: 'webgpu' }), { name: 'TypeError', message: /"webgpu".*light-bake-gpu/ });+ for (const bad of ['WebGPU', 'GPU', 1]) assert.throws(() => normalizeBakeOptions({ backend: bad }), { name: 'TypeError', message: /backend/ }, String(bad));assert.throws(() => bakeLightmaps(smallRoom(), lamp, { ...fastOptions, backend: 'gpu' }), { name: 'TypeError', message: /light-bake-gpu/ });const asynchronous = await bakeLightmapsAsync(smallRoom(), lamp, fastOptions);const synchronous = bakeLightmaps(smallRoom(), lamp, fastOptions);diff --git a/tests/path-tracer-webgpu.test.js b/tests/path-tracer-webgpu.test.jsindex 678b607c..478a338c 100644--- a/tests/path-tracer-webgpu.test.js+++ b/tests/path-tracer-webgpu.test.js@@ -3,8 +3,8 @@ import test from 'node:test';import { normalizePathTracerOptions, renderPathTracedImage } from '../src/path-tracer.js';import { buildTraceScene } from '../src/path-tracer-scene.js';-import { MEGAKERNEL_SOURCE, PATH_STATE_VECTORS, WAVEFRONT_SOURCE } from '../src/path-tracer-webgpu-kernel.js';-import { DEFAULT_WEBGPU_KERNEL, isWebGpuTracerAvailable, traceOnWebGpu, unsupportedWebGpuFeatures, WEBGPU_KERNELS } from '../src/path-tracer-webgpu.js';+import { buildMegakernelSource, MEGAKERNEL_SOURCE, PATH_STATE_VECTORS, WAVEFRONT_SOURCE } from '../src/path-tracer-webgpu-kernel.js';+import { DEFAULT_WEBGPU_KERNEL, isWebGpuTracerAvailable, traceOnWebGpu, WEBGPU_KERNELS } from '../src/path-tracer-webgpu.js';function quad(offset) {return {@@ -47,15 +47,33 @@ test('an unknown kernel name is rejected before any GPU work', async () => {assert.deepEqual(calls, ['adapter']);});-test('fog and subsurface scenes are named as unsupported so callers can fall back to gpu', async () => {- assert.deepEqual(unsupportedWebGpuFeatures(buildTraceScene(parts, {})), []);+test('fog and the subsurface walk are compiled in only for the megakernel of a scene that uses them', () => {+ assert.doesNotMatch(MEGAKERNEL_SOURCE, /scatterInFog|volumeInterval|randomWalk|bakeTexels/);+ const fogSource = buildMegakernelSource({ hasVolume: true });+ assert.match(fogSource, /fn scatterInFog\(/);+ assert.match(fogSource, /fn fogTransmittance\(/);+ assert.doesNotMatch(fogSource, /randomWalk/);+ const subsurfaceSource = buildMegakernelSource({ hasSubsurface: true });+ assert.match(subsurfaceSource, /fn randomWalk\(/);+ assert.match(subsurfaceSource, /fn enterSubsurface\(/);+ assert.doesNotMatch(subsurfaceSource, /scatterInFog/);+ assert.doesNotMatch(WAVEFRONT_SOURCE, /scatterInFog|randomWalk/);+});++test('the texel kernel replaces the camera entry point and reads the texels from the two spare bindings', () => {+ const texelSource = buildMegakernelSource({ texelBake: true });+ assert.match(texelSource, /fn bakeTexels\(/);+ assert.match(texelSource, /@binding\(9\)[^\n]*texelPoints/);+ assert.match(texelSource, /@binding\(10\)[^\n]*texelNormals/);+ assert.doesNotMatch(texelSource, /fn main\(/);+});++test('the wavefront kernel refuses a scene with fog or subsurface scattering before it asks for an adapter', async () => {const fogScene = buildTraceScene(parts, { volumeFog: { minimum: [-30, 1, -30], maximum: [30, 2, 30], density: 0.5 } });const subsurfaceParts = [{ ...parts[0], material: { color: [0.7, 0.4, 0.3], subsurface: { weight: 1, radius: [1, 0.2, 0.1], scale: 0.05 } } }];const subsurfaceScene = buildTraceScene(subsurfaceParts, {});- assert.deepEqual(unsupportedWebGpuFeatures(fogScene), ['volume fog']);- assert.deepEqual(unsupportedWebGpuFeatures(subsurfaceScene), ['subsurface scattering']);- await assert.rejects(traceOnWebGpu(fogScene, {}, {}, () => {}), /does not trace volume fog yet.*"gpu"/);- await assert.rejects(traceOnWebGpu(subsurfaceScene, {}, {}, () => {}), /does not trace subsurface scattering yet/);+ await assert.rejects(traceOnWebGpu(fogScene, {}, { kernel: 'wavefront' }, () => {}), /wavefront kernel does not trace volume fog or subsurface/);+ await assert.rejects(traceOnWebGpu(subsurfaceScene, {}, { kernel: 'wavefront' }, () => {}), /wavefront kernel does not trace volume fog or subsurface/);});test('both kernels share the scene bindings and the wavefront adds its path state', () => {