From 741eb65d1803b80d73c3753615c3a0eba5990b88 Mon Sep 17 00:00:00 2001 From: Dennis Smolek Date: Wed, 2 Dec 2026 03:14:48 +0900 Subject: [PATCH] P1.4e: opt-in chunked scene copy data (packing 'split:KxN' / 'packed:KxN'), chooseSceneCopyPacking, bit-identical renders The data region splits over K storage bindings of 2^N words; word i is chunk i >> N (V515). The default packing, kernels (355 size-snapshot files) and buffers are untouched. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 1 + DIVERGES.md | 4 + TASKS.md | 2 +- bench/adapters/pt-megakernel/index.ts | 12 +- bench/adapters/registry.ts | 11 +- bench/kernel-variants.ts | 3 + bench/pages/competitor.ts | 1 + bench/pages/scene-copy.ts | 27 ++- bench/pages/vbuffer-check.ts | 6 +- bench/scenes/scene-chunks.test.ts | 65 +++++ docs/internal/QUIET-PASS.md | 1 + docs/raytracer/scene-copy.mdx | 16 +- examples/shared/trace-kernel.ts | 4 +- .../pathtracer/src/integrator/megakernel.ts | 11 +- .../src/integrator/scene-chunked.test.ts | 63 +++++ packages/pathtracer/src/restir/restir.ts | 5 +- .../pathtracer/src/wavefront/wavefront.ts | 6 +- packages/raytracer/src/scene/constants.ts | 58 ++++- packages/raytracer/src/scene/gpu-scene.ts | 16 +- packages/raytracer/src/scene/gpu.ts | 145 ++++++++++- .../raytracer/src/scene/scene-chunked.test.ts | 228 ++++++++++++++++++ packages/raytracer/src/scene/scene-copy.ts | 29 ++- packages/raytracer/src/scene/scene-wgsl.ts | 53 +++- .../raytracer/src/trace/interval-batch.ts | 5 +- packages/raytracer/src/trace/modules.ts | 8 +- 25 files changed, 716 insertions(+), 64 deletions(-) create mode 100644 bench/scenes/scene-chunks.test.ts create mode 100644 packages/pathtracer/src/integrator/scene-chunked.test.ts create mode 100644 packages/raytracer/src/scene/scene-chunked.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index ba9d2925..81e2b8df 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -460,6 +460,7 @@ To go back: restore `pnpm-workspace.yaml` and `pnpm install --offline` (or onlin equal split per pixel on 6 of 8 scenes and differ by <= 3.2e-7 relative (1-3 ulp, relMSE 3e-17) on IORTestGrid (both schedulers) and env-sphere (wavefront): not addressing (every accessor is bit-exact in `--page scene-copy packing=both`), a different compiled kernel contracts some float ops differently. `DEFAULT_SCENE_PACKING` is still `split`; `writeSceneCopy(device, buffers, copy)` rewrites a rebuilt copy in place for either packing (the packed one rewrites the whole buffer: the data region moves when the table length changes). +- Chunked scene copy data (P1.4e, V515-V518; `packing: 'packed:3x25'` / `'split:3x25'`, `chooseSceneCopyPacking`, bench `pt_scene_chunk=`): the packing STRING carries K and N, so a kernel, `uploadSceneCopy` and `setScene` agree through the one value; a copy rebuilt with a different data length may need another K (= another kernel): `writeSceneCopy` returns false. Data word `i` is in chunk `i >> N`; appended WGSL goes through `rtApplyScenePacking(source, packing)` (not `rtPackSceneAccess` alone: `split:KxN` keeps `rtSceneTable` and only rewrites `rtSceneData[..]`). Every chunk is a storage binding: on Apple (10 per stage) Sponza's 21 MiB needs chunks of 2^21 words (K = 3: megakernel and wavefront fit; 2^20 gave "11 > 10"), and Cornell (324 data words) shows the straddle at 2^7. Forced small chunks on small scenes are the test (`--page scene-copy chunk=7`, 0 mismatches; renders per-pixel bit-identical); no real > 128 MiB scene was built. - Optional integrator outputs (R10 hooks, R4 counters, AOVs; `integrator/outputs-wgsl.ts`): their template text must emit nothing (no blank line, no `\n`) when off. Two traps hit while adding them: a gated block ending in a newline placed before the original newline adds a blank line (the megakernel stayed identical but the wavefront shade kernel grew by one `\n`), so put the leading `\n` inside the gate for end-of-line additions (`x;${on ? `\n y;` : ''}`). `node bench/size-snapshot.ts` now writes the `wf-*` wavefront kernels too (`bench/kernel-variants.ts` `wavefrontKernelVariants`): `diff -r` two snapshot directories, ignore `Only in`. diff --git a/DIVERGES.md b/DIVERGES.md index 31bc9f09..8bae02f4 100644 --- a/DIVERGES.md +++ b/DIVERGES.md @@ -216,3 +216,7 @@ why, so each one can be revisited later. One row per divergence. Kinds: **platfo | V343 | 2026-11-26 | Pharr, Wronski, Salvi, Fajardo 2024 (stochastic texture filtering, Listing 1 / S.1: one uniform reused across the axes by rescaling); Wronski, Pharr, Akenine-Moller 2025 (texel sharing between wave lanes) | `volumes.densityFilter: 'stochastic'` (V7.6): stochastic trilinear density, one texel per lookup. Differences: THREE draws from the tracking stream (one per axis) instead of one rescaled uniform; zero outside the grid without a read; no texel sharing between lanes; no tricubic. | Simplification (independent 24-bit draws keep each axis' probability exact to 2^-24 with no division by a small fraction, and need no change to the megakernel / wavefront stream protocol; the two saved PCG steps were not measured). Sharing: the 2025 paper's own supplement reports block artifacts for ray-marched volumes, and our lanes are not neighbouring pixels after the first vertex. | | V345 | 2026-11-30 | Our own dense grid lookup and brick DDA (`ptVolDensity`, `ptDdaInit` / `ptDdaNext`, V3.2 / P5.v6) | `volumes.gridSource: 'nanovdb'` (VDB-P1.7) replaces both with `@pmndrs/vdb`'s WGSL (`vdbSample`, `vdbMajorantInit` / `vdbMajorantNext`) over the same voxels and the same cells. Two differences per path: the pool's walk never returns a zero-length segment at a cell corner (ours can, and `ptVolSampleBrick` / `ptVolTrBrick` stop on one), and the NanoVDB reader adds the eight taps in another order. Images are therefore not bit-equal to the dense kernel (77-86% of pixels are; relMSE 1e-15 to 1e-6 at equal seeds). The accessor was created per lookup in the first build; since pmndrs/vdb P1.16 (2026-11-30) the kernels keep one per ray segment, made at its first lookup, and the module caches the lower node (`cache: 'lower'`): the same values, images bit-identical to the first build's. | simplification / sibling | the timing A/B of the reader options (quiet pass, VDB-P1.10); cache `'lowerLeaf'` once VDB-P1.14 is understood | | V344 | 2026-11-26 | pmndrs/upscaler defaults (`RuntimeSettings.autoExposure` on) | The NRC / Classroom chain (`nrc-pipeline`, hero) runs the temporal upscaler with `autoExposure: false`, `exposure: 1` (page control **Auto pre-exposure**, `?upAutoExposure=1` for the sibling's default). | Quality. On a dim interior (mean luminance 0.12) the metered pre-exposure lifts the image so the brightest denoised pixels (10-20) sit at the top of the upscaler's invertible tonemap, where its Catmull-Rom history resample overshoots and `tonemapInvert` turns that into values up to 139 while the camera moves (17 hot pixels per 1920 x 1080 frame, both arms; 0 and max 11 with it off; nothing with a still camera either way). Sharpness 0, locks off and shading-change detection off do not remove it; history 4 nearly does. Off also darkens less against the denoised frame (-4% vs -6..7%; N11.5). Numbers: TASKS N11.11; `bench/hero/README.md` "Bright specks while moving". The cause is in the sibling (unclamped bicubic history in tonemapped space): report there. | +| V515 | 2026-12-02 | Issue #51 (P1.4e) suggestion: a per-mesh chunk id in the table, a mesh never straddling a chunk | Chunked scene copy data (`packing: 'split:KxN' \| 'packed:KxN'`) picks the chunk by the WORD index: chunk `i >> N`, word `i & (2^N - 1)` (`rtSceneWord`, N a power of two, so a shift and a mask, no division). Nothing in the data layout moves: the words, every offset in the table and the light maps, the fingerprint and the CPU twins are those of the unchunked copy, a mesh larger than a chunk works and an index triple, a vertex or an env-map texel may straddle a boundary (each word is its own lookup). The price is a switch over K cases per data word read (the chunk bindings are separate variables, WGSL has no binding array), which a per-mesh id would pay once per mesh. | simplification | a quiet-pass A/B of unchunked vs chunked K=2/3 on Sponza (QUIET-PASS P1.4e) says the per-word pick costs more than a few %: then build the per-mesh id (needs a per-mesh data layout and a chunk id threaded through `rtSIndex` / `rtSVertex`) | +| V516 | 2026-12-02 | `SceneCopyPacking` as an enum of two | The chunk layout lives in the packing string (`'packed:3x25'` = header + table in `rtScene`, data in `rtSceneData0..2` of 2^25 words; `'split:3x25'` with `rtSceneTable`), `chooseSceneCopyPacking` picks K from the size and the device limit. Every place that already passes a packing (kernel options, `uploadSceneCopy`, `setScene`'s mismatch check, layout entries, storage-buffer counts, `rtApplyScenePacking` of appended text) carries it with no new option; `DEFAULT_SCENE_PACKING` stays `'packed'` and the unchunked kernel text and buffers are byte-identical (355 size-snapshot files). | simplification | an options object is wanted by an API user (then a parsed form behind the same string) | +| V517 | 2026-12-02 | Issue #51 (chunk the data buffer) | Only the DATA is chunked. The table (header, instances, meshes, materials, lights, texture slots; packed: plus the header vec4) must still fit one binding: it is ~100-200 B per instance / material / light, so 128 MiB is about a million lights or instances. `chooseSceneCopyPacking` and `uploadSceneCopy` throw a RangeError that names it. A chunked copy rebuilt with a different data length may need another K, which is a different packing and so a new kernel: `writeSceneCopy` returns false then. | simplification | a scene with over ~1M lights or instances | +| V518 | 2026-12-02 | Chrome / Dawn storage-buffer limit per stage (10 on Apple Metal) | Every chunk costs one storage binding (`sceneCopyStorageBuffers` = 1 + K), so the useful K is small: the megakernel (packed, Cornell) fits 5 chunks, the wavefront shade kernel (7 buffers packed) 3, and Sponza's 21 MiB needs 8 MiB chunks (K = 3) on a 10-buffer stage. `chooseSceneCopyPacking` refuses with the numbers (scene buffers + `otherStorageBuffers` over `stageLimit`) before a kernel is built; `PtMegakernel.create` / `PtWavefront.create` add the chunk count to Dawn's layout error. Chunking is for scenes past 128 MiB (K <= 3-4 at 128 MiB chunks); past ~4-5 chunks a bindless buffer table or one 2+ GiB binding (`maxStorageBufferBindingSize` raised through `requiredLimits`, the caps ask for up to 2 GiB) is the better tool. | platform | WebGPU gets binding arrays / buffer tables for storage buffers | diff --git a/TASKS.md b/TASKS.md index 2b92e267..70530994 100644 --- a/TASKS.md +++ b/TASKS.md @@ -67,7 +67,7 @@ suggestion, pros/cons and the A/B that would settle it. | P1.4c6 | Textured emitters in NEE: sample by the texture's luminance (a second alias/CDF per emissive texture) instead of BSDF-only | — | ⬜ | today a textured emitter is excluded from the light table (V52) Issue [#52](https://github.com/pmndrs/pathtracer/issues/52). | | P1.4c7 | Textures on Windows: compile time of the textured kernel (DXC), the 16-texture limit with 8 arrays, `rgba8unorm-srgb` filtering precision on D3D12 | — | ⬜ Windows | **Audit 2026-11-26:** [#34](https://github.com/pmndrs/pathtracer/issues/34). add to the Windows handoff list | | P1.4d | Environment map: copy + power/CDF; converter's `hdriRadiance` from the PFM mean | agent:envmap | ✅ | `packages/raytracer/src/scene/env-map.ts` (+ test): equirect texels, marginal/conditional CDF, f64 TS twins; map words in the scene copy `data` buffer after the light maps (no new binding), location in the env light record (words 8-10); `radiance` = sin θ-weighted map mean (power + constant fallback); converter option `hdriMap`. V48 | -| P1.4e | Chunk the data buffer past `maxStorageBufferBindingSize` (128 MiB) | — | ⬜ | `uploadSceneCopy` throws a clear error today Issue [#51](https://github.com/pmndrs/pathtracer/issues/51). | +| P1.4e | Chunk the data buffer past `maxStorageBufferBindingSize` (128 MiB) | agent:chunked-scene | ✅ opt-in (default unchanged) | `packing: 'split:KxN' \| 'packed:KxN'` (constants.ts), `chooseSceneCopyPacking` (K from size + device limit, refuses over the stage budget), `uploadSceneCopy` / `writeSceneCopy` / bind entries / layout entries, WGSL `rtSceneWord` chunk pick (V515-V518). Checks: `scene-chunked.test.ts` x2 + `bench/scenes/scene-chunks.test.ts`; `--page scene-copy chunk=7..11` 0 mismatches (both table placements, 5 chunks of 128 words on Cornell incl. surface decode across boundaries); renders `pt_scene_chunk=7` Cornell and `=21` (K = 3) Sponza, megakernel and wavefront, packed and split: ALL per-pixel bit-identical to unchunked (0 differing values of 0.8-2.8 M). Default kernels: 355 size-snapshot files `diff -rq` empty (packed and split). Open: timing of the per-word switch (QUIET-PASS P1.4e: `pt-mk-chunk` / `pt-wf-chunk`), a real > 128 MiB scene (none built; the chunk path is exercised with forced small chunks), per-mesh chunk id alternative (V515) only if the switch costs. Issue [#51](https://github.com/pmndrs/pathtracer/issues/51) (the other rows of it, P1.4b / P1.5a, are open). | | P1.4f | A/B light selection (power vs uniform-per-kind vs capped infinite lights 0.25/0.5, plus pbrt-v4's rule) | — | ✅ default `pbrt` (D22) | relMSE at 1024 spp, 3 seeds (pbrt / power / kind / cap:0.25 / cap:0.5): Cornell, quad-light, env-sphere identical; sponza-white 9.33e-3 / 8.12e-3 / 9.33e-3 / 8.12e-3 / 8.12e-3; `lights-mix` (sun+sky key) 1.67e-5 / 2.10e-5 / 1.67e-5 / 2.44e-5 / 1.29e-5; `lights-mix-lamps` 1.30e-4 / 8.69e-5 / 1.30e-4 / 6.14e-5 / 8.69e-5. Means within 0.03% everywhere. `pbrt` = `kind` on all these scenes (one area kind). Maintainer chose the common rule over `cap:0.5`. Follow-up: a light BVH for the area share (P3/P4) | | P1.4g | Light point sampling | agent:integrator | ✅ | `packages/raytracer/src/scene/light-sample.ts` (`rtSceneWgsl({ sampling: true })`): uniform area on emissive triangles, solid-angle pdf `dist²/(\|cos_l\| area)` (pmf applied by the caller), sun cone (delta at radius 0), uniform environment sphere. 26 CPU tests (E[1/pdf] = analytic quad solid angle; MC irradiance vs closed form to 2e-4). GPU `pt-check`: 0 mismatches, max rel 1.3e-5 | | P1.4h | GPU checks for alpha mask/blend once a consumer reads them | — | ⬜ | Issue [#52](https://github.com/pmndrs/pathtracer/issues/52). | diff --git a/bench/adapters/pt-megakernel/index.ts b/bench/adapters/pt-megakernel/index.ts index 64110ce6..285bc5bf 100644 --- a/bench/adapters/pt-megakernel/index.ts +++ b/bench/adapters/pt-megakernel/index.ts @@ -13,7 +13,7 @@ */ import { benchAssets, blueNoiseAssets } from '../../site-paths.ts'; import { buildTraceScene, createMeshBvhBuilder, uploadTraceScene, type NodeFormat, type TraceSceneBuffers } from '@pmndrs/bvh'; -import { ALPHA_MODE, fetchBlueNoise, createMaterial, detectCaps, requestDeviceForCaps, sceneFormatOf, uploadSceneCopy, buildSceneCopy, lightSelectionName, DEFAULT_LIGHT_SELECTION, type Caps, type LightSelection, type SceneCopy, type SceneCopyBuffers, type SceneCopyInput } from '@pmndrs/raytracer'; +import { ALPHA_MODE, fetchBlueNoise, createMaterial, detectCaps, requestDeviceForCaps, sceneFormatOf, uploadSceneCopy, chooseSceneCopyPacking, buildSceneCopy, lightSelectionName, DEFAULT_LIGHT_SELECTION, type Caps, type LightSelection, type SceneCopy, type SceneCopyBuffers, type SceneCopyInput } from '@pmndrs/raytracer'; import { sceneDensityFiles, sceneVolumes } from '../../scenes/volumes.ts'; import type { NanovdbBuild } from '../../scenes/volumes/vdb-nanovdb.ts'; @@ -134,6 +134,8 @@ export interface PtAdapterSettings extends PtIntegratorOptions { layers?: number; /** Scene copy binding (P3.11): `split` (two storage buffers) or `packed` (one). Default: the library default (`DEFAULT_SCENE_PACKING`, `packed` since D32). Images are per-pixel identical; only the addressing differs. */ scenePacking?: 'split' | 'packed'; + /** P1.4e (page arg `pt_scene_chunk=`): force the chunked scene copy with data chunks of `2^N` words (`chooseSceneCopyPacking`, table placement = `scenePacking`): a check of the chunked addressing on a scene that would fit one binding. */ + sceneChunkLog2?: number; /** bvh scene options (X1.i, D25; page args `pt_bvh`, `pt_bvh_decode`, `pt_bvh_walk`): `nodeFormat` `quantized` (default) | `f32` | the experimental wide `bvh4` | `cwbvh8` (hits are the same, tie order aside); `decode` `exact` | `folded` (wide only, default folded); `walk` `nested` | `single` (bvh4 only). */ /** Texture mip levels (X5, page arg `pt_mips`): `gpu` (default since D34: level 0 only on the CPU, levels 1+ by `@pmndrs/downsampler` in `uploadSceneCopy`; codes differ from the CPU chain by up to 2) or `cpu` (every level built in `buildSceneTextures`). */ mips?: 'cpu' | 'gpu'; @@ -249,6 +251,8 @@ export class PtMegakernelAdapter implements RendererAdapter { private kernel: PtMegakernel | PtWavefront | null = null; private trace: TraceSceneBuffers | null = null; private sceneBuffers: SceneCopyBuffers | null = null; + /** The packing the kernels are built with (`scenePacking`, or the chunked one `sceneChunkLog2` chose); undefined = the library default. */ + private packing: SceneCopyBuffers['packing'] | undefined; private scene: SceneDesc | null = null; private lastStats: Record = {}; private limits: { maxDepth: number; rrStartDepth?: number; maxVolumeDepth?: number } = { maxDepth: 1 }; @@ -335,6 +339,7 @@ export class PtMegakernelAdapter implements RendererAdapter { ...(settings.volumeGridFormat ? { volumeGridFormat: settings.volumeGridFormat } : {}), ...(settings.primary === 'vbuffer' ? { primary: 'vbuffer' } : {}), ...(settings.scenePacking ? { scenePacking: settings.scenePacking } : {}), + ...(settings.sceneChunkLog2 !== undefined ? { sceneChunkLog2: settings.sceneChunkLog2 } : {}), ...(settings.bvh && Object.keys(settings.bvh).length ? { bvh: settings.bvh } : {}), ...(settings.mips === 'cpu' ? { mips: 'cpu' } : {}), ...(settings.textureBinding === 'table' ? { textureBinding: 'table' } : {}), @@ -457,7 +462,8 @@ export class PtMegakernelAdapter implements RendererAdapter { this.trace = uploadTraceScene(device, data, scene.name); const textureOptions = { ...(this.settings.mips === 'cpu' ? { mips: 'cpu' as const } : {}), ...(this.settings.textureBinding === 'table' ? { binding: 'table' as const } : {}) }; const copy = buildSceneCopy({ ...input, options: { ...input.options, ...(Object.keys(textureOptions).length ? { textures: { ...input.options?.textures, ...textureOptions } } : {}), ...(this.settings.lightSelection ? { lightSelection: this.settings.lightSelection } : {}), surface: { ...input.options?.surface, positions: (this.settings.positions ?? 'barycentric') === 'barycentric' } } }); - this.sceneBuffers = uploadSceneCopy(device, copy, { label: `${scene.name} scene`, ...(this.settings.scenePacking ? { packing: this.settings.scenePacking } : {}) }); + this.packing = this.settings.sceneChunkLog2 !== undefined ? chooseSceneCopyPacking(device, copy, { chunkWordsLog2: this.settings.sceneChunkLog2, ...(this.settings.scenePacking ? { base: this.settings.scenePacking } : {}) }) : this.settings.scenePacking; + this.sceneBuffers = uploadSceneCopy(device, copy, { label: `${scene.name} scene`, ...(this.packing ? { packing: this.packing } : {}) }); this.lastLoad = { caps, copy, input }; const loadMs = performance.now() - t0; @@ -528,7 +534,7 @@ export class PtMegakernelAdapter implements RendererAdapter { this.nano?.pool.dispose(); this.nano = nano; const spectralTable = integratorSettings.spectral ? await fetchSpectralTable(typeof integratorSettings.spectral === 'object' ? integratorSettings.spectral.res ?? 64 : 64) : undefined; - const kernelOptions = { ...(nano ? { volumeNanovdb: nano.pool } : {}), ...(volumes?.grid && !nano ? { volumeGrid: { ...volumes.grid, ...(this.settings.volumeGridFormat === 'r16float' ? { format: 'r16float' as const } : this.settings.volumeGridFormat === 'r8unorm' ? { format: 'r8unorm' as const, scale: volumes.options.media.find((m) => m.grid)?.grid?.densityScale } : {}), ...(this.settings.volumeMajorant === 'brick' ? { majorant: brickMajorants(volumes.grid.resolution, volumes.grid.density, (this.settings.volumeShadow === 'residual' || this.settings.volumeShadow === 'telescoping' || this.settings.volumeFreeFlight === 'decomposition') ? { minima: true } : {}) } : {}) } } : {}), ...(spectralTable ? { spectralTable } : {}), ...(this.settings.mode ? { mode: this.settings.mode } : {}), ...(blueNoise ? { blueNoise } : {}), format: sceneFormatOf({ nodeFormat: this.trace.nodeFormat, triangleLeaves: this.trace.triangleLeaves, positionLayout: this.trace.positionLayout, ...(this.settings.bvh?.decode ? { wideDecode: this.settings.bvh.decode } : {}), ...(this.settings.bvh?.walk ? { wideWalk: this.settings.bvh.walk } : {}) }), layout: copy.layout, textures: copy.textureLayout, ...(this.settings.scenePacking ? { scenePacking: this.settings.scenePacking } : {}), integrator: { ...integratorSettings, ...(alphaMask ? { alphaMask } : {}), ...(alphaMask && (this.settings.alphaShadow === 'coverage' || this.settings.alphaShadow === 'stochastic') ? { alphaCoverage: this.settings.alphaCoverage ?? alphaCoverageOf(input) } : {}), envMap: !!hdriMap, envSampling: this.envSampling(!!hdriMap), materials, ...(mtlx ? { materialx: { wgsl: mtlx.programs.wgsl, normal: mtlx.programs.normal } } : {}), ...(volumes ? { volumes: { ...volumes.options, ...(this.settings.maxVolumeDepth !== undefined ? { separateDepth: true } : {}), ...(this.settings.volumeShadow ? { shadowTracking: this.settings.volumeShadow } : {}), ...(this.settings.volumeMajorant ? { majorant: this.settings.volumeMajorant } : {}), ...(this.settings.volumeFreeFlight ? { freeFlight: this.settings.volumeFreeFlight } : {}), ...(this.settings.volumeTrRoulette ? { trRoulette: true } : {}), ...(this.settings.volumeForcedNee ? { forcedNee: true } : {}), ...(this.settings.volumeMarch ? { marchSamples: this.settings.volumeMarch } : {}), ...(this.settings.volumeEquiangular ? { equiangular: true } : {}), ...(this.settings.volumeForcedGrid ? { forcedGrid: true } : {}), ...(this.settings.volumeGuiding === 'vspg' ? { guiding: 'vspg' as const } : {}), ...(this.settings.volumeDensityFilter === 'hardware' ? { densityFilter: 'hardware' as const } : this.settings.volumeDensityFilter === 'stochastic' ? { densityFilter: 'stochastic' as const } : {}), ...(this.settings.volumeGridLayout === 'atlas' ? { gridLayout: 'atlas' as const } : {}), ...(nano ? { gridSource: 'nanovdb' as const, nanovdb: { wgsl: nano.wgsl, ...(this.settings.volumeNanovdbAccessor === 'lookup' ? { accessor: 'lookup' as const } : {}) }, media: volumes.options.media.map((m) => (m.grid ? { ...m, grid: { ...m.grid, gridId: nano.gridId } } : m)) } : {}), ...(this.settings.volumeOutputs ? { outputs: true } : {}) } } : {}) }, ...(this.settings.prune !== undefined ? { prune: this.settings.prune } : {}), ...(this.settings.shortenNames !== undefined ? { shortenNames: this.settings.shortenNames } : {}), label: this.info.id }; + const kernelOptions = { ...(nano ? { volumeNanovdb: nano.pool } : {}), ...(volumes?.grid && !nano ? { volumeGrid: { ...volumes.grid, ...(this.settings.volumeGridFormat === 'r16float' ? { format: 'r16float' as const } : this.settings.volumeGridFormat === 'r8unorm' ? { format: 'r8unorm' as const, scale: volumes.options.media.find((m) => m.grid)?.grid?.densityScale } : {}), ...(this.settings.volumeMajorant === 'brick' ? { majorant: brickMajorants(volumes.grid.resolution, volumes.grid.density, (this.settings.volumeShadow === 'residual' || this.settings.volumeShadow === 'telescoping' || this.settings.volumeFreeFlight === 'decomposition') ? { minima: true } : {}) } : {}) } } : {}), ...(spectralTable ? { spectralTable } : {}), ...(this.settings.mode ? { mode: this.settings.mode } : {}), ...(blueNoise ? { blueNoise } : {}), format: sceneFormatOf({ nodeFormat: this.trace.nodeFormat, triangleLeaves: this.trace.triangleLeaves, positionLayout: this.trace.positionLayout, ...(this.settings.bvh?.decode ? { wideDecode: this.settings.bvh.decode } : {}), ...(this.settings.bvh?.walk ? { wideWalk: this.settings.bvh.walk } : {}) }), layout: copy.layout, textures: copy.textureLayout, ...(this.packing ? { scenePacking: this.packing } : {}), integrator: { ...integratorSettings, ...(alphaMask ? { alphaMask } : {}), ...(alphaMask && (this.settings.alphaShadow === 'coverage' || this.settings.alphaShadow === 'stochastic') ? { alphaCoverage: this.settings.alphaCoverage ?? alphaCoverageOf(input) } : {}), envMap: !!hdriMap, envSampling: this.envSampling(!!hdriMap), materials, ...(mtlx ? { materialx: { wgsl: mtlx.programs.wgsl, normal: mtlx.programs.normal } } : {}), ...(volumes ? { volumes: { ...volumes.options, ...(this.settings.maxVolumeDepth !== undefined ? { separateDepth: true } : {}), ...(this.settings.volumeShadow ? { shadowTracking: this.settings.volumeShadow } : {}), ...(this.settings.volumeMajorant ? { majorant: this.settings.volumeMajorant } : {}), ...(this.settings.volumeFreeFlight ? { freeFlight: this.settings.volumeFreeFlight } : {}), ...(this.settings.volumeTrRoulette ? { trRoulette: true } : {}), ...(this.settings.volumeForcedNee ? { forcedNee: true } : {}), ...(this.settings.volumeMarch ? { marchSamples: this.settings.volumeMarch } : {}), ...(this.settings.volumeEquiangular ? { equiangular: true } : {}), ...(this.settings.volumeForcedGrid ? { forcedGrid: true } : {}), ...(this.settings.volumeGuiding === 'vspg' ? { guiding: 'vspg' as const } : {}), ...(this.settings.volumeDensityFilter === 'hardware' ? { densityFilter: 'hardware' as const } : this.settings.volumeDensityFilter === 'stochastic' ? { densityFilter: 'stochastic' as const } : {}), ...(this.settings.volumeGridLayout === 'atlas' ? { gridLayout: 'atlas' as const } : {}), ...(nano ? { gridSource: 'nanovdb' as const, nanovdb: { wgsl: nano.wgsl, ...(this.settings.volumeNanovdbAccessor === 'lookup' ? { accessor: 'lookup' as const } : {}) }, media: volumes.options.media.map((m) => (m.grid ? { ...m, grid: { ...m.grid, gridId: nano.gridId } } : m)) } : {}), ...(this.settings.volumeOutputs ? { outputs: true } : {}) } } : {}) }, ...(this.settings.prune !== undefined ? { prune: this.settings.prune } : {}), ...(this.settings.shortenNames !== undefined ? { shortenNames: this.settings.shortenNames } : {}), label: this.info.id }; // D32: `auto` also routes a megakernel over the ~50 KB DXC class to the wavefront (the kernel text is only known here, after the materials / textures are decided). if (this.autoReason !== '' && this.settings.scheduler !== 'wavefront' && !volumes && !integratorSettings.spectral) { const kernelBytes = ptMegakernelWgsl(caps, ptApplyMode(kernelOptions as unknown as PtMegakernelOptions)).length; diff --git a/bench/adapters/registry.ts b/bench/adapters/registry.ts index 1e697cef..945ac347 100644 --- a/bench/adapters/registry.ts +++ b/bench/adapters/registry.ts @@ -8,7 +8,7 @@ import type { SceneDesc } from '../scenes/schema.ts'; export const ADAPTER_IDS = ['tgpt-wavefront', 'tgpt-megakernel', 'mutracer'] as const; export type AdapterId = (typeof ADAPTER_IDS)[number]; /** Our own renderers: valid for `--renderers`, but not in the default competitor set. */ -export const OWN_ADAPTER_IDS = ['pt-megakernel', 'pt-wavefront', 'pt-wf-refill', 'pt-wf-batch', 'pt-wf-refill-l2', 'pt-wf-refill-l4', 'pt-wf-batch-l2', 'pt-mk-shadow', 'pt-mk-indirect', 'pt-mk-secondary', 'pt-wf-shadow', 'pt-wf-indirect', 'pt-wf-secondary', 'pt-mk-vbuffer', 'pt-wf-vbuffer', 'pt-mk-packed', 'pt-wf-packed', 'pt-mk-lay-stoch', 'pt-mk-lay-int', 'pt-mk-lay-lut', 'pt-mk-lay-tex', 'pt-wf-lay-int', 'pt-wf-lay-lut', 'pt-wf-lay-tex', 'pt-mk-lod', 'pt-wf-lod', 'pt-mk-transmit', 'pt-mk-transmit0', 'pt-mk-transmit1', 'pt-wf-transmit', 'pt-wf-transmit0', 'pt-wf-transmit1', 'pt-mk-roulette', 'pt-mk-roulette10', 'pt-mk-roulette50', 'pt-mk-coverage', 'pt-mk-stochastic', 'pt-mk-firstk', 'pt-mk-firstk2', 'pt-mk-classified', 'pt-wf-roulette', 'pt-wf-roulette10', 'pt-wf-roulette50', 'pt-wf-coverage', 'pt-wf-stochastic', 'pt-wf-firstk', 'pt-wf-firstk2', 'pt-wf-classified', 'pt-wf-sg', 'pt-wf-sort-mat', 'pt-wf-sort-oct', 'pt-wf-sort-both', 'pt-wf-refill-sg', 'pt-wf-ordered', 'pt-wf-ordered-sg', 'pt-wf-ordered-l2', 'pt-wf-ordered-l4', 'pt-wf-refill-lod', 'pt-wf-ordered-lod', 'pt-auto'] as const; +export const OWN_ADAPTER_IDS = ['pt-megakernel', 'pt-wavefront', 'pt-wf-refill', 'pt-wf-batch', 'pt-wf-refill-l2', 'pt-wf-refill-l4', 'pt-wf-batch-l2', 'pt-mk-shadow', 'pt-mk-indirect', 'pt-mk-secondary', 'pt-wf-shadow', 'pt-wf-indirect', 'pt-wf-secondary', 'pt-mk-vbuffer', 'pt-wf-vbuffer', 'pt-mk-packed', 'pt-wf-packed', 'pt-mk-chunk', 'pt-wf-chunk', 'pt-mk-lay-stoch', 'pt-mk-lay-int', 'pt-mk-lay-lut', 'pt-mk-lay-tex', 'pt-wf-lay-int', 'pt-wf-lay-lut', 'pt-wf-lay-tex', 'pt-mk-lod', 'pt-wf-lod', 'pt-mk-transmit', 'pt-mk-transmit0', 'pt-mk-transmit1', 'pt-wf-transmit', 'pt-wf-transmit0', 'pt-wf-transmit1', 'pt-mk-roulette', 'pt-mk-roulette10', 'pt-mk-roulette50', 'pt-mk-coverage', 'pt-mk-stochastic', 'pt-mk-firstk', 'pt-mk-firstk2', 'pt-mk-classified', 'pt-wf-roulette', 'pt-wf-roulette10', 'pt-wf-roulette50', 'pt-wf-coverage', 'pt-wf-stochastic', 'pt-wf-firstk', 'pt-wf-firstk2', 'pt-wf-classified', 'pt-wf-sg', 'pt-wf-sort-mat', 'pt-wf-sort-oct', 'pt-wf-sort-both', 'pt-wf-refill-sg', 'pt-wf-ordered', 'pt-wf-ordered-sg', 'pt-wf-ordered-l2', 'pt-wf-ordered-l4', 'pt-wf-refill-lod', 'pt-wf-ordered-lod', 'pt-auto'] as const; /** Wavefront scheduling presets (P3.2): the same adapter with `refill` / `layers` set, so `matrix.ts --interleave` can A/B them in one run. `--extra pt_refill=...` still overrides. */ const WAVEFRONT_PRESETS = { 'pt-wf-refill': { refill: 'inline' }, @@ -79,6 +79,12 @@ const PACKED_PRESETS = { 'pt-wf-packed': { scenePacking: 'packed', scheduler: 'wavefront' }, } as const; +/** Chunked scene copy data (P1.4e): the packed scene copy with the data in chunks of 2^21 words (8 MiB; Sponza K = 3, Cornell K = 1), to A/B against `pt-megakernel` / `pt-wavefront` (V515's per-word chunk pick costs a switch per data word). */ +const CHUNK_PRESETS = { + 'pt-mk-chunk': { sceneChunkLog2: 21 }, + 'pt-wf-chunk': { sceneChunkLog2: 21, scheduler: 'wavefront' }, +} as const; + /** Layered-BSDF presets (P2.32b): the stochastic walk and the albedo layering (internal base) without (`none`) / with the fitted correction (the library default since D32 is `texture`), so `matrix.ts --interleave` can A/B them in one run. */ const LAYERING_PRESETS = { 'pt-mk-lay-stoch': { layering: 'stochastic' }, @@ -165,6 +171,9 @@ export async function createAdapter(id: string, options: AdapterOptions = {}): P case 'pt-mk-packed': case 'pt-wf-packed': return (await import('./pt-megakernel/index.ts')).createPtMegakernel({ ...PACKED_PRESETS[id], ...options.pt }, id); + case 'pt-mk-chunk': + case 'pt-wf-chunk': + return (await import('./pt-megakernel/index.ts')).createPtMegakernel({ ...CHUNK_PRESETS[id], ...options.pt }, id); case 'pt-mk-lay-stoch': case 'pt-mk-lay-int': case 'pt-mk-lay-lut': diff --git a/bench/kernel-variants.ts b/bench/kernel-variants.ts index 214984df..b9816243 100644 --- a/bench/kernel-variants.ts +++ b/bench/kernel-variants.ts @@ -25,6 +25,9 @@ export function kernelVariants(caps: Caps, scenePacking?: SceneCopyPacking): Ker const textures = { buckets: [bucket(false), bucket(true), bucket(true, 'clamp')] }; const variants: Record string> = { plain: () => mk(caps, { format: {}, layout }), + // P1.4e chunked scene copy data (3 chunks of 2^25 words = 128 MiB; the table in rtScene or rtSceneTable): new files, every other variant stays byte-identical. Not affected by the packing argument. + 'chunked-packed': () => ptMegakernelWgsl(caps, { format: {}, layout, scenePacking: 'packed:3x25' }), + 'chunked-split': () => ptMegakernelWgsl(caps, { format: {}, layout, scenePacking: 'split:3x25' }), env: () => mk(caps, { format: {}, layout, integrator: { envMap: true, envSampling: 'importance' } }), pcg: () => mk(caps, { format: {}, layout, integrator: { sampler: 'pcg', nee: false } }), readable: () => mk(caps, { format: {}, layout, minify: false, shortenNames: false }), diff --git a/bench/pages/competitor.ts b/bench/pages/competitor.ts index c241cdb1..5ae3e7e0 100644 --- a/bench/pages/competitor.ts +++ b/bench/pages/competitor.ts @@ -131,6 +131,7 @@ try { ...(args['pt_alpha_policy'] ? { alphaPolicy: args['pt_alpha_policy'] as 'exact' | 'opaqueShadow' | 'opaqueIndirect' | 'opaqueSecondary' } : {}), ...(args['pt_mode'] ? { mode: args['pt_mode'] as 'reference' | 'preview' | 'realtime' } : {}), ...(args['pt_packing'] ? { scenePacking: args['pt_packing'] as 'split' | 'packed' } : {}), + ...(args['pt_scene_chunk'] ? { sceneChunkLog2: numberArg(args, 'pt_scene_chunk', 14) } : {}), ...(args['pt_bvh'] || args['pt_bvh_decode'] || args['pt_bvh_walk'] ? { bvh: { ...(args['pt_bvh'] ? { nodeFormat: args['pt_bvh'] as NodeFormat } : {}), ...(args['pt_bvh_decode'] ? { decode: args['pt_bvh_decode'] as 'exact' | 'folded' } : {}), ...(args['pt_bvh_walk'] ? { walk: args['pt_bvh_walk'] as 'nested' | 'single' } : {}) } } : {}), ...(args['pt_mips'] ? { mips: args['pt_mips'] as 'cpu' | 'gpu' } : {}), ...(args['pt_tex_binding'] ? { textureBinding: args['pt_tex_binding'] as 'arrays' | 'table' } : {}), diff --git a/bench/pages/scene-copy.ts b/bench/pages/scene-copy.ts index 0da31bd9..d0d0ce21 100644 --- a/bench/pages/scene-copy.ts +++ b/bench/pages/scene-copy.ts @@ -14,6 +14,9 @@ * * Args: scenes=cornell,quad-light,mixed,many-lights lights=20000 (size of the stress scene) packing=both|split|packed (P3.11: `packed` binds the * scene copy as ONE storage buffer, header + table + data; every check above runs on both and must stay bit-exact; `tRaw` also reads raw table / data words) + * chunk= (P1.4e, V515): every check again with the data split over chunks of 2^log2 words (`chooseSceneCopyPacking`, both table placements): `rtSceneData0..K-1` + * bindings, one pick per word. The first and last word of every chunk are read raw on top of the random sample. A small scene needs a small log2 (the many-lights scene's data + * is ~100 KB: `chunk=12` = 16 KiB chunks), and K + the page's 2 io buffers must fit the stage (the page asks for at most 10, Chrome on Apple's cap). */ import { SCENE_HEADER, @@ -28,12 +31,14 @@ import { readLightIndexOfHit, readLightPmfOfHit, readMaterial, + chooseSceneCopyPacking, + rtApplyScenePacking, + parseScenePacking, readSurfaceFromTable, requestDeviceForCaps, rtModuleWgsl, rtSceneCopyBindGroupEntries, rtSceneCopyLayoutEntries, - rtPackSceneAccess, sampleAlias, type SceneCopyPacking, uploadSceneCopy, @@ -416,8 +421,15 @@ async function checkScene(name: string, copy: SceneCopy, input: SceneCopyInput, const tableVec4s = copy.table.length / 4; const n = 5000; const pairs = new Uint32Array(n * 2); + // Chunked data: the words on both sides of every chunk boundary come first (chunk c starts at c * 2^N). + const { chunks, chunkWordsLog2 } = parseScenePacking(scene.packing); + const edges: number[] = []; + for (let c = 1; c < chunks; c++) { + const b = c * 2 ** chunkWordsLog2; + if (b < copy.data.length) edges.push(b - 1, b); + } for (let i = 0; i < n; i++) { - pairs[i * 2] = i === 0 ? 0 : i === 1 ? copy.data.length - 1 : Math.floor(rnd() * copy.data.length); + pairs[i * 2] = i === 0 ? 0 : i === 1 ? copy.data.length - 1 : i - 2 < edges.length ? (edges[i - 2] as number) : Math.floor(rnd() * copy.data.length); pairs[i * 2 + 1] = i === 0 ? 0 : i === 1 ? tableVec4s - 1 : Math.floor(rnd() * tableVec4s); } const raw = await runner.run('tRaw', pairs, n, n * 5, scene); @@ -558,7 +570,9 @@ try { const lightsCount = numberArg(args, 'lights', 20000); const packingArg = args.packing ?? 'both'; if (!['both', 'split', 'packed'].includes(packingArg)) throw new Error(`packing must be both, split or packed, got '${packingArg}'`); - const packings: SceneCopyPacking[] = packingArg === 'both' ? ['split', 'packed'] : [packingArg as SceneCopyPacking]; + const bases: Array<'split' | 'packed'> = packingArg === 'both' ? ['split', 'packed'] : [packingArg as 'split' | 'packed']; + const chunkLog2 = args.chunk ? numberArg(args, 'chunk', 12) : undefined; + const packings: string[] = chunkLog2 === undefined ? bases : bases.map((b) => `${b}:chunked${chunkLog2}`); if (!navigator.gpu) throw new Error('navigator.gpu is undefined: no WebGPU in this browser.'); const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' }); @@ -574,17 +588,20 @@ try { let moduleBytes = 0; for (const name of sceneNames) { const { copy, input } = loadScene(name, lightsCount); - for (const packing of packings) { + for (const base of bases) { + // chunk=N: the packing is chosen per scene (K depends on the data), 'split:KxN' / 'packed:KxN'; the page's io group takes 2 more storage buffers (stageLimit 10: Chrome on Apple). + const packing: SceneCopyPacking = chunkLog2 === undefined ? base : chooseSceneCopyPacking(device, copy, { base, chunkWordsLog2: chunkLog2, otherStorageBuffers: 2, stageLimit: Math.min(10, device.limits.maxStorageBuffersPerShaderStage) }); const key = `${packing}/${copy.layout.normals}/${copy.layout.uvs}/${copy.layout.positions}`; let runner = runners.get(key); if (!runner) { // The full inline module: bvh walk (never called here), core, scene copy at group 2, then the test kernels (rewritten for the packed binding). - const code = rtModuleWgsl(caps, { scene: { slot: { group: 2, firstBinding: 0 }, layout: copy.layout, packing } }) + (packing === 'packed' ? rtPackSceneAccess(KERNELS) : KERNELS); + const code = rtModuleWgsl(caps, { scene: { slot: { group: 2, firstBinding: 0 }, layout: copy.layout, packing } }) + rtApplyScenePacking(KERNELS, packing); runner = await makeRunner(device, code, packing); runners.set(key, runner); moduleBytes = Math.max(moduleBytes, runner.bytes); } const gpu = uploadSceneCopy(device, copy, { label: `${name} ${packing}`, packing }); + tally.expectEqual('chunk_count', `${name}/${packing}`, [gpu.dataChunks ? gpu.dataChunks.length : 0], [parseScenePacking(packing).chunks]); const before = tally.mismatches.length; await checkScene(`${name}/${packing}`, copy, input, runner, gpu, tally); // In-place rewrite (reflections' `setTransforms` / `setLights` pattern): a rebuilt copy with a brighter sun into the same buffers, every check again. diff --git a/bench/pages/vbuffer-check.ts b/bench/pages/vbuffer-check.ts index eed6142c..2ac7d15d 100644 --- a/bench/pages/vbuffer-check.ts +++ b/bench/pages/vbuffer-check.ts @@ -12,7 +12,7 @@ * Args: scenes=cornell,MetalRoughSpheres,tex-mask,sponza-white spp=1024 check=raster,resolve,image jitters=3 specpp=16 */ import { PT_VBUFFER_NO_MATERIAL, ptCameraBasis, ptCameraDirection, ptVbufferPack, ptVbufferResolve, ptVbufferUnpack, ptVbufferWgsl, ptRaytracerModuleOptions } from '@pmndrs/pathtracer'; -import { DEFAULT_SCENE_PACKING, type SceneCopyPacking } from '@pmndrs/raytracer'; +import { DEFAULT_SCENE_PACKING } from '@pmndrs/raytracer'; import { RtBatchTracer, rtPackSceneAccess, rtModuleWgsl, rtSceneBindGroupEntries, rtSceneCopyBindGroupEntries, rtSceneCopyLayoutEntries, rtWalkEntries, sceneFormatOf, withBindings } from '@pmndrs/raytracer'; import type { AdapterSummary } from '../runner/contract.ts'; import { getArgs, numberArg, reportError, reportResult, summarizeAdapter, watchDevice } from '../runner/page-client.ts'; @@ -21,7 +21,7 @@ import { compareImages } from '../metrics/metrics.ts'; import { PtMegakernelAdapter, type PtAdapterSettings } from '../adapters/pt-megakernel/index.ts'; /** Scene copy binding (P3.11, page arg `packing=split|packed`, default: the library default, packed since D32). */ -let PACKING: SceneCopyPacking = DEFAULT_SCENE_PACKING; +let PACKING: 'split' | 'packed' = DEFAULT_SCENE_PACKING; const rtPackIf = (code: string): string => (PACKING === 'packed' ? rtPackSceneAccess(code) : code); let adapterSummary: AdapterSummary | null = null; @@ -367,7 +367,7 @@ try { void watchDevice; const scenes = (args.scenes ?? 'cornell,MetalRoughSpheres,tex-mask,sponza-white').split(','); if (args.packing && args.packing !== 'split' && args.packing !== 'packed') throw new Error(`packing must be split or packed, got '${args.packing}'`); - PACKING = (args.packing as SceneCopyPacking | undefined) ?? DEFAULT_SCENE_PACKING; + PACKING = (args.packing as 'split' | 'packed' | undefined) ?? DEFAULT_SCENE_PACKING; const only = (args.check ?? 'raster,resolve,image').split(','); for (const name of scenes) { if (only.includes('raster')) await checkRaster(name, jitters); diff --git a/bench/scenes/scene-chunks.test.ts b/bench/scenes/scene-chunks.test.ts new file mode 100644 index 00000000..bb6bfc33 --- /dev/null +++ b/bench/scenes/scene-chunks.test.ts @@ -0,0 +1,65 @@ +/** + * P1.4e: chunked scene copy data on the bench scenes. Forced small chunks (Cornell: 512 B, 128 B; Sponza: 64 KiB, 8 MiB) on the Cornell box and (when the model is downloaded) Sponza: + * every data word reads back through its chunk, the generated `rtSceneWord` (parsed back out of the WGSL text) picks the same chunk and word as the twin, + * the table is not touched, and the stage budget refuses chunk counts the device cannot bind. The GPU check is `--page scene-copy chunk=14`, the render check + * is `pt_scene_chunk=14` (docs/internal/design in TASKS P1.4e). + */ +import { existsSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import { chooseSceneCopyPacking, chunkSceneData, parseScenePacking, readChunkedDataWord, rtSceneWgsl, type SceneCopy } from '@pmndrs/raytracer'; +import { loadFileGeometry } from './file-geometry.ts'; +import { cornell } from './tier0/index.ts'; +import { sponzaWhite } from './tier2/sponza-white.ts'; +import { buildSceneCopyFromDesc } from './to-scene-copy.ts'; + +const SPONZA = existsSync(new URL('../assets/downloads/sponza', import.meta.url)); + +const device = (stage = 16) => ({ limits: { maxStorageBufferBindingSize: 128 * 2 ** 20, maxBufferSize: 256 * 2 ** 20, maxStorageBuffersPerShaderStage: stage } }); + +/** The generated WGSL `rtSceneWord`, evaluated: chunk = the case of `i >> shift` (the last one is the default), word = `i & mask`. */ +function generatedWord(packing: Parameters[0]['packing'], pieces: readonly Uint32Array[]): (i: number) => number { + const text = rtSceneWgsl({ group: 0, firstBinding: 0, packing }); + const { chunks } = parseScenePacking(packing!); + if (chunks === 1) return (i) => (pieces[0] as Uint32Array)[i] as number; + const mask = Number(/let o = i & (0x[0-9a-f]+)u;/.exec(text)![1]); + const shift = Number(/switch \(i >> (\d+)u\)/.exec(text)![1]); + const cases = new Map([...text.matchAll(/case (\d+)u: \{\s*return rtSceneData(\d+)\[o\];/g)].map((m) => [Number(m[1]), Number(m[2])] as const)); + const last = Number(/default: \{\s*return rtSceneData(\d+)\[o\];/.exec(text)![1]); + return (i) => (pieces[cases.get(i >>> shift) ?? last] as Uint32Array)[i & mask] as number; +} + +function check(name: string, copy: SceneCopy, log2: number): void { + const chunks = Math.max(1, Math.ceil(copy.data.length / 2 ** log2)); + const pieces = chunkSceneData(copy.data, chunks, log2); + expect(pieces.reduce((n, p) => n + p.length, 0), name).toBe(copy.data.length); + // The rewrite is the same text for both table placements as far as the data pick goes. + for (const base of ['split', 'packed'] as const) { + const packing = `${base}:${chunks}x${log2}` as const; + const word = generatedWord(packing, pieces); + for (let i = 0; i < copy.data.length; i++) { + const w = word(i); + if (w !== copy.data[i] || readChunkedDataWord(pieces, log2, i) !== w) throw new Error(`${name} ${packing}: data word ${i}`); + } + } +} + +describe('chunked scene copy on bench scenes', () => { + it('cornell: tiny chunks (512 B and 128 B) cover every data word', () => { + const { copy } = buildSceneCopyFromDesc(cornell); + expect(copy.data.length).toBeGreaterThan(2 ** 8); // the Cornell box is small: 324 words, so chunks of 2^7 and 2^5 words + check('cornell', copy, 7); + check('cornell', copy, 5); + const packing = chooseSceneCopyPacking(device(), copy, { chunkWordsLog2: 7, base: 'split' }); + expect(parseScenePacking(packing)).toEqual({ base: 'split', chunks: Math.ceil(copy.data.length / 128), chunkWordsLog2: 7 }); + }); + + it.skipIf(!SPONZA)('sponza-white: the same, and the stage budget refuses a chunk size the device cannot bind', () => { + const { copy } = buildSceneCopyFromDesc(sponzaWhite, { resolveFile: (g) => loadFileGeometry(g).mesh }); + expect(copy.data.length * 4).toBeGreaterThan(10 * 2 ** 20); // ~12 MiB of data + check('sponza-white', copy, 14); + check('sponza-white', copy, 21); + // 2^21 words = 8 MiB chunks: 2 chunks and the table, fine. 64 KiB chunks would be hundreds of bindings: refused, naming the numbers. + expect(chooseSceneCopyPacking(device(), copy, { chunkWordsLog2: 21 })).toBe(`packed:${Math.ceil(copy.data.length / 2 ** 21)}x21`); + expect(() => chooseSceneCopyPacking(device(), copy, { chunkWordsLog2: 14, otherStorageBuffers: 6 })).toThrow(/scene copy storage buffers \+ 6 other = \d+, over the 16 storage buffers/); + }); +}); diff --git a/docs/internal/QUIET-PASS.md b/docs/internal/QUIET-PASS.md index c8558ecc..fc9ce7ed 100644 --- a/docs/internal/QUIET-PASS.md +++ b/docs/internal/QUIET-PASS.md @@ -46,6 +46,7 @@ What the next pass should measure. Add a row when something needs a quiet-machin | R2b | Cutout shadow modes (`alphaShadow`) vs exact and solid (`opaqueShadow`), ms per sample, both schedulers, 7 rounds in one page, scenes foliage-mask, tex-mask, foliage-mask-dense, foliage-mask-grid16, foliage-mask-grid12 (the 20261115 runs had load 3-17 and the megakernel rounds varied up to 3x) | per scene and scheduler `node bench/runner/run.ts --page alpha-shadow-ab --no-csv --args scene= renderers=pt-megakernel,pt-mk-shadow,pt-mk-transmit@0.455,pt-mk-transmit@0.45,pt-mk-roulette10,pt-mk-roulette,pt-mk-coverage,pt-mk-stochastic,pt-mk-firstk,pt-mk-classified spp=1024 repeat=9` (wavefront: `pt-wavefront,pt-wf-...`; beta* per scene: 0.455 / 0.459 / 0.323 / 0.446 / 0.446), then `node bench/adapters/alpha-shadow-ab.ts --runs --ref =.cache/refs/-exact-16384.pfm` (re-render the 16384 spp exact refs with matrix.ts, `.cache/refs` is local) | confirms D31 (`alphaShadow: 'transmit'` 0.45 in the realtime / preview presets, set 2026-11-18 on provisional numbers; the grid16 / grid12 pages in the list are already done once at load 3-9: re-run with the others), whether `classified` pays below ~50% mixed triangles | | P3.6 (rerun on a quiet machine: 20261115-1714 was under load 3.4-6.4) | V-buffer primaries (`primary: 'vbuffer'`) vs traced primaries: ms per sample at equal spp, the bench rasteriser's pass INCLUDED in the vbuffer rows (a real engine's G-buffer pass is its own and usually already paid; the bench one is non-instanced, vertex-pulled, one draw per frame), both schedulers, interleaved, 5 repeats: cornell 512x512, sponza-white 1280x720, tex-mask, MetalRoughSpheres, and each again at `pt_maxdepth=1` and `2` (the real-time regime: the primary ray is a larger share of the traced rays there) | `R=pt-megakernel,pt-mk-vbuffer,pt-wavefront,pt-wf-vbuffer; node bench/adapters/matrix.ts --renderers $R --scenes cornell,tex-mask --spp 256 --repeat 5 --interleave --name p36-time`, `--scenes sponza-white --spp 64 --append`, then the same with `--extra pt_maxdepth=2`; correctness first: `node bench/runner/run.ts --page vbuffer-check --timeout 3000000` | whether `primary: 'vbuffer'` is worth wiring into the P4 real-time mode, and what raster cost an engine must hide for it to win (provisional numbers: TASKS P3.6) | | P4.2c | ReSTIR primary hit: `sharedHit` (one camera-ray trace) vs traced vs `primary: 'vbuffer'` (the bench raster pass INCLUDED), ms per frame, interleaved, 5 repeats, megakernel RIS + t + s, 1280x720 `sponza-white` and `many-lights-256`, plus blue noise on / off (best-effort numbers 20261118, load 4.2: shared x0.942, blue noise x1.005 in TASKS P4.2c) | `node bench/runner/run.ts --page restir-check --timeout 3000000 --args check=timing scenes=sponza-white,many-lights-256 w=1280 h=720 reps=5 timingframes=16` (the `ris_ts_shared`, `ris_ts_bn` rows; the V-buffer variant needs a raster-driven loop: not in the page yet) | the default of `restir.sharedHit` (D-row after the A/B) | +| P1.4e | Chunked scene copy data (V515: the chunk is picked per data WORD by a switch) vs unchunked: ms per sample at equal spp, interleaved, 5 repeats, both schedulers: `node bench/adapters/matrix.ts --renderers pt-megakernel,pt-mk-chunk,pt-wavefront,pt-wf-chunk --scenes sponza-white,cornell --spp 256 --repeat 5 --interleave --name p14e-chunk-ab`, then `node bench/adapters/paired-ratios.ts --report p14e-chunk-ab --base-map pt-mk-chunk=pt-megakernel,pt-wf-chunk=pt-wavefront`. Sponza has K = 3 chunks of 8 MiB (21 MiB of data), Cornell K = 1 (a plain lookup, the control). A ratio above ~1.03 on Sponza means the per-word switch costs: then build the per-mesh chunk id (V515). Opt-in feature, no default depends on it. | | P3.11 | Scene copy packing (`sceneCopy.packing: 'packed'`, the table + data as ONE storage buffer) vs split: ms per sample at equal spp, both schedulers, interleaved, 5 repeats: cornell 512x512, sponza-white 1280x720, tex-mask, MetalRoughSpheres (the textured / MASK kernels are the ones that gain a binding), and each again at `pt_maxdepth=2` (the primary-hit / surface-decode share is larger there) | `R=pt-megakernel,pt-mk-packed,pt-wavefront,pt-wf-packed; node bench/adapters/matrix.ts --renderers $R --scenes cornell,tex-mask,MetalRoughSpheres --spp 256 --repeat 5 --interleave --name p311-time`, `--scenes sponza-white --spp 64 --append`, then `--extra pt_maxdepth=2`; `node bench/adapters/paired-ratios.ts --report p311-time --base-map pt-mk-packed=pt-megakernel,pt-wf-packed=pt-wavefront --md`; correctness first: `node bench/runner/run.ts --page scene-copy` (packing=both), `--page trace-core --args packing=packed` | whether `DEFAULT_SCENE_PACKING` flips to `packed` (suggestion: yes if every paired ratio stays within ~2%, since a freed binding is worth more than 2% only where hooks / counters need it; if Cornell stays +2% megakernel, hoist `dataBase` once per `rtSurface` and re-measure); provisional numbers (loaded 3.6-6.2): TASKS P3.11 | | P2.32b | Layered albedo correction (`albedoCorrection: none \| lut \| texture`) vs the stochastic walk, ms per sample, megakernel and wavefront, interleaved, 5 repeats (provisional: megakernel `lut` 1.03-1.15x, `texture` 1.01-1.03x, stochastic 0.83-1.03x of plain `internal`; wavefront within noise) | `node bench/adapters/matrix.ts --renderers pt-mk-lay-stoch,pt-mk-lay-int,pt-mk-lay-lut,pt-mk-lay-tex,pt-wf-lay-int,pt-wf-lay-lut,pt-wf-lay-tex --scenes AttenuationTest,MetalRoughSpheresNoTextures,SheenTestGrid-notex --spp 512 --repeat 5 --interleave --name p232b-time` | the D24 layering default: albedo+internal+texture correction, or the stochastic walk if it is no slower | | R1 | Ray-class material LOD (`materialLod: 'secondary'`) vs full: ms per sample, interleaved, 5 repeats, megakernel and wavefront, with the albedo kernel AND the stochastic walk compiled, on `lod-cornell`, ClearCoatTest-notex, SheenTestGrid-notex, IORTestGrid-notex-A, MetalRoughSpheres; plus DXC / compile time of `shadeSecondary` (kernel-compile page with a `materialLod` variant is not built yet: time `PtWavefront.create` via `compile_ms`) | `node bench/adapters/matrix.ts --renderers pt-megakernel,pt-mk-lod --scenes lod-cornell,ClearCoatTest-notex,SheenTestGrid-notex,IORTestGrid-notex-A,MetalRoughSpheres --spp 512 --repeat 5 --interleave --name r1-time-mk --extra pt_layering=albedo,pt_tint=0,pt_coverage=1` then `--renderers pt-wavefront,pt-wf-lod` (`--name r1-time-wf`) and the same with `pt_layering=stochastic` | whether the reduced secondary material is worth enabling in the real-time preset, and at which depth (`pt_lod_depth`) | diff --git a/docs/raytracer/scene-copy.mdx b/docs/raytracer/scene-copy.mdx index 92c1133e..340f43cc 100644 --- a/docs/raytracer/scene-copy.mdx +++ b/docs/raytracer/scene-copy.mdx @@ -19,10 +19,24 @@ const group = device.createBindGroup({ layout, entries: rtSceneCopyBindGroupEntr ## Bindings and packing -The copy is one storage buffer (`packing: 'packed'`, the default) or two (`'split'`: a table and a data buffer). Packed saves a storage binding in every kernel, which matters on Chrome on Apple GPUs (10 per stage). It must fit one storage binding, about 1.5 million triangles with normals and positions; above that, upload with `packing: 'split'`. +The copy is one storage buffer (`packing: 'packed'`, the default) or two (`'split'`: a table and a data buffer). Packed saves a storage binding in every kernel, which matters on Chrome on Apple GPUs (10 per stage). It must fit one storage binding, about 1.5 million triangles with normals and positions; above that, upload with `packing: 'split'` (table and data each under the limit) or chunk the data (below). The kernel, its layout and the upload must agree on the packing. `buildGpuScene` reports it as `scene.packing`. In WGSL the copy is `rtScene` (packed) or `rtSceneTable` and `rtSceneData` (split). The generated functions are written against the split names; `rtPackSceneAccess(source)` rewrites any WGSL that reads them directly so it works packed. `rtModuleWgsl` does that for its own text. You need it only for WGSL of your own that reads the buffers by name. +### Data past one binding + +A scene whose data alone is over `maxStorageBufferBindingSize` (128 MiB on the baseline) can split the data over K bindings. It is opt-in: `buildGpuScene(device, input, { chunkData: true })`, or by hand: + +```ts +const packing = chooseSceneCopyPacking(device, copy, { otherStorageBuffers: 6, stageLimit: 10 }); // 'packed', or e.g. 'packed:3x25' +const buffers = uploadSceneCopy(device, copy, { packing }); +// build every kernel for this scene with the same string: PtMegakernel.create(..., { scenePacking: packing }) +``` + +`'packed:3x25'` is the table (with its header) in `rtScene` plus three data chunks `rtSceneData0..2` of 2^25 words (128 MiB) each; `'split:KxN'` keeps `rtSceneTable`. Word `i` of the data is in chunk `i >> N`, so a mesh, a vertex or an env-map texel may straddle two chunks and every read is still one lookup (a switch over the chunks). Every chunk takes a storage binding, so K is small in practice: `chooseSceneCopyPacking` refuses, naming the numbers, when the scene buffers plus `otherStorageBuffers` exceed `stageLimit` (Chrome on Apple allows 10 per stage; the plain packed megakernel took 5 chunks, the packed wavefront shade kernel 3). The table (instances, materials, lights) is not chunked and must fit one binding. Unchunked scenes keep byte-identical kernels and buffers. + +`rtApplyScenePacking(source, packing)` is the packing-aware form of `rtPackSceneAccess` for your own WGSL. + `writeSceneCopy(device, buffers, copy)` rewrites a rebuilt copy into existing buffers when it fits (for example after lights changed), and returns `false` when you need to upload again. ## Materials diff --git a/examples/shared/trace-kernel.ts b/examples/shared/trace-kernel.ts index ce313589..9466cf45 100644 --- a/examples/shared/trace-kernel.ts +++ b/examples/shared/trace-kernel.ts @@ -9,7 +9,7 @@ * packed, so code that reads the copy directly still works). The examples' kernels write an `array` accumulator (rgb sum, w = samples) * that `AccumulationView` draws. */ -import { rtModuleWgsl, rtPackSceneAccess, rtSceneBindGroupEntries, rtSceneCopyBindGroupEntries, rtSceneCopyLayoutEntries, rtWalkEntries, withBindings, type Caps, type GpuScene, type RtModuleOptions } from '@pmndrs/raytracer'; +import { rtApplyScenePacking, rtModuleWgsl, rtSceneBindGroupEntries, rtSceneCopyBindGroupEntries, rtSceneCopyLayoutEntries, rtWalkEntries, withBindings, type Caps, type GpuScene, type RtModuleOptions } from '@pmndrs/raytracer'; export interface TraceKernelOptions { label: string; @@ -49,7 +49,7 @@ export class TraceKernel { scene: { slot: { group: 1, firstBinding: 0 }, layout: scene.copy.layout, textures: scene.copy.textureLayout, packing: scene.packing }, ...o.module, }); - const code = `${module}\n${scene.packing === 'packed' ? rtPackSceneAccess(o.wgsl) : o.wgsl}`; + const code = `${module}\n${rtApplyScenePacking(o.wgsl, scene.packing)}`; const layouts = [ device.createBindGroupLayout({ label: `${o.label} walk`, entries: o.walk === false ? [] : withBindings(rtWalkEntries(scene.format)) }), device.createBindGroupLayout({ label: `${o.label} scene`, entries: rtSceneCopyLayoutEntries(0, scene.copy.textureLayout, scene.packing) }), diff --git a/packages/pathtracer/src/integrator/megakernel.ts b/packages/pathtracer/src/integrator/megakernel.ts index 48a48e5b..d1da0b4c 100644 --- a/packages/pathtracer/src/integrator/megakernel.ts +++ b/packages/pathtracer/src/integrator/megakernel.ts @@ -20,7 +20,7 @@ * const { accum, planes } = pt.frameBuffers; // or: const frame = await pt.readFrame(); */ import { ptRenderAllocated, ptRenderUntil, type PtAllocatedOptions, type PtAllocatedResult, type PtRenderUntilResult, type PtStopOptions } from './render-until.ts'; -import { loadBlueNoise, rtLightSampleWgsl, rtModuleWgsl, rtOwenSobolWgsl, rtPackSceneAccess, DEFAULT_SCENE_PACKING, type SceneCopyPacking, rtSceneCopyBindGroupEntries, rtSceneCopyLayoutEntries, rtMinifyWgsl, rtCreateComputePipelineAsync, rtSceneBindGroupEntries, sceneFormatOf, rtTransformWgsl, rtWalkEntries, stripWgslComments, withBindings, rtSetResourceTable, rtUsesResourceTable } from '@pmndrs/raytracer'; +import { loadBlueNoise, rtLightSampleWgsl, rtModuleWgsl, rtOwenSobolWgsl, rtApplyScenePacking, DEFAULT_SCENE_PACKING, scenePackingChunks, sceneCopyStorageBuffers, type SceneCopyPacking, rtSceneCopyBindGroupEntries, rtSceneCopyLayoutEntries, rtMinifyWgsl, rtCreateComputePipelineAsync, rtSceneBindGroupEntries, sceneFormatOf, rtTransformWgsl, rtWalkEntries, stripWgslComments, withBindings, rtSetResourceTable, rtUsesResourceTable } from '@pmndrs/raytracer'; import type { RtWgslBuild } from '@pmndrs/raytracer'; import type { BlueNoiseTexture, Caps, SceneCopyBuffers, SceneFormat, SurfaceLayout, TextureLayout, RtResourceTable } from '@pmndrs/raytracer'; import { ptBsdfAdapterWgsl, ptBsdfReducedWgsl, ptLayeredDispatchWgsl, ptReducedKernelFeatures } from '../bsdf/adapter.ts'; @@ -190,9 +190,8 @@ export function ptMegakernelBuild(caps: Caps, options: Pick 0 ? ` (the scene copy is chunked, '${options.scenePacking}': ${sceneCopyStorageBuffers(options.scenePacking)} storage buffers; fewer, larger chunks, or ask chooseSceneCopyPacking with otherStorageBuffers / stageLimit)` : ''}`); // On a compile error this throws with original line numbers, names and source text (rtCreateComputePipelineAsync). - const pipeline = await rtCreateComputePipelineAsync(device, { label, layout: device.createPipelineLayout({ bindGroupLayouts: layouts, ...(rtUsesResourceTable(options.textures) ? { usesResourceTable: true } : {}) } as GPUPipelineLayoutDescriptor), code, map, entryPoint: 'ptMain', sourceMap: options.sourceMap }); + const pipeline = await rtCreateComputePipelineAsync(device, { label, layout: pipelineLayout, code, map, entryPoint: 'ptMain', sourceMap: options.sourceMap }); let fuzzTable: GPUBuffer | null = null; if (options.integrator?.materials?.features.fuzz) { const table = ptFuzzTableF32(); diff --git a/packages/pathtracer/src/integrator/scene-chunked.test.ts b/packages/pathtracer/src/integrator/scene-chunked.test.ts new file mode 100644 index 00000000..3de8ea63 --- /dev/null +++ b/packages/pathtracer/src/integrator/scene-chunked.test.ts @@ -0,0 +1,63 @@ +/** + * Chunked scene copy data (P1.4e) in the integrator kernels: every kernel binds the table plus one `rtSceneData` per chunk, no unchunked data name is left + * (the appended integrator text goes through `rtApplyScenePacking`), textures follow the chunks, and the plain default is untouched. + * The images on a GPU are compared by `pt_scene_chunk=` (bench adapter), bit-identical to the unchunked ones on Cornell and Sponza. + */ +import { buildCaps } from '@pmndrs/raytracer'; +import { describe, expect, it } from 'vitest'; +import { ptMegakernelBuild } from './megakernel.ts'; +import { ptWavefrontBuild, PTWF_KERNELS } from '../wavefront/wavefront.ts'; + +const caps = buildCaps({ features: new Set(['subgroups', 'shader-f16', 'timestamp-query']), limits: {} }, new Set()); +const layout = { normals: true, uvs: false, positions: true }; +const texLayout = { normals: true, uvs: true, positions: true }; +const bucket = (srgb: boolean) => ({ width: 8, height: 8, colorSpace: srgb ? ('srgb' as const) : ('linear' as const), wrap: 'repeat' as const, layers: 1, mipLevels: 4 }); +const textures = { buckets: [bucket(true), bucket(false)] }; +const feat = { mix: true, thin: true, layered: true, medium: true, thinFilm: true, fuzz: true }; + +const variants: Array<[string, object]> = [ + ['plain', { format: {}, layout }], + ['env', { format: {}, layout, integrator: { envMap: true, envSampling: 'importance' } }], + ['tex-mask', { format: {}, layout: texLayout, textures, integrator: { alphaMask: true } }], + ['pbr', { format: {}, layout, integrator: { materials: { features: feat, layered: { layering: 'albedo' } } } }], +]; + +const groupBindings = (code: string, group: number): number[] => [...code.matchAll(new RegExp(`@group\\(${group}\\)\\s*@binding\\((\\d+)\\)`, 'g'))].map((m) => Number(m[1])); + +describe('chunked scene copy in the kernels (P1.4e)', () => { + for (const [name, options] of variants) { + for (const base of ['packed', 'split'] as const) { + const packing = `${base}:3x20` as const; + it(`${name} / ${packing}: the megakernel binds the table + 3 chunks, nothing unchunked is left`, () => { + const plain = ptMegakernelBuild(caps, { ...options, scenePacking: base } as never).code; + const chunked = ptMegakernelBuild(caps, { ...options, scenePacking: packing } as never).code; + for (let c = 0; c < 3; c++) expect(chunked, `chunk ${c}`).toMatch(new RegExp(`@group\\(1\\)\\s*@binding\\(${1 + c}\\)var\\s*rtSceneData${c}:\\s*array`)); + expect(chunked).not.toMatch(/rtSceneData\[/); + expect(chunked).toContain(base === 'packed' ? 'rtScene:' : 'rtSceneTable:'); + expect(chunked).not.toMatch(base === 'packed' ? /rtSceneTable/ : /rtScene\[/); + // The chunks replace the data binding (split: 2 -> 4 buffers; packed: 1 -> 4); textures and samplers shift behind them. + const extra = (base === 'packed' ? 3 : 2); + expect(groupBindings(chunked, 1).length).toBe(groupBindings(plain, 1).length + extra); + expect(groupBindings(chunked, 1)).toEqual([...groupBindings(chunked, 1)].sort((a, b) => a - b)); + expect(chunked.length - plain.length).toBeLessThan(900); + }); + + it(`${name} / ${packing}: every wavefront kernel is rewritten the same way`, () => { + const plain = ptWavefrontBuild(caps, { ...options, scenePacking: base } as never); + const chunked = ptWavefrontBuild(caps, { ...options, scenePacking: packing } as never); + for (const kernel of PTWF_KERNELS) { + expect(chunked[kernel].code, kernel).not.toMatch(/rtSceneData\[/); + // A kernel that reads the scene copy at all declares every chunk binding (the pipeline layout names them all); one that does not still has none. + const had = /rtSceneWord|rtScene\b|rtSceneTable/.test(plain[kernel].code); + expect(/rtSceneData0/.test(chunked[kernel].code), kernel).toBe(had); + } + }); + } + } + + it('the default stays the unchunked packed text', () => { + const a = ptMegakernelBuild(caps, { format: {}, layout } as never).code; + expect(a).toBe(ptMegakernelBuild(caps, { format: {}, layout, scenePacking: 'packed' } as never).code); + expect(a).not.toMatch(/rtSceneData/); + }); +}); diff --git a/packages/pathtracer/src/restir/restir.ts b/packages/pathtracer/src/restir/restir.ts index a66221b1..000cac76 100644 --- a/packages/pathtracer/src/restir/restir.ts +++ b/packages/pathtracer/src/restir/restir.ts @@ -10,7 +10,7 @@ * ray), the blue-noise texture (`sampler: 'bluenoise'`: the G-buffer pass draws the same jitter pair as the shade pass) and the layered-albedo correction texture. * `setInputs` hands the views over; the megakernel does it before every encode. */ -import { DEFAULT_SCENE_PACKING, rtCreateComputePipelineAsync, rtModuleWgsl, rtPackSceneAccess, rtTransformWgsl, type Caps, type RtWgslBuild } from '@pmndrs/raytracer'; +import { DEFAULT_SCENE_PACKING, rtCreateComputePipelineAsync, rtModuleWgsl, rtApplyScenePacking, rtTransformWgsl, type Caps, type RtWgslBuild } from '@pmndrs/raytracer'; import { ptCameraBasis, type PtCameraBasis, type PtLookAtCamera } from '../integrator/camera.ts'; import { PT_BLUENOISE_BINDING } from '../integrator/dimensions.ts'; import { PT_WORKGROUP, resolveIntegratorOptions } from '../integrator/integrator-wgsl.ts'; @@ -68,8 +68,7 @@ export function ptRestirBuild(caps: Caps, options: BuildOptions, part: 'di' | 'g const resolved = resolveIntegratorOptions(integratorOptions); const raytracer = rtModuleWgsl(caps, ptRaytracerModuleOptions(options)); const ours = [...parts, ...(resolved.primary === 'vbuffer' ? [ptVbufferWgsl()] : []), ptRestirWgsl(integratorOptions, part)].join('\n'); - const packed = (options.scenePacking ?? DEFAULT_SCENE_PACKING) === 'packed'; - const { code, map } = rtTransformWgsl(`${raytracer}\n${packed ? rtPackSceneAccess(ours) : ours}`, { prune: options.prune, shorten: options.shortenNames, minify: options.minify, keep: part === 'gi' ? [...PT_RESTIR_GI_ENTRIES] : [...PT_RESTIR_ENTRIES] }); + const { code, map } = rtTransformWgsl(`${raytracer}\n${rtApplyScenePacking(ours, options.scenePacking ?? DEFAULT_SCENE_PACKING)}`, { prune: options.prune, shorten: options.shortenNames, minify: options.minify, keep: part === 'gi' ? [...PT_RESTIR_GI_ENTRIES] : [...PT_RESTIR_ENTRIES] }); return { code, map }; } diff --git a/packages/pathtracer/src/wavefront/wavefront.ts b/packages/pathtracer/src/wavefront/wavefront.ts index 2d09a1e2..21afbf8a 100644 --- a/packages/pathtracer/src/wavefront/wavefront.ts +++ b/packages/pathtracer/src/wavefront/wavefront.ts @@ -15,7 +15,7 @@ * The params uniform is a ring of dynamic-offset slots like the megakernel's, with one record per depth iteration * (`PTWF_PARAM_SLOTS`; `maxPassesPerEncode()` says how many sample passes fit in one `encode`). */ -import { loadBlueNoise, rtCreateComputePipelineAsync, rtModuleWgsl, rtPackSceneAccess, DEFAULT_SCENE_PACKING, rtSceneBindGroupEntries, sceneFormatOf, rtSceneCopyBindGroupEntries, rtSceneCopyLayoutEntries, rtTransformWgsl, rtWalkEntries, withBindings } from '@pmndrs/raytracer'; +import { loadBlueNoise, rtCreateComputePipelineAsync, rtModuleWgsl, rtApplyScenePacking, DEFAULT_SCENE_PACKING, scenePackingChunks, sceneCopyStorageBuffers, rtSceneBindGroupEntries, sceneFormatOf, rtSceneCopyBindGroupEntries, rtSceneCopyLayoutEntries, rtTransformWgsl, rtWalkEntries, withBindings } from '@pmndrs/raytracer'; import type { BlueNoiseTexture, Caps, RtWgslBuild, SceneCopyBuffers } from '@pmndrs/raytracer'; import { ptFuzzTableF32 } from '../bsdf/fuzz.ts'; import { PT_LAYER_CORR_BINDING, ptLayerCorrCreateTexture, ptLayerCorrLayoutEntry, ptLayerCorrNeedsTexture } from '../bsdf/layered-correction.ts'; @@ -155,7 +155,7 @@ export function ptWavefrontBuild(caps: Caps, options: Pick ((options.scenePacking ?? DEFAULT_SCENE_PACKING) === 'packed' ? rtPackSceneAccess(code) : code); + const px = (code: string): string => rtApplyScenePacking(code, options.scenePacking ?? DEFAULT_SCENE_PACKING); // R1 x alpha MASK x cone LOD: the cutout test of the intersect kernel uses the widened footprint of depth >= N like the megakernel's (see `PtwfConfig.lodTexDepth`) const ro = resolveIntegratorOptions(integratorOptions); const intersectWf: PtwfConfig = lodOn && ro.alphaMask && ro.textures && ro.textureLod === 'cone' ? { ...wf, lodTexDepth: lod.lodDepth } : wf; @@ -376,7 +376,7 @@ export class PtWavefront { device.createPipelineLayout({ label: `${label} ${k}`, bindGroupLayouts: [USES_WALK[k] ? walk : empty, scenePerKernel[k] ? scene : empty, io[k], ...(k === 'args' ? [argsLayout] : []), ...(k === 'shade' && hooks ? [hooks] : []), ...(k === 'shadow' && radianceHooks ? [radianceHooks] : [])] }); const pipelineLayouts = Object.fromEntries([...PTWF_KERNELS, ...PTWF_EXTRA_KERNELS].map((k) => [k, pipelineLayout(k)])) as Record; const layoutError = await device.popErrorScope(); - if (layoutError) throw new Error(`PtWavefront: invalid bind group / pipeline layout: ${layoutError.message}`); + if (layoutError) throw new Error(`PtWavefront: invalid bind group / pipeline layout: ${layoutError.message}${scenePackingChunks(options.scenePacking ?? DEFAULT_SCENE_PACKING) > 0 ? ` (the scene copy is chunked, '${options.scenePacking}': ${sceneCopyStorageBuffers(options.scenePacking)} storage buffers; fewer, larger chunks, or ask chooseSceneCopyPacking with otherStorageBuffers / stageLimit)` : ''}`); const entry: Record = { camera: 'ptwfCamera', intersect: 'ptwfIntersect', shade: 'ptwfShade', shadow: 'ptwfShadow', args: 'ptwfArgsMain', sortHit: 'ptwfSort', sortRay: 'ptwfSort', primary: 'ptwfPrimary', voFinish: 'ptwfVoFinish' }; const built = [...PTWF_KERNELS, ...PTWF_EXTRA_KERNELS].filter((k): k is PtwfKernel => !!build[k]); const made = await Promise.all(built.map((k) => rtCreateComputePipelineAsync(device, { label: `${label} ${k}`, layout: pipelineLayouts[k], code: (build[k] as RtWgslBuild).code, map: (build[k] as RtWgslBuild).map, entryPoint: entry[k], sourceMap: options.sourceMap }))); diff --git a/packages/raytracer/src/scene/constants.ts b/packages/raytracer/src/scene/constants.ts index 97a010c4..2195a97d 100644 --- a/packages/raytracer/src/scene/constants.ts +++ b/packages/raytracer/src/scene/constants.ts @@ -42,22 +42,72 @@ export const SCENE_COPY_PACKED_STORAGE_BUFFERS = 1; * `dataBase` is the buffer's first vec4 (one uniform-address load, L1/constant-cache hot), not a uniform buffer or a pipeline constant: a uniform would * cost a binding (the thing this setting frees) and an `override` would recompile the kernel per scene. */ -export type SceneCopyPacking = 'split' | 'packed'; +export type SceneCopyPacking = 'split' | 'packed' | SceneCopyChunkedPacking; +/** + * Chunked data (P1.4e, V515): the data region is split over K storage bindings of `2^chunkWordsLog2` words each (the last one holds the rest), for a scene copy whose data + * does not fit `maxStorageBufferBindingSize`. The packing string carries the layout so every place that already passes a packing (kernel options, `uploadSceneCopy`, the + * `setScene` check, the layout entries, the storage-buffer count) carries it too: `'split:3x25'` = `rtSceneTable` + `rtSceneData0..2` (2^25 words = 128 MiB each), + * `'packed:3x25'` = `rtScene` (header + table only, no data region) + `rtSceneData0..2`. Build one with `sceneCopyChunkedPacking(base, chunks, log2)`, pick one with + * `chooseSceneCopyPacking`. The plain `'split'` / `'packed'` kernel text and buffers are untouched. + */ +export type SceneCopyChunkedPacking = `${'split' | 'packed'}:${number}x${number}`; + +/** A packing taken apart: `base` is where the table lives, `chunks` is 0 for an unchunked packing, else the data chunk count. */ +export interface ParsedScenePacking { + base: 'split' | 'packed'; + chunks: number; + chunkWordsLog2: number; +} + +/** Smallest / largest chunk size (log2 words): 4 words = 16 bytes (a whole vec4) up to 2^30 words (4 GiB). */ +export const SCENE_CHUNK_LOG2_MIN = 2; +export const SCENE_CHUNK_LOG2_MAX = 30; + +export function parseScenePacking(packing: SceneCopyPacking): ParsedScenePacking { + if (packing === 'split' || packing === 'packed') return { base: packing, chunks: 0, chunkWordsLog2: 0 }; + const m = /^(split|packed):(\d+)x(\d+)$/.exec(packing); + if (!m) throw new RangeError(`unknown scene copy packing '${packing}'`); + const chunks = Number(m[2]); + const log2 = Number(m[3]); + if (!(chunks >= 1) || log2 < SCENE_CHUNK_LOG2_MIN || log2 > SCENE_CHUNK_LOG2_MAX || chunks * 2 ** log2 > 2 ** 32) { + throw new RangeError(`scene copy packing '${packing}': ${chunks} chunks of 2^${log2} words (need 1+ chunks, log2 ${SCENE_CHUNK_LOG2_MIN}-${SCENE_CHUNK_LOG2_MAX}, at most 2^32 words in all: a data word index is a u32)`); + } + return { base: m[1] as 'split' | 'packed', chunks, chunkWordsLog2: log2 }; +} + +export function sceneCopyChunkedPacking(base: 'split' | 'packed', chunks: number, chunkWordsLog2: number): SceneCopyChunkedPacking { + const packing = `${base}:${chunks}x${chunkWordsLog2}` as SceneCopyChunkedPacking; + parseScenePacking(packing); + return packing; +} + +/** True when the table is the header + table buffer `rtScene` (packed, chunked or not). */ +export function scenePackingIsPacked(packing: SceneCopyPacking): boolean { + return packing === 'packed' || (packing !== 'split' && packing.startsWith('packed')); +} + +/** Data chunk count of a packing (0 = the data is not chunked). */ +export function scenePackingChunks(packing: SceneCopyPacking): number { + return packing === 'split' || packing === 'packed' ? 0 : parseScenePacking(packing).chunks; +} + /** * The library default (D32, provisional): `packed`, one storage binding for the table + data, which frees a binding in every kernel (hooks / counters / the wavefront's 10-buffer Apple * budget). Images are per-pixel identical to `split` (<= 3.2e-7 relative on two scenes); provisional timing: a wash on Sponza, Cornell +2% on the megakernel. `split` is the setting that * gives the pre-P3.11 kernel text and is needed for a scene copy over the single-binding cap (`uploadSceneCopy` throws and says so). Revisit if the quiet pass disagrees (QUIET-PASS P3.11 row). */ -export const DEFAULT_SCENE_PACKING: SceneCopyPacking = 'packed'; +export const DEFAULT_SCENE_PACKING: 'split' | 'packed' = 'packed'; export const PACKED_HEADER_VEC4S = 1; /** vec4 index of the table inside a packed buffer (a compile-time constant in the generated WGSL). */ export const PACKED_TABLE_BASE_VEC4S = 1; /** Words of the packed header vec4. */ export const PACKED_HEADER = { dataBase: 0, tableBase: 1, dataWords: 2, totalVec4s: 3 } as const; -/** Storage buffers the scene copy adds to a kernel for this packing. */ +/** Storage buffers the scene copy adds to a kernel for this packing: 2 split, 1 packed, `1 + chunks` when the data is chunked (the table, then one binding per chunk). */ export function sceneCopyStorageBuffers(packing: SceneCopyPacking = DEFAULT_SCENE_PACKING): number { - return packing === 'packed' ? SCENE_COPY_PACKED_STORAGE_BUFFERS : SCENE_COPY_STORAGE_BUFFERS; + if (packing === 'split') return SCENE_COPY_STORAGE_BUFFERS; + if (packing === 'packed') return SCENE_COPY_PACKED_STORAGE_BUFFERS; + return 1 + parseScenePacking(packing).chunks; } export const SCENE_HEADER_VEC4S = 4; diff --git a/packages/raytracer/src/scene/gpu-scene.ts b/packages/raytracer/src/scene/gpu-scene.ts index 6216e66b..19299e4e 100644 --- a/packages/raytracer/src/scene/gpu-scene.ts +++ b/packages/raytracer/src/scene/gpu-scene.ts @@ -10,8 +10,8 @@ import { buildTraceScene, createMeshBvhBuilder, uploadTraceScene } from '@pmndrs import type { NodeFormat, TraceSceneBuffers } from '@pmndrs/bvh'; import { sceneFormatOf } from '../trace/modules.ts'; import type { ResolvedSceneFormat } from '../trace/modules.ts'; -import { uploadSceneCopy } from './gpu.ts'; -import type { RtMipGenerator, SceneCopyBuffers } from './gpu.ts'; +import { chooseSceneCopyPacking, uploadSceneCopy } from './gpu.ts'; +import type { ChooseScenePackingOptions, RtMipGenerator, SceneCopyBuffers } from './gpu.ts'; import { buildSceneCopy } from './scene-copy.ts'; import type { SceneCopy, SceneCopyInput } from './scene-copy.ts'; import type { SceneCopyPacking } from './constants.ts'; @@ -23,6 +23,12 @@ export interface GpuSceneOptions { nodeFormat?: NodeFormat; /** Scene copy binding (`DEFAULT_SCENE_PACKING` when omitted). Kernels must be compiled with the same `scenePacking`. */ packing?: SceneCopyPacking; + /** + * Opt in to chunked data (P1.4e): when the scene copy does not fit one storage binding, split the data over K bindings (`chooseSceneCopyPacking`, base = `packing`'s table placement). + * `true` = defaults; an object passes `chunkWordsLog2` / `otherStorageBuffers` / `stageLimit` / `bindingLimit`. Kernels then must be built with `scene.packing` (they are, through `ptSceneOptions`). + * Without it a scene over the binding limit throws as before. Ignored with an explicit chunked `packing`. + */ + chunkData?: boolean | Omit; /** Hit positions from the triangle's vertices (default true) or from `origin + t * direction` (false: a smaller scene copy). */ positions?: boolean; /** Fills texture mip levels 1+ (default: a per-device `@pmndrs/downsampler`). */ @@ -60,7 +66,11 @@ export async function buildGpuScene(device: GPUDevice, input: SceneCopyInput, op } const trace = uploadTraceScene(device, data, label); const copy = buildSceneCopy({ ...input, options: { ...input.options, surface: { ...input.options?.surface, positions: options.positions ?? true } } }); - const buffers = uploadSceneCopy(device, copy, { label: `${label} copy`, ...(options.packing ? { packing: options.packing } : {}), ...(options.mipGenerator ? { mipGenerator: options.mipGenerator } : {}) }); + const chunk = options.chunkData + ? chooseSceneCopyPacking(device, copy, { ...(options.chunkData === true ? {} : options.chunkData), ...(options.packing === 'split' || options.packing === 'packed' ? { base: options.packing } : {}) }) + : undefined; + const packing = options.packing && options.packing !== 'split' && options.packing !== 'packed' ? options.packing : chunk ?? options.packing; + const buffers = uploadSceneCopy(device, copy, { label: `${label} copy`, ...(packing ? { packing } : {}), ...(options.mipGenerator ? { mipGenerator: options.mipGenerator } : {}) }); return { input, copy, trace, buffers, packing: buffers.packing, format: sceneFormatOf({ nodeFormat: trace.nodeFormat, triangleLeaves: trace.triangleLeaves, positionLayout: trace.positionLayout }), diff --git a/packages/raytracer/src/scene/gpu.ts b/packages/raytracer/src/scene/gpu.ts index de10e8fd..be6d3341 100644 --- a/packages/raytracer/src/scene/gpu.ts +++ b/packages/raytracer/src/scene/gpu.ts @@ -3,8 +3,8 @@ * Nothing here runs in the frame loop: a scene change is a rebuild + upload, never a readback. */ import { Downsampler } from '@pmndrs/downsampler/webgpu'; -import { DEFAULT_SCENE_PACKING, type SceneCopyPacking } from './constants.ts'; -import { packSceneCopy, packedSceneCopyBytes, type SceneCopy } from './scene-copy.ts'; +import { DEFAULT_SCENE_PACKING, SCENE_CHUNK_LOG2_MAX, SCENE_CHUNK_LOG2_MIN, parseScenePacking, sceneCopyChunkedPacking, sceneCopyStorageBuffers, scenePackingIsPacked, type SceneCopyPacking } from './constants.ts'; +import { chunkSceneData, packSceneCopy, packedSceneCopyBytes, type SceneCopy } from './scene-copy.ts'; import { textureTableSize, type SceneTextures, type TextureLayout, type TextureWrap } from './texture.ts'; // GPUBufferUsage bits, spelled out so this module loads in Node (tests) where the WebGPU globals do not exist. @@ -49,11 +49,13 @@ export interface SceneTextureBuffers { export interface SceneCopyBuffers { readonly packing: SceneCopyPacking; - /** `split` only: the table (`rtSceneTable`) and the data (`rtSceneData`). */ + /** `split` only: the table (`rtSceneTable`) and the data (`rtSceneData`; absent with chunked data, see `dataChunks`). */ readonly table?: GPUBuffer; readonly data?: GPUBuffer; - /** `packed` only: header + table + data in one buffer (`rtScene`). */ + /** `packed` only: header + table + data in one buffer (`rtScene`); with chunked data header + table only. */ readonly packed?: GPUBuffer; + /** Chunked data (P1.4e, `packing: 'split:KxN' | 'packed:KxN'`): the K data buffers `rtSceneData0..K-1`, each `2^N` words except the last (which holds the rest, at least 16 bytes). */ + readonly dataChunks?: readonly GPUBuffer[]; /** Bytes of the scene copy's storage buffer(s) (the packed one includes its header and the data's padding). */ readonly storageBytes: number; readonly layout: SceneCopy['layout']; @@ -67,7 +69,10 @@ export interface UploadSceneCopyOptions { label?: string; /** Add COPY_SRC (tests that read the buffers back). Default false. */ copySrc?: boolean; - /** `split` (two buffers) or `packed` (one: frees a storage binding in every kernel, needs the whole scene copy under one binding limit). Default `DEFAULT_SCENE_PACKING`. The kernels must be built with the same packing. */ + /** + * `split` (two buffers) or `packed` (one: frees a storage binding in every kernel, needs the whole scene copy under one binding limit). Default `DEFAULT_SCENE_PACKING`. The kernels must be built with the same packing. + * A chunked packing (`'split:KxN'` / `'packed:KxN'`, P1.4e) splits the data over K bindings for a scene copy past the binding limit: pick it with `chooseSceneCopyPacking`, build the kernels with the same string. + */ packing?: SceneCopyPacking; /** * Fills mip levels 1+ of the texture arrays on the GPU. Default (a scene copy built with `textures: { mips: 'gpu' }`, the default): @@ -106,17 +111,69 @@ export function sceneCopyBindingLimit(device: GPUDevice): number { return Math.min(device.limits.maxStorageBufferBindingSize, device.limits.maxBufferSize); } -/** Writes the scene copy to two new storage buffers (or one, packed). Fails clearly when a buffer would exceed the device's binding size. */ +/** Device facts `chooseSceneCopyPacking` reads (a `GPUDevice` has them). */ +export interface SceneCopyDeviceLimits { + limits: Pick & Partial>; +} + +export interface ChooseScenePackingOptions { + /** Where the table lives: `split` or `packed` (default: `DEFAULT_SCENE_PACKING`). */ + base?: 'split' | 'packed'; + /** Force chunking with chunks of `2^N` words (tests; also a way to spread a big scene over smaller buffers). Default: chunk only when the unchunked packing does not fit. */ + chunkWordsLog2?: number; + /** Binding size cap in bytes (default: the device's, `sceneCopyBindingLimit`). */ + bindingLimit?: number; + /** + * Storage buffers the rest of the kernel binds in the same stage (the bvh walk 3-4, the integrator's io, hooks...). With `stageLimit` they make the budget: scene buffers + this must + * not exceed it, else a RangeError names the numbers (chunks cost a binding each; Chrome on Apple allows 10 per stage whatever the device reports, pass `stageLimit: 10` there). + */ + otherStorageBuffers?: number; + /** Storage buffers per shader stage the target allows (default: the device's `maxStorageBuffersPerShaderStage`). */ + stageLimit?: number; +} + +const mib = (n: number) => `${(n / 2 ** 20).toFixed(1)} MiB`; + +/** + * The packing to build kernels and `uploadSceneCopy` with (P1.4e): the plain `base` while the scene copy fits one binding, else a chunked packing whose chunks are as large as the + * binding limit allows (a power of two words, `2^N`), as many as the data needs. K is chosen here, from the size and the limit; every kernel for this scene must then be built with + * the returned string. Throws a RangeError when the table alone is over the limit (the table is not chunked), when a chunk would not fit the binding limit, or when the table + + * K chunks would not fit the stage's storage buffer budget. + */ +export function chooseSceneCopyPacking(device: SceneCopyDeviceLimits, copy: Pick, options: ChooseScenePackingOptions = {}): SceneCopyPacking { + const base = options.base ?? (scenePackingIsPacked(DEFAULT_SCENE_PACKING) ? 'packed' : 'split'); + const limit = options.bindingLimit ?? Math.min(device.limits.maxStorageBufferBindingSize, device.limits.maxBufferSize); + const stageLimit = options.stageLimit ?? device.limits.maxStorageBuffersPerShaderStage; + const other = options.otherStorageBuffers ?? 0; + if (options.chunkWordsLog2 === undefined) { + const bytes = base === 'packed' ? packedSceneCopyBytes(copy) : Math.max(copy.table.byteLength, Math.ceil(copy.data.byteLength / 16) * 16); + if (bytes <= limit) return base; + } + const tableBytes = base === 'packed' ? packedSceneCopyBytes(copy, { dataInline: false }) : Math.max(16, copy.table.byteLength); + if (tableBytes > limit) throw new RangeError(`the scene copy's table is ${mib(tableBytes)}, over the storage binding limit of ${mib(limit)}; only the data region is chunked`); + const log2 = options.chunkWordsLog2 ?? Math.min(SCENE_CHUNK_LOG2_MAX, Math.floor(Math.log2(limit / 4))); + if (!Number.isInteger(log2) || log2 < SCENE_CHUNK_LOG2_MIN || log2 > SCENE_CHUNK_LOG2_MAX) throw new RangeError(`chunk size 2^${log2} words is outside 2^${SCENE_CHUNK_LOG2_MIN}..2^${SCENE_CHUNK_LOG2_MAX}`); + if (4 * 2 ** log2 > limit) throw new RangeError(`chunks of 2^${log2} words (${mib(4 * 2 ** log2)}) are over the storage binding limit of ${mib(limit)}`); + const chunks = Math.max(1, Math.ceil(copy.data.length / 2 ** log2)); + const buffers = 1 + chunks; + if (stageLimit !== undefined && buffers + other > stageLimit) { + throw new RangeError(`the data (${mib(copy.data.byteLength)}) needs ${chunks} chunks of ${mib(4 * 2 ** log2)}: ${buffers} scene copy storage buffers + ${other} other = ${buffers + other}, over the ${stageLimit} storage buffers per shader stage`); + } + return sceneCopyChunkedPacking(base, chunks, log2); +} + +/** Writes the scene copy to two new storage buffers (or one, packed; or the table and K data chunks, see `chooseSceneCopyPacking`). Fails clearly when a buffer would exceed the device's binding size. */ export function uploadSceneCopy(device: GPUDevice, copy: SceneCopy, options: UploadSceneCopyOptions = {}): SceneCopyBuffers { const label = options.label ?? 'rt scene'; const limit = sceneCopyBindingLimit(device); const packing = options.packing ?? DEFAULT_SCENE_PACKING; const byteLength = copy.byteLength + (copy.textures?.byteLength ?? 0); + if (parseScenePacking(packing).chunks > 0) return uploadChunked(device, copy, { ...options, label, packing, limit, byteLength }); if (packing === 'packed') { const bytes = packedSceneCopyBytes(copy); if (bytes > limit) { const mib = (n: number) => `${(n / 2 ** 20).toFixed(1)} MiB`; - throw new RangeError(`${label}: the packed scene copy is ${mib(bytes)} (table ${mib(copy.table.byteLength)} + data ${mib(copy.data.byteLength)}), over the device's storage binding limit of ${mib(limit)}; packing: 'split' binds them separately (each under the limit: table ${copy.table.byteLength <= limit ? 'fits' : 'does not fit'}, data ${copy.data.byteLength <= limit ? 'fits' : 'does not fit'}; chunking is a later task)`); + throw new RangeError(`${label}: the packed scene copy is ${mib(bytes)} (table ${mib(copy.table.byteLength)} + data ${mib(copy.data.byteLength)}), over the device's storage binding limit of ${mib(limit)}; packing: 'split' binds them separately (each under the limit: table ${copy.table.byteLength <= limit ? 'fits' : 'does not fit'}, data ${copy.data.byteLength <= limit ? 'fits' : 'does not fit'}; a chunked packing (chooseSceneCopyPacking, 'packed:KxN') splits the data over several bindings)`); } const packedCopy = packSceneCopy(copy); const packed = device.createBuffer({ label: `${label} packed`, size: Math.max(16, packedCopy.byteLength), usage: STORAGE | COPY_DST | (options.copySrc ? COPY_SRC : 0) }); @@ -137,7 +194,7 @@ export function uploadSceneCopy(device: GPUDevice, copy: SceneCopy, options: Upl } const make = (name: string, data: Uint32Array) => { const size = Math.max(16, Math.ceil(data.byteLength / 16) * 16); - if (size > limit) throw new RangeError(`${label} ${name}: ${size} bytes exceeds the device's storage binding limit of ${limit} (chunking is a later task)`); + if (size > limit) throw new RangeError(`${label} ${name}: ${size} bytes exceeds the device's storage binding limit of ${limit} (a chunked packing, see chooseSceneCopyPacking, splits the data over several bindings)`); const buffer = device.createBuffer({ label: `${label} ${name}`, size, usage: STORAGE | COPY_DST | (options.copySrc ? COPY_SRC : 0) }); device.queue.writeBuffer(buffer, 0, data.buffer as ArrayBuffer, data.byteOffset, data.byteLength); return buffer; @@ -161,6 +218,51 @@ export function uploadSceneCopy(device: GPUDevice, copy: SceneCopy, options: Upl }; } +/** `uploadSceneCopy` with chunked data: the table (or header + table) in one buffer, the data in K buffers of `2^N` words (the last holds the rest). */ +function uploadChunked(device: GPUDevice, copy: SceneCopy, o: { label: string; packing: SceneCopyPacking; limit: number; byteLength: number; copySrc?: boolean; mipGenerator?: RtMipGenerator }): SceneCopyBuffers { + const { label, packing, limit } = o; + const { base, chunks, chunkWordsLog2 } = parseScenePacking(packing); + const usage = STORAGE | COPY_DST | (o.copySrc ? COPY_SRC : 0); + const stage = device.limits.maxStorageBuffersPerShaderStage; + if (stage !== undefined && 1 + chunks > stage) throw new RangeError(`${label}: ${packing} binds ${1 + chunks} storage buffers (table + ${chunks} data chunks), over the device's ${stage} per shader stage`); + if (4 * 2 ** chunkWordsLog2 > limit) throw new RangeError(`${label}: ${packing} chunks of ${mib(4 * 2 ** chunkWordsLog2)} are over the device's storage binding limit of ${mib(limit)}`); + const pieces = chunkSceneData(copy.data, chunks, chunkWordsLog2); + const tableBytes = base === 'packed' ? packedSceneCopyBytes(copy, { dataInline: false }) : Math.max(16, copy.table.byteLength); + if (tableBytes > limit) throw new RangeError(`${label}: the table is ${mib(tableBytes)}, over the device's storage binding limit of ${mib(limit)} (only the data is chunked)`); + let table: GPUBuffer | undefined; + let packed: GPUBuffer | undefined; + let head: GPUBuffer; + if (base === 'packed') { + const words = packSceneCopy(copy, { dataInline: false }).words; + head = packed = device.createBuffer({ label: `${label} packed table`, size: Math.max(16, words.byteLength), usage }); + device.queue.writeBuffer(packed, 0, words.buffer as ArrayBuffer, words.byteOffset, words.byteLength); + } else { + head = table = device.createBuffer({ label: `${label} table`, size: Math.max(16, Math.ceil(copy.table.byteLength / 16) * 16), usage }); + device.queue.writeBuffer(table, 0, copy.table.buffer as ArrayBuffer, copy.table.byteOffset, copy.table.byteLength); + } + const dataChunks = pieces.map((piece, c) => { + const buffer = device.createBuffer({ label: `${label} data ${c}/${chunks}`, size: Math.max(16, Math.ceil(piece.byteLength / 16) * 16), usage }); + if (piece.byteLength) device.queue.writeBuffer(buffer, 0, piece.buffer as ArrayBuffer, piece.byteOffset, piece.byteLength); + return buffer; + }); + const textures = copy.textures ? uploadSceneTextures(device, copy.textures, label, o.mipGenerator, o.copySrc) : undefined; + return { + packing, + ...(table ? { table } : {}), + ...(packed ? { packed } : {}), + dataChunks, + storageBytes: head.size + dataChunks.reduce((sum, b) => sum + b.size, 0), + layout: copy.layout, + byteLength: o.byteLength, + ...(textures ? { textures } : {}), + destroy() { + head.destroy(); + dataChunks.forEach((b) => b.destroy()); + destroySceneTextures(textures); + }, + }; +} + /** * Rewrites a scene copy into the buffers of an earlier upload when it fits (a rebuilt copy after instances moved or the lights changed: P1.4b has no * incremental update yet). Returns false, writing nothing, when the new copy needs bigger buffers or the texture layout changed: upload again then. @@ -168,6 +270,28 @@ export function uploadSceneCopy(device: GPUDevice, copy: SceneCopy, options: Upl * header's `dataBase` says where it is). The texture arrays are not touched. Needs `COPY_DST` (always set by `uploadSceneCopy`). */ export function writeSceneCopy(device: GPUDevice, buffers: SceneCopyBuffers, copy: SceneCopy): boolean { + if (buffers.dataChunks) { + // Chunked data: the table region is rewritten in place, every chunk too; a copy whose data needs more chunks than uploaded (or more bytes in one) needs a new upload (and a new kernel: K is in the packing). + const { base, chunks, chunkWordsLog2 } = parseScenePacking(buffers.packing); + if (copy.data.length > chunks * 2 ** chunkWordsLog2) return false; + const pieces = chunkSceneData(copy.data, chunks, chunkWordsLog2); + const uploaded = buffers.dataChunks; + if (pieces.some((piece, c) => (uploaded[c] as GPUBuffer).size < Math.max(16, Math.ceil(piece.byteLength / 16) * 16))) return false; + if (base === 'packed') { + const head = buffers.packed as GPUBuffer; + if (head.size < Math.max(16, packedSceneCopyBytes(copy, { dataInline: false }))) return false; + const words = packSceneCopy(copy, { dataInline: false }).words; + device.queue.writeBuffer(head, 0, words.buffer as ArrayBuffer, words.byteOffset, words.byteLength); + } else { + const head = buffers.table as GPUBuffer; + if (head.size < Math.max(16, copy.table.byteLength)) return false; + device.queue.writeBuffer(head, 0, copy.table.buffer as ArrayBuffer, copy.table.byteOffset, copy.table.byteLength); + } + pieces.forEach((piece, c) => { + if (piece.byteLength) device.queue.writeBuffer(uploaded[c] as GPUBuffer, 0, piece.buffer as ArrayBuffer, piece.byteOffset, piece.byteLength); + }); + return true; + } if (buffers.packing === 'packed') { const packed = buffers.packed as GPUBuffer; if (packed.size < Math.max(16, packedSceneCopyBytes(copy))) return false; @@ -247,7 +371,8 @@ export function uploadSceneTextures(device: GPUDevice, textures: SceneTextures, } export function rtSceneCopyBindGroupEntries(buffers: SceneCopyBuffers, firstBinding = 0): GPUBindGroupEntry[] { - const list = buffers.packing === 'packed' ? [buffers.packed as GPUBuffer] : [buffers.table as GPUBuffer, buffers.data as GPUBuffer]; + const head = scenePackingIsPacked(buffers.packing) ? (buffers.packed as GPUBuffer) : (buffers.table as GPUBuffer); + const list = buffers.dataChunks ? [head, ...buffers.dataChunks] : buffers.packing === 'packed' ? [head] : [head, buffers.data as GPUBuffer]; const entries: GPUBindGroupEntry[] = list.map((buffer, i) => ({ binding: firstBinding + i, resource: { buffer } })); const t = buffers.textures; if (t && !t.table) { @@ -261,7 +386,7 @@ export function rtSceneCopyBindGroupEntries(buffers: SceneCopyBuffers, firstBind /** Layout entries of the scene copy's bindings: table, data (one binding when `packing` is 'packed'), then (when `textures` is given, `arrays` binding) the texture arrays and their samplers. A `table` layout adds none: the pipeline layout needs `usesResourceTable` instead (`rtUsesResourceTable`). */ export function rtSceneCopyLayoutEntries(firstBinding = 0, textures?: TextureLayout | null, packing: SceneCopyPacking = DEFAULT_SCENE_PACKING): GPUBindGroupLayoutEntry[] { - const count = packing === 'packed' ? 1 : 2; + const count = sceneCopyStorageBuffers(packing); const entries: GPUBindGroupLayoutEntry[] = Array.from({ length: count }, (_, i) => ({ binding: firstBinding + i, visibility: COMPUTE, buffer: { type: 'read-only-storage' as const } })); if (textures && textures.binding !== 'table') { const n = textures.buckets.length; diff --git a/packages/raytracer/src/scene/scene-chunked.test.ts b/packages/raytracer/src/scene/scene-chunked.test.ts new file mode 100644 index 00000000..8d69ff96 --- /dev/null +++ b/packages/raytracer/src/scene/scene-chunked.test.ts @@ -0,0 +1,228 @@ +/** + * Chunked scene copy data (P1.4e, V515): the packing strings, the chunk twin, the generated WGSL and the choice of K. + * The GPU side (every accessor bit-exact on a forced small chunk size, both table placements) is `--page scene-copy chunk=14`. + */ +import { describe, expect, it } from 'vitest'; +import { buildCaps } from '../caps/index.ts'; +import { rtModuleStorageBuffers, rtModuleWgsl, rtSceneEntries } from '../trace/index.ts'; +import { DEFAULT_SCENE_PACKING, parseScenePacking, sceneCopyChunkedPacking, sceneCopyStorageBuffers, scenePackingChunks, scenePackingIsPacked, type SceneCopyPacking } from './constants.ts'; +import { chooseSceneCopyPacking, rtSceneCopyLayoutEntries } from './gpu.ts'; +import { buildSceneCopy, chunkSceneData, packSceneCopy, packedSceneCopyBytes, readChunkedDataWord, type SceneCopy } from './scene-copy.ts'; +import { rtApplyScenePacking, rtChunkSceneData, rtPackSceneAccess, rtSceneBufferBindings, rtSceneWgsl } from './scene-wgsl.ts'; +import { balanced } from '../wgsl-names.testutil.ts'; + +const caps = buildCaps({ features: new Set(['subgroups']), limits: {} }, new Set()); +const slot = { group: 1, firstBinding: 0 }; +const layout = { normals: true, uvs: true, positions: true }; +const textures = { buckets: [{ width: 8, height: 8, colorSpace: 'srgb' as const, wrap: 'repeat' as const, layers: 1, mipLevels: 4 }] }; +const ID = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; + +/** A grid of n x n quads (2 n^2 triangles), one in sixteen emissive (a light map), a sun and a 16 x 8 environment map: indices, vertices, a light map and an env map all in `data`. */ +function gridScene(n: number): SceneCopy { + const side = n + 1; + const positions = new Float32Array(side * side * 3); + const normals = new Float32Array(side * side * 3); + const uvs = new Float32Array(side * side * 2); + for (let j = 0; j < side; j++) { + for (let i = 0; i < side; i++) { + const v = j * side + i; + positions.set([i, 0.1 * Math.sin(i + 2 * j), j], v * 3); + normals.set([0, 1, 0], v * 3); + uvs.set([i / n, j / n], v * 2); + } + } + const indices: number[] = []; + for (let j = 0; j < n; j++) { + for (let i = 0; i < n; i++) { + const a = j * side + i; + indices.push(a, a + side, a + 1, a + 1, a + side, a + side + 1); + } + } + const triangles = indices.length / 3; + const triangleMaterials = Uint16Array.from({ length: triangles }, (_, t) => (t % 16 === 0 ? 1 : 0xffff)); + const env = new Float32Array(16 * 8 * 3).map((_, k) => 0.5 + ((k * 7) % 13) / 13); + return buildSceneCopy({ + meshes: [{ positions, indices: Uint32Array.from(indices), normals, uvs, triangleMaterials }], + instances: [{ meshIndex: 0, instanceIndex: 0, objectToWorld: ID, material: 0 }], + materials: [{}, { emissionColor: [1, 2, 3] }], + sun: { direction: [0, -1, 0], irradiance: [1, 1, 1] }, + environment: { map: { width: 16, height: 8, channels: 3, data: env } }, + }); +} + +describe('chunked packing strings', () => { + it('parse, build and count', () => { + expect(sceneCopyChunkedPacking('split', 3, 14)).toBe('split:3x14'); + expect(parseScenePacking('packed:4x25')).toEqual({ base: 'packed', chunks: 4, chunkWordsLog2: 25 }); + expect(parseScenePacking('split')).toEqual({ base: 'split', chunks: 0, chunkWordsLog2: 0 }); + expect(scenePackingChunks('packed')).toBe(0); + expect(scenePackingChunks('split:2x20')).toBe(2); + expect(scenePackingIsPacked('packed:2x20')).toBe(true); + expect(scenePackingIsPacked('split:2x20')).toBe(false); + expect(scenePackingIsPacked('split')).toBe(false); + expect(() => parseScenePacking('packed:0x14' as SceneCopyPacking)).toThrow(RangeError); + expect(() => parseScenePacking('split:2x1' as SceneCopyPacking)).toThrow(RangeError); + expect(() => parseScenePacking('split:2x31' as SceneCopyPacking)).toThrow(RangeError); + expect(() => parseScenePacking('split:300x30' as SceneCopyPacking)).toThrow(/u32/); // more than 2^32 words: an index would wrap + expect(() => parseScenePacking('chunked' as SceneCopyPacking)).toThrow(/unknown/); + }); + + it('costs one storage binding per chunk, in every budget helper', () => { + expect(sceneCopyStorageBuffers('split')).toBe(2); + expect(sceneCopyStorageBuffers('packed')).toBe(1); + expect(sceneCopyStorageBuffers('split:3x20')).toBe(4); + expect(sceneCopyStorageBuffers('packed:3x20')).toBe(4); + expect(rtSceneBufferBindings('packed:5x20')).toBe(6); + expect(rtSceneEntries('packed:2x20')).toHaveLength(3); + expect(rtSceneEntries('split:2x20')).toHaveLength(3); + const base = rtModuleStorageBuffers({ scene: { slot, layout, packing: 'packed' } }); + expect(rtModuleStorageBuffers({ scene: { slot, layout, packing: 'packed:4x20' } })).toBe(base + 4); + expect(rtModuleStorageBuffers({ scene: { slot, layout, packing: 'split:4x20' } })).toBe(base + 4); + expect(rtSceneCopyLayoutEntries(0, null, 'packed:3x20').map((e) => e.binding)).toEqual([0, 1, 2, 3]); + expect(rtSceneCopyLayoutEntries(0, textures, 'split:2x20').map((e) => e.binding)).toEqual([0, 1, 2, 3, 4]); // the texture + sampler follow the chunks + expect(DEFAULT_SCENE_PACKING).toBe('packed'); // chunking is opt-in + }); +}); + +describe('chunk twin', () => { + const copy = gridScene(40); + it('every data word reads back through its chunk, for sizes that straddle triangles, vertices and the env map', () => { + expect(copy.data.length).toBeGreaterThan(10_000); + for (const log2 of [2, 3, 7, 10, 12, 14]) { + const chunks = Math.ceil(copy.data.length / 2 ** log2); + const pieces = chunkSceneData(copy.data, chunks, log2); + expect(pieces).toHaveLength(chunks); + expect(pieces.reduce((n, p) => n + p.length, 0)).toBe(copy.data.length); + for (let i = 0; i < copy.data.length; i++) if (readChunkedDataWord(pieces, log2, i) !== copy.data[i]) throw new Error(`log2 ${log2} word ${i}`); + } + }); + + it('extra chunks past the end are empty, too few chunks throw', () => { + expect(chunkSceneData(copy.data, Math.ceil(copy.data.length / 4096) + 2, 12).slice(-2).map((p) => p.length)).toEqual([0, 0]); + expect(() => chunkSceneData(copy.data, 2, 10)).toThrow(RangeError); + }); + + it('the packed table buffer of a chunked copy is header + table only', () => { + const p = packSceneCopy(copy, { dataInline: false }); + expect(p.byteLength).toBe(packedSceneCopyBytes(copy, { dataInline: false })); + expect(p.byteLength).toBe(16 + copy.table.byteLength); + expect(p.byteLength).toBeLessThan(packedSceneCopyBytes(copy)); + expect(Array.from(p.words.subarray(p.tableBase * 4))).toEqual(Array.from(copy.table)); + }); +}); + +describe('chunked WGSL', () => { + const chunked = (packing: SceneCopyPacking, extra = {}) => rtModuleWgsl(caps, { triangleLeaves: 'indexed', scene: { slot, layout, packing, ...extra }, shade: true }); + + it('split:KxN keeps rtSceneTable and binds one rtSceneData per chunk, with the chunk pick as rtSceneWord', () => { + const code = chunked('split:3x14'); + expect(balanced(code)).toBe(true); + expect(code).toContain('var rtSceneTable: array;'); + for (let c = 0; c < 3; c++) expect(code).toContain(`@group(1) @binding(${1 + c}) var rtSceneData${c}: array;`); + expect(code).toMatch(/fn rtSceneWord\(i: u32\) -> u32 \{\s*let o = i & 0x3fffu;\s*switch \(i >> 14u\)/); + expect(code).not.toMatch(/rtSceneData\[/); + expect(code).toContain('rtSceneTable[1]'); + expect(code).not.toMatch(/rtScene\[/); + expect(code).toMatch(/rtSceneWord\(/); + }); + + it('packed:KxN reads the table from rtScene (header + table) and the data from the chunks; textures follow the chunks', () => { + const code = chunked('packed:2x12', { textures }); + expect(balanced(code)).toBe(true); + expect(code).toContain('@group(1) @binding(0) var rtScene: array;'); + expect(code).toContain('@group(1) @binding(1) var rtSceneData0: array;'); + expect(code).toContain('@group(1) @binding(2) var rtSceneData1: array;'); + expect(code).toContain('@group(1) @binding(3) var rtTex0: texture_2d_array;'); + expect(code).toContain('@group(1) @binding(4) var rtSmp0: sampler;'); + expect(code).not.toMatch(/rtSceneTable|rtSceneData\[/); + expect(code).not.toMatch(/rtScene\[rtScene\[0\]/); // no data region in the buffer + const bindings = [...code.matchAll(/@group\(1\)\s*@binding\((\d+)\)/g)].map((m) => Number(m[1])); + expect(bindings).toEqual([0, 1, 2, 3, 4]); + }); + + it('one chunk is a plain lookup (no mask, no switch)', () => { + const code = rtSceneWgsl({ group: 0, firstBinding: 0, packing: 'split:1x20' }); + expect(code).toMatch(/fn rtSceneWord\(i: u32\) -> u32 \{\s*return rtSceneData0\[i\];\s*\}/); + expect(code).not.toContain('switch'); + }); + + it('the generated pick is the twin: mask, shift and case order read the chunk the TypeScript twin reads', () => { + const copy = gridScene(12); + for (const [packing, log2, chunks] of [['split:6x10', 10, 6], ['packed:9x9', 9, 9], ['split:3x13', 13, 3]] as const) { + const real = Math.ceil(copy.data.length / 2 ** log2); + expect(real).toBeLessThanOrEqual(chunks); + const text = rtSceneWgsl({ group: 0, firstBinding: 0, packing }); + const mask = Number(/let o = i & (0x[0-9a-f]+)u;/.exec(text)![1]); + const shift = Number(/switch \(i >> (\d+)u\)/.exec(text)![1]); + const cases = [...text.matchAll(/case (\d+)u: \{\s*return rtSceneData(\d+)\[o\];/g)].map((m) => [Number(m[1]), Number(m[2])]); + expect(cases.map(([a, b]) => a === b)).toEqual(Array(chunks - 1).fill(true)); + expect(text).toContain(`default: {\n return rtSceneData${chunks - 1}[o];`); + const pieces = chunkSceneData(copy.data, chunks, log2); + // The generated function, evaluated: chunk = case of (i >> shift) else the last one, word = i & mask. + const evaluate = (i: number) => (pieces[Math.min(i >>> shift, chunks - 1)] as Uint32Array)[i & mask] as number; + for (let i = 0; i < copy.data.length; i++) if (evaluate(i) !== copy.data[i]) throw new Error(`${packing} word ${i}`); + expect(mask).toBe(2 ** log2 - 1); + expect(shift).toBe(log2); + } + }); + + it('the rewrites: chunk-only keeps the table accessors, packing rewrites both, split is untouched, and all are idempotent', () => { + const src = 'let a = rtSceneTable[rtSceneTable[3].z + slot]; let b = bitcast(rtSceneData[base + (k - 1u) * stride]);'; + expect(rtChunkSceneData(src)).toBe('let a = rtSceneTable[rtSceneTable[3].z + slot]; let b = bitcast(rtSceneWord(base + (k - 1u) * stride));'); + expect(rtApplyScenePacking(src, 'split')).toBe(src); + expect(rtApplyScenePacking(src, 'packed')).toBe(rtPackSceneAccess(src)); + expect(rtApplyScenePacking(src, 'packed:3x12')).toBe(rtPackSceneAccess(src)); + expect(rtApplyScenePacking(src, 'split:3x12')).toBe(rtChunkSceneData(src)); + const once = rtChunkSceneData('rtSceneData[rtSceneTable[record + 7u].x + triangle]'); + expect(once).toBe('rtSceneWord(rtSceneTable[record + 7u].x + triangle)'); + expect(rtChunkSceneData(once)).toBe(once); + expect(() => rtChunkSceneData('rtSceneData[i')).toThrow(/unbalanced/); + }); + + it('the default text does not change: split and packed modules are what they were', () => { + const plain = rtModuleWgsl(caps, { triangleLeaves: 'indexed', scene: { slot, layout }, shade: true }); + expect(plain).toBe(rtModuleWgsl(caps, { triangleLeaves: 'indexed', scene: { slot, layout, packing: 'packed' }, shade: true })); + expect(plain).not.toMatch(/rtSceneData\d/); + expect(chunked('split')).toContain('rtSceneData: array'); + }); +}); + +describe('chooseSceneCopyPacking', () => { + const copy = gridScene(40); + const MiB = 2 ** 20; + const device = (binding: number, stage = 16) => ({ limits: { maxStorageBufferBindingSize: binding, maxBufferSize: 4 * binding, maxStorageBuffersPerShaderStage: stage } }); + + it('returns the plain packing while the copy fits one binding', () => { + expect(chooseSceneCopyPacking(device(128 * MiB), copy)).toBe('packed'); + expect(chooseSceneCopyPacking(device(128 * MiB), copy, { base: 'split' })).toBe('split'); + }); + + it('chunks past the limit: the largest power-of-two chunk under it, as many as the data needs', () => { + const tiny = 32 * 1024; + const packing = chooseSceneCopyPacking(device(tiny), copy, { base: 'split', bindingLimit: tiny }); + const { base, chunks, chunkWordsLog2 } = parseScenePacking(packing); + expect(base).toBe('split'); + expect(chunkWordsLog2).toBe(13); // 2^13 words = 32 KiB + expect(chunks).toBe(Math.ceil(copy.data.length / 2 ** 13)); + expect(chunks).toBeGreaterThan(1); + // Packed: the table + header must fit, then the same chunking. + expect(chooseSceneCopyPacking(device(tiny), copy, { bindingLimit: tiny })).toBe(`packed:${chunks}x13`); + }); + + it('forces chunks of a chosen size even when the copy fits (tests, spreading a scene over smaller buffers)', () => { + expect(chooseSceneCopyPacking(device(128 * MiB), copy, { chunkWordsLog2: 12 })).toBe(`packed:${Math.ceil(copy.data.length / 4096)}x12`); + }); + + it('counts the storage-buffer budget: scene buffers + the kernel\'s others against the stage limit', () => { + const chunks = Math.ceil(copy.data.length / 4096); + expect(() => chooseSceneCopyPacking(device(128 * MiB, chunks + 3), copy, { chunkWordsLog2: 12, otherStorageBuffers: 3 })).toThrow(new RegExp(`${1 + chunks} scene copy storage buffers \\+ 3 other = ${4 + chunks}, over the ${chunks + 3}`)); + expect(() => chooseSceneCopyPacking(device(128 * MiB, 8), copy, { chunkWordsLog2: 12, otherStorageBuffers: 3, stageLimit: 64 })).not.toThrow(); + expect(() => chooseSceneCopyPacking(device(128 * MiB, 64), copy, { chunkWordsLog2: 12, otherStorageBuffers: 3, stageLimit: chunks + 3 })).toThrow(new RegExp(`over the ${chunks + 3} storage buffers`)); + }); + + it('refuses a table over the limit (only the data is chunked) and a chunk over the limit', () => { + expect(() => chooseSceneCopyPacking(device(1024), copy, { bindingLimit: 1024 })).toThrow(/table is .* over the storage binding limit/); + expect(() => chooseSceneCopyPacking(device(128 * MiB), copy, { chunkWordsLog2: 28, bindingLimit: 64 * MiB })).toThrow(/over the storage binding limit/); + expect(() => chooseSceneCopyPacking(device(128 * MiB), copy, { chunkWordsLog2: 1 })).toThrow(/outside/); + }); +}); diff --git a/packages/raytracer/src/scene/scene-copy.ts b/packages/raytracer/src/scene/scene-copy.ts index 8882508a..5cc6a00d 100644 --- a/packages/raytracer/src/scene/scene-copy.ts +++ b/packages/raytracer/src/scene/scene-copy.ts @@ -409,14 +409,15 @@ export interface PackedSceneCopy { byteLength: number; } -/** Bytes of the packed buffer without building it (16-byte aligned regions). */ -export function packedSceneCopyBytes(copy: Pick): number { - return (PACKED_HEADER_VEC4S + copy.table.length / 4 + Math.ceil(copy.data.length / 4)) * 16; +/** Bytes of the packed buffer without building it (16-byte aligned regions). `dataInline: false` (chunked data, P1.4e): header + table only, the data lives in its chunks. */ +export function packedSceneCopyBytes(copy: Pick, options: { dataInline?: boolean } = {}): number { + return (PACKED_HEADER_VEC4S + copy.table.length / 4 + (options.dataInline === false ? 0 : Math.ceil(copy.data.length / 4))) * 16; } -export function packSceneCopy(copy: Pick): PackedSceneCopy { +export function packSceneCopy(copy: Pick, options: { dataInline?: boolean } = {}): PackedSceneCopy { + const inline = options.dataInline !== false; const tableVec4s = copy.table.length / 4; - const dataVec4s = Math.ceil(copy.data.length / 4); + const dataVec4s = inline ? Math.ceil(copy.data.length / 4) : 0; const tableBase = PACKED_TABLE_BASE_VEC4S; const dataBase = tableBase + tableVec4s; const total = dataBase + dataVec4s; @@ -426,7 +427,7 @@ export function packSceneCopy(copy: Pick): PackedSc words[PACKED_HEADER.dataWords] = copy.data.length; words[PACKED_HEADER.totalVec4s] = total; words.set(copy.table, tableBase * 4); - words.set(copy.data, dataBase * 4); + if (inline) words.set(copy.data, dataBase * 4); return { words, tableBase, dataBase, tableBytes: tableVec4s * 16, dataBytes: dataVec4s * 16, byteLength: words.byteLength }; } @@ -436,6 +437,22 @@ export function readPackedDataWord(words: Uint32Array, i: number): number { return words[(dataBase + (i >>> 2)) * 4 + (i & 3)] as number; } +/** + * Chunked data (P1.4e): the data words split into `chunks` pieces of `2^chunkWordsLog2` words (views, no copy; the last holds the rest, a chunk past the end is empty). + * Word `i` is in chunk `i >>> log2` at `i & (2^log2 - 1)`: no word is ever split, so a mesh's indices, a vertex's floats or an environment-map texel may straddle a chunk boundary + * and every access is still one lookup (V515). + */ +export function chunkSceneData(data: Uint32Array, chunks: number, chunkWordsLog2: number): Uint32Array[] { + const size = 2 ** chunkWordsLog2; + if (data.length > chunks * size) throw new RangeError(`chunkSceneData: ${data.length} data words do not fit ${chunks} chunks of ${size} words`); + return Array.from({ length: chunks }, (_, c) => data.subarray(Math.min(c * size, data.length), Math.min((c + 1) * size, data.length))); +} + +/** Twin of WGSL `rtSceneWord(i)` over chunked data. */ +export function readChunkedDataWord(chunks: readonly Uint32Array[], chunkWordsLog2: number, i: number): number { + return (chunks[i >>> chunkWordsLog2] as Uint32Array)[i & (2 ** chunkWordsLog2 - 1)] as number; +} + /** Twin of WGSL `rtScene[PACKED_TABLE_BASE + i]`: table vec4 `i` as 4 words. */ export function readPackedTableVec4(words: Uint32Array, i: number): Uint32Array { const at = (((words[PACKED_HEADER.tableBase] as number) + i) * 4) >>> 0; diff --git a/packages/raytracer/src/scene/scene-wgsl.ts b/packages/raytracer/src/scene/scene-wgsl.ts index f1b8d807..bfa8bf53 100644 --- a/packages/raytracer/src/scene/scene-wgsl.ts +++ b/packages/raytracer/src/scene/scene-wgsl.ts @@ -28,7 +28,7 @@ * fn rtApplyMaterialTextures(m, uv, uvFootprint) -> RtMaterial glTF semantics: baseColor * rgb, opacity * a, roughness * g, metalness * b, emission * rgb * fn rtApplyNormalMap(n, tangent, texel) -> vec3f tangent-space normal map (glTF: +Y up) around the shading normal */ -import { INSTANCE_LIGHT, LIGHT_FLAG, LIGHT_KIND, LIGHT_MAP_MODE, LIGHT_RECORD_VEC4S, PACKED_HEADER, PACKED_TABLE_BASE_VEC4S, SCENE_HEADER_VEC4S, SCENE_NONE, DEFAULT_SCENE_PACKING, type SceneCopyPacking } from './constants.ts'; +import { INSTANCE_LIGHT, LIGHT_FLAG, LIGHT_KIND, LIGHT_MAP_MODE, LIGHT_RECORD_VEC4S, PACKED_HEADER, PACKED_TABLE_BASE_VEC4S, SCENE_HEADER_VEC4S, SCENE_NONE, DEFAULT_SCENE_PACKING, parseScenePacking, sceneCopyStorageBuffers, scenePackingIsPacked, type SceneCopyPacking } from './constants.ts'; import { MATERIAL_FLAG, MATERIAL_RECORD_VEC4S } from './material.ts'; import { rtLightSampleWgsl } from './light-sample.ts'; import { SURFACE_TABLE } from '../trace/constants.ts'; @@ -49,9 +49,9 @@ export interface SceneWgslOptions { packing?: SceneCopyPacking; } -/** Bindings the scene copy's buffers take (2 split, 1 packed): textures start after them. */ +/** Bindings the scene copy's buffers take (2 split, 1 packed, `1 + chunks` with chunked data): textures start after them. */ export function rtSceneBufferBindings(packing: SceneCopyPacking = DEFAULT_SCENE_PACKING): number { - return packing === 'packed' ? 1 : 2; + return sceneCopyStorageBuffers(packing); } /** @@ -60,6 +60,27 @@ export function rtSceneBufferBindings(packing: SceneCopyPacking = DEFAULT_SCENE_ * parenthesised. Idempotent (the output has neither name). Does not touch the binding declarations: `rtSceneBindingsWgsl` emits those per packing. */ export function rtPackSceneAccess(source: string): string { + return rewriteSceneAccess(source, true); +} + +/** + * Chunked data with the table still in `rtSceneTable` (`split:KxN`): only `rtSceneData[e]` -> `rtSceneWord(e)` (the chunk pick, declared by `rtSceneBindingsWgsl`). + * Idempotent; the table accesses stay. + */ +export function rtChunkSceneData(source: string): string { + return rewriteSceneAccess(source, false); +} + +/** + * Points a source written against the split bindings at `packing`: unchanged for `split`, `rtPackSceneAccess` for a packed table (chunked or not), + * `rtChunkSceneData` for `split:KxN`. Every place that appends generated text to a finished scene module goes through this. + */ +export function rtApplyScenePacking(source: string, packing: SceneCopyPacking = DEFAULT_SCENE_PACKING): string { + if (scenePackingIsPacked(packing)) return rtPackSceneAccess(source); + return packing === 'split' ? source : rtChunkSceneData(source); +} + +function rewriteSceneAccess(source: string, tables: boolean): string { const re = /rtScene(Table|Data)\[/g; const convert = (text: string): string => { let out = ''; @@ -78,6 +99,7 @@ export function rtPackSceneAccess(source: string): string { const inner = convert(text.slice(open, close - 1)); out += text.slice(last, m.index); if (m[1] === 'Data') out += `rtSceneWord(${inner})`; + else if (!tables) out += `rtSceneTable[${inner}]`; else if (/^\d+u?$/.test(inner.trim())) out += `rtScene[${parseInt(inner, 10) + PACKED_TABLE_BASE_VEC4S}u]`; else out += `rtScene[${weakerThanAdd(inner) ? `(${inner})` : inner} + ${PACKED_TABLE_BASE_VEC4S}u]`; last = close; @@ -104,14 +126,29 @@ const hex = (value: number): string => `0x${value.toString(16)}u`; /** The bindings and the generic accessors (always emitted). */ export function rtSceneBindingsWgsl(o: SceneWgslOptions): string { - const packed = (o.packing ?? DEFAULT_SCENE_PACKING) === 'packed'; - const declarations = packed - ? `@group(${o.group}) @binding(${o.firstBinding}) var rtScene: array; + const packing = o.packing ?? DEFAULT_SCENE_PACKING; + const packed = scenePackingIsPacked(packing); + const { chunks, chunkWordsLog2 } = parseScenePacking(packing); + let declarations: string; + if (chunks > 0) { + // Chunked data (P1.4e): word `i` lives in chunk `i >> log2` at `i & mask`, one binding per chunk (WGSL has no binding arrays). The packed table buffer holds header + table only. + const decls = Array.from({ length: chunks }, (_, c) => `@group(${o.group}) @binding(${o.firstBinding + 1 + c}) var rtSceneData${c}: array;`).join('\n'); + const cases = Array.from({ length: chunks - 1 }, (_, c) => ` case ${c}u: {\n return rtSceneData${c}[o];\n }`).join('\n'); + const word = chunks === 1 + ? `fn rtSceneWord(i: u32) -> u32 {\n return rtSceneData0[i];\n}` + : `fn rtSceneWord(i: u32) -> u32 {\n let o = i & ${hex(2 ** chunkWordsLog2 - 1)};\n switch (i >> ${chunkWordsLog2}u) {\n${cases}\n default: {\n return rtSceneData${chunks - 1}[o];\n }\n }\n}`; + declarations = `${packed ? `@group(${o.group}) @binding(${o.firstBinding}) var rtScene: array;` : `@group(${o.group}) @binding(${o.firstBinding}) var rtSceneTable: array;`} +${decls} +${word}`; + } else { + declarations = packed + ? `@group(${o.group}) @binding(${o.firstBinding}) var rtScene: array; fn rtSceneWord(i: u32) -> u32 { return rtScene[rtScene[0][${PACKED_HEADER.dataBase}] + (i >> 2u)][i & 3u]; }` - : `@group(${o.group}) @binding(${o.firstBinding}) var rtSceneTable: array; + : `@group(${o.group}) @binding(${o.firstBinding}) var rtSceneTable: array; @group(${o.group}) @binding(${o.firstBinding + 1}) var rtSceneData: array;`; + } return /* wgsl */ ` const RT_NONE: u32 = ${hex(SCENE_NONE)}; ${declarations} @@ -532,5 +569,5 @@ export function rtSceneWgsl(o: SceneWgslOptions): string { if (!(o.materials ?? true)) throw new Error('rtSceneWgsl: textures need materials'); source += rtTexturesWgsl({ group: o.group, firstBinding: o.firstBinding, layout: o.textures, ...(o.packing ? { packing: o.packing } : {}) }); } - return (o.packing ?? DEFAULT_SCENE_PACKING) === 'packed' ? rtPackSceneAccess(source) : source; + return rtApplyScenePacking(source, o.packing ?? DEFAULT_SCENE_PACKING); } diff --git a/packages/raytracer/src/trace/interval-batch.ts b/packages/raytracer/src/trace/interval-batch.ts index c1fd9aed..6300ca4f 100644 --- a/packages/raytracer/src/trace/interval-batch.ts +++ b/packages/raytracer/src/trace/interval-batch.ts @@ -26,7 +26,7 @@ import type { Caps } from '../caps/detect.ts'; import { buildWgsl } from '../caps/wgsl.ts'; import { DEFAULT_SCENE_PACKING, type SceneCopyPacking } from '../scene/constants.ts'; import { rtSceneCopyBindGroupEntries, rtSceneCopyLayoutEntries, type SceneCopyBuffers } from '../scene/gpu.ts'; -import { rtPackSceneAccess } from '../scene/scene-wgsl.ts'; +import { rtApplyScenePacking } from '../scene/scene-wgsl.ts'; import type { SurfaceLayout } from './surface-table.ts'; import type { TextureLayout } from '../scene/texture.ts'; import type { RtShadeMode, RtShadeOptions } from '../shade/shade.ts'; @@ -311,8 +311,7 @@ export function rtIntervalKernelWgsl(caps: Caps, options: IntervalKernelOptions) const resolved = resolveIntervalOptions(options); const module = rtModuleWgsl(caps, moduleOptionsOf(options, resolved)); let hooks = options.hooksWgsl ?? ''; - const packed = options.scene && (options.scene.packing ?? DEFAULT_SCENE_PACKING) === 'packed'; - if (hooks && packed) hooks = rtPackSceneAccess(hooks); + if (hooks && options.scene) hooks = rtApplyScenePacking(hooks, options.scene.packing ?? DEFAULT_SCENE_PACKING); const entry = rtIntervalEntryWgsl(resolved); return `${module}\n${hooks}${entry}`; } diff --git a/packages/raytracer/src/trace/modules.ts b/packages/raytracer/src/trace/modules.ts index ab4437e9..6f0bb4dc 100644 --- a/packages/raytracer/src/trace/modules.ts +++ b/packages/raytracer/src/trace/modules.ts @@ -15,7 +15,7 @@ import { surfaceVertexOffsets, type SurfaceLayout } from './surface-table.ts'; import { RT_CORE_WGSL, rtBatchArgsWgsl, rtBatchWgsl, rtSurfaceWgsl } from './wgsl-source.ts'; import { RT_INTERVAL_WGSL } from './interval.ts'; import { DEFAULT_SCENE_PACKING, SCENE_HEADER_VEC4S, sceneCopyStorageBuffers, type SceneCopyPacking } from '../scene/constants.ts'; -import { rtPackSceneAccess, rtSceneWgsl, rtTextureTableEnable } from '../scene/scene-wgsl.ts'; +import { rtApplyScenePacking, rtSceneWgsl, rtTextureTableEnable } from '../scene/scene-wgsl.ts'; import type { TextureLayout } from '../scene/texture.ts'; import { rtShadeWgsl } from '../shade/shade-wgsl.ts'; import type { RtShadeOptions } from '../shade/shade.ts'; @@ -328,7 +328,7 @@ function inlineSource(options: RtModuleOptions & { traceSlot: BindingSlot }): st } if (options.shade) source += rtShadeWgsl(options.shade === true ? {} : options.shade); // The surface and shade text is written against the split bindings: point it at the packed buffer (the scene part already is). - if (options.scene && (options.scene.packing ?? DEFAULT_SCENE_PACKING) === 'packed') source = rtPackSceneAccess(source); + if (options.scene) source = rtApplyScenePacking(source, options.scene.packing ?? DEFAULT_SCENE_PACKING); return source; } @@ -353,10 +353,10 @@ export function rtWalkEntries(options: SceneFormat = {}): readonly ModuleBinding return traceModuleEntries({ triangleLeaves: sceneFormatOf(options).triangleLeaves }); } -/** The scene copy's bindings, in order: table, data (one binding, the packed buffer, with `packing: 'packed'`). */ +/** The scene copy's bindings, in order: table, data (one binding, the packed buffer, with `packing: 'packed'`; table + one per chunk with chunked data). */ export function rtSceneEntries(packing: SceneCopyPacking = DEFAULT_SCENE_PACKING): readonly ModuleBindingEntry[] { const entry: ModuleBindingEntry = { visibility: 0x4 /* GPUShaderStage.COMPUTE */, buffer: { type: 'read-only-storage' } }; - return packing === 'packed' ? [entry] : [entry, entry]; + return Array.from({ length: sceneCopyStorageBuffers(packing) }, () => entry); } /** Storage buffers the module adds to a kernel (spec section 3 binding budget). */