3D engine that AI agents drive
Add bounded depth-clipped volumetric fog
Nguyen Xuan Anf9f807c0d40d
diff --git a/README.md b/README.mdindex 14307c86..eab06b3f 100644--- a/README.md+++ b/README.md@@ -157,6 +157,7 @@ renderer.render({ eye: [4, 3, 7], target: [0, 1.5, 0], assemblyAmount: 0.5 });The core exports animation helpers, camera views and effect presets. `renderer.updateParts(parts)` uploads changes without replacing geometry buffers.The current source adds [camera paths](docs/camera-path.md) with cubic moves, target tracking, roll and focal-length conversion.It also adds [local lighting](docs/lighting.md) with eight point lights and separate key, fill and ambient controls. These controls remain source-only until the next package release.+The source also adds [depth-clipped volume fog](docs/volumetric.md) with directional scattering, shadow occlusion and deterministic density drift. It requires an opaque HDR renderer with resolved depth enabled.These camera helpers are not included in the published `0.3.3` package yet.The current source also adds [GPU skinning](docs/skinning.md) and skeletal GLB import, with four influences per vertex.The optional [physics addon](docs/physics.md) records Rapier contacts and articulated joints into a timeline for repeatable film seeks.diff --git a/docs/capability-audit.md b/docs/capability-audit.mdindex 20398b83..135ad079 100644--- a/docs/capability-audit.md+++ b/docs/capability-audit.md@@ -116,8 +116,8 @@ The current source frames portrait shots by output aspect and retains the face aThis source change has not been deployed or published to npm.Rigid joint animation and GPU skinning provide motion tools, but do not solve character modeling or material quality by themselves.-The environment has procedural shaders, fog, bloom and grading. These features do not yet produce convincing cinematic atmosphere.-Volumetric lighting, smoke, dust, explosion detail and lighting continuity require visible shot-level validation.+The environment has procedural shaders, fog, bloom and grading. Source-only volume fog adds resolved-depth clipping, directional scattering, shadow occlusion and absolute-time density drift. Native GPU fixtures match analytic extinction, block scattering behind opaque casters and reproduce earlier frames after a seek. These features do not yet produce convincing cinematic atmosphere.+Visible shafts, smoke, dust, explosion detail and lighting continuity still require shot-level improvement and validation.The current source provides an optional Rapier addon for rigid-body contacts and articulated spherical, revolute and fixed joints.A native render fixture records twelve bodies and ten joints, then reproduces the same pose and pixels after a backward seek.diff --git a/docs/lighting.md b/docs/lighting.mdindex acf041f9..f5bd51df 100644--- a/docs/lighting.md+++ b/docs/lighting.md@@ -45,7 +45,7 @@ Inputs must be finite numbers. Positions are within ±1,000,000 scene units. ColKey/fill/ambient intensity is between zero and 100. Key color components are between zero and 1,000. Large coordinates still inherit Float32 rendering precision limits.-Lights currently cast no local shadows and can illuminate through opaque walls. The original directional shadow map remains in use. Point-light shadows, spotlights, area lights, indirect bounces and volumetric scattering remain unfinished.+Lights currently cast no local shadows and can illuminate through opaque walls. The original directional shadow map remains in use. Source-only [volume fog](volumetric.md) receives directional scattering and shadows. Point-light shadows and scattering, spotlights, area lights and indirect bounces remain unfinished.## Animation and resourcesdiff --git a/docs/volumetric.md b/docs/volumetric.mdnew file mode 100644index 00000000..9048b7d3--- /dev/null+++ b/docs/volumetric.md@@ -0,0 +1,59 @@+# Depth-clipped volume fog++This API exists in the source checkout and next library build. Published version `0.3.3` does not include it yet.++Enable `{ hdr: true, depth: true }` when constructing an opaque, non-benchmark `Renderer67`. Active fog requires WebGL 2 `EXT_color_buffer_float`. Unsupported HDR negotiation rejects active fog. The depth option retains a resolved depth texture across frames and includes it in `memoryPlan`.++```js+const renderer = new Renderer67(canvas, parts, {+ hdr: true,+ depth: true,+ ground: false,+ environment: {+ lightDirection: [-0.35, 0.55, -0.85],+ volumeFog: {+ density: 0.065,+ minimum: [-5.7, 0.03, -4.7],+ maximum: [5.7, 4.5, 5.5],+ color: [0.9, 0.83, 0.7],+ steps: 24,+ maxDistance: 15,+ },+ },+});+renderer.render({ eye: [0, 2, 5], target: [0, 1, 0], time: 0 });+```++## Controls++`environment.volumeFog` defines one axis-aligned world-space volume. `frame.environment.volumeFog` replaces the whole constructor fog object for that frame. Omitted fields use the following defaults. Set `density: 0` to disable it.++| Field | Default | Accepted range |+| --- | --- | --- |+| `density` | `0` | `0…10`, extinction per scene unit |+| `minimum` | `[-100, 0, -100]` | Three components within ±100,000 |+| `maximum` | `[100, 20, 100]` | Three components within ±100,000; greater than minimum after Float32 rounding |+| `color` | `[0.8, 0.85, 0.9]` | Linear RGB, `0…1` |+| `ambient` | `[0.03, 0.035, 0.04]` | Linear RGB, `0…10` |+| `steps` | `16` | Integer `8…48` |+| `anisotropy` | `0.3` | `-0.9…0.9`; positive favors forward scattering |+| `noiseAmount` | `0.5` | `0…1`; zero gives uniform density |+| `noiseScale` | `0.3` | `0.001…100`, inverse scene units |+| `drift` | `[0.03, 0, 0]` | Three components within ±100, scene units per second |+| `maxDistance` | `100` | `0.01…10,000`, ray distance in scene units |++Values must be finite numbers. Active volume fog accepts finite frame time within ±1,000,000 seconds and a nonzero light direction with components within ±1,000,000. Noise samples absolute time, so backward seeks reproduce earlier density.++## Lighting and depth++The fullscreen march clips against resolved opaque depth, supports perspective and orthographic cameras, and stops at the volume boundary or maximum distance. It integrates Beer-Lambert extinction and directional single scattering with a Henyey-Greenstein phase function. It uses the existing directional shadow map and key-light color. Keep authored shadow bounds aligned with the light direction and covering the medium.++`part.castShadow: false` excludes a mesh from shadow rendering while keeping it visible and opaque in the color/depth pass. The flag defaults to true and must be boolean. Shadow-casting groups use separate batches. Changing a part's casting regime requires a new renderer. `updateParts()` rejects that change. A luminous window can omit its shadow, but remains an opaque emissive surface rather than transparent glass.++## Cost and limits++Resolved depth adds four estimated bytes per rendered pixel, or 2,073,600 bytes at 960 × 540. The planner reduces render dimensions when needed. The target is allocated at construction/resize, reused across frames and released by `dispose()`. The march adds no additional volume textures or geometry, but shading cost grows with covered pixels and step count.++This implements one bounded medium and one directional scattering source. Point-light scattering, multiple scattering, attenuation toward the source, transparent depth, volume grids, particles, temporal accumulation and half-resolution rendering remain unfinished. The legacy film explosion is separate and does not use this depth-clipped medium. Fog runs after bloom extraction, so scattering itself does not feed bloom.++Run `node scripts/smoke-volumetric.mjs` with the development server running for native GPU extinction, foreground clipping, directional shadow, long-distance ray, resource reuse and disposal checks. Run `node scripts/benchmark-volumetric.mjs` for a fixed laboratory comparison and deterministic noise seeking. These fixtures establish behavior, not cinematic trailer quality.diff --git a/package.json b/package.jsonindex a7e1b8a3..8712aa83 100644--- a/package.json+++ b/package.json@@ -30,7 +30,8 @@"docs/camera-path.md","docs/skinning.md","docs/physics.md",- "docs/lighting.md"+ "docs/lighting.md",+ "docs/volumetric.md"],"main": "./build/67.module.js","module": "./build/67.module.js",diff --git a/scripts/benchmark-volumetric.mjs b/scripts/benchmark-volumetric.mjsnew file mode 100644index 00000000..9aaacc54--- /dev/null+++ b/scripts/benchmark-volumetric.mjs@@ -0,0 +1,72 @@+import assert from 'node:assert/strict';+import { writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist'] });+try {+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });+ await page.route('**/volume-benchmark.html', route => route.fulfill({ contentType: 'text/html', body: '<canvas style="width:960px;height:540px;display:block"></canvas>' }));+ await page.goto('http://127.0.0.1:5173/volume-benchmark.html');+ const results = await page.evaluate(async () => {+ const { Renderer67 } = await import('/src/renderer.js');+ const { createFilmScenes, sampleFilm } = await import('/src/film.js');+ const canvas = document.querySelector('canvas');+ const scene = createFilmScenes().laboratory;+ const sample = sampleFilm(36);+ const frame = { ...sample.camera, time: sample.sceneTime, effects: { grain: 0 } };+ scene.animate(sample.sceneTime);+ const renderer = new Renderer67(canvas, scene.parts, { hdr: true, depth: true, world: true, ground: false, pixelRatio: 1, samples: 4, environment: scene.environment, shadowBounds: scene.shadowBounds });+ const context = renderer.context;+ const timer = context.getExtension('EXT_disjoint_timer_query_webgl2');+ if (!timer) throw new Error('Native GPU timer unavailable');+ const variants = {+ disabled: { volumeFog: { density: 0 } },+ enabled: {},+ tuned: { keyIntensity: 1.3, volumeFog: { ...scene.environment.volumeFog, density: 0.085, anisotropy: 0.6 } },+ };+ const results = {};+ for (const [name, environment] of Object.entries(variants)) {+ frame.environment = environment;+ for (let index = 0; index < 5; index++) renderer.render(frame);+ const samples = [];+ for (let index = 0; index < 20; index++) {+ const query = context.createQuery();+ context.beginQuery(timer.TIME_ELAPSED_EXT, query);+ renderer.render(frame);+ context.endQuery(timer.TIME_ELAPSED_EXT);+ context.flush();+ const started = performance.now();+ while (!context.getQueryParameter(query, context.QUERY_RESULT_AVAILABLE)) {+ if (performance.now() - started > 2000) throw new Error('GPU query timed out');+ await new Promise(resolve => setTimeout(resolve, 2));+ }+ if (context.getParameter(timer.GPU_DISJOINT_EXT)) throw new Error('Disjoint GPU timer');+ samples.push(context.getQueryParameter(query, context.QUERY_RESULT) / 1e6);+ context.deleteQuery(query);+ }+ samples.sort((first, second) => first - second);+ renderer.render(frame);+ results[name] = { medianMilliseconds: (samples[9] + samples[10]) / 2, samples, image: canvas.toDataURL('image/png'), glError: context.getError(), estimatedBytes: renderer.memoryPlan.estimatedBytes };+ }+ frame.environment = {};+ renderer.render(frame);+ const first = canvas.toDataURL('image/png');+ renderer.render({ ...frame, time: 4 });+ renderer.render(frame);+ results.deterministicSeek = first === canvas.toDataURL('image/png');+ renderer.dispose();+ return results;+ });+ for (const name of ['disabled', 'enabled', 'tuned']) {+ assert.equal(results[name].glError, 0);+ await writeFile(`artifacts/laboratory-volume-${name}.png`, Buffer.from(results[name].image.split(',')[1], 'base64'));+ delete results[name].image;+ }+ assert.equal(results.deterministicSeek, true);+ await writeFile('artifacts/volumetric-benchmark.json', JSON.stringify(results, null, 2));+ console.log(JSON.stringify(results, null, 2));+} finally {+ await browser.close();+}diff --git a/scripts/smoke-lighting.mjs b/scripts/smoke-lighting.mjsindex c2e7e2bf..e7a3060f 100644--- a/scripts/smoke-lighting.mjs+++ b/scripts/smoke-lighting.mjs@@ -93,7 +93,7 @@ try {const scene = createFilmScenes().laboratory;scene.animate(36);const canvas = document.querySelector('canvas');- const renderer = new Renderer67(canvas, scene.parts, { ground: false, world: true, environment: scene.environment, shadowBounds: scene.shadowBounds, samples: 4, hdr: true, pixelRatio: 1, memoryBudgetMiB: 384 });+ const renderer = new Renderer67(canvas, scene.parts, { ground: false, world: true, environment: { ...scene.environment, volumeFog: { density: 0 } }, shadowBounds: scene.shadowBounds, samples: 4, hdr: true, pixelRatio: 1, memoryBudgetMiB: 384 });const frame = { ...sampleFilm(36).camera, effects: { grain: 0 }, time: 36 };const context = renderer.context;const timer = context.getExtension('EXT_disjoint_timer_query_webgl2');diff --git a/scripts/smoke-volumetric.mjs b/scripts/smoke-volumetric.mjsnew file mode 100644index 00000000..d8201809--- /dev/null+++ b/scripts/smoke-volumetric.mjs@@ -0,0 +1,114 @@+import assert from 'node:assert/strict';+import { writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist'] });+try {+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });+ await page.route('**/volume-smoke.html', route => route.fulfill({ contentType: 'text/html', body: '<canvas style="width:960px;height:540px;display:block"></canvas>' }));+ await page.goto('http://127.0.0.1:5173/volume-smoke.html');+ const report = await page.evaluate(async () => {+ const { Renderer67, box } = await import('/build/67.module.js');+ const canvas = document.querySelector('canvas');+ const part = { geometry: box(), matrix: new Float32Array([4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 1]), material: { tag: 'unlit', color: [0.5, 0.5, 0.5], metallic: 0, roughness: 1, emission: 0 } };+ const renderer = new Renderer67(canvas, [part], { hdr: true, depth: true, samples: 4, pixelRatio: 1, ground: false });+ const depthTexture = renderer.depthTexture;+ const colorTexture = renderer.frameTexture;+ const frame = { eye: [0, 0, 5], target: [0, 0, 0], fov: 40, time: 0, environment: { keyIntensity: 0, fillIntensity: 0, ambientIntensity: 0, volumeFog: { density: 0.5, minimum: [-3, -3, 1], maximum: [3, 3, 3], ambient: [0, 0, 0], noiseAmount: 0, steps: 24 } } };+ const context = renderer.context;+ function sample(density, position = 0, steps = 24, projection = 'perspective') {+ frame.environment.volumeFog.density = density;+ frame.environment.volumeFog.steps = steps;+ frame.projection = projection;+ frame.orthographicHeight = 4;+ part.matrix[14] = position;+ renderer.updateParts([part]);+ renderer.render(frame);+ const pixel = new Uint8Array(4);+ context.readPixels(canvas.width / 2, canvas.height / 2, 1, 1, context.RGBA, context.UNSIGNED_BYTE, pixel);+ return Array.from(pixel);+ }+ const clear = sample(0);+ const behind = sample(0.5);+ const foreground = sample(0.5, 4);+ const inside = sample(0.5, 2);+ const lowSteps = sample(0.5, 0, 8);+ const highSteps = sample(0.5, 0, 48);+ const orthographic = sample(0.5, 0, 24, 'orthographic');+ const repeated = sample(0.5);+ frame.far = 1e7;+ const distantFar = sample(0.5);+ frame.far = 1e8;+ const fartherFar = sample(0.5);+ delete frame.far;+ const retained = renderer.depthTexture === depthTexture && renderer.frameTexture === colorTexture;+ const memory = renderer.memoryPlan;+ const ordinaryPlan = (await import('/src/budget.js')).planRenderSize({ width: 960, height: 540, samples: renderer.samples, hdr: true, bloom: true, geometryBytes: renderer.geometryBytes, textureBytes: renderer.textureBytes });+ const glError = context.getError();+ renderer.dispose();+ const released = !context.isTexture(depthTexture) && !context.isTexture(colorTexture);+ function scatteringSample(castShadow) {+ const background = { ...part, material: { ...part.material, color: [0, 0, 0] } };+ const blocker = { ...background, castShadow, matrix: new Float32Array([0.1, 0, 0, 0, 0, 6, 0, 0, 0, 0, 4, 0, 2.5, 0, 2, 1]) };+ const scatteringRenderer = new Renderer67(canvas, [background, blocker], {+ hdr: true, depth: true, samples: 4, pixelRatio: 1, ground: false,+ shadowBounds: { eye: [10, 0, 2], target: [0, 0, 2], extent: 5, near: 0.1, far: 20 },+ });+ scatteringRenderer.render({ eye: [0, 0, 5], target: [0, 0, 0], fov: 40, time: 0, environment: {+ lightDirection: [1, 0, 0], keyColor: [1, 1, 1], keyIntensity: 1, fillIntensity: 0, ambientIntensity: 0,+ volumeFog: { density: 0.5, minimum: [-1.5, -1.5, 1], maximum: [1.5, 1.5, 3], color: [1, 1, 1], ambient: [0, 0, 0], noiseAmount: 0, anisotropy: 0 },+ } });+ const pixel = new Uint8Array(4);+ context.readPixels(canvas.width / 2, canvas.height / 2, 1, 1, context.RGBA, context.UNSIGNED_BYTE, pixel);+ const error = context.getError();+ scatteringRenderer.dispose();+ return { pixel: Array.from(pixel), error };+ }+ const illuminated = scatteringSample(false);+ const shadowed = scatteringSample(true);+ canvas.style.width = '1px';+ canvas.style.height = '1px';+ const parallelPart = { ...part, matrix: new Float32Array([2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0.2, 0, 0.0003, 0, -6000, 1]) };+ const parallelRenderer = new Renderer67(canvas, [parallelPart], { hdr: true, depth: true, samples: 1, pixelRatio: 1, ground: false });+ const parallelFrame = { eye: [0, 0, 0], target: [5e-8, 0, -1], projection: 'orthographic', orthographicHeight: 1, near: 0.1, far: 10000,+ environment: { keyIntensity: 0, fillIntensity: 0, ambientIntensity: 0, volumeFog: {+ density: 0.0005, minimum: [0.0001, -1, -5000], maximum: [0.0002, 1, -2000], ambient: [0, 0, 0], noiseAmount: 0, maxDistance: 10000,+ } },+ };+ parallelRenderer.render(parallelFrame);+ const parallelPixel = new Uint8Array(4);+ context.readPixels(0, 0, 1, 1, context.RGBA, context.UNSIGNED_BYTE, parallelPixel);+ const parallelError = context.getError();+ parallelRenderer.dispose();+ return { clear, behind, foreground, inside, lowSteps, highSteps, orthographic, repeated, distantFar, fartherFar, illuminated, shadowed, parallelPixel: Array.from(parallelPixel), parallelError, retained, released, glError, memory, ordinaryPlan };+ });+ function displayByte(linear) {+ const mapped = Math.min(1, Math.max(0, (linear * (2.51 * linear + 0.03)) / (linear * (2.43 * linear + 0.59) + 0.14)));+ return Math.round(mapped ** (1 / 2.2) * 255);+ }+ assert.equal(report.glError, 0);+ assert.ok(Math.abs(report.clear[0] - displayByte(0.5)) <= 1);+ assert.ok(Math.abs(report.behind[0] - displayByte(0.5 * Math.exp(-1))) <= 1, 'GPU fog must match Beer-Lambert extinction over two scene units');+ assert.deepEqual(report.foreground, report.clear, 'Resolved depth must prevent fog behind an opaque foreground surface');+ assert.ok(report.inside[0] > report.behind[0] && report.inside[0] < report.clear[0]);+ assert.deepEqual(report.lowSteps, report.highSteps);+ assert.deepEqual(report.orthographic, report.behind);+ assert.deepEqual(report.repeated, report.behind);+ assert.deepEqual(report.distantFar, report.behind);+ assert.deepEqual(report.fartherFar, report.behind);+ assert.equal(report.illuminated.error, 0);+ assert.equal(report.shadowed.error, 0);+ assert.ok(report.illuminated.pixel[0] > 30, 'Directional light must illuminate the medium');+ assert.ok(report.shadowed.pixel[0] < report.illuminated.pixel[0] / 4, 'Opaque casters must block scattering without covering the camera ray');+ assert.equal(report.parallelError, 0);+ assert.ok(Math.abs(report.parallelPixel[0] - displayByte(0.5 * Math.exp(-1))) <= 2, 'A small nonzero direction must intersect a distant narrow volume');+ assert.equal(report.retained, true);+ assert.equal(report.released, true);+ assert.equal(report.memory.estimatedBytes - report.ordinaryPlan.estimatedBytes, 960 * 540 * 4);+ await writeFile('artifacts/volumetric-gpu.json', JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report, null, 2));+} finally {+ await browser.close();+}diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex 1ea2f629..db801ed0 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -18,6 +18,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- A keyframe scene uses `src/animation.js`, `src/motion.js` and `src/motion-player.js`.- An authored camera uses `src/camera-path.js` and the checkout's `docs/camera-path.md`.- Local lights use the renderer environment and the checkout's `docs/lighting.md`.+- Depth-clipped fog uses `{ hdr: true, depth: true }` and the checkout's `docs/volumetric.md`.- A skeletal asset uses `src/skinning.js`, `src/gltf.js` and the checkout's `docs/skinning.md`.- Recorded contacts or articulated physics use optional `src/physics.js` and the checkout's `docs/physics.md`.- A flat scene or axis view uses `src/canvas2d.js`, `src/camera.js` and `src/view2d.js`.diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 5bce90a8..7af936f5 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -1,5 +1,9 @@# Scene contract+<!-- skill-navigation:start -->+Read the complete [scene contract](#scene-contract) before creating parts or changing materials. It covers identities, transforms, materials, lighting, fog, animation, cameras and resources in order.+<!-- skill-navigation:end -->+Each part has these fields.```js@@ -57,6 +61,13 @@ Each light provides `position` and optional `color`, `intensity`, `radius` and ``keyIntensity`, `fillIntensity` and `ambientIntensity` independently scale existing lighting.Read the checkout's `docs/lighting.md` for defaults, numeric limits and frame overrides.Point lights currently cast no local shadows. Radius limits attenuation without creating an area emitter.+Source-only `environment.volumeFog` receives directional scattering and shadows in one bounded volume.+It requires an opaque renderer with `{ hdr: true, depth: true }` and negotiated HDR support.+Read `docs/volumetric.md` for controls, resource cost and limitations before authoring fog.+`frame.environment.volumeFog` replaces the entire constructor fog object, with defaults for omitted fields.+Use absolute frame time for reproducible density drift. Local point lights do not scatter in fog yet.+`part.castShadow: false` omits a mesh from shadows while leaving it visible and opaque.+Changing its casting regime requires a new renderer. Shadow-casting groups use separate batches.```jsconst renderer = new Renderer67(canvas, world.parts, {diff --git a/src/budget.js b/src/budget.jsindex 7494d12f..b034e973 100644--- a/src/budget.js+++ b/src/budget.js@@ -19,15 +19,15 @@ export function estimateTextureBytes(width, height, { mipmaps = true } = {}) {return bytes;}-export function estimateFrameBytes(width, height, samples, shadowResolution = 2048, { hdr = false, bloom = false } = {}) {+export function estimateFrameBytes(width, height, samples, shadowResolution = 2048, { hdr = false, bloom = false, depth = false } = {}) {// Color/depth MSAA, resolve texture, browser buffers and one screenshot/encoder staging frame.const colorBytes = hdr ? 8 : 4;const frameBytes = width * height * ((colorBytes + 4) * Math.max(1, samples) + colorBytes + 16);const bloomBytes = bloom ? Math.ceil(width / 2) * Math.ceil(height / 2) * colorBytes * 2 : 0;- return frameBytes + bloomBytes + shadowResolution ** 2 * 4;+ return frameBytes + bloomBytes + (depth ? width * height * 4 : 0) + shadowResolution ** 2 * 4;}-export function planRenderSize({ width, height, pixelRatio = 1, samples = 4, memoryBudgetMiB = 256, geometryBytes = 0, textureBytes = 0, hdr = false, bloom = false, shadowResolution = 2048, maximumSize = 8192 }) {+export function planRenderSize({ width, height, pixelRatio = 1, samples = 4, memoryBudgetMiB = 256, geometryBytes = 0, textureBytes = 0, hdr = false, bloom = false, depth = false, shadowResolution = 2048, maximumSize = 8192 }) {for (const value of [width, height, pixelRatio, samples, memoryBudgetMiB, maximumSize]) {if (!Number.isFinite(value) || value <= 0) throw new Error('Render dimensions, sample count and budget must be positive finite numbers.');}@@ -35,17 +35,17 @@ export function planRenderSize({ width, height, pixelRatio = 1, samples = 4, memif (textureBytes < 0 || !Number.isFinite(textureBytes)) throw new Error('Texture memory must be a nonnegative finite number.');if (!Number.isFinite(shadowResolution) || shadowResolution < 0) throw new Error('Shadow resolution must be nonnegative and finite.');const available = memoryBudgetMiB * MEBIBYTE - geometryBytes - textureBytes - shadowResolution ** 2 * 4;- const bytesPerPixel = (hdr ? 12 : 8) * Math.max(1, samples) + (hdr ? 24 : 20) + (bloom ? hdr ? 4 : 2 : 0);- if (available < estimateFrameBytes(64, 64, samples, 0, { hdr, bloom })) throw new Error('Memory budget cannot hold the scene and a minimum render target. Lower scene detail or increase the budget.');+ const bytesPerPixel = (hdr ? 12 : 8) * Math.max(1, samples) + (hdr ? 24 : 20) + (bloom ? hdr ? 4 : 2 : 0) + (depth ? 4 : 0);+ if (available < estimateFrameBytes(64, 64, samples, 0, { hdr, bloom, depth })) throw new Error('Memory budget cannot hold the scene and a minimum render target. Lower scene detail or increase the budget.');const requestedWidth = Math.max(1, Math.round(width * pixelRatio));const requestedHeight = Math.max(1, Math.round(height * pixelRatio));const scale = Math.min(1, maximumSize / requestedWidth, maximumSize / requestedHeight, Math.sqrt(available / (requestedWidth * requestedHeight * bytesPerPixel)));let renderWidth = Math.max(1, Math.floor(requestedWidth * scale));let renderHeight = Math.max(1, Math.floor(requestedHeight * scale));const budget = memoryBudgetMiB * MEBIBYTE;- while (estimateFrameBytes(renderWidth, renderHeight, samples, shadowResolution, { hdr, bloom }) + geometryBytes + textureBytes > budget) {+ while (estimateFrameBytes(renderWidth, renderHeight, samples, shadowResolution, { hdr, bloom, depth }) + geometryBytes + textureBytes > budget) {renderWidth = Math.max(1, renderWidth - 1);renderHeight = Math.max(1, renderHeight - 1);}- return { width: renderWidth, height: renderHeight, samples, hdr, bloom, textureBytes, estimatedBytes: estimateFrameBytes(renderWidth, renderHeight, samples, shadowResolution, { hdr, bloom }) + geometryBytes + textureBytes, reduced: renderWidth < requestedWidth || renderHeight < requestedHeight };+ return { width: renderWidth, height: renderHeight, samples, hdr, bloom, depth, textureBytes, estimatedBytes: estimateFrameBytes(renderWidth, renderHeight, samples, shadowResolution, { hdr, bloom, depth }) + geometryBytes + textureBytes, reduced: renderWidth < requestedWidth || renderHeight < requestedHeight };}diff --git a/src/film-player.js b/src/film-player.jsindex d2b352f4..560b14d4 100644--- a/src/film-player.js+++ b/src/film-player.js@@ -67,6 +67,7 @@ function renderAt(time) {pixelRatio: 1,samples,hdr: true,+ depth: true,memoryBudgetMiB,});activeScene = sample.scene;diff --git a/src/film.js b/src/film.jsindex c81b4271..c2956231 100644--- a/src/film.js+++ b/src/film.js@@ -401,7 +401,12 @@ function addScientist(builder, position = [0, 0, 0], hat = true, rotation = 0) {function addRoom(builder, laboratory = false) {const { add, beam } = builder;add('Shadowed floor', 'box', [0, -0.1, 0], [12, 0.15, 12], 'wood');- add('Rear plaster wall', 'box', [0, 2.3, -4.8], [12, 4.7, 0.15], 'plaster');+ add('Rear plaster below windows', 'box', [0, 0.6, -4.8], [12, 1.2, 0.15], 'plaster');+ add('Rear plaster above windows', 'box', [0, 4.4, -4.8], [12, 0.6, 0.15], 'plaster');+ const wallPiers = [[-6, -4.46], [-2.74, -1.16], [0.56, 2.14], [3.86, 6]];+ for (const [left, right] of wallPiers) {+ add('Plaster pier between openings', 'box', [(left + right) / 2, 2.65, -4.8], [right - left, 2.9, 0.15], 'plaster');+ }add('Side plaster wall', 'box', [-5.8, 2.3, 0], [0.15, 4.7, 12], 'plaster');add('Ceiling in shadow', 'box', [0, 4.65, 0], [12, 0.12, 12], 'black');for (let plank = 0; plank < 30; plank++) {@@ -409,7 +414,7 @@ function addRoom(builder, laboratory = false) {}for (let index = 0; index < 3; index++) {const horizontal = -3.6 + index * 3.3;- add('Tall luminous window', 'box', [horizontal, 2.65, -4.69], [1.65, 2.8, 0.04], 'window');+ add('Tall luminous window', 'box', [horizontal, 2.65, -4.69], [1.65, 2.8, 0.04], 'window').castShadow = false;for (const side of [-1, 1]) {add('Window jamb', 'box', [horizontal + side * 0.86, 2.65, -4.61], [0.09, 2.95, 0.15], 'wood');}@@ -746,9 +751,14 @@ export function createFilmScenes() {lightDirection: [-0.4, 0.8, 0.5], daylight: 0.65,};const interior = {- ...studio, fogDensity: 0.006, daylight: 0.75,+ ...studio, fogDensity: 0, daylight: 0.75,skyTop: [0.12, 0.17, 0.18], skyBottom: [0.22, 0.23, 0.18],- lightDirection: [-0.85, 0.5, -0.35],+ lightDirection: [-0.35, 0.55, -0.85],+ volumeFog: {+ density: 0.065, minimum: [-5.7, 0.03, -4.7], maximum: [5.7, 4.5, 5.5],+ color: [0.9, 0.83, 0.7], ambient: [0.02, 0.025, 0.03],+ anisotropy: 0.45, noiseAmount: 0.35, noiseScale: 0.4, drift: [0.025, 0.01, 0], steps: 24, maxDistance: 15,+ },keyIntensity: 0.7,fillIntensity: 0.35,ambientIntensity: 0.45,@@ -774,12 +784,12 @@ export function createFilmScenes() {towerParts.push(...towerBuilder.parts);return {apparatus: set(createApparatus(meshes), studio),- office: set(createOffice(meshes), { ...interior, pointLights: [...interior.pointLights, { position: [-1.45, 1.36, 0.25], color: [1, 0.82, 0.57], intensity: 1.8, range: 3, radius: 0.08 }] }, { extent: 7, target: [0, 1.6, -1], eye: [-8, 7, -4], near: 0.1, far: 30 }, 'office'),- laboratory: set(createOffice(meshes, true), interior, { extent: 7, target: [0, 1.6, -1], eye: [-8, 7, -4], near: 0.1, far: 30 }, 'laboratory'),+ office: set(createOffice(meshes), { ...interior, pointLights: [...interior.pointLights, { position: [-1.45, 1.36, 0.25], color: [1, 0.82, 0.57], intensity: 1.8, range: 3, radius: 0.08 }] }, { extent: 7, target: [0, 1.6, -1], eye: [-4, 7, -10], near: 0.1, far: 30 }, 'office'),+ laboratory: set(createOffice(meshes, true), interior, { extent: 7, target: [0, 1.6, -1], eye: [-4, 7, -10], near: 0.1, far: 30 }, 'laboratory'),settlement: set(createSettlement(meshes), desert, desertShadows, 'settlement'),portrait: set(createPortrait(meshes), { ...desert, lightDirection: [-0.7, 0.55, 0.8] }, { extent: 6, target: [0, 1, 0], eye: [-8, 5, 6], near: 0.1, far: 35 }, 'portrait'),- gadget: set(createGadget(meshes), { ...interior, lightDirection: [-0.8, 0.4, 0.5], daylight: 0.9 }, { extent: 5, target: [0, 2.5, -1], eye: [-8, 7, 4], near: 0.1, far: 30 }, 'gadget'),- control: set(createControl(meshes), { ...interior, lightDirection: [-0.4, 0.9, 0.3] }, { extent: 5, target: [0, 1, 0], eye: [-3, 8, 4], near: 0.1, far: 25 }, 'control'),+ gadget: set(createGadget(meshes), { ...interior, volumeFog: { density: 0 }, lightDirection: [-0.8, 0.4, 0.5], daylight: 0.9 }, { extent: 5, target: [0, 2.5, -1], eye: [-8, 7, 4], near: 0.1, far: 30 }, 'gadget'),+ control: set(createControl(meshes), interior, { extent: 7, target: [0, 1.6, -1], eye: [-4, 7, -10], near: 0.1, far: 30 }, 'control'),atom: set(createAtom(meshes), { ...studio, daylight: 0.25, fogDensity: 0.035 }, undefined, 'atom'),waves: set(createWaveChamber(meshes), studio, undefined, 'waves'),sparks: set(createSparks(meshes), { ...night, daylight: 0.1 }, undefined, 'sparks'),diff --git a/src/post.js b/src/post.jsindex 7662f21f..cbddcb54 100644--- a/src/post.js+++ b/src/post.js@@ -27,6 +27,23 @@ uniform float volumeExplosion;uniform float explosionProgress;uniform mat4 inverseViewProjection;uniform vec3 eye;+uniform sampler2D sceneDepth;+uniform sampler2D volumeShadowMap;+uniform mat4 volumeLightProjection;+uniform vec3 volumeLightDirection;+uniform vec3 volumeLightColor;+uniform float volumeDensity;+uniform vec3 volumeMinimum;+uniform vec3 volumeMaximum;+uniform vec3 volumeColor;+uniform vec3 volumeAmbient;+uniform vec3 volumeDrift;+uniform int volumeSteps;+uniform float volumeAnisotropy;+uniform float volumeNoiseAmount;+uniform float volumeNoiseScale;+uniform float volumeMaxDistance;+uniform float orthographic;out vec4 outputColor;float luminance(vec3 color) { return dot(color, vec3(0.299, 0.587, 0.114)); }float hash(vec3 position) { return fract(sin(dot(position, vec3(127.1, 311.7, 74.7))) * 43758.5453); }@@ -78,6 +95,56 @@ vec3 explosion(vec3 background) {accumulated = accumulated / (accumulated + 0.5);return accumulated + background * transmittance;}+vec3 volumeFog(vec3 background) {+ vec2 clipXY = textureCoordinate * 2.0 - 1.0;+ vec4 farPoint = inverseViewProjection * vec4(clipXY, 1.0, 1.0);+ vec4 nearPoint = inverseViewProjection * vec4(clipXY, -1.0, 1.0);+ vec3 origin = orthographic > 0.5 ? nearPoint.xyz / nearPoint.w : eye;+ vec3 direction = normalize(farPoint.xyz - origin * farPoint.w);+ float depth = texture(sceneDepth, textureCoordinate).r;+ vec4 surfacePoint = inverseViewProjection * vec4(clipXY, depth * 2.0 - 1.0, 1.0);+ float surfaceDistance = volumeMaxDistance;+ if (surfacePoint.w > 0.0) surfaceDistance = max(0.0, dot(surfacePoint.xyz - origin * surfacePoint.w, direction) / surfacePoint.w);+ float exitDistance = min(volumeMaxDistance, surfaceDistance);+ float entry = 0.0;+ for (int axis = 0; axis < 3; axis++) {+ if (direction[axis] == 0.0) {+ if (origin[axis] < volumeMinimum[axis] || origin[axis] > volumeMaximum[axis]) return background;+ } else {+ float first = (volumeMinimum[axis] - origin[axis]) / direction[axis];+ float second = (volumeMaximum[axis] - origin[axis]) / direction[axis];+ entry = max(entry, min(first, second));+ exitDistance = min(exitDistance, max(first, second));+ }+ }+ if (entry >= exitDistance) return background;+ float stepSize = (exitDistance - entry) / float(volumeSteps);+ vec3 lightDirection = normalize(volumeLightDirection);+ float cosine = dot(direction, lightDirection);+ float anisotropy = volumeAnisotropy;+ float phase = (1.0 - anisotropy * anisotropy) / (12.5663706 * pow(1.0 + anisotropy * anisotropy - 2.0 * anisotropy * cosine, 1.5));+ float jitter = hash(vec3(gl_FragCoord.xy, 0));+ float transmittance = 1.0;+ vec3 accumulated = vec3(0);+ for (int index = 0; index < 48; index++) {+ if (index >= volumeSteps) break;+ vec3 position = origin + direction * (entry + (float(index) + jitter) * stepSize);+ float noise = 1.0;+ if (volumeNoiseAmount > 0.0) noise = mix(1.0, cloudNoise((position - volumeDrift * time) * volumeNoiseScale) * 2.0, volumeNoiseAmount);+ float opacity = 1.0 - exp(-volumeDensity * noise * stepSize);+ vec4 lightPosition = volumeLightProjection * vec4(position, 1);+ vec3 shadow = lightPosition.xyz / lightPosition.w * 0.5 + 0.5;+ float visibility = 1.0;+ if (all(greaterThanEqual(shadow, vec3(0))) && all(lessThanEqual(shadow, vec3(1)))) {+ visibility = step(shadow.z - 0.0008, texture(volumeShadowMap, shadow.xy).r);+ }+ vec3 scattering = volumeColor * (volumeAmbient + volumeLightColor * phase * visibility);+ accumulated += transmittance * opacity * scattering;+ transmittance *= 1.0 - opacity;+ if (transmittance < 0.001) break;+ }+ return accumulated + background * transmittance;+}void main() {vec2 texel = 1.0 / resolution;vec3 center = texture(frameTexture, textureCoordinate).rgb;@@ -103,6 +170,7 @@ void main() {float coverage = texture(frameTexture, textureCoordinate).a;if (transparent > 0.5) color = center / max(coverage, 0.00001);if (bloomStrength > 0.0) color += texture(bloomTexture, textureCoordinate).rgb * bloomStrength;+ if (volumeDensity > 0.0) color = volumeFog(color);if (hdrEnabled > 0.5) {color = clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);color = pow(color, vec3(1.0 / 2.2));diff --git a/src/renderer.js b/src/renderer.jsindex 923ae2ee..186e24f1 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -5,6 +5,7 @@ import { planRenderSize, estimateTextureBytes } from './budget.js';import { applyProjection } from './camera.js';import { resolveEffects } from './effects.js';import { createLightingState, updateLightingState } from './lighting.js';+import { resolveVolumeFog } from './volumetric.js';import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10 };@@ -123,13 +124,14 @@ export function groupParts(parts, batching = true) {const batches = [];for (const part of parts) {validateTransform(part);+ if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');validateSkinGeometry(part.geometry, part.skin);if (part.skin) validateSkinPose(part.skin, part.geometry, part.matrix);if (part.skin && PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Skinned parts require a standard material tag.');const key = batching ? part.geometry : part;if (!groups.has(key)) groups.set(key, new Map());let maps = groups.get(key);- for (const value of [...materialMapState(part.material), part.skin ?? null]) {+ for (const value of [...materialMapState(part.material), part.skin ?? null, part.castShadow !== false]) {if (!maps.has(value)) maps.set(value, new Map());maps = maps.get(value);}@@ -167,22 +169,26 @@ function sampleCount(context, format, requested) {}export class Renderer67 {- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {} } = {}) {+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {} } = {}) {this.canvas = canvas;if (!Number.isInteger(samples) || samples < 1) throw new Error('MSAA sample count must be a positive integer.');if (new Set(parts).size !== parts.length) throw new Error('Scene parts must have distinct object identities for animation.');this.lighting = createLightingState();updateLightingState(this.lighting, environment, { world });+ const volume = resolveVolumeFog(environment.volumeFog);+ if (volume.density > 0 && (!depth || benchmark || transparent || !hdr)) throw new Error('Volume fog requires depth:true, hdr:true, an opaque canvas and normal rendering');this.context = canvas.getContext('webgl2', { antialias: true, alpha: Boolean(transparent), premultipliedAlpha: true, powerPreference: 'high-performance' });if (!this.context) throw new Error('WebGL2 is unavailable. Enable hardware acceleration or use a supported browser.');this.transparent = Boolean(transparent);this.pixelRatio = pixelRatio;this.benchmark = benchmark;+ this.depth = Boolean(depth && !benchmark);this.world = world;this.environment = environment;this.shadowBounds = shadowBounds;this.memoryBudgetMiB = memoryBudgetMiB;this.hdr = Boolean(hdr && !benchmark && this.context.getExtension('EXT_color_buffer_float'));+ if (volume.density > 0 && !this.hdr) throw new Error('Volume fog requires EXT_color_buffer_float for HDR rendering');this.multisampleSamples = benchmark ? 0 : sampleCount(this.context, this.hdr ? this.context.RGBA16F : this.context.RGBA8, Math.min(samples, this.context.getParameter(this.context.MAX_SAMPLES)));this.capabilities = { hdr: this.hdr, hdrRequested: Boolean(hdr), hdrFallbackReason: hdr && !this.hdr ? benchmark ? 'HDR is disabled in benchmark mode' : 'EXT_color_buffer_float is unavailable' : null, samples: this.multisampleSamples };this.geometryBytes = 0;@@ -233,7 +239,7 @@ export class Renderer67 {if (geometry.colors && geometry.colors.length !== geometry.positions.length) throw new Error('Geometry colors must contain RGB for every vertex.');}const expectedGeometryBytes = groups.reduce((total, group) => total + ['positions', 'normals', 'indices', 'uvs', 'colors'].reduce((bytes, field) => bytes + (group[0].geometry[field]?.byteLength ?? 0), 0) + group.length * INSTANCE_STRIDE * 4, 0);- planRenderSize({ width: Math.max(1, canvas.clientWidth), height: Math.max(1, canvas.clientHeight), pixelRatio, samples: this.samples, memoryBudgetMiB, geometryBytes: expectedGeometryBytes, textureBytes: this.textureBytes, hdr: this.hdr, bloom: !benchmark, maximumSize: textureLimit });+ planRenderSize({ width: Math.max(1, canvas.clientWidth), height: Math.max(1, canvas.clientHeight), pixelRatio, samples: this.samples, memoryBudgetMiB, geometryBytes: expectedGeometryBytes, textureBytes: this.textureBytes, hdr: this.hdr, bloom: !benchmark, depth: this.depth, maximumSize: textureLimit });this.view = mat4.create();this.projection = mat4.create();this.viewProjection = mat4.create();@@ -249,7 +255,7 @@ export class Renderer67 {if (!benchmark) {this.postProgram = compileProgram(this.context, fullscreenVertex, postFragment);this.skyProgram = compileProgram(this.context, fullscreenVertex, skyFragment);- this.postUniforms = Object.fromEntries(['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye'].map((name) => [name, this.context.getUniformLocation(this.postProgram, name)]));+ this.postUniforms = Object.fromEntries(['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'orthographic'].map((name) => [name, this.context.getUniformLocation(this.postProgram, name)]));this.bloomProgram = compileProgram(this.context, fullscreenVertex, bloomFragment);this.bloomUniforms = Object.fromEntries(['sourceTexture', 'texelDirection', 'threshold', 'extract'].map(name => [name, this.context.getUniformLocation(this.bloomProgram, name)]));this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight', 'hdrEnabled'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));@@ -374,7 +380,7 @@ export class Renderer67 {const skin = parts[0].skin ?? null;const skinTexture = skin ? this.createSkinTexture(this.skinTextures, skin, skin.jointMatrices, 4) : null;const influenceTexture = skin ? this.createSkinTexture(this.influenceTextures, geometry, null, 2) : null;- const batch = { vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor' };+ const batch = { vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: parts[0].castShadow !== false };parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));return batch;}@@ -413,6 +419,8 @@ export class Renderer67 {this.updatePartIdentities.add(part);const location = this.partLocations.get(part);if (!location) throw new Error(`Unknown part identity: ${part.name}`);+ if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');+ if ((part.castShadow !== false) !== location.batch.castShadow) throw new Error(`Shadow casting changes require a new renderer: ${part.name}`);if (part.geometry !== location.geometry) throw new Error(`Geometry changes require a new renderer: ${part.name}`);if ((part.skin ?? null) !== location.skin || part.skin?.jointMatrices !== location.jointMatrices || part.geometry.skinIndices !== location.skinIndices || part.geometry.skinWeights !== location.skinWeights) throw new Error(`Skin identity changes require a new renderer: ${part.name}`);if (part.skin) {@@ -496,14 +504,14 @@ export class Renderer67 {context.uniform1f(this.depthAssemblyUniform, this.assemblyAmount ?? 0);context.enable(context.POLYGON_OFFSET_FILL);context.polygonOffset(1, 1);- for (const batch of this.batches) if (!batch.floor) this.drawBatch(batch);+ for (const batch of this.batches) if (!batch.floor && batch.castShadow) this.drawBatch(batch);context.disable(context.POLYGON_OFFSET_FILL);context.bindFramebuffer(context.FRAMEBUFFER, null);this.shadowsDirty = false;}resize() {- const plan = planRenderSize({ width: Math.max(1, this.canvas.clientWidth), height: Math.max(1, this.canvas.clientHeight), pixelRatio: this.pixelRatio, samples: this.samples, memoryBudgetMiB: this.memoryBudgetMiB, geometryBytes: this.geometryBytes, textureBytes: this.textureBytes, hdr: this.hdr, bloom: !this.benchmark, maximumSize: Math.min(this.context.getParameter(this.context.MAX_RENDERBUFFER_SIZE), this.context.getParameter(this.context.MAX_TEXTURE_SIZE)) });+ const plan = planRenderSize({ width: Math.max(1, this.canvas.clientWidth), height: Math.max(1, this.canvas.clientHeight), pixelRatio: this.pixelRatio, samples: this.samples, memoryBudgetMiB: this.memoryBudgetMiB, geometryBytes: this.geometryBytes, textureBytes: this.textureBytes, hdr: this.hdr, bloom: !this.benchmark, depth: this.depth, maximumSize: Math.min(this.context.getParameter(this.context.MAX_RENDERBUFFER_SIZE), this.context.getParameter(this.context.MAX_TEXTURE_SIZE)) });const { width, height } = plan;this.memoryPlan = plan;if (this.canvas.width !== width || this.canvas.height !== height) {@@ -522,6 +530,7 @@ export class Renderer67 {if (this.multisampleColor) context.deleteRenderbuffer(this.multisampleColor);if (this.multisampleDepth) context.deleteRenderbuffer(this.multisampleDepth);if (this.frameTexture) context.deleteTexture(this.frameTexture);+ if (this.depthTexture) context.deleteTexture(this.depthTexture);for (const target of this.bloomTargets ?? []) {context.deleteTexture(target.texture);context.deleteFramebuffer(target.framebuffer);@@ -532,6 +541,7 @@ export class Renderer67 {this.multisampleColor = null;this.multisampleDepth = null;this.frameTexture = null;+ this.depthTexture = null;}allocateFrameTargets(width, height) {@@ -558,6 +568,16 @@ export class Renderer67 {this.resolveFramebuffer = context.createFramebuffer();context.bindFramebuffer(context.FRAMEBUFFER, this.resolveFramebuffer);context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, this.frameTexture, 0);+ if (this.depth) {+ this.depthTexture = context.createTexture();+ context.bindTexture(context.TEXTURE_2D, this.depthTexture);+ context.texImage2D(context.TEXTURE_2D, 0, context.DEPTH_COMPONENT24, width, height, 0, context.DEPTH_COMPONENT, context.UNSIGNED_INT, null);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);+ context.framebufferTexture2D(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.TEXTURE_2D, this.depthTexture, 0);+ }if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Resolve framebuffer allocation failed. Choose a lower quality preset.');this.bloomWidth = Math.max(1, Math.ceil(width / 2));this.bloomHeight = Math.max(1, Math.ceil(height / 2));@@ -596,11 +616,11 @@ export class Renderer67 {context.drawArrays(context.TRIANGLES, 0, 3);}- resolveFrame(frame, effects) {+ resolveFrame(frame, effects, environment, volume) {const context = this.context;context.bindFramebuffer(context.READ_FRAMEBUFFER, this.multisampleFramebuffer);context.bindFramebuffer(context.DRAW_FRAMEBUFFER, this.resolveFramebuffer);- context.blitFramebuffer(0, 0, this.canvas.width, this.canvas.height, 0, 0, this.canvas.width, this.canvas.height, context.COLOR_BUFFER_BIT, context.NEAREST);+ context.blitFramebuffer(0, 0, this.canvas.width, this.canvas.height, 0, 0, this.canvas.width, this.canvas.height, context.COLOR_BUFFER_BIT | (this.depth ? context.DEPTH_BUFFER_BIT : 0), context.NEAREST);if (effects.bloom.strength > 0) this.drawBloom(effects.bloom);context.bindFramebuffer(context.FRAMEBUFFER, null);context.viewport(0, 0, this.canvas.width, this.canvas.height);@@ -611,6 +631,27 @@ export class Renderer67 {context.activeTexture(context.TEXTURE0);context.bindTexture(context.TEXTURE_2D, this.frameTexture);context.uniform1i(this.postUniforms.frameTexture, 0);+ context.activeTexture(context.TEXTURE1);+ context.bindTexture(context.TEXTURE_2D, this.depthTexture ?? this.whiteTexture);+ context.uniform1i(this.postUniforms.sceneDepth, 1);+ context.activeTexture(context.TEXTURE3);+ context.bindTexture(context.TEXTURE_2D, this.shadowTexture);+ context.uniform1i(this.postUniforms.volumeShadowMap, 3);+ context.uniformMatrix4fv(this.postUniforms.volumeLightProjection, false, this.lightProjection);+ context.uniform3fv(this.postUniforms.volumeLightDirection, environment.lightDirection);+ context.uniform3fv(this.postUniforms.volumeLightColor, this.lighting.keyColor);+ context.uniform1f(this.postUniforms.volumeDensity, volume.density);+ context.uniform3fv(this.postUniforms.volumeMinimum, volume.minimum);+ context.uniform3fv(this.postUniforms.volumeMaximum, volume.maximum);+ context.uniform3fv(this.postUniforms.volumeColor, volume.color);+ context.uniform3fv(this.postUniforms.volumeAmbient, volume.ambient);+ context.uniform3fv(this.postUniforms.volumeDrift, volume.drift);+ context.uniform1i(this.postUniforms.volumeSteps, volume.steps);+ context.uniform1f(this.postUniforms.volumeAnisotropy, volume.anisotropy);+ context.uniform1f(this.postUniforms.volumeNoiseAmount, volume.noiseAmount);+ context.uniform1f(this.postUniforms.volumeNoiseScale, volume.noiseScale);+ context.uniform1f(this.postUniforms.volumeMaxDistance, volume.maxDistance);+ context.uniform1f(this.postUniforms.orthographic, frame.projection === 'orthographic' ? 1 : 0);context.activeTexture(context.TEXTURE2);context.bindTexture(context.TEXTURE_2D, effects.bloom.strength > 0 ? this.bloomTargets[1].texture : this.whiteTexture);context.uniform1i(this.postUniforms.bloomTexture, 2);@@ -682,6 +723,14 @@ export class Renderer67 {const { eye, target = [0, 1.2, 0], armorColor = [0.53, 0.39, 0.24], armorSurface = [0.88, 0.32], exposure = 1, inspection = false } = frame;const effects = resolveEffects(frame.effects);const environment = { lightDirection: [-3, 6, 4], fogColor: [0.35, 0.43, 0.43], fogDensity: 0.006, daylight: 1, explosionCenter: [0, 0, 0], ...this.environment, ...frame.environment };+ const volume = resolveVolumeFog(environment.volumeFog);+ if (volume.density > 0) {+ if (!this.depth || !this.hdr || this.transparent || this.benchmark) throw new Error('Volume fog requires depth:true, active HDR and an opaque canvas');+ if (!Number.isFinite(frame.time ?? 0) || Math.abs(frame.time ?? 0) > 1e6) throw new RangeError('Volume time must be finite and within ±1000000 seconds');+ const direction = environment.lightDirection;+ const lightLength = direction?.length === 3 ? Math.hypot(...direction) : NaN;+ if (!Number.isFinite(lightLength) || lightLength < 1e-6 || !Array.from(direction).every(component => typeof component === 'number' && Math.abs(component) <= 1e6)) throw new RangeError('Volume light direction must have a finite nonzero length and bounded components');+ }updateLightingState(this.lighting, environment, { world: this.world });const start = performance.now();const context = this.context;@@ -738,7 +787,7 @@ export class Renderer67 {context.uniform1i(this.uniforms.shadowMap, 0);for (const batch of this.batches) this.drawBatch(batch, true);context.bindVertexArray(null);- if (!this.benchmark) this.resolveFrame(frame, effects);+ if (!this.benchmark) this.resolveFrame(frame, effects, environment, volume);this.cpuMilliseconds = performance.now() - start;}diff --git a/src/volumetric.js b/src/volumetric.jsnew file mode 100644index 00000000..4cece408--- /dev/null+++ b/src/volumetric.js@@ -0,0 +1,38 @@+const DEFAULT_MINIMUM = Object.freeze([-100, 0, -100]);+const DEFAULT_MAXIMUM = Object.freeze([100, 20, 100]);+const DEFAULT_COLOR = Object.freeze([0.8, 0.85, 0.9]);+const DEFAULT_AMBIENT = Object.freeze([0.03, 0.035, 0.04]);+const DEFAULT_DRIFT = Object.freeze([0.03, 0, 0]);++function finiteRange(value, minimum, maximum, label) {+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {+ throw new RangeError(`${label} must be between ${minimum} and ${maximum}`);+ }+ return value;+}++function vector(value, minimum, maximum, label) {+ if (value?.length !== 3) throw new TypeError(`${label} requires three components`);+ for (let axis = 0; axis < 3; axis++) finiteRange(value[axis], minimum, maximum, label);+ return value;+}++export function resolveVolumeFog(input = {}) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('volumeFog must be an object');+ const density = finiteRange(input.density ?? 0, 0, 10, 'Volume density');+ const minimum = vector(input.minimum ?? DEFAULT_MINIMUM, -1e5, 1e5, 'Volume minimum');+ const maximum = vector(input.maximum ?? DEFAULT_MAXIMUM, -1e5, 1e5, 'Volume maximum');+ for (let axis = 0; axis < 3; axis++) {+ if (Math.fround(maximum[axis]) <= Math.fround(minimum[axis])) throw new RangeError('Volume bounds must remain ordered after Float32 rounding');+ }+ const color = vector(input.color ?? DEFAULT_COLOR, 0, 1, 'Volume color');+ const ambient = vector(input.ambient ?? DEFAULT_AMBIENT, 0, 10, 'Volume ambient');+ const drift = vector(input.drift ?? DEFAULT_DRIFT, -100, 100, 'Volume drift');+ const steps = finiteRange(input.steps ?? 16, 8, 48, 'Volume steps');+ if (!Number.isInteger(steps)) throw new RangeError('Volume steps must be an integer');+ const anisotropy = finiteRange(input.anisotropy ?? 0.3, -0.9, 0.9, 'Volume anisotropy');+ const noiseAmount = finiteRange(input.noiseAmount ?? 0.5, 0, 1, 'Volume noise amount');+ const noiseScale = finiteRange(input.noiseScale ?? 0.3, 0.001, 100, 'Volume noise scale');+ const maxDistance = finiteRange(input.maxDistance ?? 100, 0.01, 1e4, 'Volume maximum distance');+ return { density, minimum, maximum, color, ambient, drift, steps, anisotropy, noiseAmount, noiseScale, maxDistance };+}diff --git a/tests/budget.test.js b/tests/budget.test.jsindex 953647e3..7cf32007 100644--- a/tests/budget.test.js+++ b/tests/budget.test.js@@ -36,3 +36,13 @@ test('invalid or impossible memory requests fail before allocation', () => {assert.throws(() => planRenderSize({ width: 1280, height: 720, geometryBytes: 300 * 1024 ** 2, memoryBudgetMiB: 128 }), /cannot hold/);assert.throws(() => planRenderSize({ width: Infinity, height: 720 }));});++test('resolved depth adds exactly four bytes per pixel and participates in resolution reduction', () => {+ assert.equal(estimateFrameBytes(540, 960, 4, 2048, { hdr: true, depth: true }) - estimateFrameBytes(540, 960, 4, 2048, { hdr: true }), 540 * 960 * 4);+ const options = { width: 7680, height: 4320, hdr: true, bloom: true, samples: 4, memoryBudgetMiB: 64 };+ const ordinary = planRenderSize(options);+ const resolved = planRenderSize({ ...options, depth: true });+ assert.ok(resolved.width < ordinary.width);+ assert.equal(resolved.estimatedBytes, estimateFrameBytes(resolved.width, resolved.height, 4, 2048, { hdr: true, bloom: true, depth: true }));+ assert.ok(resolved.estimatedBytes <= 64 * 1024 ** 2);+});diff --git a/tests/renderer.test.js b/tests/renderer.test.jsindex 2f8390f3..63107aa0 100644--- a/tests/renderer.test.js+++ b/tests/renderer.test.js@@ -11,7 +11,7 @@ function part(name, geometry = {}, map) {function retainedRenderer(parts) {const writes = [];const renderer = Object.create(Renderer67.prototype);- const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 41).fill(7) };+ const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 41).fill(7), castShadow: true };renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData(target, offset, data) { writes.push({ target, offset, data: Array.from(data) }); } };renderer.partLocations = new Map(parts.map((item, index) => [item, {batch, index, geometry: item.geometry, map: item.material.map ?? null, normalMatrix: mat3.create(), skin: item.skin ?? null,@@ -44,6 +44,21 @@ test('batching shares geometry only when texture descriptor identities also matcassert.equal(groupParts(parts, false).length, 4);});+test('shadowless parts form separate render batches and cannot change casting after upload', () => {+ const geometry = {};+ const caster = part('caster', geometry);+ const window = { ...part('window', geometry), castShadow: false };+ const groups = groupParts([caster, window]);+ assert.equal(groups.length, 2);+ assert.equal(groups[0][0], caster);+ assert.equal(groups[1][0], window);+ const { renderer, writes } = retainedRenderer([caster]);+ caster.castShadow = false;+ assert.throws(() => renderer.updateParts([caster]), /Shadow casting/);+ assert.equal(writes.length, 0);+ assert.throws(() => groupParts([{ ...window, castShadow: 0 }]), /boolean/);+});+test('instance animation reuses retained buffers, updates inverse-transpose normals and RGB emission', () => {const parts = [part('moving'), part('static')];const { renderer, batch, writes } = retainedRenderer(parts);diff --git a/tests/volumetric.test.js b/tests/volumetric.test.jsnew file mode 100644index 00000000..f85df1ec--- /dev/null+++ b/tests/volumetric.test.js@@ -0,0 +1,22 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { resolveVolumeFog } from '../src/volumetric.js';+import { Renderer67 } from '../src/renderer.js';++test('bounded volume controls default disabled and preserve ordinary input data', () => {+ assert.equal(resolveVolumeFog().density, 0);+ const input = { density: 0.05, minimum: [-4, 0, -4], maximum: [4, 5, 4], color: [0.8, 0.6, 0.3], steps: 24 };+ const snapshot = structuredClone(input);+ const resolved = resolveVolumeFog(input);+ assert.equal(resolved.density, 0.05);+ assert.equal(resolved.steps, 24);+ assert.deepEqual(input, snapshot);+});++test('volume preflight rejects malformed controls and Float32 collapsed bounds', () => {+ for (const input of [null, [], { density: -1 }, { density: Infinity }, { steps: 7 }, { steps: 12.5 }, { noiseScale: 0 }, { noiseAmount: 1.01 }, { anisotropy: 1 }, { minimum: [1e5, 0, 0], maximum: [1e5 + 1e-8, 1, 1] }, { color: [1, NaN, 1] }, { drift: [0, '1', 0] }]) {+ assert.throws(() => resolveVolumeFog(input));+ }+ assert.throws(() => new Renderer67({}, [], { hdr: true, environment: { volumeFog: { density: 0.1 } } }), /depth:true/);+ assert.throws(() => new Renderer67({}, [], { hdr: true, depth: true, transparent: true, environment: { volumeFog: { density: 0.1 } } }), /opaque/);+});