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.

A live frame's camera rays in a pass of their own (frame structure, step 1) (#280)

Yujia605120f5aed4
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 7337d99..a57b066 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2920,6 +2920,12 @@ Mutations: 26. 25 failed a test there was; one, a texture put on a shelf too low
Found by review: a translucent particle's material given another function kept the kernel's old dispatch for the
translucency pass, which has its particles' functions alone; the kernel is made again where those are others.
+**A live frame's camera rays in a pass of their own (2026-11-25).** The first step of the frame's structure: the
+kernel's `first_hit` traces the camera rays and leaves each pixel's hit and motion vector, and `main` starts its
+paths from the hits (docs/RUNTIME.md "The live architecture"). The pictures are the same. It is there for what
+comes next: a mirror's first hit replaced by the surface it shows, and light sampling that reads this frame's
+depth and motion before the paths. Test: `the_first_pass_leaves_the_camera_hits`.
+
**Nothing reads a world-space triangle (2026-11-25, after it).** Nothing made one any more; what read them is
deleted. Hardware traversal: the traversal groups and their BLASes, with the feature for a group past 2^24
triangles and the bit that told a model's TLAS instance from a group's (an instance's custom data is its record).
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index fb79038..948b5e9 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1600,8 +1600,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.)
+ (`finish`'s records are the kernel's 23rd and a frame's camera hits its 24th; the translucency pass, which
+ reads neither, binds group 1 without them, and stays at 29.)
(Hardware traversal no longer binds software traversal's trees, a placeholder there; the light tiles' lists took
the binding.)
@@ -1715,6 +1715,15 @@ 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).
+A live frame is two passes of the kernel. `first_hit` traces every pixel's camera ray, once a frame (one jitter,
+no lens: the frame's samples share it), and leaves the hit (`first_hits`, 32 bytes a traced pixel: distance,
+barycentrics, triangle, instance, part) and its motion vector, which needs no material. `main` starts each path
+from that record and evaluates the surface there once; the guides that need the material (albedo, normal,
+roughness) stay its to write. What needs this frame's depth and motion before the lighting has its place between
+the two. Both layouts; an offline render is one pass. Measured before it was written, twelve heavy clips: the
+split alone +0.4 % of a frame's GPU time, within the runs' spread (two of them +2 %, not explained); with the
+first pass evaluating the surface too, for the guides, +5 %.
+
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.
@@ -2262,7 +2271,7 @@ on the device", and differs where it says so.
| `tables` (4) and, with the 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 of their own (bindings 4 to 6, before #89) and reads them right from `tables` whole; not as the views (above) |
| `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 |
| `vertices` (1), `leaves` (2), `nodes` (3), `prev_verts` (6) | per vertex, per triangle, per node | storage (megabytes) |
- | `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 |
+ | `accum` (11), group 1 (radiance cache, the trace's outputs, a frame's camera hits, `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 1e91511..a6a1873 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -123,7 +123,7 @@ struct Params {
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, glass energy, emitter triangles
word_first: array<vec4<u32>, 2>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, the instances' rows
- live_first: array<vec4<u32>, 2>, // the merged layout: each of group 1's vec4 sections' first vec4 in `ML.vecs` (heap.rs `Live`): cache values (0), refl, motion, direct; lists, -, -, -
+ live_first: array<vec4<u32>, 2>, // the merged layout: each of group 1's vec4 sections' first vec4 in `ML.vecs` (heap.rs `Live`): cache values (0), refl, motion, direct; lists, first hits, (the first hits' vec4s), -
live_len: vec4<u32>, // and the vec4s of refl, motion, direct, lists
};
@@ -3156,6 +3156,8 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
// - direct_out: live deterministic direct light per traced pixel (`dl_det` at the camera hit; w: the light it
// reports, "Light tiles");
// - light_lists: the light tiles' lists, 64 vec4s a tile, as the live pass `light_tiles` made them last frame;
+// - first_hits: a live frame's camera hits, 2 per traced pixel (`first_store`): `first_hit` writes them, `main`
+// starts its paths from them;
// - cache_keys, cache_acc, cache_val: the radiance cache (below, at `cache_on`);
// - loop_guard_trips: the loop guard's count (first word: the invocations a loop of which was stopped).
@if(merged) {
@@ -3175,12 +3177,16 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
fn refl_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[0].y + i]; }
fn refl_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].y + i] = v; }
fn motion_len() -> u32 { return P.live_len.y; }
+ fn motion_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[0].z + i]; }
fn motion_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].z + i] = v; }
fn direct_len() -> u32 { return P.live_len.z; }
fn direct_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[0].w + i]; }
fn direct_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].w + i] = v; }
fn lists_len() -> u32 { return P.live_len.w; }
fn list_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[1].x + i]; }
+ fn first_len() -> u32 { return P.live_first[1].z; }
+ fn first_vec_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[1].y + i]; }
+ fn first_vec_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[1].y + i] = v; }
fn cache_key_load(i: u32) -> u32 { return atomicLoad(&ML.cache_keys[i]); }
fn cache_key_claim(i: u32, k: u32) -> bool { let r = atomicCompareExchangeWeak(&ML.cache_keys[i], 0u, k); return r.exchanged || r.old_value == k; }
fn cache_key_clear(i: u32) { atomicStore(&ML.cache_keys[i], 0u); }
@@ -3203,6 +3209,7 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
fn refl_load(i: u32) -> vec4<f32> { return refl[i]; }
fn refl_store(i: u32, v: vec4<f32>) { refl[i] = v; }
fn motion_len() -> u32 { return arrayLength(&motion_out); }
+ fn motion_load(i: u32) -> vec4<f32> { return motion_out[i]; }
fn motion_store(i: u32, v: vec4<f32>) { motion_out[i] = v; }
fn direct_len() -> u32 { return arrayLength(&direct_out); }
fn direct_load(i: u32) -> vec4<f32> { return direct_out[i]; }
@@ -3224,6 +3231,22 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
// 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;
+ @group(1) @binding(10) var<storage, read_write> first_hits: array<vec4<f32>>;
+ fn first_len() -> u32 { return arrayLength(&first_hits); }
+ fn first_vec_load(i: u32) -> vec4<f32> { return first_hits[i]; }
+ fn first_vec_store(i: u32, v: vec4<f32>) { first_hits[i] = v; }
+}
+
+// A camera hit as the first-hit pass leaves it: (t, u, v, triangle low) (triangle high, instance low, instance high,
+// part). The integers as 16-bit halves: a float keeps those exactly, and its bits are not an integer's to keep.
+fn first_store(pix: u32, h: Hit) {
+ first_vec_store(pix * 2u, vec4<f32>(h.t, h.u, h.v, f32(h.tri & 0xffffu)));
+ first_vec_store(pix * 2u + 1u, vec4<f32>(f32(h.tri >> 16u), f32(h.inst & 0xffffu), f32(h.inst >> 16u), f32(h.part)));
+}
+fn first_load(pix: u32) -> Hit {
+ let a = first_vec_load(pix * 2u);
+ let b = first_vec_load(pix * 2u + 1u);
+ return Hit(a.x, u32(a.w) | (u32(b.x) << 16u), a.y, a.z, u32(b.y) | (u32(b.z) << 16u), u32(b.w));
}
// The loop guard (gpu.rs `loop_guard_of`; docs/RUNTIME.md "The engine in a browser"): every loop of the kernel, the
@@ -3800,20 +3823,52 @@ fn cache_resolve(@builtin(global_invocation_id) gid: vec3<u32>) {
// ------------------------------------------------------------------------------------------------
-@compute @workgroup_size(8, 8, 1)
-fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
+// The camera hit's motion: from the hit point `p` to where that surface point was the previous frame (w = 1), zeros
+// where it stands still.
+fn first_motion(hit: Hit, p: vec3<f32>) -> vec4<f32> {
+ var mv = vec4<f32>(0.0);
+ // A deforming mesh keeps its previous vertices in model space, where its instance's record says.
+ var deforms = false;
+ if (LIVE && P.motion.x > 0.5 && !is_proc(hit) && has(F_INST)) {
+ deforms = has(F_DEFORM) && (bitcast<u32>(instance_at(hit.inst).n1.w) & INST_DEFORMS) != 0u;
+ }
+ if (LIVE && P.motion.x > 0.5 && is_proc(hit)) {
+ // Procedural geometry: its object-space hit point through the previous frame's rows.
+ let r = instance_at(hit.inst);
+ if (any(r.p0 != r.m0) || any(r.p1 != r.m1) || any(r.p2 != r.m2)) {
+ let lp = vec4<f32>(proc_point(r, p), 1.0);
+ mv = vec4<f32>(vec3<f32>(dot(r.p0, lp), dot(r.p1, lp), dot(r.p2, lp)) - p, 1.0);
+ }
+ } else if (LIVE && P.motion.x > 0.5 && has(F_INST)) {
+ // A movable instance: its model-space hit point (the previous pose's for a deforming mesh) through the
+ // previous frame's transform (p rows; the same as m when it did not move).
+ let r = instance_at(hit.inst);
+ if (deforms || any(r.p0 != r.m0) || any(r.p1 != r.m1) || any(r.p2 != r.m2)) {
+ let ix = tri_indices(hit.tri);
+ let now = (ix + vec3<u32>(r.info.z)) * VERTEX_VEC4;
+ var q0 = vertices[now.x].xyz;
+ var q1 = vertices[now.y].xyz;
+ var q2 = vertices[now.z].xyz;
+ // (A deforming mesh's previous positions are where its record says, n2.w, its vertices as the
+ // mesh has them. F_DEFORM: a scene with such a mesh.)
+ if (has(F_DEFORM) && deforms) {
+ let before = (ix + vec3<u32>(bitcast<u32>(r.n2.w))) * VERTEX_VEC4;
+ q0 = prev_verts[before.x].xyz;
+ q1 = prev_verts[before.y].xyz;
+ q2 = prev_verts[before.z].xyz;
+ }
+ let lp = vec4<f32>(q0 + (q1 - q0) * hit.u + (q2 - q0) * hit.v, 1.0);
+ mv = vec4<f32>(vec3<f32>(dot(r.p0, lp), dot(r.p1, lp), dot(r.p2, lp)) - p, 1.0);
+ }
+ }
+ return mv;
+}
+
+// A pixel's camera ray. `cam`: its random numbers (the jitter offline, the lens).
+struct CamRay { o: vec3<f32>, d: vec3<f32> };
+fn camera_ray(gid: vec2<u32>, cam: vec4<f32>) -> CamRay {
let w = P.size.x;
let h = P.size.y;
- if (gid.x >= w || gid.y >= h) { return; }
- let pix = gid.y * w + gid.x;
- // Every pixel's deterministic direct light is written each frame (0 unless the camera hits a surface): a pixel that
- // turned to sky must not keep what a surface left there.
- if (LIVE && P.misc.w < 0.5 && direct_len() >= w * h) { direct_store(pix, vec4<f32>(0.0, 0.0, 0.0, select(0.0, f32(LT_NONE), has(F_LISTS)))); }
- if (has(F_LISTS)) { lt_fb = LT_NONE; }
- rng_start(gid.xy, P.size.z, P.size.w, 0u);
- cur_depth = 0u;
- let cam = rng4(rng_dim(D_CAMERA));
-
// Live: one sub-pixel jitter a frame for the whole image (live/frame.rs: Halton 2, 3), which the temporal upscaler
// resolves (live.wgsl `upscale`). Offline, every sample draws its own.
var jx = cam.x;
@@ -3832,6 +3887,45 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
o += P.cam_right.xyz * (r * cos(phi)) + P.cam_up.xyz * (r * sin(phi));
d = normalize(focus - o);
}
+ return CamRay(o, d);
+}
+
+// A live frame's first pass: every pixel's camera ray, which is the frame's (one jitter, no lens: its samples share
+// it). It leaves the hit for `main`'s paths (`first_hits`) and the hit's motion vector, which needs no material: what
+// runs between the two passes has this frame's depth (the hit's t) and motion.
+@compute @workgroup_size(8, 8, 1)
+fn first_hit(@builtin(global_invocation_id) gid: vec3<u32>) {
+ let w = P.size.x;
+ let h = P.size.y;
+ if (gid.x >= w || gid.y >= h || first_len() < 2u * w * h) { return; }
+ rng_start(gid.xy, P.size.z, P.size.w, 0u);
+ cur_depth = 0u;
+ mirror_path = false;
+ let pix = gid.y * w + gid.x;
+ let cr = camera_ray(gid.xy, rng4(rng_dim(D_CAMERA)));
+ let hit = trace(cr.o, cr.d, INF, TRACE_CLOSEST);
+ first_store(pix, hit);
+ var mv = vec4<f32>(0.0);
+ // (The hit point as `surface` has it.)
+ if (hit.tri != 0xffffffffu) { mv = first_motion(hit, cr.o + cr.d * hit.t); }
+ if (motion_len() >= w * h) { motion_store(pix, select(vec4<f32>(0.0), mv, !non_finite(mv.xyz))); }
+}
+
+@compute @workgroup_size(8, 8, 1)
+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
+ let w = P.size.x;
+ let h = P.size.y;
+ if (gid.x >= w || gid.y >= h) { return; }
+ let pix = gid.y * w + gid.x;
+ // Every pixel's deterministic direct light is written each frame (0 unless the camera hits a surface): a pixel that
+ // turned to sky must not keep what a surface left there.
+ if (LIVE && P.misc.w < 0.5 && direct_len() >= w * h) { direct_store(pix, vec4<f32>(0.0, 0.0, 0.0, select(0.0, f32(LT_NONE), has(F_LISTS)))); }
+ if (has(F_LISTS)) { lt_fb = LT_NONE; }
+ rng_start(gid.xy, P.size.z, P.size.w, 0u);
+ cur_depth = 0u;
+ let cr = camera_ray(gid.xy, rng4(rng_dim(D_CAMERA)));
+ var d = cr.d;
+ var o = cr.o;
var radiance = vec3<f32>(0.0);
var first_t = 0.0;
@@ -3862,7 +3956,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
// The camera hit is transmissive (glass, water): its reflections stay in the specular signal too (the resolve's
// neighbours there mostly went through, so it had no rays to rebuild them from: live glass lost its reflection).
var glass0 = false;
- var mv = vec4<f32>(0.0);
dl_det = vec3<f32>(0.0);
dl_det_spec = vec3<f32>(0.0);
var specular_bounce = true;
@@ -3886,7 +3979,9 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
mirror_path = false;
for (var depth = 0u; depth <= P.counts.z; depth++) {
cur_depth = depth;
- var hit = trace(o, d, INF, TRACE_CLOSEST);
+ // A live frame's camera hit is its first pass's (`first_hit`).
+ var hit = Hit(INF, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);
+ if (LIVE && depth == 0u) { hit = first_load(pix); } else { hit = trace(o, d, INF, TRACE_CLOSEST); }
// Ray tracing off: the camera ray above was the last one traced for this pixel.
if (depth == 0u) { rays_off = LIVE && P.jitter.z > 0.5; }
if (has(F_FOG) && P.fog.x > 0.0) {
@@ -3987,42 +4082,12 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let s = surface(o, d, hit, width);
if (depth == 0u) {
first_t = hit.t;
- let ti = hit.tri;
- // A deforming mesh keeps its previous vertices in model space, where its instance's record says.
- var deforms = false;
- if (LIVE && P.motion.x > 0.5 && !is_proc(hit) && has(F_INST)) {
- deforms = has(F_DEFORM) && (bitcast<u32>(instance_at(hit.inst).n1.w) & INST_DEFORMS) != 0u;
- }
- if (LIVE && P.motion.x > 0.5 && is_proc(hit)) {
- // Procedural geometry: its object-space hit point through the previous frame's rows.
- let r = instance_at(hit.inst);
- if (any(r.p0 != r.m0) || any(r.p1 != r.m1) || any(r.p2 != r.m2)) {
- let lp = vec4<f32>(proc_point(r, s.p), 1.0);
- mv = vec4<f32>(vec3<f32>(dot(r.p0, lp), dot(r.p1, lp), dot(r.p2, lp)) - s.p, 1.0);
- }
- } else if (LIVE && P.motion.x > 0.5 && has(F_INST)) {
- // A movable instance: its model-space hit point (the previous pose's for a deforming mesh) through the
- // previous frame's transform (p rows; the same as m when it did not move).
- let r = instance_at(hit.inst);
- if (deforms || any(r.p0 != r.m0) || any(r.p1 != r.m1) || any(r.p2 != r.m2)) {
- let ix = tri_indices(ti);
- let now = (ix + vec3<u32>(r.info.z)) * VERTEX_VEC4;
- var q0 = vertices[now.x].xyz;
- var q1 = vertices[now.y].xyz;
- var q2 = vertices[now.z].xyz;
- // (A deforming mesh's previous positions are where its record says, n2.w, its vertices as the
- // mesh has them. F_DEFORM: a scene with such a mesh.)
- if (has(F_DEFORM) && deforms) {
- let before = (ix + vec3<u32>(bitcast<u32>(r.n2.w))) * VERTEX_VEC4;
- q0 = prev_verts[before.x].xyz;
- q1 = prev_verts[before.y].xyz;
- q2 = prev_verts[before.z].xyz;
- }
- let lp = vec4<f32>(q0 + (q1 - q0) * hit.u + (q2 - q0) * hit.v, 1.0);
- mv = vec4<f32>(vec3<f32>(dot(r.p0, lp), dot(r.p1, lp), dot(r.p2, lp)) - s.p, 1.0);
- }
+ if (has(F_LISTS)) {
+ // (Where the hit was the previous frame: the first pass's motion vector.)
+ var before = s.p;
+ if (LIVE && motion_len() >= w * h) { before += motion_load(pix).xyz; }
+ lt_list_start(before);
}
- if (has(F_LISTS)) { lt_list_start(s.p + mv.xyz); }
albedo = select(s.base, s.emissive / max(max(s.emissive.r, max(s.emissive.g, s.emissive.b)), 1e-6), s.card);
normal = s.n;
anim = s.anim;
@@ -4202,9 +4267,6 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
if (non_finite(dropped)) { dropped = vec3<f32>(0.0); }
spec = clamp(spec, vec3<f32>(0.0), max(radiance - e0, vec3<f32>(0.0)));
let diff = max(radiance - e0 - spec - dropped, vec3<f32>(0.0));
- if (P.misc.w < 0.5 && motion_len() >= w * h) {
- motion_store(pix, select(vec4<f32>(0.0), mv, !non_finite(mv.xyz)));
- }
if (P.motion.y > 0.5 && P.misc.w < 0.5 && resolve_bound()) {
// The reconstruction consumes the noisy path itself. Its material guides reuse the idle ray slots.
refl_store(pix * 2u, vec4<f32>(guide_diffuse, guide_glass.x));
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index e54e913..a9bd9c0 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -321,7 +321,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::{DEFERRED_BINDING, GUARD_BINDING, LISTS_BINDING, LIVE_BINDING, TABLE_VIEWS};
+ use crate::merged::{DEFERRED_BINDING, FIRST_BINDING, GUARD_BINDING, LISTS_BINDING, LIVE_BINDING, TABLE_VIEWS};
let LayoutShape { hwrt, merged, whole_tables, guard } = shape;
let (read, write) = (storage_buffer(true), storage_buffer(false));
// Group 0: the parameters; the vertices; the tables' heap, the words' heap; the previous frame's vertices of
@@ -353,8 +353,8 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupL
scene.push(layout_entry(ACC_BINDING, ACCELERATION_STRUCTURE));
}
// Group 1: 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, 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).
+ // direct light, the pixels left for `finish`, a frame's camera hits, 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![];
if merged {
live.push(layout_entry(LIVE_BINDING, write));
@@ -362,6 +362,7 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupL
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));
+ live.push(layout_entry(FIRST_BINDING, write));
if guard {
live.push(layout_entry(GUARD_BINDING, write));
}
@@ -1575,6 +1576,9 @@ pub struct KernelBufs {
pub motion: Buf,
pub direct: Buf,
pub lists: Buf,
+ /// A live frame's camera hits, 32 bytes a traced pixel (pathtrace.wgsl `first_store`): its first pass writes them,
+ /// its paths start from them.
+ pub first: 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>,
@@ -1586,35 +1590,35 @@ pub struct KernelBufs {
}
impl KernelBufs {
- /// Each in a buffer of its own: the live passes' four of these bytes, made (and `deferred` of one record: its view
- /// makes it for what it traces), with this radiance cache and loop guard's count.
- fn separate(d: &wgpu::Device, cache: CacheBuffers, guard: Option<Buf>, refl: u64, motion: u64, direct: u64, lists: u64) -> KernelBufs {
- 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 }));
- KernelBufs { cache, 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 }
+ /// Each in a buffer of its own: a view's five of these bytes (`VIEW_BUFFERS`), made (and `deferred` of one
+ /// record: its view makes it for what it traces), with this radiance cache and loop guard's count.
+ fn separate(d: &wgpu::Device, cache: CacheBuffers, guard: Option<Buf>, view: [u64; 5]) -> KernelBufs {
+ let sb = |k: usize| Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some(VIEW_BUFFERS[k]), size: view[k], usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }));
+ KernelBufs { cache, refl: sb(0), motion: sb(1), direct: sb(2), lists: sb(3), first: sb(4), deferred: Some(deferred_buffer(d, 1)), guard, merged: None }
}
- /// These for a view of another size: the four that follow the size made again, the radiance cache and the loop
+ /// These for a view of another size: the five that follow the size made again, the radiance cache and the loop
/// guard's count kept. The merged layout's are one buffer: all of it made again, the cache (as long) empty.
- pub fn resized(&self, d: &wgpu::Device, refl: u64, motion: u64, direct: u64, lists: u64) -> KernelBufs {
+ pub fn resized(&self, d: &wgpu::Device, view: [u64; 5]) -> KernelBufs {
match self.merged {
- Some(_) => KernelBufs::new(d, true, true, self.cache.val.size / 32, refl, motion, direct, lists),
- None => KernelBufs::separate(d, self.cache.clone(), self.guard.clone(), refl, motion, direct, lists),
+ Some(_) => KernelBufs::new(d, true, true, self.cache.val.size / 32, view),
+ None => KernelBufs::separate(d, self.cache.clone(), self.guard.clone(), view),
}
}
- /// For a cache of `entries` and the live passes' four of these bytes.
+ /// For a cache of `entries` and a view's five of these bytes (`VIEW_BUFFERS`).
/// `guard`: the layout as written has the guard's count (`Gpu::guard_room`).
- pub fn new(d: &wgpu::Device, merged: bool, guard: bool, entries: u64, refl: u64, motion: u64, direct: u64, lists: u64) -> KernelBufs {
+ pub fn new(d: &wgpu::Device, merged: bool, guard: bool, entries: u64, view: [u64; 5]) -> KernelBufs {
if !merged {
let guard = guard.then(|| Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard"), size: crate::merged::GUARD_WORDS as u64 * 4, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false })));
- return KernelBufs::separate(d, CacheBuffers::new(d, entries), guard, refl, motion, direct, lists);
+ return KernelBufs::separate(d, CacheBuffers::new(d, entries), guard, view);
}
// (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 bytes = live_sizes(entries, view);
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), deferred: None, 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), first: b(Live::First), 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
@@ -1622,7 +1626,7 @@ impl KernelBufs {
pub fn place(&self, p: &mut Params) {
let Some(heap) = &self.merged else { return };
let first = |s: Live| ((heap.at(s) - heap.at(Live::CacheVal)) / 16) as u32;
- p.live_first = [[first(Live::CacheVal), first(Live::Refl), first(Live::Motion), first(Live::Direct)], [first(Live::Lists), 0, 0, 0]];
+ p.live_first = [[first(Live::CacheVal), first(Live::Refl), first(Live::Motion), first(Live::Direct)], [first(Live::Lists), first(Live::First), (self.first.size / 16) as u32, 0]];
p.live_len = [&self.refl, &self.motion, &self.direct, &self.lists].map(|b| (b.size / 16) as u32);
}
}
@@ -1632,17 +1636,22 @@ 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 kernel's buffers that follow a view's size, in the order their bytes are given: the specular-lobe rays, the
+/// motion vectors, the direct light, the light tiles' lists, the camera hits.
+pub const VIEW_BUFFERS: [&str; 5] = ["refl", "motion", "direct", "light lists", "first hits"];
+
/// 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
+/// `entries` long and a view's five 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`).
-pub(crate) fn live_sizes(entries: u64, refl: u64, motion: u64, direct: u64, lists: u64) -> [u64; 8] {
- [CACHE_SIZE * 4, CACHE_SIZE * 32, crate::merged::GUARD_WORDS as u64 * 4, entries * 32, refl, motion, direct, lists]
+pub(crate) fn live_sizes(entries: u64, view: [u64; 5]) -> [u64; 9] {
+ [CACHE_SIZE * 4, CACHE_SIZE * 32, crate::merged::GUARD_WORDS as u64 * 4, entries * 32, view[0], view[1], view[2], view[3], view[4]]
}
/// Group-1 bind group of the kernel: the radiance cache and the reflection resolve's inputs (`KernelBufs`); in the
/// merged layout, the one buffer.
-/// `deferred`: with `finish`'s records (`live_layout`; the translucency pass's `tl_live_layout` is without).
-pub fn live_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, b: &KernelBufs, deferred: bool) -> wgpu::BindGroup {
+/// `paths`: with what the paths' passes alone use, `finish`'s records and the camera hits (`live_layout`; the
+/// translucency pass's `tl_live_layout` is without).
+pub fn live_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, b: &KernelBufs, paths: bool) -> wgpu::BindGroup {
fn e(binding: u32, b: &Buf) -> wgpu::BindGroupEntry<'_> {
wgpu::BindGroupEntry { binding, resource: b.binding() }
}
@@ -1650,7 +1659,8 @@ pub fn live_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, b: &Ker
Some(heap) => d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("live"), layout, entries: &[wgpu::BindGroupEntry { binding: crate::merged::LIVE_BINDING, resource: heap.buffer.as_entire_binding() }] }),
None => {
let mut entries = vec![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.deferred.as_ref().filter(|_| paths).map(|r| e(crate::merged::DEFERRED_BINDING, r)));
+ entries.extend(paths.then(|| e(crate::merged::FIRST_BINDING, &b.first)));
entries.extend(b.guard.as_ref().map(|g| e(crate::merged::GUARD_BINDING, g)));
d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("live"), layout, entries: &entries })
}
@@ -2167,12 +2177,12 @@ impl Gpu {
layout_entry(6, storage_buffer(true)),
],
});
- let no_live_bufs = KernelBufs::new(&device, merged, guard_room(hwrt), 1, 64, 64, 64, 64);
+ let no_live_bufs = KernelBufs::new(&device, merged, guard_room(hwrt), 1, [64; 5]);
let no_live = live_bind_group(&device, &live_layout, &no_live_bufs, true);
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout), Some(&live_layout)], immediate_size: 0 });
let (tl_layout, tl_pipeline_layout, tl_live_layout, no_live_tl) = if hwrt {
let l = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("translucent"), entries: &tl_entries });
- let tl_vis: Vec<_> = live_entries.iter().filter(|e| merged || e.binding != crate::merged::DEFERRED_BINDING).copied().collect();
+ let tl_vis: Vec<_> = live_entries.iter().filter(|e| merged || ![crate::merged::DEFERRED_BINDING, crate::merged::FIRST_BINDING].contains(&e.binding)).copied().collect();
let vl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("live, 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 = live_bind_group(&device, &vl, &no_live_bufs, false);
@@ -2236,8 +2246,9 @@ impl Gpu {
self.kernel_passes.lock().unwrap().keys().map(|k| k.2).collect()
}
- /// 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).
+ /// A live pass of a scene's kernel variant beside `main`: `first_hit` (the frame's camera rays, before its paths),
+ /// `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 (p, made) = self.maker().pass(k, entry, self.cache());
if made {
diff --git a/renderer/src/heap.rs b/renderer/src/heap.rs
index ab3a0cd..3dcb6d6 100644
--- a/renderer/src/heap.rs
+++ b/renderer/src/heap.rs
@@ -92,7 +92,7 @@ impl Section for Stream {
/// `MergedLive`, whose members are where these sections are: a test holds it). The radiance cache's keys and sums
/// and the loop guard's count, atomic words at fixed places; then the vec4 arrays, the sections of the struct's last
/// member: the cache's values, what the live passes read of a trace (the specular-lobe rays, the motion vectors, the
-/// direct light), the light tiles' lists.
+/// direct light), the light tiles' lists, a frame's camera hits.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Live {
CacheKeys,
@@ -103,10 +103,11 @@ pub enum Live {
Motion,
Direct,
Lists,
+ First,
}
impl Section for Live {
- const COUNT: usize = 8;
+ const COUNT: usize = 9;
const UNIT: u64 = 4;
const LABEL: &'static str = "live";
fn index(self) -> usize {
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index cce6d41..cf55470 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -117,7 +117,7 @@ impl LiveCore {
return;
}
// (What a frame asks: as the load makes them, and the guides and the translucency pass where it has them.)
- let mut passes: Vec<&'static str> = vec![];
+ let mut passes: Vec<&'static str> = vec!["first_hit"];
if !self.g.merged {
passes.push("finish");
}
@@ -289,6 +289,8 @@ impl LiveCore {
let media_composite = media.then(|| g.kernel_pass(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(kernel, "finish"), d));
+ // The frame's camera rays, before its paths (pathtrace.wgsl `first_hit`).
+ let first = g.kernel_pass(kernel, "first_hit");
// This frame's sub-pixel jitter (Halton 2, 3), every camera ray'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.
@@ -393,9 +395,14 @@ impl LiveCore {
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, &[]);
+ // (The frame's samples share its camera hits.)
+ if k == 0 {
+ pass.set_pipeline(&first);
+ pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);
+ }
+ pass.set_pipeline(&pipeline);
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 {
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index a0f4f20..8eb0699 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -4917,3 +4917,51 @@ fn models_with_functions_the_scene_has_come_in_place() {
w.set_transform(33, Vec3::new(-0.2, -0.5, 1.1), glam::Quat::IDENTITY, Vec3::splat(0.5)).unwrap();
check("a model with a function that came in the same commit", &mut live, &mut w);
}
+
+/// A live frame's first pass leaves each pixel's camera hit and its paths start from it. On a ball of 80,000
+/// triangles (a triangle's index past 16 bits) the distance the first pass wrote is to the point the normal the
+/// paths wrote names, the instance is the ball's, and the samples hold the same distance; a pixel of sky holds a miss.
+#[test]
+fn the_first_pass_leaves_the_camera_hits() {
+ let (mut w, r, n, at, eye) = (world(), 0.5f32, 200u32, Vec3::new(0.3, -0.2, 2.5), Vec3::new(0.0, 0.0, 5.0));
+ let mut g = Geometry { positions: vec![], normals: vec![], uvs: vec![], indices: vec![], groups: vec![], colors: vec![] };
+ // (Open at the poles: no triangle without area.)
+ for (j, i) in (0..=n).flat_map(|j| (0..=n).map(move |i| (j, i))) {
+ let (th, ph) = (0.05 + (std::f32::consts::PI - 0.1) * j as f32 / n as f32, std::f32::consts::TAU * i as f32 / n as f32);
+ let d = Vec3::new(th.sin() * ph.cos(), th.cos(), th.sin() * ph.sin());
+ g.positions.extend((d * r).to_array());
+ g.normals.extend(d.to_array());
+ g.uvs.extend([0.0, 0.0]);
+ }
+ for a in (0..n).flat_map(|j| (0..n).map(move |i| j * (n + 1) + i)) {
+ g.indices.extend([a, a + 1, a + n + 1, a + 1, a + n + 2, a + n + 1]);
+ }
+ w.set_geometry(30, g).unwrap();
+ w.set_object(30, "ball".into(), None, Kind::Mesh { geometry: 30, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(30, at, glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let presets = crate::default_presets_dir();
+ let mut live = match gpu::Gpu::new().and_then(|g| LiveCore::new(g, &w, Path::new("."), &presets, 96, 54)) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ live.render(1, |_, _| {});
+ let (iw, ih) = live.internal_size();
+ let pixels = (iw * ih) as u64;
+ let ball = live.sc.tables.retained.instance(30).expect("the ball is an instance").instance;
+ let f = &live.targets.kernel.first;
+ let hits: Vec<[f32; 8]> = read_back(&live, &f.buffer, f.offset, pixels * 32);
+ let samples: Vec<[f32; 20]> = read_back(&live, &live.targets.accum, 0, pixels * gpu::SAMPLE_BYTES);
+ // (pathtrace.wgsl `first_store`: t, u, v, then the triangle, the instance and the part as 16-bit halves.)
+ let (tri, inst) = (|h: &[f32; 8]| h[3] as u32 | (h[4] as u32) << 16, |h: &[f32; 8]| h[5] as u32 | (h[6] as u32) << 16);
+ let on: Vec<usize> = (0..pixels as usize).filter(|&k| inst(&hits[k]) == ball && tri(&hits[k]) != u32::MAX).collect();
+ assert!(on.len() > 200 && on.iter().any(|&k| tri(&hits[k]) >= 1 << 16), "{} pixels on the ball, the last triangle {:?}", on.len(), on.iter().map(|&k| tri(&hits[k])).max());
+ for &k in &on {
+ let (t, normal) = (hits[k][0], Vec3::new(samples[k][8], samples[k][9], samples[k][10]));
+ let to = (at + normal * r - eye).length();
+ assert!((to - t).abs() < 2e-3 && hits[k][1] >= 0.0 && hits[k][2] >= 0.0 && hits[k][1] + hits[k][2] <= 1.0 + 1e-5, "pixel {k}: hit {:?}, its normal {normal} names a point {to} away", hits[k]);
+ assert_eq!(samples[k][3].to_bits(), t.to_bits(), "pixel {k}: the samples' distance is the hit's");
+ }
+ // (No sky in this world: a ray past everything misses.)
+ let missed = hits.iter().filter(|h| tri(h) == u32::MAX).count();
+ assert!(missed > 200 && hits.iter().filter(|h| tri(h) == u32::MAX).all(|h| inst(h) == u32::MAX), "{missed} pixels of nothing, each a miss whole");
+}
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 0b4663b..87d4936 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -244,6 +244,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
let codes_sent: Vec<u32> = prep.gpu_emitter_tris.iter().map(|t| t.code).collect();
let up = g.upload(&sc, &targets.accum, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, 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
+ let _ = g.kernel_pass(&up.kernel, "first_hit");
if !g.merged {
let _ = g.kernel_pass(&up.kernel, "finish");
}
diff --git a/renderer/src/live/targets.rs b/renderer/src/live/targets.rs
index 07dc721..8c401cb 100644
--- a/renderer/src/live/targets.rs
+++ b/renderer/src/live/targets.rs
@@ -108,11 +108,10 @@ pub struct Targets {
size: (u32, u32),
}
-/// What a view of `w` x `h` holds of each of the kernel's four buffers that follow its size, bytes (`gpu::KernelBufs`:
-/// the specular rays, the motion vectors, the direct light, the light tiles' lists).
-fn kernel_bytes(w: u32, h: u32) -> [u64; 4] {
+/// What a view of `w` x `h` holds of each of the kernel's buffers that follow its size, bytes (`gpu::VIEW_BUFFERS`).
+fn kernel_bytes(w: u32, h: u32) -> [u64; 5] {
let n = (w * h) as u64;
- [n * 32, n * 16, n * 16, layout::light_lists(w, h) as u64 * 16]
+ [n * 32, n * 16, n * 16, layout::light_lists(w, h) as u64 * 16, n * 32]
}
impl Targets {
@@ -136,13 +135,12 @@ impl Targets {
wgpu::Extent3d { width: LUT, height: LUT, depth_or_array_layers: LUT },
);
let (bufs, out) = Self::own(d, w, h);
- let [refl, motion, direct, lists] = kernel_bytes(w, h);
let mut t = Targets {
params: d.create_buffer(&wgpu::BufferDescriptor { label: Some("live params"), size: std::mem::size_of::<LiveParams>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }),
accum: g.accum_buffer(w, h),
bufs,
out,
- kernel: gpu::KernelBufs::new(d, g.merged, g.guard_room(), cache, refl, motion, direct, lists),
+ kernel: gpu::KernelBufs::new(d, g.merged, g.guard_room(), cache, kernel_bytes(w, h)),
translucent_low: None,
lut_view: lut_tex.create_view(&Default::default()),
lut_tex,
@@ -162,8 +160,7 @@ impl Targets {
let d = &g.device;
(self.bufs, self.out) = Self::own(d, w, h);
self.accum = g.accum_buffer(w, h);
- let [refl, motion, direct, lists] = kernel_bytes(w, h);
- self.kernel = self.kernel.resized(d, refl, motion, direct, lists);
+ self.kernel = self.kernel.resized(d, kernel_bytes(w, h));
self.translucent_low = None;
self.size = (w, h);
self.bgs = self.bind_groups(d, passes);
diff --git a/renderer/src/merged.rs b/renderer/src/merged.rs
index f7b2c75..0a845a4 100644
--- a/renderer/src/merged.rs
+++ b/renderer/src/merged.rs
@@ -41,6 +41,9 @@ 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;
+/// A live frame's camera hits (`gpu::KernelBufs::first`; pathtrace.wgsl `first_hits`) in the layout as written; in
+/// the merged one a section (`heap::Live::First`).
+pub const FIRST_BINDING: u32 = 10;
#[cfg(test)]
mod tests {
@@ -78,18 +81,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 22 (20 under hardware traversal, which has neither of the trees' buffers). Because the merged
+ /// The layout as written has 23 (21 under hardware traversal, which has neither of the trees' buffers). 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, 22, "the kernel as written");
+ assert_eq!(declared, 23, "the kernel as written");
// (`main` no longer adds to the cache's sums: `finish` trains it. Without units it reads no node.)
assert_eq!(used.iter().map(|u| u.1).max(), Some(20), "{used:?}");
let hw = kernel_wgsl(&kernel_template(), &KernelVariant::new(true, Default::default(), 0));
- assert_eq!(hw.matches("var<storage").count(), 20 + 4, "hardware traversal: neither of the trees' buffers (and the translucency pass's four)");
+ assert_eq!(hw.matches("var<storage").count(), 21 + 4, "hardware traversal: neither of the trees' buffers (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'");
@@ -97,11 +100,14 @@ mod tests {
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:?}");
- let read = if features & crate::gpu::F_UNITS != 0 { 8 } else { 7 };
- assert_eq!(used.iter().find(|u| u.0 == "main").map(|u| u.1), Some(read), "the trace reads all eight a page has with units (the trees' leaves the eighth), no tree without");
+ // (With units the paths and the first pass each read seven of the eight a page has. The paths leave out
+ // the previous frame's vertices, the first pass's for its motion vectors; the first pass, the samples.)
+ let units = (features & crate::gpu::F_UNITS != 0) as usize;
+ let of = |pass: &str| used.iter().find(|u| u.0 == pass).map(|u| u.1);
+ assert_eq!((of("main"), of("first_hit")), (Some(6 + units), Some(5 + 2 * units)), "features {features:#x}");
assert_eq!(declared, 8, "features {features:#x}");
// The struct's members are the first sections; its last, the vec4s, begins where the cache's values do.
- let (at, _) = crate::heap::Heap::<crate::heap::Live>::starts_for(&crate::gpu::live_sizes(1, 64, 64, 64, 64));
+ let (at, _) = crate::heap::Heap::<crate::heap::Live>::starts_for(&crate::gpu::live_sizes(1, [64; 5]));
assert_eq!(layout(&m, "MergedLive").0, at[..4]);
}
}
@@ -142,6 +148,7 @@ mod tests {
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;")));
+ assert!(kernel_template().contains(&format!("@group(1) @binding({FIRST_BINDING}) var<storage, read_write> first_hits: array<vec4<f32>>;")));
// 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]); }"));
@@ -173,8 +180,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: the guard's count and `finish`'s records too. Merged: the eight a page has.)
- assert_eq!(declared as u32, if merged { 8 } else { 23 }, "{used:?}");
+ // (As written: the guard's count, `finish`'s records and the camera hits too. Merged: the eight a page has.)
+ assert_eq!(declared as u32, if merged { 8 } else { 24 }, "{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.