From f43de95bb6b98f3ac83101ff55cda424139f52f6 Mon Sep 17 00:00:00 2001 From: yujiaxu Date: Fri, 4 Dec 2026 15:15:41 +0800 Subject: [PATCH 1/2] The output is composed from guides of its own Under a render scale of 1 the frame has two grids. The kernel's `guides` pass traces the camera's ray for every output pixel each frame, at one of eight places in the pixel: the surface's distance, colour and normal, and the light that is the pixel's own (what it sees directly, and the directional lights' direct light with a shadow ray). The traced grid keeps the lighting, its samples at their pixels' centres: the frame's jitter moved every traced sample over its pixel, a sample changed surface at an edge and texel under a normal map, and its histories started again each time. - `gcompose` gives an output pixel the denoised irradiance and specular light of the traced samples on its surface, times its colour, plus its light. `gupscale` keeps the output's history; `track`, `judge` and `reject` judge it as they judge the upscaler's. - A thing thinner than two output pixels that a guide saw is recorded with its distance and its place, and `gcarry` takes the record on by the two cameras while the guides of the frames after miss it (`Thin`): the history moves with the thing, is spared the clamp in motion, and is dropped where the thing has gone on. - Reconstruction `builtin` (the default) is this where the traced grid is coarser than the output. `builtin-upscaler` is the frame as it was, and what `builtin` runs at scale 1 and in a diagnostic view. - The guides and a medium's record lie after the traced pixels' direct light in the kernel's direct buffer, which grows the first time a frame composes its output. - A render test may name a render scale and a reconstruction method. Three of the upscaler's tests run at half scale too; a unit test holds a first frame's texture to the output's resolution under both kinds of light. Co-Authored-By: Claude Fable 5.2 --- README.md | 4 +- docs/RUNTIME.md | 38 +- packages/scene/src/rendering.ts | 5 +- renderer/shaders/live.wgsl | 382 +++++++++++++++++- renderer/shaders/pathtrace.wgsl | 171 +++++++- renderer/src/gpu.rs | 20 + renderer/src/live/frame.rs | 92 ++++- renderer/src/live/inplace_tests.rs | 82 +++- renderer/src/live/layout.rs | 10 + renderer/src/live/mod.rs | 31 +- renderer/src/live/reconstruction.rs | 24 +- renderer/src/live/targets.rs | 22 +- .../compose-dimming-behind-edge-live.ts | 14 + tests/render/compose-lamps-parallax-live.ts | 17 + tests/render/compose-lamps-still-live.ts | 14 + tests/render/lib.ts | 4 + tools/test-render.ts | 2 +- 17 files changed, 868 insertions(+), 64 deletions(-) create mode 100644 tests/render/compose-dimming-behind-edge-live.ts create mode 100644 tests/render/compose-lamps-parallax-live.ts create mode 100644 tests/render/compose-lamps-still-live.ts diff --git a/README.md b/README.md index 33aaac97..e8fb5002 100644 --- a/README.md +++ b/README.md @@ -153,8 +153,8 @@ node tools/three/open.ts scenes/bistro.ts # the same scene in three.js, in your In the window: drag to orbit, right-drag to pan, wheel to zoom, WASD/QE to fly, `R` to reset, `P` for a snapshot. `play` and `live` take `--quality` (`auto`, `native`, `quality`, `balanced`, `performance`, `ultra-performance`), -`--reconstruction` (`builtin`, `auto`, an upscaler: `fsr`, `metalfx`, `dlss`; a joint denoiser: `metalfx-denoised`, -`dlss-rr`; or a list in order of preference) and `--latency`. FSR 1 also runs on WebGPU; DLSS requires an opt-in NVIDIA +`--reconstruction` (`builtin`, `builtin-upscaler`, `auto`, an upscaler: `fsr`, `metalfx`, `dlss`; a joint denoiser: +`metalfx-denoised`, `dlss-rr`; or a list in order of preference) and `--latency`. FSR 1 also runs on WebGPU; DLSS requires an opt-in NVIDIA SDK build; MetalFX requires supported Apple hardware. See [live rendering settings and the TypeScript API](docs/RUNTIME.md#live-rendering-settings). diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md index 956c716a..7d649555 100644 --- a/docs/RUNTIME.md +++ b/docs/RUNTIME.md @@ -1883,7 +1883,7 @@ between what a frame affords and what is shown (renderer/src/live/rendering.rs): | setting | the gap | ThreeRT's own | vendor technology it maps | |---|---|---|---| | `quality` | rays: the render resolution every later stage works from | dynamic resolution | (a budget, not a technique) | -| `reconstruction` | noise, then pixels | denoiser + temporal upscaler | DLSS SR / RR, MetalFX, FSR, XeSS | +| `reconstruction` | noise, then pixels | denoiser + the output composed from its own guides, or a temporal upscaler | DLSS SR / RR, MetalFX, FSR, XeSS | | `frameGeneration` | frames shown per frame rendered | none | DLSS FG, FSR FG, XeSS FG, MetalFX frame interpolation (none integrated yet) | | `latency` | input to photon | one frame queued instead of two | Reflex, Anti-Lag 2, XeLL | @@ -1911,7 +1911,8 @@ provider, which read different signals: | `--reconstruction` | denoise | upscale | |---|---|---| -| `builtin` (default) | ThreeRT | ThreeRT (temporal) | +| `builtin` (default) | ThreeRT | ThreeRT: the output composed from guides of its own (below) | +| `builtin-upscaler` | ThreeRT | ThreeRT's temporal upscaler (what `builtin` runs at scale 1) | | `fsr` | ThreeRT | AMD FidelityFX Super Resolution **1** (spatial EASU + RCAS; also on WebGPU) | | `metalfx` | ThreeRT | Apple's temporal scaler (macOS 13+, iOS 16+) | | `dlss` | ThreeRT | NVIDIA DLSS Super Resolution; DLAA at scale 1 (x86-64 Windows/Linux, RTX on Vulkan, feature `dlss`) | @@ -1923,8 +1924,9 @@ provider, which read different signals: A list (`dlss-rr,dlss,fsr`) is an order of preference; `builtin` ends every list. `quality` presets are the vendors' ratios exactly (`ultra-performance` is a third: 640 pixels across 1080p, the smallest input DLSS takes, where a typed -`--scale 0.333` gives 639 and DLSS reports itself unsupported). Diagnostic views use `builtin`. A provider that -fails while encoding a frame falls back to `builtin` from that frame on. +`--scale 0.333` gives 639 and DLSS reports itself unsupported). Diagnostic views use `builtin` (they show the traced +grid's buffers, through the upscaler's passes). A provider that fails while encoding a frame falls back to `builtin` +from that frame on. A provider says which render scales it takes (`scale_range`: MetalFX scales its output up to 3x the input, so a third and up; DLSS from its modes' input ranges). Under dynamic resolution (`quality: auto`) the governor does not go below @@ -1932,6 +1934,34 @@ the range of the method that runs, nor below that of the first method asked for it goes up to it, and from there the method runs. (A 2560 x 1440 view that dynamic resolution held at a quarter never ran MetalFX before.) +### ThreeRT's own: the output composed from its guides + +Under a render scale of 1 a frame has two grids, and `builtin` gives each what it is for (live/frame.rs `decoupled`): + +- **The output grid has the camera's rays.** Every frame the kernel's `guides` pass traces the camera's ray for + every *output* pixel, at the frame's place in the pixel (8 places): the surface's distance, colour and normal, and + the light that is the pixel's own (what it sees directly, a sky, the directional lights' direct light with their + shadow ray). A mirror's pixel has the surface it shows. +- **The traced grid has the lighting.** Its samples stand at their pixels' centres (no jitter), so each keeps one + surface, and one texel of it, while the camera holds still, and the denoisers' histories are of one place. +- **`gcompose`** gives each output pixel the denoised irradiance and specular light of the traced samples around it + that lie on its surface (by its plane and its normal), times its own colour, plus its own light, behind the medium + the traced samples' rays were marched through. +- **`gupscale`** keeps the output's history: a frame counts by where its guide lay in the pixel at rest and whole + when the pixel moves; `track`, `judge` and `reject` judge the history as they judge the upscaler's. +- **Thin things** (live.wgsl `Thin`): a thing thinner than two output pixels that a guide saw is recorded with its + distance and carried by the two cameras while the guides of the frames after miss it (`gcarry`): its light goes + with it and not with what is behind it, and is not cut by the clamp in motion. + +`builtin-upscaler` is the frame as it was before: the camera's rays at the render resolution alone, one jitter for +every ray, and the temporal upscaler (`judge`, `reject`, `upscale`, the thin features' locks). At scale 1 the two +grids are one and `builtin` runs those passes too. Both run with ray queries and with software traversal. + +What it costs is the guides: a camera ray an output pixel (Bistro at 1280 × 720 and half resolution on an M4: 3.3 ms +of a frame of 20.5; the output's passes take 1.7 ms where the upscaler's took 0.8), and 60 bytes an output pixel more +of buffers (the guides 32, the composition 16, the thin things' records 12; 16 more where the scene has media: 55 MB +at 1280 × 720). docs/ROADMAP.md § 1a has what it gives for that. + ### TypeScript ```ts diff --git a/packages/scene/src/rendering.ts b/packages/scene/src/rendering.ts index 06893d11..5c4ed2ae 100644 --- a/packages/scene/src/rendering.ts +++ b/packages/scene/src/rendering.ts @@ -3,7 +3,8 @@ * src/live/rendering.rs has the whole table): * * - `quality`: how many rays, as the render resolution (`"auto"`: dynamic resolution). - * - `reconstruction`: the noise and the missing pixels. ThreeRT's own denoiser and upscaler (`"builtin"`), an upscaler + * - `reconstruction`: the noise and the missing pixels. ThreeRT's own denoiser, and the output composed from the + * camera's rays for every output pixel (`"builtin"`) or its temporal upscaler (`"builtin-upscaler"`); an upscaler * that replaces only the upscaling (`"dlss"`, `"metalfx"`, `"fsr"`), or a joint denoiser that replaces both and * reads the noisy signal itself (`"dlss-rr"`, `"metalfx-denoised"`). A list is an order of preference. * - `frameGeneration`: frames shown per frame rendered (none is integrated yet: it reports itself unavailable). @@ -14,7 +15,7 @@ */ /** One way of reconstructing the frame. `custom:` names a provider the embedding renderer registered. */ -export type ReconstructionMethod = "builtin" | "off" | "fsr" | "metalfx" | "metalfx-denoised" | "dlss" | "dlss-rr" | `custom:${string}`; +export type ReconstructionMethod = "builtin" | "builtin-upscaler" | "off" | "fsr" | "metalfx" | "metalfx-denoised" | "dlss" | "dlss-rr" | `custom:${string}`; export type ReconstructionRequest = "auto" | ReconstructionMethod | readonly ReconstructionMethod[]; export type QualityRequest = "auto" | "native" | "quality" | "balanced" | "performance" | "ultra-performance" | number; export type FrameGenerationRequest = "off" | "auto" | "2x" | "3x" | "4x"; diff --git a/renderer/shaders/live.wgsl b/renderer/shaders/live.wgsl index 79b09e89..453335f3 100644 --- a/renderer/shaders/live.wgsl +++ b/renderer/shaders/live.wgsl @@ -33,8 +33,8 @@ struct LiveParams { lb: vec4, // local exposure's wide blur of log luminance: weight of level 0..3 lb2: vec4, // of level 4, 5; its wide Gaussian's weight, 1 / (2 sigma^2) dof: vec4, // depth of field: CoC radius of infinity (output px; 0 = off), focus distance (m), max radius (px), - - jit: vec4, // this frame's sub-pixel jitter (every traced sample's: x, y in 0 .. 1 of a traced pixel), -, - - state: vec4, // which half of the lasting buffers is this frame's (0 / 1; `this_half`), -, -, - + jit: vec4, // this frame's sub-pixel jitter (every traced sample's: x, y in 0 .. 1 of a traced pixel); the output grid's guides' (z, w in 0 .. 1 of an output pixel: `gcompose`) + state: vec4, // which half of the lasting buffers is this frame's (0 / 1; `this_half`), the output grid is composed from its own guides (1; `gcompose`, `gupscale`), the scene has media the camera's rays are marched through (1), the previous frame's output was composed so too (1: `Thin`'s records of it are there) lt: vec4, // the light tiles (`light_tiles`): this frame's grid offset x, y (traced pixels), -, tiles a row }; // (`Pixel`, a sample of the trace: records.wgsl, a part of this module. normal.w: `medium_tr`, `medium_share`.) @@ -120,6 +120,13 @@ struct LiveParams { // both are ranges of one buffer, which a pass uses one way), and the tiles' lists it writes. @group(0) @binding(28) var light_rw: array>; @group(0) @binding(29) var light_lists: array>; +// The output grid's own composition of this frame (`gcompose`): rgb, w the distance of the surface its guide saw +// (negative: a surface that moves by itself; 0: the sky). +@group(0) @binding(30) var gout: array>; +// The output grid's thin things (`Thin`): per output pixel this frame's record and the previous frame's (two halves, +// as a lasting buffer's), then the best of the previous frame's records that land on the nine pixels around it now +// (`gcompose` clears it, `gcarry` writes, `gupscale` reads). +@group(0) @binding(31) var thin: array>; // Element i of this frame's half of a lasting buffer, and of the previous frame's. fn this_half(i: u32) -> u32 { return L.state.x * L.size.x * L.size.y + i; } @@ -1457,6 +1464,182 @@ fn compose(@builtin(global_invocation_id) gid: vec3) { sample_vel[q] = vec4(vel, depth, reactive); } +// ---- The output grid composed from its own guides (live/frame.rs `decoupled`). +// The kernel's guides pass (pathtrace.wgsl `guides`) leaves, for every OUTPUT pixel and at this frame's place in it +// (L.jit.zw), what the camera sees there: the surface's distance, albedo and normal, and the light that is the +// pixel's own (what it sees directly, and the directional lights' direct light on the surface): two vec4s a pixel +// after the traced pixels' direct light in `direct_in` (`guide_px`). The lighting stays on the traced grid, whose +// samples do not move (no jitter): each keeps one surface, and one texel of it, while the camera holds still. Here +// each output pixel takes the denoised irradiance and specular light of the traced samples around it that lie on +// ITS surface (within G_PLANE of its plane, by the normals' agreement), multiplies the irradiance by its own albedo +// and adds its own light. +struct Guide { own: vec3, t: f32, albedo: vec3, n: vec3 }; +fn guide_px(p: u32) -> Guide { + let at = L.size.x * L.size.y + 2u * p; + let a = direct_in[at]; + let b = direct_in[at + 1u]; + // (The normal as the kernel's `dir_pack` has it: octahedral, twelve bits each way in one float.) + let hi = floor(b.w / 4096.0); + let q = vec2(hi, b.w - hi * 4096.0) / 4095.0 * 2.0 - 1.0; + return Guide(a.rgb, a.w, b.rgb, oct_dec_f(q)); +} +// A traced sample counts for a pixel within this share of the pixel's distance off its plane, and by its normal's +// cosine to this power. +const G_PLANE: f32 = 0.01; +const G_NPOW: f32 = 32.0; +struct Lit { irr: vec3, spec: vec3, w: f32 }; +// Traced sample (qx, qy)'s lighting for a surface point pg (normal ng, at distance tg), by `ws` and its guides. +fn lit_tap(qx: i32, qy: i32, ws: f32, pg: vec3, ng: vec3, tg: f32, guided: bool) -> Lit { + if (qx < 0 || qy < 0 || qx >= i32(L.isz.x) || qy >= i32(L.isz.y)) { return Lit(vec3(0.0), vec3(0.0), 0.0); } + let q = u32(qy) * L.isz.x + u32(qx); + var wt = ws; + if (guided) { + // (The sample's surface as the temporal passes keep it, `GB`: eight bytes.) + let s = gb_unpack(gbuffer[this_half(q)]); + if (s.depth <= 0.0) { return Lit(vec3(0.0), vec3(0.0), 0.0); } + let sp = sample_pos(qx, qy); + let dir = ray_dir(L.cur, sp.x, sp.y); + let ps = L.cur.pos.xyz + dir * (s.depth / max(dot(dir, L.cur.fwd.xyz), 1e-6)); + let pd = abs(dot(ng, ps - pg)) / (G_PLANE * tg); + wt *= exp(-pd * pd) * pow(max(dot(ng, s.n), 0.0), G_NPOW); + } + return Lit(fa[q].rgb * wt, spec_load(1u, q).rgb * wt, wt); +} + +@compute @workgroup_size(8, 8, 1) +fn gcompose(@builtin(global_invocation_id) gid: vec3) { + let w = L.size.x; + let h = L.size.y; + if (gid.x >= w || gid.y >= h) { return; } + let p = gid.y * w + gid.x; + let g = guide_px(p); + let tg = g.t; + let e = vec2(f32(gid.x), f32(gid.y)) + L.jit.zw; + let up = vec2(f32(w), f32(h)) / vec2(f32(L.isz.x), f32(L.isz.y)); + // In traced-sample units: sample (qx, qy) sits at (qx, qy). + let rc = e / up - L.jit.xy; + let f0 = vec2(floor(rc)); + let ft = rc - floor(rc); + // A medium before the surface (smoke, fire: `media_composite` marched the traced samples' rays and left its + // light and its transmittance after the guides in `direct_in`): between the four samples around. (L.state.z: the + // scene has such media.) + var med = vec4(0.0); + var mw = 0.0; + for (var k = 0; k < select(0, 4, L.state.z != 0u); k++) { + let qx = f0.x + (k & 1); + let qy = f0.y + (k >> 1u); + if (qx < 0 || qy < 0 || qx >= i32(L.isz.x) || qy >= i32(L.isz.y)) { continue; } + let bw = select(1.0 - ft.x, ft.x, (k & 1) == 1) * select(1.0 - ft.y, ft.y, (k >> 1u) == 1); + med += direct_in[3u * L.size.x * L.size.y + u32(qy) * L.isz.x + u32(qx)] * bw; + mw += bw; + } + med = select(vec4(0.0, 0.0, 0.0, 1.0), med / mw, mw > 1e-4); + if (non_finite(med.rgb) || non_finite(vec3(med.w))) { med = vec4(0.0, 0.0, 0.0, 1.0); } + // The pixel's own light: what the camera sees directly, and the directional lights' light on the surface. + var c = finite_or_zero(g.own) * med.w + med.rgb; + if (tg > 0.0) { + let pg = L.cur.pos.xyz + ray_dir(L.cur, e.x, e.y) * tg; + let ng = g.n; + var irr = vec3(0.0); + var spec = vec3(0.0); + var wsum = 0.0; + for (var k = 0; k < 4; k++) { + let bw = select(1.0 - ft.x, ft.x, (k & 1) == 1) * select(1.0 - ft.y, ft.y, (k >> 1u) == 1); + let t = lit_tap(f0.x + (k & 1), f0.y + (k >> 1u), bw, pg, ng, tg, true); + irr += t.irr; spec += t.spec; wsum += t.w; + } + if (wsum < 0.05) { + // None of the four is of this surface: the sixteen around, by their distance. + irr = vec3(0.0); spec = vec3(0.0); wsum = 0.0; + for (var k = 0; k < 16; k++) { + let o = vec2(k % 4 - 1, k / 4 - 1); + let d = vec2(o) - ft; + let t = lit_tap(f0.x + o.x, f0.y + o.y, exp(-dot(d, d) / 1.5), pg, ng, tg, true); + irr += t.irr; spec += t.spec; wsum += t.w; + } + if (wsum < 1e-4) { + // Nor of those (a thing thinner than the traced grid): the four nearest as they are. + irr = vec3(0.0); spec = vec3(0.0); wsum = 0.0; + for (var k = 0; k < 4; k++) { + let bw = select(1.0 - ft.x, ft.x, (k & 1) == 1) * select(1.0 - ft.y, ft.y, (k >> 1u) == 1); + let t = lit_tap(f0.x + (k & 1), f0.y + (k >> 1u), bw, pg, ng, tg, false); + irr += t.irr; spec += t.spec; wsum += t.w; + } + } + } + if (wsum > 0.0) { c += (max(g.albedo, vec3(0.02)) * irr + spec) / wsum * med.w; } + } + // (Whether the surface moves by itself is the nearest traced sample's to say: the guides have the camera's rays alone.) + let nq = clamp(vec2(round(rc)), vec2(0), vec2(L.isz.xy) - 1); + let moves = gb_unpack(gbuffer[this_half(u32(nq.y) * L.isz.x + u32(nq.x))]).moves; + gout[p] = vec4(finite_or_zero(max(c, vec3(0.0))), select(tg, -tg, moves)); + atomicStore(&thin[2u * w * h + p], 0u); +} + +// `Thin`, per output pixel: a thing thinner than two pixels that the pixel's guide saw (`gupscale`), kept while the +// guides of the frames after miss it. Every output pixel has a guide each frame, at the frame's place in the pixel: +// a lamp a third of a pixel wide is seen by one frame in nine, and the others see what is behind it. The history +// holds its light; what the frames that miss it need to know is that it is still there, and where: else its light +// goes with what is behind it (before a sky that does not move with the camera's slide, a field of such lamps left +// 0.79 of its light beside its edge; `upscale` has its locks for this, live.wgsl `Lock`, found by the traced +// samples' emission), and in motion the clamp into this frame's compositions cuts it. Here the test is the guides' +// distances, which have no noise and are every pixel's own: thin is a guide nearer than both of some pair of +// opposite neighbours that no 2 x 2 block of the nine is like (within THIN_FRONT of its distance: `Lock`'s rule, on +// distance for luminance), so a wire and a leaf's tip as a lamp, lit or not. A record is the +// thing's distance, where in its pixel it was seen, and how many frames it is kept without being seen again +// (THIN_LIFE: a sequence and a half of the guides' eight places); in one word: the distance's logarithm in sixteen +// bits (a 2048th of a stop), the life in four, the place in six each way. +// - `gcarry` takes each record of the previous frame to where its point is now, by the two cameras alone (a thing +// on a surface that moves by itself is not recorded: it is found again when a guide next sees it), onto the pixel +// it falls in and the eight around that one: the longest-lived where several come to one pixel, then the nearest. +// (A pixel reads one word so; reading the nine landing places around itself, most of them empty, was a fifth of +// `gupscale`'s time.) +// - `gupscale` takes, for a pixel, the thing its own guide saw, else the one that came to it if it lies in front +// of what the pixel sees: the history there moves by that thing's motion (an edge moves with what is in front of +// it), is spared the clamp in motion while the record's life is young, and `judge`'s finding of something gone +// is not taken for it. The pixel the thing lies in keeps its record (of things in neighbouring pixels the best +// one's is kept, and the others are found again when a guide sees them). Where no thing is around now and one +// was recorded around the place the history comes from, the history holds a thing that has gone on: if this +// frame's compositions do not explain its colour it is dropped. +const THIN_LIFE: u32 = 12u; +const THIN_FRONT: f32 = 0.05; +// A record's word, 0: none. From the top: the life + 1 in four bits, the distance's code from the far end in +// fourteen (a 512th of a stop), the place in seven each way: from a pixel before this one to a pixel after it, for +// the records `gcarry` leaves at a thing's neighbours. The greater of two words is the longer-lived record, then the +// nearer. +struct Thin { t: f32, life: u32, at: vec2 }; +fn thin_pack(t: f32, life: u32, at: vec2) -> u32 { + let code = u32(clamp(round((log2(max(t, 1.0e-6)) + 10.0) * 512.0), 0.0, 16383.0)); + let a = vec2(clamp((at + 1.0) * (128.0 / 3.0), vec2(0.0), vec2(127.0))); + return ((min(life, 13u) + 1u) << 28u) | ((16383u - code) << 14u) | (a.x << 7u) | a.y; +} +fn thin_unpack(v: u32) -> Thin { + return Thin(exp2(f32(16383u - ((v >> 14u) & 0x3fffu)) / 512.0 - 10.0), (v >> 28u) - 1u, (vec2(f32((v >> 7u) & 127u), f32(v & 127u)) + 0.5) * (3.0 / 128.0) - 1.0); +} + +@compute @workgroup_size(8, 8, 1) +fn gcarry(@builtin(global_invocation_id) gid: vec3) { + let w = i32(L.size.x); + let h = i32(L.size.y); + if (L.size.w != 0u || L.state.w == 0u || i32(gid.x) >= w || i32(gid.y) >= h) { return; } + let v = atomicLoad(&thin[last_half(gid.y * L.size.x + gid.x)]); + if ((v >> 28u) <= 1u) { return; } + let r = thin_unpack(v); + let was = vec2(gid.xy) + r.at; + let pw = L.prev.pos.xyz + ray_dir(L.prev, was.x, was.y) * r.t; + let c = cur_pixel(pw); + let at = c.xy + 0.5; + let q = vec2(floor(at)); + if (c.z <= 0.0 || q.x < 0 || q.y < 0 || q.x >= w || q.y >= h) { return; } + let t = distance(pw, L.cur.pos.xyz); + for (var k = 0; k < 9; k++) { + let x = q.x + k % 3 - 1; + let y = q.y + k / 3 - 1; + if (x < 0 || y < 0 || x >= w || y >= h) { continue; } + atomicMax(&thin[u32(2 * w * h + y * w + x)], thin_pack(t, r.life - 1u, at - vec2(f32(x), f32(y)))); + } +} + // The upscaler's state of each traced sample, after `compose`: how much it flickers (`Flicker`) and the thin feature's // lock (`Lock`), into this frame's half of `up_state`. @compute @workgroup_size(8, 8, 1) @@ -1734,11 +1917,13 @@ fn flicker_at(q: u32) -> Flicker { // history there), the motion its output pixels reproject by: the surface nearest the camera among the nine samples // around (the sky the farthest), since an edge moves with what is in front of it; and whether its history is of // something that is gone. -struct Judged { d: vec3, lum: f32, vel: vec2, gone: bool, moved: bool }; +// (`dark`: the light that counts as none at this frame's exposure, a hundredth of display white; for `gupscale`, which +// has the frame's exposure from here.) +struct Judged { d: vec3, lum: f32, vel: vec2, gone: bool, moved: bool, dark: f32 }; fn judged_at(q: u32) -> Judged { let v = up_state[judged_slot(q)]; let b = unpack2x16float(v.y); - return Judged(vec3(unpack2x16float(v.x), b.x), b.y, unpack2x16float(v.z), v.w != 0u, v.w == 2u); + return Judged(vec3(unpack2x16float(v.x), b.x), b.y, unpack2x16float(v.z), (v.w & 3u) != 0u, (v.w & 3u) == 2u, unpack2x16float(v.w).y); } @compute @workgroup_size(8, 8, 1) @@ -1867,8 +2052,8 @@ fn judge(@builtin(global_invocation_id) gid: vec3) { // A locked sample's distance from the history's range is no finding (a lamp finer than a pixel lies above it // whenever a sample hits it). d *= 1.0 - locked(q); - // (w: 1 gone, 2 gone with what was in front moving.) - up_state[judged_slot(q)] = vec4(pack2x16float(d.xy), pack2x16float(vec2(d.z, l)), pack2x16float(vel), select(u32(gone), 2u, gone && gone_moving)); + // (w: 1 gone, 2 gone with what was in front moving; its other half `dark`.) + up_state[judged_slot(q)] = vec4(pack2x16float(d.xy), pack2x16float(vec2(d.z, l)), pack2x16float(vel), select(u32(gone), 2u, gone && gone_moving) | pack2x16float(vec2(0.0, min(0.01 / exposure_scale(), 6.0e4)))); } // `reject`: per traced pixel, into `spec_pp`'s slot 0 (free once the specular filter is done; f16): the correction @@ -2105,6 +2290,191 @@ fn upscale(@builtin(global_invocation_id) gid: vec3) { if (L.misc2.z > 0.0 || L.dof.x > 0.0) { sb[i] = img; } else { fa[i] = img; } } +// The output's history where the output is composed from its own guides (`gcompose`; live/frame.rs `decoupled`), in +// place of `upscale`: every pixel has a composition of its own each frame, on this frame's surfaces and by the +// denoised lighting, so there are no samples to gather. What judges the history stays (`track`, `judge`, `reject`: +// a traced sample's flicker, its distance from the history, the verdict of the samples around together): measured +// without them on 2026-12-04, what a moving object leaves behind was 28 % further from its settled frame than with +// the upscaler (for 18 % nearer with them) and a lamp's bounce took four times as long to settle. A thing thinner +// than two pixels is the output grid's own to keep (`Thin`): the traced samples do not move and see such a thing +// always or never, so the upscaler's locks, which those samples' emission finds, say nothing here. +// - The motion is the one `judge` chose at the nearest traced sample, or a thin thing's own; the history is +// corrected and discounted by `reject`'s verdict between the four around, as `upscale` takes it. +// - A frame weighs G_REST by the guide sample's distance from the pixel's centre (the upscaler's kernel) at rest, +// where the history holds UP_SAMPLES: as many frames as the upscaler's does. A pixel that moves takes whole +// frames (G_MOVING) into its UP_MOVING samples: the composition is this frame's surfaces at the output's +// resolution and has nothing of a resampled history's blur, so the shorter history shows more (Bistro walking, +// detail against offline: 0.46 for 0.41 with the weight at rest, 0.54 with whole frames, flicker after a move no +// higher). At rest whole frames flicker as the upscaler does (Bistro held, 4 x 4 change 0.144 for 0.046). +// - While the scene's lighting changes (L.mode.z) the history's level over nine pixels follows the composition's by +// G_FOLLOW a frame (means by 1 2 1 each way: with a plain mean, whose response is negative at some frequencies, +// the correction fed those until the picture burst). What differs between the two at that scale is the light, +// not the sampling, and the history is sharper than the upscaler's, so a traced sample falls outside its range +// less often and `judge` finds a slow change later (a city at dusk read 1.12 of offline's light for the +// upscaler's 1.09; with this 1.07). Not otherwise, and no faster: the composition's own slow noise comes through +// by the same gain (Bistro held, a tenth a frame: 4 x 4 change 0.41 for 0.046; a jump rule on one frame's +// difference lets a bright outlier through as a lamp switched on: 1.09). +const G_REST: f32 = 0.42; +const G_MOVING: f32 = 1.0; +const G_FOLLOW: f32 = 0.03; +@compute @workgroup_size(8, 8, 1) +fn gupscale(@builtin(global_invocation_id) gid: vec3) { + let w = L.size.x; + let h = L.size.y; + if (gid.x >= w || gid.y >= h) { return; } + let i = gid.y * w + gid.x; + let iw = i32(L.isz.x); + let ih = i32(L.isz.y); + let up = vec2(f32(w), f32(h)) / vec2(f32(iw), f32(ih)); + let g = gout[i]; + let cur = g.rgb; + var xlo = vec3(1.0e30); + var xhi = vec3(-1.0e30); + var coarse = vec3(0.0); + // Thin (`Thin`): this pixel's guide is nearer than both of some pair of opposite neighbours' (`far`), and no 2 x 2 + // block of the nine is like it (`like`). (The guides' distances, the sky the farthest. Two masks and no array + // of the nine: with one, the pass took 1.29 ms for 1.09 at 1280 x 720 on an M4 while the camera moves.) + let own = select(1.0e29, abs(g.w), g.w != 0.0); + var like = 0u; + var far = 0u; + for (var k = 0; k < 9; k++) { + let ox = k % 3 - 1; + let oy = k / 3 - 1; + let x = clamp(i32(gid.x) + ox, 0, i32(w) - 1); + let y = clamp(i32(gid.y) + oy, 0, i32(h) - 1); + let c9 = gout[u32(y) * w + u32(x)]; + xlo = min(xlo, c9.rgb); + xhi = max(xhi, c9.rgb); + coarse += c9.rgb * f32((2 - abs(ox)) * (2 - abs(oy))); + let d = select(1.0e29, abs(c9.w), c9.w != 0.0); + if (max(d, own) < (1.0 + THIN_FRONT) * min(d, own)) { like |= 1u << u32(k); } + if ((1.0 + THIN_FRONT) * own < d) { far |= 1u << u32(k); } + } + coarse /= 16.0; + // (Not on a surface that moves by itself.) + let still = g.w >= 0.0; + let across = (far & (((far >> 8u) & 1u) | ((far >> 6u) & 2u) | ((far >> 4u) & 4u) | ((far >> 2u) & 8u))) != 0u; + let seen = still && own < 1.0e29 && across && (like & 27u) != 27u && (like & 54u) != 54u && (like & 216u) != 216u && (like & 432u) != 432u; + // The thin thing here: the one this pixel's guide saw, else the one that came to it (`gcarry`) if it lies in front + // of what the pixel sees. + // (`at`: where it is, output pixels, a pixel's centre at + 0.5. `around`: one is among the nine pixels now, in + // front of what this pixel sees or not.) + var thing = Thin(0.0, 0u, vec2(0.0)); + var record = 0u; + var around = seen; + if (seen) { + thing = Thin(own, THIN_LIFE, vec2(gid.xy) + L.jit.zw); + record = thin_pack(own, THIN_LIFE, L.jit.zw); + } else if (L.size.w == 0u) { + let near = atomicLoad(&thin[2u * w * h + i]); + if (near != 0u) { + around = true; + let c = thin_unpack(near); + if (still && c.t * (1.0 + THIN_FRONT) < own) { + thing = Thin(c.t, c.life, vec2(gid.xy) + c.at); + // (The record stays with the pixel the thing lies in.) + if (all(c.at >= vec2(0.0)) && all(c.at < vec2(1.0))) { record = near; } + } + } + } + atomicStore(&thin[this_half(i)], record); + // (In full for the first half of its life, fading over the second, as a lock.) + let lock = select(0.0, clamp(2.0 * f32(thing.life) / f32(THIN_LIFE), 0.0, 1.0), thing.t > 0.0); + // The traced sample nearest the pixel: its reactive mask, its depth for the circle of confusion, the motion + // `judge` chose there; `reject`'s verdict between the four around (`upscale`'s reading of both). + let rc = (vec2(gid.xy) + 0.5) / up - L.jit.xy; + let bc = clamp(vec2(round(rc)), vec2(0), vec2(iw - 1, ih - 1)); + let bq = u32(bc.y * iw + bc.x); + let f0 = vec2(floor(rc)); + let ft = rc - floor(rc); + var verdict = vec4(0.0); + var vsum = 0.0; + var gone_near = false; + var shaded = 0.0; + for (var k = 0; k < 4; k++) { + let qx = f0.x + (k & 1); + let qy = f0.y + (k >> 1u); + if (qx < 0 || qy < 0 || qx >= iw || qy >= ih) { continue; } + let bw = select(1.0 - ft.x, ft.x, (k & 1) == 1) * select(1.0 - ft.y, ft.y, (k >> 1u) == 1); + let j = u32(qy * iw + qx); + let v = spec_load(0u, j); + gone_near = gone_near || (v.w > 1.5 && bw > 0.0); + verdict += vec4(v.xyz, min(v.w, 1.0)) * bw; + vsum += bw; + // (A sample whose light changed lately, `track`: the history is of the light before.) + if (L.mode.z != 0u && bw > 0.02) { shaded = max(shaded, clamp((LIGHT_SETTLE - unpack2x16float(up_state[this_half(j)].y).y) / (LIGHT_SETTLE - 1.0), 0.0, 1.0)); } + } + verdict = select(vec4(0.0, 0.0, 0.0, 1.0), verdict / vsum, vsum > 1e-4); + // (A thin thing the traced samples saw a frame ago and miss now is not gone: its record says where it is.) + if (gone_near && lock < 0.5) { verdict = vec4(0.0, 0.0, 0.0, 1.0); } + let judged = judged_at(bq); + var vel = judged.vel; + if (thing.t > 0.0 && camera_moves()) { + // (The thing's own motion, by its distance: what is behind it moves otherwise.) + let pv = prev_pixel(L.cur.pos.xyz + ray_dir(L.cur, thing.at.x, thing.at.y) * thing.t); + if (pv.z > 0.0) { vel = clamp(thing.at - 0.5 - pv.xy, vec2(-2048.0), vec2(2048.0)); } + } + var hist = vec4(0.0); + if (L.size.w == 0u) { + let hp = vec2(f32(gid.x), f32(gid.y)) - vel; + if (hp.x > -0.5 && hp.y > -0.5 && hp.x < f32(w) - 0.5 && hp.y < f32(h) - 0.5) { + if (vel.x == 0.0 && vel.y == 0.0) { hist = color_hist[last_half(i)]; } else { hist = up_history(hp.x, hp.y); } + } + if (non_finite(hist.rgb) || non_finite(vec3(hist.w))) { hist = vec4(0.0); } + // A thing that has gone on: none around now, one around where the history comes from, and a colour there + // that this frame's compositions do not explain (`judge`'s rule for what is gone, UP_STALE). + if (hist.w > 0.0 && !around && L.state.w != 0u && lum(abs(hist.rgb - clamp(hist.rgb, xlo, xhi))) > UP_STALE * lum(hist.rgb) + judged.dark) { + let hq = vec2(round(hp)); + var was = false; + for (var k = 0; k < 9; k++) { + let x = hq.x + k % 3 - 1; + let y = hq.y + k / 3 - 1; + if (x < 0 || y < 0 || x >= i32(w) || y >= i32(h)) { continue; } + was = was || atomicLoad(&thin[last_half(u32(y) * w + u32(x))]) != 0u; + } + if (was) { verdict = vec4(0.0, 0.0, 0.0, 1.0); } + } + if (hist.w > 0.0 && L.mode.z != 0u) { + let hq = vec2(round(hp)); + var hm = vec3(0.0); + var hn = 0.0; + for (var k = 0; k < 9; k++) { + let x = hq.x + k % 3 - 1; + let y = hq.y + k / 3 - 1; + if (x < 0 || y < 0 || x >= i32(w) || y >= i32(h)) { continue; } + let hv = color_hist[last_half(u32(y) * w + u32(x))]; + if (hv.w <= 0.0 || non_finite(hv.rgb)) { continue; } + let b9 = f32((2 - abs(k % 3 - 1)) * (2 - abs(k / 3 - 1))); + hm += hv.rgb * b9; + hn += b9; + } + if (hn > 15.5) { + hist = vec4(max(hist.rgb + G_FOLLOW * (coarse - hm / hn), vec3(0.0)), hist.w); + } + } + } + let moving = clamp(length(vel) / UP_SPEED, 0.0, 1.0); + let dj = L.jit.zw - 0.5; + let conf = mix(G_REST * exp(-UP_SHARP * dot(dj, dj)), G_MOVING, moving); + var outc = cur; + var count = conf; + let kept = hist.w * (1.0 - verdict.w); + if (kept > 0.0) { + var hc = max(hist.rgb + verdict.xyz, vec3(0.0)); + // (Not at a thin thing: the one no guide saw this frame is still there.) + hc = mix(hc, clamp(hc, xlo, xhi), max(moving, shaded) * (1.0 - lock)); + var rest = UP_SAMPLES; + if (L.mode.z != 0u) { rest = mix(UP_LIVE, UP_SAMPLES, lock); } + let most = min(mix(rest, UP_MOVING, moving), mix(UP_SAMPLES, UP_REACTIVE, clamp(sample_vel[bq].w, 0.0, 1.0))); + count = min(kept + conf, most); + outc = mix(hc, cur, clamp(conf / max(count, 1e-4), 0.0, 1.0)); + } + let lin = finite_or_zero(max(outc, vec3(0.0))); + color_hist[this_half(i)] = vec4(lin, count); + let img = vec4(lin, dof_coc(sample_vel[bq].z)); + if (L.misc2.z > 0.0 || L.dof.x > 0.0) { sb[i] = img; } else { fa[i] = img; } +} + // ------------------------------------------------------------------------------------------------ exposure // Exposure applied to scene radiance: manual (ae2.x) or this frame's auto exposure. diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl index 34541ca0..5c8d78a9 100644 --- a/renderer/shaders/pathtrace.wgsl +++ b/renderer/shaders/pathtrace.wgsl @@ -111,7 +111,7 @@ struct Params { vol: vec4, // volumetric scattering albedo (0 = off), HG anisotropy, extinction scale in range, - vol2: vec4, // volumetric albedo tint rgb, range (m, 0 = unlimited) jitter: vec4, // live: this frame's sub-pixel jitter x, y (every camera ray's); ray tracing off (1); - - cache: vec4, // live radiance cache (1 = on), history cap in samples, history cap in frames, - + cache: vec4, // live radiance cache (1 = on), history cap in samples, history cap in frames; the output is composed from its own guides (1: `seen_medium_at`) motion: vec4, // live motion vectors: 1 = on; `render --signals`; software traversal's units: the top tree's root, their count (bits) light_lod: vec4, // live light LOD (lib.rs emitter_lod): reference position, d0 (0 = off) emit_power: vec4, // the emitter CDF's power and cull as the CPU built it (lib.rs `EmitterCull`); not read here @@ -121,7 +121,7 @@ struct Params { aerial: vec4, // the sky's aerial perspective (F_AERIAL): density multiple, Rayleigh scale, Mie scale, - background: vec4, // three.js scene.background (radiance), 1 (F_BACKGROUND) ltile: vec4, // live light tiles (`lt_list_start`): 1 with last frame's lists (0: none), tiles a row, the grid's offset when they were built (x | y << 16), candidates a vertex the camera sees takes from its list - ltile2: vec4, // the traced size they were built at, -, - + ltile2: vec4, // the traced size they were built at; the output's pixels (`guide_at`), - lt_cam: array, 4>, // the camera they were built under: position (w = tan(fov/2)), forward (w = aspect), right, up table_first: array, 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, 2>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, the instances' rows; the triangles' indices, the cutouts' maps @@ -1321,6 +1321,8 @@ var nee_alone: bool = false; const DL_ALL: u32 = 0u; const DL_REST: u32 = 1u; const DL_SAMPLED: u32 = 2u; +// (The directional lights alone: the guides' pass, each output pixel's own.) +const DL_SUN: u32 = 3u; var dl_part: u32 = 0u; // `direct_light` without the sky: a surface seen in a reflection lights itself from the lights, the sky's light @@ -2523,6 +2525,7 @@ fn direct_light(s: Surface, lb: Lobes, v: vec3) -> vec3 { dl_det += sum; dl_det_spec += dl_spec; } + if (dl_part == DL_SUN) { return sum; } // gpu.rs `KernelSwitches::light_pick`: past the camera hit, the directional lights and one of the other kinds a // scene has (local lights, emitters, the sky), weighted by their number. @if(light_pick) let has_local = P.counts.x > P.counts2.x; @@ -3451,6 +3454,12 @@ fn surf_room() -> bool { if (!LIVE || P.jitter.w < 0.5 || !(emitters_on() || min(P.counts.x - P.counts2.x, P.counts.x - P.counts2.w) > RIS_EXACT)) { return false; } return first_len() >= (2u + select(0u, CHAIN_VECS, has(F_MIRROR)) + SURF_VECS) * P.size.x * P.size.y; } +// Where the output is composed from its own guides (live/frame.rs `decoupled`; P.cache.w), `direct_out` is longer +// than the traced pixels' direct light: after an output of vec4s (P.ltile2.z: the output's pixels) come the output +// grid's guides, two vec4s a pixel (`guides`), and in a scene with media a vec4 a traced pixel: a medium's light +// before the surface and its transmittance (`media_composite`). +fn guide_at(pix: u32) -> u32 { return P.ltile2.z + 2u * pix; } +fn seen_medium_at(pix: u32) -> u32 { return 3u * P.ltile2.z + pix; } // Two numbers of 0..1 as one whole number a float keeps: `bits` of the 24 for the second. fn pair_pack(a: f32, b: f32, bits: u32) -> f32 { let nb = f32(1u << bits); @@ -4084,7 +4093,12 @@ fn media_composite(@builtin(global_invocation_id) gid: vec3) { let d = normalize(P.cam_fwd.xyz + P.cam_right.xyz * (ndc.x * P.cam_pos.w * P.cam_fwd.w) + P.cam_up.xyz * (ndc.y * P.cam_pos.w)); let ft = first_depth(pix); let mm = media_march(P.cam_pos.xyz, d, select(1.0e30, ft, ft > 0.0), true, rng_dim(D_MEDIA)); - if (mm.tr >= 1.0 && all(mm.light == vec3(0.0))) { return; } + // (Its light and transmittance by themselves too, for the output's own composition: live.wgsl `gcompose`.) + let apart = P.cache.w > 0.5 && direct_len() > seen_medium_at(pix); + if (mm.tr >= 1.0 && all(mm.light == vec3(0.0))) { + if (apart) { direct_store(seen_medium_at(pix), vec4(0.0, 0.0, 0.0, 1.0)); } + return; + } let samples = P.misc.w + 1.0; // this dispatch runs with the frame's last sample's parameters let lw = vec3(0.2126, 0.7152, 0.0722); let rest = dot(mm.light, lw) - mm.moving.y + dot(px.color.rgb + px.spec.rgb + px.emit.rgb, lw) / samples * mm.tr; @@ -4092,6 +4106,7 @@ fn media_composite(@builtin(global_invocation_id) gid: vec3) { px.normal = vec4(px.normal.xyz, floor(clamp(share, 0.0, 1.0) * 255.0) + 0.5 * clamp(mm.tr, 0.0, 1.0)); px.emit = vec4(px.emit.rgb * mm.tr + mm.light * samples, px.emit.w); accum[pix] = px; + if (apart) { direct_store(seen_medium_at(pix), vec4(mm.light, clamp(mm.tr, 0.0, 1.0))); } if (direct_len() >= w * h) { direct_store(pix, vec4(direct_load(pix).rgb * mm.tr, direct_load(pix).w)); } } @@ -4208,22 +4223,15 @@ fn camera_ray(gid: vec2, cam: vec4) -> CamRay { // 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) { - 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); - // Through mirrors to the surface the pixel shows, which `main` starts its path from (`Chain`). The material is - // read only where its record says it can be a mirror. Not with ray tracing off; not procedural geometry. +// Through mirrors from a camera hit to the surface the pixel shows (`Chain`: what `main` starts its path from, and +// the guides' pass its surface), at most `longest` of them: the surface shown, where its ray starts and which way it +// goes, the mirrors passed, the way to the last one, the turn of a direction there, what the chain left of the light +// and what it added. The material is read only where its record says it can be a mirror. Not procedural geometry. +struct Followed { c: Chain, n: u32, d: vec3 }; +fn follow_mirrors(o: vec3, d: vec3, hit: Hit, longest: u32) -> Followed { var seen = hit; - var so = cr.o; - var sd = cr.d; + var so = o; + var sd = d; var chain = 0u; var way = 0.0; var weight = vec3(1.0); @@ -4231,7 +4239,6 @@ fn first_hit(@builtin(global_invocation_id) gid: vec3) { var cone_w = 0.0; var cone_a = 2.0 * P.cam_pos.w / lod_height(); var xf = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); - let longest = select(min(MIRROR_CHAIN, max(P.counts.z, 1u) - 1u), 0u, !has(F_MIRROR) || P.jitter.z > 0.5 || first_len() < (2u + CHAIN_VECS) * w * h); for (var b = 0u; b < longest; b++) { if (seen.tri == 0xffffffffu || is_proc(seen) || !has(F_INST) || seen.inst == NO_INST) { break; } if (!mirror_possible(material_at(row_word(instance_at(seen.inst).info.w, seen.part, 0u) & ROW_MATERIAL))) { break; } @@ -4272,6 +4279,28 @@ fn first_hit(@builtin(global_invocation_id) gid: vec3) { sd = l; seen = trace(so, sd, INF, TRACE_CLOSEST); } + return Followed(Chain(seen, so, way, xf, weight, light), chain, sd); +} + +@compute @workgroup_size(8, 8, 1) +fn first_hit(@builtin(global_invocation_id) gid: vec3) { + 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); + // Through mirrors to the surface the pixel shows (`follow_mirrors`). Not with ray tracing off. + let longest = select(min(MIRROR_CHAIN, max(P.counts.z, 1u) - 1u), 0u, !has(F_MIRROR) || P.jitter.z > 0.5 || first_len() < (2u + CHAIN_VECS) * w * h); + let f = follow_mirrors(cr.o, cr.d, hit, longest); + let seen = f.c.seen; + let so = f.c.o; + let sd = f.d; + let chain = f.n; + let xf = f.c.xf; first_store(pix, hit, chain); // The motion of the surface shown, as the pixel sees it: through the chain. var mv = vec4(0.0); @@ -4279,11 +4308,113 @@ fn first_hit(@builtin(global_invocation_id) gid: vec3) { if (seen.tri != 0xffffffffu) { mv = first_motion(seen, so + sd * seen.t); } if (chain > 0u) { mv = vec4(xf * mv.xyz, mv.w); - chain_store(pix, Chain(seen, so, way, xf, weight, light)); + chain_store(pix, f.c); } if (motion_len() >= w * h) { motion_store(pix, select(vec4(0.0), mv, !non_finite(mv.xyz))); } } +// The guides of the output grid, where a frame's output is composed from them (live/frame.rs `decoupled`, live.wgsl +// `gcompose`): for every OUTPUT pixel, at the frame's place in it (P.jitter.xy: a jitter of its own), what the camera +// sees there as `main` has it at a path's camera hit: the surface shown (through mirrors, `follow_mirrors`), its +// distance, albedo, normal and roughness; the light seen directly (emission, the sky, the fog's and the haze's own +// light on the way), under what the way lets through; and the directional lights' direct light on the surface +// (`direct_light`'s first part, DL_SUN: deterministic but for the disk's reach, and this pixel's own shadow ray, so +// a shadow's edge has the output's resolution). No light is gathered beyond that: the lighting is the traced +// grid's. Two vec4s a pixel after the traced pixels' direct light in `direct_out` (`guide_at`): the light that is the +// pixel's own (what it sees directly and that sun light) and the distance; the albedo and the normal (`dir_pack`). +// P.size is the output's here. +@compute @workgroup_size(8, 8, 1) +fn guides(@builtin(global_invocation_id) gid: vec3) { + let w = P.size.x; + let h = P.size.y; + if (gid.x >= w || gid.y >= h || direct_len() < 3u * P.ltile2.z) { return; } + let pix = gid.y * w + gid.x; + rng_start(gid.xy, P.size.z, P.size.w, 0u); + cur_depth = 0u; + mirror_path = false; + rays_off = false; + let cr = camera_ray(gid.xy, rng4(rng_dim(D_CAMERA))); + var hit = trace(cr.o, cr.d, INF, TRACE_CLOSEST); + var o = cr.o; + var d = cr.d; + var thr = vec3(1.0); + var e0 = vec3(0.0); + var way = 0.0; + var chain = 0u; + var weight = vec3(1.0); + var xf = mat3x3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0)); + let cone_a = 2.0 * P.cam_pos.w / lod_height(); + var cone_w = 0.0; + if (has(F_MIRROR)) { + // (As `main` takes a chain from the first pass: the surface it shows, the light it added, what it left.) + let f = follow_mirrors(cr.o, cr.d, hit, min(MIRROR_CHAIN, max(P.counts.z, 1u) - 1u)); + if (f.n > 0u) { + chain = f.n; + way = f.c.way; + e0 += f.c.light; + weight = f.c.weight; + thr *= weight; + cone_w = cone_a * way; + o = f.c.o; + xf = f.c.xf; + d = transpose(xf) * d; + hit = f.c.seen; + } + } + let miss = hit.tri == 0xffffffffu; + // The way to the surface, as `main`'s camera segment: fog (its own light is seen directly), the sky's haze, water + // behind a mirror. (The fog's sampled scattering is lighting: the traced grid's.) + if (has(F_FOG) && P.fog.x > 0.0) { + let t0 = max(P.fog.w - way, 0.0); + let t1 = select(hit.t, 2.0e4, miss); + var od = fog_depth(o, d, t0, t1); + if (has(F_VOLUME) && P.vol.x > 0.0) { + let tv = select(t1, min(t1, max(P.vol2.w - way, 0.0)), P.vol2.w > 0.0); + od += fog_depth(o, d, t0, max(tv, t0)) * (P.vol.z - 1.0); + } + let tr = max(exp(-od), 1.0 - P.fog_color.w); + e0 += thr * (1.0 - tr) * P.fog_color.rgb; + thr *= tr; + } + if (has(F_AERIAL) && !miss) { + let ta = aerial_tr(o, d, hit.t); + e0 += thr * (1.0 - ta) * aerial_light(d); + thr *= ta; + } + if (has(F_HMEDIA) && chain > 0u) { thr *= media_homogeneous(o, d, select(hit.t, 1.0e30, miss), true, rng_sub(rng_dim(D_MEDIA), 1u)).tr; } + var first_t = 0.0; + var albedo = vec3(0.0); + var normal = vec3(0.0); + var sun = vec3(0.0); + if (miss) { + e0 += thr * sky_mis(d, 0.0); + } else { + let s = surface(o, d, hit, cone_w + cone_a * hit.t); + first_t = way + hit.t; + 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; + if (any(s.emissive > vec3(0.0)) && (s.front || !s.card)) { e0 += thr * s.emissive; } + if (P.counts2.x > 0u && !s.card) { + let v = -d; + dl_part = DL_SUN; + sun = thr * direct_light(s, lobes(s, max(dot(s.n, v), 1e-4)), v); + dl_part = DL_ALL; + } + if (chain > 0u) { + // (Behind a mirror chain, as the pixel sees it: the albedo under the chain's weight, the normal turned.) + albedo *= weight; + normal = xf * normal; + } + } + if (non_finite(e0)) { e0 = vec3(0.0); } + if (non_finite(sun)) { sun = vec3(0.0); } + if (non_finite(albedo)) { albedo = vec3(0.0); } + if (non_finite(normal) || dot(normal, normal) < 1e-12) { normal = vec3(0.0, 1.0, 0.0); } + if (non_finite(vec3(first_t))) { first_t = 0.0; } + direct_store(guide_at(pix), vec4(e0 + sun, first_t)); + direct_store(guide_at(pix) + 1u, vec4(albedo, dir_pack(normal))); +} + @compute @workgroup_size(8, 8, 1) fn main(@builtin(global_invocation_id) gid: vec3) { let w = P.size.x; diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs index a895cce2..e1974a73 100644 --- a/renderer/src/gpu.rs +++ b/renderer/src/gpu.rs @@ -1657,6 +1657,26 @@ impl KernelBufs { } } + /// These with the direct light's buffer of `bytes` (room after the traced pixels' for the output grid's guides: + /// pathtrace.wgsl `guide_at`). As `with_first`. + pub fn with_direct(&self, d: &wgpu::Device, bytes: u64) -> KernelBufs { + let view = [self.refl.size, self.motion.size, bytes, self.lists.size, self.first.size]; + match self.merged { + Some(_) => KernelBufs::new(d, true, true, self.cache.val.size / 32, view), + None => KernelBufs { + cache: self.cache.clone(), + refl: self.refl.clone(), + motion: self.motion.clone(), + direct: Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some(VIEW_BUFFERS[2]), size: bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false })), + lists: self.lists.clone(), + first: self.first.clone(), + deferred: self.deferred.clone(), + guard: self.guard.clone(), + merged: None, + }, + } + } + /// 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, view: [u64; 5]) -> KernelBufs { diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs index f6cad9a8..e8b9ac4a 100644 --- a/renderer/src/live/frame.rs +++ b/renderer/src/live/frame.rs @@ -145,13 +145,19 @@ pub(super) struct Profile { pub(super) media_sum: f64, } +/// Whether pass `name` runs: the passes that compose the output from its own guides only where it is (`decoupled`), and +/// there not the ones they stand in for. +fn decoupled_runs(decoupled: bool, name: &str) -> bool { + if decoupled { !layout::DECOUPLED_SKIPS.contains(&name) } else { !layout::DECOUPLED_PASSES.contains(&name) } +} + impl LiveCore { /// The kernel this frame runs. The scene's (`up.kernel`: an edit that brings a feature or a function changes it) /// where what a frame asks of it is made; else the one the view has, while the scene's is made on another thread /// (`Gpu::warm_kernel`): the frame does not wait for a compile, and what the new kernel draws (fog, a clear /// coat, a function) comes when it is ready. A view's first kernel is its load's. In lockstep a frame is its /// world's alone, and a browser has no other thread: there the frame makes its kernel itself. - fn choose_kernel(&mut self, guides: bool) { + fn choose_kernel(&mut self, guides: bool, out_guides: bool) { let wanted = &self.sc.up.kernel; let key = |k: &gpu::Kernel| (k.features, k.hash, k.approx); if self.kernel.as_ref().is_some_and(|k| key(k) == key(wanted)) { @@ -165,6 +171,9 @@ impl LiveCore { if guides { passes.push("surface_guides"); } + if out_guides { + passes.push("guides"); + } if wanted.features & gpu::F_MEDIA != 0 { passes.extend(["media_train", "media_composite"]); } @@ -230,6 +239,14 @@ impl LiveCore { let size = ReconstructionSize { input: [iw, ih], output: [w, h], dynamic: self.dynamic_res }; self.reset |= self.reconstructor.prepare(&self.g, &self.targets, size, self.view_mode != 0); let reconstruction = self.reconstructor.active; + // The output composed from guides of its own (`builtin` where the traced grid is coarser than the output; not + // in a view mode, which shows the traced grid's buffers): the camera's rays for every OUTPUT pixel each frame, + // jittered (pathtrace.wgsl `guides`), the lighting on the traced grid at fixed places, and the output + // composed from both and kept in a history of its own (live.wgsl `gcompose`, `gupscale`). + let decoupled = reconstruction.composes_output() && (iw, ih) != (w, h) && self.view_mode == 0; + if decoupled { + self.ensure_guides(self.sc.up.kernel.features & gpu::F_MEDIA != 0); + } self.ensure_first(iw as u64 * ih as u64); self.ensure_deferred(iw as u64 * ih as u64); if self.sc.up.translucent.is_some() { @@ -314,7 +331,7 @@ impl LiveCore { } } self.inst_moved = false; - self.choose_kernel(reconstruction.guides()); + self.choose_kernel(reconstruction.guides(), decoupled); let g = &self.g; let kernel = self.kernel.as_ref().unwrap_or(&self.sc.up.kernel); let t_submit = Instant::now(); @@ -328,12 +345,22 @@ impl LiveCore { 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"); + // The output grid's guides (pathtrace.wgsl `guides`), where the output is composed from them. + let out_guides = g.kernel_pass(kernel, if decoupled { "guides" } else { "first_hit" }); // The lights a camera hit resamples, after a sample's paths (pathtrace.wgsl `direct`). let direct = g.kernel_pass(kernel, "direct"); // 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. - let jitter = if reconstruction.unjittered() { + let guide_jitter = { + let quant = |v: f32| (v * 4095.0).round() / 4095.0; + (quant(halton(self.frame % 8 + 1, 2)), quant(halton(self.frame % 8 + 1, 3))) + }; + // (The traced samples stay at their pixels' centres where the output has guides of its own: a sample that + // moves over its pixel changes surface at an edge and texel under a normal map, and its history starts + // again each time. Measured 2026-12-04: with the frame's jitter kept, the output's composition gains the + // same detail in motion and none of the steadiness at rest.) + let jitter = if reconstruction.unjittered() || decoupled { (0.5, 0.5) } else { let phases = ((8.0 * (w as f32 / iw as f32) * (h as f32 / ih as f32)).round() as u32).clamp(8, 512); @@ -361,6 +388,8 @@ impl LiveCore { p.lt_cam = cam; } // Software traversal's units as edits left them: the top tree's root and how many it holds (trace_units.wgsl). + // (The output's pixels: where its guides start in the direct light's buffer, pathtrace.wgsl `guide_at`.) + p.ltile2[2] = w * h; if let Some(u) = &self.sc.up.units { (p.motion[2], p.motion[3]) = (f32::from_bits(u.layout.top_first), f32::from_bits(u.count)); } @@ -379,6 +408,7 @@ impl LiveCore { let lit = self.live_lighting(); p.cache = [1.0, CACHE_SAMPLES, if lit { CACHE_FRAMES_LIT } else { CACHE_FRAMES }, 0.0]; } + p.cache[3] = decoupled as u32 as f32; p.time[0] = shader_time(self.time); p.cam_pos = [cam.pos.x, cam.pos.y, cam.pos.z, cam.tan_half_fov]; p.cam_fwd = [cam.fwd.x, cam.fwd.y, cam.fwd.z, self.aspect]; @@ -391,7 +421,18 @@ impl LiveCore { p.counts[3] = p.counts[3].min(2); self.sc.up.place(&mut p); self.targets.kernel.place(&mut p); - g.queue.write_buffer(&self.sc.up.params, 0, bytemuck::bytes_of(&p)); + // (The guides' pass has the parameters first: it runs after what the frame prepares, before the paths.) + let gp = (decoupled && k == 0).then(|| { + let mut gp = p; + gp.jitter = [guide_jitter.0, guide_jitter.1, 0.0, 0.0]; + gp.size = [w, h, p.size[2], p.size[3]]; + gp.counts2[2] = 0; + gp.ltile[0] = 0; + self.sc.up.place(&mut gp); + self.targets.kernel.place(&mut gp); + gp + }); + g.queue.write_buffer(&self.sc.up.params, 0, bytemuck::bytes_of(gp.as_ref().unwrap_or(&p))); let mut e = g.device.create_command_encoder(&Default::default()); // Particles: placed for this frame's time and camera, then their BLASes built again (before the trace). // The grid programs (density grids changed on the GPU), before anything reads the grids. @@ -441,10 +482,29 @@ impl LiveCore { weighed = ts.is_some(); g.weigh_emitters(&self.sc.up, &mut self.weights, t.emitter_tris.len() as u32, t.light_tree.as_ref(), t.stride as u32, b.light_lod, crate::EmitterCull::of(b), &mut e, ts); } + if gp.is_some() { + { + // (The trace's time begins here: its stamps' first, the paths' pass below writing the second.) + let tw = match (&self.profile, &self.timer, timed) { + (Some(p), _, _) => Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: None }), + (None, Some(t), Some(slot)) => Some(wgpu::ComputePassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: Some(slot as u32 * TIMER_QUERIES), end_of_pass_write_index: None }), + _ => None, + }; + let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("live guides"), timestamp_writes: tw }); + pass.set_bind_group(0, &self.sc.up.bg, &[]); + pass.set_bind_group(1, &self.kernel_bg, &[]); + pass.set_pipeline(&out_guides); + pass.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1); + } + g.queue.submit([e.finish()]); + g.queue.write_buffer(&self.sc.up.params, 0, bytemuck::bytes_of(&p)); + e = g.device.create_command_encoder(&Default::default()); + } { + let begin = |i: u32| (!decoupled).then_some(i); let tw = match (&self.profile, &self.timer, timed) { - (Some(p), _, _) if k == 0 => Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) }), - (None, Some(t), Some(slot)) if k == 0 => Some(wgpu::ComputePassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: Some(slot as u32 * TIMER_QUERIES), end_of_pass_write_index: Some(slot as u32 * TIMER_QUERIES + 1) }), + (Some(p), _, _) if k == 0 => Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: begin(0), end_of_pass_write_index: Some(1) }), + (None, Some(t), Some(slot)) if k == 0 => Some(wgpu::ComputePassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: begin(slot as u32 * TIMER_QUERIES), end_of_pass_write_index: Some(slot as u32 * TIMER_QUERIES + 1) }), _ => None, }; if let Some((_, d)) = &finish { @@ -523,8 +583,8 @@ impl LiveCore { lb: [b.base_level[0], b.base_level[1], b.base_level[2], b.base_level[3]], lb2: [b.base_level[4], b.base_level[5], b.base_wide[0], b.base_wide[1]], dof: dof_params(self.view.dof.as_ref(), cam.tan_half_fov, w, h), - jit: [jitter.0, jitter.1, 0.0, 0.0], - state: [1 - self.frame % 2, 0, 0, 0], + jit: [jitter.0, jitter.1, guide_jitter.0, guide_jitter.1], + state: [1 - self.frame % 2, decoupled as u32, media as u32, (decoupled && self.prev_decoupled) as u32], lt: [tile_at.0, tile_at.1, 0, layout::light_tiles(iw)], }; g.queue.write_buffer(&self.targets.params, 0, bytemuck::bytes_of(&lp)); @@ -604,7 +664,7 @@ impl LiveCore { for (k, (name, grid, pipe)) in self.passes.pipes.iter().enumerate() { let q = (k as u32 + 1) * 2; let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(name), timestamp_writes: Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(q), end_of_pass_write_index: (!(use_provider && *name == "upscale")).then_some(q + 1) }) }); - if !reconstruction.skips(name) && (self.view_mode != 0 || !layout::VIEW_MODE_PASSES.contains(name)) && (tiles_on || *name != layout::LIGHT_TILES_PASS) { + if !reconstruction.skips(name) && (self.view_mode != 0 || !layout::VIEW_MODE_PASSES.contains(name)) && (tiles_on || *name != layout::LIGHT_TILES_PASS) && decoupled_runs(decoupled, name) { pass.set_pipeline(pipe); pass.set_bind_group(0, &self.targets.bgs[k], &[]); let (gw, gh) = grid.size((w, h), (iw, ih), self.prev_isz); @@ -640,13 +700,16 @@ impl LiveCore { tl_dispatch(&mut pass, true); continue; } - if reconstruction.skips(name) || (self.view_mode == 0 && layout::VIEW_MODE_PASSES.contains(name)) || (!tiles_on && *name == layout::LIGHT_TILES_PASS) { + if reconstruction.skips(name) || (self.view_mode == 0 && layout::VIEW_MODE_PASSES.contains(name)) || (!tiles_on && *name == layout::LIGHT_TILES_PASS) || (!decoupled && layout::DECOUPLED_PASSES.contains(name)) { continue; } - pass.set_pipeline(pipe); - pass.set_bind_group(0, &self.targets.bgs[k], &[]); - let (gw, gh) = grid.size((w, h), (iw, ih), self.prev_isz); - pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1); + // (The decoupled picture's own stage has run by `upscale`'s turn: what follows the upscaler follows it.) + if decoupled_runs(decoupled, name) { + pass.set_pipeline(pipe); + pass.set_bind_group(0, &self.targets.bgs[k], &[]); + let (gw, gh) = grid.size((w, h), (iw, ih), self.prev_isz); + pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1); + } if *name == "upscale" { tl_dispatch(&mut pass, false); tl_dispatch(&mut pass, true); @@ -732,6 +795,7 @@ impl LiveCore { self.prev_cam = cam; self.shown_spp = spp.max(1); self.prev_isz = (iw, ih); + self.prev_decoupled = decoupled; let cu = cam.uniform(self.aspect); self.light_tiles = tiles_on.then_some((layout::light_tiles(iw), tile_at.0 | tile_at.1 << 16, (iw, ih), [cu.pos, cu.fwd, cu.right, cu.up])); self.reset = false; diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs index 7962207b..4c4cef8e 100644 --- a/renderer/src/live/inplace_tests.rs +++ b/renderer/src/live/inplace_tests.rs @@ -4007,7 +4007,8 @@ fn a_hidden_volumes_passes_are_made_at_load() { } /// A bright HDR panel catches clipping before reconstruction, stale bindings after resize, and -/// carrying temporal history through a cut. MetalFX methods run only where the SDK supports them. +/// carrying temporal history through a cut. Both of ThreeRT's own methods, and the providers; MetalFX methods run +/// only where the SDK supports them. #[test] fn reconstruction_keeps_hdr_emitters_and_resets_on_a_cut() { let Ok(gpu) = gpu::Gpu::new() else { return }; @@ -4027,6 +4028,8 @@ fn reconstruction_keeps_hdr_emitters_and_resets_on_a_cut() { [hdr[p], hdr[p + 1], hdr[p + 2]] }; let methods = [ + Method::Builtin, + Method::BuiltinUpscaler, Method::Fsr, Method::Off, #[cfg(metalfx)] @@ -4039,8 +4042,8 @@ fn reconstruction_keeps_hdr_emitters_and_resets_on_a_cut() { core.set_reconstruction(method.clone()); core.set_camera(scene_cam); for _ in 0..16 { core.render(1, |_, _| {}); } - if core.reconstruction() == Method::Builtin { - assert!(!matches!(method, Method::Fsr | Method::Off)); + if core.reconstruction() != method { + assert!(!matches!(method, Method::Builtin | Method::BuiltinUpscaler | Method::Fsr | Method::Off)); eprintln!("{} unsupported on this device: {:?}", method.name(), core.reconstruction_status().skipped); continue; } @@ -4117,6 +4120,9 @@ fn reconstruction_takes_the_first_method_that_runs_and_says_why() { assert_eq!(Reconstruction::parse("metalfx-denoised, builtin").unwrap(), Reconstruction::Prefer(vec![Method::MetalFxDenoised, Method::Builtin])); assert_eq!(Reconstruction::from_json(&serde_json::json!(["dlss-rr", "fsr"])).unwrap().name(), "dlss-rr,fsr"); assert_eq!(Reconstruction::parse("auto").unwrap(), Reconstruction::Auto); + assert_eq!(Reconstruction::parse("builtin-upscaler,builtin").unwrap(), Reconstruction::Prefer(vec![Method::BuiltinUpscaler, Method::Builtin])); + assert_eq!(Reconstruction::default(), Reconstruction::Prefer(vec![Method::Builtin]), "the output composed from its own guides is the default"); + assert_eq!(Method::platform()[..2], [Method::Builtin, Method::BuiltinUpscaler]); assert!(Reconstruction::parse("dlss-fg").is_err()); let r = RenderingRequest::from_json(&serde_json::json!({ "quality": "ultra-performance", "latency": "on", "frameGeneration": "2x" })).unwrap(); assert_eq!(((1920.0 * r.quality.unwrap().scale().unwrap()) as f32).round(), 640.0, "a third of 1080p's width is DLSS's 640"); @@ -4281,6 +4287,76 @@ fn checker(width: u32, height: u32, cell: u32, a: [u8; 3], b: [u8; 3]) -> crate: crate::world::Texture { source: crate::world::TextureSource::Pixels { width, height, rgba: std::sync::Arc::new(rgba) }, srgb: true, wrap: true, repeat: [1.0, 1.0], offset: [0.0, 0.0] } } +/// Of the fine detail of `want` (each pixel's luminance less the mean of the 5 x 5 pixels around it), the share +/// `got` has: 1 where all of it is there, 0 where none is. Pictures of `w` pixels a row, RGB. +fn detail_share(got: &[f32], want: &[f32], w: usize) -> f64 { + let h = want.len() / 3 / w; + let fine = |p: &[f32]| -> Vec { + let l = |x: usize, y: usize| { let k = (y * w + x) * 3; 0.2126 * p[k] as f64 + 0.7152 * p[k + 1] as f64 + 0.0722 * p[k + 2] as f64 }; + (2..h - 2).flat_map(|y| (2..w - 2).map(move |x| (x, y))).map(|(x, y)| { + let mean = (y - 2..=y + 2).flat_map(|j| (x - 2..=x + 2).map(move |i| (i, j))).map(|(i, j)| l(i, j)).sum::() / 25.0; + l(x, y) - mean + }).collect() + }; + let (g, t) = (fine(got), fine(want)); + g.iter().zip(&t).map(|(a, b)| a * b).sum::() / t.iter().map(|b| b * b).sum::() +} + +/// Under a render scale of 1 `builtin` composes the output from guides of its own: the camera's rays for every +/// output pixel each frame (a surface's colour, its normal and distance, the light that is its own and the sun's), +/// and the lighting from the traced grid. A wall's texture of cells 2 output pixels wide, a traced pixel each, is +/// there in the frame after a cut, lit by an emitter (the traced grid's lighting times the output's colour) and by +/// a sun (the output's own). The upscaler (`builtin-upscaler`) has in that frame what the traced grid has, and the +/// rest as its history gathers the jittered samples. +#[test] +fn builtin_composes_the_output_from_guides_of_its_own() { + let json = |v: serde_json::Value| serde_json::from_value::(v).unwrap(); + for sun in [false, true] { + let Ok(g) = gpu::Gpu::new() else { return }; + let what = if sun { "lit by a sun" } else { "lit by an emitter" }; + let mut w = wall_world(2.2, serde_json::json!({ "name": "glow", "color": [0, 0, 0], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": 40, "doubleSided": true })); + w.set_geometry(1, Geometry { positions: vec![-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 1.0, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] }).unwrap(); + w.set_texture(30, checker(48, 48, 1, [235, 235, 235], [30, 30, 30])).unwrap(); + w.set_material(1, json(serde_json::json!({ "name": "checks", "color": [1, 1, 1], "map": 30, "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true }))); + if sun { + let light = serde_json::from_value(serde_json::json!({ "type": "directional", "color": [1.0, 0.9, 0.8], "castShadow": true, "intensity": 2.0, "angularDiameter": 0.5 })).unwrap(); + w.set_object(20, "sun".into(), None, Kind::Light(light), true, false).unwrap(); + w.set_transform(20, Vec3::ZERO, glam::Quat::from_rotation_x(-0.5) * glam::Quat::from_rotation_y(0.4), Vec3::ONE).unwrap(); + } else { + // (Behind the camera.) + w.set_geometry(21, Geometry { positions: vec![-0.4, -0.4, 0.0, 0.4, -0.4, 0.0, 0.4, 0.4, 0.0, -0.4, 0.4, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0; 8], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] }).unwrap(); + w.set_object(21, "lamp".into(), None, Kind::Mesh { geometry: 21, material: 3, own_blas: false, materials: vec![] }, true, false).unwrap(); + w.set_transform(21, Vec3::new(0.0, 0.0, 3.2), glam::Quat::IDENTITY, Vec3::ONE).unwrap(); + } + let mut live = LiveCore::new(g, &w, Path::new("."), &crate::default_presets_dir(), 192, 108).unwrap(); + live.view_mode = 0; + live.fixed_dt = Some(1.0 / 60.0); + let shot = |live: &mut LiveCore, method: Method, scale: f32, frames: u32| { + live.set_scale(scale); + live.set_reconstruction(method.clone()); + forget(live); + for _ in 0..frames { live.render(1, |_, _| {}); } + assert_eq!(live.reconstruction(), method); + live.read_hdr().unwrap() + }; + // (At scale 1 the two grids are one and both methods are the upscaler's passes.) + let want = shot(&mut live, Method::Builtin, 1.0, 48); + assert!(want.iter().all(|v| v.is_finite()) && want.iter().sum::() > 0.0, "{what}: a picture"); + // Read on an M4: composed 1.32 after one frame (one sample a pixel has the cells' whole contrast, which the + // picture at scale 1 has less its filter's blur) and 1.18 after eight; upscaled 0.54 and 1.02. + for (frames, least) in [(1, 0.9), (8, 0.9)] { + let composed = shot(&mut live, Method::Builtin, 0.5, frames); + assert_eq!(live.reconstruction_status().upscale, "builtin"); + let share = detail_share(&composed, &want, 192); + assert!(share > least && share < 1.6, "{what}: {share:.3} of the texture's detail after {frames} frames"); + } + let upscaled = shot(&mut live, Method::BuiltinUpscaler, 0.5, 1); + assert_eq!(live.reconstruction_status().upscale, "builtin-upscaler"); + let share = detail_share(&upscaled, &want, 192); + assert!(share < 0.75, "{what}: the traced grid alone has {share:.3} of the texture's detail in a first frame"); + } +} + /// By world material: the keys of the textures its slots name in the pages (base, normal, roughness, metalness, /// emissive, occlusion), None where it names none. Where in the pages a texture lies, and its number, are a view's own. fn textures_named(c: &LiveCore) -> std::collections::BTreeMap>> { diff --git a/renderer/src/live/layout.rs b/renderer/src/live/layout.rs index 20f88f62..45de3bd7 100644 --- a/renderer/src/live/layout.rs +++ b/renderer/src/live/layout.rs @@ -89,6 +89,8 @@ pub(super) const RESOURCES: &[(&str, Res)] = &[ ("light_rw", Res::KernelReports), ("light_lists", Res::KernelLists), ("lock_fwd", Res::Own(Count::Pixels(1))), + ("gout", Res::Own(Count::Pixels(1))), + ("thin", Res::Own(Count::Pixels(3))), ]; /// The grid a pass runs over, in invocations (workgroups of 8 x 8). @@ -128,9 +130,12 @@ pub(super) const PASSES: &[(&str, Grid)] = &[ ("sfilt2", Grid::Traced), ("lock_carry", Grid::PrevTraced), ("compose", Grid::Traced), + ("gcompose", Grid::Output), ("track", Grid::Traced), ("judge", Grid::Traced), ("reject", Grid::Traced), + ("gcarry", Grid::Output), + ("gupscale", Grid::Output), ("upscale", Grid::Output), ("dof_tiles", Grid::Tiles16), ("dof", Grid::Output), @@ -160,6 +165,11 @@ pub(super) const PASSES: &[(&str, Grid)] = &[ /// per-pass profile times an empty pass for each, to keep its timestamps in `PASSES`' order). pub(super) const VIEW_MODE_PASSES: &[&str] = &["view_raw", "view_hdr", "view_sample"]; +/// The output grid's own composition and its history (frame.rs `decoupled`): run only when the guides are traced +/// for them; and the passes they stand in for (the upscaler, and the thin features' locks, which it alone reads). +pub(super) const DECOUPLED_PASSES: &[&str] = &["gcompose", "gcarry", "gupscale"]; +pub(super) const DECOUPLED_SKIPS: &[&str] = &["lock_carry", "upscale"]; + /// The light tiles' pass: run only in a scene whose local lights are resampled (more than the kernel sums exactly). pub(super) const LIGHT_TILES_PASS: &str = "light_tiles"; diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs index 70125582..f363f6ac 100644 --- a/renderer/src/live/mod.rs +++ b/renderer/src/live/mod.rs @@ -152,9 +152,12 @@ struct LiveParams { lb2: [f32; 4], /// Depth of field: CoC radius of infinity (output px; 0 = off), focus distance (m), max radius (px), -. dof: [f32; 4], - /// This frame's sub-pixel jitter (every camera ray's: x, y in 0 .. 1 of a traced pixel), -, -. + /// This frame's sub-pixel jitter (every traced sample's: x, y in 0 .. 1 of a traced pixel); the output grid's + /// guides' (z, w in 0 .. 1 of an output pixel: frame.rs `decoupled`). jit: [f32; 4], - /// Which half of the lasting buffers is this frame's (live.wgsl `this_half`; the other the previous frame's), -. + /// Which half of the lasting buffers is this frame's (live.wgsl `this_half`; the other the previous frame's); the + /// output is composed from guides of its own (1); the scene has media the camera's rays are marched through + /// (1); the previous frame's output was composed so too (1: its thin things' records are there to carry). state: [u32; 4], /// The light tiles (live.wgsl `light_tiles`): this frame's grid offset x, y, -, tiles a row. lt: [u32; 4], @@ -388,6 +391,9 @@ pub struct LiveCore { inst_moved: bool, /// The previous frame's traced size (its traced-grid diffuse history; 0 before the first frame). prev_isz: (u32, u32), + /// The previous frame composed its output from guides of its own (frame.rs `decoupled`): its thin things' records + /// are this frame's to carry (live.wgsl `Thin`). + prev_decoupled: bool, /// The light tiles' lists as the last frame built them (pathtrace.wgsl `Params::ltile`'s y, z, `ltile2`'s size /// and `lt_cam`, that frame's camera): what this frame's paths take candidates from. None: no lists (the first /// frame, after a reset, a scene whose local lights are summed exactly). @@ -590,7 +596,7 @@ impl LiveCore { let mut core = LiveCore { kernel: None, more_features: Default::default(), - reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], weights_dirty: true, weights: None, slot_used: false, flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, 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: Default::default(), 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, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, direct_pass: std::env::var("THREERT_DIRECT_PASS").map_or(true, |v| v != "0"), view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, 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, cache, kernel_bg, tl_kernel_bg, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], 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, guard_trips: guard_read.as_ref().map(|_| 0), guard_read }; + reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], weights_dirty: true, weights: None, slot_used: false, flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, 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: Default::default(), 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, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, direct_pass: std::env::var("THREERT_DIRECT_PASS").map_or(true, |v| v != "0"), view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, 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, cache, kernel_bg, tl_kernel_bg, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), prev_decoupled: false, 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, guard_trips: guard_read.as_ref().map(|_| 0), guard_read }; core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal); core.apply_post(); Ok(core) @@ -836,6 +842,25 @@ impl LiveCore { (self.kernel_bg, self.tl_kernel_bg) = kernel_bind_groups(&self.g, &self.targets); } + /// Room after the traced pixels' direct light for the output grid's guides (`media`: and a medium's record a + /// traced pixel), where a frame's output is composed from them (frame.rs `decoupled`). The kernel's buffers are + /// made again for it once, as for `ensure_first`. + pub(super) fn ensure_guides(&mut self, media: bool) { + let direct = if media { 4 } else { 3 }; + if self.targets.direct >= direct { + return; + } + self.targets.grow_direct(&self.g, &self.passes, direct); + // (The merged layout's cache is in the buffer made again, as in `ensure_first`.) + if self.g.merged { + if let Some(c) = &mut self.cache { + c.bufs = self.targets.kernel.cache.clone(); + } + (self.reset, self.prev_isz) = (true, (0, 0)); + } + (self.kernel_bg, self.tl_kernel_bg) = kernel_bind_groups(&self.g, &self.targets); + } + /// Room for a frame's camera hits at `pixels` traced pixels: 32 bytes each, 96 more for a mirror chain in a /// scene that has a mirror (`gpu::F_MIRROR`; pathtrace.wgsl `Chain`: without the room the first pass follows no /// mirror), and the surface the paths find there (`gpu::SURFACE_BYTES`: without the room the paths light it diff --git a/renderer/src/live/reconstruction.rs b/renderer/src/live/reconstruction.rs index c96b6606..651f2f4e 100644 --- a/renderer/src/live/reconstruction.rs +++ b/renderer/src/live/reconstruction.rs @@ -28,8 +28,13 @@ use wgpu::{CommandBuffer, CommandEncoder, TextureView}; /// One way of reconstructing the frame: who denoises and who upscales. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Method { - /// ThreeRT's denoiser, then its temporal upscaler. + /// ThreeRT's denoiser, then the output composed from guides of its own: the camera's rays for every output + /// pixel each frame, the lighting on the traced grid (frame.rs `decoupled`). At scale 1 the two grids are one + /// and it is `builtin-upscaler`. Builtin, + /// ThreeRT's denoiser, then its temporal upscaler: the camera's rays at the render resolution alone (what + /// `builtin` was before the output had guides of its own). + BuiltinUpscaler, /// Neither: each frame's samples as traced (the signal a joint denoiser receives), brought to the output size /// without history. A view of the input, not a way to ship. Off, @@ -51,6 +56,7 @@ impl Method { pub fn name(&self) -> &str { match self { Self::Builtin => "builtin", + Self::BuiltinUpscaler => "builtin-upscaler", Self::Off => "off", Self::Fsr => "fsr", Self::MetalFx => "metalfx", @@ -64,6 +70,7 @@ impl Method { pub fn parse(s: &str) -> Result { Ok(match s.trim() { "builtin" => Self::Builtin, + "builtin-upscaler" => Self::BuiltinUpscaler, "off" => Self::Off, "fsr" => Self::Fsr, "metalfx" => Self::MetalFx, @@ -73,13 +80,13 @@ impl Method { s if s.strip_prefix("custom:").is_some_and(|id| { (1..=48).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') }) => Self::Custom(Arc::from(s)), - s => anyhow::bail!("unknown reconstruction '{s}'; use auto, builtin, off, fsr, metalfx, metalfx-denoised, dlss, dlss-rr or custom:"), + s => anyhow::bail!("unknown reconstruction '{s}'; use auto, builtin, builtin-upscaler, off, fsr, metalfx, metalfx-denoised, dlss, dlss-rr or custom:"), }) } /// The methods this build could run on its platform, in the order the viewer's key cycles them. pub fn platform() -> Vec { - let mut m = vec![Self::Builtin]; + let mut m = vec![Self::Builtin, Self::BuiltinUpscaler]; #[cfg(metalfx)] m.extend([Self::MetalFxDenoised, Self::MetalFx]); #[cfg(dlss)] @@ -282,6 +289,7 @@ impl Provider { pub(super) enum Active { #[default] Builtin, + BuiltinUpscaler, Off, Fsr, /// `providers[i]`, an upscaler. @@ -314,6 +322,9 @@ impl Active { /// No sub-pixel jitter: nothing accumulates it. pub(super) fn unjittered(self) -> bool { matches!(self, Self::Off | Self::Fsr) } + /// The output is composed from guides of its own where the traced grid is coarser than it (frame.rs `decoupled`). + pub(super) fn composes_output(self) -> bool { self == Self::Builtin } + /// A provider takes the upscale stage's place (its passes do not run; it does, where `upscale` would). pub(super) fn external(self) -> bool { matches!(self, Self::Fsr | Self::Upscaler(_) | Self::Joint(_)) } @@ -436,6 +447,7 @@ impl Reconstructor { pub(super) fn method(&self) -> Method { match self.active { Active::Builtin => Method::Builtin, + Active::BuiltinUpscaler => Method::BuiltinUpscaler, Active::Off => Method::Off, Active::Fsr => Method::Fsr, Active::Upscaler(i) | Active::Joint(i) => self.providers[i].0.clone(), @@ -446,6 +458,7 @@ impl Reconstructor { let m = self.method(); let (denoise, upscale) = match self.active { Active::Builtin => ("builtin".into(), "builtin".into()), + Active::BuiltinUpscaler => ("builtin".into(), "builtin-upscaler".into()), Active::Off => ("none".into(), "none".into()), Active::Fsr | Active::Upscaler(_) => ("builtin".into(), m.name().into()), Active::Joint(_) => (m.name().into(), m.name().into()), @@ -467,7 +480,7 @@ impl Reconstructor { let old = self.active; self.skipped.clear(); self.active = if diagnostic { - if let Some(m) = self.requested.chain().into_iter().find(|m| *m != Method::Builtin) { + if let Some(m) = self.requested.chain().into_iter().find(|m| !matches!(m, Method::Builtin | Method::BuiltinUpscaler)) { self.skipped.push((m, Skip::DiagnosticView, "a view mode shows ThreeRT's own buffers".into())); } Active::Builtin @@ -508,6 +521,7 @@ impl Reconstructor { fn try_method(&mut self, g: &gpu::Gpu, targets: &Targets, m: &Method, size: ReconstructionSize) -> std::result::Result { match m { Method::Builtin => return Ok(Active::Builtin), + Method::BuiltinUpscaler => return Ok(Active::BuiltinUpscaler), Method::Off => return Ok(Active::Off), _ => {} } @@ -568,7 +582,7 @@ impl Reconstructor { cam: Camera, aspect: f32, jitter: (f32, f32), exposure: f32, reset: bool, ) -> Result> { let i = match self.active { - Active::Builtin | Active::Off => return Ok(None), + Active::Builtin | Active::BuiltinUpscaler | Active::Off => return Ok(None), Active::Fsr => { self.fsr.as_ref().unwrap().encode(e); return Ok(None); } Active::Upscaler(i) | Active::Joint(i) => i, }; diff --git a/renderer/src/live/targets.rs b/renderer/src/live/targets.rs index 35a6a2a8..6d9e4ef2 100644 --- a/renderer/src/live/targets.rs +++ b/renderer/src/live/targets.rs @@ -106,12 +106,17 @@ pub struct Targets { /// The bind group of each pass, in `Passes::pipes`' order. pub(super) bgs: Vec, size: (u32, u32), + /// The direct light's buffer, in outputs of vec4s (`kernel_bytes`). + pub(super) direct: u64, } /// 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] { +/// `direct`: the direct light's buffer in outputs of vec4s: 1, the traced pixels' direct light alone; 3 with the +/// output grid's guides after it (two vec4s an output pixel: pathtrace.wgsl `guide_at`), 4 with a medium's record a +/// traced pixel after those (`seen_medium_at`). +fn kernel_bytes(w: u32, h: u32, direct: u64) -> [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 * 32, n * 16, n * 16 * direct, layout::light_lists(w, h) as u64 * 16, n * 32] } impl Targets { @@ -140,7 +145,8 @@ impl Targets { accum: g.accum_buffer(w, h), bufs, out, - kernel: gpu::KernelBufs::new(d, g.merged, g.guard_room(), cache, kernel_bytes(w, h)), + kernel: gpu::KernelBufs::new(d, g.merged, g.guard_room(), cache, kernel_bytes(w, h, 1)), + direct: 1, translucent_low: None, lut_view: lut_tex.create_view(&Default::default()), lut_tex, @@ -159,6 +165,14 @@ impl Targets { self.bgs = self.bind_groups(&g.device, passes); } + /// The kernel's buffers with the direct light's of `direct` outputs of vec4s (`kernel_bytes`: room for the output + /// grid's guides, and a medium's records), and the passes' bind groups over them. As `grow_first`. + pub(super) fn grow_direct(&mut self, g: &gpu::Gpu, passes: &Passes, direct: u64) { + self.direct = direct; + self.kernel = self.kernel.with_direct(&g.device, kernel_bytes(self.size.0, self.size.1, direct)[2]); + self.bgs = self.bind_groups(&g.device, passes); + } + /// For another size: what follows it is made again (the samples, the passes' own buffers and the output, the /// kernel's four, the translucent particles'), with the bind groups over them. The radiance cache, which is the /// world's, the passes' parameters and the tone-map table stay. (The merged layout keeps the cache in one buffer @@ -167,7 +181,7 @@ impl Targets { let d = &g.device; (self.bufs, self.out) = Self::own(d, w, h); self.accum = g.accum_buffer(w, h); - self.kernel = self.kernel.resized(d, kernel_bytes(w, h)); + self.kernel = self.kernel.resized(d, kernel_bytes(w, h, self.direct)); self.translucent_low = None; self.size = (w, h); self.bgs = self.bind_groups(d, passes); diff --git a/tests/render/compose-dimming-behind-edge-live.ts b/tests/render/compose-dimming-behind-edge-live.ts new file mode 100644 index 00000000..94aac38d --- /dev/null +++ b/tests/render/compose-dimming-behind-edge-live.ts @@ -0,0 +1,14 @@ +// upscale/dimming-behind-edge-live at half the render scale, where the output is composed from guides of its own +// (live.wgsl `gcompose`, `gupscale`): the emitting wall is each output pixel's own light, and its history beside the +// slab's edge follows as fast as far from it. +import type { TestMeta } from "./lib.ts"; + +export { default } from "./upscale-dimming-behind-edge-live.ts"; + +export const test: TestMeta = { + id: "compose/dimming-behind-edge-live", features: ["dynamic-emission", "upscaler"], reference: "analytic", temporal: true, + metric: { kind: "ratio", a: [0.5063, 0.3, 0.5313, 0.7], b: [0.8, 0.3, 0.95, 0.7], expected: 1, tolerance: 0.1 }, + scale: 0.5, + live: 90, + note: "a wall 4 % dimmer every frame behind a black slab's edge: its four pixels beside the edge (the second to the fifth) as far from it", +}; diff --git a/tests/render/compose-lamps-parallax-live.ts b/tests/render/compose-lamps-parallax-live.ts new file mode 100644 index 00000000..8c9d9fa1 --- /dev/null +++ b/tests/render/compose-lamps-parallax-live.ts @@ -0,0 +1,17 @@ +// upscale/lamps-parallax-live at half the render scale, where the output is composed from guides of its own (live.wgsl +// `Thin`): a lamp a guide saw is recorded with its distance and carried by the two cameras while the guides of the +// frames after miss it, so its light goes with it and not with the sky behind. Without the records the band beside +// the field's edge held 0.79 of the field's mean; with them 0.003, and the field in its slide has 1.10 of the lamps' +// light (held still 1.06; under the upscaler at this scale 0.33). +import type { TestMeta } from "./lib.ts"; + +export { default } from "./upscale-lamps-parallax-live.ts"; + +export const test: TestMeta = { + id: "compose/lamps-parallax-live", features: ["dynamic-emission", "upscaler", "procedural"], reference: "analytic", temporal: true, + // The field's edge ends 30.5 pixels left of the centre (u 0.309): b the field, a the sky beside it. + metric: { kind: "ratio", a: [0.315, 0.3, 0.4, 0.7], b: [0.1, 0.3, 0.28, 0.7], expected: 0, tolerance: 0.1 }, + scale: 0.5, + live: 60, + note: "lamps a third of a pixel wide before the black sky, the camera sliding 1.4 pixels a frame: no light beside the field", +}; diff --git a/tests/render/compose-lamps-still-live.ts b/tests/render/compose-lamps-still-live.ts new file mode 100644 index 00000000..8917836f --- /dev/null +++ b/tests/render/compose-lamps-still-live.ts @@ -0,0 +1,14 @@ +// upscale/lamps-still-live at half the render scale, where the output is composed from guides of its own (live.wgsl +// `gcompose`, `gupscale`): a lamp is a third of an output pixel wide, a guide in nine sees it, and the field keeps +// its light. +import type { TestMeta } from "./lib.ts"; + +export { default } from "./upscale-lamps-still-live.ts"; + +export const test: TestMeta = { + id: "compose/lamps-still-live", features: ["dynamic-emission", "upscaler", "procedural"], reference: "analytic", temporal: true, + metric: { kind: "radiance", region: [0.3, 0.3, 0.7, 0.7], expected: 0.1, tolerance: 0.1 }, + scale: 0.5, + live: 60, + note: "lamps a third of a pixel wide, 1.44 % of the field at 6.94 nits, the view still: 0.1", +}; diff --git a/tests/render/lib.ts b/tests/render/lib.ts index 544b64fd..6a55b010 100644 --- a/tests/render/lib.ts +++ b/tests/render/lib.ts @@ -24,6 +24,10 @@ export interface TestMeta { spp?: number; /** Render with the real-time renderer for this many frames (radiance cache, temporal passes) instead. */ live?: number; + /** A live test's render scale (default 1: the traced grid is the output's) and its reconstruction method + * (default `builtin`; docs/RUNTIME.md "Live rendering settings"). */ + scale?: number; + reconstruction?: string; /** A live test's approximations (`APPROX` bits; default all of them: the live view as it ships). */ approx?: number; /** Scene time, s (animated materials; default 0). */ diff --git a/tools/test-render.ts b/tools/test-render.ts index bf7b64ce..8780878b 100644 --- a/tools/test-render.ts +++ b/tools/test-render.ts @@ -65,7 +65,7 @@ for (const { file, meta } of tests) { const name = file.replace(/\.ts$/, ""); const bundle = (await bundleGame(join(dir, file), join(out, `${name}.js`))).out; const hdr = join(out, `${name}.raw`); - proc.stdin!.write(JSON.stringify({ id: ++id, game: bundle, assets, out: join(out, `${name}.png`), hdr, spp: meta.spp ?? 64, denoise: false, live: meta.live, approx: meta.approx, time: meta.time }) + "\n"); + proc.stdin!.write(JSON.stringify({ id: ++id, game: bundle, assets, out: join(out, `${name}.png`), hdr, spp: meta.spp ?? 64, denoise: false, live: meta.live, scale: meta.scale, reconstruction: meta.reconstruction, approx: meta.approx, time: meta.time }) + "\n"); const reply = JSON.parse((await lines.next()).value as string); const ms = performance.now() - t; if (!reply.ok) { From f9eb40f3409d8168928587d4449413e953774da9 Mon Sep 17 00:00:00 2001 From: yujiaxu Date: Fri, 4 Dec 2026 15:15:41 +0800 Subject: [PATCH 2/2] The roadmap's entry for the output composed from its guides What it is, what was measured against main (two scenes in motion, the benches, twelve clips against offline), what it costs, what was tried and not kept, and what is not done. Co-Authored-By: Claude Fable 5.2 --- docs/ROADMAP.md | 91 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index bd2313fc..abae37c6 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -2647,6 +2647,97 @@ Not done. A mesh that comes by an edit (a streamed city's cells are those) is he come some frames after its build, its instances be placed again, and a mesh that is rebuilt every frame left alone. wgpu has no refit (`PreferUpdate` builds): a deforming mesh is rebuilt. Not checked on Vulkan. +**The output is composed from guides of its own (2026-12-04, after it).** The entries above found the picture's +error in motion to be the reconstruction's, three to four times what it is at rest. Its cause is where the histories +live: the lighting's are on the traced grid, and the frame's jitter moves every traced sample over its pixel. At an +edge the sample changes surface and under a normal map texel, its histories start again, and the upscaler has the +surfaces of an output pixel only as its history gathers them, which a pixel that moves does not let it. Offline, the +same frames with the lighting kept at half rate and the surfaces given at the output's (eleven moments of two +scenes) had 0.83 to 0.87 of the offline render's detail on the street and 0.72 to 0.80 in the hall, where the +upscaler has 0.68 and 0.58 at rest and 0.39 to 0.47 and 0.37 to 0.46 moving. + +- Under a render scale of 1 the frame has two grids (live/frame.rs `decoupled`; docs/RUNTIME.md "ThreeRT's own: the + output composed from its guides"). The kernel's `guides` pass traces the camera's ray for every output pixel each + frame, at one of eight places in the pixel: distance, colour, normal, and the pixel's own light (what it sees + directly; the directional lights' direct light with a shadow ray of its own, so a sun's shadow has the output's + edge). The traced grid's samples stand still, and their histories are of one place. `gcompose` gives an output + pixel the denoised lighting of the traced samples on its surface, times its colour, plus its light; `gupscale` + keeps the output's history, judged by `track`, `judge` and `reject` as the upscaler's is. +- A thing thinner than two output pixels is the output grid's to keep (live.wgsl `Thin`). A guide in nine sees a + lamp a third of a pixel wide; the traced samples, which no longer move, see it always or never, so the upscaler's + locks say nothing here. A guide nearer than both of some pair of opposite neighbours, with no 2 x 2 block like it, + is recorded with its distance and its place, and `gcarry` takes the record on by the two cameras while the guides + of the frames after miss it: the history there moves with the thing, is spared the clamp in motion, and where the + thing has gone on and the frame does not explain the colour left, the history is dropped. upscale/lamps-parallax + at half scale (compose/lamps-parallax-live): beside the sliding field's edge 0.79 of the field's mean light + without the records, 0.003 with them (the upscaler at that scale 0.003); the field in its slide has 1.10 of the + lamps' light (held still 1.06), for the upscaler's 0.33 at that scale and 0.79 at scale 1. +- A setting: reconstruction `builtin` is this where the traced grid is coarser than the output, and the default; + `builtin-upscaler` is the frame as it was (one jitter for every ray, `judge`, `reject`, `upscale`, the locks), and + what `builtin` runs at scale 1 and in a diagnostic view. With `builtin-upscaler` the street's measures and its + frame's time are main's. + +Measured on an M4 at half resolution, main → this. + +- Two scenes recorded in lockstep at 1280 × 720 while the camera turns, strafes, orbits and stops. The street: the + change of 4 × 4 block means from a frame to the next 0.138 → 0.046 held still, 0.437 → 0.189 after the turn, 0.636 + → 0.302 after the strafe, 0.684 → 0.202 after the stop; per pixel 0.304 → 0.134, 0.543 → 0.262, 0.752 → 0.403, + 0.718 → 0.376. Of the offline render's detail 0.681 → 0.776 still, 0.459 → 0.551 mid-turn, 0.467 → 0.578 + mid-strafe, 0.387 → 0.477 as the camera stops, along its walk 0.369 → 0.452, 0.412 → 0.539, 0.385 → 0.534; ΔE 2.05 + → 1.92, 2.80 → 2.63, 3.11 → 2.94, 3.52 → 3.33, 3.77 → 3.55, 3.73 → 3.43, 4.64 → 3.95. The hall, its machines + moving throughout: block means 1.411 → 1.435 still, 1.520 → 1.261, 2.217 → 1.798, 2.032 → 1.933, and a moment + after the stop 0.944 → 1.065; per pixel 1.407 → 1.229, 1.763 → 1.090, 2.165 → 1.043, 2.075 → 1.015; detail 0.583 + → 0.645 still, 0.462 → 0.538, 0.407 → 0.505, 0.290 → 0.405 as the camera stops, along its path 0.402 → 0.542 and + 0.415 → 0.519; ΔE 3.87 → 3.87, 4.76 → 4.59, 4.80 → 4.79, 5.61 → 5.44, 4.87 → 4.62, 4.12 → 3.88. +- `bench-object-ghosting`: ΔE over the sixteen moments 20 % less in the mean (the device's slide 1.84 → 1.39, the + end of its lift 1.01 → 0.38, the thrown lamp in flight 9.88 → 8.83; the runner 0.41 → 0.43 and, a third of a + second after, 0.30 → 0.33). `bench-temporal --shot edit`: a lamp switched off, its pool settled in 32 frames for + 64; switched on, its bounce at 32 frames has 0.925 of its settled light for 0.876; a sign switched off, its floor + at 32 frames ΔE 0.99 for 0.79. +- `bench-ghosting --quick --check` passes, with more excess than main's: mid-turn 0.79 → 1.10 (trail 5 → 10 pixels), + mid-strafe 1.27 → 1.36, half a second after the turn's return 1.03 → 1.30, a tenth of a second after the stop 1.46 + → 1.67 (5 → 11 pixels). Not explained. +- Twelve clips against offline, this build beside main's (main, this, this, main). ΔE: a crowded night street 3.34 + → 3.11, the city 2.04 → 1.87, the hall 3.21 → 3.14, coloured lights 1.25 → 1.21, rooms 0.88 → 0.83, foliage 0.80 → + 0.75; a neon street 1.51 both; a home 2.87 → 2.92, metals and gems 2.32 → 2.35, refraction 0.88 → 0.89, a museum + 1.28 → 1.29 (not explained). Detail: the crowd 0.491 → 0.593, the hall 0.677 → 0.741, the home 0.923 → 0.996, + coloured lights 0.886 → 0.953, refraction 0.928 → 0.966, the museum 0.886 → 0.955, rooms 0.836 → 0.876, foliage + 0.835 → 0.889; the city 0.906 → 1.152 (more than the offline render's own: the measure is a regression on its + gradients, and a picture sharper than the reference's pixels reads over 1); metals and gems 0.311 both; the neon + street 0.715 → 0.693. Whole pixels' change from a frame to the next: less on ten (the home 1.256 → 0.574, the neon + street 0.137 → 0.063, the museum 0.206 → 0.103, the crowd 1.267 → 1.007, the city 0.482 → 0.364), foliage 1.461 → + 1.518. +- What it costs: a camera ray an output pixel. A frame's GPU time on the twelve clips 7 to 31 % more: the crowd + 10.35 → 13.61 ms, the city 18.24 → 20.43, the neon street 12.40 → 13.58, the hall 11.67 → 14.72, a voxel level + 16.68 → 19.37, the home 13.57 → 15.79, coloured lights 14.73 → 15.83, metals and gems 13.43 → 15.04, refraction + 11.83 → 13.04, the museum 12.50 → 14.60, rooms 5.43 → 6.62, foliage 11.56 → 13.80. The street at 1280 × 720: 16.3 → + 20.5 at rest and 18.2 → 22.0 walking, of which the trace 10.3 → 13.6 and 11.8 → 14.8 (the guides), `gcompose` + 0.72, `gcarry` 0.05 and `gupscale` 0.87 (1.10 walking) for `upscale`'s 0.67 (1.02) and `lock_carry`'s 0.09. + Buffers: 60 bytes an output pixel more, 76 where the scene has media. +- The guides are an entry point of the kernel of their own. Run as a mode of `main` they took 6.5 ms on the street + and the crowd's frame was 118 % dearer, not 31: `main`'s weight an invocation, not the rays. +- Under software traversal (`THREERT_HWRT=0`) the street's picture is within 0.005 of this in detail and 0.04 in ΔE, + and the three new render tests pass. Unit suite 298 (one new: a wall's texture of cells two output pixels wide is + in the frame after a cut, lit by an emitter and by a sun, where the traced grid alone has half of it), render suite + 280 (three new: the upscaler's three at half scale). + +Tried and not kept, each measured: the traced samples kept on the frame's jitter (the same detail in motion, none +of the steadiness at rest); the history following the composition's level everywhere (the street held still +changed 0.41 for 0.046: it follows only while the scene's lighting changes, by 3 % a frame); a rule that takes a +frame whole where it differs much (a bright outlier passes for a lamp switched on: 1.09); the frame without +`track`, `judge` and `reject` (what a moving object leaves behind 28 % further from its settled frame, a lamp's +bounce four times as long to settle); a jitter that keeps each traced sample on its surface, and guides for half +the pixels a frame (no better, or dearer than what they save); the lighting's direction kept with it (no gain +offline); paths only where the lighting's variance asks (97 to 100 % of them would still be traced). At equal frame +time, the lighting's scale lowered to pay for the guides, the picture was a trade (ΔE 5 to 18 % worse; before the +guides had their own pass). + +Not done. The guides are traced: rasterised they would cost a fraction, and that is what is left of the frame's +time to gain here. A lamp or a lit window thinner than a pixel that is part of a larger surface has no record (its +distance is its surface's): in motion the clamp cuts its light, as the upscaler's did before its locks. A thing on a +surface that moves by itself is not recorded either. Dynamic resolution pays for the guides with a lower scale: not +measured. Not checked on Vulkan, nor in a browser (both of its modules build). + **The live passes from one place (2026-11-14, after it).** A buffer and a pass more (the locks' carry, above) took seven edits that had to agree: the declaration in live.wgsl, the bind group layout's entries, the pass list, the buffers' sizes and order, the bind group's entries, the dispatch grid (in two copies), and the merged layout's table.