Skip to content

3D engine that AI agents drive

Trace mesh local volumes on the WebGPU path tracer (#2004)

Nguyen Xuan An8e5956a583ba
diff --git a/changes/2004.md b/changes/2004.md
new file mode 100644
index 00000000..010b3c84
--- /dev/null
+++ b/changes/2004.md
@@ -0,0 +1 @@
+- The WebGPU path tracer now draws mesh local volumes (`environment.localVolumes` with shape "mesh" and fit "mesh"): the closed mesh and its BVH ride in the volume buffer and the ray is marched over its inside segments as the CPU tracer does, with a mean FLIP of 0.0020 to the CPU frame on an L-shaped room; before, backend "webgpu" threw and named "cpu". Backend "native" still refuses them (#2004).
diff --git a/docs/volumetric.md b/docs/volumetric.md
index bb8d5522..fee48159 100644
--- a/docs/volumetric.md
+++ b/docs/volumetric.md
@@ -139,7 +139,7 @@ In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is th
Inside one step the glow is weighted by the exact integral over the step, not by the transmittance at its start (#1894). A step of optical depth `tau` (its extinction times its width, per colour channel) adds `emission * width * (1 - exp(-tau)) / tau` of light, then dims what lies behind by `exp(-tau)`; with the start-of-step weight every step counted its light too bright, by about 25 percent at `tau` 0.44, which is a dense box or sphere at 32 steps. Below `tau` 0.001 the weight uses its series. The rasterizer's shape and grid marches, the CPU path tracer's shape, grid and mesh marches and the WebGPU tracer's shape and grid marches all use it (`src/volume-step-integral.js`), so a dense volume is dimmer than it was and a thin one, whose weight is near 1, is unchanged. On the 1-octave sphere of `bench/cycles-parity/capture-volume-edge.mjs` (density 7, 32 steps) the edge width went from 0.2926 to 0.2295 sphere radii and the core from 0.697 to 0.618, against Cycles' 0.2330 and 0.619. The scatter term already used `1 - exp(-extinction)` and is unchanged.
-Each volume is marched between its entry and its exit, cut at the first surface, and the volumes are composited nearest entry first. Two boxes or spheres that share a stretch of the ray are marched together over it: the volume that starts where the nearest one starts joins its march, which stops where another volume starts or one of the two ends, and at every step the glow and the dimming of both add. A soft edge therefore stays soft where another volume's entry plane lies in front of it; before this, the nearer volume was marched whole and dimmed the farther one's glow in front of it, which drew a hard slab. The CPU path tracer marches them the same way (the WebGPU kernel still composites nearest entry first). Three or more volumes that overlap are joined in pairs, nearest first, and a mesh volume or a grid volume is still marched whole, so those overlaps stay an approximation. A scene whose volumes do not overlap, and a scene with one volume, draws bit for bit as before. A frame that overlaps volumes keeps the cost of the marches (a stretch costs the larger step count of its two volumes) and splits a long volume into at most a few stretches. Local volumes are drawn before `volumeFog`, so a fog in front of a puff also dims it. They need the same renderer as the fog (`hdr: true`, `depth: true`, an opaque canvas) and are drawn in the post pass, so they are not in the lightmap bake: a scene bake (`bake` in a recipe) leaves them out, an emissive volume lights no baked surface and no volume dims the baked light, and the bake report names them in `skippedLocalVolumes` (index, shape, whether emissive) with a `warnings` line. A scene without local volumes bakes and reports exactly as before. Add a point light or an emissive part where the volume's glow should reach a wall. The path tracer traces them on `backend: "cpu"` with the same fields, noise included, and on `backend: "webgpu"` (the megakernel) for box, sphere and grid volumes: the WGSL march repeats the CPU one (same step count, jittered midpoints, falloff, noise, sun and sky light of a scattering volume), compiled in only for a scene that has volumes, and on the 480 by 300 reference scene at 32 samples it differs from the CPU frame by a mean FLIP of 0.0011. A mesh volume on `webgpu` throws an error that says to use backend `"cpu"`. A grid volume (#1785) is drawn there too: its voxels follow the volume table in the same storage buffer (the megakernel binds storage buffers only, so no 3D texture), read with the same trilinear weights as the CPU tracer, with one velocity tap per step for `volumeShutter` and the baked blackbody emission; a 128 cubed grid with blackbody and shutter is about 100 MB of float vectors, so lower `--max-resolution` for a device with a smaller storage buffer; the WebGPU wavefront kernel and the realtime WebGPU tracer refuse every local volume. Backend `native` (Cook) draws grid volumes, see "Grid volumes in Cook" below; a box, sphere or mesh volume there throws an error that names its kind. Every other tracer entry point (backend `gpu`, the progressive and both realtime tracers, the GPU light bake) throws `environment.localVolumes is traced by the CPU path tracer only` instead of leaving them out. Cost grows with the covered pixels times `steps` times the number of volumes that the pixel's ray crosses; a ray that misses every volume pays only the interval test.
+Each volume is marched between its entry and its exit, cut at the first surface, and the volumes are composited nearest entry first. Two boxes or spheres that share a stretch of the ray are marched together over it: the volume that starts where the nearest one starts joins its march, which stops where another volume starts or one of the two ends, and at every step the glow and the dimming of both add. A soft edge therefore stays soft where another volume's entry plane lies in front of it; before this, the nearer volume was marched whole and dimmed the farther one's glow in front of it, which drew a hard slab. The CPU path tracer marches them the same way (the WebGPU kernel still composites nearest entry first). Three or more volumes that overlap are joined in pairs, nearest first, and a mesh volume or a grid volume is still marched whole, so those overlaps stay an approximation. A scene whose volumes do not overlap, and a scene with one volume, draws bit for bit as before. A frame that overlaps volumes keeps the cost of the marches (a stretch costs the larger step count of its two volumes) and splits a long volume into at most a few stretches. Local volumes are drawn before `volumeFog`, so a fog in front of a puff also dims it. They need the same renderer as the fog (`hdr: true`, `depth: true`, an opaque canvas) and are drawn in the post pass, so they are not in the lightmap bake: a scene bake (`bake` in a recipe) leaves them out, an emissive volume lights no baked surface and no volume dims the baked light, and the bake report names them in `skippedLocalVolumes` (index, shape, whether emissive) with a `warnings` line. A scene without local volumes bakes and reports exactly as before. Add a point light or an emissive part where the volume's glow should reach a wall. The path tracer traces them on `backend: "cpu"` with the same fields, noise included, and on `backend: "webgpu"` (the megakernel) for box, sphere, mesh and grid volumes: the WGSL march repeats the CPU one (same step count, jittered midpoints, falloff, noise, sun and sky light of a scattering volume), compiled in only for a scene that has volumes, and on the 480 by 300 reference scene at 32 samples it differs from the CPU frame by a mean FLIP of 0.0011. A mesh volume (#2004) is drawn there too, with the CPU tracer's model: its part's triangles and their own BVH sit in a block at the end of the volume buffer, the ray is walked from surface crossing to surface crossing, the parity of the crossings says where it is inside, and the inside segments share the volume's `steps` by length, with absorption and emission and a profile of 1. The WebGPU walk steps `1e-5` of the volume's diagonal past a crossing where the CPU walk steps `1e-6`, because it works in 32 bit. The mesh block is compiled and uploaded only for a scene that has a mesh volume, a scene may hold at most 262144 triangles across its mesh volumes (the error says to simplify the parts or use backend `"cpu"`), and on the L-shaped room scene of `tests/helpers/mesh-volume-render.js` at 32 samples the WebGPU frame differs from the CPU frame by a mean FLIP of 0.0020. Backend `native` still refuses a mesh volume. A grid volume (#1785) is drawn there too: its voxels follow the volume table in the same storage buffer (the megakernel binds storage buffers only, so no 3D texture), read with the same trilinear weights as the CPU tracer, with one velocity tap per step for `volumeShutter` and the baked blackbody emission; a 128 cubed grid with blackbody and shutter is about 100 MB of float vectors, so lower `--max-resolution` for a device with a smaller storage buffer; the WebGPU wavefront kernel and the realtime WebGPU tracer refuse every local volume. Backend `native` (Cook) draws grid volumes, see "Grid volumes in Cook" below; a box, sphere or mesh volume there throws an error that names its kind. Every other tracer entry point (backend `gpu`, the progressive and both realtime tracers, the GPU light bake) throws `environment.localVolumes is traced by the CPU path tracer only` instead of leaving them out. Cost grows with the covered pixels times `steps` times the number of volumes that the pixel's ray crosses; a ray that misses every volume pays only the interval test.
### Thick smoke and thin haze
diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.js
index 0c990e62..dad3d1c1 100644
--- a/src/path-tracer-scene.js
+++ b/src/path-tracer-scene.js
@@ -593,7 +593,7 @@ export function attachTracer(scene) {
/** Local volumes are traced by the CPU path tracer and, for boxes and spheres, the WebGPU final tracer. Every other tracer entry point calls this so none drops them silently. */
export function refuseLocalVolumes(scene, tracerName) {
if (!scene.localVolumes) return;
- throw new RangeError(`environment.localVolumes is traced by the CPU path tracer only; ${tracerName} cannot draw them. Use backend "cpu" (backend "webgpu" draws box, sphere and grid volumes) or remove the volumes.`);
+ throw new RangeError(`environment.localVolumes is traced by the CPU path tracer only; ${tracerName} cannot draw them. Use backend "cpu" (backend "webgpu" draws box, sphere, mesh and grid volumes) or remove the volumes.`);
}
// The rasterizer's own test (renderer.js `isHidden`): a part hides by `visible: false` or by the `visibility.visible` that a posed scene keys.
diff --git a/src/path-tracer-volume.js b/src/path-tracer-volume.js
index a484e542..4b2ad0fc 100644
--- a/src/path-tracer-volume.js
+++ b/src/path-tracer-volume.js
@@ -95,7 +95,7 @@ export function prepareMeshVolume(volume, label) {
const openEdges = countOpenEdges(positions, geometry.indices, diagonal * 1e-6);
if (openEdges > 0) throw new RangeError(`${label}.part "${volume.part.name}" is not a closed mesh (${openEdges} open edges), so it has no inside; close it or use fit "bounds"`);
const bvh = buildTriangleBvh(positions, geometry.indices);
- return { ...volume, mesh: { tracer: createTracer({ positions, indices: geometry.indices, bvh }), stepOffset: diagonal * 1e-6 } };
+ return { ...volume, mesh: { tracer: createTracer({ positions, indices: geometry.indices, bvh }), stepOffset: diagonal * 1e-6, positions, indices: geometry.indices, bvh } };
}
/**
diff --git a/src/path-tracer-webgpu-kernel.js b/src/path-tracer-webgpu-kernel.js
index 3a13528e..f67221b9 100644
--- a/src/path-tracer-webgpu-kernel.js
+++ b/src/path-tracer-webgpu-kernel.js
@@ -16,7 +16,7 @@ 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 buildCommonSource = ({ hasVolume = false, hasLocalVolumes = false, hasGridVolume = false, hasNoiseOctaves = false, hasEmissionRamp = false } = {}) => /* wgsl */ `
+const buildCommonSource = ({ hasVolume = false, hasLocalVolumes = false, hasGridVolume = false, hasNoiseOctaves = false, hasEmissionRamp = false, hasMeshVolume = false } = {}) => /* wgsl */ `
const PI: f32 = 3.14159265358979;
const TWO_PI: f32 = 6.28318530717959;
const TRIANGLE_TEXELS: i32 = 10;
@@ -882,7 +882,7 @@ fn addDirect(depth: i32, normal: vec3<f32>, distance: f32, weightMode: i32) {
}
${hasVolume ? VOLUME_FUNCTIONS : hasLocalVolumes ? PHASE_FUNCTIONS : ''}
-${hasLocalVolumes ? buildLocalVolumeFunctions({ hasGrid: hasGridVolume, hasNoiseOctaves, hasEmissionRamp }) : ''}
+${hasLocalVolumes ? buildLocalVolumeFunctions({ hasGrid: hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMesh: hasMeshVolume }) : ''}
fn flushShadowRay() {
if (!shadowPending) { return; }
shadowPending = false;
@@ -1179,7 +1179,7 @@ fn bakeTexels(@builtin(global_invocation_id) id: vec3<u32>, @builtin(num_workgro
`;
// `realtime` is the set of WGSL pieces of path-tracer-realtime-webgpu-kernel.js (REALTIME_KERNEL_PIECES); the real-time tracer passes them in, so other bundles do not carry them.
-export const buildMegakernelSource = ({ hasVolume = false, hasLocalVolumes = false, hasGridVolume = false, hasNoiseOctaves = false, hasEmissionRamp = false, hasSubsurface = false, texelBake = false, realtime = null } = {}) => buildCommonSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp }) + /* wgsl */ `
+export const buildMegakernelSource = ({ hasVolume = false, hasLocalVolumes = false, hasGridVolume = false, hasNoiseOctaves = false, hasEmissionRamp = false, hasMeshVolume = false, hasSubsurface = false, texelBake = false, realtime = null } = {}) => buildCommonSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume }) + /* wgsl */ `
${realtime ? realtime.declarations + realtime.addLights : `// The first hit lights from every emitter; later hits draw one, and divide by the chance of drawing it.
fn addLights(depth: i32, normal: vec3<f32>) {
let emitterCount = params.emittersFlagsSample.x;
diff --git a/src/path-tracer-webgpu-local-volumes.js b/src/path-tracer-webgpu-local-volumes.js
index 3f87f3c3..29a1d999 100644
--- a/src/path-tracer-webgpu-local-volumes.js
+++ b/src/path-tracer-webgpu-local-volumes.js
@@ -5,12 +5,13 @@ import { bakeEmissionRamp } from './local-volume-ramp-bake.js';
import { meanEnvironmentRadiance } from './path-tracer-volume.js';
import { bakedGridEmission, GRID_MOTION_TIME_STEP, gridUnitVelocity, volumeGridFloats } from './volume-grid.js';
import { STEP_INTEGRAL_WGSL } from './volume-step-integral.js';
+import { packNodes } from './path-tracer-gpu-pack.js';
// Local volumes (environment.localVolumes: boxes and spheres of absorbing, emitting and scattering medium) on the WebGPU path
// tracer (#1048). The WGSL is the march of createLocalVolumeCrossing in path-tracer-volume.js: the same step count, jittered
// midpoints, profile with falloff and noise, and the same sun and sky terms for a scattering volume, so the two tracers draw one
// picture and differ by noise only. The march is spliced into the megakernel only for a scene that has volumes.
-// Mesh volumes need a BVH the table below has no room for and stay on backend "cpu". A grid volume (#1785) rides in the same buffer after the
+// A mesh volume (#2004) carries its own triangles and BVH in a block at the end of the buffer and is marched over the inside segments of the closed mesh, as the CPU tracer does. A grid volume (#1785) rides in the same buffer after the
// table: the megakernel's one bind group holds storage buffers only, so the voxels are float vectors read with the trilinear weights of
// sampleVolumeGrid, not a 3D texture. The motion blur reads each step at its shutter time, as the CPU tracer does.
@@ -19,6 +20,16 @@ export const LOCAL_VOLUME_TEXELS = 8;
export const LOCAL_VOLUME_HEADER_TEXELS = 2;
/** The shape code of a grid volume in the table (box 0, sphere 1). Negative so the box and sphere tests of the kernel never match it. */
export const LOCAL_VOLUME_GRID_SHAPE = -1;
+/** The shape code of a mesh volume in the table. */
+export const LOCAL_VOLUME_MESH_SHAPE = -2;
+/** The most triangles the mesh volumes of one scene may hold together: 262144 triangles are about 30 MB of nodes and corners in the volume buffer. */
+export const MAX_WEBGPU_MESH_VOLUME_TRIANGLES = 262144;
+/** Vectors per triangle of a mesh volume: the corner and the two edges. */
+export const MESH_VOLUME_TRIANGLE_TEXELS = 3;
+/** The most surface crossings along one ray and the most inside segments they make (MAXIMUM_MESH_CROSSINGS and MAXIMUM_MESH_SEGMENTS of path-tracer-volume.js). */
+export const MESH_VOLUME_MAXIMUM_CROSSINGS = 64;
+/** A crossing at a distance cannot be told from the surface it left by less than this fraction of the volume's diagonal (the CPU tracer steps 1e-6 in 64 bit; 32 bit needs more). */
+export const MESH_VOLUME_STEP_OFFSET_FRACTION = 1e-5;
/** Vectors of one emission ramp in the ramp block: the source, stop count and range, the emission strength, then up to LOCAL_VOLUME_RAMP_STOPS colours. */
export const LOCAL_VOLUME_RAMP_TEXELS = 2 + LOCAL_VOLUME_RAMP_STOPS;
/** Vectors in front of a grid's voxels: the resolution and blackbody weight, then the shutter, the two optional channel flags and the voxel stride. */
@@ -26,11 +37,11 @@ export const LOCAL_VOLUME_GRID_HEADER_TEXELS = 2;
const IDENTITY_AXES = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
-/** Throws for a volume the WebGPU tracer cannot draw, naming the kind and the backend that can; does nothing for a scene without volumes. */
+/** Throws for a volume the WebGPU tracer cannot draw; does nothing for a scene without volumes. A mesh volume has to come prepared (its part bound and its BVH built by the trace scene). */
export function assertWebGpuLocalVolumes(scene) {
scene.localVolumes?.forEach((volume, index) => {
- if (volume.shape === 'mesh' || volume.part) {
- throw new RangeError(`environment.localVolumes[${index}] is a mesh volume, which only backend "cpu" traces; the WebGPU path tracer draws box, sphere and grid volumes. Use backend "cpu" or make it a box or sphere.`);
+ if (volume.part && !volume.mesh) {
+ throw new RangeError(`environment.localVolumes[${index}] is a mesh volume that was not prepared for tracing; build the scene with buildTraceScene, which builds its BVH, or use fit "bounds".`);
}
});
}
@@ -41,6 +52,7 @@ export function webGpuVolumeFeatures(volumes) {
hasGridVolume: Boolean(volumes?.some(volume => volume.shape === 'grid')),
hasNoiseOctaves: Boolean(volumes?.some(volume => volume.noiseAmount > 0 && volume.noiseOctaves > 1)),
hasEmissionRamp: Boolean(volumes?.some(volume => volume.emissionRamp)),
+ hasMeshVolume: Boolean(volumes?.some(volume => volume.mesh)),
};
}
@@ -49,12 +61,15 @@ export function webGpuVolumeFeatures(volumes) {
* followed by eight vectors per volume:
* 0 centre, shape (0 box, 1 sphere) 1 half extents, falloff 2 absorption times density, noise amount
* 3 emission times strength, noise scale 4 steps, scatter, anisotropy, radius 5-7 the three rows of the box axes.
+ * A mesh volume has shape code LOCAL_VOLUME_MESH_SHAPE and its number among the mesh volumes in the radius slot of vector 4; its table row is otherwise a box's, so the same fields set its steps, absorption and emission.
+ * The second float of the header is the vector index of the mesh block, relative to the table (0 without mesh volumes); the mesh block is the last block of the buffer.
* The fourth float of vector 5 is the noise octaves minus one and that of vector 7 is the ramp number plus one (0 for no ramp); a ramp block follows the table
* and the grid block (packWebGpuEmissionRamps).
*/
export function packWebGpuLocalVolumes(volumes, environment) {
if (volumes.length > MAX_LOCAL_VOLUMES) throw new RangeError(`The WebGPU path tracer holds at most ${MAX_LOCAL_VOLUMES} local volumes, got ${volumes.length}`);
const rampVolumes = volumes.filter(volume => volume.emissionRamp);
+ const meshVolumes = volumes.filter(volume => volume.mesh);
const table = new Float32Array((LOCAL_VOLUME_HEADER_TEXELS + volumes.length * LOCAL_VOLUME_TEXELS) * 4);
table.set([volumes.length, 0, 0, 0], 0);
table.set([...meanEnvironmentRadiance(environment), 0], 4);
@@ -62,13 +77,14 @@ export function packWebGpuLocalVolumes(volumes, environment) {
const at = (LOCAL_VOLUME_HEADER_TEXELS + index * LOCAL_VOLUME_TEXELS) * 4;
const isSphere = volume.shape === 'sphere';
const isGrid = volume.shape === 'grid';
+ const isMesh = Boolean(volume.mesh);
const half = isSphere ? [volume.radius, volume.radius, volume.radius] : volume.size.map(extent => extent / 2);
const axes = volume.axes ?? IDENTITY_AXES;
- table.set([...volume.center, isGrid ? LOCAL_VOLUME_GRID_SHAPE : isSphere ? 1 : 0], at);
+ table.set([...volume.center, isGrid ? LOCAL_VOLUME_GRID_SHAPE : isMesh ? LOCAL_VOLUME_MESH_SHAPE : isSphere ? 1 : 0], at);
table.set([...half, volume.falloff], at + 4);
table.set([...volume.absorption.map(channel => channel * volume.density), volume.noiseAmount], at + 8);
table.set([...volume.emission.map(channel => channel * volume.emissionStrength), volume.noiseScale], at + 12);
- table.set([volume.steps, volume.scatter ?? 0, volume.anisotropy ?? 0, isSphere ? volume.radius : 0], at + 16);
+ table.set([volume.steps, volume.scatter ?? 0, volume.anisotropy ?? 0, isSphere ? volume.radius : isMesh ? meshVolumes.indexOf(volume) : 0], at + 16);
const octavesAfterFirst = (volume.noiseOctaves ?? 1) - 1;
const rampNumber = volume.emissionRamp ? rampVolumes.indexOf(volume) + 1 : 0;
for (let row = 0; row < 3; row++) table.set([axes[row * 3], axes[row * 3 + 1], axes[row * 3 + 2], row === 0 ? octavesAfterFirst : row === 2 ? rampNumber : 0], at + 20 + row * 4);
@@ -77,6 +93,10 @@ export function packWebGpuLocalVolumes(volumes, environment) {
const blocks = [table];
if (gridVolume) blocks.push(packWebGpuGrid(gridVolume));
if (rampVolumes.length > 0) blocks.push(packWebGpuEmissionRamps(rampVolumes));
+ if (meshVolumes.length > 0) {
+ table[1] = blocks.reduce((length, block) => length + block.length, 0) / 4;
+ blocks.push(packWebGpuMeshVolumes(meshVolumes));
+ }
return blocks.length === 1 ? table : concatenateFloats(blocks);
}
@@ -107,6 +127,45 @@ export function packWebGpuEmissionRamps(rampVolumes) {
return block;
}
+/**
+ * The mesh block, the last block of the buffer: the mesh count, then one descriptor vector per mesh volume, then each mesh's BVH nodes and triangles.
+ * header 0 mesh count, 0, 0, 0
+ * header 1+ node start, triangle start (vector indices from the block), the step offset past a crossing, node count
+ * nodes two vectors a node as packNodes writes them (minimum and right child or minus the leaf count, maximum and first slot)
+ * triangles MESH_VOLUME_TRIANGLE_TEXELS vectors a leaf slot: the first corner, then the two edges, in world space
+ */
+export function packWebGpuMeshVolumes(meshVolumes) {
+ const triangleTotal = meshVolumes.reduce((total, volume) => total + volume.mesh.indices.length / 3, 0);
+ if (triangleTotal > MAX_WEBGPU_MESH_VOLUME_TRIANGLES) {
+ throw new RangeError(`The WebGPU path tracer holds at most ${MAX_WEBGPU_MESH_VOLUME_TRIANGLES} triangles across mesh local volumes, got ${triangleTotal}; simplify the parts or use backend "cpu".`);
+ }
+ const headerTexels = 1 + meshVolumes.length;
+ const sizes = meshVolumes.map(volume => ({ nodes: volume.mesh.bvh.nodeCount * 2, triangles: (volume.mesh.indices.length / 3) * MESH_VOLUME_TRIANGLE_TEXELS }));
+ const block = new Float32Array((headerTexels + sizes.reduce((total, size) => total + size.nodes + size.triangles, 0)) * 4);
+ block[0] = meshVolumes.length;
+ let cursor = headerTexels;
+ meshVolumes.forEach((volume, index) => {
+ const { positions, indices, bvh } = volume.mesh;
+ const diagonal = Math.hypot(...volume.size);
+ block.set([cursor, cursor + sizes[index].nodes, diagonal * MESH_VOLUME_STEP_OFFSET_FRACTION, bvh.nodeCount], (1 + index) * 4);
+ block.set(packNodes(bvh).data.subarray(0, sizes[index].nodes * 4), cursor * 4);
+ const triangleBase = (cursor + sizes[index].nodes) * 4;
+ for (let slot = 0; slot < bvh.triangleOrder.length; slot++) {
+ const triangle = bvh.triangleOrder[slot];
+ const first = indices[triangle * 3] * 3;
+ const second = indices[triangle * 3 + 1] * 3;
+ const third = indices[triangle * 3 + 2] * 3;
+ for (let axis = 0; axis < 3; axis++) {
+ block[triangleBase + slot * 12 + axis] = positions[first + axis];
+ block[triangleBase + slot * 12 + 4 + axis] = positions[second + axis] - positions[first + axis];
+ block[triangleBase + slot * 12 + 8 + axis] = positions[third + axis] - positions[first + axis];
+ }
+ }
+ cursor += sizes[index].nodes + sizes[index].triangles;
+ });
+ return block;
+}
+
function gridBlockLength(volume) {
const [width, height, depth] = volume.gridData.resolution;
return (LOCAL_VOLUME_GRID_HEADER_TEXELS + width * height * depth * gridVoxelStride(volume)) * 4;
@@ -160,9 +219,9 @@ export function packWebGpuGrid(volume) {
/**
* The march. `params.seedAndAtlas.w` is the vector index of the table header in the materials buffer. With `hasGrid` the grid march and sampler are
* spliced in; without it the text is what it was before grids, so a scene without a grid compiles the same kernel. `hasNoiseOctaves` and `hasEmissionRamp`
- * splice the fractal noise and the ramp light the same way.
+ * splice the fractal noise and the ramp light the same way, and `hasMesh` the mesh volume march.
*/
-export const buildLocalVolumeFunctions = ({ hasGrid = false, hasNoiseOctaves = false, hasEmissionRamp = false } = {}) => /* wgsl */ `
+export const buildLocalVolumeFunctions = ({ hasGrid = false, hasNoiseOctaves = false, hasEmissionRamp = false, hasMesh = false } = {}) => /* wgsl */ `
${STEP_INTEGRAL_WGSL}
const LOCAL_VOLUME_TEXELS: i32 = ${LOCAL_VOLUME_TEXELS};
const LOCAL_VOLUME_HEADER_TEXELS: i32 = ${LOCAL_VOLUME_HEADER_TEXELS};
@@ -339,8 +398,13 @@ fn crossLocalVolumes(depth: i32, origin: vec3<f32>, segmentLength: f32) {
var order: array<i32, ${MAX_LOCAL_VOLUMES}>;
var crossed = 0;
for (var volume = 0; volume < count; volume++) {
- if (!localVolumeInterval(volume, origin, direction, segmentLength)) { continue; }
- entries[volume] = localSpan.x;
+${hasMesh ? ` if (localVolumeTexel(volume, 0).w < -1.5) {
+ let segmentCount = meshVolumeSegments(volume, origin, direction, segmentLength);
+ if (segmentCount == 0) { continue; }
+ localSpan = vec2<f32>(meshSegments[0], meshSegments[segmentCount * 2 - 1]);
+ } else if (!localVolumeInterval(volume, origin, direction, segmentLength)) { continue; }
+` : ` if (!localVolumeInterval(volume, origin, direction, segmentLength)) { continue; }
+`} entries[volume] = localSpan.x;
exits[volume] = localSpan.y;
var slot = crossed;
crossed++;
@@ -353,7 +417,11 @@ fn crossLocalVolumes(depth: i32, origin: vec3<f32>, segmentLength: f32) {
var emitted = vec3<f32>(0.0);
for (var rank = 0; rank < crossed; rank++) {
let volume = order[rank];
-${hasGrid ? ` if (localVolumeTexel(volume, 0).w < -0.5) {
+${hasMesh ? ` if (localVolumeTexel(volume, 0).w < -1.5) {
+ emitted += crossLocalMesh(volume, origin, segmentLength, jitter);
+ continue;
+ }
+` : ''}${hasGrid ? ` if (localVolumeTexel(volume, 0).w < -0.5) {
emitted += crossLocalGrid(volume, origin, entries[volume], exits[volume] - entries[volume], jitter);
continue;
}
@@ -377,7 +445,7 @@ ${hasEmissionRamp ? ` emitted += throughput * localEmissionRampLight(volume
}
addRadiance(depth, emitted);
}
-${hasEmissionRamp ? buildRampFunctions(hasGrid) : ''}${hasGrid ? buildGridFunctions({ hasEmissionRamp }) : ''}`;
+${hasEmissionRamp ? buildRampFunctions(hasGrid) : ''}${hasGrid ? buildGridFunctions({ hasEmissionRamp }) : ''}${hasMesh ? MESH_FUNCTIONS : ''}`;
// The fractal value noise of localVolumeFractalNoise in local-volume-noise.js: octaves at twice the frequency and half the weight, divided by the weights.
const FRACTAL_NOISE_FUNCTION = /* wgsl */ `fn localVolumeFractalNoise(position: vec3<f32>, octaves: i32) -> f32 {
@@ -536,5 +604,145 @@ ${hasEmissionRamp ? ` emitted += throughput * localEmissionRampLight(volume,
}
`;
+/**
+ * The WGSL of a mesh volume (marchMeshVolume and meshVolumeSegments of the CPU tracer): the ray is walked from surface crossing to surface crossing through the mesh's own
+ * BVH, the parity of the crossings says where it is inside, and the inside segments share the volume's steps by length. The block layout is packWebGpuMeshVolumes'.
+ */
+const MESH_FUNCTIONS = /* wgsl */ `
+const MESH_MAXIMUM_CROSSINGS: i32 = ${MESH_VOLUME_MAXIMUM_CROSSINGS};
+const MESH_MAXIMUM_SEGMENTS: i32 = ${MESH_VOLUME_MAXIMUM_CROSSINGS / 2};
+const MESH_TRIANGLE_TEXELS: i32 = ${MESH_VOLUME_TRIANGLE_TEXELS};
+
+var<private> meshCrossings: array<f32, ${MESH_VOLUME_MAXIMUM_CROSSINGS}>;
+var<private> meshSegments: array<f32, ${MESH_VOLUME_MAXIMUM_CROSSINGS}>;
+var<private> meshNodeStack: array<i32, 128>;
+var<private> meshEntryStack: array<f32, 128>;
+
+// The vector index of the mesh block: the second float of the table header says how far it is from the table.
+fn meshBlockBase() -> i32 {
+ let first = i32(params.seedAndAtlas.w);
+ return first + i32(materials[first].y);
+}
+
+fn meshBoxEntry(nodeBase: i32, node: i32, origin: vec3<f32>, inverse: vec3<f32>) -> f32 {
+ let low = materials[nodeBase + node * 2];
+ let high = materials[nodeBase + 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);
+}
+
+// The distance to the nearest surface of a mesh volume along a ray, either side, or -1 when there is none.
+fn meshNearestSurface(nodeBase: i32, triangleBase: i32, origin: vec3<f32>, rayDirection: vec3<f32>) -> f32 {
+ var nearest = 1e30;
+ let inverse = safeInverse(rayDirection);
+ var stackSize = 1;
+ meshNodeStack[0] = 0;
+ meshEntryStack[0] = 0.0;
+ while (stackSize > 0) {
+ stackSize--;
+ let node = meshNodeStack[stackSize];
+ if (!(meshEntryStack[stackSize] < nearest)) { continue; }
+ let header = materials[nodeBase + node * 2];
+ if (header.w < 0.0) {
+ let start = i32(materials[nodeBase + node * 2 + 1].w);
+ let end = start + i32(-header.w);
+ for (var slot = start; slot < end; slot++) {
+ let base = triangleBase + slot * MESH_TRIANGLE_TEXELS;
+ let corner = materials[base].xyz;
+ let edgeFirst = materials[base + 1].xyz;
+ let edgeSecond = materials[base + 2].xyz;
+ let pivot = cross(rayDirection, 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(rayDirection, query) / determinant;
+ if (secondWeight < 0.0 || firstWeight + secondWeight > 1.0) { continue; }
+ let distance = dot(edgeSecond, query) / determinant;
+ if (distance < 0.0 || distance >= nearest) { continue; }
+ nearest = distance;
+ }
+ continue;
+ }
+ let left = node + 1;
+ let right = i32(header.w);
+ let leftEntry = meshBoxEntry(nodeBase, left, origin, inverse);
+ let rightEntry = meshBoxEntry(nodeBase, right, origin, inverse);
+ let nearFirst = leftEntry <= rightEntry;
+ meshNodeStack[stackSize] = select(left, right, nearFirst);
+ meshEntryStack[stackSize] = select(leftEntry, rightEntry, nearFirst);
+ meshNodeStack[stackSize + 1] = select(right, left, nearFirst);
+ meshEntryStack[stackSize + 1] = select(rightEntry, leftEntry, nearFirst);
+ stackSize += 2;
+ }
+ return select(nearest, -1.0, nearest >= 1e30);
+}
+
+// Where a ray is inside a closed mesh volume, clipped to [0, limit]: the [entry, exit] pairs go to meshSegments and their number is returned.
+fn meshVolumeSegments(volume: i32, origin: vec3<f32>, rayDirection: vec3<f32>, limit: f32) -> i32 {
+ let block = meshBlockBase();
+ let descriptor = materials[block + 1 + i32(localVolumeTexel(volume, 4).w)];
+ let nodeBase = block + i32(descriptor.x);
+ let triangleBase = block + i32(descriptor.y);
+ var crossingCount = 0;
+ var cursor = 0.0;
+ while (crossingCount < MESH_MAXIMUM_CROSSINGS) {
+ let distance = meshNearestSurface(nodeBase, triangleBase, origin + rayDirection * cursor, rayDirection);
+ if (distance < 0.0) { break; }
+ cursor += distance;
+ meshCrossings[crossingCount] = cursor;
+ crossingCount++;
+ cursor += descriptor.z;
+ }
+ var inside = (crossingCount % 2) == 1;
+ var start = 0.0;
+ var segmentCount = 0;
+ for (var crossing = 0; crossing < crossingCount; crossing++) {
+ let distance = meshCrossings[crossing];
+ if (inside) {
+ let end = min(distance, limit);
+ if (end > start && segmentCount < MESH_MAXIMUM_SEGMENTS) {
+ meshSegments[segmentCount * 2] = start;
+ meshSegments[segmentCount * 2 + 1] = end;
+ segmentCount++;
+ }
+ } else {
+ start = distance;
+ }
+ inside = !inside;
+ }
+ return segmentCount;
+}
+
+// One mesh volume along the ray: its steps are shared between the inside segments in proportion to their length, and the profile is 1.
+fn crossLocalMesh(volume: i32, origin: vec3<f32>, limit: f32, jitter: f32) -> vec3<f32> {
+ let segmentCount = meshVolumeSegments(volume, origin, direction, limit);
+ var total = 0.0;
+ for (var segment = 0; segment < segmentCount; segment++) { total += meshSegments[segment * 2 + 1] - meshSegments[segment * 2]; }
+ let extinction = localVolumeTexel(volume, 2).xyz;
+ let emission = localVolumeTexel(volume, 3).xyz;
+ let volumeSteps = localVolumeTexel(volume, 4).x;
+ var emitted = vec3<f32>(0.0);
+ for (var segment = 0; segment < segmentCount; segment++) {
+ let entry = meshSegments[segment * 2];
+ let segmentLength = meshSegments[segment * 2 + 1] - entry;
+ let steps = max(1, i32(floor(volumeSteps * segmentLength / total + 0.5)));
+ let stepLength = segmentLength / f32(steps);
+ for (var stepIndex = 0; stepIndex < steps; stepIndex++) {
+ emitted += throughput * emission * stepLength * volumeStepIntegral(extinction * stepLength);
+ throughput *= exp(-extinction * stepLength);
+ }
+ }
+ return emitted;
+}
+`;
+
/** The march without grids, as the kernel splices it into a scene that has box and sphere volumes. */
export const LOCAL_VOLUME_FUNCTIONS = buildLocalVolumeFunctions();
diff --git a/src/path-tracer-webgpu.js b/src/path-tracer-webgpu.js
index 10f2e701..e70f5464 100644
--- a/src/path-tracer-webgpu.js
+++ b/src/path-tracer-webgpu.js
@@ -83,10 +83,10 @@ async function getSession() {
}
/** 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, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasSubsurface, texelBake, realtime }) {
+function describeVariant({ kernel, hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume, hasSubsurface, texelBake, realtime }) {
if (kernel === 'wavefront') return { code: WAVEFRONT_SOURCE, entryPoints: WAVEFRONT_ENTRY_POINTS };
- if (realtime) return { code: buildMegakernelSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasSubsurface, realtime }), entryPoints: ['traceRealtime'] };
- return { code: buildMegakernelSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasSubsurface, texelBake }), entryPoints: [texelBake ? 'bakeTexels' : 'main'] };
+ if (realtime) return { code: buildMegakernelSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume, hasSubsurface, realtime }), entryPoints: ['traceRealtime'] };
+ return { code: buildMegakernelSource({ hasVolume, hasLocalVolumes, hasGridVolume, hasNoiseOctaves, hasEmissionRamp, hasMeshVolume, hasSubsurface, texelBake }), entryPoints: [texelBake ? 'bakeTexels' : 'main'] };
}
async function compileKernel(current, variant) {
@@ -103,7 +103,7 @@ async function compileKernel(current, variant) {
}
async function getKernel(current, variant) {
- const key = [variant.kernel, variant.hasVolume, variant.hasLocalVolumes, variant.hasGridVolume, variant.hasNoiseOctaves, variant.hasEmissionRamp, variant.hasSubsurface, variant.texelBake, Boolean(variant.realtime)].join(':');
+ const key = [variant.kernel, variant.hasVolume, variant.hasLocalVolumes, variant.hasGridVolume, variant.hasNoiseOctaves, variant.hasEmissionRamp, variant.hasMeshVolume, variant.hasSubsurface, variant.texelBake, Boolean(variant.realtime)].join(':');
if (!current.kernels.has(key)) current.kernels.set(key, compileKernel(current, variant));
return current.kernels.get(key);
}
diff --git a/tests/helpers/mesh-volume-render.js b/tests/helpers/mesh-volume-render.js
new file mode 100644
index 00000000..e7ddf666
--- /dev/null
+++ b/tests/helpers/mesh-volume-render.js
@@ -0,0 +1,35 @@
+// Runs in the page of withWebGpuPage: an L-shaped closed room (a hidden part) over a floor, filled with a glowing mesh volume (#2004), path traced on the CPU and on the
+// WebGPU tracer with the same seed, so a test and an evidence script compare the two. Returns the linear pixels of each backend and the seconds each took.
+export async function renderMeshVolumeBothBackends({ width, height, samples, volumeExtra = {} }) {
+ const { box: makeBox } = await import('/src/geometry.js');
+ const { renderPathTracedImage } = await import('/src/path-tracer.js');
+ // Three unit squares in x and z (the notch is x in 1..2, z in 1..2), extruded in y from 0 to 1.
+ const outline = [[0, 0], [1, 0], [2, 0], [2, 1], [1, 1], [1, 2], [0, 2], [0, 1]];
+ const positions = [];
+ for (const height01 of [0, 1]) for (const [x, z] of outline) positions.push(x, height01, z);
+ const indices = [];
+ const top = outline.length;
+ for (const [firstCorner, secondCorner, thirdCorner, fourthCorner] of [[0, 1, 4, 7], [1, 2, 3, 4], [7, 4, 5, 6]]) {
+ indices.push(firstCorner, secondCorner, thirdCorner, firstCorner, thirdCorner, fourthCorner, top + firstCorner, top + thirdCorner, top + secondCorner, top + firstCorner, top + fourthCorner, top + thirdCorner);
+ }
+ for (let corner = 0; corner < outline.length; corner++) {
+ const next = (corner + 1) % outline.length;
+ indices.push(corner, next, top + next, corner, top + next, top + corner);
+ }
+ const geometry = { positions: new Float32Array(positions), indices: new Uint32Array(indices), normals: new Float32Array(positions.length) };
+ const roomMatrix = new Float32Array([3, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, -3, 0.05, -3, 1]);
+ const floorMatrix = new Float32Array([10, 0, 0, 0, 0, 0.05, 0, 0, 0, 0, 10, 0, 0, 0, 0, 1]);
+ const material = { color: [0.5, 0.5, 0.5] };
+ const parts = [{ name: 'floor', geometry: makeBox(0, 1), matrix: floorMatrix, material }, { name: 'room', visible: false, geometry, matrix: roomMatrix, material }];
+ const volume = { shape: 'mesh', part: 'room', fit: 'mesh', density: 1.2, falloff: 0, steps: 24, absorption: [0.7, 0.8, 1], emission: [0.9, 0.45, 0.15], emissionStrength: 1.5, ...volumeExtra };
+ const map = { width: 4, height: 2, channels: 3, data: new Float32Array(24).fill(0.15), intensity: 1, rotation: 0 };
+ const environment = { localVolumes: [volume], keyColor: [3, 3, 3], lightDirection: [1, 0.6, 0.3], map };
+ const camera = { eye: [0, 6, 7.5], target: [0, 0.7, 0], fov: 45 };
+ const result = {};
+ for (const backend of ['cpu', 'webgpu']) {
+ const started = performance.now();
+ const image = await renderPathTracedImage({ parts, environment, camera }, { width, height, samples, bounces: 3, seed: 7, backend, denoiser: 'none', threads: 1 });
+ result[backend] = { linear: Array.from(image.linear), seconds: (performance.now() - started) / 1000, ignored: image.report?.ignored ?? [] };
+ }
+ return result;
+}
diff --git a/tests/path-tracer-webgpu-local-volumes.test.js b/tests/path-tracer-webgpu-local-volumes.test.js
index 9cb272c1..d58f422a 100644
--- a/tests/path-tracer-webgpu-local-volumes.test.js
+++ b/tests/path-tracer-webgpu-local-volumes.test.js
@@ -8,9 +8,11 @@ import { resolveLocalVolumes } from '../src/local-volumes.js';
import { buildTraceScene, refuseLocalVolumes } from '../src/path-tracer-scene.js';
import { bindLocalVolumeParts } from '../src/local-volume-parts.js';
import { buildMegakernelSource, MEGAKERNEL_SOURCE } from '../src/path-tracer-webgpu-kernel.js';
-import { assertWebGpuLocalVolumes, buildLocalVolumeFunctions, LOCAL_VOLUME_FUNCTIONS, LOCAL_VOLUME_GRID_HEADER_TEXELS, LOCAL_VOLUME_GRID_SHAPE, LOCAL_VOLUME_HEADER_TEXELS, LOCAL_VOLUME_RAMP_TEXELS, LOCAL_VOLUME_TEXELS, packWebGpuLocalVolumes, webGpuVolumeFeatures } from '../src/path-tracer-webgpu-local-volumes.js';
+import { assertWebGpuLocalVolumes, buildLocalVolumeFunctions, LOCAL_VOLUME_FUNCTIONS, LOCAL_VOLUME_GRID_HEADER_TEXELS, LOCAL_VOLUME_GRID_SHAPE, LOCAL_VOLUME_HEADER_TEXELS, LOCAL_VOLUME_MESH_SHAPE, LOCAL_VOLUME_RAMP_TEXELS, LOCAL_VOLUME_TEXELS, MAX_WEBGPU_MESH_VOLUME_TRIANGLES, MESH_VOLUME_STEP_OFFSET_FRACTION, MESH_VOLUME_TRIANGLE_TEXELS, packWebGpuLocalVolumes, packWebGpuMeshVolumes, webGpuVolumeFeatures } from '../src/path-tracer-webgpu-local-volumes.js';
import { decodeVolumeGrid, encodeVolumeGrid, registerVolumeGrid } from '../src/volume-grid.js';
+import { meshVolumeSegments } from '../src/path-tracer-volume.js';
import { renderBlastBothBackends } from './helpers/grid-blast-render.js';
+import { renderMeshVolumeBothBackends } from './helpers/mesh-volume-render.js';
import { traceOnWebGpu } from '../src/path-tracer-webgpu.js';
import { withWebGpuPage } from './helpers/webgpu-page.js';
@@ -66,14 +68,208 @@ test('the march is compiled into the megakernel only for a scene that has local
assert.match(both, /fn scatterInFog\(/);
});
-test('a mesh volume is refused on the WebGPU tracer with the backend that draws it, and a grid volume is not', async () => {
- assert.throws(() => assertWebGpuLocalVolumes({ localVolumes: [{ shape: 'box' }, { shape: 'mesh', part: { name: 'room' } }] }), /localVolumes\[1\] is a mesh volume, which only backend "cpu" traces/);
+// A closed L-shaped prism (three unit squares in x and z, the notch at x and z in 1..2, extruded in y from 0 to 1) and two unit boxes with a gap of two units: the shapes of the mesh volume tests.
+function lPrismMesh() {
+ const outline = [[0, 0], [1, 0], [2, 0], [2, 1], [1, 1], [1, 2], [0, 2], [0, 1]];
+ const positions = [];
+ for (const height of [0, 1]) for (const [x, z] of outline) positions.push(x, height, z);
+ const indices = [];
+ const top = outline.length;
+ for (const [firstCorner, secondCorner, thirdCorner, fourthCorner] of [[0, 1, 4, 7], [1, 2, 3, 4], [7, 4, 5, 6]]) {
+ indices.push(firstCorner, secondCorner, thirdCorner, firstCorner, thirdCorner, fourthCorner, top + firstCorner, top + thirdCorner, top + secondCorner, top + firstCorner, top + fourthCorner, top + thirdCorner);
+ }
+ for (let corner = 0; corner < outline.length; corner++) {
+ const next = (corner + 1) % outline.length;
+ indices.push(corner, next, top + next, corner, top + next, top + corner);
+ }
+ return { positions: new Float32Array(positions), indices: new Uint32Array(indices) };
+}
+
+function dumbbellMesh() {
+ const corners = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1];
+ const faces = [0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 3, 7, 6, 3, 6, 2, 0, 4, 7, 0, 7, 3, 1, 2, 6, 1, 6, 5];
+ const positions = [...corners];
+ for (let index = 0; index < corners.length; index += 3) positions.push(corners[index] + 3, corners[index + 1], corners[index + 2]);
+ return { positions: new Float32Array(positions), indices: new Uint32Array([...faces, ...faces.map(index => index + 8)]) };
+}
+
+const MESH_SMOKE = { shape: 'mesh', part: 'room', fit: 'mesh', density: 1.2, falloff: 0, steps: 24, emission: [0.9, 0.45, 0.15], emissionStrength: 1.5 };
+
+// The trace scene of a hidden part of that shape with a mesh volume over it: its volumes are what the WebGPU tracer receives (the mesh BVH built by buildTraceScene).
+function meshVolumeScene(mesh, matrix = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])) {
+ const room = { name: 'room', visible: false, geometry: { ...mesh, normals: new Float32Array(mesh.positions.length) }, matrix, material: { color: [0.5, 0.5, 0.5] } };
+ return buildTraceScene([floorPart(), room], { localVolumes: [MESH_SMOKE] });
+}
+
+test('a mesh volume is drawn by the WebGPU tracer once its BVH is built, and a part that was never prepared is refused with what to do', () => {
+ const scene = meshVolumeScene(lPrismMesh());
+ assert.doesNotThrow(() => assertWebGpuLocalVolumes(scene));
+ assert.equal(webGpuVolumeFeatures(scene.localVolumes).hasMeshVolume, true);
+ assert.equal(webGpuVolumeFeatures(resolveLocalVolumes([SMOKE_BOX, PUFF], 'volumes')).hasMeshVolume, false);
+ assert.throws(() => assertWebGpuLocalVolumes({ localVolumes: [{ shape: 'box' }, { shape: 'mesh', part: { name: 'room' } }] }), /localVolumes\[1\] is a mesh volume that was not prepared for tracing; build the scene with buildTraceScene/);
assert.doesNotThrow(() => assertWebGpuLocalVolumes({ localVolumes: [{ shape: 'grid', gridData: {} }] }));
assert.doesNotThrow(() => assertWebGpuLocalVolumes({ localVolumes: resolveLocalVolumes([SMOKE_BOX, PUFF], 'volumes') }));
assert.doesNotThrow(() => assertWebGpuLocalVolumes({}));
- const scene = buildTraceScene([floorPart()], { localVolumes: [SMOKE_BOX] });
- scene.localVolumes = [{ ...scene.localVolumes[0], shape: 'mesh', part: { name: 'room' } }];
- await assert.rejects(traceOnWebGpu(scene, {}, { width: 2, height: 2, samples: 1, bounces: 1 }, () => {}), /is a mesh volume, which only backend "cpu" traces/);
+});
+
+test('a mesh volume packs the mesh shape code and its mesh number in its table row, and the header says where the mesh block starts', () => {
+ const scene = meshVolumeScene(lPrismMesh());
+ const table = packWebGpuLocalVolumes(scene.localVolumes, null);
+ const row = LOCAL_VOLUME_HEADER_TEXELS * 4;
+ assert.equal(table[row + 3], LOCAL_VOLUME_MESH_SHAPE);
+ assert.equal(table[row + 19], 0, 'the first mesh volume');
+ assert.equal(table[1], LOCAL_VOLUME_HEADER_TEXELS + LOCAL_VOLUME_TEXELS, 'the block follows the one table row, counted in vectors');
+ assert.deepEqual(rounded(table.subarray(row + 16, row + 19)), [24, 0, 0], 'the steps of the volume, no scatter');
+ const [plainBox] = resolveLocalVolumes([SMOKE_BOX], 'volumes');
+ assert.equal(packWebGpuLocalVolumes([plainBox], null)[1], 0, 'a scene without a mesh volume keeps 0 in the second header float');
+});
+
+// The packed mesh block read the way the WGSL reads it, with a plain loop over the leaves instead of the stack walk: the nearest surface along a ray, or -1.
+function nearestPackedSurface(block, meshNumber, origin, direction) {
+ const descriptor = (1 + meshNumber) * 4;
+ const nodeStart = block[descriptor];
+ const triangleStart = block[descriptor + 1];
+ const nodeCount = block[descriptor + 3];
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+ let nearest = Infinity;
+ for (let node = 0; node < nodeCount; node++) {
+ const header = (nodeStart + node * 2) * 4;
+ const leafCount = -block[header + 3];
+ if (!(leafCount > 0)) continue;
+ const first = block[header + 7];
+ for (let slot = first; slot < first + leafCount; slot++) {
+ const base = (triangleStart + slot * 3) * 4;
+ const corner = [block[base], block[base + 1], block[base + 2]];
+ const edgeFirst = [block[base + 4], block[base + 5], block[base + 6]];
+ const edgeSecond = [block[base + 8], block[base + 9], block[base + 10]];
+ const pivot = cross(direction, edgeSecond);
+ const determinant = dot(edgeFirst, pivot);
+ if (determinant === 0) continue;
+ const offset = origin.map((value, axis) => value - corner[axis]);
+ const firstWeight = dot(offset, pivot) / determinant;
+ if (firstWeight < 0 || firstWeight > 1) continue;
+ const query = cross(offset, edgeFirst);
+ const secondWeight = dot(direction, query) / determinant;
+ if (secondWeight < 0 || firstWeight + secondWeight > 1) continue;
+ const distance = dot(edgeSecond, query) / determinant;
+ if (distance >= 0 && distance < nearest) nearest = distance;
+ }
+ }
+ return nearest === Infinity ? -1 : nearest;
+}
+
+// The inside segments of the packed mesh volume by the crossing walk of meshVolumeSegments in the WGSL.
+function packedSegments(table, origin, direction, limit) {
+ const block = table.subarray(table[1] * 4);
+ const stepOffset = block[6];
+ const crossings = [];
+ let cursor = 0;
+ while (crossings.length < 64) {
+ const distance = nearestPackedSurface(block, 0, origin.map((value, axis) => value + direction[axis] * cursor), direction);
+ if (distance < 0) break;
+ cursor += distance;
+ crossings.push(cursor);
+ cursor += stepOffset;
+ }
+ let inside = crossings.length % 2 === 1;
+ let start = 0;
+ const segments = [];
+ for (const crossing of crossings) {
+ if (inside) {
+ const end = Math.min(crossing, limit);
+ if (end > start) segments.push([start, end]);
+ } else {
+ start = crossing;
+ }
+ inside = !inside;
+ }
+ return segments;
+}
+
+test('the packed mesh block gives the segments the CPU tracer finds: an L arm, the notch, a ray that leaves and comes back, and a ray that starts inside', () => {
+ const cpuSegments = (scene, origin, direction, limit) => {
+ const out = new Float64Array(64);
+ const count = meshVolumeSegments(scene.localVolumes[0], ...origin, ...direction, limit, out);
+ return Array.from({ length: count }, (value, segment) => [out[segment * 2], out[segment * 2 + 1]]);
+ };
+ const close = (actual, expected, label) => {
+ const message = `${label}: ${JSON.stringify(actual)} against ${JSON.stringify(expected)}`;
+ assert.equal(actual.length, expected.length, message);
+ actual.forEach((segment, index) => segment.forEach((value, end) => assert.ok(Math.abs(value - expected[index][end]) < 1e-3, message)));
+ };
+ const lShape = meshVolumeScene(lPrismMesh());
+ const lTable = packWebGpuLocalVolumes(lShape.localVolumes, null);
+ const rays = [
+ ['through the long arm', [-1, 0.37, 0.43], [1, 0, 0], 10],
+ ['through the notch', [-1, 0.37, 1.5], [1, 0, 0], 10],
+ ['down through the corner', [0.5, 5, 0.5], [0, -1, 0], 20],
+ ['starting inside', [0.5, 0.5, 0.5], [1, 0, 0], 10],
+ ['clipped by the limit', [-1, 0.37, 0.43], [1, 0, 0], 2],
+ ['a miss', [-1, 3, 0.43], [1, 0, 0], 10],
+ ];
+ for (const [label, origin, direction, limit] of rays) close(packedSegments(lTable, origin, direction, limit), cpuSegments(lShape, origin, direction, limit), label);
+ assert.equal(cpuSegments(lShape, [-1, 0.37, 1.5], [1, 0, 0], 10).length, 1, 'the notch ray crosses the first arm only');
+ const twoShells = meshVolumeScene(dumbbellMesh());
+ const through = cpuSegments(twoShells, [-1, 0.5, 0.5], [1, 0, 0], 20);
+ assert.equal(through.length, 2, 'the ray leaves the first box and enters the second');
+ close(packedSegments(packWebGpuLocalVolumes(twoShells.localVolumes, null), [-1, 0.5, 0.5], [1, 0, 0], 20), through, 'a ray that leaves and comes back');
+});
+
+test('the mesh block holds the triangles in world space, the BVH nodes of packNodes and a step offset past a crossing', () => {
+ const placed = new Float32Array([2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0, 10, 0, 0, 1]);
+ const scene = meshVolumeScene(dumbbellMesh(), placed);
+ const [volume] = scene.localVolumes;
+ const table = packWebGpuLocalVolumes(scene.localVolumes, null);
+ const block = table.subarray(table[1] * 4);
+ const { bvh, indices, positions } = volume.mesh;
+ assert.equal(block[0], 1, 'one mesh volume');
+ assert.equal(block[7], bvh.nodeCount);
+ assert.ok(Math.abs(block[6] - Math.hypot(...volume.size) * MESH_VOLUME_STEP_OFFSET_FRACTION) < 1e-6, 'a fraction of the volume diagonal');
+ const triangleBase = block[5] * 4;
+ const triangle = bvh.triangleOrder[0];
+ const cornerAt = vertex => Array.from(positions.subarray(indices[triangle * 3 + vertex] * 3, indices[triangle * 3 + vertex] * 3 + 3));
+ assert.deepEqual(rounded(block.subarray(triangleBase, triangleBase + 3)), rounded(cornerAt(0)), 'the first corner of the first leaf slot, in world space');
+ assert.deepEqual(rounded(block.subarray(triangleBase + 4, triangleBase + 7)), rounded(cornerAt(1).map((value, axis) => value - cornerAt(0)[axis])), 'then the edge to the second corner');
+ assert.ok(Math.min(...positions.filter((value, index) => index % 3 === 0)) >= 10, 'the part matrix moved the mesh');
+ assert.equal(block.length, (1 + 1 + bvh.nodeCount * 2 + (indices.length / 3) * MESH_VOLUME_TRIANGLE_TEXELS) * 4, 'header, descriptor, nodes and triangles');
+});
+
+test('the mesh volumes of one scene may hold at most the triangle limit, and the error says what to pass instead', () => {
+ const tooMany = { mesh: { indices: new Uint32Array(3 * (MAX_WEBGPU_MESH_VOLUME_TRIANGLES + 1)) } };
+ assert.throws(() => packWebGpuMeshVolumes([tooMany]), /at most 262144 triangles across mesh local volumes, got 262145; simplify the parts or use backend "cpu"/);
+});
+
+test('the mesh march is compiled only for a scene that has a mesh volume, and any other scene gets the kernel it had before mesh volumes', () => {
+ assert.equal(LOCAL_VOLUME_FUNCTIONS, buildLocalVolumeFunctions({ hasMesh: false }));
+ assert.equal(buildLocalVolumeFunctions({ hasGrid: true, hasNoiseOctaves: true, hasEmissionRamp: true }), buildLocalVolumeFunctions({ hasGrid: true, hasNoiseOctaves: true, hasEmissionRamp: true, hasMesh: false }));
+ const plain = buildMegakernelSource({ hasLocalVolumes: true, hasGridVolume: true, hasNoiseOctaves: true, hasEmissionRamp: true });
+ assert.doesNotMatch(plain, /mesh|Mesh/);
+ assert.match(plain, /if \(!localVolumeInterval\(volume, origin, direction, segmentLength\)\) \{ continue; \}\n entries\[volume\] = localSpan\.x;/);
+ const withMesh = buildMegakernelSource({ hasLocalVolumes: true, hasMeshVolume: true });
+ assert.match(withMesh, /fn meshVolumeSegments\(volume: i32, origin: vec3<f32>, rayDirection: vec3<f32>, limit: f32\) -> i32/);
+ assert.match(withMesh, /fn meshNearestSurface\(/);
+ assert.match(withMesh, /emitted \+= crossLocalMesh\(volume, origin, segmentLength, jitter\);/);
+ assert.match(withMesh, /localSpan = vec2<f32>\(meshSegments\[0\], meshSegments\[segmentCount \* 2 - 1\]\);/);
+ assert.match(withMesh, /let steps = max\(1, i32\(floor\(volumeSteps \* segmentLength \/ total \+ 0\.5\)\)\);/, 'the steps are shared by segment length, rounded half up as Math.round does');
+ assert.match(withMesh, /var inside = \(crossingCount % 2\) == 1;/, 'the origin is inside when the crossings ahead are odd');
+});
+
+test('on a WebGPU adapter a mesh volume over an L-shaped room matches the CPU tracer', { timeout: 300000 }, async context => {
+ await withWebGpuPage(context, async page => {
+ const { cpu, webgpu } = await page.evaluate(renderMeshVolumeBothBackends, { width: 48, height: 30, samples: 32 });
+ let difference = 0;
+ let reference = 0;
+ let lit = 0;
+ cpu.linear.forEach((value, index) => {
+ difference += Math.abs(value - webgpu.linear[index]);
+ reference += value;
+ if (value > 0.05) lit++;
+ });
+ assert.deepEqual(webgpu.ignored, []);
+ assert.ok(lit > 200, `the room shows in the frame: ${lit} lit values`);
+ assert.ok(difference / reference < 0.05, `mean relative difference ${(difference / reference).toFixed(4)}`);
+ }, { hardwareOnly: true });
});
// A 2 x 2 x 1 grid with distinct values per voxel, bound as a volume with the options a test turns on.
@@ -212,8 +408,8 @@ const RAMP_FIRE = { shape: 'box', center: [0, 1, 0], size: [2, 2, 2], density: 1
test('noiseOctaves and emissionRamp no longer throw on the WebGPU tracer', () => {
const volumes = resolveLocalVolumes([OCTAVE_SMOKE, RAMP_FIRE], 'volumes');
assert.doesNotThrow(() => assertWebGpuLocalVolumes({ localVolumes: volumes }));
- assert.deepEqual(webGpuVolumeFeatures(volumes), { hasGridVolume: false, hasNoiseOctaves: true, hasEmissionRamp: true });
- assert.deepEqual(webGpuVolumeFeatures(resolveLocalVolumes([SMOKE_BOX, PUFF], 'volumes')), { hasGridVolume: false, hasNoiseOctaves: false, hasEmissionRamp: false });
+ assert.deepEqual(webGpuVolumeFeatures(volumes), { hasGridVolume: false, hasNoiseOctaves: true, hasEmissionRamp: true, hasMeshVolume: false });
+ assert.deepEqual(webGpuVolumeFeatures(resolveLocalVolumes([SMOKE_BOX, PUFF], 'volumes')), { hasGridVolume: false, hasNoiseOctaves: false, hasEmissionRamp: false, hasMeshVolume: false });
});
test('the table keeps the octaves after the first in vector 5 and the ramp number in vector 7, and a ramp block follows with the stops baked', () => {
diff --git a/tests/volume-grid-motion-shadow.test.js b/tests/volume-grid-motion-shadow.test.js
index a99ac5b8..ebf96163 100644
--- a/tests/volume-grid-motion-shadow.test.js
+++ b/tests/volume-grid-motion-shadow.test.js
@@ -30,5 +30,5 @@ test('the WebGPU tracer accepts a moving grid volume and its grid march reads ea
assert.ok(gridKernel.includes('fn localGridMotionPoint(volume: i32, point: vec3<f32>, timeFraction: f32)'));
assert.ok(gridKernel.includes('localGridSample(volume, localGridMotionPoint(volume, point, timeFraction))'), 'each grid sample moves along the velocity by its shutter time');
assert.doesNotMatch(buildLocalVolumeFunctions(), /localGridMotionPoint/, 'a scene without a grid compiles no grid motion');
- assert.throws(() => assertWebGpuLocalVolumes({ localVolumes: [{ shape: 'mesh', part: { name: 'room' }, motionShutter: 0.5 }] }), /localVolumes\[0\] is a mesh volume, which only backend "cpu" traces/);
+ assert.throws(() => assertWebGpuLocalVolumes({ localVolumes: [{ shape: 'mesh', part: { name: 'room' }, motionShutter: 0.5 }] }), /localVolumes\[0\] is a mesh volume that was not prepared for tracing/);
});