3D engine that AI agents drive
Local volumes: shape "mesh" fills a part (#807)
Nguyen Xuan An301a3c2aba78
diff --git a/changes/807.md b/changes/807.mdnew file mode 100644index 00000000..326a8130--- /dev/null+++ b/changes/807.md@@ -0,0 +1 @@+- `environment.localVolumes` takes `shape: "mesh"` with a `part`: the part's oriented bounds in the rasterizer and the CPU path tracer, or its closed mesh (`fit: "mesh"`) in the CPU path tracer (#807)diff --git a/changes/807.size.md b/changes/807.size.mdnew file mode 100644index 00000000..23cf9c9d--- /dev/null+++ b/changes/807.size.md@@ -0,0 +1,10 @@+- entry:path-tracer: the mesh volume walk for the CPU path tracer: closed-mesh check, a BVH per volume part and the crossing-to-crossing segments, an agent-facing capability of the CPU tracer.+- entry:path-tracer+lazy: the same code, counted with the lazy chunks.+- entry:path-tracer-progressive: the same code, because the progressive tracer builds the same trace scene.+- entry:path-tracer-progressive+lazy: the same code, counted with the lazy chunks.+- entry:path-tracer-realtime: the same code, because the realtime tracer builds the same trace scene.+- entry:light-bake-gpu: the same code, because the GPU bake builds the same trace scene and refuses local volumes after binding them.+- entry:fog-shader: part binding (oriented bounds, part lookup and its errors) and the box orientation in the post shader, so smoke can fill a modelled room without its numbers written twice.+- scene:agent-scene: the recipe check for shape "mesh", part and fit runs in the core where the recipe is validated, an agent-facing capability.+- scene:agent-scene+lazy: the same code plus the part binding in the lazy fog addon.+- goal:agent-scene: the scene is already over its goal; the mesh field checks must run where the recipe is checked, and the gain is an agent-facing capability (lead's trade-off call, 368 bytes gzip).diff --git a/docs/agent-look.md b/docs/agent-look.mdindex acccb9c1..55965618 100644--- a/docs/agent-look.md+++ b/docs/agent-look.md@@ -142,7 +142,7 @@ Sky colors use display RGB, matching the renderer's existing environment contrac| `fogColor` | `[0.35, 0.43, 0.43]` | Components from `0` to `1` || `fogDensity` | `null` | `0` to `10`. `null` fits the density to the scene: `0.006`, or `1.2` divided by the scene diagonal in metres when that is smaller, so a 900 m scene keeps 30 percent of its contrast at the far side. Set `0` for no fog || `volumeFog` | Complete defaults below | One bounded world volume |-| `localVolumes` | Absent | Up to 8 box or sphere volumes that absorb and emit light; see [volume fog](https://67js.codepawl.com/volumetric.md#local-volumes) |+| `localVolumes` | Absent | Up to 8 box, sphere or mesh (a part) volumes that absorb and emit light; see [volume fog](https://67js.codepawl.com/volumetric.md#local-volumes) |Directional key radiance equals `keyColor * keyIntensity`.Zero intensity disables that lighting contribution.diff --git a/docs/volumetric.md b/docs/volumetric.mdindex afc9108e..83519d6d 100644--- a/docs/volumetric.md+++ b/docs/volumetric.md@@ -108,7 +108,7 @@ In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is th## Local volumes-`environment.localVolumes` holds up to 8 boxes or spheres that absorb and emit light: candle haze, a smoke puff, a glowing cloud in one place. They need no `volumeFog` and do not scatter, so a lamp does not light them; they only dim what is behind them and add their own glow. A scene without `localVolumes` draws exactly as before and compiles nothing extra.+`environment.localVolumes` holds up to 8 boxes, spheres or parts that absorb and emit light: candle haze, a smoke puff, a glowing cloud in one place. They need no `volumeFog` and do not scatter, so a lamp does not light them; they only dim what is behind them and add their own glow. A scene without `localVolumes` draws exactly as before and compiles nothing extra.```json{ "environment": { "localVolumes": [@@ -118,8 +118,9 @@ In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is th| Field | Default | Meaning || --- | --- | --- |-| `shape` | `box` | `box` takes `size: [width, height, depth]`, `sphere` takes `radius` |-| `center` | required | World position |+| `shape` | `box` | `box` takes `size: [width, height, depth]`, `sphere` takes `radius`, `mesh` takes `part` |+| `center` | required for `box` and `sphere` | World position |+| `part`, `fit` | required, `bounds` | `mesh` only. `part` names a part of the scene; `fit` is `bounds` or `mesh` (see below) || `density` | `1` | `0` to `100`. Extinction per unit length at the core || `absorption` | `[1, 1, 1]` | Per colour channel share of the density, `0` to `1`. A larger value dims that channel more, so `[0.1, 0.6, 1]` removes blue first and leaves a warm tint || `emission`, `emissionStrength` | `[0, 0, 0]`, `1` | Glow colour and its radiance per unit length at the core, `0` to `1000`. Emission does not depend on `density`, so `density: 0` is a pure glow |@@ -129,6 +130,20 @@ In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is thEach volume is marched on its own between its entry and its exit, cut at the first surface, and the volumes are composited nearest entry first. Overlapping volumes are therefore an approximation. 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. The path tracer traces them on `backend: "cpu"` with the same fields except the noise, and every other tracer entry point (backends `gpu` and `native`, the progressive and realtime tracers, the GPU light bake) throws 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.+### Mesh volumes++`shape: "mesh"` takes its place and size from a part, so smoke can fill a room or a modelled shape without writing its numbers twice.++```json+{ "environment": { "localVolumes": [ { "shape": "mesh", "part": "hall", "fit": "mesh", "density": 1.5, "falloff": 0 } ] } }+```++- `fit: "bounds"` (the default) uses the part's bounding box in its own frame, carried through its matrix: an oriented box, tight for a rotated or scaled part. It draws in the rasterizer and the CPU path tracer, and `falloff` fades its edges as for a box.+- `fit: "mesh"` uses the closed mesh itself. The CPU path tracer walks the ray from crossing to crossing, so an L-shaped room or two separate shells are filled exactly, and a ray that leaves the mesh and returns crosses both pieces. The mesh has no distance field, so `falloff` is ignored (the density is the same everywhere inside). The rasterizer has no mesh pass: it throws an error that names `environment.localVolumes[n].fit` instead of drawing the bounds, so a scene never shows a box where it asked for an L.+- A part that is `visible: false` is not drawn by the rasterizer and is left out of the traced geometry when a mesh volume names it, so a hidden part can shape smoke without becoming a wall.+- The part must be rigid (not skinned) and have volume. A mesh with open edges has no inside: `fit: "mesh"` throws an error with the part name and the number of open edges. A `part` that names nothing throws `environment.localVolumes[n].part "x" names no part in the scene` with the part names.+- The mesh walk follows at most 64 surface crossings per ray (32 segments inside), so the cost stays bounded; the `steps` of the volume are shared between its segments by length.+### Reference render and frame time`node bench/reference/local-volumes.mjs gpu` draws a smoky room (a haze box with noise and a glowing noisy puff, `bench/reference/images/local-volumes.png`) and the same room without volumes (`local-volumes-plain.png`), and times both: 960 x 540, 4x MSAA, median of 200 frames with readback, three rounds with the order alternating. On the RTX 3060 shared with other jobs (2026-11-10) the room without volumes took 1.34, 1.25 and 1.07 ms, and with the two volumes 2.13, 2.11 and 1.54 ms, so the pair costs about 0.5 to 0.9 ms at this size (noisy; treat it as a range).diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 387e6029..e46e6ba4 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -270,7 +270,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({maxSpotLights: MAX_SPOT_LIGHTS, maxAreaLights: MAX_AREA_LIGHTS,localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, tileSize: 512 }),lightLinking: Object.freeze({ fields: Object.freeze(['environment.keyAffects', 'pointLights[].affects', 'spotLights[].affects', 'areaLights[].affects']), unlisted: 'a light without affects lights every node', unknownNode: 'rejected', bake: 'honoured', pathTracer: 'ignored, named in report.ignored' }),- localVolumes: Object.freeze({ field: 'environment.localVolumes', maximum: 8, shapes: Object.freeze(['box', 'sphere']), fields: 'shape, center, size (box) or radius (sphere), density 0-100 (1), falloff 0-1 (0.5), absorption rgb 0-1 (1,1,1), emission rgb 0-1, emissionStrength 0-1000 (1), noiseAmount 0-1 (0), noiseScale (1), steps 4-32 (16)', note: 'Absorb and emit, no scattering; needs hdr and depth like volumeFog; noise is raster only; path tracer: backend cpu only (gpu and native throw).' }),+ localVolumes: Object.freeze({ field: 'environment.localVolumes', maximum: 8, shapes: Object.freeze(['box', 'sphere', 'mesh']), fields: 'shape, center, size (box) or radius (sphere) or part + fit bounds|mesh (mesh: the named part, bounds by default; fit mesh needs a closed part and backend cpu), density 0-100 (1), falloff 0-1 (0.5), absorption rgb 0-1 (1,1,1), emission rgb 0-1, emissionStrength 0-1000 (1), noiseAmount 0-1 (0), noiseScale (1), steps 4-32 (16)', note: 'Absorb and emit, no scattering; needs hdr and depth like volumeFog; noise is raster only; path tracer: backend cpu only (gpu and native throw).' }),shadowCascades: Object.freeze({ field: 'environment.shadowCascades', counts: Object.freeze([0, 1, 2, 3, 4]), zero: 'one shadow map', automatic: 'three cascades when shadow.extent is above 40 and the field is unset', maximumDistance: 150, note: 'volume fog and water read the single map' }),lineArt: Object.freeze({ field: 'environment.lines', fields: 'width px 0.25-16 (1.5), color, boundaries, creaseAngle deg (35), depthJump (0.08), toon steps 0-8, polylines [{points [x,y,z] 2-256, color, width, depthTest, closed}] max 64; {} turns on, null clears; material toon 0-8', note: 'docs/line-art.md' }),viewTransform: Object.freeze({diff --git a/src/fog-shader.js b/src/fog-shader.jsindex c2c76ad2..891e66d3 100644--- a/src/fog-shader.js+++ b/src/fog-shader.js@@ -1,5 +1,6 @@import { registerShaderFeatureCode } from './shader-registry.js';import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes } from './local-volumes.js';+import { bindLocalVolumeParts } from './local-volume-parts.js';import { FogFieldTexture, createFogLightBuffers, packFogLights, volumeShadowAmbient, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD, resolveFogDetail, fogUsesDetail } from './fog-field.js';// The volume fog step of the post pass: its uniforms and the march that scatters light through the fog box. Only a renderer that@@ -77,11 +78,11 @@ function bindFieldAndLights(renderer, post, volume) {// The local volumes of the frame (environment.localVolumes), checked and packed once before the post program is chosen, so a bad// field or a renderer without depth or HDR throws before any program is bound. Returns the count packed, or 0 for an empty list.function prepareLocalVolumes(renderer, input) {- const volumes = resolveLocalVolumes(input, 'environment.localVolumes');- if (volumes.length === 0) return 0;+ const resolved = resolveLocalVolumes(input, 'environment.localVolumes');+ if (resolved.length === 0) return 0;if (!renderer.depth || !renderer.hdr || renderer.transparent || renderer.benchmark) throw new Error('Local volumes require depth:true, active HDR and an opaque canvas');const buffers = (renderer.localVolumeBuffers ??= createLocalVolumeBuffers());- packLocalVolumes(volumes, buffers);+ packLocalVolumes(bindLocalVolumeParts(resolved, renderer.sceneParts, { meshFit: false }), buffers);return buffers.count;}@@ -97,6 +98,7 @@ function bindLocalVolumes(renderer, post, frame) {context.uniform4fv(locate('localVolumeAbsorption[0]'), buffers.absorption);context.uniform4fv(locate('localVolumeEmission[0]'), buffers.emission);context.uniform4fv(locate('localVolumeSteps[0]'), buffers.steps);+ context.uniform4fv(locate('localVolumeAxes[0]'), buffers.axes);}const LOCAL_VOLUME_DECLARATIONS = `@@ -107,11 +109,15 @@ uniform vec4 localVolumeExtents[8];uniform vec4 localVolumeAbsorption[8];uniform vec4 localVolumeEmission[8];uniform vec4 localVolumeSteps[8];+uniform vec4 localVolumeAxes[24];`;// Each volume is marched on its own between its entry and exit (cut at the first surface) and composited nearest first: the colour// behind it is dimmed by exp(-absorption * profile * step) and its emission is added, both per colour channel.const LOCAL_VOLUME_FUNCTIONS = `+vec3 localVolumeLocal(int index, vec3 vector) {+ return vec3(dot(localVolumeAxes[index * 3].xyz, vector), dot(localVolumeAxes[index * 3 + 1].xyz, vector), dot(localVolumeAxes[index * 3 + 2].xyz, vector));+}vec2 localVolumeInterval(int index, vec3 origin, vec3 direction) {vec3 center = localVolumeCenters[index].xyz;vec3 halfSize = localVolumeExtents[index].xyz;@@ -123,15 +129,17 @@ vec2 localVolumeInterval(int index, vec3 origin, vec3 direction) {float root = sqrt(discriminant);return vec2(-along - root, -along + root);}+ vec3 localOrigin = localVolumeLocal(index, origin - center);+ vec3 localDirection = localVolumeLocal(index, direction);float entry = -1e30;float exitDistance = 1e30;for (int axis = 0; axis < 3; axis++) {- float relative = center[axis] - origin[axis];- if (direction[axis] == 0.0) {+ float relative = -localOrigin[axis];+ if (localDirection[axis] == 0.0) {if (abs(relative) > halfSize[axis]) return vec2(0.0);} else {- float first = (relative - halfSize[axis]) / direction[axis];- float second = (relative + halfSize[axis]) / direction[axis];+ float first = (relative - halfSize[axis]) / localDirection[axis];+ float second = (relative + halfSize[axis]) / localDirection[axis];entry = max(entry, min(first, second));exitDistance = min(exitDistance, max(first, second));}@@ -140,6 +148,7 @@ vec2 localVolumeInterval(int index, vec3 origin, vec3 direction) {}float localVolumeProfile(int index, vec3 position) {vec3 offset = position - localVolumeCenters[index].xyz;+ if (localVolumeCenters[index].w < 0.5) offset = localVolumeLocal(index, offset);vec3 halfSize = localVolumeExtents[index].xyz;float distanceRatio = localVolumeCenters[index].w > 0.5 ? length(offset) / halfSize.x : max(max(abs(offset.x) / halfSize.x, abs(offset.y) / halfSize.y), abs(offset.z) / halfSize.z);float falloff = localVolumeExtents[index].w;diff --git a/src/local-volume-parts.js b/src/local-volume-parts.jsnew file mode 100644index 00000000..746e376a--- /dev/null+++ b/src/local-volume-parts.js@@ -0,0 +1,76 @@+// Binds the mesh volumes of environment.localVolumes (shape "mesh") to the parts they name. A volume that fits the bounds of its+// part becomes an oriented box: the part's local bounding box carried through its matrix, so a rotated room is still a tight box.+// A volume that fits the closed mesh keeps the part for the CPU path tracer, which walks the mesh itself+// (path-tracer-volume.js, prepareMeshVolume); the rasterizer has no mesh pass and refuses it with a message that names the field.++const LISTED_PART_NAMES = 12;+const boundsByGeometry = new WeakMap();++function localBounds(geometry) {+ let bounds = boundsByGeometry.get(geometry);+ if (bounds) return bounds;+ const positions = geometry.positions;+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (let index = 0; index < positions.length; index += 3) {+ for (let axis = 0; axis < 3; axis++) {+ minimum[axis] = Math.min(minimum[axis], positions[index + axis]);+ maximum[axis] = Math.max(maximum[axis], positions[index + axis]);+ }+ }+ bounds = { minimum, maximum };+ boundsByGeometry.set(geometry, bounds);+ return bounds;+}++function orientedBounds(part, label) {+ const { minimum, maximum } = localBounds(part.geometry);+ const matrix = part.matrix ?? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];+ const localCenter = minimum.map((low, axis) => (low + maximum[axis]) / 2);+ const center = [0, 1, 2].map(row => matrix[row] * localCenter[0] + matrix[4 + row] * localCenter[1] + matrix[8 + row] * localCenter[2] + matrix[12 + row]);+ const size = [];+ const axes = [];+ for (let column = 0; column < 3; column++) {+ const x = matrix[column * 4];+ const y = matrix[column * 4 + 1];+ const z = matrix[column * 4 + 2];+ const scale = Math.hypot(x, y, z);+ if (!(scale > 0)) throw new RangeError(`${label}.part "${part.name}" has a flat transform; a mesh volume needs a part with volume`);+ size.push((maximum[column] - minimum[column]) * scale);+ axes.push(x / scale, y / scale, z / scale);+ }+ if (!size.every(extent => extent > 0)) throw new RangeError(`${label}.part "${part.name}" has no thickness along one axis; a mesh volume needs a part with volume`);+ return { center, size, axes };+}++function findPart(parts, name, label) {+ const part = parts.find(candidate => candidate.name === name);+ if (part) return part;+ const names = parts.map(candidate => candidate.name).filter(Boolean);+ const listed = names.slice(0, LISTED_PART_NAMES).join(', ');+ throw new RangeError(`${label}.part "${name}" names no part in the scene${listed ? `; parts: ${listed}${names.length > LISTED_PART_NAMES ? ', ...' : ''}` : ''}`);+}++/**+ * Returns the resolved volumes with every mesh volume bound to its part. Pass `meshFit: false` for the rasterizer, which draws+ * the bounds only. Volumes that are not meshes are returned as they are.+ */+export function bindLocalVolumeParts(volumes, parts, { meshFit = true, label = 'environment.localVolumes' } = {}) {+ if (!volumes.some(volume => volume.shape === 'mesh')) return volumes;+ return volumes.map((volume, index) => {+ if (volume.shape !== 'mesh') return volume;+ const field = `${label}[${index}]`;+ const part = findPart(parts, volume.part, field);+ if (!part.geometry?.positions || !part.geometry.indices) throw new TypeError(`${field}.part "${part.name}" has no geometry`);+ if (part.skin) throw new RangeError(`${field}.part "${part.name}" is skinned; a mesh volume needs a rigid part`);+ const bounds = orientedBounds(part, field);+ if (volume.fit === 'mesh') {+ if (!meshFit) throw new RangeError(`${field}.fit "mesh" is traced by the CPU path tracer only; the rasterizer draws the part's bounds. Use fit "bounds" or the path tracer with backend "cpu".`);+ return { ...volume, ...bounds, part };+ }+ const rest = { ...volume };+ delete rest.part;+ delete rest.fit;+ return { ...rest, shape: 'box', ...bounds };+ });+}diff --git a/src/local-volumes.js b/src/local-volumes.jsindex ddf9cb6e..ff09be36 100644--- a/src/local-volumes.js+++ b/src/local-volumes.js@@ -1,12 +1,13 @@import { finiteRange } from './volumetric.js';-// Local volumes: up to MAX_LOCAL_VOLUMES boxes or spheres that absorb and emit light, for candle haze, smoke puffs and glowing+// Local volumes: up to MAX_LOCAL_VOLUMES boxes, spheres or parts (shape "mesh") that absorb and emit light, for candle haze, smoke puffs and glowing// fog in one place. They sit beside environment.volumeFog (the one scattering volume) and need no fog. The post pass marches// each one separately and composites them from the nearest entry to the farthest, so overlapping volumes are an approximation.export const MAX_LOCAL_VOLUMES = 8;-export const LOCAL_VOLUME_SHAPES = Object.freeze(['box', 'sphere']);-export const LOCAL_VOLUME_FIELDS = Object.freeze(['shape', 'center', 'size', 'radius', 'density', 'falloff', 'absorption', 'emission', 'emissionStrength', 'noiseAmount', 'noiseScale', 'steps']);+export const LOCAL_VOLUME_SHAPES = Object.freeze(['box', 'sphere', 'mesh']);+export const LOCAL_VOLUME_FIT = Object.freeze(['bounds', 'mesh']);+export const LOCAL_VOLUME_FIELDS = Object.freeze(['shape', 'part', 'fit', 'center', 'size', 'radius', 'density', 'falloff', 'absorption', 'emission', 'emissionStrength', 'noiseAmount', 'noiseScale', 'steps']);export const LOCAL_VOLUME_MAXIMUM_STEPS = 32;function vectorField(value, minimum, maximum, label) {@@ -23,7 +24,7 @@ function resolveLocalVolume(input, label) {if (!LOCAL_VOLUME_SHAPES.includes(shape)) throw new RangeError(`${label}.shape must be one of ${LOCAL_VOLUME_SHAPES.join(', ')}`);const resolved = {shape,- center: vectorField(input.center, -1e5, 1e5, `${label}.center`),+ ...(shape === 'mesh' ? {} : { center: vectorField(input.center, -1e5, 1e5, `${label}.center`) }),density: finiteRange(input.density ?? 1, 0, 100, `${label}.density`),falloff: finiteRange(input.falloff ?? 0.5, 0, 1, `${label}.falloff`),absorption: vectorField(input.absorption ?? [1, 1, 1], 0, 1, `${label}.absorption`),@@ -34,6 +35,17 @@ function resolveLocalVolume(input, label) {steps: finiteRange(input.steps ?? 16, 4, LOCAL_VOLUME_MAXIMUM_STEPS, `${label}.steps`),};if (!Number.isInteger(resolved.steps)) throw new RangeError(`${label}.steps must be an integer`);+ if (shape === 'mesh') {+ if (typeof input.part !== 'string' || input.part === '') throw new TypeError(`${label}.part must be the name of the part that bounds the volume`);+ for (const field of ['center', 'size', 'radius']) {+ if (input[field] !== undefined) throw new TypeError(`${label}.${field} belongs to a box or a sphere; a mesh volume takes its place and size from the part named in ${label}.part`);+ }+ resolved.part = input.part;+ resolved.fit = input.fit ?? 'bounds';+ if (!LOCAL_VOLUME_FIT.includes(resolved.fit)) throw new RangeError(`${label}.fit must be one of ${LOCAL_VOLUME_FIT.join(', ')}`);+ return resolved;+ }+ if (input.part !== undefined || input.fit !== undefined) throw new TypeError(`${label}.part and ${label}.fit belong to shape "mesh"`);if (shape === 'sphere') {if (input.size !== undefined) throw new TypeError(`${label}.size belongs to a box; a sphere takes radius`);resolved.radius = finiteRange(input.radius, 0.001, 1e4, `${label}.radius`);@@ -54,10 +66,13 @@ export function resolveLocalVolumes(input, label = 'localVolumes') {/** The uniform arrays the post shader reads, one vec4 per volume. Pass resolved volumes. */export function createLocalVolumeBuffers() {const size = MAX_LOCAL_VOLUMES * 4;- return { count: 0, centers: new Float32Array(size), extents: new Float32Array(size), absorption: new Float32Array(size), emission: new Float32Array(size), steps: new Float32Array(size) };+ return { count: 0, centers: new Float32Array(size), extents: new Float32Array(size), absorption: new Float32Array(size), emission: new Float32Array(size), steps: new Float32Array(size), axes: new Float32Array(size * 3) };}+const IDENTITY_AXES = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);+export function packLocalVolumes(volumes, buffers) {+ if (volumes.some(volume => volume.shape === 'mesh')) throw new RangeError('A mesh volume names a part: bind it with bindLocalVolumeParts before packing');buffers.count = volumes.length;volumes.forEach((volume, index) => {const at = index * 4;@@ -67,15 +82,26 @@ export function packLocalVolumes(volumes, buffers) {buffers.absorption.set([...volume.absorption.map(channel => channel * volume.density), volume.noiseAmount], at);buffers.emission.set([...volume.emission.map(channel => channel * volume.emissionStrength), volume.noiseScale], at);buffers.steps.set([volume.steps, 0, 0, 0], at);+ const axes = volume.axes ?? IDENTITY_AXES;+ for (let axis = 0; axis < 3; axis++) buffers.axes.set([axes[axis * 3], axes[axis * 3 + 1], axes[axis * 3 + 2], 0], (index * 3 + axis) * 4);});return buffers;}/** The density factor of a volume at a point, 0 to 1, without noise: 1 at the core, fading over the outer `falloff` share. */export function localVolumeProfile(volume, x, y, z) {- const offsetX = x - volume.center[0];- const offsetY = y - volume.center[1];- const offsetZ = z - volume.center[2];+ if (volume.shape === 'mesh') return 1;+ let offsetX = x - volume.center[0];+ let offsetY = y - volume.center[1];+ let offsetZ = z - volume.center[2];+ if (volume.axes) {+ const axes = volume.axes;+ const alongX = axes[0] * offsetX + axes[1] * offsetY + axes[2] * offsetZ;+ const alongY = axes[3] * offsetX + axes[4] * offsetY + axes[5] * offsetZ;+ offsetZ = axes[6] * offsetX + axes[7] * offsetY + axes[8] * offsetZ;+ offsetX = alongX;+ offsetY = alongY;+ }const distance = volume.shape === 'sphere'? Math.hypot(offsetX, offsetY, offsetZ) / volume.radius: Math.max(Math.abs(offsetX) / (volume.size[0] / 2), Math.abs(offsetY) / (volume.size[1] / 2), Math.abs(offsetZ) / (volume.size[2] / 2));@@ -100,10 +126,19 @@ export function localVolumeInterval(volume, originX, originY, originZ, directionentry = Math.max(entry, -along - root);exit = Math.min(exit, -along + root);} else {+ const axes = volume.axes;+ const offsetX = originX - volume.center[0];+ const offsetY = originY - volume.center[1];+ const offsetZ = originZ - volume.center[2];for (let axis = 0; axis < 3; axis++) {const origin = axis === 0 ? originX : axis === 1 ? originY : originZ;- const direction = axis === 0 ? directionX : axis === 1 ? directionY : directionZ;- const relative = volume.center[axis] - origin;+ let direction = axis === 0 ? directionX : axis === 1 ? directionY : directionZ;+ let relative = volume.center[axis] - origin;+ if (axes) {+ const at = axis * 3;+ relative = -(axes[at] * offsetX + axes[at + 1] * offsetY + axes[at + 2] * offsetZ);+ direction = axes[at] * directionX + axes[at + 1] * directionY + axes[at + 2] * directionZ;+ }const halfSize = volume.size[axis] / 2;if (direction === 0) {if (Math.abs(relative) > halfSize) return false;diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.jsindex 0ee62c88..edad602a 100644--- a/src/path-tracer-scene.js+++ b/src/path-tracer-scene.js@@ -2,8 +2,9 @@ import { buildTriangleBvh } from './triangle-bvh.js';import { createTracer } from './ray-query.js';import { SUN_BIT, POINT_FIRST_BIT, SPOT_FIRST_BIT, AREA_FIRST_BIT } from './light-link-bits.js';import { boxProjectedGeometry, columnLengths } from './export-box-uv.js';-import { resolveTraceVolume } from './path-tracer-volume.js';+import { resolveTraceVolume, prepareMeshVolume } from './path-tracer-volume.js';import { resolveLocalVolumes } from './local-volumes.js';+import { bindLocalVolumeParts } from './local-volume-parts.js';import { resolveTraceSubsurface } from './path-tracer-subsurface.js';import { lightShapeSupport } from './shader-registry.js';import { flushOrderOf } from './depth-layer.js';@@ -310,7 +311,19 @@ export function refuseLocalVolumes(scene, tracerName) {throw new RangeError(`environment.localVolumes is traced by the CPU path tracer only; ${tracerName} cannot draw them. Use backend "cpu" or remove the volumes.`);}-export function buildTraceScene(parts, environment = {}) {+// The volumes of the trace, and the hidden parts that only bound a mesh volume: the rasterizer does not draw a part with+// `visible: false`, and the trace leaves it out of the geometry too, so a part can shape smoke without becoming a wall.+function resolveTraceLocalVolumes(input, parts) {+ if (!input?.length) return { volumes: null, boundsOnlyParts: [] };+ const resolved = resolveLocalVolumes(input, 'environment.localVolumes');+ const meshPartNames = new Set(resolved.filter(volume => volume.shape === 'mesh').map(volume => volume.part));+ const volumes = bindLocalVolumeParts(resolved, parts).map((volume, index) => (volume.part ? prepareMeshVolume(volume, `environment.localVolumes[${index}]`) : volume));+ return { volumes, boundsOnlyParts: parts.filter(part => meshPartNames.has(part.name) && part.visible === false) };+}++export function buildTraceScene(allParts, environment = {}) {+ const { volumes: localVolumes, boundsOnlyParts } = resolveTraceLocalVolumes(environment.localVolumes, allParts);+ const parts = boundsOnlyParts.length ? allParts.filter(part => !boundsOnlyParts.includes(part)) : allParts;if (!Array.isArray(parts) || parts.length < 1 || parts.length > MAX_TRACE_PARTS) throw new RangeError(`A path trace takes 1 to ${MAX_TRACE_PARTS} parts.`);const geometry = flattenParts(parts);const bvh = buildTriangleBvh(geometry.positions, geometry.indices);@@ -323,7 +336,7 @@ export function buildTraceScene(parts, environment = {}) {lights: resolveLights(environment),environment: resolveEnvironment(environment.map),volume: resolveTraceVolume(environment.volumeFog),- localVolumes: environment.localVolumes?.length ? resolveLocalVolumes(environment.localVolumes, 'environment.localVolumes') : null,+ localVolumes,surfaceOffset: extent * 1e-5,farDistance: extent * 1e4,});diff --git a/src/path-tracer-volume.js b/src/path-tracer-volume.jsindex 5184119c..8b005445 100644--- a/src/path-tracer-volume.js+++ b/src/path-tracer-volume.js@@ -1,5 +1,7 @@import { resolveVolumeFog } from './volumetric.js';import { localVolumeInterval, localVolumeProfile } from './local-volumes.js';+import { buildTriangleBvh } from './triangle-bvh.js';+import { createTracer } from './ray-query.js';// Homogeneous fog for the path tracer: a box of uniform scattering medium with the colour, density and anisotropy of the// rasterizer's `environment.volumeFog`. Distances to the next scattering event are drawn from the exact free-flight@@ -63,6 +65,119 @@ export function sampleHenyeyGreensteinCosine(anisotropy, unit) {return Math.max(-1, Math.min(1, (1 + squared - ratio * ratio) / (2 * anisotropy)));}+const MAXIMUM_MESH_CROSSINGS = 64;+const MAXIMUM_MESH_SEGMENTS = MAXIMUM_MESH_CROSSINGS / 2;+const IDENTITY_MATRIX = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];++function weldedVertexIds(positions, tolerance) {+ const ids = new Map();+ const welded = new Uint32Array(positions.length / 3);+ for (let vertex = 0; vertex < welded.length; vertex++) {+ const key = `${Math.round(positions[vertex * 3] / tolerance)},${Math.round(positions[vertex * 3 + 1] / tolerance)},${Math.round(positions[vertex * 3 + 2] / tolerance)}`;+ if (!ids.has(key)) ids.set(key, ids.size);+ welded[vertex] = ids.get(key);+ }+ return welded;+}++/** The number of edges that do not join exactly two triangles, with vertices at the same place counted as one. 0 for a closed mesh. */+export function countOpenEdges(positions, indices, tolerance) {+ const welded = weldedVertexIds(positions, tolerance);+ const uses = new Map();+ for (let corner = 0; corner < indices.length; corner += 3) {+ for (let edge = 0; edge < 3; edge++) {+ const from = welded[indices[corner + edge]];+ const to = welded[indices[corner + (edge + 1) % 3]];+ if (from === to) continue;+ const key = from < to ? `${from}-${to}` : `${to}-${from}`;+ uses.set(key, (uses.get(key) ?? 0) + 1);+ }+ }+ let open = 0;+ for (const count of uses.values()) {+ if (count !== 2) open++;+ }+ return open;+}++/**+ * Gives a mesh volume (shape "mesh", bound to its part by bindLocalVolumeParts) what the tracer needs: the part's triangles in+ * world space with their own BVH. A mesh that is not closed has no inside, so it throws with the number of open edges.+ */+export function prepareMeshVolume(volume, label) {+ const { geometry, matrix = IDENTITY_MATRIX } = volume.part;+ const source = geometry.positions;+ const positions = new Float32Array(source.length);+ for (let vertex = 0; vertex < source.length; vertex += 3) {+ const x = source[vertex];+ const y = source[vertex + 1];+ const z = source[vertex + 2];+ positions[vertex] = matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12];+ positions[vertex + 1] = matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13];+ positions[vertex + 2] = matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14];+ }+ const diagonal = Math.hypot(...volume.size);+ 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 } };+}++/**+ * Where a ray is inside a closed mesh volume: writes `[entry, exit]` pairs into `out`, clipped to `[0, limit]`, and returns how+ * many. The ray is walked from crossing to crossing, so an L-shaped room gives two segments where a ray leaves and comes back.+ * Whether the origin is inside follows from the parity of the crossings ahead of it.+ */+export function meshVolumeSegments(volume, originX, originY, originZ, directionX, directionY, directionZ, limit, out) {+ const { tracer, stepOffset } = volume.mesh;+ const crossings = [];+ let cursor = 0;+ while (crossings.length < MAXIMUM_MESH_CROSSINGS) {+ const found = tracer.trace(originX + directionX * cursor, originY + directionY * cursor, originZ + directionZ * cursor, directionX, directionY, directionZ, Infinity, false);+ if (found.nearestTriangle < 0) break;+ cursor += found.nearestDistance;+ crossings.push(cursor);+ cursor += stepOffset;+ }+ let inside = crossings.length % 2 === 1;+ let start = 0;+ let count = 0;+ for (const crossing of crossings) {+ if (inside) {+ const end = Math.min(crossing, limit);+ if (end > start && count < MAXIMUM_MESH_SEGMENTS) {+ out[count * 2] = start;+ out[count * 2 + 1] = end;+ count++;+ }+ } else {+ start = crossing;+ }+ inside = !inside;+ }+ return count;+}++/** Marches the inside segments of a mesh volume; `volume.steps` are shared between them in proportion to their length. */+function marchMeshVolume(volume, spans, originX, originY, originZ, directionX, directionY, directionZ, jitter, throughput, emitted) {+ let total = 0;+ for (let slot = 0; slot < spans.length; slot += 2) total += spans[slot + 1] - spans[slot];+ for (let slot = 0; slot < spans.length; slot += 2) {+ const entry = spans[slot];+ const segmentLength = spans[slot + 1] - entry;+ const steps = Math.max(1, Math.round(volume.steps * segmentLength / total));+ const stepLength = segmentLength / steps;+ for (let step = 0; step < steps; step++) {+ const distance = entry + (step + jitter) * stepLength;+ const width = localVolumeProfile(volume, originX + directionX * distance, originY + directionY * distance, originZ + directionZ * distance) * stepLength;+ for (let channel = 0; channel < 3; channel++) {+ emitted[channel] += throughput[channel] * volume.emission[channel] * volume.emissionStrength * width;+ throughput[channel] *= Math.exp(-volume.absorption[channel] * volume.density * width);+ }+ }+ }+}+/*** Builds the function that carries a ray through the scene's local volumes (environment.localVolumes). Each volume is marched with* its own step count between its entry and exit, nearest entry first: the emitted light is added in proportion to the throughput@@ -75,13 +190,21 @@ export function createLocalVolumeCrossing(volumes) {const exits = new Float64Array(volumes.length);const order = new Int32Array(volumes.length);const span = new Float64Array(2);+ const meshScratch = new Float64Array(MAXIMUM_MESH_SEGMENTS * 2);+ const meshSpans = new Array(volumes.length);return function crossLocalVolumes(originX, originY, originZ, directionX, directionY, directionZ, length, jitter, throughput, emitted) {emitted[0] = 0;emitted[1] = 0;emitted[2] = 0;let count = 0;for (let index = 0; index < volumes.length; index++) {- if (!localVolumeInterval(volumes[index], originX, originY, originZ, directionX, directionY, directionZ, length, span)) continue;+ if (volumes[index].mesh) {+ const segmentCount = meshVolumeSegments(volumes[index], originX, originY, originZ, directionX, directionY, directionZ, length, meshScratch);+ if (segmentCount === 0) continue;+ meshSpans[index] = meshScratch.slice(0, segmentCount * 2);+ span[0] = meshScratch[0];+ span[1] = meshScratch[segmentCount * 2 - 1];+ } else if (!localVolumeInterval(volumes[index], originX, originY, originZ, directionX, directionY, directionZ, length, span)) continue;entries[index] = span[0];exits[index] = span[1];let slot = count++;@@ -93,6 +216,10 @@ export function createLocalVolumeCrossing(volumes) {}for (let rank = 0; rank < count; rank++) {const volume = volumes[order[rank]];+ if (volume.mesh) {+ marchMeshVolume(volume, meshSpans[order[rank]], originX, originY, originZ, directionX, directionY, directionZ, jitter, throughput, emitted);+ continue;+ }const entry = entries[order[rank]];const stepLength = (exits[order[rank]] - entry) / volume.steps;for (let step = 0; step < volume.steps; step++) {diff --git a/tests/local-volume-parts-raster.test.js b/tests/local-volume-parts-raster.test.jsnew file mode 100644index 00000000..7cf9113a--- /dev/null+++ b/tests/local-volume-parts-raster.test.js@@ -0,0 +1,101 @@+// Mesh volumes in the rasterizer post pass (issue 807): the bounds of a part, carried through its matrix, draw as an oriented box.+// Draws in headless Chrome (SwiftShader, no GPU) from the Vite dev server and skips when Chrome cannot start.+import test from 'node:test';+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { freePort } from './helpers/free-port.js';++async function startServer(port) {+ const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });+ await new Promise((resolve, reject) => {+ const timeout = setTimeout(() => reject(new Error('The dev server did not start.')), 30000);+ server.stdout.on('data', (data) => {+ if (/ready in/.test(data.toString())) {+ clearTimeout(timeout);+ resolve();+ }+ });+ server.on('exit', (code) => {+ clearTimeout(timeout);+ reject(new Error(`The dev server exited ${code}.`));+ });+ });+ return server;+}++// A grey wall at z = 0 seen from z = 5, and a hidden unit-box part "room" turned a quarter about y: its local x lies along -z+// (scale 1), local y along y (scale 2) and local z along +x (scale 3), centred on (0, 0, 2), so it fills x -1.5..1.5, y -1..1, z 1.5..2.5.+async function drawInChrome(page, scenarios) {+ const task = async (list) => {+ const { box } = await import('/src/geometry.js');+ const { Renderer67 } = await import('/src/renderer.js');+ await import('/src/fog-shader.js');+ const canvas = document.createElement('canvas');+ canvas.width = 64;+ canvas.height = 64;+ document.body.append(canvas);+ const copy = document.createElement('canvas');+ copy.width = 64;+ copy.height = 64;+ const copyContext = copy.getContext('2d', { willReadFrequently: true });+ const material = { tag: 'unlit', color: [0.4, 0.4, 0.4], metallic: 0, roughness: 1, emission: 0 };+ const wall = { name: 'wall', geometry: box(0, 1), matrix: new Float32Array([12, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0.2, 0, 0, 0, -0.1, 1]), material };+ const room = { name: 'room', visible: false, geometry: box(0, 1), matrix: new Float32Array([0, 0, -1, 0, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 2, 1]), material };+ const results = [];+ for (const localVolumes of list) {+ const renderer = new Renderer67(canvas, [wall, room], { hdr: true, depth: true, samples: 1, pixelRatio: 1, ground: false });+ const environment = { keyIntensity: 0, fillIntensity: 0, ambientIntensity: 0, localVolumes };+ let message = null;+ try {+ renderer.render({ eye: [0, 0, 5], target: [0, 0, 0], fov: 40, time: 0, environment });+ } catch (error) {+ message = error.message;+ }+ copyContext.drawImage(canvas, 0, 0, 64, 64);+ results.push({ message, pixels: Array.from(copyContext.getImageData(0, 0, 64, 64).data), glError: renderer.context.getError() });+ renderer.dispose?.();+ }+ return results;+ };+ return page.evaluate(task, scenarios);+}++test('the rasterizer draws a mesh volume as the oriented bounds of its part and refuses a mesh fit', async (context) => {+ let chromium;+ try {+ ({ chromium } = await import('playwright'));+ } catch {+ context.skip('playwright is not installed');+ return;+ }+ const port = await freePort();+ const server = await startServer(port);+ let browser;+ try {+ try {+ browser = await chromium.launch({ headless: true, args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'] });+ } catch (error) {+ context.skip(`Chrome did not start: ${error.message.split('\n')[0]}`);+ return;+ }+ const page = await browser.newPage({ viewport: { width: 64, height: 64 } });+ await page.goto(`http://127.0.0.1:${port}/`);+ const smoke = { density: 2, falloff: 0, steps: 24 };+ const [plain, byPart, byBox, wrongFit, unknown] = await drawInChrome(page, [+ [],+ [{ shape: 'mesh', part: 'room', ...smoke }],+ [{ shape: 'box', center: [0, 0, 2], size: [3, 2, 1], ...smoke }],+ [{ shape: 'mesh', part: 'room', fit: 'mesh' }],+ [{ shape: 'mesh', part: 'hall' }],+ ]);+ assert.equal(byPart.message, null);+ assert.equal(byPart.glError, 0);+ assert.notDeepEqual(byPart.pixels, plain.pixels, 'the part fills a volume that dims the wall');+ assert.deepEqual(byPart.pixels, byBox.pixels, 'the oriented bounds of the turned part draw as the box they equal');+ assert.match(wrongFit.message, /environment\.localVolumes\[0\]\.fit "mesh" is traced by the CPU path tracer only/);+ assert.match(unknown.message, /environment\.localVolumes\[0\]\.part "hall" names no part in the scene; parts: wall, room/);+ } finally {+ await browser?.close();+ server.kill();+ }+});diff --git a/tests/local-volume-parts.test.js b/tests/local-volume-parts.test.jsnew file mode 100644index 00000000..807d0d59--- /dev/null+++ b/tests/local-volume-parts.test.js@@ -0,0 +1,194 @@+// Mesh volumes (issue 807): environment.localVolumes entries with shape "mesh" take their place and size from a part.+// Bounds fit becomes an oriented box for the rasterizer and the tracer; mesh fit walks the closed mesh in the CPU tracer.+import test from 'node:test';+import assert from 'node:assert/strict';+import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes, localVolumeInterval } from '../src/local-volumes.js';+import { bindLocalVolumeParts } from '../src/local-volume-parts.js';+import { createLocalVolumeCrossing, prepareMeshVolume, countOpenEdges } from '../src/path-tracer-volume.js';+import { renderPathTracedImage } from '../src/path-tracer.js';+import { normalizeAgentLook } from '../src/agent-look.js';++const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];++// A closed box from (0,0,0) to (1,1,1), eight shared corners and twelve triangles.+function unitBox() {+ const positions = new Float32Array([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 indices = new Uint32Array([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]);+ return { positions, indices };+}++// An L-shaped prism: 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.+function lPrism() {+ 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 [a, b, c, d] of [[0, 1, 4, 7], [1, 2, 3, 4], [7, 4, 5, 6]]) {+ indices.push(a, b, c, a, c, d, top + a, top + c, top + b, top + a, top + d, top + c);+ }+ 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) };+}++// Two unit boxes with a gap of two units between them, as one closed mesh in two shells.+function dumbbell() {+ const box = unitBox();+ const positions = new Float32Array(48);+ positions.set(box.positions);+ for (let index = 0; index < box.positions.length; index += 3) {+ positions[24 + index] = box.positions[index] + 3;+ positions[24 + index + 1] = box.positions[index + 1];+ positions[24 + index + 2] = box.positions[index + 2];+ }+ const indices = new Uint32Array(72);+ indices.set(box.indices);+ for (let index = 0; index < box.indices.length; index++) indices[36 + index] = box.indices[index] + 8;+ return { positions, indices };+}++function part(name, mesh, matrix = IDENTITY, extra = {}) {+ return { name, geometry: { ...mesh, normals: new Float32Array(mesh.positions.length) }, matrix, ...extra };+}++const SMOKE = { density: 1, falloff: 0, steps: 8 };++function transmittanceAlong(volumes, origin, direction, length) {+ const crossing = createLocalVolumeCrossing(volumes);+ const throughput = new Float64Array([1, 1, 1]);+ crossing(...origin, ...direction, length, 0.5, throughput, new Float64Array(3));+ return throughput[0];+}++function closedVolume(mesh, volumeFields = {}, matrix = IDENTITY) {+ const [resolved] = resolveLocalVolumes([{ shape: 'mesh', part: 'room', fit: 'mesh', ...SMOKE, ...volumeFields }]);+ const [bound] = bindLocalVolumeParts([resolved], [part('room', mesh, matrix)]);+ return prepareMeshVolume(bound, 'environment.localVolumes[0]');+}++test('a mesh volume resolves to a part and refuses the fields of a box or a sphere, naming the field', () => {+ const [volume] = resolveLocalVolumes([{ shape: 'mesh', part: 'room' }]);+ assert.equal(volume.part, 'room');+ assert.equal(volume.fit, 'bounds');+ assert.equal('center' in volume, false);+ assert.throws(() => resolveLocalVolumes([{ shape: 'mesh' }]), /localVolumes\[0\]\.part must be the name of the part/);+ assert.throws(() => resolveLocalVolumes([{ shape: 'mesh', part: 'room', size: [1, 1, 1] }]), /localVolumes\[0\]\.size belongs to a box or a sphere/);+ assert.throws(() => resolveLocalVolumes([{ shape: 'mesh', part: 'room', fit: 'hull' }]), /localVolumes\[0\]\.fit must be one of bounds, mesh/);+ assert.throws(() => resolveLocalVolumes([{ center: [0, 0, 0], size: [1, 1, 1], part: 'room' }]), /localVolumes\[0\]\.part and localVolumes\[0\]\.fit belong to shape "mesh"/);+ assert.equal(normalizeAgentLook({ environment: { localVolumes: [{ shape: 'mesh', part: 'room' }] } }).environment.localVolumes[0].part, 'room');+});++test('a part reference that names no part throws with the field and the part names', () => {+ const [volume] = resolveLocalVolumes([{ shape: 'mesh', part: 'hall' }]);+ assert.throws(() => bindLocalVolumeParts([volume], [part('room', unitBox()), part('floor', unitBox())]), /environment\.localVolumes\[0\]\.part "hall" names no part in the scene; parts: room, floor/);+ assert.throws(() => bindLocalVolumeParts([{ ...volume, part: 'room' }], [part('room', unitBox(), IDENTITY, { skin: {} })]), /localVolumes\[0\]\.part "room" is skinned/);+ assert.throws(() => bindLocalVolumeParts([{ ...volume, part: 'room' }], [part('room', unitBox(), [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])]), /has a flat transform/);+});++test('the bounds of a rotated, scaled part become an oriented box that the interval and the packing carry', () => {+ const quarterTurn = [0, 0, -2, 0, 0, 3, 0, 0, 1, 0, 0, 0, 10, 0, 0, 1];+ const [volume] = resolveLocalVolumes([{ shape: 'mesh', part: 'room', falloff: 0 }]);+ const [box] = bindLocalVolumeParts([volume], [part('room', unitBox(), quarterTurn)]);+ assert.equal(box.shape, 'box');+ assert.deepEqual(box.size.map(extent => Math.round(extent * 1e6) / 1e6), [2, 3, 1]);+ assert.deepEqual(box.center.map(value => Math.round(value * 1e6) / 1e6), [10.5, 1.5, -1]);+ const span = new Float64Array(2);+ assert.equal(localVolumeInterval(box, 10.5, 1.5, -5, 0, 0, 1, 100, span), true, 'the long axis lies along z after the turn');+ assert.deepEqual(Array.from(span).map(value => Math.round(value * 1e6) / 1e6), [3, 5]);+ assert.equal(localVolumeInterval(box, 10.5, 1.5, -5, 1, 0, 0, 100, span), false);+ const buffers = packLocalVolumes([box], createLocalVolumeBuffers());+ assert.deepEqual(Array.from(buffers.axes.slice(0, 12)).map(value => Math.round(value)), [0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 0]);+ assert.throws(() => packLocalVolumes([volume], createLocalVolumeBuffers()), /bindLocalVolumeParts/);+});++test('the rasterizer draws bounds only: a fit "mesh" volume throws a message that names the field', () => {+ const [volume] = resolveLocalVolumes([{ shape: 'mesh', part: 'room', fit: 'mesh' }]);+ assert.throws(() => bindLocalVolumeParts([volume], [part('room', unitBox())], { meshFit: false }), /environment\.localVolumes\[0\]\.fit "mesh" is traced by the CPU path tracer only/);+});++test('an open mesh has no inside: it throws with the open edge count, and a closed one reports none', () => {+ const closed = lPrism();+ assert.equal(countOpenEdges(closed.positions, closed.indices, 1e-6), 0);+ assert.equal(countOpenEdges(unitBox().positions, unitBox().indices, 1e-6), 0);+ const open = { positions: closed.positions, indices: closed.indices.slice(0, closed.indices.length - 6) };+ assert.throws(() => closedVolume(open), /environment\.localVolumes\[0\]\.part "room" is not a closed mesh \(\d+ open edges\)/);+});++test('the transmittance through an L-shaped closed mesh is exp(-density * length inside), against the analytic length', () => {+ const volume = closedVolume(lPrism(), { density: 0.7 });+ const alongArm = transmittanceAlong([volume], [-1, 0.37, 0.43], [1, 0, 0], 10);+ assert.ok(Math.abs(alongArm - Math.exp(-0.7 * 2)) < 1e-9, `through the long arm ${alongArm}`);+ const throughShortArm = transmittanceAlong([volume], [-1, 0.37, 1.43], [1, 0, 0], 10);+ assert.ok(Math.abs(throughShortArm - Math.exp(-0.7 * 1)) < 1e-9, `through the short arm ${throughShortArm}`);+ const pastNotch = transmittanceAlong([volume], [1.43, 0.37, 3], [0, 0, -1], 10);+ assert.ok(Math.abs(pastNotch - Math.exp(-0.7 * 1)) < 1e-9, `from the notch side ${pastNotch}`);+ const thread = transmittanceAlong([volume], [1.61, 0.37, 1.71], [0, 0, 1], 10);+ assert.equal(thread, 1, 'a ray through the notch crosses no smoke');+ const upward = transmittanceAlong([volume], [0.31, -2, 1.47], [0, 1, 0], 10);+ assert.ok(Math.abs(upward - Math.exp(-0.7 * 1)) < 1e-9, `through the height ${upward}`);+});++test('a ray that leaves a closed mesh and comes back crosses both pieces, starts inside, and stops at its limit', () => {+ const volume = closedVolume(dumbbell(), { density: 1 });+ const both = transmittanceAlong([volume], [-1, 0.37, 0.43], [1, 0, 0], 20);+ assert.ok(Math.abs(both - Math.exp(-2)) < 1e-9, `two shells ${both}`);+ const fromInside = transmittanceAlong([volume], [0.5, 0.37, 0.43], [1, 0, 0], 20);+ assert.ok(Math.abs(fromInside - Math.exp(-1.5)) < 1e-9, `starting inside ${fromInside}`);+ const cut = transmittanceAlong([volume], [-1, 0.37, 0.43], [1, 0, 0], 1.5);+ assert.ok(Math.abs(cut - Math.exp(-0.5)) < 1e-9, `cut by a surface ${cut}`);+});++test('mesh volumes are deterministic: the same ray and jitter give the same bits', () => {+ const volume = closedVolume(lPrism(), { density: 0.9, emission: [1, 0.5, 0.2], emissionStrength: 2, falloff: 0.5 });+ const run = () => {+ const throughput = new Float64Array([1, 1, 1]);+ const emitted = new Float64Array(3);+ createLocalVolumeCrossing([volume])(-1, 0.37, 0.43, 1, 0, 0, 10, 0.31, throughput, emitted);+ return [...throughput, ...emitted];+ };+ assert.deepEqual(run(), run());+});++const LOOKING_DOWN = { eye: [0, 3, 0], target: [0, 0, 0], up: [0, 0, -1], fov: 40 };+const IMAGE = { width: 16, height: 16, denoise: false, threads: 1, bounces: 1, samples: 1 };++function glowingGround() {+ const half = 20;+ const geometry = {+ positions: new Float32Array([-half, 0, half, half, 0, half, half, 0, -half, -half, 0, -half]),+ normals: new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]),+ uvs: new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ };+ return { name: 'ground', geometry, material: { tag: 'surface', metallic: 0, roughness: 1, color: [0, 0, 0], ior: 1, emission: 1, emissiveColor: [1, 1, 1] } };+}++async function pixel(fit, column, row) {+ // The L covers x and z from -0.4 to 0.4 with its notch in the corner where both are positive, from y 0.2 to 1.2.+ const matrix = [0.4, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.4, 0, -0.4, 0.2, -0.4, 1];+ const room = part('room', lPrism(), matrix, { visible: false, material: glowingGround().material });+ const environment = { localVolumes: [{ shape: 'mesh', part: 'room', fit, density: 1, falloff: 0, steps: 8 }] };+ const { linear } = await renderPathTracedImage({ parts: [glowingGround(), room], environment, camera: LOOKING_DOWN }, IMAGE);+ return linear[(row * 16 + column) * 3];+}++test('the path tracer fills a hidden L-shaped part with smoke and leaves the notch clear, while bounds fill the whole box', async () => {+ const insideArm = await pixel('mesh', 5, 5);+ const inNotch = await pixel('mesh', 10, 10);+ const boundsNotch = await pixel('bounds', 10, 10);+ const outside = await pixel('mesh', 1, 1);+ assert.ok(Math.abs(insideArm - Math.exp(-1)) < 0.01, `arm ${insideArm}`);+ assert.equal(inNotch, 1, 'the notch of the L is clear');+ assert.ok(Math.abs(boundsNotch - Math.exp(-1)) < 0.01, `bounds fill the notch: ${boundsNotch}`);+ assert.equal(outside, 1);+ assert.equal(await pixel('mesh', 5, 5), insideArm, 'the same scene renders the same pixel');+});++test('a scene without mesh volumes builds the same trace scene as before', async () => {+ const withoutVolumes = await renderPathTracedImage({ parts: [glowingGround()], environment: {}, camera: LOOKING_DOWN }, IMAGE);+ const emptyList = await renderPathTracedImage({ parts: [glowingGround()], environment: { localVolumes: [] }, camera: LOOKING_DOWN }, IMAGE);+ assert.deepEqual(Array.from(emptyList.linear), Array.from(withoutVolumes.linear));+});