The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Kernel: the live renderer's shortcuts as named approximations (#92)
Yujiaa5fb642207a0
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 13af16b..f9d94ab 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -2401,6 +2401,17 @@ access (it fails on a wrong entry: tried). The kernels' code is the same: renderchanged in four layouts, bench-window's shots as main's, the trace equal (Bistro 8.65 / 8.64 ms, lamp-rooms 3.71 /3.72), `tools/web-hello.ts` in Chrome passes.+**The live renderer's shortcuts, named (2026-11-15, after it).** An inventory of where a live path gathers other+light than an offline one found 16 places: the live architecture (the radiance cache, the clamps, the bounce limit,+media marched and composited, depth of field as post), and seven shortcuts taken for speed over the months, each a+`LIVE` check somewhere in the kernel: glass and media on shadow rays, cutouts on later rays and on emitters' shadow+rays, the hardware shadow query, far emitters, white noise. The seven are bits of one pipeline constant now+(`APPROX`; docs/RUNTIME.md "How live differs from offline", with what each was measured at), live taking all and+offline none as before, and a live view can run without them (`THREERT_APPROX=0`): Bistro held still then reads ΔE+1.67 for 1.82. No picture changes (render-identity 0 of 194 in four layouts, bench-window's shots as main's) and+the trace is equal (Bistro 8.52 / 8.52 ms). Next: a test for each that holds the live picture without it to the offline one,+their bias and cost measured again, and the defaults decided from that.+## 2. Temporal fixesTargets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); thediff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex b8f6e59..1d2136a 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1341,6 +1341,34 @@ frame found (pathtrace.wgsl "Light tiles", live.wgsl `light_tiles`):a vertex the camera sees and 1 past it, spread over the list without repeats, beside the uniform candidates (8 and3), which then stand for the lights the list lacks. Each candidate is weighed by the lights it stands for: the estimate is the same sum whatever a list holds.+## How live differs from offline++One kernel renders both (`override LIVE`). Where a live path gathers other light than an offline one, it is one of+two kinds.++**Approximations**: shortcuts a live trace takes to stay in its frame. Each is a bit of the pipeline constant+`APPROX` (pathtrace.wgsl `A_*`, gpu.rs), so a kernel without one has no code for it. Offline has none; a live view+has all (`gpu::A_LIVE`) unless `THREERT_APPROX=<bits>` says otherwise (`0`: the offline estimator's rays in a live+view, the way to hold a live picture to the offline one).++| bit | what a live ray does | recorded when it was taken |+|---|---|---|+| 1 `A_GLASS_SHADOWS` | shadow rays to the analytic lights and the sky pass glass in full, untinted | dark water near the camera +11 % of its +20 %; one more trace a shadow ray in glass scenes |+| 2 `A_MEDIA_SHADOWS` | only homogeneous media dim shadow rays: smoke and fire cast no shadow | the volume functions at every shadow ray: Kabukichō 0.4 ms with a smoke column out of view |+| 4 `A_CUTOUT_PATHS` | cutouts are opaque to rays past a camera hit's own, off mirror paths | Bistro's frame 16.1 / 19.9 -> 14.2 / 16.0 ms; the picture 0.3 % darker |+| 8 `A_CUTOUT_EMITTERS` | cutouts are opaque to emitters' shadow rays | 0.9 ms of the Bistro crowd's frame; 1.7 % of the light under foliage |+| 16 `A_SHADOW_QUERY` | hardware traversal: a shadow ray past a cutout is one query with a candidate loop (it loses hits on Metal) | 1.6 ms of Bistro's trace at its worst; ΔE +0.04 |+| 32 `A_FAR_EMITTERS` | the light tree proposes no emitter beyond 120 m; without a tree, the emitter cull (60 m, 120 m in view) | the 3 x 3 district 2.0 -> 0.5 ms; Tokyo's dusk aerials 10-12 % dark, far emitters' glow in fog lost |+| 64 `A_WHITE_NOISE` | a hash, not Sobol, past the camera hit's own decisions (variance only) | all-Sobol: +2.1 ms of Bistro's 8.4 ms trace |++Bistro held still, all of them off: ΔE against the offline render 1.82 -> 1.67 (bench-window `still-bistro`).++**The live architecture**, not switches: the path ends in the radiance cache at its first bounce that is not through+glass; the cache term, its training (4 x) and each sample (256) are clamped beside the kernel's own clamp; at most+4 bounces; a camera ray's media are marched and composited after the trace with isotropic in-scatter from the+cache's voxels, and later segments meet homogeneous media alone; depth of field is a post pass; translucent+particles are lit from the cache's voxels.+## What the kernel trustsThe kernel follows indices it reads from buffers and loops over counts it is given; it checks none of them (adiff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgslindex b507b8a..e3290b8 100644--- a/renderer/shaders/pathtrace.wgsl+++ b/renderer/shaders/pathtrace.wgsl@@ -55,6 +55,19 @@ const MAT_EMITTER_CARD: i32 = 2;const MAT_UNLIT: i32 = 4;// Live (real-time) mode: write this frame's 1-spp sample + first-hit distance instead of accumulating.override LIVE: bool = false;+// The live renderer's approximations (gpu::A_*; docs/RUNTIME.md "How live differs from offline"): what a live path+// leaves out or takes a cheaper way to stay in its frame, each a bit, each with the bias and the cost it was measured+// at. A pipeline's constant, as FEAT is: a kernel without one has no code for it. Offline has none; a live view has+// them all unless it asks otherwise (THREERT_APPROX), which is how a live picture is held to the offline one.+override APPROX: u32 = 0u;+const A_GLASS_SHADOWS: u32 = 1u; // shadow rays to the analytic lights and the sky pass glass in full, untinted (`occluded`)+const A_MEDIA_SHADOWS: u32 = 2u; // of the media only the homogeneous ones dim shadow rays (`media_shadows`)+const A_CUTOUT_PATHS: u32 = 4u; // cutouts are opaque to rays past a camera hit's own, off mirror paths (`cutouts_opaque`)+const A_CUTOUT_EMITTERS: u32 = 8u; // cutouts are opaque to emitters' shadow rays (`occluded_emitter`)+const A_SHADOW_QUERY: u32 = 16u; // hardware traversal: a shadow ray past a cutout is one query with a candidate loop (trace_hw.wgsl)+const A_FAR_EMITTERS: u32 = 32u; // the light tree proposes no emitter beyond LT_FAR (`lt_imp`; without a tree: the emitter cull)+const A_WHITE_NOISE: u32 = 64u; // variance only: a hash, not Sobol, past the camera hit's own decisions (sample.wgsl `rng_white`)+fn approx(a: u32) -> bool { return (APPROX & a) != 0u; }// Features the scene uses (gpu::F_*): the rest is compiled out, so plain scenes pay nothing for them.override FEAT: u32 = 0xffffffffu;const F_MASKED: u32 = 1u;@@ -333,8 +346,8 @@ fn emitter_pick_u(u: f32) -> vec4<f32> {// them (from entry P.ltree.y).const LT_LEAF: u32 = 0x80000000u;const LT_PATH_BITS: u32 = 26u;-// Live: tree nodes wholly farther than this (m) from the shading point are not proposed (never within one Bistro; in-// the 3 x 3 district its far copies: 2.0 -> 0.5 ms).+// A_FAR_EMITTERS: tree nodes wholly farther than this (m) from the shading point are not proposed (never within one+// Bistro; in the 3 x 3 district its far copies: 2.0 -> 0.5 ms).const LT_FAR: f32 = 120.0;fn lt_on() -> bool { return P.ltree.w > 0.5; }@@ -358,9 +371,9 @@ fn lt_imp(nd: vec4<f32>, x: vec3<f32>, n: vec3<f32>) -> f32 {cb = max(cos_t * cos_b + sqrt(max(1.0 - cos_t * cos_t, 0.0)) * sin_b, 0.0);}}- // Live, nodes wholly farther than LT_FAR from x are not proposed (their light comes by BSDF rays, emit_mis weighs- // them 1): shadow rays across a district cost more than the light they find.- if (LIVE && d2 > (LT_FAR + czr.y) * (LT_FAR + czr.y)) { return 0.0; }+ // A_FAR_EMITTERS: nodes wholly farther than LT_FAR from x are not proposed (their light comes by BSDF rays,+ // emit_mis weighs them 1): shadow rays across a district cost more than the light they find.+ if (approx(A_FAR_EMITTERS) && d2 > (LT_FAR + czr.y) * (LT_FAR + czr.y)) { return 0.0; }return nd.z * cb / max(d2, r2);}@@ -741,16 +754,20 @@ fn tri_hit(ti: u32, o: vec3<f32>, d: vec3<f32>) -> Hit {fn occluded(o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> bool {shadow_tint = vec3<f32>(1.0);if (trace(o, d, tmax, TRACE_SHADOW).tri != 0xffffffffu) { return true; }- if (!LIVE && has(F_GLASS) && glass_blocks(o, d, tmax, false, rd)) { return true; }+ if (!approx(A_GLASS_SHADOWS) && has(F_GLASS) && glass_blocks(o, d, tmax, false, rd)) { return true; }// Through media: blocked with probability 1 - transmittance (an unbiased estimate of it, ratio tracking).if (media_shadows()) { return rng1(rd) >= media_tr(o, d, tmax, rd); }- // Live: homogeneous media (water) analytically.- return LIVE && has(F_HMEDIA) && rng1(rd) >= media_homogeneous(o, d, tmax, false, rd).tr;+ return homogeneous_blocks(o, d, tmax, rd);}-// Offline: what the glass a shadow ray crosses lets through (it has passed every opaque caster). At each glass surface-// the share of the BSDF's transmission lobe: transmission x (1 - the specular directional albedo) at the crossing-// angle. The ray goes straight (no refraction, no caustics, no tint: UE's path tracer), so a light seen from under+// A_MEDIA_SHADOWS: the homogeneous media (water) alone dim a shadow ray, analytically.+fn homogeneous_blocks(o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> bool {+ return approx(A_MEDIA_SHADOWS) && has(F_HMEDIA) && rng1(rd) >= media_homogeneous(o, d, tmax, false, rd).tr;+}++// Without A_GLASS_SHADOWS: what the glass a shadow ray crosses lets through (it has passed every opaque caster). At+// each glass surface the share of the BSDF's transmission lobe, transmission x (1 - the specular directional albedo)+// at the crossing angle, times the glass's colour. The ray goes straight (no refraction, no caustics), so a light seen from under// water at more than the critical angle still lights through the surface, as its refracted light does. `sky`: an odd// number of glass surfaces lets nothing through (occluded_sky). Unattenuated, light under a water surface came both// through it and from the paths it reflects back (a white furnace through water read 1.25).@@ -788,15 +805,15 @@ fn glass_blocks(o: vec3<f32>, d: vec3<f32>, tmax: f32, sky: bool, rd: u32) -> boreturn false;}-// A shadow ray's glass tint where there can be one (offline, scenes with glass); elsewhere a constant 1 the compiler-// folds away, so their code (and images) stay as they were.+// A shadow ray's glass tint where there can be one (scenes with glass, without A_GLASS_SHADOWS); elsewhere a constant+// 1 the compiler folds away, so their code (and images) stay as they were.fn gtint(v: vec3<f32>) -> vec3<f32> {- if (!LIVE && has(F_GLASS)) { return v; }+ if (!approx(A_GLASS_SHADOWS) && has(F_GLASS)) { return v; }return vec3<f32>(1.0);}// What reaches a lit point from a light along a shadow ray: 0 when occluded, else 1 or the tint of the glass it passed-// (offline). `shadows` false (a light that casts none): 1, no ray.+// (`gtint`). `shadows` false (a light that casts none): 1, no ray.fn light_vis(shadows: bool, o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> vec3<f32> {if (!shadows) { return vec3<f32>(1.0); }if (occluded(o, d, tmax, rd)) { return vec3<f32>(0.0); }@@ -858,9 +875,9 @@ fn glass_at(h: Hit, d: vec3<f32>, t: f32) -> GlassAt {fn occluded_sky(o: vec3<f32>, d: vec3<f32>, rd: u32) -> bool {shadow_tint = vec3<f32>(1.0);if (trace(o, d, INF, TRACE_SHADOW).tri != 0xffffffffu) { return true; }- if (!LIVE && has(F_GLASS) && glass_blocks(o, d, INF, true, rd)) { return true; }+ if (!approx(A_GLASS_SHADOWS) && has(F_GLASS) && glass_blocks(o, d, INF, true, rd)) { return true; }if (media_shadows()) { return rng1(rd) >= media_tr(o, d, INF, rd); }- return LIVE && has(F_HMEDIA) && rng1(rd) >= media_homogeneous(o, d, INF, false, rd).tr;+ return homogeneous_blocks(o, d, INF, rd);}// Live homogeneous media (VolumeMesh `homogeneous`: constant coefficients, Coeff = albedo rgb + extinction, Emission rgb,@@ -933,17 +950,17 @@ fn media_homogeneous(o: vec3<f32>, d: vec3<f32>, tmax: f32, light: bool, rd: u32return r;}-// Media in shadow rays: offline, and in the live media voxel training (media_train sets `media_voxels`). The live-// megakernel has no media code at all: inlined at every shadow ray, the volume functions cost Kabukichō 0.4 ms with-// a smoke column out of view (its media are composited in a pass of their own, media_composite).+// Every medium on a shadow ray (`media_tr`): without A_MEDIA_SHADOWS, and in the live media voxel training+// (media_train sets `media_voxels`). With it a live trace's shadow rays run no volume function: inlined at every+// shadow ray they cost Kabukichō 0.4 ms with a smoke column out of view (`homogeneous_blocks` is what is left).var<private> media_voxels: bool = false;-fn media_shadows() -> bool { return (!LIVE || media_voxels) && has(F_MEDIA) && P.time.w > 0.5; }+fn media_shadows() -> bool { return (!approx(A_MEDIA_SHADOWS) || media_voxels) && has(F_MEDIA) && P.time.w > 0.5; }// Shadow rays toward emissive surfaces: every surface blocks them, as it blocks the BSDF rays that find the same// emitters (their MIS partner; a pass-through here counted light that no path can reach, and more of it the larger// the emitter's sampling share). UE's path tracer, too, reaches emissive surfaces only through rays that every mesh// blocks.-// Shadow ray to an emitter sample (any surface blocks). Live, alpha-cutout triangles are opaque to it at camera hits too+// Shadow ray to an emitter sample (any surface blocks). A_CUTOUT_EMITTERS: alpha-cutout triangles are opaque to it at camera hits too// (deeper vertices take them as opaque anyway, `cutouts_opaque`): the leaves of a tree block as whole cards. A bias,// accepted by the user on 2026-11-09 to bring the Bistro crowd within its 60 fps budget: the alpha tests of these rays// were ~0.9 ms of the frame (crowd GPU p50 15.06 -> 14.16 ms, frame start p95 17.14 -> 16.67 ms), and cost the live@@ -951,15 +968,15 @@ fn media_shadows() -> bool { return (!LIVE || media_voxels) && has(F_MEDIA) && P// Removing the bias without the cost (an opacity micromap, or these rays compacted into a pass of their own) is a// follow-up item (ROADMAP § 0). Offline rendering always tests.fn occluded_emitter(o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> bool {- if (trace(o, d, tmax, select(TRACE_ANY, TRACE_ANY_OPAQUE, LIVE)).tri != 0xffffffffu) { return true; }+ if (trace(o, d, tmax, select(TRACE_ANY, TRACE_ANY_OPAQUE, approx(A_CUTOUT_EMITTERS))).tri != 0xffffffffu) { return true; }if (media_shadows()) { return rng1(rd) >= media_tr(o, d, tmax, rd); }- return LIVE && has(F_HMEDIA) && rng1(rd) >= media_homogeneous(o, d, tmax, false, rd).tr;+ return homogeneous_blocks(o, d, tmax, rd);}fn occluded_any(o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> bool {if (trace(o, d, tmax, TRACE_ANY).tri != 0xffffffffu) { return true; }if (media_shadows()) { return rng1(rd) >= media_tr(o, d, tmax, rd); }- return LIVE && has(F_HMEDIA) && rng1(rd) >= media_homogeneous(o, d, tmax, false, rd).tr;+ return homogeneous_blocks(o, d, tmax, rd);}// ------------------------------------------------------------------------------------------------@@ -1109,14 +1126,14 @@ fn mat_base(m: Material) -> MatOut {return MatOut(m.base_color.rgb, m.params.y, m.params.x, m.params.z, m.emissive.rgb, vec3<f32>(0.0, 1.0, 0.0), m.base_color.a, false);}-// Live rays past the camera ray and its own light samples, off mirror-like paths (whose image is still seen), take+// A_CUTOUT_PATHS: rays past the camera ray and its own light samples, off mirror-like paths (whose image is still seen), take// alpha-cutout triangles as opaque: no alpha test, no stepping through the leaves behind. The leaves of a tree are then// solid cards to indirect light and to the light samples of later bounces. Through foliage that was most of the trace:// Bistro along its camera path, frame GPU 16.1 / 19.9 ms -> 14.2 / 16.0 at its first pose / 15 s in; against the// unbiased offline render the live image 0.3 % darker, ΔE +0.02–0.04 (the clamps' darkening is 9–13 %). Offline// rendering always tests.fn cutouts_opaque() -> bool {- return LIVE && cur_depth >= 1u && !mirror_path;+ return approx(A_CUTOUT_PATHS) && cur_depth >= 1u && !mirror_path;}// Alpha-cutout test for candidate hits on masked triangles (mesh UVs, footprint of a camera ray at distance t). `inst`:@@ -3129,8 +3146,9 @@ fn media_train(@builtin(global_invocation_id) gid: vec3<u32>) {// the sample for `compose` to apply after the denoisers, as volumetrics are composed over a denoised surface// elsewhere. Scaled before, a surface's history kept the shadow of the smoke of the frames before. With it goes how// much of the pixel is a medium that changes with time (what it hides, or its light's share of the pixel): the-// upscaler's reactive mask there. normal.w = that share in 8 bits, plus half the transmittance. Reflection, GI and-// shadow rays do not see media live (offline paths do).+// upscaler's reactive mask there. normal.w = that share in 8 bits, plus half the transmittance. Past the camera ray a+// live path meets the homogeneous media alone (the path loop), its shadow rays too with A_MEDIA_SHADOWS; offline+// paths track every medium.@compute @workgroup_size(8, 8, 1)fn media_composite(@builtin(global_invocation_id) gid: vec3<u32>) {let w = P.size.x;@@ -3456,7 +3474,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {break;}// Live: the path ends in the radiance cache at its first bounce. Surfaces seen in mirror-like reflections- // (specular lobe below roughness 0.4, where UE traces reflections) get exact direct light, as UE's hit+ // (specular lobe below roughness 0.4, where UE traces reflections) get direct light of their own, as UE's hit// lighting does, and the cache's indirect part; others reflect the cache's total. Rotating tiles train the// cache. For the first frames after a reset or a camera cut (live/mod.rs COLD_FALLBACK_FRAMES; flag 1 later),// pixels that find their voxel cold trace a fresh estimate and use it meanwhile, without inserting the voxel:diff --git a/renderer/shaders/sample.wgsl b/renderer/shaders/sample.wgslindex 8d0446c..feb1bcb 100644--- a/renderer/shaders/sample.wgsl+++ b/renderer/shaders/sample.wgsl@@ -129,9 +129,10 @@ const D_VOL_LIGHT: u32 = 14u; // lights at a point in a medium (`phase_direct`,const D_VOXEL: u32 = 15u; // the radiance cache's volume points (`point_sphere`)const D_CACHE: u32 = 16u; // the cache's fixed-point dither-// Live: Sobol only for the camera path's first vertex (not a loop's parts: `rng_sub` sets the top bit), a hash-// elsewhere (as NVIDIA's RTXPT; all-Sobol cost 2 ms of Bistro's trace). Offline: Sobol everywhere (as Cycles).-fn rng_white(d: u32) -> bool { return LIVE && (cur_depth > 0u || RNG_PATH != 0u || d >= 0x80000000u); }+// A_WHITE_NOISE (live): Sobol only for the camera path's first vertex (not a loop's parts: `rng_sub` sets the top+// bit), a hash elsewhere (as NVIDIA's RTXPT; all-Sobol cost 2 ms of Bistro's trace). Without it: Sobol everywhere+// (offline, as Cycles).+fn rng_white(d: u32) -> bool { return approx(A_WHITE_NOISE) && (cur_depth > 0u || RNG_PATH != 0u || d >= 0x80000000u); }fn white(d: u32, c: u32) -> f32 { return f32(hash_hp(rng_seed(d) ^ (RNG_INDEX * 0x9e3779b9u + c * 0x85ebca6bu)) >> 8u) * (1.0 / 16777216.0); }// A hash, always: for loops of no fixed length (delta tracking's steps), where a new Sobol dimension a step is QMC'sdiff --git a/renderer/shaders/trace_hw.wgsl b/renderer/shaders/trace_hw.wgslindex 3ad12d1..0cc0af6 100644--- a/renderer/shaders/trace_hw.wgsl+++ b/renderer/shaders/trace_hw.wgsl@@ -27,12 +27,12 @@// Any hit blocks a shadow ray, except a cutout one that its alpha lets through.let h = trace_opaque(o, d, tmax_in, mask, true);if (h.tri == 0xffffffffu || is_proc(h) || !cutout(h.tri) || alpha_pass(h.tri, h.inst, h.u, h.v, h.t)) { return h; }- // Live: one query whose candidate loop alpha-tests the cutouts (`trace_any_cutout`). It loses hits on Metal+ // A_SHADOW_QUERY: one query whose candidate loop alpha-tests the cutouts (`trace_any_cutout`). It loses hits on Metal// from run to run, confirmed ones too: offline it made two runs of one render differ in 75 % of Kabukichō's// pixels and 98 % of Bistro's at 64 spp (the ordered steps below: 0–0.06 % and 2–10 %, Bistro's own share of// ties). Live it is 1.6 ms of Bistro's trace less at its worst stretch, its image ΔE +0.04 against the// unbiased render; offline, which is that render, steps in order.- if (LIVE) { return trace_any_cutout(o, d, tmax_in, mask); }+ if (approx(A_SHADOW_QUERY)) { return trace_any_cutout(o, d, tmax_in, mask); }}// In order, each query starting past the last cutout hit its alpha let through. Shadow rays take up to 64 of them// and count as blocked past that: with 16, as closest hits take, the rest counted as unblocked (light through densediff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex 5fa6b1e..8119c35 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -19,6 +19,8 @@ pub struct Gpu {pub uniform_tables: bool,/// The kernel's switches this device was opened with (`KernelSwitches`): they are in `source`.pub switches: KernelSwitches,+ /// The approximations a live view's kernel takes (`A_*`; `GpuOptions::approx`).+ pub approx: u32,/// Compiled pipelines kept between runs (`GpuOptions::pipeline_cache`), where the backend has such a cache.pipeline_cache: Option<crate::pipeline_cache::PipelineCache>,/// Kernel source (hardware or software traversal spliced in); scenes with material functions get their own module.@@ -33,7 +35,7 @@ pub struct Gpu {pipeline_layout: wgpu::PipelineLayout,/// Kernel variants by (feature mask, material-function code hash, LIVE): `FEAT` compiles out the features a scene/// does not use (they cost registers even when idle); `LIVE` = one fresh sample per dispatch for the viewport.- pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool), wgpu::ComputePipeline>>,+ pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool, u32), wgpu::ComputePipeline>>,layout: wgpu::BindGroupLayout,/// Group 1, the live viewport's: primary visibility (texture_2d<u32>), the radiance cache (`CacheBuffers`) and/// what the live passes read of a trace (`KernelBufs`). Offline renders bind `no_vis` (1x1 texture `no_vis_view`,@@ -54,9 +56,9 @@ pub struct Gpu {/// pipelines (`translucent`, `volume_train`) by the kernel's variant key.tl_layout: Option<wgpu::BindGroupLayout>,tl_pipeline_layout: Option<wgpu::PipelineLayout>,- tl_pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool), TranslucentPipelines>>,+ tl_pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool, u32), TranslucentPipelines>>,/// The live media passes (pathtrace.wgsl `media_train`, `media_composite`) by kernel variant and entry point.- media_passes: std::sync::Mutex<std::collections::HashMap<(u32, u64, &'static str), wgpu::ComputePipeline>>,+ media_passes: std::sync::Mutex<std::collections::HashMap<(u32, u64, &'static str, u32), wgpu::ComputePipeline>>,/// The procedural blobs of the last upload (`upload_procs`).proc_cache: std::sync::Mutex<Option<ProcCache>>,/// The last upload's procedural BLASes by geometry hash (read-only once built; another upload may share them), with@@ -1108,11 +1110,14 @@ pub struct GpuOptions {/// A directory to keep compiled pipelines in between runs (pipeline_cache.rs). None: nothing is kept.pub pipeline_cache: Option<std::path::PathBuf>,pub kernel: KernelSwitches,+ /// The live renderer's approximations (`A_*`). None: all of them (`A_LIVE`). 0: a live view whose kernel is the+ /// offline one's estimator, slower, for holding its picture to the offline render's.+ pub approx: Option<u32>,}impl GpuOptions {- /// THREERT_UNIFORM_TABLES=1|0, THREERT_PIPELINE_CACHE=<directory>, and the kernel's switches- /// (`KernelSwitches::from_env`).+ /// THREERT_UNIFORM_TABLES=1|0, THREERT_PIPELINE_CACHE=<directory>, THREERT_APPROX=<bits of `A_*`>, and the+ /// kernel's switches (`KernelSwitches::from_env`).pub fn from_env() -> GpuOptions {Self::from_vars(&|name| std::env::var(name).ok(), cfg!(target_os = "android"))}@@ -1123,6 +1128,7 @@ impl GpuOptions {uniform_tables: var("THREERT_UNIFORM_TABLES").map(|v| v == "1"),pipeline_cache: var("THREERT_PIPELINE_CACHE").filter(|d| !d.is_empty()).map(std::path::PathBuf::from),kernel: KernelSwitches::from_vars(var, android),+ approx: var("THREERT_APPROX").and_then(|v| v.trim().parse().ok()),}}@@ -1344,9 +1350,21 @@ pub struct Kernel {/// The scene's geometry functions and their dispatch (pathtrace.wgsl `geometry_function`), spliced like `functions`.pub geometry_functions: String,pub hash: u64,+ /// The approximations its live pipelines are compiled with (`A_*`; an offline pipeline has none): the device's+ /// (`Gpu::approx`) unless a view sets others.+ pub approx: u32,}impl Kernel {+ /// A pipeline's constants: `LIVE`, `FEAT`, `APPROX`.+ fn constants(&self, live: bool) -> [(&'static str, f64); 3] {+ [("LIVE", if live { 1.0 } else { 0.0 }), ("FEAT", self.features as f64), ("APPROX", self.approx_of(live) as f64)]+ }++ fn approx_of(&self, live: bool) -> u32 {+ if live { self.approx } else { 0 }+ }+pub fn new(scene: &Scene, groups: [usize; GROUPS]) -> Kernel {let mut functions = String::new();if !scene.shaders.is_empty() {@@ -1435,10 +1453,22 @@ impl Kernel {functions.hash(&mut h);volume_functions.hash(&mut h);geometry_functions.hash(&mut h);- Kernel { features: features(scene, groups), functions, volume_functions, geometry_functions, hash: h.finish() }+ Kernel { features: features(scene, groups), functions, volume_functions, geometry_functions, hash: h.finish(), approx: A_LIVE }}}+// The live renderer's approximations (`override APPROX` in pathtrace.wgsl, which says what each is; docs/RUNTIME.md+// "How live differs from offline").+pub const A_GLASS_SHADOWS: u32 = 1;+pub const A_MEDIA_SHADOWS: u32 = 2;+pub const A_CUTOUT_PATHS: u32 = 4;+pub const A_CUTOUT_EMITTERS: u32 = 8;+pub const A_SHADOW_QUERY: u32 = 16;+pub const A_FAR_EMITTERS: u32 = 32;+pub const A_WHITE_NOISE: u32 = 64;+/// All of them: what a live view takes unless it asks otherwise (`GpuOptions::approx`).+pub const A_LIVE: u32 = 127;+// Kernel features (`override FEAT` in pathtrace.wgsl).pub const F_MASKED: u32 = 1;pub const F_FOG: u32 = 64;@@ -1678,6 +1708,7 @@ impl Gpu {let pipeline_cache = cache_feature.and_then(|_| crate::pipeline_cache::PipelineCache::open(&device, options.pipeline_cache.as_ref()?, &adapter_info));let uniform_tables = options.uniform_tables_on(merged, cfg!(target_os = "android"));let switches = options.kernel;+ let approx = options.approx.unwrap_or(A_LIVE) & A_LIVE;let src = kernel_template();// Bounds checks are not needed: all indices come from our own BVH / scene builder.let module = unsafe {@@ -1721,7 +1752,7 @@ impl Gpu {} else {(None, None)};- Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, switches, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), tl_layout, tl_pipeline_layout, tl_pipelines: Default::default(), media_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })+ Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, switches, approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), tl_layout, tl_pipeline_layout, tl_pipelines: Default::default(), media_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })}/// Whether this device's kernel buffers have the loop guard's count (`guard_room`; always in the merged layout).@@ -1747,10 +1778,10 @@ impl Gpu {pub fn pipeline(&self, k: &Kernel, live: bool) -> wgpu::ComputePipeline {let mut cache = self.pipelines.lock().unwrap();cache- .entry((k.features, k.hash, live))+ .entry((k.features, k.hash, live, k.approx_of(live))).or_insert_with(|| {let module = self.kernel_module(k);- let constants = [("LIVE", if live { 1.0 } else { 0.0 }), ("FEAT", k.features as f64)];+ let constants = k.constants(live);let p = self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {label: Some(if live { "pathtrace-live" } else { "pathtrace" }),layout: Some(&self.pipeline_layout),@@ -1806,10 +1837,10 @@ impl Gpu {pub fn media_pipeline(&self, k: &Kernel, entry: &'static str) -> wgpu::ComputePipeline {let mut cache = self.media_passes.lock().unwrap();cache- .entry((k.features, k.hash, entry))+ .entry((k.features, k.hash, entry, k.approx)).or_insert_with(|| {let module = self.kernel_module(k);- let constants = [("LIVE", 1.0), ("FEAT", k.features as f64)];+ let constants = k.constants(true);let p = self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {label: Some(entry),layout: Some(&self.pipeline_layout),@@ -1828,10 +1859,10 @@ impl Gpu {pub fn translucent_pipelines(&self, k: &Kernel, live: bool) -> TranslucentPipelines {let mut cache = self.tl_pipelines.lock().unwrap();cache- .entry((k.features, k.hash, live))+ .entry((k.features, k.hash, live, k.approx_of(live))).or_insert_with(|| {let module = self.kernel_module(k);- let constants = [("LIVE", if live { 1.0 } else { 0.0 }), ("FEAT", k.features as f64)];+ let constants = k.constants(live);let make = |entry: &str| {self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {label: Some(entry),@@ -2264,7 +2295,7 @@ impl Gpu {});let bg_parts = BindParts { nodes: b_nodes, tex_view, env_view, sampler, grid_view };let bg = self.scene_bind_group(&SceneBuffers { params: &b_params, verts: &b_verts, attrs: &b_attrs, heap: &heap, words: &words, prev_verts: &b_prev, accum: &b_accum, parts: &bg_parts, accel: accel.as_ref(), uniform: uniform.as_ref() });- let kernel = Kernel::new(scene, groups);+ let kernel = Kernel { approx: self.approx, ..Kernel::new(scene, groups) };// Translucent particles (hardware RT): their own BLAS + TLAS, rebuilt after the particle pass.let translucent = match &accel {Some(_) if !scene.trans_tris.is_empty() => {@@ -3340,6 +3371,17 @@ mod tests {seen |= bit;}let wgsl = include_str!("../shaders/pathtrace.wgsl");+ // The live approximations: one bit each, the shader's the same, `A_LIVE` all of them.+ let approx = [+ ("A_GLASS_SHADOWS", A_GLASS_SHADOWS), ("A_MEDIA_SHADOWS", A_MEDIA_SHADOWS), ("A_CUTOUT_PATHS", A_CUTOUT_PATHS), ("A_CUTOUT_EMITTERS", A_CUTOUT_EMITTERS),+ ("A_SHADOW_QUERY", A_SHADOW_QUERY), ("A_FAR_EMITTERS", A_FAR_EMITTERS), ("A_WHITE_NOISE", A_WHITE_NOISE),+ ];+ assert_eq!(approx.iter().fold(0, |all, a| { assert!(a.1.is_power_of_two() && all & a.1 == 0, "{} = {}", a.0, a.1); all | a.1 }), A_LIVE);+ let declared: Vec<&str> = wgsl.lines().filter(|l| l.starts_with("const A_")).collect();+ assert_eq!(declared.len(), approx.len());+ for (name, bit) in approx {+ assert!(declared.iter().any(|l| l.starts_with(&format!("const {name}: u32 = {bit}u;"))), "{name}: pathtrace.wgsl and gpu.rs differ");+ }assert!(wgsl.contains(&format!("const RIS_EXACT: u32 = {RIS_EXACT}u;")), "RIS_EXACT: pathtrace.wgsl and gpu.rs differ");for line in wgsl.lines().filter(|l| l.starts_with("const F_")) {let name = &line[6..line.find(':').unwrap()];diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex ae0d3d2..d702215 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -231,8 +231,10 @@ impl LiveCore {return;}b.light_lod = [self.cam.pos.x, self.cam.pos.y, self.cam.pos.z, d0];- b.emit_power[1] = EMITTER_CULL;- b.emit_power[2] = EMITTER_CULL * EMITTER_CULL_VIEW;+ // (A_FAR_EMITTERS: the cull is the scenes' without a light tree; without it every emitter is proposed.)+ let cull = if self.sc.up.kernel.approx & gpu::A_FAR_EMITTERS != 0 { EMITTER_CULL } else { 0.0 };+ b.emit_power[1] = cull;+ b.emit_power[2] = cull * EMITTER_CULL_VIEW;// The frustum's half-diagonal: tan = tan(fov / 2) x sqrt(1 + aspect^2).let half = (self.cam.tan_half_fov * (1.0 + (w as f32 / h as f32).powi(2)).sqrt()).atan() + EMITTER_CULL_MARGIN.to_radians();b.lod_view = [self.cam.fwd.x, self.cam.fwd.y, self.cam.fwd.z, half.min(std::f32::consts::PI).cos()];diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rsindex 8c1a25e..fccfde6 100644--- a/renderer/src/live/load.rs+++ b/renderer/src/live/load.rs@@ -234,7 +234,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Plet _ = g.pipeline(&up.kernel, true); // compile the scene's kernel variant now, not in the first framelet sky_inputs = ((prep.env.width, prep.env.height), sc.camera.position.y.max(0.0), prep.env_nee_floor);let mut base = prep.params;- // The live viewport resamples fewer light-tree candidates at camera hits than offline renders (ltree.rs).+ // The live view's own count of light-tree candidates at camera hits (ltree.rs `RIS_LIVE`).if base.ltree[3] > 0.5 {base.ltree[3] = crate::ltree::live_candidates() as f32;}@@ -242,7 +242,8 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pbase.cam_fwd[3] = w as f32 / h as f32;let bgs = targets.bind_groups(&g.device, passes, &up.accum);let exposure_settings = ExposureSettings::new(&sc.camera.exposure, &sc.preset.post);- // Manual: 2^-EV100. Auto: a first guess for the firefly clamp (the GPU histogram takes over from frame 1).+ // Manual: 2^-EV100. Auto: a first guess (the GPU histogram takes the exposure over from frame 1; the kernel's+ // firefly clamp, `Params::misc[0]`, keeps `prepare`'s guess).let exposure = match &sc.camera.exposure {crate::desc::Exposure::Manual { ev100 } => 2f32.powf(-ev100),crate::desc::Exposure::Auto { compensation, max_ev100, .. } => 2f32.powf(*compensation) / 2f32.powf(*max_ev100),diff --git a/renderer/src/sample.rs b/renderer/src/sample.rsindex 7d6ed1d..e7d3855 100644--- a/renderer/src/sample.rs+++ b/renderer/src/sample.rs@@ -124,7 +124,7 @@ mod tests {}}- /// sample.wgsl on the GPU gives these numbers, offline (`LIVE` false; to the last place: a u32's conversion to f32+ /// sample.wgsl on the GPU gives these numbers, offline (no `A_WHITE_NOISE`; to the last place: a u32's conversion to f32/// may round either way). (Skipped without a GPU.)#[test]fn the_shader_is_this() {@@ -135,7 +135,7 @@ mod tests {};let d = &g.device;let seeds = [0u32, 0x1234_5678, hash_hp(99)];- let src = format!("{}\noverride LIVE: bool = false;\nvar<private> cur_depth: u32;\n@group(0) @binding(0) var<storage, read_write> out: array<u32>;\nconst SEEDS = array<u32, 3>({}u, {}u, {}u);\n@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) {{\n let i = id.x;\n RNG_SEED = SEEDS[i % 3u];\n RNG_INDEX = i;\n let r = rng4(7u + i % 5u);\n for (var k = 0u; k < 4u; k++) {{ out[i * 4u + k] = bitcast<u32>(r[k]); }}\n}}\n", include_str!("../shaders/sample.wgsl"), seeds[0], seeds[1], seeds[2]);+ let src = format!("{}\noverride APPROX: u32 = 0u;\nconst A_WHITE_NOISE: u32 = 64u;\nfn approx(a: u32) -> bool {{ return (APPROX & a) != 0u; }}\nvar<private> cur_depth: u32;\n@group(0) @binding(0) var<storage, read_write> out: array<u32>;\nconst SEEDS = array<u32, 3>({}u, {}u, {}u);\n@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) {{\n let i = id.x;\n RNG_SEED = SEEDS[i % 3u];\n RNG_INDEX = i;\n let r = rng4(7u + i % 5u);\n for (var k = 0u; k < 4u; k++) {{ out[i * 4u + k] = bitcast<u32>(r[k]); }}\n}}\n", include_str!("../shaders/sample.wgsl"), seeds[0], seeds[1], seeds[2]);let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(src.into()) });let pipeline = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: None, layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None });let n = 256u32;diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 255d669..3a8e23e 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -1820,8 +1820,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se}}stats.insert("unique_triangles", (tris.len() + pool_tris.len()) as f64);- // Cutout materials: their triangles take the any-hit path in traversal. Glass lets shadow rays through- // (unattenuated: no caustics, like UE's raster shadows of translucency).+ // Cutout materials: their triangles take the any-hit path in traversal. Glass casts no shadow of its own: what a+ // shadow ray keeps past it is the kernel's (`glass_tr`; in full with `A_GLASS_SHADOWS`).for (f, a) in tri_flags.iter_mut().zip(&attrs) {let m = &materials[a.uv[3].to_bits() as usize];if m.uv2[3] > 0.0 {