Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Kernel: the scene's read-only data in two buffers of sections (#89)

Yujia2c917b92a55d
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 62af41d..806e8d2 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2343,6 +2343,35 @@ turning, another part of the scene's. Now it reads the list of the tile it was s
camera turning 2 degrees a frame), the last moving frame, dE / p99: 2.00 / 8.57 without lists, 0.86 / 4.82 with
them at the pixel, 0.80 / 3.54 now; 0.19 ms of a list scene's trace (3.57 -> 3.76 on lamp-rooms).
+**The scene's read-only data in two buffers (2026-11-15, after it).** New scene data rode in other data's buffers,
+since the kernel had no binding to spare (28 of Metal's 29 with the translucency pass): the light tree after the
+emitter CDF, the light groups after the lights, the procedural geometry after the environment's CDF, the vertex
+colours after the previous vertices. A browser's kernel had its seven tables a second time as the sized arrays of a
+struct, copied every frame and compiled again when one doubled. Now the tables are the sections of one buffer of
+vec4s and the flat arrays the sections of one of 32-bit words (`renderer/src/heap.rs`; docs/RUNTIME.md "The scene's
+tables"), each found by an offset in the parameters: what a scene has more of is a section, a table that grows
+compiles nothing, a browser copies nothing, and the integers that were read through a float's bits (procedural
+words, vertex colours) are read as integers.
+- Read all from the one buffer, the trace was 3 to 5 % slower natively (Bistro 8.57 -> 8.98 ms): the offset fetched
+ before every read, the records' assembly, and a third no single change explains (seven timing variants). So
+ where a stage has the bindings, the seven tables read at every hit or light are bound again as typed views of
+ their sections, and the light tree and the environment's CDF are their buffers' first sections, read from
+ element 0. Trace against main (1440p at 0.375, alternated, ms): Bistro 8.58 -> 8.65, Zero Day 9.53 -> 9.57,
+ lamp-rooms 3.80 -> 3.72, Kabukichō 16.35 -> 16.10; software traversal Bistro 47.17 -> 47.48, lamp-rooms the same.
+ A browser, with no binding for the views, reads from the buffer whole: in the merged layout natively Bistro
+ 47.2-47.7 -> 46.8, lamp-rooms the same. The count of bindings natively is as it was (22, 28 with the translucency
+ pass); what changed is that new data does not need one.
+- The first build passed the whole suite and render-identity (0 of 192 changed in four layouts) and still drew
+ Bistro wrong live (dE 7.12 for 1.82): the live loader gave the light tree to its tables before the upload read
+ its nodes, and no test had a tree in a live view before an edit rewrote it. What showed it was the timing: a trace
+ a third faster. Fixed, with the tests that see it (`light/emitter-tree`, `-live`: 1.4 for 73.6 without the fix).
+- Android keeps four tables' uniform copies until a device has run without them (why its driver misread them is
+ not known).
+- Checks, with the loop guard: the unit tests and test-render (194); render-identity against main natively, merged,
+ under software traversal and with the uniform tables: 0 of 194 changed in any; bench-window's five shots and
+ still-kabukicho as main's to the digit (the moving ones within 0.3 %); offline renders of five scenes as main's
+ (three byte-identical, Bistro and Zero Day within what a build differs from itself).
+
## 2. Temporal fixes
Targets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); the
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 7977c2a..a12684b 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -741,22 +741,22 @@ tree (ROADMAP § 6).
the node host as `GameSession` does, and sends the canvas' clicks down the same path. `node tools/build-web.ts
[game.ts] --serve` builds and serves it (needs the wasm-bindgen CLI of the crate's version).
- **The merged binding layout** (`renderer/src/merged.rs`). WebGPU gives a stage 8 storage buffers by default; the
- kernel binds 19. (The live passes need none of it: each has a layout of its own, of the bindings its entry point
+ kernel binds 20. (The live passes need none of it: each has a layout of its own, of the bindings its entry point
uses, `renderer/src/live/layout.rs` from live.wgsl as build.rs reads it, and none binds more than eight, a unit
- test's check; a page binds them as natively.) There is one source: pathtrace.wgsl declares the kernel's tables and
- its group-1 buffers in an `@if(merged) { .. } @else { .. }` block each (WESL's conditional translation, "The
- kernel's source"), and the kernel reads and writes them only through functions each block declares
- (`material_at`, `cache_acc_add`, `refl_store`, ...).
- - The kernel's seven tables become the arrays of one struct in one buffer; their lengths are WESL constants the
- source imports (gpu.rs `KernelVariant::constants`), each a power of two above a floor, so a kernel is compiled
- again only when a table doubles. The renderer keeps writing its own buffers and a frame copies them into the
- struct's.
+ test's check; a page binds them as natively.) There is one source: pathtrace.wgsl declares the views of its
+ tables and its group-1 buffers in an `@if(merged) { .. } @else { .. }` block each (WESL's conditional
+ translation, "The kernel's source"), and the kernel reads and writes them only through functions each block
+ declares (`material_at`, `cache_acc_add`, `refl_store`, ...).
+ - The scene's tables are the sections of one buffer on every device ("The scene's tables"). Here the kernel has
+ no views of them and reads its seven tables from the buffer whole: no second copy of a table, nothing copied a
+ frame, no kernel compiled when one grows.
- The kernel's six group-1 buffers (the radiance cache, what the live passes read of a trace) are ranges of one
- buffer, the arrays of a second struct; what the live passes read of it starts at multiples of 256 bytes, so they
- bind those ranges as buffers of their own.
+ buffer, the arrays of a struct whose lengths are WESL constants the source imports (gpu.rs
+ `KernelVariant::constants`); what the live passes read of it starts at multiples of 256 bytes, so they bind
+ those ranges as buffers of their own.
- The merged block declares none of the buffers by its own name, so a read or write that goes past the functions
does not compile in it (naga names the line). A test reads the merged variants with naga: valid WGSL, 8 storage
- buffers for the kernel (19 as written), the structs' arrays where the Rust side puts them.
+ buffers for the kernel (20 as written), the struct's arrays where the Rust side puts them.
- Until 2026-11-14 the browser's kernel was written from the native one as text: a scanner of WGSL in merged.rs
found every use of the thirteen names, followed the locals that shadowed them through their scopes, and rewrote
each use (the uniform tables and the loop guard were made the same way).
@@ -1265,6 +1265,43 @@ too is an override, from F_TINT).
- The repository's Rust is pinned (`rust-toolchain.toml`, 1.100.0): wesl-rs 0.6 asks for 1.97.1 or newer, and the
determinism checks' recorded hashes are of one compiler.
+## The scene's tables
+
+The kernel's read-only scene data other than triangles is two storage buffers, each a row of sections
+(`renderer/src/heap.rs`):
+- `tables` (group 0, binding 4), vec4s (`Table`): the light tree's nodes, materials, lights, the light groups'
+ spheres, the emitter CDF with its guide table, the texture pages' rects, objects, instance records, media and the
+ GGX energy table.
+- `words` (binding 5), 32-bit words (`Stream`): the environment's CDF, the procedural geometry's data, the vertex
+ colours (`env_cdf_at`, `pword`, `vcolor_word`). Integers are read as integers, not through a float's bits.
+
+`Params::table_first` and `word_first` name each section's first element and are written with the parameters
+(`Uploaded::place`). What a scene has more of is another section, not another binding.
+- **One buffer, two ways to read it.** The renderer makes, writes and grows one tables' buffer on every device.
+ The seven tables read at every hit or light (materials, lights, the emitter CDF, texture rects, objects,
+ instances, media) are bound again as typed arrays over their sections (bindings 12 to 18; merged.rs
+ `TABLE_VIEWS`), and the kernel reads them as it would buffers of their own. In the merged layout, a browser's,
+ which has no binding for the views, the kernel reads all seven from the buffer whole: a record made of its vec4s
+ from the section's offset.
+- **Why the views.** Reading everything from the buffer whole natively cost 3 to 5 % of the trace on an Apple M5
+ (1440p at 0.375, hardware traversal; Bistro 8.57 -> 8.98 ms, Zero Day 9.52 -> 9.98, lamp-rooms 3.79 -> 3.92). By
+ timing variants: the offset fetched from the parameters before every read 0.16 ms of Bistro's 0.41 (as a pipeline
+ constant it is free, but a table that grows then compiles a pipeline; read once into private variables it is
+ not), records made of vec4s instead of read as structs 0.08, the rest not found in any one change. With the views:
+ Bistro +0.07 ms (0.8 %), Zero Day +0.04, lamp-rooms -0.08.
+- A heap's first section is at element 0 whatever grows, so it is read with no offset: the light tree and the
+ environment's CDF, the two read most that have no view (with an offset: Bistro +0.15 ms, Zero Day +0.13).
+- A section starts at a multiple of 256 bytes, so it can be bound as a buffer of its own: the views, and the
+ particle passes' objects (read-write).
+- A section that outgrows its room (materials or emitters added while the game runs, an edit's objects or records)
+ gets more in a new buffer, the rest copied on the GPU (`Heap::grow`), and the bind groups that hold the buffer
+ are made again (`Gpu::rebind_scene`: the kernel's and the particle passes'). No kernel is compiled for it.
+- Until 2026-11-15 each table was a buffer of its own; the light groups rode after the lights, the light tree after
+ the emitter CDF, the procedural data after the environment's CDF and the vertex colours after the previous
+ vertices; and a browser's kernel had seven tables as the sized arrays of a struct, a second copy of each made
+ every frame, and was compiled again when a table doubled. The count of bindings is as it was: 22 buffers and
+ acceleration structures a stage natively, 28 of Metal's 29 with the translucency pass (29 with the loop guard's).
+
## Random numbers
`shaders/sample.wgsl`: shuffled, Owen-scrambled Sobol (Burley 2020; Cycles' Sobol-Burley), four dimensions padded by
@@ -1344,34 +1381,40 @@ on scenes that are not all at hand. What was measured again on this source, on t
on the device", and differs where it says so.
- **Uniform tables** (`GpuOptions::uniform_tables`, `THREERT_UNIFORM_TABLES=1|0`; default on Android; never with the
- merged layout). The driver gave the kernel other buffers' contents for four of its read-only storage buffers:
- `tex_info` (binding 14), `objects` (15), `instances` (17), `media` (18). As uniform buffers they read right.
- - The kernel's source has them under `@if(uniform_tables)` (pathtrace.wgsl): the four declarations as sized
- uniform arrays at the same bindings (their lengths WESL constants, merged.rs `UNIFORM_LEN`), and their accessors
- hold every index to the array (`min(i, last)`), so nothing is read outside a uniform buffer.
- - The renderer keeps writing its storage buffers. `Gpu::sync_tables` copies the four into their uniform buffers in
- a frame's encoder, after the particle passes (which write their objects' entries on the GPU) and before the trace.
+ merged layout). The driver gave the kernel other buffers' contents for four of its read-only storage buffers, each
+ a binding of its own then: `tex_info` (binding 14), `objects` (15), `instances` (17), `media` (18), all numbered
+ after the acceleration structure (13). As uniform buffers they read right.
+ - Since 2026-11-15 the four are views of their sections of the tables' buffer ("The scene's tables"), still at
+ bindings of their own (15 to 18), and the acceleration structure is the group's last binding (19). **Whether
+ the driver reads them right there is not known: no device has run it.** Until one has, Android keeps the
+ uniform copies; `THREERT_UNIFORM_TABLES=0` on the device is the run that decides (if it draws right, the copies
+ and their bounds can go).
+ - The kernel's source has them under `@if(uniform_tables)` (pathtrace.wgsl): four sized uniform arrays at
+ bindings 15 to 18 (merged.rs `UNIFORM_TABLES`; their lengths WESL constants), and their accessors hold every
+ index to the array (`min(i, last)`), so nothing is read outside a uniform buffer.
+ - The renderer writes the tables' buffer. `Gpu::sync_tables` copies the four sections into their uniform buffers
+ in a frame's encoder, after the particle passes (which write their objects' entries on the GPU) and before the
+ trace.
- A uniform binding holds 64 KiB, so the arrays are bounded: 2,048 textures, 4,096 object entries (1,365 objects;
1,024 with instance colours), 409 instance records (model instances, procedural objects, `dynamicGeometry`
meshes), all 32 media. A scene with more reads the last entry for the rest, and the renderer says so on stderr
- when it uploads the scene and once when in-place edits pass a bound. `THREERT_UNIFORM_TABLES=0` binds storage
- buffers again.
+ when it uploads the scene and once when in-place edits pass a bound. `THREERT_UNIFORM_TABLES=0` binds the
+ views of their sections.
- **The kernel's other storage buffers stay as they are**, each for its reason:
| buffer | size | decision |
|---|---|---|
- | `materials` (4), `lights` (5) | 288 B and 80 B an entry | storage: the device drew right with them as they are; 64 KiB would hold 227 materials |
- | `emitters` (6) | the emitter CDF and the light tree | storage: megabytes in a lit scene |
- | `env_cdf` (10) | the environment's CDF, then the procedural geometry's data | storage (megabytes); its light sampling is off on Android, below |
- | `tri_verts` (1), `attrs` (2), `nodes` (3), `prev_verts` (16) | per triangle | storage (megabytes) |
+ | `tables` (4) and its views `materials` (12), `lights` (13), `emitters` (14) | megabytes in a lit scene | storage: the device drew right with materials, lights and emitters as storage buffers (bindings 4 to 6 then) |
+ | `words` (5): the environment's CDF, the procedural geometry's data, vertex colours | megabytes | storage; the environment's light sampling is off on Android, below |
+ | `tri_verts` (1), `attrs` (2), `nodes` (3), `prev_verts` (6) | per triangle | storage (megabytes) |
| `accum` (11), group 1 (radiance cache, the trace's outputs, the loop guard's count) | per pixel, per cache entry | written by the kernel: cannot be uniform |
| group 2, the translucency pass (`timg`, `vpts`, `vcount`, `tlow`) | per pixel | written by the pass |
| the particle passes' `systems`, `spawns`, `grid`; the grid programs' `srcs` | small, read-only | storage: other shaders, of eleven bindings at most and no acceleration structure; not known to misread (the fix on the device left them alone) |
| the live passes (`live.wgsl`: 25 storage buffers, `ae_bins` and `ae_state` among them; at most eight a pass) | per pixel; two tiny | storage: written by the passes; the device showed their output right |
- Two of these are what a device run should look at first: `prev_verts` is the one storage buffer left after the
- acceleration structure's binding (13) and feeds the motion vectors of moving objects and the vertex colours;
- `env_cdf` also holds the procedural geometry (voxel worlds).
+ Two of these are what a device run should look at first: `prev_verts` (binding 16 then, after the acceleration
+ structure's) feeds the motion vectors of moving objects; `words` holds the procedural geometry (voxel worlds) and
+ the vertex colours.
- **The kernel's switches** (`gpu::KernelSwitches`; flags of the kernel's conditional translation, `@if` in its source, as a scene's features are: "The kernel's source" below):
| switch | default | what it does | on the device |
@@ -1447,7 +1490,7 @@ source under ThreeRT for Android 0.4.0, which sets `THREERT_PIPELINE_CACHE` and
149 ms and Material balls 74 against 96 are faster without ray queries; OpenStrikeRT is 336 against 146. A ray
query has a high fixed cost on this driver; ray queries stay the default. `THREERT_RASTER=1` (raster primary
visibility): Sunlit room 136 against 149 ms.
-- **Not looked at on the device:** voxel worlds and procedural geometry (`env_cdf`'s second half), particles, media,
+- **Not looked at on the device:** voxel worlds and procedural geometry (then `env_cdf`'s second half), particles, media,
a map with cutout foliage (`THREERT_CUTOUT_LITE`'s figures are the author's), `THREERT_ENV_NEE=1`, and the
motion vectors of moving objects (`prev_verts`): soldiers were looked at standing, not frame by frame in motion.
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 9b68239..05501da 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -19,8 +19,7 @@
// guard the loop guard (gpu.rs `loop_guard_of`, `guard_loops`)
// The numbers a variant is compiled for are WESL constants (`import constants::`, gpu.rs `KernelVariant::constants`): the
// merged layout's array lengths, the uniform tables', the loop guard's limit.
-@if(merged) import constants::{MT_MATERIALS, MT_LIGHTS, MT_EMITTERS, MT_TEX_INFO, MT_OBJECTS, MT_INSTANCES, MT_MEDIA,
- ML_CACHE_KEYS, ML_CACHE_ACC, ML_CACHE_VAL, ML_REFL, ML_MOTION_OUT, ML_DIRECT_OUT};
+@if(merged) import constants::{ML_CACHE_KEYS, ML_CACHE_ACC, ML_CACHE_VAL, ML_REFL, ML_MOTION_OUT, ML_DIRECT_OUT};
@if(uniform_tables) import constants::{UT_TEX_INFO, UT_OBJECTS, UT_INSTANCES, UT_MEDIA};
@if(merged || guard) import constants::GUARD_WORDS;
@if(guard) import constants::LOOP_GUARD_LIMIT;
@@ -104,13 +103,15 @@ struct Params {
light_lod: vec4<f32>, // live light LOD (lib.rs emitter_lod): reference position, d0 (0 = off)
emit_power: vec4<f32>, // x: the emitter CDF's total without light LOD (= misc.y when it is off); y: emitter cull radius (0 = off); z: its reach in the view cone
lod_view: vec4<f32>, // emitter cull's view cone (lib.rs EmitterCull): forward direction, cos of the half-angle
- ltree: vec4<f32>, // light tree (ltree.rs): first node in `emitters` (bits), its entry count (bits: the moving emitters' first), P(pick a moving one), candidates at camera hits (0 = off)
- procs: vec4<u32>, // procedural geometry (F_PROC): its data's first word in env_cdf, object count, first record in `instances`, -
+ ltree: vec4<f32>, // light tree (ltree.rs): -, its entry count (bits: the moving emitters' first), P(pick a moving one), candidates at camera hits (0 = off)
+ procs: vec4<u32>, // procedural geometry (F_PROC): -, object count, first record in `instances`, -
aerial: vec4<f32>, // the sky's aerial perspective (F_AERIAL): density multiple, Rayleigh scale, Mie scale, -
background: vec4<f32>, // three.js scene.background (radiance), 1 (F_BACKGROUND)
ltile: vec4<u32>, // live light tiles (`lt_list_start`): the lists' first vec4 in direct_out (0: none), tiles a row, the grid's offset when they were built (x | y << 16), candidates a vertex the camera sees takes from its list
ltile2: vec4<u32>, // the traced size they were built at, -, -
lt_cam: array<vec4<f32>, 4>, // the camera they were built under: position (w = tan(fov/2)), forward (w = aspect), right, up
+ table_first: array<vec4<u32>, 3>, // each table's first vec4 in `tables` (heap.rs `Table`): light tree (0), materials, lights, light groups; emitters, tex_info, objects, instances; media, energy LUT, -, -
+ word_first: vec4<u32>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, -
};
struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, t: vec4<f32>, x: vec4<f32> };
@@ -135,13 +136,15 @@ struct Pixel { color: vec4<f32>, albedo: vec4<f32>, normal: vec4<f32>, emit: vec
@group(0) @binding(7) var textures: texture_2d_array<f32>;
@group(0) @binding(8) var samp: sampler;
@group(0) @binding(9) var env_tex: texture_2d<f32>;
-// [0, H): marginal row CDF, then H rows of W conditional CDF entries; then the procedural data from P.procs.x (`gdata`).
-@group(0) @binding(10) var<storage, read> env_cdf: array<f32>;
+// The scene's flat arrays, sections of one buffer of 32-bit words (heap.rs `Stream`), each from the word
+// `P.word_first` names: the environment's CDF (floats: [0, H) the rows' marginal CDF, then H rows of W conditional
+// entries; `env_cdf_at`), the procedural data (`pword`, `gdata`), the vertex colours (`vcolor_word`).
+@group(0) @binding(5) var<storage, read> words: array<u32>;
+// (The CDF is the buffer's first section: from word 0, no offset to read.)
+fn env_cdf_at(i: u32) -> f32 { return bitcast<f32>(words[i]); }
@group(0) @binding(11) var<storage, read_write> accum: array<Pixel>;
-// GGX energy LUT (E.x, E.y) for 32 roughness x 32 NoV, packed 2 per vec4
-@group(0) @binding(12) var<uniform> energy_lut: array<vec4<f32>, 512>;
// The dynamic triangles' vertices (kernel layout, from triangle P.group_first[1].x on) as they were the previous frame.
-@group(0) @binding(16) var<storage, read> prev_verts: array<vec4<f32>>;
+@group(0) @binding(6) var<storage, read> prev_verts: array<vec4<f32>>;
// Model instances (scene::GpuInstance): world matrix rows, normal matrix rows, (first triangle, object, LOD offset bits, -).
struct Instance { m0: vec4<f32>, m1: vec4<f32>, m2: vec4<f32>, n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, info: vec4<u32>, p0: vec4<f32>, p1: vec4<f32>, p2: vec4<f32> };
// Bounded participating media (`VolumeMesh`, gpu.rs MediumGpu; F_MEDIA), P.time.w of them: world -> local affine rows,
@@ -149,47 +152,76 @@ struct Instance { m0: vec4<f32>, m1: vec4<f32>, m2: vec4<f32>, n0: vec4<f32>, n1
// simulated grid), (majorant 1/m, HG anisotropy, -, -), customData, parameters.
struct Medium { w0: vec4<f32>, w1: vec4<f32>, w2: vec4<f32>, a: vec4<u32>, b: vec4<f32>, c: vec4<f32>, p: array<vec4<f32>, 8> };
-// The scene's tables, read through `material_at`, `light_at`, `emitter_at`, `tex_info_at`, `object_at`, `instance_at`
-// and `medium_at` in every layout:
-// - materials (scene::GpuMaterial), lights (scene::GpuLight);
+// The scene's tables: sections of one buffer of vec4s (heap.rs `Table`), each from the vec4 `P.table_first` names:
+// - materials (scene::GpuMaterial), lights (scene::GpuLight), and per LIGHT_GROUP local lights a sphere (centre,
+// radius) holding all their light (lib.rs `light_groups`);
// - emitters: (triangle index bits, cumulative weight (normalized), weight, area) for i < counts.y, then the guide
-// table: EMITTER_GUIDE + 1 entry indices (bits), four per vec4 (lib.rs emitter_cdf), then the light tree;
+// table: EMITTER_GUIDE + 1 entry indices (bits), four per vec4 (lib.rs emitter_cdf); the light tree's nodes;
// - tex_info, per texture: (u0, v0, du, dv) of its rect in the page, (layer, wrap, width, height). See texpack.rs;
// - objects, per object (scene node): pivot (world position), world bounds size (UE ObjectPositionWS /
// ObjectBounds), then what `OBJECT_STRIDE` says;
-// - instances (Instance), media (Medium).
+// - instances (Instance), media (Medium);
+// - the GGX energy LUT: (E.x, E.y) for 32 roughness x 32 NoV, two per vec4.
+// The buffer whole is `tables` in every layout (unsigned words: integers are read as they are, floats by a bit
+// cast): the light groups, the light tree and the energy LUT are read from it, and what a scene has more of is
+// another section of it, not another binding.
+@group(0) @binding(4) var<storage, read> tables: array<vec4<u32>>;
+fn table_f(i: u32) -> vec4<f32> { return bitcast<vec4<f32>>(tables[i]); }
+fn table_i(i: u32) -> vec4<i32> { return bitcast<vec4<i32>>(tables[i]); }
+// (The light tree is the buffer's first section: from vec4 0, no offset to read.)
+fn lt_node(i: u32) -> vec4<f32> { return table_f(i); }
+fn light_group_at(i: u32) -> vec4<f32> { return table_f(P.table_first[0].w + i); }
+fn energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].y + i); }
+// The seven tables read at every hit or light, through `material_at`, `light_at`, `emitter_at`, `tex_info_at`,
+// `object_at`, `instance_at` and `medium_at` in every layout.
@if(merged) {
- // The merged layout (merged.rs): the seven as the arrays of one struct in one buffer, their lengths the renderer's
- // (`merged::Caps`: each a power of two, so a scene that grows compiles a kernel again only when a table doubles).
- struct MergedTables {
- materials: array<Material, MT_MATERIALS>,
- lights: array<Light, MT_LIGHTS>,
- emitters: array<vec4<f32>, MT_EMITTERS>,
- tex_info: array<vec4<f32>, MT_TEX_INFO>,
- objects: array<vec4<f32>, MT_OBJECTS>,
- instances: array<Instance, MT_INSTANCES>,
- media: array<Medium, MT_MEDIA>,
- };
- @group(0) @binding(4) var<storage, read> MT: MergedTables;
- fn material_at(i: u32) -> Material { return MT.materials[i]; }
- fn light_at(i: u32) -> Light { return MT.lights[i]; }
- fn emitter_at(i: u32) -> vec4<f32> { return MT.emitters[i]; }
- fn tex_info_at(i: u32) -> vec4<f32> { return MT.tex_info[i]; }
- fn object_at(i: u32) -> vec4<f32> { return MT.objects[i]; }
- fn instance_at(i: u32) -> Instance { return MT.instances[i]; }
- fn medium_at(i: u32) -> Medium { return MT.media[i]; }
+ // The merged layout (merged.rs: a browser's eight storage buffers): from the buffer whole, a record made of its
+ // vec4s (their counts: the tests hold them to the renderer's records). Slower than the views below where it was
+ // measured (docs/RUNTIME.md "The scene's tables"): an offset from the parameters at every read, the records'
+ // assembly.
+ const MATERIAL_VEC4: u32 = 18u;
+ const LIGHT_VEC4: u32 = 5u;
+ const INSTANCE_VEC4: u32 = 10u;
+ const MEDIUM_VEC4: u32 = 14u;
+ fn material_at(i: u32) -> Material {
+ let b = P.table_first[0].y + i * MATERIAL_VEC4;
+ let t0 = table_i(b + 16u);
+ let t1 = table_i(b + 17u);
+ return Material(table_f(b), table_f(b + 1u), table_f(b + 2u), table_i(b + 3u), table_i(b + 4u), table_f(b + 5u), table_f(b + 6u), table_f(b + 7u),
+ array<vec4<f32>, 8>(table_f(b + 8u), table_f(b + 9u), table_f(b + 10u), table_f(b + 11u), table_f(b + 12u), table_f(b + 13u), table_f(b + 14u), table_f(b + 15u)),
+ array<i32, 8>(t0.x, t0.y, t0.z, t0.w, t1.x, t1.y, t1.z, t1.w));
+ }
+ fn light_at(i: u32) -> Light {
+ let b = P.table_first[0].z + i * LIGHT_VEC4;
+ return Light(table_f(b), table_f(b + 1u), table_f(b + 2u), table_f(b + 3u), table_f(b + 4u));
+ }
+ fn emitter_at(i: u32) -> vec4<f32> { return table_f(P.table_first[1].x + i); }
+ fn tex_info_at(i: u32) -> vec4<f32> { return table_f(P.table_first[1].y + i); }
+ fn object_at(i: u32) -> vec4<f32> { return table_f(P.table_first[1].z + i); }
+ fn instance_at(i: u32) -> Instance {
+ let b = P.table_first[1].w + i * INSTANCE_VEC4;
+ return Instance(table_f(b), table_f(b + 1u), table_f(b + 2u), table_f(b + 3u), table_f(b + 4u), table_f(b + 5u), tables[b + 6u], table_f(b + 7u), table_f(b + 8u), table_f(b + 9u));
+ }
+ fn medium_at(i: u32) -> Medium {
+ let b = P.table_first[2].x + i * MEDIUM_VEC4;
+ return Medium(table_f(b), table_f(b + 1u), table_f(b + 2u), tables[b + 3u], table_f(b + 4u), table_f(b + 5u),
+ array<vec4<f32>, 8>(table_f(b + 6u), table_f(b + 7u), table_f(b + 8u), table_f(b + 9u), table_f(b + 10u), table_f(b + 11u), table_f(b + 12u), table_f(b + 13u)));
+ }
} @else {
- @group(0) @binding(4) var<storage, read> materials: array<Material>;
- @group(0) @binding(5) var<storage, read> lights: array<Light>;
- @group(0) @binding(6) var<storage, read> emitters: array<vec4<f32>>;
+ // Where a stage has bindings to spare, each of the seven's section is bound again as an array of its own type
+ // (gpu.rs `Gpu::scene_bind_group`: the same buffer, from the section's first byte): a read is one typed load.
+ @group(0) @binding(12) var<storage, read> materials: array<Material>;
+ @group(0) @binding(13) var<storage, read> lights: array<Light>;
+ @group(0) @binding(14) var<storage, read> emitters: array<vec4<f32>>;
fn material_at(i: u32) -> Material { return materials[i]; }
fn light_at(i: u32) -> Light { return lights[i]; }
fn emitter_at(i: u32) -> vec4<f32> { return emitters[i]; }
@if(uniform_tables) {
- // The uniform tables (merged.rs `UNIFORM_TABLES`): sized uniform arrays, every index held to the array (a
- // scene with more entries than one holds reads the last for the rest; nothing outside the buffer is read).
- @group(0) @binding(14) var<uniform> tex_info: array<vec4<f32>, UT_TEX_INFO>;
- @group(0) @binding(15) var<uniform> objects: array<vec4<f32>, UT_OBJECTS>;
+ // The uniform tables (merged.rs `UNIFORM_TABLES`): these four from sized uniform arrays, copies of their
+ // sections, every index held to the array (a scene with more entries than one holds reads the last for the
+ // rest; nothing outside the buffer is read).
+ @group(0) @binding(15) var<uniform> tex_info: array<vec4<f32>, UT_TEX_INFO>;
+ @group(0) @binding(16) var<uniform> objects: array<vec4<f32>, UT_OBJECTS>;
@group(0) @binding(17) var<uniform> instances: array<Instance, UT_INSTANCES>;
@group(0) @binding(18) var<uniform> media: array<Medium, UT_MEDIA>;
fn tex_info_at(i: u32) -> vec4<f32> { return tex_info[min(i, UT_TEX_INFO - 1u)]; }
@@ -197,8 +229,8 @@ struct Medium { w0: vec4<f32>, w1: vec4<f32>, w2: vec4<f32>, a: vec4<u32>, b: ve
fn instance_at(i: u32) -> Instance { return instances[min(i, UT_INSTANCES - 1u)]; }
fn medium_at(i: u32) -> Medium { return media[min(i, UT_MEDIA - 1u)]; }
} @else {
- @group(0) @binding(14) var<storage, read> tex_info: array<vec4<f32>>;
- @group(0) @binding(15) var<storage, read> objects: array<vec4<f32>>;
+ @group(0) @binding(15) var<storage, read> tex_info: array<vec4<f32>>;
+ @group(0) @binding(16) var<storage, read> objects: array<vec4<f32>>;
@group(0) @binding(17) var<storage, read> instances: array<Instance>;
@group(0) @binding(18) var<storage, read> media: array<Medium>;
fn tex_info_at(i: u32) -> vec4<f32> { return tex_info[i]; }
@@ -208,10 +240,9 @@ struct Medium { w0: vec4<f32>, w1: vec4<f32>, w2: vec4<f32>, a: vec4<u32>, b: ve
}
}
// Density grids (gpu.rs F_GRID, `GridsGpu`): field A of every grid, stacked along z; one cell in scenes without.
-@group(0) @binding(19) var grid_tex: texture_3d<f32>;
-// Vertex colours (three.js `vertexColors`; gpu.rs F_VCOLOR): three sRGB 8-bit colours per triangle, after the previous
-// vertices in `prev_verts` from vec4 P.procs.w.
-fn vcolor_word(k: u32) -> u32 { return bitcast<u32>(prev_verts[P.procs.w + k / 4u][k % 4u]); }
+@group(0) @binding(10) var grid_tex: texture_3d<f32>;
+// Vertex colours (three.js `vertexColors`; gpu.rs F_VCOLOR): three sRGB 8-bit colours per triangle.
+fn vcolor_word(k: u32) -> u32 { return words[P.word_first.z + k]; }
fn vcolor(t: u32, u: f32, v: f32) -> vec3<f32> {
let c0 = srgb_to_linear(unpack4x8unorm(vcolor_word(t * 3u)).rgb);
let c1 = srgb_to_linear(unpack4x8unorm(vcolor_word(t * 3u + 1u)).rgb);
@@ -311,7 +342,6 @@ const LT_FAR: f32 = 120.0;
fn lt_on() -> bool { return P.ltree.w > 0.5; }
-fn lt_node(i: u32) -> vec4<f32> { return emitter_at(bitcast<u32>(P.ltree.x) + i); }
// Importance of a tree node seen from x on a surface with normal n (n = 0: no hemisphere, a fog point): power x the
// best cosine any point of its sphere can have at x / max(distance², radius²).
@@ -456,12 +486,12 @@ struct GIn { o: vec3<f32>, d: vec3<f32>, tmin: f32, tmax: f32, prim: u32, lo: ve
struct GOut { t: f32, normal: vec3<f32>, material: u32, attr: vec2<f32> };
// Procedural data (scene::proc_data): per object its header (`proc_vec`), materials, boxes (min xyz, max xyz) and the
-// game's own data, 32-bit words after the environment's CDF in env_cdf (the kernel has no binding to spare).
+// game's own data, 32-bit words.
// `pword`: the renderer's own reads (headers, boxes, materials). `gdata`: the geometry function's, of its object's data
// only, word i.data .. i.data + i.count - 1; anything else reads 0. The kernel is compiled without bounds checks (its
// indices come from the scene build) and the function is game code: it must not reach past its data.
-fn pword(k: u32) -> u32 { return bitcast<u32>(env_cdf[P.procs.x + k]); }
-fn pwordf(k: u32) -> f32 { return env_cdf[P.procs.x + k]; }
+fn pword(k: u32) -> u32 { return words[P.word_first.y + k]; }
+fn pwordf(k: u32) -> f32 { return bitcast<f32>(pword(k)); }
var<private> gdata_first: u32;
var<private> gdata_count: u32;
fn gdata(k: u32) -> u32 {
@@ -1292,7 +1322,7 @@ fn energy_lookup(roughness: f32, nov: f32) -> vec2<f32> {
fn lut(x: u32, y: u32) -> vec2<f32> {
let i = y * 32u + x;
- let v = energy_lut[i / 2u];
+ let v = energy_at(i / 2u);
return select(v.xy, v.zw, (i & 1u) == 1u);
}
@@ -1485,11 +1515,11 @@ fn env_pdf(d: vec3<f32>) -> f32 {
let uv = env_uv(d);
let x = min(u32(uv.x * f32(w)), w - 1u);
let y = min(u32(uv.y * f32(h)), h - 1u);
- @if(!strict) let row_p = env_cdf[y] - select(0.0, env_cdf[y - 1u], y > 0u);
- @if(strict) let row_p = env_cdf[y] - select(0.0, env_cdf[max(y, 1u) - 1u], y > 0u);
+ @if(!strict) let row_p = env_cdf_at(y) - select(0.0, env_cdf_at(y - 1u), y > 0u);
+ @if(strict) let row_p = env_cdf_at(y) - select(0.0, env_cdf_at(max(y, 1u) - 1u), y > 0u);
let base = h + y * w;
- @if(!strict) let col_p = env_cdf[base + x] - select(0.0, env_cdf[base + x - 1u], x > 0u);
- @if(strict) let col_p = env_cdf[base + x] - select(0.0, env_cdf[base + max(x, 1u) - 1u], x > 0u);
+ @if(!strict) let col_p = env_cdf_at(base + x) - select(0.0, env_cdf_at(base + x - 1u), x > 0u);
+ @if(strict) let col_p = env_cdf_at(base + x) - select(0.0, env_cdf_at(base + max(x, 1u) - 1u), x > 0u);
let sin_t = sin((f32(y) + 0.5) / f32(h) * PI);
return row_p * col_p * f32(w) * f32(h) / (2.0 * PI * PI * max(sin_t, 1e-4));
}
@@ -1499,7 +1529,7 @@ fn lower_bound(start: u32, count: u32, x: f32) -> u32 {
var hi = count;
while (lo < hi) {
let mid = (lo + hi) / 2u;
- if (env_cdf[start + mid] < x) { lo = mid + 1u; } else { hi = mid; }
+ if (env_cdf_at(start + mid) < x) { lo = mid + 1u; } else { hi = mid; }
}
return min(lo, count - 1u);
}
@@ -1748,12 +1778,12 @@ fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>,
let ns = P.counts2.w;
let n_sh = P.counts.x - ns;
let end = select(ns, P.counts.x, n_sh <= RIS_EXACT || nl <= RIS_EXACT);
- // In groups of LIGHT_GROUP (spatially sorted; after the lights, a sphere holding all their light per group:
- // lib.rs lights_with_groups): a group x is outside of is skipped whole.
+ // In groups of LIGHT_GROUP (spatially sorted; a sphere holding all their light per group: lib.rs
+ // light_groups): a group x is outside of is skipped whole.
var i = nd;
loop {
if (i >= end) { break; }
- let gs = light_at(P.counts.x + (i - nd) / LIGHT_GROUP).pos;
+ let gs = light_group_at((i - nd) / LIGHT_GROUP);
let gend = min(i + LIGHT_GROUP, end);
if (distance(x, gs.xyz) > gs.w) {
i = gend;
diff --git a/renderer/shaders/trace_hw.wgsl b/renderer/shaders/trace_hw.wgsl
index 1569452..3ad12d1 100644
--- a/renderer/shaders/trace_hw.wgsl
+++ b/renderer/shaders/trace_hw.wgsl
@@ -2,7 +2,7 @@
// mask 2; opaque groups never report candidates, alpha-cutout groups are confirmed by `alpha_pass`.
// instance_custom_data holds the instance's first global triangle index, or in scenes where a group starts beyond
// 2^24 triangles (F_HUGE: custom data has 24 bits) its traversal group, whose first triangle is in P.group_first.
-@if(hwrt) @group(0) @binding(13) var acc: acceleration_structure;
+@if(hwrt) @group(0) @binding(19) var acc: acceleration_structure;
@if(hwrt) fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {
// Ray tracing off (pathtrace.wgsl `rays_off`): past the camera ray, every ray misses.
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index d205815..a404a25 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -1,5 +1,6 @@
//! Headless wgpu backend: uploads the flattened scene once, accumulates path-traced samples, reads back HDR.
+use crate::heap::{Heap, Section, Stream, Table};
use crate::scene::Scene;
use crate::GROUPS;
use anyhow::{anyhow, Result};
@@ -48,7 +49,7 @@ pub struct Gpu {
/// Hardware ray queries (Metal / Vulkan RT). Software BVH traversal otherwise.
pub hwrt: bool,
/// Last uploaded texture pages, reused while the scene's texture set is unchanged (live edits re-upload often).
- pages: std::sync::Mutex<Option<(u64, wgpu::TextureView, wgpu::Buffer)>>,
+ pages: std::sync::Mutex<Option<(u64, wgpu::TextureView, std::sync::Arc<Vec<[f32; 4]>>)>>,
/// The translucency pass (hardware RT): group 2's layout (translucent.wgsl), the kernel layout with it, and its
/// pipelines (`translucent`, `volume_train`) by the kernel's variant key.
tl_layout: Option<wgpu::BindGroupLayout>,
@@ -105,11 +106,10 @@ pub struct Params {
/// Live emitter cull's view cone (lib.rs `EmitterCull`): the forward direction it was built for (xyz), the cosine
/// of its half-angle (w).
pub lod_view: [f32; 4],
- /// Light tree (`ltree`): its first node in `emitters` (bits), its entry count (bits: the first moving emitter's
- /// entry), the probability of picking a moving emitter (their share of power), candidates at camera hits (0 = off).
+ /// Light tree (`ltree`): -, its entry count (bits: the first moving emitter's entry), the probability of picking
+ /// a moving emitter (their share of power), candidates at camera hits (0 = off).
pub ltree: [f32; 4],
- /// Procedural geometry (F_PROC; scene::proc_data): its first word in the `env_cdf` binding (after the environment's
- /// CDF), object count, first record in `instances`, -.
+ /// Procedural geometry (F_PROC; scene::proc_data): -, object count, first record in `instances`, -.
pub procs: [u32; 4],
/// The sky's aerial perspective (F_AERIAL; `scene::aerial_params`): density multiple, Rayleigh scale, Mie scale, -.
pub aerial: [f32; 4],
@@ -124,6 +124,11 @@ pub struct Params {
/// The camera the lists were built under (the last frame's): position (w = tan(fov / 2)), forward (w = aspect),
/// right, up. A camera hit reads the list of the tile it was seen in then.
pub lt_cam: [[f32; 4]; 4],
+ /// Each table's first vec4 in the tables' heap (`heap::Table`'s order; `Uploaded::place`).
+ pub table_first: [[u32; 4]; 3],
+ /// Each stream's first word in the words' heap (`heap::Stream`'s order): the environment's CDF, the procedural
+ /// data, the vertex colours, -.
+ pub word_first: [u32; 4],
}
/// Room the live view's in-place geometry edits grow into (live/edits.rs `edit_geometry`), past the scene's own data:
@@ -180,28 +185,17 @@ pub struct PendingProc {
size: wgpu::BlasAABBGeometrySizeDescriptor,
}
-/// The kernel's bindings of the seven tables the merged layout holds in one (merged.rs `TABLES`, in its order).
-const MERGED_TABLE_BINDINGS: [u32; 7] = [4, 5, 6, 14, 15, 17, 18];
-
-impl Uploaded {
- /// The seven tables, in merged.rs `TABLES`' order.
- fn table_buffers(&self) -> [&wgpu::Buffer; 7] {
- [&self.materials, &self.lights, &self.emitters, &self.bg_parts.texinfo, &self.objects, &self.instances, &self.media]
- }
-}
-
-/// The uniform tables' buffers among the seven (`table_buffers`), in merged.rs `UNIFORM_TABLES`' order.
-fn uniform_sources(tables: [&wgpu::Buffer; 7]) -> [&wgpu::Buffer; 4] {
- crate::merged::UNIFORM_TABLES.map(|k| tables[k])
-}
+/// The acceleration structure's binding in the scene's group (trace_hw.wgsl `acc`): the last, after every buffer.
+const ACC_BINDING: u32 = 19;
/// A note for each uniform table that a scene has more entries of (`used`, merged.rs `UNIFORM_TABLES`' order) than
/// its array holds: the kernel reads the last entry for the rest.
pub(crate) fn uniform_overflow(used: [u64; 4]) -> Vec<String> {
- use crate::merged::{TABLES, UNIFORM_LEN, UNIFORM_TABLES};
- (0..4)
- .filter(|&k| used[k] > UNIFORM_LEN[k] as u64)
- .map(|k| format!("uniform tables: the scene has {} entries of `{}`, a uniform buffer holds {} (the rest read as the last one; THREERT_UNIFORM_TABLES=0 binds storage buffers)", used[k], TABLES[UNIFORM_TABLES[k]].name, UNIFORM_LEN[k]))
+ crate::merged::UNIFORM_TABLES
+ .iter()
+ .zip(used)
+ .filter(|(t, used)| *used > t.len as u64)
+ .map(|(t, used)| format!("uniform tables: the scene has {used} entries of `{}`, a uniform buffer holds {} (the rest read as the last one; THREERT_UNIFORM_TABLES=0 reads the tables' heap)", t.name, t.len))
.collect()
}
@@ -210,18 +204,10 @@ fn uniform_copy_bytes(table: u64, copy: u64) -> u64 {
table.min(copy) & !3
}
-/// A scene bind group's entries with the uniform tables' copies in their tables' places.
-fn bind_uniform_tables<'a>(entries: &mut Vec<wgpu::BindGroupEntry<'a>>, copies: &'a [wgpu::Buffer; 4]) {
- let bindings = crate::merged::UNIFORM_TABLES.map(|k| MERGED_TABLE_BINDINGS[k]);
- entries.retain(|e| !bindings.contains(&e.binding));
- entries.extend(copies.iter().zip(bindings).map(|(b, binding)| wgpu::BindGroupEntry { binding, resource: b.as_entire_binding() }));
-}
/// What the scene bind group holds besides `Uploaded`'s buffers (`Gpu::rebind_scene` makes it again).
pub struct BindParts {
pub nodes: wgpu::Buffer,
- pub energy: wgpu::Buffer,
- pub texinfo: wgpu::Buffer,
pub tex_view: wgpu::TextureView,
pub env_view: wgpu::TextureView,
pub sampler: wgpu::Sampler,
@@ -229,14 +215,50 @@ pub struct BindParts {
pub grid_view: wgpu::TextureView,
}
+/// What the scene's bind group is made of (`Gpu::scene_bind_group`).
+struct SceneBuffers<'a> {
+ params: &'a wgpu::Buffer,
+ verts: &'a wgpu::Buffer,
+ attrs: &'a wgpu::Buffer,
+ heap: &'a Heap<Table>,
+ words: &'a Heap<Stream>,
+ prev_verts: &'a wgpu::Buffer,
+ accum: &'a wgpu::Buffer,
+ parts: &'a BindParts,
+ accel: Option<&'a Accel>,
+ uniform: Option<&'a [wgpu::Buffer; 4]>,
+}
+
+/// The scene's buffers a particle pass writes (particles.wgsl, gpu_particles.wgsl: bindings 2 to 6; the objects'
+/// section of the tables as a buffer of its own). The pass's bind group holds them: one replaced, the group is made
+/// again (`Gpu::rebind_scene`).
+struct ParticleTargets<'a> {
+ verts: &'a wgpu::Buffer,
+ prev_verts: &'a wgpu::Buffer,
+ blas_verts: &'a wgpu::Buffer,
+ heap: &'a Heap<Table>,
+ attrs: &'a wgpu::Buffer,
+}
+
+fn buffer_entry(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {
+ wgpu::BindGroupEntry { binding, resource: b.as_entire_binding() }
+}
+
+/// A particle pass's bind group: its `own` buffers at their bindings, and the scene's it writes.
+fn particle_bind_group(d: &wgpu::Device, pipeline: &wgpu::ComputePipeline, label: &str, own: &[(u32, &wgpu::Buffer)], t: &ParticleTargets) -> wgpu::BindGroup {
+ let mut entries: Vec<wgpu::BindGroupEntry> = own.iter().map(|(binding, b)| buffer_entry(*binding, b)).collect();
+ entries.extend([buffer_entry(2, t.verts), buffer_entry(3, t.prev_verts), buffer_entry(4, t.blas_verts), wgpu::BindGroupEntry { binding: 5, resource: t.heap.binding(Table::Objects) }, buffer_entry(6, t.attrs)]);
+ d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some(label), layout: &pipeline.get_bind_group_layout(0), entries: &entries })
+}
+
pub struct Uploaded {
pub bg: wgpu::BindGroup,
pub bg_parts: BindParts,
- /// The merged layout (merged.rs): the buffer of the kernel's `MergedTables`, the seven tables below as its arrays
- /// (`Gpu::sync_tables` copies them there each frame; their lengths: `kernel.caps`).
- pub tables: Option<wgpu::Buffer>,
- /// The uniform tables (`Gpu::uniform_tables`): the uniform buffers the kernel reads `bg_parts.texinfo`, `objects`,
- /// `instances` and `media` from (merged.rs `UNIFORM_TABLES`' order; `Gpu::sync_tables` copies them there each frame).
+ /// The scene's tables (heap.rs): materials, lights, emitters, objects, instances, media and the rest, each a
+ /// section that edits write in place (`Heap::write`) and grow (`Heap::grow`, then `Gpu::rebind_scene`).
+ pub heap: Heap<Table>,
+ /// The uniform tables (`Gpu::uniform_tables`): the uniform buffers the kernel reads four tables from (merged.rs
+ /// `UNIFORM_TABLES`' order; `Gpu::sync_tables` copies their sections there each frame).
pub uniform: Option<[wgpu::Buffer; 4]>,
pub accum: wgpu::Buffer,
pub params: wgpu::Buffer,
@@ -244,11 +266,6 @@ pub struct Uploaded {
pub height: u32,
/// Kernel specialisation for this scene (`Gpu::pipeline`).
pub kernel: Kernel,
- /// Tables that parameter edits rewrite in place (`patch`).
- pub materials: wgpu::Buffer,
- pub lights: wgpu::Buffer,
- pub objects: wgpu::Buffer,
- pub emitters: wgpu::Buffer,
/// Triangle vertices / shading attributes (posed models rewrite their ranges).
pub verts: wgpu::Buffer,
pub attrs: wgpu::Buffer,
@@ -265,19 +282,17 @@ pub struct Uploaded {
pub gpu_particles: Option<GpuParticlesGpu>,
/// The density grids (the atlas the kernel reads, the grid programs' pass), when the scene has any.
pub grids: Option<GridsGpu>,
- /// The media table (`MediumGpu`) and each medium's node.
- pub media: wgpu::Buffer,
- /// Vertex colours (F_VCOLOR): their byte offset in `prev_verts` (three words per triangle, room included).
- pub vcolor_base: Option<u64>,
+ /// Each medium's node (the media table's order).
+ /// The scene has vertex colours (F_VCOLOR): three words per triangle in `words`, the edit room's included.
+ pub vcolors: bool,
pub media_nodes: Vec<u32>,
/// Per medium: its node is hidden (`set_medium_hidden`). The live view runs no media pass while all are.
pub media_hidden: std::cell::RefCell<Vec<bool>>,
- /// The model instances' kernel records (`GpuInstance`): movable ones are rewritten when they move.
- pub instances: wgpu::Buffer,
- /// Room for in-place geometry edits (`EditRoom`), and the binding that holds the environment CDF and the
- /// procedural region, with the CDF's length and the region's words in use (the room follows them).
+ /// Room for in-place geometry edits (`EditRoom`), and the scene's 32-bit arrays (heap.rs `Stream`: the
+ /// environment's CDF, the procedural region, the vertex colours), with the CDF's length and the region's words
+ /// in use (the room follows them).
pub room: EditRoom,
- pub cdf: wgpu::Buffer,
+ pub words: Heap<Stream>,
pub cdf_words: usize,
pub region_words: usize,
/// The environment map (`write_env` replaces it in place when a dynamic sky's sun moves).
@@ -296,6 +311,9 @@ pub struct ParticleGpu {
params: wgpu::Buffer,
/// The system table (`ParticleSystemGpu`) and each system's node (pivot updates when it moves).
table: wgpu::Buffer,
+ /// The pass's own buffers besides: the last frame's vertices, the translucent BLAS input's stand-in.
+ last: wgpu::Buffer,
+ no_trans: wgpu::Buffer,
nodes: Vec<u32>,
systems: u32,
max_count: u32,
@@ -342,6 +360,23 @@ pub struct Translucent {
pub low: wgpu::Buffer,
}
+impl Uploaded {
+ /// The light table as it is now, and its groups' spheres (lib.rs `light_groups`).
+ pub fn put_lights(&self, q: &wgpu::Queue, lights: &[crate::scene::GpuLight]) {
+ self.heap.write(q, Table::Lights, 0, bytemuck::cast_slice(lights));
+ self.heap.write(q, Table::LightGroups, 0, bytemuck::cast_slice(&crate::light_groups(lights)));
+ }
+
+ /// Where the kernel finds each table and stream (`Params::table_first`, `word_first`): written with the
+ /// parameters, every time (a section that grew moves those after it).
+ pub fn place(&self, p: &mut Params) {
+ let first = self.heap.firsts();
+ p.table_first = std::array::from_fn(|k| std::array::from_fn(|j| first.get(k * 4 + j).copied().unwrap_or(0)));
+ let first = self.words.firsts();
+ p.word_first = std::array::from_fn(|k| first.get(k).copied().unwrap_or(0));
+ }
+}
+
impl Translucent {
/// Rebuilds the BLAS from the particle pass's vertices, and the TLAS.
fn build(&self, e: &mut wgpu::CommandEncoder) {
@@ -499,6 +534,8 @@ pub struct GpuParticlesGpu {
bg: wgpu::BindGroup,
params: wgpu::Buffer,
table: wgpu::Buffer,
+ last: wgpu::Buffer,
+ state: wgpu::Buffer,
spawns: wgpu::Buffer,
pub grid: wgpu::Buffer,
systems: std::cell::RefCell<Vec<GpuParticleSystemGpu>>,
@@ -762,17 +799,15 @@ impl KernelVariant {
}
/// The numbers the variant is compiled for, WESL constants (`import constants::`): the merged layout's array
- /// lengths (`MT_<table>`, `ML_<buffer>`), the uniform tables' (`UT_<table>`), the loop guard's count's words and
- /// its limit.
+ /// lengths (`ML_<buffer>`), the uniform tables' (`UT_<table>`), the loop guard's count's words and its limit.
pub fn constants(&self) -> Vec<(String, u32)> {
- use crate::merged::{GUARD_WORDS, KERNEL_LIVE, TABLES, UNIFORM_LEN, UNIFORM_TABLES};
+ use crate::merged::{GUARD_WORDS, KERNEL_LIVE, UNIFORM_TABLES};
let mut out = vec![];
if let Some(c) = &self.merged {
- out.extend(TABLES.iter().zip(c.tables).map(|(m, n)| (format!("MT_{}", m.name.to_uppercase()), n)));
out.extend(KERNEL_LIVE.iter().zip(c.live).map(|(m, n)| (format!("ML_{}", m.name.to_uppercase()), n)));
}
if self.uniform_tables {
- out.extend(UNIFORM_TABLES.iter().zip(UNIFORM_LEN).map(|(&k, n)| (format!("UT_{}", TABLES[k].name.to_uppercase()), n)));
+ out.extend(UNIFORM_TABLES.iter().map(|t| (format!("UT_{}", t.name.to_uppercase()), t.len)));
}
if self.merged.is_some() || self.guard.is_some() {
out.push(("GUARD_WORDS".into(), GUARD_WORDS));
@@ -1213,8 +1248,8 @@ pub struct Kernel {
/// The scene's geometry functions and their dispatch (pathtrace.wgsl `geometry_function`), spliced like `functions`.
pub geometry_functions: String,
pub hash: u64,
- /// The merged layout (merged.rs): the lengths of the merged structs' arrays this kernel's source is written for
- /// (the tables': `Gpu::upload`; group 1's: an offline render's `no_vis`, a live view's `KernelBufs`).
+ /// The merged layout (merged.rs): the lengths of the merged struct's arrays this kernel's source is written for
+ /// (an offline render's `no_vis`, a live view's `KernelBufs`).
pub caps: Option<crate::merged::Caps>,
}
@@ -1534,8 +1569,8 @@ impl Gpu {
// layout with more does not validate).
let merged = cfg!(target_arch = "wasm32") || std::env::var("THREERT_MERGED").is_ok_and(|v| v == "1");
limits.max_storage_buffers_per_shader_stage = if merged { crate::merged::STORAGE_BUFFERS } else { al.max_storage_buffers_per_shader_stage.min(31) };
- // Storage + uniform buffers together (the kernel binds 19 storage buffers, a live pass at most 8, each beside its
- // uniforms; Metal allows 31).
+ // Storage + uniform buffers and acceleration structures together (the translucency pass binds 24 storage
+ // buffers, 25 with the loop guard's, 2 uniform ones and 2 structures; Metal allows 29).
limits.max_buffers_and_acceleration_structures_per_shader_stage = al.max_buffers_and_acceleration_structures_per_shader_stage.min(31);
limits.max_acceleration_structures_per_shader_stage = al.max_acceleration_structures_per_shader_stage;
limits.max_blas_geometry_count = al.max_blas_geometry_count;
@@ -1579,51 +1614,39 @@ impl Gpu {
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
count: None,
};
- // (The uniform tables: these four bindings hold uniform buffers; merged.rs `UNIFORM_TABLES`.)
- let table = |binding: u32| if uniform_tables { uniform(binding) } else { storage(binding, true) };
+ let texture = |binding: u32, view_dimension: wgpu::TextureViewDimension| wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension, multisampled: false },
+ count: None,
+ };
+ // Group 0, the scene (pathtrace.wgsl's declarations): the parameters; triangles, their attributes, the
+ // software tree; the tables' heap; the words' heap; the dynamic triangles' previous vertices; the
+ // texture pages and their sampler, the environment, the density grids' atlas (a 1-cell texture in scenes
+ // without grids, whose kernel does not read it); the accumulation buffer; then what only some layouts have.
let mut entries = vec![
- uniform(0),
- storage(1, true),
- storage(2, true),
- storage(3, true),
- storage(4, true),
- storage(5, true),
- storage(6, true),
- wgpu::BindGroupLayoutEntry {
- binding: 7,
- visibility: wgpu::ShaderStages::COMPUTE,
- ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2Array, multisampled: false },
- count: None,
- },
- wgpu::BindGroupLayoutEntry { binding: 8, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None },
- wgpu::BindGroupLayoutEntry {
- binding: 9,
- visibility: wgpu::ShaderStages::COMPUTE,
- ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false },
- count: None,
- },
- storage(10, true),
- storage(11, false),
- uniform(12),
- table(14),
- table(15),
- storage(16, true),
- table(17),
- table(18),
- // The density grids' atlas (F_GRID; a 1-cell texture in scenes without grids, whose kernel does not read it).
- wgpu::BindGroupLayoutEntry {
- binding: 19,
- visibility: wgpu::ShaderStages::COMPUTE,
- ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D3, multisampled: false },
- count: None,
- },
+ uniform(0),
+ storage(1, true),
+ storage(2, true),
+ storage(3, true),
+ storage(4, true),
+ storage(5, true),
+ storage(6, true),
+ texture(7, wgpu::TextureViewDimension::D2Array),
+ wgpu::BindGroupLayoutEntry { binding: 8, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None },
+ texture(9, wgpu::TextureViewDimension::D2),
+ texture(10, wgpu::TextureViewDimension::D3),
+ storage(11, false),
];
- if hwrt {
- entries.push(wgpu::BindGroupLayoutEntry { binding: 13, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::AccelerationStructure { vertex_return: false }, count: None });
+ // The tables the kernel reads at every hit or light, bound again as typed views of their sections (merged.rs
+ // `TABLE_VIEWS`; the merged layout has no binding for them), four of them uniform copies where a driver
+ // needs it (`UNIFORM_TABLES`).
+ if !merged {
+ let copied = |b: u32| uniform_tables && crate::merged::UNIFORM_TABLES.iter().any(|t| t.binding == b);
+ entries.extend(crate::merged::TABLE_VIEWS.iter().map(|&(_, b)| if copied(b) { uniform(b) } else { storage(b, true) }));
}
- // The merged layout: the seven tables are one binding, the first of theirs (merged.rs `TABLES`).
- if merged {
- entries.retain(|e| !MERGED_TABLE_BINDINGS[1..].contains(&e.binding));
+ if hwrt {
+ entries.push(wgpu::BindGroupLayoutEntry { binding: ACC_BINDING, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::AccelerationStructure { vertex_return: false }, count: None });
}
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &entries });
let mut vis_entries = vec![
@@ -1838,10 +1861,10 @@ impl Gpu {
/// The radiance cache's per-frame resolve (pathtrace.wgsl `cache_resolve`; kernel bind groups).
pub fn cache_resolve_pipeline(&self, bufs: &KernelBufs) -> wgpu::ComputePipeline {
- // (The merged layout: the kernel written for these buffers' lengths, and the least tables.)
+ // (The merged layout: the kernel written for these buffers' lengths.)
let module = match (&self.module, &bufs.merged) {
(Some(m), _) => m.clone(),
- (None, Some((_, live))) => self.kernel_module(&Kernel::plain(crate::merged::Caps { tables: crate::merged::TABLE_MIN, live: *live })),
+ (None, Some((_, live))) => self.kernel_module(&Kernel::plain(crate::merged::Caps { live: *live })),
(None, None) => unreachable!("the merged layout's group 1 is one buffer"),
};
let p = self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
@@ -1857,7 +1880,7 @@ impl Gpu {
}
/// Texture pages for the scene's texture set (see `texpack`), cached across uploads of the same set.
- fn texture_pages(&self, scene: &Scene, timings: &mut Vec<(String, f64)>) -> (wgpu::TextureView, wgpu::Buffer) {
+ fn texture_pages(&self, scene: &Scene, timings: &mut Vec<(String, f64)>) -> (wgpu::TextureView, std::sync::Arc<Vec<[f32; 4]>>) {
let key = crate::texpack::set_key(&scene.textures);
let mut cache = self.pages.lock().unwrap();
if let Some((k, view, info)) = cache.as_ref() {
@@ -1890,8 +1913,7 @@ impl Gpu {
}
}
let view = tex.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });
- // (The merged layout copies it into the tables' buffer, the uniform tables into its uniform copy: `sync_tables`.)
- let info = d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("tex_info"), contents: bytemuck::cast_slice(&packed.info), usage: if self.merged || self.uniform_tables { wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC } else { wgpu::BufferUsages::STORAGE } });
+ let info = std::sync::Arc::new(packed.info);
timings.push(("texture_pages_ms".into(), t.elapsed().as_secs_f64() * 1000.0));
*cache = Some((key, view.clone(), info.clone()));
(view, info)
@@ -1900,10 +1922,9 @@ impl Gpu {
/// Uploads a prepared scene (geometry, materials, textures, environment, acceleration structures) and returns the
/// bind group used by both the offline and the live kernels. `accum` holds one 80-byte Pixel per output pixel.
#[allow(clippy::too_many_arguments)]
- pub fn upload(&self, scene: &Scene, w: u32, h: u32, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], timings: &mut Vec<(String, f64)>) -> Result<Uploaded> {
+ pub fn upload(&self, scene: &Scene, w: u32, h: u32, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], timings: &mut Vec<(String, f64)>) -> Result<Uploaded> {
let d = &self.device;
let t0 = Instant::now();
- // Empty tables still bind one zeroed element (the largest is a material, 368 B).
// (The vertices too: the kernel's tree over no triangle is a leaf of triangle 0, which these zeros make a
// triangle without area; bvh.rs `EMPTY`.)
let buf = |label: &str, bytes: &[u8], usage: wgpu::BufferUsages| {
@@ -1934,14 +1955,7 @@ impl Gpu {
// The dynamic tail (groups 4..8; the instanced pool follows it, its deforming meshes first: theirs too).
let dynamic_end: usize = groups.iter().sum::<usize>() + crate::scene::deforming_pool(&scene.meshes);
let prev = &tri_verts[(dynamic_first * 3).min(tri_verts.len())..(dynamic_end * 3).min(tri_verts.len())];
- // Vertex colours (F_VCOLOR) ride after the previous vertices (the kernel has no binding to spare), from vec4
- // `Params::procs.w` on, the edit room's triangles' too (the edits write theirs). Without them: as before.
- let b_prev = if scene.gpu_vcolors.is_empty() {
- buf("prev verts", bytemuck::cast_slice(prev), edit)
- } else {
- debug_assert_eq!(prev.len(), scene.vcolor_base as usize);
- buf_room("prev verts + vertex colours", &[bytemuck::cast_slice(prev), bytemuck::cast_slice(&scene.gpu_vcolors)].concat(), (room.tris * 12).next_multiple_of(16), edit)
- };
+ let b_prev = buf("prev verts", bytemuck::cast_slice(prev), edit);
// The vertex colours' bytes on the GPU (the edit room's included).
timings.push(("vcolor_mb".into(), if scene.gpu_vcolors.is_empty() { 0.0 } else { (scene.gpu_vcolors.len() * 4 + room.tris * 12) as f64 / (1 << 20) as f64 }));
let b_attrs = buf_room("attrs", bytemuck::cast_slice(&scene.attrs), room.tris * std::mem::size_of::<crate::scene::GpuTriAttr>(), edit);
@@ -1950,19 +1964,8 @@ impl Gpu {
// What the triangles hold on the GPU besides their BLASes: vertices (a, e1, e2), attributes, the software BVH's nodes
// (ROADMAP § 6 step 2's table: a meshed representation against voxel data).
timings.push(("tri_data_mb".into(), (std::mem::size_of_val(tri_verts) + std::mem::size_of_val(&scene.attrs[..]) + nodes.len()) as f64 / (1 << 20) as f64));
- let b_mats = buf("materials", bytemuck::cast_slice(&scene.materials), edit);
- let b_lights = buf("lights", bytemuck::cast_slice(&crate::lights_with_groups(&scene.lights)), edit);
- let b_emit = buf("emitters", bytemuck::cast_slice(emitters), edit);
- let (b_cdf, region_words, proc_room) = match &scene.proc_layout {
- None => (buf("env_cdf", bytemuck::cast_slice(env_cdf), st | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC), 0, 0),
- Some(l) => self.upload_procs(env_cdf, l, room.proc_words, timings)?,
- };
+ let (words, region_words, proc_room) = self.upload_words(scene, env_cdf, room.proc_words, room.tris, timings)?;
let room = EditRoom { proc_words: proc_room, ..room };
- let b_energy = buf("energy", bytemuck::cast_slice(energy), wgpu::BufferUsages::UNIFORM);
- let b_objects = buf_room("objects", bytemuck::cast_slice(&scene.objects), room.objects * scene.object_stride() * 16, edit);
- let none = [crate::scene::GpuInstance::default()];
- // COPY_DST: live pose / customData edits (`set_medium`).
- let b_media = buf("media", bytemuck::cast_slice(&scene.media), edit);
// Density grids: field A of each in the atlas (stacked along z), their data; for a grid with a program, its
// other textures (A', B, B'), its two half steps and its sources.
let grids = (!scene.grids.is_empty()).then(|| {
@@ -2017,14 +2020,29 @@ impl Gpu {
GridsGpu { atlas, pipeline, grids, step: std::cell::Cell::new(0) }
});
let grid_view = grids.as_ref().map_or_else(|| self.no_grid_view.clone(), |g| g.atlas.create_view(&Default::default()));
- // COPY_DST: movable instances' transforms (live moves).
- // The procedural objects' records follow the model instances' (moved like them); records edits add follow both.
- let b_instances = buf_room("instances", bytemuck::cast_slice(if records.is_empty() { &none[..] } else { &records[..] }), room.records * std::mem::size_of::<crate::scene::GpuInstance>(), edit);
let accum_size = (w as u64) * (h as u64) * 80;
let b_accum = d.create_buffer(&wgpu::BufferDescriptor { label: Some("accum"), size: accum_size, usage: st | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let b_params = d.create_buffer(&wgpu::BufferDescriptor { label: Some("params"), size: std::mem::size_of::<Params>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
- let (tex_view, b_texinfo) = self.texture_pages(scene, timings);
+ let (tex_view, tex_info) = self.texture_pages(scene, timings);
+ // The scene's tables, the sections of one buffer (heap.rs), written as it is made. The objects' and the
+ // records' have the edits' room after them (the procedural objects' records follow the model instances').
+ let none = [crate::scene::GpuInstance::default()];
+ let spheres = crate::light_groups(&scene.lights);
+ let parts: [(Table, &[u8], usize); Table::COUNT] = [
+ (Table::LightTree, bytemuck::cast_slice(light_tree), 0),
+ (Table::Materials, bytemuck::cast_slice(&scene.materials), 0),
+ (Table::Lights, bytemuck::cast_slice(&scene.lights), 0),
+ (Table::LightGroups, bytemuck::cast_slice(&spheres), 0),
+ (Table::Emitters, bytemuck::cast_slice(emitters), 0),
+ (Table::TexInfo, bytemuck::cast_slice(&tex_info[..]), 0),
+ (Table::Objects, bytemuck::cast_slice(&scene.objects), room.objects * scene.object_stride() * 16),
+ (Table::Instances, bytemuck::cast_slice(if records.is_empty() { &none[..] } else { &records[..] }), room.records * std::mem::size_of::<crate::scene::GpuInstance>()),
+ (Table::Media, bytemuck::cast_slice(&scene.media), 0),
+ (Table::Energy, bytemuck::cast_slice(energy), 0),
+ ];
+ assert!(parts.iter().enumerate().all(|(k, p)| p.0.index() == k), "the tables in `Table`'s order");
+ let heap = Heap::filled(d, &parts.map(|p| (p.1.len() + p.2) as u64), |put| parts.iter().for_each(|p| put(p.0, 0, p.1)));
let env_tex = d.create_texture(&wgpu::TextureDescriptor {
label: Some("env"),
@@ -2238,53 +2256,19 @@ impl Gpu {
fn e(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {
wgpu::BindGroupEntry { binding, resource: b.as_entire_binding() }
}
- let mut bg_entries = vec![
- e(0, &b_params),
- e(1, &b_verts),
- e(2, &b_attrs),
- e(3, &b_nodes),
- e(4, &b_mats),
- e(5, &b_lights),
- e(6, &b_emit),
- wgpu::BindGroupEntry { binding: 7, resource: wgpu::BindingResource::TextureView(&tex_view) },
- wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::Sampler(&sampler) },
- wgpu::BindGroupEntry { binding: 9, resource: wgpu::BindingResource::TextureView(&env_view) },
- e(10, &b_cdf),
- e(11, &b_accum),
- e(12, &b_energy),
- e(14, &b_texinfo),
- e(15, &b_objects),
- e(16, &b_prev),
- e(17, &b_instances),
- e(18, &b_media),
- wgpu::BindGroupEntry { binding: 19, resource: wgpu::BindingResource::TextureView(&grid_view) },
- ];
- if let Some(a) = &accel {
- bg_entries.push(wgpu::BindGroupEntry { binding: 13, resource: a.tlas.as_binding() });
- }
- // The merged layout: the tables' one buffer in their place (merged.rs).
- let all_tables = [&b_mats, &b_lights, &b_emit, &b_texinfo, &b_objects, &b_instances, &b_media];
- let tables = self.merged.then(|| self.tables_buffer(all_tables));
- if let Some((t, _)) = &tables {
- bg_entries.retain(|e| !MERGED_TABLE_BINDINGS.contains(&e.binding));
- bg_entries.push(e(crate::merged::TABLES_BINDING, t));
- }
- // The uniform tables: four tables' uniform copies in their place (merged.rs `UNIFORM_TABLES`).
+ // The uniform tables: four tables' sections again in uniform buffers (merged.rs `UNIFORM_TABLES`).
let uniform = self.uniform_tables.then(|| {
- // What the scene has of each, against what its array holds (the buffers have the edits' room after it).
- let used = [b_texinfo.size() / 16, scene.objects.len() as u64, records.len() as u64, scene.media.len() as u64];
+ // What the scene has of each, against what its array holds (the sections have the edits' room after it).
+ let used = [tex_info.len() as u64, scene.objects.len() as u64, records.len() as u64, scene.media.len() as u64];
for note in uniform_overflow(used) {
eprintln!("threert: {note}");
}
- self.uniform_copies(uniform_sources(all_tables))
+ self.uniform_copies(&heap)
});
- if let Some(u) = &uniform {
- bind_uniform_tables(&mut bg_entries, u);
- }
- let bg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.layout, entries: &bg_entries });
+ let bg_parts = BindParts { nodes: b_nodes, tex_view, env_view, sampler, grid_view };
+ let bg = self.scene_bind_group(&SceneBuffers { params: &b_params, verts: &b_verts, attrs: &b_attrs, heap: &heap, words: &words, prev_verts: &b_prev, accum: &b_accum, parts: &bg_parts, accel: accel.as_ref(), uniform: uniform.as_ref() });
let mut kernel = Kernel::new(scene, groups);
- kernel.caps = tables.as_ref().map(|t| crate::merged::Caps { tables: t.1, live: self.no_vis_bufs.merged.as_ref().expect("merged").1 });
- let tables = tables.map(|t| t.0);
+ kernel.caps = self.no_vis_bufs.merged.as_ref().map(|m| crate::merged::Caps { live: m.1 });
// Translucent particles (hardware RT): their own BLAS + TLAS, rebuilt after the particle pass.
let translucent = match &accel {
Some(_) if !scene.trans_tris.is_empty() => {
@@ -2337,17 +2321,14 @@ impl Gpu {
let params = d.create_buffer(&wgpu::BufferDescriptor { label: Some("particle params"), size: 48, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let last = d.create_buffer(&wgpu::BufferDescriptor { label: Some("particles last"), size: b_prev.size(), usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });
let no_trans = d.create_buffer(&wgpu::BufferDescriptor { label: None, size: 64, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false });
- let pbg = d.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("particles"),
- layout: &pipeline.get_bind_group_layout(0),
- entries: &[e(0, &params), e(1, &b_sys), e(2, &b_verts), e(3, &b_prev), e(4, &a.verts), e(5, &b_objects), e(6, &b_attrs), e(7, &last), e(8, translucent.as_ref().map_or(&no_trans, |t| &t.verts))],
- });
+ let written = ParticleTargets { verts: &b_verts, prev_verts: &b_prev, blas_verts: &a.verts, heap: &heap, attrs: &b_attrs };
+ let pbg = particle_bind_group(d, &pipeline, "particles", &[(0, &params), (1, &b_sys), (7, &last), (8, translucent.as_ref().map_or(&no_trans, |t| &t.verts))], &written);
let nodes = scene.particles.iter().map(|p| p.seed).collect();
let opaque = scene.particles.iter().any(|p| !p.translucent);
let counts = scene.particles.iter().map(|p| p.count).collect();
let translucent_sys = scene.particles.iter().map(|p| p.translucent).collect();
let hidden = std::cell::RefCell::new(scene.particles.iter().map(|p| if p.hidden { Hidden::Idle } else { Hidden::Shown }).collect());
- Some(ParticleGpu { pipeline, stamp, bg: pbg, params, table: b_sys, nodes, systems: systems.len() as u32, max_count: scene.particles.iter().map(|p| p.count).max().unwrap_or(0), fresh: std::cell::Cell::new(true), opaque, counts, translucent: translucent_sys, hidden })
+ Some(ParticleGpu { pipeline, stamp, bg: pbg, params, table: b_sys, last, no_trans, nodes, systems: systems.len() as u32, max_count: scene.particles.iter().map(|p| p.count).max().unwrap_or(0), fresh: std::cell::Cell::new(true), opaque, counts, translucent: translucent_sys, hidden })
}
_ => None,
};
@@ -2380,26 +2361,22 @@ impl Gpu {
if let Some(o) = &scene.voxel_occupancy {
o.write().unwrap().dirty.clear();
}
- let bg = d.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("gpu particles"),
- layout: &pipeline.get_bind_group_layout(0),
- entries: &[e(0, &params), e(1, &table), e(2, &b_verts), e(3, &b_prev), e(4, &a.verts), e(5, &b_objects), e(6, &b_attrs), e(7, &last), e(8, &state), e(9, &spawns), e(10, &grid)],
- });
+ let written = ParticleTargets { verts: &b_verts, prev_verts: &b_prev, blas_verts: &a.verts, heap: &heap, attrs: &b_attrs };
+ let bg = particle_bind_group(d, &pipeline, "gpu particles", &[(0, &params), (1, &table), (7, &last), (8, &state), (9, &spawns), (10, &grid)], &written);
let host = scene.gpu_particles.iter().map(|ps| (0u32, 0.0f32, ps.rate)).collect();
let sm = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("stamp"), source: wgpu::ShaderSource::Wgsl(STAMP_WGSL.into()) });
let sp = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("stamp"), layout: None, module: &sm, entry_point: Some("stamp"), compilation_options: Default::default(), cache: self.cache() });
let sbg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("stamp"), layout: &sp.get_bind_group_layout(0), entries: &[e(0, &a.verts), wgpu::BindGroupEntry { binding: 1, resource: a.tlas.as_binding() }] });
- Some(GpuParticlesGpu { pipeline, stamp: (sp, sbg), bg, params, table, spawns, grid, systems: std::cell::RefCell::new(systems), host: std::cell::RefCell::new(host), nodes: scene.gpu_particles.iter().map(|p| p.node).collect(), max_cap: scene.gpu_particles.iter().map(|p| p.capacity).max().unwrap_or(0), frame: std::cell::Cell::new(0), fresh: std::cell::Cell::new(true), grid_o, grid_n })
+ Some(GpuParticlesGpu { pipeline, stamp: (sp, sbg), bg, params, table, last, state, spawns, grid, systems: std::cell::RefCell::new(systems), host: std::cell::RefCell::new(host), nodes: scene.gpu_particles.iter().map(|p| p.node).collect(), max_cap: scene.gpu_particles.iter().map(|p| p.capacity).max().unwrap_or(0), frame: std::cell::Cell::new(0), fresh: std::cell::Cell::new(true), grid_o, grid_n })
}
_ => None,
};
self.queue.submit([]);
self.device.poll(wgpu::PollType::wait_indefinitely())?;
timings.push(("upload_ms".into(), t0.elapsed().as_secs_f64() * 1000.0));
- let bg_parts = BindParts { nodes: b_nodes, energy: b_energy, texinfo: b_texinfo, tex_view, env_view, sampler, grid_view };
// (The scene's own pipelines, made above: particles, grid programs.)
self.save_pipeline_cache();
- Ok(Uploaded { bg, bg_parts, tables, uniform, accum: b_accum, params: b_params, width: w, height: h, kernel, materials: b_mats, lights: b_lights, objects: b_objects, emitters: b_emit, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, units: scene.units.clone(), particles, gpu_particles, grids, translucent, media: b_media, vcolor_base: (!scene.gpu_vcolors.is_empty()).then_some(scene.vcolor_base as u64 * 16), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), instances: b_instances, room, cdf: b_cdf, cdf_words: env_cdf.len(), region_words, env_tex })
+ Ok(Uploaded { bg, bg_parts, heap, uniform, accum: b_accum, params: b_params, width: w, height: h, kernel, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, units: scene.units.clone(), particles, gpu_particles, grids, translucent, vcolors: !scene.gpu_vcolors.is_empty(), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), room, words, cdf_words: env_cdf.len(), region_words, env_tex })
}
/// Bytes Metal allocates for an AABB BLAS over `count` boxes in `boxes` (its own size query through wgpu-hal; None
@@ -2454,64 +2431,69 @@ impl Gpu {
}
}
- /// The `env_cdf` binding of a scene with procedural geometry: the environment CDF, then the procedural region
- /// (scene::ProcLayout: headers and materials, then the geometries' blobs). Written straight into the new buffer's
- /// mapping; the blobs are copied on the GPU from the last upload when its geometries are the same.
- /// `room`: words of edit room wanted after the region (`EditRoom`); returns the buffer, the region's words in use
- /// and the room it got (as much as the binding limit leaves).
- fn upload_procs(&self, env_cdf: &[f32], l: &crate::scene::ProcLayout, room: usize, timings: &mut Vec<(String, f64)>) -> Result<(wgpu::Buffer, usize, usize)> {
+ /// The scene's 32-bit arrays (heap.rs `Stream`): the environment's CDF, the procedural region (scene::ProcLayout:
+ /// headers and materials, then the geometries' blobs) and the vertex colours, each with its edit room
+ /// (`room_words` after the region, as much of it as the binding limit leaves; `room_tris` triangles' colours).
+ /// Written straight into the new buffer's mapping; the blobs are copied on the GPU from the last upload when its
+ /// geometries are the same. Returns the heap, the region's words in use and the room it got.
+ fn upload_words(&self, scene: &Scene, env_cdf: &[f32], room_words: usize, room_tris: usize, timings: &mut Vec<(String, f64)>) -> Result<(Heap<Stream>, usize, usize)> {
let t = Instant::now();
- let (cdf, head) = (env_cdf.len(), l.head.len());
- let used = ((cdf + head + l.blob_words).max(1) * 4) as u64;
- let limit = self.device.limits().max_storage_buffer_binding_size as u64;
+ let l = scene.proc_layout.as_ref();
+ let (head, blob_words) = l.map_or((0, 0), |l| (l.head.len(), l.blob_words));
+ let colors: &[u8] = bytemuck::cast_slice(&scene.gpu_vcolors);
+ let color_bytes = if colors.is_empty() { 0 } else { colors.len() + room_tris * 12 };
+ let sizes = |room: usize| [(env_cdf.len() * 4) as u64, ((head + blob_words + room) * 4) as u64, color_bytes as u64];
+ let (used, limit) = (Heap::<Stream>::size_for(&sizes(0)), self.device.limits().max_storage_buffer_binding_size as u64);
if used > limit {
return Err(anyhow!("procedural geometry: {} MB of data, more than this device binds in one buffer ({} MB)", used >> 20, limit >> 20));
}
- let room = room.min(((limit - used) / 4) as usize);
- let bytes = used + room as u64 * 4;
- let key = l.key();
- let blob_at = ((cdf + head) * 4) as u64;
- let blob_bytes = (l.blob_words * 4) as u64;
+ // (A section's size is rounded up to where the next may start.)
+ let room = room_words.min(((limit - used) / 4).saturating_sub(crate::heap::ALIGN / 4) as usize);
+ let sizes = sizes(room);
+ let blob_at = (head * 4) as u64;
+ let blob_bytes = (blob_words * 4) as u64;
+ let key = l.map(|l| l.key());
let mut cache = self.proc_cache.lock().unwrap();
- let reuse = cache.as_ref().filter(|c| c.key == key && c.bytes == blob_bytes);
- let usage = wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC;
+ let reuse = cache.as_ref().filter(|c| blob_bytes > 0 && Some(&c.key) == key.as_ref() && c.bytes == blob_bytes);
// Reused blobs: the small parts written through the queue, the blobs copied on the GPU (a mapped buffer of the
// whole size would be zero-filled on the CPU first: 17 ms for 256 MB). New ones: written into the mapping.
- let b = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("env_cdf + procedural"), size: bytes, usage, mapped_at_creation: reuse.is_none() });
- if let Some(c) = reuse {
- self.queue.write_buffer(&b, 0, bytemuck::cast_slice(env_cdf));
- self.queue.write_buffer(&b, (cdf * 4) as u64, bytemuck::cast_slice(&l.head));
- if c.bytes > 0 {
+ let heap = match (reuse, l) {
+ (Some(c), Some(l)) => {
+ let heap = Heap::new(&self.device, &sizes);
+ heap.write(&self.queue, Stream::EnvCdf, 0, bytemuck::cast_slice(env_cdf));
+ heap.write(&self.queue, Stream::Procs, 0, bytemuck::cast_slice(&l.head));
+ heap.write(&self.queue, Stream::VertexColors, 0, colors);
let mut e = self.device.create_command_encoder(&Default::default());
- e.copy_buffer_to_buffer(&c.buf, c.offset, &b, blob_at, c.bytes);
+ e.copy_buffer_to_buffer(&c.buf, c.offset, &heap.buffer, heap.at(Stream::Procs) + blob_at, c.bytes);
self.queue.submit([e.finish()]);
+ heap
}
- } else {
- {
- let mut m = b.slice(..).get_mapped_range_mut().map_err(|e| anyhow!("procedural data: {e:?}"))?;
- // (Mapped memory is write-only here: byte ranges written whole.)
- let mut put = |word: usize, bytes: &[u8]| m.slice(word * 4..word * 4 + bytes.len()).copy_from_slice(bytes);
- put(0, bytemuck::cast_slice(env_cdf));
- put(cdf, bytemuck::cast_slice(&l.head));
+ _ => Heap::filled(&self.device, &sizes, |put| {
+ put(Stream::EnvCdf, 0, bytemuck::cast_slice(env_cdf));
+ put(Stream::VertexColors, 0, colors);
+ let Some(l) = l else { return };
+ put(Stream::Procs, 0, bytemuck::cast_slice(&l.head));
for (blob, off) in &l.blobs {
- let o = cdf + head + off;
- put(o, bytemuck::cast_slice(&blob.boxes));
- put(o + blob.boxes.len(), bytemuck::cast_slice(&blob.data));
+ let mut at = blob_at + (off * 4) as u64;
+ let mut parts: Vec<&[u8]> = vec![bytemuck::cast_slice(&blob.boxes), bytemuck::cast_slice(&blob.data)];
if l.sw {
let (nodes, order) = blob.sw_bvh();
- let o = o + blob.boxes.len() + blob.data.len();
- put(o, bytemuck::cast_slice(nodes));
- put(o + nodes.len(), bytemuck::cast_slice(order));
+ parts.extend([bytemuck::cast_slice::<_, u8>(nodes), bytemuck::cast_slice(order)]);
+ }
+ for part in parts {
+ put(Stream::Procs, at, part);
+ at += part.len() as u64;
}
}
- }
- b.unmap();
+ }),
+ };
+ if let Some(key) = key {
+ timings.push((if reuse.is_some() { "proc_copy_ms" } else { "proc_upload_ms" }.into(), t.elapsed().as_secs_f64() * 1000.0));
+ // The procedural region's GPU bytes (headers, materials, blobs: boxes and data, once per distinct geometry).
+ timings.push(("proc_data_mb".into(), ((head + blob_words) * 4) as f64 / (1 << 20) as f64));
+ *cache = Some(ProcCache { key, buf: heap.buffer.clone(), offset: heap.at(Stream::Procs) + blob_at, bytes: blob_bytes });
}
- timings.push((if reuse.is_some() { "proc_copy_ms" } else { "proc_upload_ms" }.into(), t.elapsed().as_secs_f64() * 1000.0));
- // The procedural region's GPU bytes (headers, materials, blobs: boxes and data, once per distinct geometry).
- timings.push(("proc_data_mb".into(), ((head + l.blob_words) * 4) as f64 / (1 << 20) as f64));
- *cache = Some(ProcCache { key, buf: b.clone(), offset: blob_at, bytes: blob_bytes });
- Ok((b, head + l.blob_words, room))
+ Ok((heap, head + blob_words, room))
}
/// The particle pass (scene time, camera, frame time, rain, wetness), then the dynamic BLASes and the TLAS rebuilt.
@@ -2804,8 +2786,7 @@ impl Gpu {
}
/// A volume node moved or changed its customData: its medium's world -> local rows / `custom` (None: unchanged).
- /// Replaces the environment map and its sampling CDF in place (a dynamic sky's new bake). Both keep their sizes:
- /// the CDF heads the binding it shares with the procedural region, which follows it.
+ /// Replaces the environment map and its sampling CDF in place (a dynamic sky's new bake). Both keep their sizes.
pub fn write_env(&self, up: &Uploaded, env: &EnvMap, cdf: &[f32]) {
let size = up.env_tex.size();
if (env.width, env.height) != (size.width, size.height) || cdf.len() != up.cdf_words {
@@ -2818,7 +2799,7 @@ impl Gpu {
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(env.width * 8), rows_per_image: Some(env.height) },
size,
);
- self.queue.write_buffer(&up.cdf, 0, bytemuck::cast_slice(cdf));
+ up.words.write(&self.queue, Stream::EnvCdf, 0, bytemuck::cast_slice(cdf));
}
/// A volume node shown or hidden by its own `visible`, in place: its media keep their place in the table with
@@ -2832,7 +2813,7 @@ impl Gpu {
found = true;
hidden[k] = hide;
let at = k * size + std::mem::offset_of!(crate::scene::MediumGpu, a) + 4;
- self.queue.write_buffer(&up.media, at as u64, bytemuck::bytes_of(&if hide { crate::scene::MEDIUM_HIDDEN } else { shape }));
+ up.heap.write(&self.queue, Table::Media, at as u64, bytemuck::bytes_of(&if hide { crate::scene::MEDIUM_HIDDEN } else { shape }));
}
found
}
@@ -2846,10 +2827,10 @@ impl Gpu {
let size = std::mem::size_of::<crate::scene::MediumGpu>();
for (k, _) in up.media_nodes.iter().enumerate().filter(|(_, n)| **n == node) {
if let Some(r) = rows {
- self.queue.write_buffer(&up.media, (k * size) as u64, bytemuck::cast_slice(&r));
+ up.heap.write(&self.queue, Table::Media, (k * size) as u64, bytemuck::cast_slice(&r));
}
if let Some(c) = custom {
- self.queue.write_buffer(&up.media, (k * size + std::mem::offset_of!(crate::scene::MediumGpu, c)) as u64, bytemuck::cast_slice(&c));
+ up.heap.write(&self.queue, Table::Media, (k * size + std::mem::offset_of!(crate::scene::MediumGpu, c)) as u64, bytemuck::cast_slice(&c));
}
}
}
@@ -2953,59 +2934,51 @@ impl Gpu {
}
}
- /// The scene bind group again, from `up`'s buffers as they are now (a buffer that grew: live/edits.rs `write_emitters`).
- pub fn rebind_scene(&self, up: &mut Uploaded) {
- fn e(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {
- wgpu::BindGroupEntry { binding, resource: b.as_entire_binding() }
- }
- let p = &up.bg_parts;
+ /// The scene's bind group (group 0: pathtrace.wgsl's declarations, the layout `Gpu::new` makes).
+ fn scene_bind_group(&self, b: &SceneBuffers) -> wgpu::BindGroup {
+ let view = |binding: u32, v| wgpu::BindGroupEntry { binding, resource: wgpu::BindingResource::TextureView(v) };
+ let p = b.parts;
let mut entries = vec![
- e(0, &up.params),
- e(1, &up.verts),
- e(2, &up.attrs),
- e(3, &p.nodes),
- e(4, &up.materials),
- e(5, &up.lights),
- e(6, &up.emitters),
- wgpu::BindGroupEntry { binding: 7, resource: wgpu::BindingResource::TextureView(&p.tex_view) },
+ buffer_entry(0, b.params),
+ buffer_entry(1, b.verts),
+ buffer_entry(2, b.attrs),
+ buffer_entry(3, &p.nodes),
+ buffer_entry(4, &b.heap.buffer),
+ buffer_entry(5, &b.words.buffer),
+ buffer_entry(6, b.prev_verts),
+ view(7, &p.tex_view),
wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::Sampler(&p.sampler) },
- wgpu::BindGroupEntry { binding: 9, resource: wgpu::BindingResource::TextureView(&p.env_view) },
- e(10, &up.cdf),
- e(11, &up.accum),
- e(12, &p.energy),
- e(14, &p.texinfo),
- e(15, &up.objects),
- e(16, &up.prev_verts),
- e(17, &up.instances),
- e(18, &up.media),
- wgpu::BindGroupEntry { binding: 19, resource: wgpu::BindingResource::TextureView(&p.grid_view) },
+ view(9, &p.env_view),
+ view(10, &p.grid_view),
+ buffer_entry(11, b.accum),
];
- if let Some(a) = &up.accel {
- entries.push(wgpu::BindGroupEntry { binding: 13, resource: a.tlas.as_binding() });
- }
- // The merged layout: the tables' buffer, a larger one if a table outgrew its array (the kernel's source then
- // has the new lengths: compiled on its next use).
- let now: [u32; 7] = std::array::from_fn(|k| crate::merged::table_cap(k, up.table_buffers()[k].size()));
- let tables = match (&up.tables, &up.kernel.caps) {
- (Some(t), Some(caps)) if now == caps.tables => Some(t.clone()),
- (Some(_), Some(_)) => Some(self.tables_buffer(up.table_buffers()).0),
- _ => None,
- };
- if let Some(t) = &tables {
- entries.retain(|e| !MERGED_TABLE_BINDINGS.contains(&e.binding));
- entries.push(e(crate::merged::TABLES_BINDING, t));
+ if !self.merged {
+ for &(table, binding) in &crate::merged::TABLE_VIEWS {
+ let copy = b.uniform.and_then(|u| u.iter().zip(&crate::merged::UNIFORM_TABLES).find(|(_, t)| t.binding == binding).map(|(c, _)| c));
+ entries.push(match copy {
+ Some(c) => buffer_entry(binding, c),
+ None => wgpu::BindGroupEntry { binding, resource: b.heap.binding(table) },
+ });
+ }
}
- // The uniform tables: the same copies (their size does not follow a table's: merged.rs `UNIFORM_LEN`).
- if let Some(u) = &up.uniform {
- bind_uniform_tables(&mut entries, u);
+ if let Some(a) = b.accel {
+ entries.push(wgpu::BindGroupEntry { binding: ACC_BINDING, resource: a.tlas.as_binding() });
}
- let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.layout, entries: &entries });
- drop(entries);
- up.bg = bg;
- if let (Some(_), Some(caps)) = (&tables, &mut up.kernel.caps) {
- caps.tables = now;
+ self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.layout, entries: &entries })
+ }
+
+ /// The bind groups that hold the scene's buffers again, from `up`'s as they are now (one that grew: the tables,
+ /// live/edits.rs): the kernel's, and the particle passes'.
+ pub fn rebind_scene(&self, up: &mut Uploaded) {
+ up.bg = self.scene_bind_group(&SceneBuffers { params: &up.params, verts: &up.verts, attrs: &up.attrs, heap: &up.heap, words: &up.words, prev_verts: &up.prev_verts, accum: &up.accum, parts: &up.bg_parts, accel: up.accel.as_ref(), uniform: up.uniform.as_ref() });
+ let Some(a) = &up.accel else { return };
+ let written = ParticleTargets { verts: &up.verts, prev_verts: &up.prev_verts, blas_verts: &a.verts, heap: &up.heap, attrs: &up.attrs };
+ if let Some(p) = &mut up.particles {
+ p.bg = particle_bind_group(&self.device, &p.pipeline, "particles", &[(0, &p.params), (1, &p.table), (7, &p.last), (8, up.translucent.as_ref().map_or(&p.no_trans, |t| &t.verts))], &written);
+ }
+ if let Some(p) = &mut up.gpu_particles {
+ p.bg = particle_bind_group(&self.device, &p.pipeline, "gpu particles", &[(0, &p.params), (1, &p.table), (7, &p.last), (8, &p.state), (9, &p.spawns), (10, &p.grid)], &written);
}
- up.tables = tables;
}
/// The loop guard's count as the GPU has it now (None: `kernel` has no guard): the invocations it stopped since
@@ -3023,52 +2996,31 @@ impl Gpu {
Ok(Some(n))
}
- /// The buffer of the merged layout's `MergedTables` for these seven tables (merged.rs `TABLES`' order), and its
- /// arrays' lengths.
- fn tables_buffer(&self, tables: [&wgpu::Buffer; 7]) -> (wgpu::Buffer, [u32; 7]) {
- let caps: [u32; 7] = std::array::from_fn(|k| crate::merged::table_cap(k, tables[k].size()));
- let (_, size) = crate::merged::offsets(&crate::merged::TABLES, &caps);
- (self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("merged tables"), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), caps)
- }
-
- /// The uniform tables' buffers for these four tables (merged.rs `UNIFORM_TABLES`' order), filled from them as they
- /// are now.
- fn uniform_copies(&self, tables: [&wgpu::Buffer; 4]) -> [wgpu::Buffer; 4] {
- use crate::merged::{TABLES, UNIFORM_LEN, UNIFORM_TABLES};
- let copies: [wgpu::Buffer; 4] = std::array::from_fn(|k| {
- let m = &TABLES[UNIFORM_TABLES[k]];
+ /// The uniform tables' buffers (merged.rs `UNIFORM_TABLES`' order), filled from their sections as they are now.
+ fn uniform_copies(&self, heap: &Heap<Table>) -> [wgpu::Buffer; 4] {
+ let copies = crate::merged::UNIFORM_TABLES.each_ref().map(|t| {
// (COPY_SRC: read back by the test that holds them to the tables, and by whoever diagnoses a driver.)
- self.device.create_buffer(&wgpu::BufferDescriptor { label: Some(m.name), size: m.stride * UNIFORM_LEN[k] as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false })
+ self.device.create_buffer(&wgpu::BufferDescriptor { label: Some(t.name), size: t.stride * t.len as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false })
});
let mut e = self.device.create_command_encoder(&Default::default());
- Self::copy_uniform(&mut e, tables, &copies);
+ Self::copy_uniform(&mut e, heap, &copies);
self.queue.submit([e.finish()]);
copies
}
- fn copy_uniform(e: &mut wgpu::CommandEncoder, tables: [&wgpu::Buffer; 4], copies: &[wgpu::Buffer; 4]) {
- for (src, dst) in tables.into_iter().zip(copies) {
- let bytes = uniform_copy_bytes(src.size(), dst.size());
- if bytes > 0 {
- e.copy_buffer_to_buffer(src, 0, dst, 0, bytes);
- }
+ fn copy_uniform(e: &mut wgpu::CommandEncoder, heap: &Heap<Table>, copies: &[wgpu::Buffer; 4]) {
+ for (t, dst) in crate::merged::UNIFORM_TABLES.iter().zip(copies) {
+ e.copy_buffer_to_buffer(&heap.buffer, heap.at(t.table), dst, 0, uniform_copy_bytes(heap.cap(t.table), dst.size()));
}
}
- /// The merged layout: the tables as they are now, copied into the struct's buffer. The renderer writes the tables
- /// where it always did; the passes that read the scene read this copy, so it is made in their encoder, before
- /// them, each frame (the tables are small: a few copies of kilobytes). The uniform tables: the same, into the
- /// four uniform buffers. After whatever writes a table on the GPU in that encoder (the particle passes write
- /// their objects' entries).
+ /// The uniform tables: their sections as they are now, copied into the four uniform buffers. The renderer writes
+ /// the tables' heap; the passes that read the scene read these copies, so they are made in their encoder, before
+ /// them, each frame, after whatever writes a table on the GPU in that encoder (the particle passes write their
+ /// objects' entries).
pub fn sync_tables(&self, up: &Uploaded, e: &mut wgpu::CommandEncoder) {
if let Some(u) = &up.uniform {
- Self::copy_uniform(e, uniform_sources(up.table_buffers()), u);
- }
- let (Some(t), Some(caps)) = (&up.tables, &up.kernel.caps) else { return };
- let (at, _) = crate::merged::offsets(&crate::merged::TABLES, &caps.tables);
- for (k, src) in up.table_buffers().into_iter().enumerate() {
- let room = crate::merged::TABLES[k].stride * caps.tables[k] as u64;
- e.copy_buffer_to_buffer(src, 0, t, at[k], src.size().min(room));
+ Self::copy_uniform(e, &up.heap, u);
}
}
@@ -3182,6 +3134,7 @@ impl Gpu {
for s in 0..n {
let mut p = base;
p.size[2] = s;
+ up.place(&mut p);
self.queue.write_buffer(&up.params, 0, bytemuck::bytes_of(&p));
let mut enc = d.create_command_encoder(&Default::default());
{
@@ -3214,10 +3167,10 @@ impl Gpu {
#[cfg(not(target_arch = "wasm32"))]
/// Render `spp` samples. `base` holds everything except the per-dispatch sample index.
#[allow(clippy::too_many_arguments)]
- pub fn render(&self, scene: &Scene, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], base: Params, spp: u32, timings: &mut Vec<(String, f64)>) -> Result<Frame> {
+ pub fn render(&self, scene: &Scene, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], base: Params, spp: u32, timings: &mut Vec<(String, f64)>) -> Result<Frame> {
let d = &self.device;
let (w, h) = (scene.width, scene.height);
- let up = self.upload(scene, w, h, tri_verts, groups, nodes, emitters, env, env_cdf, energy, timings)?;
+ let up = self.upload(scene, w, h, tri_verts, groups, nodes, emitters, light_tree, env, env_cdf, energy, timings)?;
let pipeline = self.pipeline(&up.kernel, false);
// Particles: placed once, at the scene time and camera.
if up.particles.is_some() {
@@ -3273,6 +3226,7 @@ impl Gpu {
for k in 0..batch.min(spp - s) {
let mut p = base;
p.size[2] = s + k;
+ up.place(&mut p);
self.queue.write_buffer(b_params, 0, bytemuck::bytes_of(&p));
let mut enc = d.create_command_encoder(&Default::default());
{
@@ -3539,7 +3493,7 @@ mod tests {
assert_eq!(queries, if hwrt { 3 } else { 0 });
assert_eq!(strict.matches("ray_bad(o, d, tmax").count(), queries, "every ray query is guarded");
assert_eq!(strict.matches("fn ray_bad(").count(), hwrt as usize);
- assert!(!strict.contains("env_cdf[y - 1u]") && !strict.contains("env_cdf[base + x - 1u]") && plain.contains("env_cdf[y - 1u]"));
+ assert!(!strict.contains("env_cdf_at(y - 1u)") && !strict.contains("env_cdf_at(base + x - 1u)") && plain.contains("env_cdf_at(y - 1u)"));
let lit = v(hwrt, KernelSwitches { strict: true, cutout_lite: 2, last_direct: true, last_sun: false, light_pick: true });
assert_eq!(lit.matches("radiance += dz;").count(), 1);
assert!(!lit.contains("fn sun_light("), "last_direct takes the directional lights already");
@@ -3553,22 +3507,22 @@ mod tests {
}
/// The uniform tables' buffers: each array fits a uniform binding of 64 KiB, the media's holds every medium a
- /// scene may have, and the four are at their tables' bindings. A copy takes what the table and its uniform buffer
- /// both hold, in whole words; a scene with more entries than an array is said, by name.
+ /// scene may have, and the four are at their own bindings, before the acceleration structure's. A copy takes what
+ /// the table's section and its uniform buffer both hold, in whole words; a scene with more entries than an array
+ /// is said, by name.
#[test]
fn the_uniform_tables_fit_their_bindings() {
- use crate::merged::{TABLES, UNIFORM_LEN, UNIFORM_TABLES};
- let bindings = UNIFORM_TABLES.map(|k| MERGED_TABLE_BINDINGS[k]);
- assert_eq!(bindings, [14, 15, 17, 18]);
- for (k, &t) in UNIFORM_TABLES.iter().enumerate() {
- let m = &TABLES[t];
- assert!(kernel_template().contains(&format!("@group(0) @binding({}) var<uniform> {}: array<", bindings[k], m.name)), "{}", m.name);
- let bytes = m.stride * UNIFORM_LEN[k] as u64;
- assert!(bytes <= 65536 && bytes % 16 == 0, "{}: {bytes} bytes", m.name);
- }
- assert_eq!(UNIFORM_TABLES.map(|t| TABLES[t].name), ["tex_info", "objects", "instances", "media"]);
- assert_eq!(UNIFORM_LEN[3] as usize, crate::scene::MAX_MEDIA);
- assert_eq!(UNIFORM_LEN[2] as u64, 65536 / TABLES[5].stride);
+ use crate::merged::UNIFORM_TABLES;
+ for t in &UNIFORM_TABLES {
+ assert!(kernel_template().contains(&format!("@group(0) @binding({}) var<uniform> {}: array<", t.binding, t.name)), "{}", t.name);
+ let bytes = t.stride * t.len as u64;
+ assert!(bytes <= 65536 && bytes % 16 == 0 && t.binding < ACC_BINDING, "{}: {bytes} bytes", t.name);
+ }
+ assert_eq!(UNIFORM_TABLES.each_ref().map(|t| t.table), [Table::TexInfo, Table::Objects, Table::Instances, Table::Media]);
+ assert_eq!(UNIFORM_TABLES[3].len as usize, crate::scene::MAX_MEDIA);
+ assert_eq!(UNIFORM_TABLES[2].len as u64, 65536 / UNIFORM_TABLES[2].stride);
+ assert_eq!([UNIFORM_TABLES[2].stride as usize, UNIFORM_TABLES[3].stride as usize], [std::mem::size_of::<crate::scene::GpuInstance>(), std::mem::size_of::<crate::scene::MediumGpu>()]);
+ assert!(kernel_template().contains(&format!("@group(0) @binding({ACC_BINDING}) var acc: acceleration_structure;")));
// A table shorter than its array, one with the edits' room past it, one whose size is not the array's multiple.
assert_eq!([uniform_copy_bytes(512, 65536), uniform_copy_bytes(1 << 20, 65536), uniform_copy_bytes(65600, 65440), uniform_copy_bytes(0, 7168), uniform_copy_bytes(7, 64)], [512, 65536, 65440, 0, 4]);
assert!(uniform_overflow([4096, 4096, 409, 32]).is_empty());
diff --git a/renderer/src/heap.rs b/renderer/src/heap.rs
new file mode 100644
index 0000000..028c0d5
--- /dev/null
+++ b/renderer/src/heap.rs
@@ -0,0 +1,197 @@
+//! The scene's read-only data as the kernel binds it: two buffers, each a row of named sections.
+//!
+//! `Table`s (pathtrace.wgsl `tables`, an array of vec4s): the scene's records. `Stream`s (`words`, an array of
+//! 32-bit words): its flat arrays. A section holds one of them and the room after it, and the kernel finds it by the
+//! element `Params::table_first` / `Params::word_first` name (`Heap::firsts`), so what a scene has more of is
+//! another section, not another binding. Sections start at multiples of `ALIGN` bytes: a pass that writes one binds it as a buffer of
+//! its own (`Heap::binding`), and a binding's offset is a multiple of that (WebGPU's
+//! `minStorageBufferOffsetAlignment`). One that outgrows its room is given more in a new buffer, the contents copied
+//! on the GPU (`Heap::grow`); the scene's bind group is then made again (`Gpu::rebind_scene`).
+
+use std::marker::PhantomData;
+
+/// Where a section may start, and the least it holds (an empty table still reads as zeros), in bytes.
+pub const ALIGN: u64 = 256;
+const LEAST: u64 = 512;
+
+/// A heap's sections: their count, their element's size in bytes and each one's place in `Params`.
+pub trait Section: Copy {
+ const COUNT: usize;
+ const UNIT: u64;
+ const LABEL: &'static str;
+ fn index(self) -> usize;
+}
+
+/// The scene's tables, in `Params::table_first`'s order (pathtrace.wgsl `material_at` and the others). The first
+/// is at element 0 whatever grows, so the kernel reads it with no offset: the one read most that has no view of its
+/// own (merged.rs `TABLE_VIEWS`).
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Table {
+ /// The emitters' tree (ltree.rs), a vec4 a node.
+ LightTree,
+ /// `scene::GpuMaterial`.
+ Materials,
+ /// `scene::GpuLight`.
+ Lights,
+ /// One sphere (centre, radius) per `LIGHT_GROUP` local lights (lib.rs `light_groups`).
+ LightGroups,
+ /// The emitter CDF: (triangle bits, cumulative weight, weight, area) per emissive triangle (lib.rs `emitter_cdf`).
+ Emitters,
+ /// Two vec4s a texture (texpack.rs).
+ TexInfo,
+ /// `Scene::object_stride` vec4s an object.
+ Objects,
+ /// `scene::GpuInstance`: the model instances' records, then the procedural objects'.
+ Instances,
+ /// `scene::MediumGpu`.
+ Media,
+ /// The GGX energy table, 512 vec4s.
+ Energy,
+}
+
+impl Section for Table {
+ const COUNT: usize = 10;
+ const UNIT: u64 = 16;
+ const LABEL: &'static str = "tables";
+ fn index(self) -> usize {
+ self as usize
+ }
+}
+
+/// The scene's flat arrays of 32-bit words, in `Params::word_first`'s order (pathtrace.wgsl `env_cdf_at`, `pword`,
+/// `vcolor_word`). The first is at word 0 whatever grows, so the kernel reads it with no offset: the one read most.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Stream {
+ /// The environment's sampling CDF (floats): the rows' marginal CDF, then each row's.
+ EnvCdf,
+ /// The procedural geometry's region (scene::ProcLayout): headers and materials, then the geometries' blobs.
+ Procs,
+ /// Vertex colours: three sRGB8 words a triangle, in the triangles' GPU order.
+ VertexColors,
+}
+
+impl Section for Stream {
+ const COUNT: usize = 3;
+ const UNIT: u64 = 4;
+ const LABEL: &'static str = "words";
+ fn index(self) -> usize {
+ self as usize
+ }
+}
+
+/// A heap: its buffer, and each section's first byte and size.
+pub struct Heap<S: Section> {
+ pub buffer: wgpu::Buffer,
+ at: Vec<u64>,
+ cap: Vec<u64>,
+ _s: PhantomData<S>,
+}
+
+/// Where sections of at least `bytes` each are, their sizes, and the buffer's.
+fn place(bytes: &[u64]) -> (Vec<u64>, Vec<u64>, u64) {
+ let cap: Vec<u64> = bytes.iter().map(|b| (*b).max(LEAST).next_multiple_of(ALIGN)).collect();
+ let at: Vec<u64> = cap.iter().scan(0u64, |end, c| Some(std::mem::replace(end, *end + c))).collect();
+ let size = cap.iter().sum();
+ (at, cap, size)
+}
+
+const USAGE: wgpu::BufferUsages = wgpu::BufferUsages::STORAGE.union(wgpu::BufferUsages::COPY_DST).union(wgpu::BufferUsages::COPY_SRC);
+
+impl<S: Section> Heap<S> {
+ /// The bytes of a heap whose sections hold `bytes` each.
+ pub fn size_for(bytes: &[u64]) -> u64 {
+ place(bytes).2
+ }
+
+ /// A heap of zeros with sections of at least `bytes` each (`S::COUNT` of them), to be written through the queue.
+ pub fn new(device: &wgpu::Device, bytes: &[u64]) -> Self {
+ assert_eq!(bytes.len(), S::COUNT);
+ let (at, cap, size) = place(bytes);
+ let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(S::LABEL), size, usage: USAGE, mapped_at_creation: false });
+ Heap { buffer, at, cap, _s: PhantomData }
+ }
+
+ /// The same, filled while it is made: `fill` is given `put(section, byte, data)`, which writes into the buffer's
+ /// mapping (no copy through the queue).
+ pub fn filled(device: &wgpu::Device, bytes: &[u64], fill: impl FnOnce(&mut dyn FnMut(S, u64, &[u8]))) -> Self {
+ assert_eq!(bytes.len(), S::COUNT);
+ let (at, cap, size) = place(bytes);
+ let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(S::LABEL), size, usage: USAGE, mapped_at_creation: true });
+ {
+ let mut m = buffer.slice(..).get_mapped_range_mut().expect("mapped at creation");
+ fill(&mut |s: S, byte: u64, data: &[u8]| {
+ let k = s.index();
+ assert!(byte + data.len() as u64 <= cap[k], "{}: section {k} holds {} bytes, {} written at {byte}", S::LABEL, cap[k], data.len());
+ let o = (at[k] + byte) as usize;
+ m.slice(o..o + data.len()).copy_from_slice(data);
+ });
+ }
+ buffer.unmap();
+ Heap { buffer, at, cap, _s: PhantomData }
+ }
+
+ /// A section's first byte in the buffer.
+ pub fn at(&self, s: S) -> u64 {
+ self.at[s.index()]
+ }
+
+ /// The bytes a section holds.
+ pub fn cap(&self, s: S) -> u64 {
+ self.cap[s.index()]
+ }
+
+ /// Each section's first element, for `Params`.
+ pub fn firsts(&self) -> Vec<u32> {
+ self.at.iter().map(|a| (a / S::UNIT) as u32).collect()
+ }
+
+ /// `data` into a section, `byte` bytes from its start.
+ pub fn write(&self, q: &wgpu::Queue, s: S, byte: u64, data: &[u8]) {
+ let k = s.index();
+ assert!(byte + data.len() as u64 <= self.cap[k], "{}: section {k} holds {} bytes, {} written at {byte}", S::LABEL, self.cap[k], data.len());
+ q.write_buffer(&self.buffer, self.at[k] + byte, data);
+ }
+
+ /// A section as a buffer of its own.
+ pub fn binding(&self, s: S) -> wgpu::BindingResource<'_> {
+ let k = s.index();
+ wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &self.buffer, offset: self.at[k], size: std::num::NonZeroU64::new(self.cap[k]) })
+ }
+
+ /// The bytes of this heap with section `s` holding `bytes`.
+ pub fn size_with(&self, s: S, bytes: u64) -> u64 {
+ let mut want = self.cap.clone();
+ want[s.index()] = bytes;
+ place(&want).2
+ }
+
+ /// Section `s` with room for `bytes`: a new buffer, every section's contents copied on the GPU and submitted now,
+ /// so writes queued after this land on the copy. The sections after it move: whoever holds the buffer or an
+ /// offset (the scene's bind group, `Params`) reads them again.
+ pub fn grow(&mut self, device: &wgpu::Device, q: &wgpu::Queue, s: S, bytes: u64) {
+ let mut want = self.cap.clone();
+ want[s.index()] = bytes;
+ let (at, cap, size) = place(&want);
+ let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(S::LABEL), size, usage: USAGE, mapped_at_creation: false });
+ let mut e = device.create_command_encoder(&Default::default());
+ for k in 0..S::COUNT {
+ e.copy_buffer_to_buffer(&self.buffer, self.at[k], &buffer, at[k], self.cap[k].min(cap[k]));
+ }
+ q.submit([e.finish()]);
+ (self.buffer, self.at, self.cap) = (buffer, at, cap);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sections_start_where_a_pass_can_bind_them() {
+ let (at, cap, size) = place(&[0, 1, 513, 4096]);
+ assert_eq!(cap, [512, 512, 768, 4096]);
+ assert_eq!(at, [0, 512, 1024, 1792]);
+ assert_eq!(size, 5888);
+ assert!(at.iter().all(|a| a % ALIGN == 0));
+ }
+}
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 2588d8a..ecb2073 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -12,6 +12,7 @@ pub mod denoise;
pub mod desc;
pub mod files;
pub mod gpu;
+pub mod heap;
#[cfg(not(target_arch = "wasm32"))]
pub mod host;
pub mod live;
@@ -73,7 +74,7 @@ pub struct Prepared {
pub energy: Vec<[f32; 4]>,
/// Emissive triangles (also those at power 0), for re-weighting `emitters` after power / material edits.
pub emitter_tris: Vec<EmitterTri>,
- /// The light tree over the static emitters (`ltree`), its nodes after the CDF in `emitters`.
+ /// The light tree over the static emitters (`ltree`).
pub light_tree: Option<ltree::LightTree>,
/// Material -> runs of its flattened static triangles (first, end in the traversal order, object), and the
/// materials that also cover pool or dynamic triangles: a material that starts emitting gets emitter entries in
@@ -213,7 +214,7 @@ pub fn rng_seed() -> u32 {
pub const LIGHT_GROUP: usize = 16;
/// Distance beyond which a local light gives nothing (the kernel's range test in `local_lights`); f32::MAX without a
-/// range. (A black light gives nothing anywhere: `lights_with_groups` leaves it out.)
+/// range. (A black light gives nothing anywhere: `light_groups` leaves it out.)
fn light_reach(l: &scene::GpuLight) -> f32 {
if l.color[3] <= 0.0 {
return f32::MAX;
@@ -260,7 +261,7 @@ fn light_class(l: &scene::GpuLight) -> u8 {
/// The kernel's light order: directional lights first (it loops over them), then local lights without shadows (evaluated
/// exactly at camera hits, like UE's deferred lights), then shadowed ones (one shadow ray each when few, else sampled);
-/// each class spatially sorted into the kernel's light groups (`lights_with_groups`).
+/// each class spatially sorted into the kernel's light groups (`light_groups`).
pub fn light_order(lights: &[scene::GpuLight]) -> Vec<usize> {
let mut order: Vec<usize> = (0..lights.len()).collect();
order.sort_by_key(|&i| light_class(&lights[i]));
@@ -272,19 +273,19 @@ pub fn light_order(lights: &[scene::GpuLight]) -> Vec<usize> {
order
}
-/// The light table as uploaded: the lights, then per group of LIGHT_GROUP local lights (counted from the first local
-/// one) an entry whose `pos` is the sphere (centre, radius) holding every point its lights reach. Black lights (off, or
-/// hidden: `scene::gpu_light_shown`) reach nothing and are in no sphere; a group of them alone has radius -1 (no point
-/// is in it). THREERT_LIGHT_GROUPS=0: unbounded spheres, every light tested (A/B).
-pub fn lights_with_groups(lights: &[scene::GpuLight]) -> Vec<scene::GpuLight> {
+/// The light groups' table: per group of LIGHT_GROUP local lights (counted from the first local one) the sphere
+/// (centre, radius) holding every point its lights reach. Black lights (off, or hidden: `scene::gpu_light_shown`)
+/// reach nothing and are in no sphere; a group of them alone has radius -1 (no point is in it).
+/// THREERT_LIGHT_GROUPS=0: unbounded spheres, every light tested (A/B).
+pub fn light_groups(lights: &[scene::GpuLight]) -> Vec<[f32; 4]> {
static OFF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let off = *OFF.get_or_init(|| std::env::var("THREERT_LIGHT_GROUPS").is_ok_and(|v| v == "0"));
let nd = lights.iter().take_while(|l| l.pos[3] == 0.0).count();
- let mut out = lights.to_vec();
+ let mut out = vec![];
for g in lights[nd..].chunks(LIGHT_GROUP) {
let lit = |l: &&scene::GpuLight| l.color[..3].iter().any(|c| *c > 0.0);
if !off && !g.iter().any(|l| lit(&l)) {
- out.push(scene::GpuLight { pos: [0.0, 0.0, 0.0, -1.0], ..Default::default() });
+ out.push([0.0, 0.0, 0.0, -1.0]);
continue;
}
let (mut a, mut b) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
@@ -305,7 +306,7 @@ pub fn lights_with_groups(lights: &[scene::GpuLight]) -> Vec<scene::GpuLight> {
if r < f32::MAX {
r = r * (1.0 + 1e-5) + 1e-3 * (1.0 + c.abs().max_element() * 1e-3);
}
- out.push(scene::GpuLight { pos: [c.x, c.y, c.z, r], ..Default::default() });
+ out.push([c.x, c.y, c.z, r]);
}
out
}
@@ -613,16 +614,9 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
// From here on an entry of the tree is its position in `emitter_tris` (the live view's refits read it so).
t.order = (0..t.order.len() as u32).collect();
}
- let (mut emitters, total, _) = emitter_cdf(&emitter_tris, &sc.materials, &sc.objects, sc.object_stride(), [0.0; 4], EmitterCull::default());
- let ltree_param = match &light_tree {
- Some(t) => {
- let off = emitters.len() as u32;
- emitters.extend_from_slice(&t.nodes);
- // The moving emitters (after the tree's in the CDF) are picked with the probability of their share of power.
- [f32::from_bits(off), f32::from_bits(t.order.len() as u32), if total > 0.0 { ((total - t.power) / total).max(0.0) } else { 0.0 }, ltree::RIS_OFFLINE as f32]
- }
- None => [0.0; 4],
- };
+ let (emitters, total, _) = emitter_cdf(&emitter_tris, &sc.materials, &sc.objects, sc.object_stride(), [0.0; 4], EmitterCull::default());
+ // The moving emitters (after the tree's in the CDF) are picked with the probability of their share of power.
+ let ltree_param = light_tree.as_ref().map_or([0.0; 4], |t| [0.0, f32::from_bits(t.order.len() as u32), if total > 0.0 { ((total - t.power) / total).max(0.0) } else { 0.0 }, ltree::RIS_OFFLINE as f32]);
// Sky / environment.
let t = Instant::now();
@@ -670,14 +664,8 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
scene::SkyData::Color(c) => (gpu::EnvMap { width: 1, height: 1, texels: vec![[c.x, c.y, c.z, 1.0]] }, *c, false),
scene::SkyData::None => (gpu::EnvMap { width: 1, height: 1, texels: vec![[0.0; 4]] }, Vec3::ZERO, false),
};
- // The procedural region rides after the environment's CDF (its binding is the kernel's one flat 32-bit array, and
- // the kernel has no binding to spare: Metal's 29 with the translucency pass); gpu.rs `upload_procs` lays it out.
let env_cdf = build_env_cdf(&env);
- // (w: the vertex colours' first vec4 in `prev_verts`, after the dynamic tail's previous vertices; gpu.rs F_VCOLOR.)
- if !sc.gpu_vcolors.is_empty() {
- sc.vcolor_base = ((groups[4..].iter().sum::<usize>() + scene::deforming_pool(&sc.meshes)) * 3) as u32;
- }
- let procs = [env_cdf.len() as u32, sc.procs.len() as u32, sc.gpu_instances.len() as u32, sc.vcolor_base];
+ let procs = [0, sc.procs.len() as u32, sc.gpu_instances.len() as u32, 0];
// Environment light sampling (one shadow ray per vertex) is skipped when the sky is negligible next to the emitters
// (night streets): escaping BSDF rays still pick it up, with full MIS weight. The emitters as if all on: a
// time-of-day room loaded by day decides at dusk as one loaded at night does (live/edits.rs `put_sky`).
@@ -746,6 +734,9 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
ltile: [0; 4],
ltile2: [0; 4],
lt_cam: [[0.0; 4]; 4],
+ // (`gpu::Uploaded::place`, with the buffers.)
+ table_first: [[0; 4]; 3],
+ word_first: [0; 4],
};
let mut params = params;
let mut first = 0u32;
@@ -1044,20 +1035,20 @@ mod light_lod_tests {
let sorted: Vec<_> = order.iter().map(|&i| lights[i]).collect();
let classes: Vec<u8> = sorted.iter().map(light_class).collect();
assert!(classes.windows(2).all(|w| w[0] <= w[1]), "classes stay in order");
- let table = lights_with_groups(&sorted);
+ let table = light_groups(&sorted);
let nd = 1;
- assert_eq!(table.len(), sorted.len() + (sorted.len() - nd).div_ceil(LIGHT_GROUP));
+ assert_eq!(table.len(), (sorted.len() - nd).div_ceil(LIGHT_GROUP));
for (i, l) in sorted.iter().enumerate().skip(nd) {
- let g = table[sorted.len() + (i - nd) / LIGHT_GROUP].pos;
+ let g = table[(i - nd) / LIGHT_GROUP];
let d = Vec3::new(g[0], g[1], g[2]).distance(Vec3::from_slice(&l.pos[..3]));
assert!(d + light_reach(l) <= g[3], "light {i} reaches out of its group's sphere");
}
// Spatially compact: the groups' mean radius well under that of the same classes in their original order.
let mut plain: Vec<usize> = (0..lights.len()).collect();
plain.sort_by_key(|&i| light_class(&lights[i]));
- let unsorted = lights_with_groups(&plain.iter().map(|&i| lights[i]).collect::<Vec<_>>());
- let mean = |t: &[scene::GpuLight]| {
- let r: Vec<f32> = t[sorted.len()..].iter().map(|g| g.pos[3]).filter(|r| *r < f32::MAX).collect();
+ let unsorted = light_groups(&plain.iter().map(|&i| lights[i]).collect::<Vec<_>>());
+ let mean = |t: &[[f32; 4]]| {
+ let r: Vec<f32> = t.iter().map(|g| g[3]).filter(|r| *r < f32::MAX).collect();
r.iter().sum::<f32>() / r.len() as f32
};
assert!(mean(&table) < 0.5 * mean(&unsorted), "groups are compact: {} vs {}", mean(&table), mean(&unsorted));
@@ -1070,15 +1061,15 @@ mod light_lod_tests {
let at = |x: f32, lit: bool| scene::GpuLight { pos: [x, 0.0, 0.0, 1.0], color: [if lit { 1.0 } else { 0.0 }, 0.0, 0.0, 10.0], ..Default::default() };
// 16 lit lights within 15 m and, in their group's place, one of them black 10 km away: the sphere as without it.
let mut near: Vec<_> = (0..LIGHT_GROUP).map(|k| at(k as f32, true)).collect();
- let lit = lights_with_groups(&near)[LIGHT_GROUP].pos;
+ let lit = light_groups(&near)[0];
near[3] = at(-10_000.0, false);
- let with_black = lights_with_groups(&near)[LIGHT_GROUP].pos;
+ let with_black = light_groups(&near)[0];
assert!(with_black[3] <= lit[3] && with_black[3] > 0.0, "{with_black:?} for {lit:?}");
// A group of black lights alone: radius -1.
let dark: Vec<_> = (0..LIGHT_GROUP + 2).map(|k| at(k as f32, k < LIGHT_GROUP)).collect();
- let t = lights_with_groups(&dark);
- assert!(t[dark.len()].pos[3] > 0.0);
- assert_eq!(t[dark.len() + 1].pos[3], -1.0);
+ let t = light_groups(&dark);
+ assert!(t[0][3] > 0.0);
+ assert_eq!(t[1][3], -1.0);
}
}
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 61399ba..917345c 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -15,13 +15,24 @@ impl Gather {
self.parts.push((at, bytes.to_vec()));
}
+ /// Into a heap's section (offsets from its start).
+ pub(super) fn flush_section<S: Section + std::fmt::Debug>(self, q: &wgpu::Queue, heap: &Heap<S>, s: S) {
+ let end = self.parts.iter().map(|p| p.0 + p.1.len() as u64).max().unwrap_or(0);
+ assert!(end <= heap.cap(s), "{s:?}: {end} bytes written, the section holds {}", heap.cap(s));
+ self.flush_at(q, &heap.buffer, heap.at(s));
+ }
+
pub(super) fn flush(self, q: &wgpu::Queue, b: &wgpu::Buffer) {
+ self.flush_at(q, b, 0);
+ }
+
+ fn flush_at(self, q: &wgpu::Queue, b: &wgpu::Buffer, base: u64) {
let mut parts = self.parts;
let mut sorted = parts.clone();
sorted.sort_by_key(|p| p.0);
if sorted.windows(2).any(|w| w[0].0 + w[0].1.len() as u64 > w[1].0) {
for (at, bytes) in parts.drain(..) {
- q.write_buffer(b, at, &bytes);
+ q.write_buffer(b, base + at, &bytes);
}
return;
}
@@ -31,14 +42,14 @@ impl Gather {
Some((start, data)) if *start + data.len() as u64 == at => data.extend_from_slice(&bytes),
_ => {
if let Some((start, data)) = run.take() {
- q.write_buffer(b, start, &data);
+ q.write_buffer(b, base + start, &data);
}
run = Some((at, bytes));
}
}
}
if let Some((start, data)) = run {
- q.write_buffer(b, start, &data);
+ q.write_buffer(b, base + start, &data);
}
}
}
@@ -209,66 +220,73 @@ impl Grow<'_> {
sizes.iter().all(|&s| s <= max)
}
- /// Triangles: vertices, attributes, the BLASes' vertices, vertex colours (after the previous vertices).
- pub(super) fn tris(&self, h: &mut Holes, extra: usize, verts: &mut wgpu::Buffer, attrs: &mut wgpu::Buffer, prev: &mut wgpu::Buffer, vcolor_base: Option<u64>, accel: &mut gpu::Accel) -> bool {
+ /// Triangles: vertices, attributes, the BLASes' vertices, and in a scene with them (`colors`) vertex colours.
+ pub(super) fn tris(&self, h: &mut Holes, extra: usize, verts: &mut wgpu::Buffer, attrs: &mut wgpu::Buffer, words: &mut Heap<Stream>, colors: bool, accel: &mut gpu::Accel) -> bool {
if !self.ok {
return false;
}
let cap = Self::cap(h, extra);
- let prev_bytes = vcolor_base.map_or(0, |base| (base + cap as u64 * 12).next_multiple_of(16));
- if !self.fits(&[(cap * 48) as u64, (cap * std::mem::size_of::<scene::GpuTriAttr>()) as u64, (cap * 36) as u64, prev_bytes]) {
+ let color_bytes = (cap * 12) as u64;
+ if !self.fits(&[(cap * 48) as u64, (cap * std::mem::size_of::<scene::GpuTriAttr>()) as u64, (cap * 36) as u64, if colors { words.size_with(Stream::VertexColors, color_bytes) } else { 0 }]) {
return false;
}
*verts = self.g.grown(verts, (cap * 48) as u64, "verts");
*attrs = self.g.grown(attrs, (cap * std::mem::size_of::<scene::GpuTriAttr>()) as u64, "attrs");
self.g.grow_blas_verts(accel, (cap * 36) as u64);
- if vcolor_base.is_some() {
- *prev = self.g.grown(prev, prev_bytes, "prev verts + vertex colours");
+ if colors {
+ words.grow(&self.g.device, &self.g.queue, Stream::VertexColors, color_bytes);
}
h.cap = cap;
true
}
+ /// A table's section to `bytes` (heap.rs `Heap::grow`), if the device binds the buffer that makes.
+ fn table(&self, heap: &mut Heap<Table>, t: Table, bytes: u64) -> bool {
+ if !self.fits(&[heap.size_with(t, bytes)]) {
+ return false;
+ }
+ heap.grow(&self.g.device, &self.g.queue, t, bytes);
+ true
+ }
+
/// Kernel records and the TLAS (a record's instance is `inst_base` + it).
- pub(super) fn records(&self, h: &mut Holes, extra: usize, instances: &mut wgpu::Buffer, accel: &mut gpu::Accel) -> bool {
+ pub(super) fn records(&self, h: &mut Holes, extra: usize, heap: &mut Heap<Table>, accel: &mut gpu::Accel) -> bool {
if !self.ok {
return false;
}
let cap = Self::cap(h, extra);
- if !self.fits(&[(cap * std::mem::size_of::<scene::GpuInstance>()) as u64]) {
+ if !self.table(heap, Table::Instances, (cap * std::mem::size_of::<scene::GpuInstance>()) as u64) {
return false;
}
- *instances = self.g.grown(instances, (cap * std::mem::size_of::<scene::GpuInstance>()) as u64, "instances");
self.g.grow_tlas(accel, accel.inst_base + cap);
h.cap = cap;
true
}
/// Object-table entries (`stride` vec4s each).
- pub(super) fn objects(&self, h: &mut Holes, extra: usize, objects: &mut wgpu::Buffer, stride: usize) -> bool {
+ pub(super) fn objects(&self, h: &mut Holes, extra: usize, heap: &mut Heap<Table>, stride: usize) -> bool {
if !self.ok {
return false;
}
let cap = Self::cap(h, extra);
- if !self.fits(&[(cap * stride * 16) as u64]) {
+ if !self.table(heap, Table::Objects, (cap * stride * 16) as u64) {
return false;
}
- *objects = self.g.grown(objects, (cap * stride * 16) as u64, "objects");
h.cap = cap;
true
}
- /// Procedural words, after the environment's CDF (`cdf_words` of them).
- pub(super) fn words(&self, cap: &mut usize, need: usize, cdf: &mut wgpu::Buffer, cdf_words: usize) -> bool {
+ /// The procedural region's words.
+ pub(super) fn words(&self, cap: &mut usize, need: usize, words: &mut Heap<Stream>) -> bool {
if !self.ok {
return false;
}
let new = (*cap * 2).max(need);
- if !self.fits(&[((cdf_words + new) * 4) as u64]) {
+ if !self.fits(&[words.size_with(Stream::Procs, (new * 4) as u64)]) {
return false;
}
*cap = new;
- *cdf = self.g.grown(cdf, ((cdf_words + *cap) * 4) as u64, "env_cdf + procedural");
+ words.grow(&self.g.device, &self.g.queue, Stream::Procs, (new * 4) as u64);
true
}
}
@@ -484,7 +502,7 @@ impl LiveCore {
catch_up.put(i as u64 * size, bytemuck::bytes_of(r));
}
}
- catch_up.flush(&self.g.queue, &self.sc.up.instances);
+ catch_up.flush_section(&self.g.queue, &self.sc.up.heap, Table::Instances);
}
if rigid_ok && (dynamic.is_empty() || (!changes.structural && self.repose(world, &dynamic)?)) {
// A new shared pose and nothing else that rebuilds the TLAS (no move): rebuild it for the meshes' new bounds.
@@ -537,10 +555,10 @@ impl LiveCore {
if d.lights_moved {
e.regroup_lights();
}
- q.write_buffer(&up.lights, 0, bytemuck::cast_slice(&crate::lights_with_groups(&e.lights)));
+ up.put_lights(q, &e.lights);
}
if d.objects {
- q.write_buffer(&up.objects, 0, bytemuck::cast_slice(&e.objects));
+ up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&e.objects));
}
if d.materials || d.emitters {
self.add_material_emitters();
@@ -604,7 +622,7 @@ impl LiveCore {
for &i in idx {
e.lights[i] = gl;
}
- self.g.queue.write_buffer(&self.sc.up.lights, 0, bytemuck::cast_slice(&crate::lights_with_groups(&e.lights)));
+ self.sc.up.put_lights(&self.g.queue, &e.lights);
}
}
}
@@ -688,7 +706,7 @@ impl LiveCore {
if merged {
(lo, hi) = (lo.min(i as usize), hi.max(i as usize));
} else {
- q.write_buffer(&self.sc.up.instances, i as u64 * size, bytemuck::bytes_of(&r));
+ self.sc.up.heap.write(q, Table::Instances, i as u64 * size, bytemuck::bytes_of(&r));
}
let pivot = w.transform_point3(glam::Vec3::ZERO);
let st = self.sc.tables.stride;
@@ -699,9 +717,9 @@ impl LiveCore {
self.inst_moving.push(i);
}
if merged {
- q.write_buffer(&self.sc.up.instances, lo as u64 * size, bytemuck::cast_slice(&self.sc.gpu_instances[lo..=hi]));
+ self.sc.up.heap.write(q, Table::Instances, lo as u64 * size, bytemuck::cast_slice(&self.sc.gpu_instances[lo..=hi]));
}
- q.write_buffer(&self.sc.up.objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
+ self.sc.up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
self.inst_moved = true;
match top {
gpu::Top::Hw(accel) => {
@@ -718,16 +736,15 @@ impl LiveCore {
}
}
- /// The material table to the GPU: written in place, or, with more materials than its buffer holds (materials added
- /// while the game runs), into a buffer twice the size, the scene's bind group made over it.
+ /// The material table to the GPU: written in place; with more materials than its section holds (materials added
+ /// while the game runs), the section is made twice the size first and the scene's bind groups made again.
pub(super) fn upload_materials(&mut self) {
let bytes: &[u8] = bytemuck::cast_slice(&self.sc.tables.materials);
- if bytes.len() as u64 > self.sc.up.materials.size() {
- let usage = self.sc.up.materials.usage();
- self.sc.up.materials = self.g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("materials"), size: (bytes.len() as u64 * 2).next_multiple_of(16), usage, mapped_at_creation: false });
+ if bytes.len() as u64 > self.sc.up.heap.cap(Table::Materials) {
+ self.sc.up.heap.grow(&self.g.device, &self.g.queue, Table::Materials, bytes.len() as u64 * 2);
self.g.rebind_scene(&mut self.sc.up);
}
- self.g.queue.write_buffer(&self.sc.up.materials, 0, bytes);
+ self.sc.up.heap.write(&self.g.queue, Table::Materials, 0, bytes);
}
/// The record of a mesh an edit added in place that moves as an instance does (`move_instances`): one a rigid body
@@ -846,36 +863,34 @@ impl LiveCore {
}
}
- /// The emitter CDF `em` (its total weight and the emitters' power), then the light tree's nodes, into the emitters
- /// buffer (grown, and the scene bind group made again, when they no longer fit), and the kernel's parameters.
+ /// The emitter CDF `em` (its total weight and the emitters' power) and the light tree's nodes into their tables
+ /// (grown, and the scene's bind groups made again, when they no longer fit), and the kernel's parameters.
pub(super) fn put_emitters(&mut self, em: &[[f32; 4]], total: f32, power: f32) {
let g = &self.g;
let LoadedScene { tables: e, base: b, up, .. } = &mut self.sc;
let nodes: &[[f32; 4]] = e.light_tree.as_ref().map_or(&[], |t| &t.nodes);
- let need = ((em.len() + nodes.len()) * 16) as u64;
- if need > up.emitters.size() {
- // (The usage it was made with: the merged layout copies the tables each frame, `Gpu::sync_tables`.)
- let usage = up.emitters.usage();
- up.emitters = g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("emitters"), size: need + need / 2, usage, mapped_at_creation: false });
- g.rebind_scene(up);
- }
- if !em.is_empty() {
- g.queue.write_buffer(&up.emitters, 0, bytemuck::cast_slice(em));
+ let mut grew = false;
+ for (t, data) in [(Table::Emitters, em), (Table::LightTree, nodes)] {
+ let need = (data.len() * 16) as u64;
+ if need > up.heap.cap(t) {
+ up.heap.grow(&g.device, &g.queue, t, need + need / 2);
+ grew = true;
+ }
+ up.heap.write(&g.queue, t, 0, bytemuck::cast_slice(data));
}
- if let Some(t) = e.light_tree.as_ref() {
- g.queue.write_buffer(&up.emitters, em.len() as u64 * 16, bytemuck::cast_slice(&t.nodes));
+ if grew {
+ g.rebind_scene(up);
}
let _ = b;
- self.emitter_params(em.len(), total, power);
+ self.emitter_params(total, power);
}
- /// The kernel's emitter parameters for a CDF of `entries` (its total weight; the emitters' power) and the tree.
- pub(super) fn emitter_params(&mut self, entries: usize, total: f32, power: f32) {
+ /// The kernel's emitter parameters for a CDF of this total weight (and the emitters' power) and the tree.
+ pub(super) fn emitter_params(&mut self, total: f32, power: f32) {
let LoadedScene { tables: e, base: b, .. } = &mut self.sc;
b.emit_power[0] = power;
b.misc[1] = total;
if let Some(t) = e.light_tree.as_ref() {
- b.ltree[0] = f32::from_bits(entries as u32);
// The tree's entries (with the slot: the static ones and those added in place), the rest by power share.
if t.dynamic.is_some() {
b.ltree[1] = f32::from_bits(t.order.len() as u32);
@@ -905,7 +920,7 @@ impl LiveCore {
e.put_powers(&powers);
self.sc.emit = None;
e.defer_powers = false;
- self.g.queue.write_buffer(&self.sc.up.objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
+ self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
self.write_emitters();
return;
}
@@ -929,18 +944,23 @@ impl LiveCore {
let Some(powers) = self.sc.emit.as_mut().and_then(|w| w.flight.take()) else { return };
let e = &mut self.sc.tables;
e.put_powers(&powers);
- self.g.queue.write_buffer(&self.sc.up.objects, 0, bytemuck::cast_slice(&e.objects));
+ self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&e.objects));
if let Some(t) = e.light_tree.as_mut() {
for (n, &p) in t.nodes.iter_mut().zip(&r.node_powers) {
n[2] = p;
}
t.power = t.nodes.first().map_or(0.0, |n| n[2]);
}
- // (Same entries and nodes as the CDF the scene was loaded with: the buffer holds them.)
+ // (Same entries and nodes as the CDF the scene was loaded with: their tables hold them.)
let mut enc = self.g.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("emitters") });
- enc.copy_buffer_to_buffer(&r.staging, 0, &self.sc.up.emitters, 0, r.bytes.min(self.sc.up.emitters.size()));
+ let (heap, cdf) = (&self.sc.up.heap, r.entries as u64 * 16);
+ for (t, from, bytes) in [(Table::Emitters, 0, cdf), (Table::LightTree, cdf, r.bytes - cdf)] {
+ if bytes > 0 {
+ enc.copy_buffer_to_buffer(&r.staging, from, &heap.buffer, heap.at(t), bytes.min(heap.cap(t)));
+ }
+ }
self.g.queue.submit([enc.finish()]);
- self.emitter_params(r.entries, r.total, r.power);
+ self.emitter_params(r.total, r.power);
self.lit_changed = self.frame.max(1);
}
@@ -957,7 +977,7 @@ impl LiveCore {
powers.append(&mut e.deferred);
if !powers.is_empty() {
e.put_powers(&powers);
- self.g.queue.write_buffer(&self.sc.up.objects, 0, bytemuck::cast_slice(&e.objects));
+ self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&e.objects));
// The lighting changed (as when a result lands): `live_lighting` for the next 45 frames.
self.lit_changed = self.frame.max(1);
}
@@ -1030,10 +1050,10 @@ impl LiveCore {
top.moved(slot0 + i, wm, Some((n.cast_shadow, hidden)));
}
let q = &self.g.queue;
- q.write_buffer(&sc.up.instances, (rec0 * size) as u64, bytemuck::cast_slice(&sc.gpu_instances[rec0..rec0 + cap]));
+ sc.up.heap.write(q, Table::Instances, (rec0 * size) as u64, bytemuck::cast_slice(&sc.gpu_instances[rec0..rec0 + cap]));
let st = sc.tables.stride;
let at = place.object as usize * st;
- q.write_buffer(&sc.up.objects, (at * 16) as u64, bytemuck::cast_slice(&sc.tables.objects[at..at + cap * st]));
+ sc.up.heap.write(q, Table::Objects, (at * 16) as u64, bytemuck::cast_slice(&sc.tables.objects[at..at + cap * st]));
self.inst_moving.extend(rec0 as u32..(rec0 + cap) as u32);
sc.tables.retained.instanced.get_mut(&id).unwrap().drawn = t.count;
done += 1;
@@ -1069,7 +1089,7 @@ impl LiveCore {
let mut r = p.gpu(old.info[0]);
r.p = old.m;
self.sc.gpu_instances[i] = r;
- self.g.queue.write_buffer(&self.sc.up.instances, i as u64 * size, bytemuck::bytes_of(&r));
+ self.sc.up.heap.write(&self.g.queue, Table::Instances, i as u64 * size, bytemuck::bytes_of(&r));
let pivot = w.transform_point3(glam::Vec3::ZERO);
let st = self.sc.tables.stride;
let o = &mut self.sc.tables.objects[p.object as usize * st];
@@ -1081,7 +1101,7 @@ impl LiveCore {
}
self.inst_moving.push(i as u32);
}
- self.g.queue.write_buffer(&self.sc.up.objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
+ self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
if let (true, Some(accel)) = (build_tlas, self.sc.up.accel.as_ref()) {
let mut e = self.g.device.create_command_encoder(&Default::default());
self.g.rebuild_tlas(accel, &mut e);
@@ -1158,10 +1178,10 @@ impl LiveCore {
}
// A model's node instances are contiguous: one write.
if ilo < ihi {
- self.g.queue.write_buffer(&self.sc.up.instances, ilo as u64 * size, bytemuck::cast_slice(&self.sc.gpu_instances[ilo..ihi]));
+ self.sc.up.heap.write(&self.g.queue, Table::Instances, ilo as u64 * size, bytemuck::cast_slice(&self.sc.gpu_instances[ilo..ihi]));
}
self.inst_moved = true;
- self.g.queue.write_buffer(&self.sc.up.objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
+ self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
if lo < hi {
// Motion vectors of the flattened triangles: the previous frame's vertices, as `repose` keeps them.
let both = self.prev_span.map_or((lo, hi), |(a, b)| (a.min(lo), b.max(hi)));
@@ -1321,7 +1341,7 @@ impl LiveCore {
q.write_buffer(&up.verts, k * 48, bytemuck::cast_slice(&verts[lo * 3..hi * 3]));
q.write_buffer(&up.attrs, k * 96, bytemuck::cast_slice(&attrs[lo..hi]));
q.write_buffer(&accel.verts, k * 36, bytemuck::cast_slice(&blas[lo * 3..hi * 3]));
- q.write_buffer(&up.objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
+ up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
let mut e = self.g.device.create_command_encoder(&Default::default());
self.g.rebuild_dynamic(accel, &mut e);
let profile_blas = std::env::var("THREERT_PROFILE_BLAS").is_ok_and(|v| v == "1");
@@ -1348,10 +1368,10 @@ impl LiveCore {
let r = (tris[k].tri as usize - first) * 3;
crate::ltree::tri_vertices(&verts[r..r + 3])
});
- let (q, up, off) = (&self.g.queue, &self.sc.up, self.sc.base.ltree[0].to_bits() as u64);
- q.write_buffer(&up.emitters, off * 16, bytemuck::cast_slice(&t.nodes[..1]));
- q.write_buffer(&up.emitters, (off + 2) * 16, bytemuck::cast_slice(&t.nodes[2..3]));
- q.write_buffer(&up.emitters, (off + t.moving_nodes as u64) * 16, bytemuck::cast_slice(&t.nodes[t.moving_nodes..]));
+ let (q, heap) = (&self.g.queue, &self.sc.up.heap);
+ heap.write(q, Table::LightTree, 0, bytemuck::cast_slice(&t.nodes[..1]));
+ heap.write(q, Table::LightTree, 2 * 16, bytemuck::cast_slice(&t.nodes[2..3]));
+ heap.write(q, Table::LightTree, t.moving_nodes as u64 * 16, bytemuck::cast_slice(&t.nodes[t.moving_nodes..]));
}
/// Copies the GPU's current vertices of a dynamic-tail span into `prev_verts` (submitted before any write queued
@@ -1589,9 +1609,9 @@ impl LiveCore {
let mut pending_procs = vec![];
let mut split = EditSplit::default();
let (mut w_cdf, mut w_verts, mut w_attrs, mut w_blas, mut w_records, mut w_objects) = (Gather::default(), Gather::default(), Gather::default(), Gather::default(), Gather::default(), Gather::default());
- // Vertex colours (F_VCOLOR), in `prev_verts` after the previous vertices.
+ // Vertex colours (F_VCOLOR).
let mut w_colors = Gather::default();
- let vcolor_base = up.vcolor_base;
+ let vcolors = up.vcolors;
// (geometry, material) -> the mesh built in this batch (objects sharing a replaced geometry share it again).
let mut fresh: std::collections::HashMap<(u32, u32), u32> = Default::default();
let mask = |shadow: bool| if shadow { 1 } else { 2 };
@@ -1621,7 +1641,7 @@ impl LiveCore {
Some(&k) => k as usize,
None => match edit.objects.take(1) {
Some(k) => k,
- None if grow.objects(&mut edit.objects, 1, &mut up.objects, tables.stride) => {
+ None if grow.objects(&mut edit.objects, 1, &mut up.heap, tables.stride) => {
edit.grows += 1;
edit.rebind = true;
edit.objects.take(1).ok_or("edit room: objects")?
@@ -1654,7 +1674,7 @@ impl LiveCore {
if used <= edit.word_cap {
return true;
}
- let ok = grow.words(&mut edit.word_cap, used, &mut up.cdf, up.cdf_words);
+ let ok = grow.words(&mut edit.word_cap, used, &mut up.words);
if ok {
edit.grows += 1;
edit.rebind = true;
@@ -1668,7 +1688,7 @@ impl LiveCore {
if !words_left(w + p.blob.boxes.len() + p.blob.data.len(), edit) {
return Err("edit room: procedural words".into());
}
- let at = |word: usize| ((up.cdf_words + word) * 4) as u64;
+ let at = |word: usize| (word * 4) as u64;
w_cdf.put(at(w), bytemuck::cast_slice(&p.blob.boxes));
w_cdf.put(at(w + p.blob.boxes.len()), bytemuck::cast_slice(&p.blob.data));
edit.word += p.blob.boxes.len() + p.blob.data.len();
@@ -1681,7 +1701,7 @@ impl LiveCore {
if !words_left(header + words.len(), edit) {
return Err("edit room: procedural words".into());
}
- w_cdf.put(((up.cdf_words + header) * 4) as u64, bytemuck::cast_slice(&words));
+ w_cdf.put((header * 4) as u64, bytemuck::cast_slice(&words));
edit.word += words.len();
let blas = g.proc_blas(&p.blob, &mut pending_procs, &mut fresh_blases);
let entry = p.object_entry(o);
@@ -1756,7 +1776,7 @@ impl LiveCore {
return Err("the scene's first cutout (kernel feature)".into());
}
let colored = world.materials.get(material).is_some_and(|m| m.vertex_colors) && world.geometries.get(geometry).is_some_and(|g| !g.colors.is_empty());
- if colored && vcolor_base.is_none() {
+ if colored && !vcolors {
return Err("the scene's first vertex colours (kernel feature)".into());
}
let key = if emits { (u32::MAX - id, mat) } else { (*geometry, mat) };
@@ -1815,7 +1835,7 @@ impl LiveCore {
let first = match edit.tris.take(t.len()) {
Some(f) => f,
// (Software traversal's room does not grow: the rebuild makes a larger one.)
- None if match &mut top { gpu::Top::Hw(accel) => grow.tris(&mut edit.tris, t.len(), &mut up.verts, &mut up.attrs, &mut up.prev_verts, vcolor_base, accel), gpu::Top::Sw(_) => false } => {
+ None if match &mut top { gpu::Top::Hw(accel) => grow.tris(&mut edit.tris, t.len(), &mut up.verts, &mut up.attrs, &mut up.words, vcolors, accel), gpu::Top::Sw(_) => false } => {
edit.grows += 1;
edit.rebind = true;
edit.tris.take(t.len()).ok_or("edit room: triangles")?
@@ -1868,13 +1888,13 @@ impl LiveCore {
if !top.sw() {
w_blas.put((first * 36) as u64, bytemuck::cast_slice(&blas_verts));
}
- if let Some(base) = vcolor_base {
+ if vcolors {
// White where it has none: the room's slots may hold an earlier mesh's.
let mut c = if colored { scene::tri_colors(geo, false, None) } else { vec![scene::WHITE; t.len()] };
if let (Some(tree), true) = (&tree, colored) {
c = tree.order.iter().map(|&i| c[i as usize]).collect();
}
- w_colors.put(base + (first * 12) as u64, bytemuck::cast_slice(&c));
+ w_colors.put((first * 12) as u64, bytemuck::cast_slice(&c));
}
split.upload += t2.elapsed().as_secs_f64() * 1e3;
let rel = first - edit.pool_first;
@@ -1934,7 +1954,7 @@ impl LiveCore {
}
let r0 = match edit.records.take(cap) {
Some(r) => r,
- None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, cap, &mut up.instances, accel), gpu::Top::Sw(_) => false } => {
+ None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, cap, &mut up.heap, accel), gpu::Top::Sw(_) => false } => {
edit.grows += 1;
edit.rebind = true;
edit.records.take(cap).ok_or("edit room: records")?
@@ -1943,7 +1963,7 @@ impl LiveCore {
};
let o0 = match edit.objects.take(cap) {
Some(k) => k,
- None if grow.objects(&mut edit.objects, cap, &mut up.objects, tables.stride) => {
+ None if grow.objects(&mut edit.objects, cap, &mut up.heap, tables.stride) => {
edit.grows += 1;
edit.rebind = true;
edit.objects.take(cap).ok_or("edit room: objects")?
@@ -2002,7 +2022,7 @@ impl LiveCore {
_ => {
let r = match edit.records.take(1) {
Some(r) => r,
- None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, 1, &mut up.instances, accel), gpu::Top::Sw(_) => false } => {
+ None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, 1, &mut up.heap, accel), gpu::Top::Sw(_) => false } => {
edit.grows += 1;
edit.rebind = true;
edit.records.take(1).ok_or("edit room: records")?
@@ -2035,15 +2055,15 @@ impl LiveCore {
}
// The gathered writes, merged, before the builds that read them.
let tw = Instant::now();
- w_cdf.flush(q, &up.cdf);
+ w_cdf.flush_section(q, &up.words, Stream::Procs);
w_verts.flush(q, &up.verts);
w_attrs.flush(q, &up.attrs);
if let gpu::Top::Hw(accel) = &top {
w_blas.flush(q, &accel.verts);
}
- w_colors.flush(q, &up.prev_verts);
- w_records.flush(q, &up.instances);
- w_objects.flush(q, &up.objects);
+ w_colors.flush_section(q, &up.words, Stream::VertexColors);
+ w_records.flush_section(q, &up.heap, Table::Instances);
+ w_objects.flush_section(q, &up.heap, Table::Objects);
split.upload += tw.elapsed().as_secs_f64() * 1e3;
let t3 = Instant::now();
new_meshes.sort_unstable();
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index f2ae0f0..0affeef 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -241,7 +241,7 @@ impl LiveCore {
self.land_powers_now();
let (e, b) = (&self.sc.tables, &mut self.sc.base);
let (em, total, power) = crate::emitter_cdf(&e.emitter_tris, &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b));
- self.g.queue.write_buffer(&self.sc.up.emitters, 0, bytemuck::cast_slice(&em));
+ self.sc.up.heap.write(&self.g.queue, Table::Emitters, 0, bytemuck::cast_slice(&em));
b.misc[1] = total;
b.emit_power[0] = power;
}
@@ -334,7 +334,7 @@ impl LiveCore {
for i in std::mem::take(&mut self.inst_moving) {
let r = &mut self.sc.gpu_instances[i as usize];
r.p = r.m;
- self.g.queue.write_buffer(&self.sc.up.instances, i as u64 * size, bytemuck::bytes_of(r));
+ self.sc.up.heap.write(&self.g.queue, Table::Instances, i as u64 * size, bytemuck::bytes_of(r));
}
}
self.inst_moved = false;
@@ -394,6 +394,7 @@ impl LiveCore {
p.misc[3] = k as f32;
p.counts[2] = p.counts[2].min(self.bounces);
p.counts[3] = p.counts[3].min(2);
+ self.sc.up.place(&mut p);
g.queue.write_buffer(&self.sc.up.params, 0, bytemuck::bytes_of(&p));
let mut e = g.device.create_command_encoder(&Default::default());
// Particles: placed for this frame's time and camera, then the dynamic BLASes rebuilt (before the raster and
@@ -431,8 +432,8 @@ impl LiveCore {
let blas_ts = self.profile.as_ref().map(|p| (&p.queries, n * 2 + 2));
g.run_particles(&self.sc.up, cam.pos.to_array(), cam.fwd.to_array(), shader_time(self.time), self.frame_dt, b.time[2], b.time[1], &mut e, pass_ts, blas_ts);
}
- // (The merged layout and the uniform tables: the tables as this frame's edits and the particle passes above
- // left them, where the kernel reads them; merged.rs.)
+ // (The uniform tables: their sections as this frame's edits and the particle passes above left them, where
+ // the kernel reads them; merged.rs.)
if k == 0 {
g.sync_tables(&self.sc.up, &mut e);
}
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 1b2c862..373fc84 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -229,7 +229,8 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
tables.defer_powers = emit.is_some();
let (mat_runs, tri_order) = (std::mem::take(&mut prep.mat_runs), std::mem::take(&mut prep.tri_order));
let fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty(), prep.groups);
- let mut up = g.upload(&sc, w, h, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;
+ // (The light tree is the tables' by now: its nodes from there.)
+ let mut up = g.upload(&sc, w, h, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;
// The merged layout: the kernel written for this view's group-1 buffers (merged.rs).
if let (Some(caps), Some((_, live))) = (&mut up.kernel.caps, &targets.kernel.merged) {
caps.live = *live;
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 962ee43..9a67846 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -29,6 +29,7 @@
//! live passes, the caches' training, the GPU timing); `session` the headless runner (native only).
use crate::gpu::Buf;
+use crate::heap::{Heap, Section, Stream, Table};
use crate::world::World;
use crate::{gpu, post, scene, tables};
// (The headless runner, `session`, native only, is what uses all of it.)
@@ -578,7 +579,7 @@ impl LiveCore {
});
}
let Some(a) = up.accel.as_ref() else { return serde_json::Value::Null };
- let buffers = [&up.verts, &up.attrs, &up.prev_verts, &up.instances, &up.objects, &up.cdf, &up.emitters, &a.verts].iter().map(|b| b.size()).sum::<u64>();
+ let buffers = [&up.verts, &up.attrs, &up.prev_verts, &up.heap.buffer, &up.words.buffer, &a.verts].iter().map(|b| b.size()).sum::<u64>();
let live: u64 = self.sc.meshes.iter().enumerate().filter(|(k, _)| e.users.get(&(*k as u32)).copied().unwrap_or(0) > 0).map(|(_, m)| m.count as u64).sum::<u64>() + e.pool_first as u64;
let mb = |b: f64| (b / (1 << 20) as f64 * 10.0).round() / 10.0;
serde_json::json!({
@@ -1228,7 +1229,7 @@ mod instanced_tests {
let mut sc = crate::scene::build(&w, Path::new("."), &presets, None).unwrap();
(sc.width, sc.height) = (64, 36);
let prep = crate::prepare(g, &mut sc, &mut vec![]);
- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();
+ let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();
frame.color.iter().flatten().map(|v| v.to_bits()).collect::<Vec<u32>>()
};
let (a, b) = (offline(&plain), offline(&uniform));
@@ -1241,24 +1242,24 @@ mod instanced_tests {
// Live: the uniform buffers follow the tables.
let mut core = LiveCore::new(uniform, &w, Path::new("."), &presets, 64, 36).unwrap();
w.take_changes();
- let read = |core: &LiveCore, buf: &wgpu::Buffer, bytes: u64| -> Vec<u8> {
+ let read = |core: &LiveCore, buf: &wgpu::Buffer, at: u64, bytes: u64| -> Vec<u8> {
let d = &core.g.device;
let to = d.create_buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let mut e = d.create_command_encoder(&Default::default());
- e.copy_buffer_to_buffer(buf, 0, &to, 0, bytes);
+ e.copy_buffer_to_buffer(buf, at, &to, 0, bytes);
core.g.queue.submit([e.finish()]);
to.slice(..).map_async(wgpu::MapMode::Read, |_| {});
d.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let bytes = to.slice(..).get_mapped_range().unwrap().to_vec();
bytes
};
- // Each table's bytes and its uniform copy's, over what both hold.
+ // Each table's section and its uniform copy, over what both hold.
let pairs = |core: &LiveCore| -> Vec<(Vec<u8>, Vec<u8>)> {
let up = &core.sc.up;
let copies = up.uniform.as_ref().expect("the uniform tables' buffers");
- [&up.bg_parts.texinfo, &up.objects, &up.instances, &up.media].into_iter().zip(copies).map(|(t, c)| {
- let n = t.size().min(c.size()) & !3;
- (read(core, t, n), read(core, c, n))
+ crate::merged::UNIFORM_TABLES.iter().zip(copies).map(|(t, c)| {
+ let n = up.heap.cap(t.table).min(c.size()) & !3;
+ (read(core, &up.heap.buffer, up.heap.at(t.table), n), read(core, c, 0, n))
}).collect()
};
core.render(1, |_, _| {});
diff --git a/renderer/src/ltree.rs b/renderer/src/ltree.rs
index c8366c3..c8d336e 100644
--- a/renderer/src/ltree.rs
+++ b/renderer/src/ltree.rs
@@ -48,6 +48,11 @@ pub fn live_candidates() -> u32 {
std::env::var("THREERT_LT_RIS").ok().and_then(|v| v.parse().ok()).unwrap_or(RIS_LIVE).max(1)
}
+/// A scene's tree as the kernel reads it: its nodes (none without a tree).
+pub fn nodes_of(tree: Option<&LightTree>) -> &[[f32; 4]] {
+ tree.map_or(&[], |t| &t.nodes)
+}
+
/// Node child word: internal nodes hold their left child (the right one follows it); leaves LEAF | (count - 1) << 29 |
/// their first entry.
pub const LEAF: u32 = 0x8000_0000;
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index 676b701..be832dc 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -472,7 +472,7 @@ fn render(g: &gpu::Gpu, job: &Job, presets: &Path, init_ms: f64, hosts: &mut Hos
if job.signals.is_some() {
params.motion[1] = 1.0;
}
- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.env, &prep.env_cdf, &prep.energy, params, spp, &mut timings)?;
+ let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, threert_render::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, params, spp, &mut timings)?;
if let Some(prefix) = &job.signals {
// The raw (undenoised) means: diffuse = color less specular and emission.
let diffuse: Vec<f32> = frame.color.iter().zip(&frame.specular).zip(&frame.emission).flat_map(|((c, s), e)| [0, 1, 2].map(|k| (c[k] - s[k] - e[k]).max(0.0))).collect();
diff --git a/renderer/src/merged.rs b/renderer/src/merged.rs
index 3f3723c..218dba9 100644
--- a/renderer/src/merged.rs
+++ b/renderer/src/merged.rs
@@ -1,20 +1,19 @@
//! The merged binding layout: the kernel with at most eight storage buffers a stage, WebGPU's default limit
-//! (`maxStorageBuffersPerShaderStage`). The kernel binds 19 as it is written: more than a browser gives a page. (The
-//! live passes need none of this: each binds at most eight, live/layout.rs, and a page binds them as they are.)
+//! (`maxStorageBuffersPerShaderStage`). The kernel binds 20 as it is written: more than a browser gives a page.
+//! (The live passes need none of this: each binds at most eight, live/layout.rs, and a page binds them as they are.)
//!
-//! The kernel's source has both layouts: pathtrace.wgsl declares its tables and its group-1 buffers in an
+//! The kernel's source has both layouts: pathtrace.wgsl declares its tables' views and its group-1 buffers in an
//! `@if(merged) { .. } @else { .. }` block each (WESL's conditional translation, `gpu::KernelVariant`), and reads and
//! writes them only through functions declared in each (`material_at`, `cache_acc_add`, `refl_store`, ...). This
-//! module is the Rust side's half: which buffers are merged, the lengths of the merged structs' arrays (WESL constants
-//! the source imports, `gpu::KernelVariant::constants`) and where the arrays are, for the buffers the renderer makes
-//! and copies. `THREERT_MERGED=1` runs the same layout natively (software traversal), so the tests that check the
-//! renderer check it too (docs/RUNTIME.md "The engine in a browser").
+//! module is the Rust side's half: which views a layout binds, the lengths of the merged struct's arrays (WESL
+//! constants the source imports, `gpu::KernelVariant::constants`) and where the arrays are, for the buffer the
+//! renderer makes. `THREERT_MERGED=1` runs the same layout natively (software traversal), so the tests that check
+//! the renderer check it too (docs/RUNTIME.md "The engine in a browser").
//!
//! What is merged:
-//! - The kernel's seven tables (`TABLES`: materials, lights, emitters, texture pages, objects, instances, media)
-//! become the arrays of one struct, `MT: MergedTables`, in one buffer. Their lengths are each a power of two no
-//! less than `TABLE_MIN`, so a scene that grows compiles a kernel again only when a table doubles. The renderer
-//! keeps writing its own buffers; each frame copies them into the struct's (`Gpu::sync_tables`; they are small).
+//! - The scene's tables are the sections of one buffer in every layout (heap.rs). As written the kernel binds the
+//! seven it reads at every hit or light again, each section as a typed array (`TABLE_VIEWS`); here it binds none
+//! of them and reads all seven from the buffer whole.
//! - The kernel's six group-1 buffers (`KERNEL_LIVE`: the radiance cache, what the live passes read of a trace) and
//! the loop guard's count become the arrays of `ML: MergedLive`, one buffer that they are ranges of
//! (`gpu::KernelBufs`). What the live passes read of it starts at a multiple of 256 bytes (`@align(256)`): the
@@ -22,7 +21,9 @@
//! `minStorageBufferOffsetAlignment`).
//!
//! The tests below read every variant with naga: valid WGSL, no stage with more than `STORAGE_BUFFERS`, and the
-//! structs' arrays where `offsets` and `live_layout` put them.
+//! struct's arrays where `live_layout` puts them.
+
+use crate::heap::Table;
/// WebGPU's default `maxStorageBuffersPerShaderStage`: what the merged layout fits.
pub const STORAGE_BUFFERS: u32 = 8;
@@ -36,19 +37,9 @@ pub struct Member {
pub align: u64,
}
-/// The kernel's tables, in `MergedTables`' order (group 0, binding `TABLES_BINDING`).
-pub const TABLES: [Member; 7] = [
- Member { name: "materials", stride: 288, align: 16 },
- Member { name: "lights", stride: 80, align: 16 },
- Member { name: "emitters", stride: 16, align: 16 },
- Member { name: "tex_info", stride: 16, align: 16 },
- Member { name: "objects", stride: 16, align: 16 },
- Member { name: "instances", stride: 160, align: 16 },
- Member { name: "media", stride: 224, align: 16 },
-];
-pub const TABLES_BINDING: u32 = 4;
-/// The least length of each table's array: scenes below it share one kernel source.
-pub const TABLE_MIN: [u32; 7] = [64, 64, 1024, 256, 1024, 64, 16];
+/// The tables the kernel as written binds again as typed arrays over their sections, and their bindings (group 0;
+/// pathtrace.wgsl `materials`, `lights`, `emitters`, `tex_info`, `objects`, `instances`, `media`).
+pub const TABLE_VIEWS: [(Table, u32); 7] = [(Table::Materials, 12), (Table::Lights, 13), (Table::Emitters, 14), (Table::TexInfo, 15), (Table::Objects, 16), (Table::Instances, 17), (Table::Media, 18)];
/// The kernel's group-1 buffers, in `MergedLive`'s order (group 1, binding `KERNEL_LIVE_BINDING`).
pub const KERNEL_LIVE: [Member; 6] = [
@@ -82,60 +73,49 @@ pub fn live_layout(caps: &[u32; 6]) -> (Vec<u64>, u64) {
(out, at.next_multiple_of(members.iter().map(|m| m.align).max().unwrap_or(16)))
}
-/// The lengths of the merged structs' arrays: what a kernel's source is written for (`gpu::Kernel::caps`).
+/// The lengths of the merged struct's arrays: what a kernel's source is written for (`gpu::Kernel::caps`).
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Caps {
- pub tables: [u32; 7],
pub live: [u32; 6],
}
-/// A table's array length for a buffer of `bytes`.
-pub fn table_cap(k: usize, bytes: u64) -> u32 {
- (bytes.div_ceil(TABLES[k].stride).max(1) as u32).next_power_of_two().max(TABLE_MIN[k])
-}
-
/// A group-1 buffer's array length: its own (the kernel reads some of them, `arrayLength`).
pub fn live_cap(k: usize, bytes: u64) -> u32 {
assert_eq!(bytes % KERNEL_LIVE[k].stride, 0, "merged layout: {} of {bytes} bytes", KERNEL_LIVE[k].name);
(bytes / KERNEL_LIVE[k].stride) as u32
}
-/// Where a merged struct's arrays are (bytes), and the struct's size: WGSL's layout rules.
-pub fn offsets(members: &[Member], caps: &[u32]) -> (Vec<u64>, u64) {
- let (mut at, mut out) = (0u64, vec![]);
- for (m, &c) in members.iter().zip(caps) {
- at = at.next_multiple_of(m.align);
- out.push(at);
- at += m.stride * c as u64;
- }
- (out, at.next_multiple_of(members.iter().map(|m| m.align).max().unwrap_or(1)))
-}
-
-/// The uniform tables (`gpu::GpuOptions::uniform_tables`; docs/RUNTIME.md "Android"): which of `TABLES` the kernel
-/// reads from uniform buffers instead of storage buffers, in the layout as written. Qualcomm's Adreno 740 driver
-/// (Vulkan, Android 13) gave the kernel other buffers' contents for these four: a model's textures came out as
-/// another table's numbers, instance records sent hits to the wrong triangles, an emissive object's power read as
-/// something else's and lit nothing. As uniform buffers they read right. They are the four of the kernel's read-only
-/// tables that are bounded (the others: below).
+/// The uniform tables (`gpu::GpuOptions::uniform_tables`; docs/RUNTIME.md "Android"): the tables the kernel reads
+/// from uniform buffers, copies of their sections, instead of from views of the sections. Qualcomm's Adreno 740 driver
+/// (Vulkan, Android 13) gave the kernel other buffers' contents for these four when each was a read-only storage
+/// buffer: a model's textures came out as another table's numbers, instance records sent hits to the wrong
+/// triangles, an emissive object's power read as something else's and lit nothing. As uniform buffers they read
+/// right. (Whether they read right as views of the tables' buffer, which no device has run yet, is not known:
+/// until one has, Android keeps the copies.)
///
/// In the kernel (pathtrace.wgsl, `@if(uniform_tables)`) the four are sized uniform arrays at their own bindings, and
/// every index into them is held to the array (`tex_info_at` and the others: `min(i, last)`). A scene with more
/// entries than an array holds reads the last one for the rest (the renderer says so when it uploads one,
/// `Gpu::upload`); nothing is read outside the buffer, which the kernel's unchecked indexing would otherwise do.
///
-/// The kernel's other storage buffers stay storage buffers, each for its reason:
-/// - `materials` (288 B each), `lights` (80 B): the device drew right with them as they are, and 64 KiB would hold
-/// 227 materials;
-/// - `emitters` (the emitter CDF and the light tree), `env_cdf` (the environment's CDF, then the procedural
-/// geometry's data), `tri_verts`, `attrs`, `nodes`, `prev_verts` (and the vertex colours after them): megabytes,
-/// which no uniform binding holds;
-/// - `accum` and group 1 (the radiance cache, the trace's outputs): written by the kernel.
-pub const UNIFORM_TABLES: [usize; 4] = [3, 4, 5, 6];
-/// Their arrays' lengths (a uniform buffer's array is sized): what 64 KiB hold, the size every device gives a uniform
+/// An array's length (a uniform buffer's array is sized) is what 64 KiB hold, the size every device gives a uniform
/// binding (WebGPU's `maxUniformBufferBindingSize`, Vulkan's least `maxUniformBufferRange` on the phones this is
/// for), and for the media what a scene may have (`scene::MAX_MEDIA`). In a scene's terms: 2,048 textures, 1,365
/// objects (1,024 with instance colours), 409 instance records, every medium.
-pub const UNIFORM_LEN: [u32; 4] = [4096, 4096, 409, 32];
+pub struct UniformTable {
+ pub table: Table,
+ /// Its array in the kernel, the array's binding (group 0) and length, and its element's bytes.
+ pub name: &'static str,
+ pub binding: u32,
+ pub len: u32,
+ pub stride: u64,
+}
+pub const UNIFORM_TABLES: [UniformTable; 4] = [
+ UniformTable { table: Table::TexInfo, name: "tex_info", binding: 15, len: 4096, stride: 16 },
+ UniformTable { table: Table::Objects, name: "objects", binding: 16, len: 4096, stride: 16 },
+ UniformTable { table: Table::Instances, name: "instances", binding: 17, len: 409, stride: 160 },
+ UniformTable { table: Table::Media, name: "media", binding: 18, len: 32, stride: 224 },
+];
#[cfg(test)]
mod tests {
@@ -151,7 +131,7 @@ mod tests {
fn caps() -> Caps {
// A cache of one entry, a view of 64 x 36: lengths that are not round.
let n = 64 * 36;
- Caps { tables: TABLE_MIN, live: [1, 8, 2, 2 * n, n, n] }
+ Caps { live: [1, 8, 2, 2 * n, n, n] }
}
fn parse(src: &str) -> (naga::Module, naga::valid::ModuleInfo) {
@@ -177,34 +157,32 @@ mod tests {
}
/// Kernel variants in the merged layout: valid WGSL, no entry point with more than eight storage buffers, none
- /// declared beyond them (a pipeline layout counts what is declared), and the merged structs' arrays where `offsets`
- /// and `live_layout` put them. The layout as written has 19. Because the merged block declares none of the
- /// buffers by their own names, a read or write of one past its accessor does not compile here (and naga says
- /// where), whatever the other layouts take.
+ /// declared beyond them (a pipeline layout counts what is declared), and the merged struct's arrays where
+ /// `live_layout` puts them. The layout as written has 20. Because the merged blocks declare none of the views
+ /// or of group 1's buffers by their own names, a read or write of one past its accessor does not compile here
+ /// (and naga says where), whatever the other layouts take.
#[test]
fn the_merged_kernel_fits_eight_storage_buffers() {
let (m, info) = parse(&variant(0, None));
let (used, declared) = storage_buffers(&m, &info);
- assert_eq!(declared, 19, "the kernel as written");
- assert_eq!(used.iter().map(|u| u.1).max(), Some(19), "{used:?}");
+ assert_eq!(declared, 20, "the kernel as written");
+ assert_eq!(used.iter().map(|u| u.1).max(), Some(20), "{used:?}");
let caps = caps();
for features in [0, crate::gpu::F_VCOLOR, crate::gpu::F_GRID, crate::gpu::F_TINT | crate::gpu::F_UNLIT | crate::gpu::F_BACKGROUND, crate::gpu::F_SOURCE] {
let src = variant(features, Some(&caps));
- assert!(src.contains("const MT_MEDIA = 16u;") && src.contains(&format!("const ML_REFL = {}u;", caps.live[3])), "the lengths, as constants");
+ assert!(src.contains(&format!("const ML_REFL = {}u;", caps.live[3])), "the lengths, as constants");
let (m, info) = parse(&src);
let (used, declared) = storage_buffers(&m, &info);
assert!(declared as u32 <= STORAGE_BUFFERS, "features {features:#x}: {declared} declared");
assert!(used.iter().all(|u| u.1 as u32 <= STORAGE_BUFFERS), "features {features:#x}: {used:?}");
assert_eq!(used.iter().find(|u| u.0 == "main").map(|u| u.1), Some(8), "the trace reads all eight");
- assert_eq!(layout(&m, "MergedTables"), offsets(&TABLES, &caps.tables));
assert_eq!(layout(&m, "MergedLive"), live_layout(&caps.live));
}
}
/// Every kernel variant with the uniform tables: valid WGSL; the four tables are uniform buffers at their own
- /// bindings, sized as the Rust side makes their buffers; the other fifteen storage buffers are as written; and
- /// each of the four is indexed once, in its accessor, held to its array, so nothing is read outside a uniform
- /// buffer.
+ /// bindings, sized as the Rust side makes their buffers; the storage buffers are as written; and each of the
+ /// four is indexed once, in its accessor, held to its array, so nothing is read outside a uniform buffer.
#[test]
fn the_uniform_tables_are_four_sized_uniform_arrays() {
let globals = |m: &naga::Module, uniform: bool| -> Vec<(String, u32, u32)> {
@@ -228,15 +206,15 @@ mod tests {
for features in [0, crate::gpu::F_VCOLOR, crate::gpu::F_GRID, crate::gpu::F_TINT | crate::gpu::F_UNLIT | crate::gpu::F_BACKGROUND, crate::gpu::F_SOURCE] {
let src = kernel_wgsl(&kernel_template(), &KernelVariant { uniform_tables: true, ..KernelVariant::new(false, Default::default(), features) });
let (m, info) = parse(&src);
- assert_eq!(storage_buffers(&m, &info).1, 15, "features {features:#x}");
- let tables: Vec<(String, u32, u32)> = globals(&m, true).into_iter().filter(|g| g.0 != "P" && g.0 != "energy_lut").collect();
- let want: Vec<(String, u32, u32)> = UNIFORM_TABLES.iter().zip(UNIFORM_LEN).zip([14, 15, 17, 18]).map(|((&k, len), binding)| (TABLES[k].name.to_string(), binding, (TABLES[k].stride * len as u64) as u32)).collect();
+ assert_eq!(storage_buffers(&m, &info).1, 16, "features {features:#x}");
+ let tables: Vec<(String, u32, u32)> = globals(&m, true).into_iter().filter(|g| g.0 != "P").collect();
+ let want: Vec<(String, u32, u32)> = UNIFORM_TABLES.iter().map(|t| (t.name.to_string(), t.binding, (t.stride * t.len as u64) as u32)).collect();
assert_eq!(tables, want, "features {features:#x}");
// The storage buffers that stay: the same names at the same bindings as the kernel as written.
let kept = |m: &naga::Module| globals(m, false).into_iter().map(|g| (g.0, g.1)).filter(|g| !want.iter().any(|w| w.0 == g.0)).collect::<Vec<_>>();
assert_eq!(kept(&m), kept(&written), "features {features:#x}");
- for &k in &UNIFORM_TABLES {
- let name = TABLES[k].name;
+ for t in &UNIFORM_TABLES {
+ let name = t.name;
let upper = name.to_uppercase();
assert_eq!(src.matches(&format!("{name}[")).count(), 1, "{name}: indexed in its accessor only (features {features:#x})");
assert!(src.contains(&format!("{name}[min(i, UT_{upper} - 1u)]")), "{name}: held to its array");
@@ -244,15 +222,27 @@ mod tests {
}
}
- /// The Rust side's records are the size the merged structs give their elements.
+ /// The kernel reads a record from as many vec4s of the tables as the Rust side's record has, and makes of them
+ /// a struct of that size.
#[test]
- fn the_tables_strides_are_the_records() {
+ fn the_tables_records_are_the_kernels() {
use crate::scene::{GpuInstance, GpuLight, GpuMaterial, MediumGpu};
- let sizes = [std::mem::size_of::<GpuMaterial>(), std::mem::size_of::<GpuLight>(), 16, 16, 16, std::mem::size_of::<GpuInstance>(), std::mem::size_of::<MediumGpu>()];
- assert_eq!(TABLES.iter().map(|m| m.stride as usize).collect::<Vec<_>>(), sizes);
- assert_eq!(table_cap(0, 0), 64);
- assert_eq!(table_cap(0, 288 * 65), 128);
- assert_eq!(table_cap(2, 512), 1024);
+ let src = variant(0, Some(&caps()));
+ let (m, _) = parse(&src);
+ // (The views' bindings follow the buffer's, and are the kernel's.)
+ for (k, (table, binding)) in TABLE_VIEWS.iter().enumerate() {
+ let name = ["materials", "lights", "emitters", "tex_info", "objects", "instances", "media"][k];
+ assert!(kernel_template().contains(&format!("@group(0) @binding({binding}) var<storage, read> {name}: array<")), "{table:?}");
+ }
+ for (name, constant, bytes) in [("Material", "MATERIAL_VEC4", std::mem::size_of::<GpuMaterial>()), ("Light", "LIGHT_VEC4", std::mem::size_of::<GpuLight>()), ("Instance", "INSTANCE_VEC4", std::mem::size_of::<GpuInstance>()), ("Medium", "MEDIUM_VEC4", std::mem::size_of::<MediumGpu>())] {
+ assert!(kernel_template().contains(&format!("const {constant}: u32 = {}u;", bytes / 16)), "{constant}");
+ assert_eq!(layout(&m, name).1 as usize, bytes, "{name}");
+ }
+ assert_eq!(<Table as crate::heap::Section>::COUNT, Table::Energy as usize + 1);
+ // What the kernel reads with no offset is its heap's first section.
+ assert_eq!((Table::LightTree as usize, crate::heap::Stream::EnvCdf as usize), (0, 0));
+ assert!(kernel_template().contains("fn lt_node(i: u32) -> vec4<f32> { return table_f(i); }") && kernel_template().contains("fn env_cdf_at(i: u32) -> f32 { return bitcast<f32>(words[i]); }"));
+ assert!(<Table as crate::heap::Section>::COUNT <= 12, "`Params::table_first` names every table");
}
/// The loop guard opens every loop of the kernel but counted ones (`for (var i = N; i < M; i++)`, literals), the
@@ -281,7 +271,7 @@ mod tests {
let (m, info) = parse(&g);
let (used, declared) = storage_buffers(&m, &info);
// (As written: one buffer more, where the device has room. Merged: still eight.)
- assert_eq!(declared as u32, if merged.is_some() { STORAGE_BUFFERS } else { 20 }, "{used:?}");
+ assert_eq!(declared as u32, if merged.is_some() { STORAGE_BUFFERS } else { 21 }, "{used:?}");
}
// The pass on its own: nested loops, a `continuing` block, comments and braces in them, a loop in an `if`; a
// counted loop left alone, one bounded by a variable or assigning its counter guarded.
@@ -299,18 +289,18 @@ mod tests {
fn the_variant_gives_what_it_imports() {
let v = KernelVariant { merged: Some(caps()), guard: Some(9), ..KernelVariant::new(false, Default::default(), 0) };
let c = v.constants();
- assert_eq!(c.len(), 7 + 6 + 2);
- assert!(c.contains(&("MT_TEX_INFO".into(), TABLE_MIN[3])) && c.contains(&("ML_DIRECT_OUT".into(), 64 * 36)) && c.contains(&("LOOP_GUARD_LIMIT".into(), 9)) && c.contains(&("GUARD_WORDS".into(), GUARD_WORDS)));
+ assert_eq!(c.len(), 6 + 2);
+ assert!(c.contains(&("ML_DIRECT_OUT".into(), 64 * 36)) && c.contains(&("LOOP_GUARD_LIMIT".into(), 9)) && c.contains(&("GUARD_WORDS".into(), GUARD_WORDS)));
let u = KernelVariant { uniform_tables: true, ..KernelVariant::new(false, Default::default(), 0) }.constants();
assert_eq!(u, vec![("UT_TEX_INFO".into(), 4096), ("UT_OBJECTS".into(), 4096), ("UT_INSTANCES".into(), 409), ("UT_MEDIA".into(), 32)]);
assert!(KernelVariant::default().constants().is_empty());
}
#[test]
- #[should_panic(expected = "MT_MEDIA")]
+ #[should_panic(expected = "ML_REFL")]
fn a_constant_the_source_imports_must_be_given() {
let mut c = KernelVariant { merged: Some(caps()), ..KernelVariant::new(false, Default::default(), 0) }.constants();
- c.retain(|(n, _)| n != "MT_MEDIA");
+ c.retain(|(n, _)| n != "ML_REFL");
crate::gpu::wesl_wgsl(&kernel_template(), &KernelVariant { merged: Some(caps()), ..Default::default() }.flags(), &c);
}
}
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 71e2cec..255d669 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -447,8 +447,6 @@ pub struct Scene {
/// The vertex colours as the GPU reads them (`prepare`): three words per triangle in GPU order, none in a scene
/// without them (gpu.rs F_VCOLOR).
pub gpu_vcolors: Vec<u32>,
- /// Where they start in `prev_verts` (vec4s: the previous vertices of the dynamic tail come first; `Params::procs.w`).
- pub vcolor_base: u32,
pub attrs: Vec<GpuTriAttr>,
pub materials: Vec<GpuMaterial>,
pub textures: Vec<Texture>,
@@ -508,8 +506,8 @@ pub struct Scene {
/// Procedural geometry (`Kind::Procedural`) and the geometry functions it runs: (name, WGSL code, helpers).
pub procs: Vec<ProcObject>,
pub geometry_fns: Vec<(String, String, String)>,
- /// The kernel's procedural region and records (`prepare`: `proc_layout`, `ProcObject::gpu`); the region follows the
- /// environment's CDF in the `env_cdf` binding (`Params::procs`), the records the model instances' in `instances`.
+ /// The kernel's procedural region and records (`prepare`: `proc_layout`, `ProcObject::gpu`); the region is a
+ /// section of the words' heap (heap.rs `Stream::Procs`), the records follow the model instances' in `instances`.
pub proc_layout: Option<ProcLayout>,
pub proc_records: Vec<GpuInstance>,
/// Software traversal's units (`prepare`: the instances it keeps as instances; units.rs), None under hardware
@@ -859,7 +857,7 @@ pub fn apply_shader(gm: &mut GpuMaterial, sh: &desc::ShaderRef, shaders: &HashMa
/// Analytic light of a light object with world matrix `m` (rect lights with a visible card are emitter geometry
/// instead, see `card_material`). Emission scales with the node's power.
/// `gpu_light` of a light that may be hidden (`shown`: `World::shown`): hidden, its entry stays where it is in the
-/// table, black (the kernel skips black lights, and they are in no group's sphere: lib.rs `lights_with_groups`).
+/// table, black (the kernel skips black lights, and they are in no group's sphere: lib.rs `light_groups`).
pub fn gpu_light_shown(l: &Light, m: Mat4, power: f32, shown: bool) -> Option<GpuLight> {
let mut gl = gpu_light(l, m, power)?;
if !shown {
@@ -1848,7 +1846,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
vcolors,
pool_vcolors,
gpu_vcolors: vec![],
- vcolor_base: 0,
tri_flags,
attrs,
materials,
diff --git a/tests/render/light-emitter-tree-live.ts b/tests/render/light-emitter-tree-live.ts
new file mode 100644
index 0000000..796dfb7
--- /dev/null
+++ b/tests/render/light-emitter-tree-live.ts
@@ -0,0 +1,7 @@
+// light/emitter-tree in the real-time renderer: the tree as the scene is loaded, before any edit writes it again.
+import def, { test as base } from "./light-emitter-tree.ts";
+import type { TestMeta } from "./lib.ts";
+
+export const test: TestMeta = { ...base, id: "light/emitter-tree-live", metric: { ...base.metric, tolerance: 0.03 }, temporal: true, live: 120 };
+
+export default def;
diff --git a/tests/render/light-emitter-tree.ts b/tests/render/light-emitter-tree.ts
new file mode 100644
index 0000000..ed5aa46
--- /dev/null
+++ b/tests/render/light-emitter-tree.ts
@@ -0,0 +1,31 @@
+// Emitters sampled by a light tree from the first frame: 144 emissive specks (5 cm, 20,000 nits; 288 triangles, over
+// the tree's 256) in a 12 x 12 grid 2 m above an albedo-0.5 Lambert plane, facing it. Each gives the centre
+// L A cos^2 / d^2 (cos = 2 / d), so the plane shows 0.5 / pi x their sum; a speck is 0.0006 sr from there, so paths
+// that are not sent to the emitters find almost none of it.
+import { Color, Mesh, MeshStandardMaterial, PlaneGeometry } from "@threert/scene";
+import { CENTER, camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+const [N, STEP, H, SIDE, NITS] = [12, 0.5, 2, 0.05, 20000];
+const at = (k: number) => (k - (N - 1) / 2) * STEP;
+const cells = Array.from({ length: N * N }, (_, k) => [at(k % N), at(Math.floor(k / N))]);
+const sum = cells.reduce((s, [x, z]) => s + (H * H) / (x * x + z * z + H * H) ** 2, 0);
+
+export const test: TestMeta = {
+ id: "light/emitter-tree", features: ["emissive", "light-tree", "lambert"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: (0.5 / Math.PI) * NITS * SIDE * SIDE * sum, tolerance: 0.02 },
+ note: "144 emissive specks over a Lambert plane, sampled by a light tree: their sum at the centre",
+};
+
+export default function () {
+ const scene = sceneWithSky(0);
+ const glow = new MeshStandardMaterial({ name: "glow", color: new Color(0, 0, 0), emissive: new Color(1, 1, 1), emissiveIntensity: NITS, roughness: 1 });
+ const geometry = new PlaneGeometry(SIDE, SIDE);
+ const specks = cells.map(([x, z], k) => {
+ const m = new Mesh(geometry, glow);
+ m.name = `speck-${k}`;
+ m.rotation.x = Math.PI / 2;
+ m.position.set(x, H, z);
+ return m;
+ });
+ return result(scene, camera(scene, [0, 0.5, 0.001], [0, 0, 0], 40), [plane(400, lambert(0.5, "floor"), "floor"), ...specks]);
+}