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.

Live trace: a second pass for the pixels that go on past the cache lookup (#106)

Yujia8cb4e9b146fd
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 14ad125..5cf9621 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2493,6 +2493,25 @@ Zero Day 9.41 -> 8.41 ms (-10.6 %), Bistro 8.57 -> 8.05 (-6.1 %) and 4.58 -> 4.3
slice 9.00 -> 8.29, a glass scene 4.97 -> 4.60, Kabukichō 16.23 -> 14.61 guarded (-10 %); scenes without cutouts
(lamp-rooms, the fire scene, Tokyo) as they were. The shortcuts now save Zero Day 0.3 ms where they cost it 0.4.
+**A second pass for the pixels that go on (2026-11-16, after it).** Where a live path ends in the cache most pixels
+read a warm voxel and are done; some have more to trace: a training path (1 tile in 8), a cold voxel's estimate, a
+reflection hit's lights (a third of Zero Day's pixels). Traced in `main` they held their SIMD groups, and their code
+cost every pixel (`main` without it: Bistro 8.06 -> 6.54 ms). They leave a 96-byte record now, and the kernel's
+`finish` pass traces the records after each sample, one invocation each, and adds the light to the pixel as the
+epilogue splits it. The estimator is the same: bench-window's shots as main's (Bistro 1.81, lamp-rooms 0.63, the
+slice 5.40, Kabukichō 4.66); render-identity: no offline picture differs, 13 live ones of 229 at single pixels with
+the image's mean within 4e-5 (which slot a voxel takes follows the order of inserts), and the build repeats itself
+to the byte where main did not (its lookups raced its own training). The trace: Bistro 8.16 -> 7.29 ms (-10.7 %)
+and 4.36 -> 3.98 along its camera path, Zero Day 8.52 -> 7.75 (-9.0 %), lamp-rooms 3.79 -> 3.24 (-14.5 %), the
+Bistro slice 8.32 -> 7.31 (-12.1 %); guarded, Tokyo 4.74 -> 4.28 (-9.7 %) and Kabukichō 14.60 -> 13.64 (-6.6 %:
+the pass costs 2.7 ms there, the wet street's material function run again for each record). The layout as written
+only; the merged one ends its paths in `main` as before. The records' buffer follows the traced size (50 MB at
+960 x 540). It is the kernel's 23rd binding, and the translucency pass, at Metal's 29 a stage already, binds
+group 1 without it: the next buffer needs a layout for each pass of what it reads. (Kabukichō's profile, for
+whoever reads it next: the particles' BLAS slot is 0.45 ms when the frame fits a display interval and 1.0 to 1.7
+with a spread of 3 when it is between one and two, in main's build too: it times a wait.) Next here: the segment
+test, whose pixels can go to the pass; a record that carries the surface where its material function is dear.
+
## 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 77bc747..06a2024 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1310,6 +1310,8 @@ The kernel's read-only scene data other than triangles is two storage buffers, e
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).
+ (`finish`'s records are the kernel's 23rd; the translucency pass, which does not read them, binds group 1
+ without, and stays at 29.)
(Hardware traversal no longer binds software traversal's trees, a placeholder there; the light tiles' lists took
the binding.)
@@ -1371,6 +1373,13 @@ cache's voxels, and later segments meet homogeneous media alone; depth of field
particles are lit from the cache's voxels; past a camera hit's own decisions the sampler is a hash, not Sobol
(variance only).
+Where a path ends in the cache, `main` takes only what a warm voxel holds. The pixels with more to trace there (a
+training path, a cold voxel's estimate, a reflection hit's lights) leave a record of 96 bytes, and a second pass
+of the kernel, `finish`, traces them after each sample and adds their light to the pixel, one invocation a record.
+They are few and scattered: traced in `main` they held their SIMD groups, and their code cost every pixel (the
+trace 9 to 15 % faster without, Kabukichō 7). The records' buffer follows the traced size. The layout as written
+only; the merged one ends its paths in `main`.
+
The radiance cache is held to numbers by the `cache/*` tests (a bounce off a lit floor, the same off a coated one
and with the floor on a voxel face, two bounces in a view's first frame, a lit ground seen in a mirror, a furnace
box, a corner): within 2 % of the offline or analytic value. A lookup whose voxel has too few samples reads the
@@ -1461,7 +1470,7 @@ on the device", and differs where it says so.
| `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 |
+ | `accum` (11), group 1 (radiance cache, the trace's outputs, `finish`'s records, 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 |
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 36ef9fb..29cd0fa 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -2917,6 +2917,9 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
@group(1) @binding(8) var<storage, read_write> loop_guard_trips: array<atomic<u32>, GUARD_WORDS>;
fn loop_guard_stopped() { atomicAdd(&loop_guard_trips[0], 1u); }
}
+ // The pixels of this sample that `finish` ends (below `cache_end`): their number, then a record each.
+ struct Deferred { n: atomic<u32>, recs: array<vec4<u32>> };
+ @group(1) @binding(9) var<storage, read_write> deferred: Deferred;
}
// The loop guard (gpu.rs `loop_guard_of`; docs/RUNTIME.md "The engine in a browser"): every loop of the kernel, the
@@ -3194,6 +3197,101 @@ fn cache_train(s0: Surface, d0: vec3<f32>, cone0: vec2<f32>, depth: u32, insert:
return Fresh(e, min(direct[0], e));
}
+// What a live path ends with at its first bounce, surface `s` (reached along d; ray-cone width there + spread; path
+// weight `thr`): what `s` reflects of the cache. Surfaces seen in mirror-like reflections (`hit_light`: specular lobe
+// below roughness 0.4, where UE traces reflections) get direct light of their own, as UE's hit lighting does, and the
+// cache's indirect part; others reflect the cache's total. Rotating tiles train the cache (`train`). A pixel that
+// finds its voxel cold at every level (`cache_get`) traces a fresh estimate and uses it, without inserting the voxel:
+// the low-sample entries such pixels inserted kept later frames slower until evicted (the crowd's square ~2 ms).
+// (Until 2026-11-16 that held for a view's first 30 frames; later a cold voxel was read as it was, black where there
+// was none. With the coarser levels few lookups are cold, and the rule's own test cost more than their traces:
+// Bistro 9.05 ms with it, 8.87 without.)
+fn cache_end(s: Surface, d: vec3<f32>, cone: vec2<f32>, thr: vec3<f32>, depth: u32, train: bool, hit_light: bool, straight: bool) -> vec3<f32> {
+ let v1 = -d;
+ let lb1 = lobes(s, max(dot(s.n, v1), 1e-4));
+ var e = cache_get(s, hit_light);
+ if (train || e.w < CACHE_WARM) {
+ // Training tiles trace deep (coherent: whole SIMD groups); scattered cold pixels one vertex.
+ let fresh = cache_train(s, d, cone, select(1u, CACHE_DEPTH, train), train);
+ RNG_PATH = 0u;
+ if (e.w < CACHE_WARM) { e = vec4<f32>(select(fresh.total, fresh.total - fresh.direct, hit_light), 1.0); }
+ }
+ cur_depth = depth;
+ var c = thr * cache_reflectance(lb1) * e.rgb;
+ // Resampled lights, not the exact loop camera hits get (that costs 2x here: mirror pixels are scattered).
+ mirror_path = mirror_path && (u32(P.cache.w) & 8u) != 0u;
+ // (The lights alone: the sky's light is in the cache's indirect part, whole. Its samples taken afresh
+ // here against the white-lobe ones the cache left out do not add up on a glossy surface: a white metal
+ // ground in a mirror read 0.80 of a uniform sky. The lights' still are: weights of two lobes, right for a
+ // Lambert surface and for small lights; as light samples alone they were fireflies on Kabukichō's wet
+ // street, flicker + 22 %.)
+ if (hit_light) {
+ lights_only = true;
+ c += thr * direct_light(s, lb1, v1);
+ lights_only = false;
+ }
+ let lum = luminance(c);
+ if (lum > P.misc.x && !straight) { c *= P.misc.x / lum; }
+ return c;
+}
+
+// A pixel `main` left for `finish`, DEFERRED_VECS vec4<u32>s (floats as their bits): (pixel, DF_ flags | depth << 8,
+// light list + its length, hit triangle) (hit instance, u, v, k_spec.x) (hit point, cone width) (ray direction, cone
+// spread) (path weight, k_spec.y) (the specular ray's weight, k_spec.z).
+const DEFERRED_VECS: u32 = 6u;
+const DEFERRED_ROW: u32 = 16384u; // `finish` invocations a dispatch row (gpu.rs DEFERRED_ROW)
+const DF_TRAIN: u32 = 1u; // of a training tile
+const DF_OUT: u32 = 2u; // its light is still to add (a cold voxel, a reflection hit's lights)
+const DF_HIT_LIGHT: u32 = 4u;
+const DF_STRAIGHT: u32 = 8u;
+const DF_MIRROR: u32 = 16u;
+const DF_RESOLVE: u32 = 32u; // the reflection resolve takes the specular share
+const DF_REFL_RAY: u32 = 64u; // the camera hit's sample was a specular-lobe ray
+
+// Live, after each sample's trace: the pixels that had more to trace than a warm voxel's lookup (`cache_end`: a
+// training path, a cold voxel's fresh estimate, a reflection hit's lights), one invocation each. `main` left them a
+// record and wrote the pixel without that light; this adds it, split as the epilogue of `main` splits it. Such pixels
+// are few and scattered (a third of a glossy scene's, an eighth for training): traced in `main`, the others' lanes
+// idled beside them, and the code cost every pixel (Bistro 8.06 -> 6.54 ms without it, before this pass's own work).
+// The layout as written only: the merged one ends its paths in `main`.
+@if(!merged) @compute @workgroup_size(64, 1, 1)
+fn finish(@builtin(global_invocation_id) gid: vec3<u32>) {
+ let at = (gid.y * DEFERRED_ROW + gid.x) * DEFERRED_VECS;
+ if (gid.y * DEFERRED_ROW + gid.x >= atomicLoad(&deferred.n) || at + DEFERRED_VECS > arrayLength(&deferred.recs)) { return; }
+ let r0 = deferred.recs[at];
+ let r1 = deferred.recs[at + 1u];
+ let r2 = bitcast<vec4<f32>>(deferred.recs[at + 2u]);
+ let r3 = bitcast<vec4<f32>>(deferred.recs[at + 3u]);
+ let r4 = bitcast<vec4<f32>>(deferred.recs[at + 4u]);
+ let r5 = bitcast<vec4<f32>>(deferred.recs[at + 5u]);
+ let pix = r0.x;
+ let fl = r0.y;
+ rng_start(vec2<u32>(pix % P.size.x, pix / P.size.x), P.size.z, P.size.w, 0u);
+ cur_depth = fl >> 8u;
+ mirror_path = (fl & DF_MIRROR) != 0u;
+ rays_off = LIVE && P.raster.w > 0.5;
+ if (has(F_LISTS)) {
+ lt_list = r0.z & ~(LT_LIST - 1u);
+ lt_list_n = r0.z & (LT_LIST - 1u);
+ lt_fb = LT_NONE;
+ }
+ // (The hit point as the ray's origin, at distance 0.)
+ let s = surface(r2.xyz, r3.xyz, Hit(0.0, r0.w, bitcast<f32>(r1.y), bitcast<f32>(r1.z), r1.x), r2.w);
+ let c = cache_end(s, r3.xyz, vec2<f32>(r2.w, r3.w), r4.xyz, fl >> 8u, (fl & DF_TRAIN) != 0u, (fl & DF_HIT_LIGHT) != 0u, (fl & DF_STRAIGHT) != 0u);
+ if ((fl & DF_OUT) == 0u || non_finite(c)) { return; }
+ let cs = c * vec3<f32>(bitcast<f32>(r1.w), r4.w, r5.w);
+ var px = accum[pix];
+ px.color = vec4<f32>(px.color.rgb + (c - cs), px.color.w);
+ if ((fl & DF_RESOLVE) == 0u) {
+ px.spec = vec4<f32>(px.spec.rgb + cs, px.spec.w);
+ } else if (P.misc.w < 0.5 && resolve_bound()) {
+ var li = cs;
+ if ((fl & DF_REFL_RAY) != 0u) { li = select(c / r5.xyz, vec3<f32>(0.0), r5.xyz < vec3<f32>(1e-6)); }
+ if (!non_finite(li)) { refl[pix * 2u] += vec4<f32>(li, 0.0); }
+ }
+ accum[pix] = px;
+}
+
// Live, after the trace: MEDIA_TRAIN_POINTS fresh estimates (point_radiance) into the volume voxels, each at a random
// point where a camera ray toward a random traced pixel crosses the media before its first hit.
@compute @workgroup_size(64, 1, 1)
@@ -3580,44 +3678,37 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
}
break;
}
- // Live: the path ends in the radiance cache at its first bounce. Surfaces seen in mirror-like reflections
- // (specular lobe below roughness 0.4, where UE traces reflections) get direct light of their own, as UE's hit
- // lighting does, and the cache's indirect part; others reflect the cache's total. Rotating tiles train the
- // cache. A pixel that finds its voxel cold at every level (`cache_get`) traces a fresh estimate and uses it,
- // without inserting the voxel: the low-sample entries such pixels inserted kept later frames slower until
- // evicted (the crowd's square ~2 ms). (Until 2026-11-16 that held for a view's first 30 frames; later a cold
- // voxel was read as it was, black where there was none. With the coarser levels few lookups are cold, and
- // the rule's own test cost more than their traces: Bistro 9.05 ms with it, 8.87 without.)
- let cfl = u32(P.cache.w);
+ // Live: the path ends in the radiance cache at its first bounce (`cache_end`).
if (cache_on() && depth >= 1u && !(has(F_GLASS) && s.transmission > 0.0)) {
- let v1 = -d;
- let lb1 = lobes(s, max(dot(s.n, v1), 1e-4));
- let hit_light = spec_lobe && rough0 < 0.4 && depth == 1u && (cfl & 2u) == 0u;
- var e = cache_get(s, hit_light);
- let train = (((gid.x >> 3u) + 3u * (gid.y >> 2u) + pcg(P.size.z)) & CACHE_TRAIN_MASK) == 0u && (cfl & 4u) == 0u;
- if (train || e.w < CACHE_WARM) {
- // Training tiles trace deep (coherent: whole SIMD groups); scattered cold pixels one vertex.
- let fresh = cache_train(s, d, vec2<f32>(width, cone_a), select(1u, CACHE_DEPTH, train), train);
- RNG_PATH = 0u;
- if (e.w < CACHE_WARM) { e = vec4<f32>(select(fresh.total, fresh.total - fresh.direct, hit_light), 1.0); }
- }
- cur_depth = depth;
- var c = thr * cache_reflectance(lb1) * e.rgb;
- // Resampled lights, not the exact loop camera hits get (that costs 2x here: mirror pixels are scattered).
- mirror_path = mirror_path && (cfl & 8u) != 0u;
- // (The lights alone: the sky's light is in the cache's indirect part, whole. Its samples taken afresh
- // here against the white-lobe ones the cache left out do not add up on a glossy surface: a white metal
- // ground in a mirror read 0.80 of a uniform sky. The lights' still are: weights of two lobes, right for a
- // Lambert surface and for small lights; as light samples alone they were fireflies on Kabukichō's wet
- // street, flicker + 22 %.)
- if (hit_light) {
- lights_only = true;
- c += thr * direct_light(s, lb1, v1);
- lights_only = false;
+ let hit_light = spec_lobe && rough0 < 0.4 && depth == 1u && (u32(P.cache.w) & 2u) == 0u;
+ let train = (((gid.x >> 3u) + 3u * (gid.y >> 2u) + pcg(P.size.z)) & CACHE_TRAIN_MASK) == 0u && (u32(P.cache.w) & 4u) == 0u;
+ @if(merged) { radiance += cache_end(s, d, vec2<f32>(width, cone_a), thr, depth, train, hit_light, straight); }
+ @if(!merged) {
+ // Here only what a warm voxel holds; a pixel with more to trace is left for `finish`.
+ let e = cache_get(s, hit_light);
+ let later = hit_light || e.w < CACHE_WARM;
+ if (later || train) {
+ let at = atomicAdd(&deferred.n, 1u) * DEFERRED_VECS;
+ if (at + DEFERRED_VECS <= arrayLength(&deferred.recs)) {
+ let fl = (depth << 8u) | select(0u, DF_TRAIN, train) | select(0u, DF_OUT, later) | select(0u, DF_HIT_LIGHT, hit_light) | select(0u, DF_STRAIGHT, straight)
+ | select(0u, DF_MIRROR, mirror_path) | select(0u, DF_RESOLVE, resolve_on() && !through0 && !glass0) | select(0u, DF_REFL_RAY, refl_pdf > 0.0);
+ var lt = 0u;
+ if (has(F_LISTS) && lt_list_n > 0u) { lt = lt_list + lt_list_n; }
+ deferred.recs[at] = vec4<u32>(pix, fl, lt, hit.tri);
+ deferred.recs[at + 1u] = vec4<u32>(hit.inst, bitcast<u32>(hit.u), bitcast<u32>(hit.v), bitcast<u32>(k_spec.x));
+ deferred.recs[at + 2u] = bitcast<vec4<u32>>(vec4<f32>(s.p, width));
+ deferred.recs[at + 3u] = bitcast<vec4<u32>>(vec4<f32>(d, cone_a));
+ deferred.recs[at + 4u] = bitcast<vec4<u32>>(vec4<f32>(thr, k_spec.y));
+ deferred.recs[at + 5u] = bitcast<vec4<u32>>(vec4<f32>(refl_w, k_spec.z));
+ }
+ }
+ if (!later) {
+ var c = thr * cache_reflectance(lobes(s, max(dot(s.n, -d), 1e-4))) * e.rgb;
+ let lum = luminance(c);
+ if (lum > clamp_v && !straight) { c *= clamp_v / lum; }
+ radiance += c;
+ }
}
- let lum = luminance(c);
- if (lum > clamp_v && !straight) { c *= clamp_v / lum; }
- radiance += c;
break;
}
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 3fd93a6..011148b 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -58,9 +58,13 @@ pub struct Gpu {
/// pipelines (`translucent`, `volume_train`) by the kernel's variant key.
tl_layout: Option<wgpu::BindGroupLayout>,
tl_pipeline_layout: Option<wgpu::PipelineLayout>,
+ /// Its group 1: `vis_layout` without `finish`'s records, which the pass does not read (with them its three groups
+ /// are one buffer past Metal's 29 a stage), and `no_vis` made for it.
+ pub tl_vis_layout: Option<wgpu::BindGroupLayout>,
+ no_vis_tl: Option<wgpu::BindGroup>,
tl_pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool, u32), TranslucentPipelines>>,
- /// The live media passes (pathtrace.wgsl `media_train`, `media_composite`) by kernel variant and entry point.
- media_passes: std::sync::Mutex<std::collections::HashMap<(u32, u64, &'static str, u32), wgpu::ComputePipeline>>,
+ /// The kernel's passes beside `main` (`kernel_pass`) by kernel variant and entry point.
+ kernel_passes: std::sync::Mutex<std::collections::HashMap<(u32, u64, &'static str, u32), wgpu::ComputePipeline>>,
/// The procedural blobs of the last upload (`upload_procs`).
proc_cache: std::sync::Mutex<Option<ProcCache>>,
/// The last upload's procedural BLASes by geometry hash (read-only once built; another upload may share them), with
@@ -223,7 +227,7 @@ const ACCELERATION_STRUCTURE: wgpu::BindingType = wgpu::BindingType::Acceleratio
/// (what the kernel writes), group 2 (the translucency pass's; hardware traversal). A test holds them to what every
/// variant of the kernel's source declares (`the_kernels_layouts_are_its_declarations`).
pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupLayoutEntry>; 3] {
- use crate::merged::{GUARD_BINDING, LISTS_BINDING, LIVE_BINDING, TABLE_VIEWS, UNIFORM_TABLES};
+ use crate::merged::{DEFERRED_BINDING, GUARD_BINDING, LISTS_BINDING, LIVE_BINDING, TABLE_VIEWS, UNIFORM_TABLES};
let LayoutShape { hwrt, merged, uniform_tables, guard } = shape;
let (read, write) = (storage_buffer(true), storage_buffer(false));
// Group 0: the parameters; triangles and their attributes; the tables' heap, the words' heap; the dynamic
@@ -257,14 +261,15 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupL
}
// Group 1: the raster pass's visibility; then, merged, the one buffer (`heap::Live`, the loop guard's count in
// it); as written, the radiance cache's three, the light tiles' lists, the specular rays, the motion vectors, the
- // direct light, and the loop guard's count where a kernel of this device may have the guard (one without it does
- // not name the binding).
+ // direct light, the pixels left for `finish`, and the loop guard's count where a kernel of this device may have
+ // the guard (one without it does not name the binding).
let mut live = vec![layout_entry(0, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Uint, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false })];
if merged {
live.push(layout_entry(LIVE_BINDING, write));
} else {
live.extend([1, 2, 3, 5, 6, 7].map(|b| layout_entry(b, write)));
live.push(layout_entry(LISTS_BINDING, read));
+ live.push(layout_entry(DEFERRED_BINDING, write));
if guard {
live.push(layout_entry(GUARD_BINDING, write));
}
@@ -1210,6 +1215,10 @@ pub fn tlas_rows(w: glam::Mat4) -> [f32; 12] {
/// Entries of the live radiance cache (pathtrace.wgsl CACHE_SIZE).
pub const CACHE_SIZE: u64 = 1 << 18;
+/// The kernel's `finish` pass (pathtrace.wgsl): a record's bytes (DEFERRED_VECS vec4s) after the 16 of their count,
+/// and the invocations of a dispatch row (DEFERRED_ROW).
+pub const DEFERRED_BYTES: u64 = 96;
+pub const DEFERRED_ROW: u32 = 16384;
/// A buffer, or a range of one: in the merged layout (merged.rs) several of the engine's buffers are ranges of the one
/// buffer a binding holds.
@@ -1271,6 +1280,9 @@ pub struct KernelBufs {
pub motion: Buf,
pub direct: Buf,
pub lists: Buf,
+ /// The pixels a sample's trace leaves for `finish` (their count, then `DEFERRED_BYTES` each): the layout as
+ /// written only. Of one record until a live view makes it for its traced size (`deferred_buffer`).
+ pub deferred: Option<Buf>,
/// The loop guard's count (`guard_loops`: its first word, the invocations a loop of which was stopped): with
/// the guard, and always in the merged layout.
pub guard: Option<Buf>,
@@ -1285,14 +1297,14 @@ impl KernelBufs {
if !merged {
let sb = |label: &str, size: u64| Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }));
let guard = guard.then(|| sb("loop guard", crate::merged::GUARD_WORDS as u64 * 4));
- return KernelBufs { cache: CacheBuffers::new(d, entries), refl: sb("refl", refl), motion: sb("motion", motion), direct: sb("direct", direct), lists: sb("light lists", lists), guard, merged: None };
+ return KernelBufs { cache: CacheBuffers::new(d, entries), refl: sb("refl", refl), motion: sb("motion", motion), direct: sb("direct", direct), lists: sb("light lists", lists), deferred: Some(deferred_buffer(d, 1)), guard, merged: None };
}
// (The cache's keys and sums are as long as the kernel's struct says, whatever `entries`: `live_sizes`. A
// section's range is the bytes asked for: a pass that binds it sees an array of that length.)
let bytes = live_sizes(entries, refl, motion, direct, lists);
let heap = Heap::<Live>::new(d, &bytes);
let b = |s: Live| Buf { buffer: heap.buffer.clone(), offset: heap.at(s), size: bytes[s.index()] };
- KernelBufs { cache: CacheBuffers { keys: b(Live::CacheKeys), acc: b(Live::CacheAcc), val: b(Live::CacheVal) }, refl: b(Live::Refl), motion: b(Live::Motion), direct: b(Live::Direct), lists: b(Live::Lists), guard: Some(b(Live::Guard)), merged: Some(heap) }
+ KernelBufs { cache: CacheBuffers { keys: b(Live::CacheKeys), acc: b(Live::CacheAcc), val: b(Live::CacheVal) }, refl: b(Live::Refl), motion: b(Live::Motion), direct: b(Live::Direct), lists: b(Live::Lists), deferred: None, guard: Some(b(Live::Guard)), merged: Some(heap) }
}
/// Where the kernel finds the vec4 sections in the merged layout (`Params::live_first`, `live_len`): written with
@@ -1305,6 +1317,11 @@ impl KernelBufs {
}
}
+/// `finish`'s buffer for `records` pixels: their count (16 bytes, cleared before each sample), then the records.
+pub fn deferred_buffer(d: &wgpu::Device, records: u64) -> Buf {
+ Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some("deferred"), size: 16 + records.max(1) * DEFERRED_BYTES, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }))
+}
+
/// The bytes of the merged layout's group-1 buffer's sections (`heap::Live`'s order) for a cache whose values are
/// `entries` long and the live passes' four of these bytes. The cache's keys and sums and the loop guard's count are
/// members of the kernel's struct, of the kernel's lengths (pathtrace.wgsl `MergedLive`).
@@ -1314,7 +1331,8 @@ pub(crate) fn live_sizes(entries: u64, refl: u64, motion: u64, direct: u64, list
/// Group-1 bind group of the kernel: a primary-visibility texture, the radiance cache and the
/// reflection resolve's inputs (`KernelBufs`); in the merged layout, the texture and the one buffer.
-pub fn vis_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, view: &wgpu::TextureView, b: &KernelBufs) -> wgpu::BindGroup {
+/// `deferred`: with `finish`'s records (`vis_layout`; the translucency pass's `tl_vis_layout` is without).
+pub fn vis_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, view: &wgpu::TextureView, b: &KernelBufs, deferred: bool) -> wgpu::BindGroup {
fn e(binding: u32, b: &Buf) -> wgpu::BindGroupEntry<'_> {
wgpu::BindGroupEntry { binding, resource: b.binding() }
}
@@ -1323,6 +1341,7 @@ pub fn vis_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, view: &w
Some(heap) => d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("vis"), layout, entries: &[tex, wgpu::BindGroupEntry { binding: crate::merged::LIVE_BINDING, resource: heap.buffer.as_entire_binding() }] }),
None => {
let mut entries = vec![tex, e(1, &b.cache.keys), e(2, &b.cache.acc), e(3, &b.cache.val), e(crate::merged::LISTS_BINDING, &b.lists), e(5, &b.refl), e(6, &b.motion), e(7, &b.direct)];
+ entries.extend(b.deferred.as_ref().filter(|_| deferred).map(|r| e(crate::merged::DEFERRED_BINDING, r)));
entries.extend(b.guard.as_ref().map(|g| e(crate::merged::GUARD_BINDING, g)));
d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("vis"), layout, entries: &entries })
}
@@ -1743,16 +1762,19 @@ impl Gpu {
],
});
let no_vis_bufs = KernelBufs::new(&device, merged, guard_room(hwrt), 1, 64, 64, 64, 64);
- let no_vis = vis_bind_group(&device, &vis_layout, &no_vis_view, &no_vis_bufs);
+ let no_vis = vis_bind_group(&device, &vis_layout, &no_vis_view, &no_vis_bufs, true);
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout), Some(&vis_layout)], immediate_size: 0 });
- let (tl_layout, tl_pipeline_layout) = if hwrt {
+ let (tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl) = if hwrt {
let l = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("translucent"), entries: &tl_entries });
- let tpl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("translucent"), bind_group_layouts: &[Some(&layout), Some(&vis_layout), Some(&l)], immediate_size: 0 });
- (Some(l), Some(tpl))
+ let tl_vis: Vec<_> = vis_entries.iter().filter(|e| merged || e.binding != crate::merged::DEFERRED_BINDING).copied().collect();
+ let vl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("vis, translucent"), entries: &tl_vis });
+ let tpl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("translucent"), bind_group_layouts: &[Some(&layout), Some(&vl), Some(&l)], immediate_size: 0 });
+ let nv = vis_bind_group(&device, &vl, &no_vis_view, &no_vis_bufs, false);
+ (Some(l), Some(tpl), Some(vl), Some(nv))
} else {
- (None, None)
+ (None, None, None, None)
};
- Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), tl_layout, tl_pipeline_layout, tl_pipelines: Default::default(), media_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })
+ Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })
}
/// Whether this device's kernel buffers have the loop guard's count (`guard_room`; always in the merged layout).
@@ -1837,10 +1859,10 @@ impl Gpu {
.clone()
}
- /// A live media pass of a scene's kernel variant: `media_train` (the volume voxels) or `media_composite` (camera
- /// rays through media, after the trace).
- pub fn media_pipeline(&self, k: &Kernel, entry: &'static str) -> wgpu::ComputePipeline {
- let mut cache = self.media_passes.lock().unwrap();
+ /// A live pass of a scene's kernel variant beside `main`: `finish` (the pixels a sample's trace left), `media_train`
+ /// (the volume voxels) or `media_composite` (camera rays through media, after the trace).
+ pub fn kernel_pass(&self, k: &Kernel, entry: &'static str) -> wgpu::ComputePipeline {
+ let mut cache = self.kernel_passes.lock().unwrap();
cache
.entry((k.features, k.hash, entry, k.approx))
.or_insert_with(|| {
@@ -3178,7 +3200,7 @@ impl Gpu {
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("translucent"), timestamp_writes: None });
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &up.bg, &[]);
- pass.set_bind_group(1, &self.no_vis, &[]);
+ pass.set_bind_group(1, self.no_vis_tl.as_ref().unwrap(), &[]);
pass.set_bind_group(2, &tbg, &[]);
pass.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1);
}
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index 8f9e5a2..9a6f98f 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -254,6 +254,7 @@ impl LiveCore {
self.take_emitters();
let (w, h) = (self.w, self.h);
let (iw, ih) = self.internal_size();
+ self.ensure_deferred(iw as u64 * ih as u64);
let now = Instant::now();
// Lockstep (benchmarks) renders at a fixed frame time, whatever the wall clock says.
self.frame_dt = self.fixed_dt.unwrap_or_else(|| now.duration_since(self.last_frame).as_secs_f32());
@@ -344,8 +345,10 @@ impl LiveCore {
let pipeline = g.pipeline(&self.sc.up.kernel, true);
// (No media pass while every medium is hidden: a pool of idle fireballs costs the frame nothing.)
let media = self.sc.up.kernel.features & gpu::F_MEDIA != 0 && self.sc.up.media_hidden.borrow().iter().any(|h| !h);
- let media_train = (media && self.cache.is_some()).then(|| g.media_pipeline(&self.sc.up.kernel, "media_train"));
- let media_composite = media.then(|| g.media_pipeline(&self.sc.up.kernel, "media_composite"));
+ let media_train = (media && self.cache.is_some()).then(|| g.kernel_pass(&self.sc.up.kernel, "media_train"));
+ let media_composite = media.then(|| g.kernel_pass(&self.sc.up.kernel, "media_composite"));
+ // The pixels a sample's trace leaves at the radiance cache (pathtrace.wgsl `finish`).
+ let finish = self.targets.kernel.deferred.as_ref().filter(|_| self.cache.is_some()).map(|d| (g.kernel_pass(&self.sc.up.kernel, "finish"), d));
// This frame's sub-pixel jitter (Halton 2, 3), every camera ray's and the raster visibility pass's: 8 phases at
// full resolution, as many more as an output pixel has fewer traced ones (8 / scale^2: the upscaler needs each
// output pixel visited), in the 12 bits a side the samples carry it in.
@@ -447,11 +450,19 @@ impl LiveCore {
(None, Some(t), Some(slot)) if k == 0 => Some(wgpu::ComputePassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: Some(slot as u32 * 8), end_of_pass_write_index: Some(slot as u32 * 8 + 1) }),
_ => None,
};
+ if let Some((_, d)) = &finish {
+ e.clear_buffer(&d.buffer, d.offset, Some(4));
+ }
let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("live trace"), timestamp_writes: tw });
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &self.sc.up.bg, &[]);
pass.set_bind_group(1, &self.kernel_bg, &[]);
pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);
+ // (Rows over every traced pixel: the invocations past the records' count leave at once.)
+ if let Some((f, _)) = &finish {
+ pass.set_pipeline(f);
+ pass.dispatch_workgroups(gpu::DEFERRED_ROW / 64, (iw * ih).div_ceil(gpu::DEFERRED_ROW), 1);
+ }
// Participating media: their volume voxels trained after the trace (pathtrace.wgsl media_train), and
// camera rays through media once the frame's samples are traced (media_composite). In the trace's pass
// and timing; profiled, the frame's last sample's media passes are a pass of their own (`media`).
@@ -538,7 +549,7 @@ impl LiveCore {
let tl_dispatch = |pass: &mut wgpu::ComputePass, train: bool| {
if let Some((pipes, tbg, _)) = &tl {
pass.set_bind_group(0, &self.sc.up.bg, &[]);
- pass.set_bind_group(1, &self.kernel_bg, &[]);
+ pass.set_bind_group(1, self.tl_kernel_bg.as_ref().unwrap(), &[]);
pass.set_bind_group(2, tbg, &[]);
if train {
pass.set_pipeline(&pipes.train);
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index fccfde6..2339041 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -232,6 +232,9 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
// (The light tree is the tables' by now: its nodes from there.)
let 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)?;
let _ = g.pipeline(&up.kernel, true); // compile the scene's kernel variant now, not in the first frame
+ if !g.merged {
+ let _ = g.kernel_pass(&up.kernel, "finish");
+ }
let sky_inputs = ((prep.env.width, prep.env.height), sc.camera.position.y.max(0.0), prep.env_nee_floor);
let mut base = prep.params;
// The live view's own count of light-tree candidates at camera hits (ltree.rs `RIS_LIVE`).
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 1654cfd..91a2195 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -332,6 +332,8 @@ pub struct LiveCore {
cache: Option<RadianceCache>,
/// Kernel group 1: primary visibility + radiance cache + what the live passes read of a trace.
kernel_bg: wgpu::BindGroup,
+ /// The same for the translucency pass (`gpu::Gpu::tl_vis_layout`; hardware traversal).
+ tl_kernel_bg: Option<wgpu::BindGroup>,
/// Span (relative to the dynamic tail) re-transformed by the last in-place update whose previous-frame vertices
/// (`Uploaded::prev_verts`) still hold the frame before it: synced to the current ones next frame.
prev_span: Option<(usize, usize)>,
@@ -535,12 +537,14 @@ impl LiveCore {
let timer = (g.timestamps && profile.is_none()).then(|| FrameTimer::new(&g.device));
let raster = std::env::var("THREERT_RASTER").is_ok_and(|v| v == "1").then(|| Raster::new(&g, w, h));
let cache = cache_on.then(|| RadianceCache { bufs: targets.kernel.cache.clone(), resolve: g.cache_resolve_pipeline() });
- let kernel_bg = gpu::vis_bind_group(&g.device, &g.vis_layout, raster.as_ref().map_or(&g.no_vis_view, |r| &r.vis), &targets.kernel);
+ let vis = raster.as_ref().map_or(&g.no_vis_view, |r| &r.vis);
+ let kernel_bg = gpu::vis_bind_group(&g.device, &g.vis_layout, vis, &targets.kernel, true);
+ let tl_kernel_bg = g.tl_vis_layout.as_ref().map(|l| gpu::vis_bind_group(&g.device, l, vis, &targets.kernel, false));
// (Read whenever a kernel of this session may have the guard: under software traversal a scene's first unit
// brings it, `gpu::loop_guard_of`.)
let guard_read = (gpu::loop_guard_of(!g.hwrt).is_some() && targets.kernel.guard.is_some())
.then(|| (g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard read"), size: 4, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), Arc::new(AtomicU32::new(0))));
- let mut core = LiveCore { particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, prev_span: None, reposed: false, emitters_moved: false, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, sky_cover: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
+ let mut core = LiveCore { particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, sky_cover: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);
core.sky_cover = core.sc.tables.cloud_cover;
core.apply_post(&pp);
@@ -702,6 +706,19 @@ impl LiveCore {
self.cam = c;
}
+ /// Room in `finish`'s records for a sample of `pixels` traced pixels, any of which may leave one. The buffer follows
+ /// the traced size, not the output's (96 bytes a pixel: 354 MB for a 2560 x 1440 output, 50 traced at 0.375), and
+ /// is made a quarter larger than asked, so dynamic resolution's steps seldom make it again.
+ pub(super) fn ensure_deferred(&mut self, pixels: u64) {
+ let Some(d) = &self.targets.kernel.deferred else { return };
+ if self.cache.is_none() || d.size >= 16 + pixels * gpu::DEFERRED_BYTES {
+ return;
+ }
+ self.targets.kernel.deferred = Some(gpu::deferred_buffer(&self.g.device, (pixels + pixels / 4).min(self.w as u64 * self.h as u64)));
+ let vis = self.raster.as_ref().map_or(&self.g.no_vis_view, |r| &r.vis);
+ self.kernel_bg = gpu::vis_bind_group(&self.g.device, &self.g.vis_layout, vis, &self.targets.kernel, true);
+ }
+
/// Renders one frame with `spp` samples per pixel; returns the command buffers to submit after the samples.
/// Path-trace dispatches are submitted inside (each needs its own uniform contents).
/// Traced resolution at the current render scale.
diff --git a/renderer/src/merged.rs b/renderer/src/merged.rs
index 1d2caba..c2b5714 100644
--- a/renderer/src/merged.rs
+++ b/renderer/src/merged.rs
@@ -38,6 +38,9 @@ pub const LISTS_BINDING: u32 = 4;
/// merged layout a section (`heap::Live::Guard`), written only by a kernel with the guard.
pub const GUARD_BINDING: u32 = 8;
pub const GUARD_WORDS: u32 = 4;
+/// The pixels a live sample leaves for the kernel's `finish` pass (`gpu::KernelBufs::deferred`): the layout as
+/// written only.
+pub const DEFERRED_BINDING: u32 = 9;
/// 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
@@ -107,17 +110,18 @@ 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), no length of a view's buffer in the source,
/// and `MergedLive`'s members where the renderer puts their sections.
- /// The layout as written has 21 (20 under hardware traversal, which has no trees' buffer). Because the merged
+ /// The layout as written has 22 (21 under hardware traversal, which has no trees' buffer). 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, false));
let (used, declared) = storage_buffers(&m, &info);
- assert_eq!(declared, 21, "the kernel as written");
+ assert_eq!(declared, 22, "the kernel as written");
+ // (`main` no longer adds to the cache's sums: `finish` trains it.)
assert_eq!(used.iter().map(|u| u.1).max(), Some(21), "{used:?}");
let hw = kernel_wgsl(&kernel_template(), &KernelVariant::new(true, Default::default(), 0));
- assert_eq!(hw.matches("var<storage").count(), 20 + 4, "hardware traversal: no trees' buffer (and the translucency pass's four)");
+ assert_eq!(hw.matches("var<storage").count(), 21 + 4, "hardware traversal: no trees' buffer (and the translucency pass's four)");
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, true);
assert!(!src.contains("arrayLength"), "the lengths are the parameters'");
@@ -158,7 +162,7 @@ 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, 17, "features {features:#x}");
+ assert_eq!(storage_buffers(&m, &info).1, 18, "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}");
@@ -192,6 +196,10 @@ mod tests {
}
assert_eq!(<Table as crate::heap::Section>::COUNT, Table::Energy as usize + 1);
assert!(kernel_template().contains(&format!("const CACHE_SIZE: u32 = {}u;", crate::gpu::CACHE_SIZE)));
+ // `finish`'s records and its dispatch rows.
+ assert!(kernel_template().contains(&format!("const DEFERRED_VECS: u32 = {}u;", crate::gpu::DEFERRED_BYTES / 16)));
+ assert!(kernel_template().contains(&format!("const DEFERRED_ROW: u32 = {}u;", crate::gpu::DEFERRED_ROW)));
+ assert!(kernel_template().contains(&format!("@group(1) @binding({DEFERRED_BINDING}) var<storage, read_write> deferred: Deferred;")));
// 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]); }"));
@@ -223,8 +231,8 @@ mod tests {
assert_eq!(g.matches("if (loop_guard()) {").count(), loops(&plain) - counted(&plain));
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 { STORAGE_BUFFERS } else { 22 }, "{used:?}");
+ // (As written: the guard's count and `finish`'s records too. Merged: still eight.)
+ assert_eq!(declared as u32, if merged { STORAGE_BUFFERS } else { 23 }, "{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.