Skip to content

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

252 KB
Raw Blame
// ThreeRT native path tracer. One sample per pixel per dispatch, accumulated in `accum`.
// Shading model mirrors UE5 DefaultLit: Lambert diffuse + GGX / Smith-joint-approx / Schlick(F90 = saturate(50 F0.g)),
// with GGX multiple-scattering energy compensation and diffuse energy preservation.
// Material / atmosphere extensions: texture pages with ray-cone LOD, alpha cutout, world mapping,
// wetness / puddles / ripples / grime, procedural facade windows, emissive animation, RIS many-light sampling, height
// fog with volumetric single scattering. Each is compiled out when the scene does not use it (FEAT).
//
// The kernel is this file and records.wgsl, sample.wgsl, trace_units.wgsl, trace_hw.wgsl and translucent.wgsl after it (gpu.rs `KERNEL_FILES`),
// compiled for a device and a scene by WESL's conditional translation (`@if`, gpu.rs `kernel_wgsl`): a declaration
// or a statement under `@if(x)` is there only where x holds. The flags:
//   hwrt                  hardware traversal (ray queries) in the software BVH walk's place, and the translucency pass
//   strict, cutout_lite, cutout_lite2, last_direct, last_sun, light_pick
//                         a device's switches (gpu.rs `KernelSwitches`: what a GPU the kernel as written is wrong or
//                         too slow on needs)
//   units                 software traversal's second level (gpu.rs `F_UNITS`); a scene's other features are bits
//                         of `FEAT`, a pipeline-overridable constant
//   merged                the merged binding layout (merged.rs: at most eight storage buffers a stage, a browser's)
//   whole_tables          the seven typed tables read from the tables' buffer whole, as `merged` reads them, and
//                         no views of their sections (gpu.rs `GpuOptions::table_views`: Android's drivers)
//   guard                 the loop guard (gpu.rs `loop_guard_of`, `guard_loops`)
// The numbers a variant is compiled for are WESL constants (`import constants::`, gpu.rs `KernelVariant::constants`): the
// loop guard's words and its limit.
@if(merged || guard) import constants::GUARD_WORDS;
@if(guard) import constants::LOOP_GUARD_LIMIT;
@if(hwrt) enable wgpu_ray_query;

const PI: f32 = 3.14159265358979;
const INF: f32 = 3.0e38;
const TRI_NO_SHADOW: u32 = 1u;
const TRACE_CLOSEST: u32 = 0u;
const TRACE_SHADOW: u32 = 1u;
const TRACE_ANY: u32 = 2u;
// Any hit on any surface, an alpha-cutout's triangles by their maps, with no read of their texture (live emitter
// shadow rays: `emitter_tr`; one without a map is opaque).
const TRACE_ANY_OPAQUE: u32 = 3u;
const TRI_MASKED: u32 = 2u;
// Highest texture-page mip (texpack::MIPS - 1) and the ray-cone LOD bias (negative = sharper; accumulation antialiases).
const TEX_MAX_LEVEL: f32 = 4.0;
const LOD_BIAS: f32 = 0.5;

// Pixel footprint for texture LOD: the output resolution when tracing below it (upsampled like UE TSR's mip bias).
fn lod_height() -> f32 {
    return f32(select(P.size.y, P.counts2.z, P.counts2.z > 0u));
}
// Local lights: up to RIS_EXACT are evaluated exhaustively, more are resampled from RIS_M candidates (one shadow ray).
const RIS_EXACT: u32 = 8u;
const RIS_M: u32 = 8u;
const LIGHT_GROUP: u32 = 16u; // lib.rs LIGHT_GROUP
// Emitter candidates per camera-ray hit (sample_emitter_ris).
const EMIT_RIS_M: u32 = 6u;
// Volumetric fog runs on 1 / (VOL_RATE_MASK + 1) of the pixel tiles per sample (0 = every pixel).
const VOL_RATE_MASK: u32 = 1u;
const MAT_DOUBLE_SIDED: i32 = 1;
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 (`shadow_tr`)
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; // emitters' shadow rays ask a cutout's map and read no texture; one without maps is opaque to them (`emitter_tr`)
const A_FAR_EMITTERS: u32 = 16u;   // the light tree proposes no emitter beyond LT_FAR (`lt_imp`; without a tree: the emitter cull)
const A_CUTOUT_DEEP: u32 = 32u;    // of the cutouts a ray that sees (a camera ray, a mirror path's) meets, the CUTOUT_DEEP-th stands whole: the alpha is asked of those before it alone (`trace`, `trace_units`)
fn approx(a: u32) -> bool { return (APPROX & a) != 0u; }
const CUTOUT_DEEP: u32 = 8u;
// 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;
const F_PART: u32 = 1024u; // a particle system's mesh among the instances: a hit's object is its particle's (`tri_data`)
const F_FOG: u32 = 64u;
const F_VOLUME: u32 = 128u;
const F_TEX: u32 = 256u;
const F_FUNC: u32 = 512u;
const F_GLASS: u32 = 2048u;
const F_COAT: u32 = 4096u;
const F_MIRROR: u32 = 8192u; // a material that can be a mirror alone (`mirror_possible`): the first pass follows it
const F_INST: u32 = 16384u;
const F_MEDIA: u32 = 32768u;
const F_PEMIT: u32 = 65536u; // opaque particles' emitters (one not shown has no area)
const F_HMEDIA: u32 = 131072u; // homogeneous media (water): live attenuation of paths and shadow rays (media_homogeneous)
const F_AERIAL: u32 = 16777216u; // the sky's aerial perspective (aerial_tr) on segments ending on a surface
const F_PROC: u32 = 262144u; // procedural geometry (ProceduralMesh): AABB candidates in every query, `surface_proc`
const F_TINT: u32 = 524288u; // instance colours: OBJECT_STRIDE 4, `obj_tint`
const F_UNLIT: u32 = 1048576u; // MeshBasicMaterial (MAT_UNLIT)
const F_BACKGROUND: u32 = 2097152u; // scene.background (`sky_mis`)
const F_VCOLOR: u32 = 4194304u; // vertex colours (`vcolor`)
const F_GRID: u32 = 33554432u; // density grids (`vgrid`)
const F_IFUNC: u32 = 268435456u; // a material function on an instanced mesh: `mat_in_at` places the triangle by its instance
const F_DEFORM: u32 = 1073741824u; // a mesh that deforms among the instances: its previous vertices by its record (the first hit's motion)
const F_IGLASS: u32 = 536870912u; // glass among an instance's other sections: a shadow ray steps through it by its row (trace_hw.wgsl), a unit's walk skips it
const F_LISTS: u32 = 134217728u; // light tiles (`lt_list_start`): a scene whose shadow-casting local lights are resampled
fn has(f: u32) -> bool { return (FEAT & f) != 0u; }

struct Params {
    cam_pos: vec4<f32>,   // w = tan(fov/2)
    cam_fwd: vec4<f32>,   // w = aspect
    cam_right: vec4<f32>, // w = lens radius
    cam_up: vec4<f32>,    // w = focus distance
    size: vec4<u32>,      // width, height, sample index, seed
    counts: vec4<u32>,    // lights, emitters, max bounces, rr depth
    env: vec4<f32>,       // has env map, env width, env height, sun light index (-1 none)
    misc: vec4<f32>,      // clamp (absolute radiance), - (the emitters' total weight is their table's: `emitter_totals`), env total weight, _
    sky_color: vec4<f32>, // constant sky radiance when no env map
    counts2: vec4<u32>,   // directional lights (first in `lights`), environment NEE on, output height for texture LOD (0 = traced height), first shadowed local light
    time: vec4<f32>,      // scene time (s), wetness, rain, -
    fog: vec4<f32>,       // density at fog height (1/m), height falloff (1/m), fog height, start distance (m)
    fog_color: vec4<f32>, // ambient inscattering radiance, max opacity
    vol: vec4<f32>,       // volumetric scattering albedo (0 = off), HG anisotropy, extinction scale in range, -
    vol2: vec4<f32>,      // volumetric albedo tint rgb, range (m, 0 = unlimited)
    jitter: vec4<f32>,    // live: this frame's sub-pixel jitter x, y (every camera ray's); ray tracing off (1); -
    cache: vec4<f32>,     // 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<f32>,    // live motion vectors: 1 = on; `render --signals`; software traversal's units: the top tree's root, their count (bits)
    light_lod: vec4<f32>, // live light LOD (lib.rs emitter_lod): reference position, d0 (0 = off)
    emit_power: vec4<f32>, // the emitter CDF's power and cull as the CPU built it (lib.rs `EmitterCull`); not read here
    lod_view: vec4<f32>,   // emitter cull's view cone (lib.rs EmitterCull): forward direction, cos of the half-angle
    ltree: vec4<f32>,      // light tree (ltree.rs): -, its entry count (bits: the moving emitters' first), - (the tail's share is the table's: `emitter_totals`), candidates at camera hits (0 = off)
    procs: vec4<u32>,      // procedural geometry (F_PROC): -, object count, first record in `instances`, -
    aerial: vec4<f32>,     // the sky's aerial perspective (F_AERIAL): density multiple, Rayleigh scale, Mie scale, -
    background: vec4<f32>, // three.js scene.background (radiance), 1 (F_BACKGROUND)
    ltile: vec4<u32>,      // live light tiles (`lt_list_start`): 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<u32>,     // the traced size they were built at; the output's pixels (`guide_at`), -
    lt_cam: array<vec4<f32>, 4>, // the camera they were built under: position (w = tan(fov/2)), forward (w = aspect), right, up
    table_first: array<vec4<u32>, 3>, // each table's first vec4 in `tables` (heap.rs `Table`): light tree (0), materials, lights, light groups; emitters, tex_info, objects, instances; media, energy LUT, glass energy, emitter triangles
    word_first: array<vec4<u32>, 2>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, the instances' rows; the triangles' indices, the cutouts' maps
    live_first: array<vec4<u32>, 2>, // the merged layout: each of group 1's vec4 sections' first vec4 in `ML.vecs` (heap.rs `Live`): cache values (0), refl, motion, direct; lists, first hits, (the first hits' vec4s), -
    live_len: vec4<u32>,   // and the vec4s of refl, motion, direct, lists
};

// (`TriAttr`, a triangle's attributes, and `Pixel`, a sample in `accum`: records.wgsl.)
struct Node { bmin: vec3<f32>, left_or_first: u32, bmax: vec3<f32>, count: u32 };
// See scene::GpuMaterial for the field layout.
struct Material {
    base_color: vec4<f32>, emissive: vec4<f32>, params: vec4<f32>, tex0: vec4<i32>, tex1: vec4<i32>, uv: vec4<f32>,
    uv2: vec4<f32>, layer: vec4<f32>, mp: array<vec4<f32>, 8>, mt: array<i32, 8>,
};
// See scene::GpuLight (x = volumetric scattering scale, specular scale, rect barn-door cosine, -).
struct Light { pos: vec4<f32>, dir: vec4<f32>, color: vec4<f32>, ext: vec4<f32>, x: vec4<f32> };

@group(0) @binding(0) var<uniform> P: Params;
// The scene's vertices (indexed.rs `Vertex`), each kept once, a record of three rows: (position, u), (normal, v),
// (tangent, hand; a hand of 0: it has none). A triangle is three of them, by its indices in `words` (`tri_data`).
@group(0) @binding(1) var<storage, read> vertices: array<vec4<f32>>;
const VERTEX_VEC4: u32 = 3u;
// Software traversal's trees (hardware traversal has no binding for them): their nodes, and their leaves'
// triangles (indexed.rs `Leaf`), the trees' own copy, three vec4s a triangle in the triangles' order: (v0, id),
// (e1, id), (e2, -). A candidate's test reads nothing else. The ids: its section of its mesh, and its index in the
// section.
@if(!hwrt) @group(0) @binding(2) var<storage, read> leaves: array<vec4<f32>>;
@if(!hwrt) @group(0) @binding(3) var<storage, read> nodes: array<Node>;
@if(!hwrt) fn leaf_id(ti: u32, k: u32) -> u32 { return bitcast<u32>(leaves[ti * 3u + k].w); }
@group(0) @binding(7) var textures: texture_2d_array<f32>;
@group(0) @binding(8) var samp: sampler;
@group(0) @binding(9) var env_tex: texture_2d<f32>;
// The scene's flat arrays, sections of one buffer of 32-bit words (heap.rs `Stream`), each from the word
// `P.word_first` names: the environment's CDF (floats: [0, H) the rows' marginal CDF, then H rows of W conditional
// entries; `env_cdf_at`), the procedural data (`pword`, `gdata`), the vertex colours (`vcolor_word`), the instances'
// rows (`row_word`).
@group(0) @binding(5) var<storage, read> words: array<u32>;
// (The CDF is the buffer's first section: from word 0, no offset to read.)
fn env_cdf_at(i: u32) -> f32 { return bitcast<f32>(words[i]); }
@group(0) @binding(11) var<storage, read_write> accum: array<Pixel>;
// The vertices that move as they were the previous frame (their records: the positions are read), from the first of
// them on.
@group(0) @binding(6) var<storage, read> prev_verts: array<vec4<f32>>;
// Instances (scene::GpuInstance): world matrix rows, normal matrix rows, (first triangle, object, a spare word, its rows' first).
struct Instance { m0: vec4<f32>, m1: vec4<f32>, m2: vec4<f32>, n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, info: vec4<u32>, p0: vec4<f32>, p1: vec4<f32>, p2: vec4<f32> };
// Bounded participating media (`VolumeMesh`, gpu.rs MediumGpu; F_MEDIA), P.time.w of them: world -> local affine rows,
// (volume function, shape: 0 box / 1 sphere / 2 none while its node is hidden, homogeneous, 1 = it changes with time: `VolumeFunction` `animated`, a
// simulated grid), (majorant 1/m, HG anisotropy, -, -), customData, parameters.
struct Medium { w0: vec4<f32>, w1: vec4<f32>, w2: vec4<f32>, a: vec4<u32>, b: vec4<f32>, c: vec4<f32>, p: array<vec4<f32>, 8> };

// The scene's tables: sections of one buffer of vec4s (heap.rs `Table`), each from the vec4 `P.table_first` names:
//  - materials (scene::GpuMaterial), lights (scene::GpuLight), and per LIGHT_GROUP local lights a sphere (centre,
//    radius) holding all their light (lib.rs `light_groups`);
//  - emitters: (its emitter's index: bits, cumulative weight (normalized), weight, area) for i < counts.y, then the
//    guide table: EMITTER_GUIDE + 1 entry indices (bits), four per vec4 (lib.rs emitter_cdf); the emitters'
//    triangles (`EmitterTri`); the light tree's nodes;
//  - tex_info, per texture: (u0, v0, du, dv) of its rect in the page, (layer, wrap, width, height). See texpack.rs;
//  - objects, per object (scene node): pivot (world position), world bounds size (UE ObjectPositionWS /
//    ObjectBounds), then what `OBJECT_STRIDE` says;
//  - instances (Instance), media (Medium);
//  - the GGX energy table (`energy_lookup`): the specular lobe's two albedo terms at 32 roughnesses x 32 sqrt(NoV), two
//    nodes per vec4;
//  - the glass energy table (`glass_energy`): four values per vec4.
// The buffer whole is `tables` in every layout (unsigned words: integers are read as they are, floats by a bit
// cast): the light groups, the light tree and the energy LUT are read from it, and what a scene has more of is
// another section of it, not another binding.
@group(0) @binding(4) var<storage, read> tables: array<vec4<u32>>;
fn table_f(i: u32) -> vec4<f32> { return bitcast<vec4<f32>>(tables[i]); }
fn table_i(i: u32) -> vec4<i32> { return bitcast<vec4<i32>>(tables[i]); }
// (The light tree is the buffer's first section: from vec4 0, no offset to read.)
fn lt_node(i: u32) -> vec4<f32> { return table_f(i); }
fn light_group_at(i: u32) -> vec4<f32> { return table_f(P.table_first[0].w + i); }
fn energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].y + i); }
fn glass_energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].z + i); }
// An emitter's triangle (lib.rs `GpuEmitterTri`): in world space, the light list's own copy, so a light sample reads
// no placement (what moves it is copied again: emitter_fill.wgsl); `tri`: its triangle in the triangles' table
// (attributes: `emitter_attrs`), `inst`: the instance that places it, `code`: the light tree's path code (0: not one
// of the tree's), EMITTER_MOVES if it moves; `part`: as a hit's (`Hit.part`): its section of its instance's mesh;
// `flags`: EMITTER_CARD. Four vec4s, a cache line.
struct EmitterTri { v0: vec3<f32>, tri: u32, e1: vec3<f32>, inst: u32, e2: vec3<f32>, code: u32, part: u32, flags: u32 };
const EMITTER_TRI_VEC4: u32 = 4u;
const EMITTER_MOVES: u32 = 0x80000000u;
fn emitter_tri_at(i: u32) -> EmitterTri {
    let b = P.table_first[2].w + i * EMITTER_TRI_VEC4;
    let r0 = tables[b];
    let r1 = tables[b + 1u];
    let r2 = tables[b + 2u];
    let r3 = tables[b + 3u];
    return EmitterTri(bitcast<vec3<f32>>(r0.xyz), r0.w, bitcast<vec3<f32>>(r1.xyz), r1.w, bitcast<vec3<f32>>(r2.xyz), r2.w, r3.x, r3.y);
}
// The seven tables read at every hit or light, through `material_at`, `light_at`, `emitter_at`, `tex_info_at`,
// `object_at`, `instance_at` and `medium_at` in every layout.
@if(merged || whole_tables) {
    // The merged layout (merged.rs: a browser's eight storage buffers), and a device whose driver reads the views below
    // wrong (gpu.rs `GpuOptions::table_views`: Android): from the buffer whole, a record made of its vec4s (their
    // counts: the tests hold them to the renderer's records). Slower than the views below where it was measured
    // (docs/RUNTIME.md "The scene's tables"): an offset from the parameters at every read, the records' assembly.
    const MATERIAL_VEC4: u32 = 18u;
    const LIGHT_VEC4: u32 = 5u;
    const INSTANCE_VEC4: u32 = 10u;
    const MEDIUM_VEC4: u32 = 14u;
    fn material_at(i: u32) -> Material {
        let b = P.table_first[0].y + i * MATERIAL_VEC4;
        let t0 = table_i(b + 16u);
        let t1 = table_i(b + 17u);
        return Material(table_f(b), table_f(b + 1u), table_f(b + 2u), table_i(b + 3u), table_i(b + 4u), table_f(b + 5u), table_f(b + 6u), table_f(b + 7u),
            array<vec4<f32>, 8>(table_f(b + 8u), table_f(b + 9u), table_f(b + 10u), table_f(b + 11u), table_f(b + 12u), table_f(b + 13u), table_f(b + 14u), table_f(b + 15u)),
            array<i32, 8>(t0.x, t0.y, t0.z, t0.w, t1.x, t1.y, t1.z, t1.w));
    }
    fn light_at(i: u32) -> Light {
        let b = P.table_first[0].z + i * LIGHT_VEC4;
        return Light(table_f(b), table_f(b + 1u), table_f(b + 2u), table_f(b + 3u), table_f(b + 4u));
    }
    fn emitter_at(i: u32) -> vec4<f32> { return table_f(P.table_first[1].x + i); }
    fn tex_info_at(i: u32) -> vec4<f32> { return table_f(P.table_first[1].y + i); }
    fn object_at(i: u32) -> vec4<f32> { return table_f(P.table_first[1].z + i); }
    fn instance_at(i: u32) -> Instance {
        let b = P.table_first[1].w + i * INSTANCE_VEC4;
        return Instance(table_f(b), table_f(b + 1u), table_f(b + 2u), table_f(b + 3u), table_f(b + 4u), table_f(b + 5u), tables[b + 6u], table_f(b + 7u), table_f(b + 8u), table_f(b + 9u));
    }
    fn medium_at(i: u32) -> Medium {
        let b = P.table_first[2].x + i * MEDIUM_VEC4;
        return Medium(table_f(b), table_f(b + 1u), table_f(b + 2u), tables[b + 3u], table_f(b + 4u), table_f(b + 5u),
            array<vec4<f32>, 8>(table_f(b + 6u), table_f(b + 7u), table_f(b + 8u), table_f(b + 9u), table_f(b + 10u), table_f(b + 11u), table_f(b + 12u), table_f(b + 13u)));
    }
} @else {
    // Where a stage has bindings to spare, each of the seven's section is bound again as an array of its own type
    // (gpu.rs `Gpu::scene_bind_group`: the same buffer, from the section's first byte): a read is one typed load.
    @group(0) @binding(12) var<storage, read> materials: array<Material>;
    @group(0) @binding(13) var<storage, read> lights: array<Light>;
    @group(0) @binding(14) var<storage, read> emitters: array<vec4<f32>>;
    fn material_at(i: u32) -> Material { return materials[i]; }
    fn light_at(i: u32) -> Light { return lights[i]; }
    fn emitter_at(i: u32) -> vec4<f32> { return emitters[i]; }
    @group(0) @binding(15) var<storage, read> tex_info: array<vec4<f32>>;
    @group(0) @binding(16) var<storage, read> objects: array<vec4<f32>>;
    @group(0) @binding(17) var<storage, read> instances: array<Instance>;
    @group(0) @binding(18) var<storage, read> media: array<Medium>;
    fn tex_info_at(i: u32) -> vec4<f32> { return tex_info[i]; }
    fn object_at(i: u32) -> vec4<f32> { return objects[i]; }
    fn instance_at(i: u32) -> Instance { return instances[i]; }
    fn medium_at(i: u32) -> Medium { return media[i]; }
}
// Density grids (gpu.rs F_GRID, `GridsGpu`): field A of every grid, stacked along z; one cell in scenes without.
@group(0) @binding(10) var grid_tex: texture_3d<f32>;
// Vertex colours (three.js `vertexColors`; gpu.rs F_VCOLOR): three sRGB 8-bit colours per triangle.
fn vcolor_word(k: u32) -> u32 { return words[P.word_first[0].z + k]; }
fn vcolor(t: u32, u: f32, v: f32) -> vec3<f32> {
    let c0 = srgb_to_linear(unpack4x8unorm(vcolor_word(t * 3u)).rgb);
    let c1 = srgb_to_linear(unpack4x8unorm(vcolor_word(t * 3u + 1u)).rgb);
    let c2 = srgb_to_linear(unpack4x8unorm(vcolor_word(t * 3u + 2u)).rgb);
    return c0 * (1.0 - u - v) + c1 * u + c2 * v;
}


fn inst_vec(r: Instance, v: vec3<f32>) -> vec3<f32> { return vec3<f32>(dot(r.m0.xyz, v), dot(r.m1.xyz, v), dot(r.m2.xyz, v)); }
// An instance that mirrors its mesh (scene.rs `INST_MIRRORED`, a bit of the record's n1.w): -1, else 1. The placed
// edges' cross product then points to the mesh's inner side, and the tangent frame changes hand.
const INST_MIRRORED: u32 = 4u;
fn inst_sign(r: Instance) -> f32 { return select(1.0, -1.0, (bitcast<u32>(r.n1.w) & INST_MIRRORED) != 0u); }
fn inst_normal(r: Instance, n: vec4<f32>) -> vec4<f32> {
    return vec4<f32>(normalize(vec3<f32>(dot(r.n0.xyz, n.xyz), dot(r.n1.xyz, n.xyz), dot(r.n2.xyz, n.xyz))), n.w);
}
// A model-space triangle's `x` as its instance has it: the instance's object (the record's `info`), and for a
// particle system's mesh the particle's past it (`tri_data` has which; 0 for every other mesh).
fn inst_x(info: vec4<u32>, x: vec4<f32>) -> vec4<f32> {
    return vec4<f32>(x.x, bitcast<f32>(info.y + bitcast<u32>(x.y)), x.z, x.w);
}
// An instance's rows (scene.rs `Row`): four words a section of its mesh, from the record's info.w on. The material
// with its class bits, the section's first triangle, its first emitter (NO_EMITTER: it does not emit). Which section
// a triangle of a mesh is in, its hit says (`Hit.part`); a record's n1.w says whether a row of it is a cutout's or
// glass, and whether its mesh deforms.
const INST_CUTOUT: u32 = 16u;
const INST_GLASS: u32 = 32u;
const INST_DEFORMS: u32 = 64u;
// The instance's mesh is a particle system's: two triangles and an object a particle, from the record's object on.
const INST_PARTICLES: u32 = 128u;
const ROW_MATERIAL: u32 = 0xffffffu;
const ROW_CUTOUT: u32 = 0x1000000u;
const ROW_GLASS: u32 = 0x2000000u;
const NO_EMITTER: u32 = 0xffffffffu;
fn row_word(first: u32, section: u32, k: u32) -> u32 { return words[P.word_first[0].w + (first + section) * 4u + k]; }

// A cutout's map (cutout.rs): whether a point of one of its triangles is solid or a hole, for a ray that only asks
// whether something stands in its way, without the triangle's corners, its material or its texture. A stream of the
// words (`P.word_first[1].y`): a word a triangle of the section, from where its instance's row says (its last word,
// above its lowest bit, plus one), then the triangles' lattices of cells, two bits a cell.
const CUTOUT_NO_MAP: u32 = 0u;
const CUTOUT_NOTHING: u32 = 14u;
const CUTOUT_WHOLE: u32 = 15u;
// The cell of a lattice of n cells an edge that the point (u, v) lies in (cutout.rs `cell_of`, the same).
fn cutout_cell(u: f32, v: f32, n: u32) -> u32 {
    let x = clamp(u, 0.0, 1.0) * f32(n);
    let y = clamp(v, 0.0, 1.0) * f32(n);
    let j = min(u32(y), n - 1u);
    let i = min(u32(x), n - 1u - j);
    let across = (x - f32(i)) + (y - f32(j)) > 1.0 && i + j + 1u < n;
    return j * (2u * n - j) + 2u * i + u32(across);
}
// What the map says of the point (u, v) of triangle `rank` of section `part` of an instance whose rows begin at
// `rows`: 1 solid, 0 a hole, -1 the section has no map (a material whose function may change its opacity, a
// section an edit made). A cell that is a part of both counts as the larger part (its state's low bit).
fn cutout_mapped(rows: u32, part: u32, rank: u32, u: f32, v: f32) -> i32 {
    let run = row_word(rows, part, 3u) >> 1u;
    if (run == 0u) { return -1; }
    let first = P.word_first[1].y;
    let w = words[first + run - 1u + rank];
    let tag = w & 15u;
    if (tag == CUTOUT_WHOLE) { return 1; }
    if (tag == CUTOUT_NOTHING) { return 0; }
    if (tag == CUTOUT_NO_MAP) { return -1; }
    let k = cutout_cell(u, v, 1u << tag);
    return i32((words[first + (w >> 4u) + (k >> 4u)] >> ((k & 15u) * 2u)) & 1u);
}

// The material of a triangle, given its attributes and the instance that places it. Every read of a hit's material
// goes through here: where the material is kept is this function's alone. In the row of the triangle's section,
// which its instance has.
fn material_of(a: TriAttr, inst: u32) -> u32 {
    if (!has(F_INST) || inst == NO_INST) { return 0u; }
    return row_word(instance_at(inst).info.w, bitcast<u32>(a.uv.w), 0u) & ROW_MATERIAL;
}

// A triangle's three vertices (indexed.rs), counted from its mesh's first: what a hit and a candidate's test read,
// and what the acceleration structures are built from.
fn tri_indices(ti: u32) -> vec3<u32> {
    let k = P.word_first[1].x + ti * 3u;
    return vec3<u32>(words[k], words[k + 1u], words[k + 2u]);
}
// Whether an emitter is a rect light's card, which lights one side: its entry says (lib.rs `EMITTER_CARD`).
const EMITTER_CARD: u32 = 1u;
fn emitter_is_card(em: EmitterTri) -> bool { return (em.flags & EMITTER_CARD) != 0u; }
// A triangle read whole: its first corner and its edges, and its attributes as a hit has them: normals and UVs a
// corner; `uv.w`: its section (`part`); `x.y`: its object (where its attributes are placed, `inst_x`: of a particle
// system's mesh, which particle it is). `vi`: where its three vertices are in `vertices` (their tangents are read
// where a frame is asked: `hit_tangent`). `inst`, `part`: as a hit has them (`Hit`): its vertices count from its
// mesh's first.
struct TriData { a: TriAttr, v0: vec3<f32>, e1: vec3<f32>, e2: vec3<f32>, vi: vec3<u32> }
fn tri_data(ti: u32, inst: u32, part: u32) -> TriData {
    var base = 0u;
    var particle = 0u;
    if (has(F_INST) && inst != NO_INST) {
        let r = instance_at(inst);
        base = r.info.z;
        // A particle system's mesh: which particle the triangle is (two each, from the mesh's first).
        if (has(F_PART) && (bitcast<u32>(r.n1.w) & INST_PARTICLES) != 0u) { particle = (ti - r.info.x) >> 1u; }
    }
    let i = (tri_indices(ti) + vec3<u32>(base)) * VERTEX_VEC4;
    let p0 = vertices[i.x];
    let p1 = vertices[i.y];
    let p2 = vertices[i.z];
    var n0 = vertices[i.x + 1u];
    var n1 = vertices[i.y + 1u];
    var n2 = vertices[i.z + 1u];
    let e1 = p1.xyz - p0.xyz;
    let e2 = p2.xyz - p0.xyz;
    // A skinned mesh whose model has no normals has zeros: the triangle's own, as it is posed.
    if (has(F_DEFORM) && all(n0.xyz == vec3<f32>(0.0))) {
        let f = cross(e1, e2);
        let l = length(f);
        var flat = vec3<f32>(0.0);
        if (l > 0.0 && (bitcast<u32>(l) & 0x7f800000u) != 0x7f800000u) { flat = f / l; }
        n0 = vec4<f32>(flat, n0.w);
        n1 = vec4<f32>(flat, n1.w);
        n2 = vec4<f32>(flat, n2.w);
    }
    return TriData(TriAttr(vec4<f32>(n0.xyz, p0.w), vec4<f32>(n1.xyz, n0.w), vec4<f32>(n2.xyz, p1.w), vec4<f32>(n1.w, p2.w, n2.w, bitcast<f32>(part)),
                            vec4<f32>(0.0, bitcast<f32>(particle), 0.0, 0.0)), p0.xyz, e1, e2, i);
}
// The tangent frame at a point of a triangle (barycentrics u, v), in the world: (tangent, hand). Its three vertices'
// tangents there (a file's, a particle's), the hand its first vertex's; a triangle without tangents (a hand of 0)
// has its own, from its edges, its UVs and its first normal as `td` has them (its model's space). Then placed by its
// instance (`inst`; NO_INST: left as it is). Not of unit length where it is its vertices': who asks makes it so
// against the normal. Asked where a frame is read: a normal map, a function.
fn hit_tangent(td: TriData, inst: u32, u: f32, v: f32) -> vec4<f32> {
    let t0 = vertices[td.vi.x + 2u];
    var t = vec4<f32>(t0.xyz * (1.0 - u - v) + vertices[td.vi.y + 2u].xyz * u + vertices[td.vi.z + 2u].xyz * v, t0.w);
    if (t0.w == 0.0) {
        let a = td.a;
        let uv0 = vec2<f32>(a.n0.w, a.n1.w);
        let d1 = vec2<f32>(a.n2.w, a.uv.x) - uv0;
        let d2 = a.uv.yz - uv0;
        let det = d1.x * d2.y - d2.x * d1.y;
        if (abs(det) < 1e-12) {
            var any = vec3<f32>(0.0, 1.0, 0.0);
            if (abs(a.n0.x) < 0.9) { any = vec3<f32>(1.0, 0.0, 0.0); }
            t = vec4<f32>(normalize(cross(a.n0.xyz, any)), 1.0);
        } else {
            let r = 1.0 / det;
            let tu = (td.e1 * d2.y - td.e2 * d1.y) * r;
            let l = length(tu);
            var tn = vec3<f32>(0.0);
            if (l > 0.0 && (bitcast<u32>(l) & 0x7f800000u) != 0x7f800000u) { tn = tu / l; }
            let bt = (td.e2 * d1.x - td.e1 * d2.x) * r;
            var hand = -1.0;
            if (dot(cross(a.n0.xyz, tn), bt) < 0.0) { hand = 1.0; }
            t = vec4<f32>(tn, hand);
        }
    }
    if (has(F_INST) && inst != NO_INST) {
        let r = instance_at(inst);
        t = vec4<f32>(unit_or_zero(inst_vec(r, t.xyz)), t.w * inst_sign(r));
    }
    return t;
}
// A vector of unit length, or zeros where it has no direction (or is not finite).
fn unit_or_zero(v: vec3<f32>) -> vec3<f32> {
    let d = dot(v, v);
    if (d > 0.0 && (bitcast<u32>(d) & 0x7f800000u) != 0x7f800000u) { return normalize(v); }
    return vec3<f32>(0.0);
}

// A model-space triangle's shading attributes placed by instance r. (Not its tangents, which
// are placed where they are read: `hit_tangent`.)
fn inst_attr(r: Instance, a: TriAttr) -> TriAttr {
    var b = a;
    b.n0 = inst_normal(r, a.n0);
    b.n1 = inst_normal(r, a.n1);
    b.n2 = inst_normal(r, a.n2);
    b.x = inst_x(r.info, a.x);
    return b;
}

// ------------------------------------------------------------------------------------------------
// RNG

// Path vertex index of the current shading point (cheaper procedural detail / fewer candidates past the first hit).
var<private> cur_depth: u32;
// Live "ray tracing off" (P.jitter.z, LiveCore::rays): set once the camera's own ray has found its surface. From then
// on `trace` reports a miss, so nothing is shadowed, a bounce sees the sky and a mirror reflects the sky: what a
// rasterizer without shadow maps draws, on any GPU, from the same scene and the same shading. The switch is a uniform:
// no kernel is rebuilt to flip it.
var<private> rays_off: bool;
// The path so far is camera ray + mirror-like bounces (puddles, glass): surface detail is still visible.
var<private> mirror_path: bool;

// Shading points the camera sees, directly or in a mirror-like reflection (wet streets, glass): they get the exact
// light loop and resampled emitters, so reflections are as clean as what they reflect.
fn seen_directly() -> bool {
    return cur_depth == 0u || (cur_depth == 1u && mirror_path);
}
// Specular share of the last BSDF evaluation (per channel), the specular part of the direct light being summed, and
// whether the last BSDF sample took the specular lobe: the live denoiser filters diffuse and specular apart.
var<private> split_frac: vec3<f32>;
// Where the last vertex sampled emitters (its point and normal, 0 = none: fog): a BSDF ray's emitter hit weighs its MIS
// by the light tree's pmf there (emit_mis).
var<private> mis_x: vec3<f32>;
var<private> mis_n: vec3<f32>;
var<private> dl_spec: vec3<f32>;
// At camera hits, the direct light from directional lights (the sun: a tiny disk, so nearly deterministic) and its
// specular part: the live viewport keeps it in a signal of its own (no denoiser; short history while things change).
// Local lights stay in the denoised signals: their soft shadows are noisy, and on Kabukicho moving them here cost
// motion and static error (excess 1.71 / 1.86 / 2.20 -> 1.92 / 1.95 / 2.33, k = 1 SSIM 0.640 -> 0.620).
var<private> dl_det: vec3<f32>;
var<private> dl_det_spec: vec3<f32>;
var<private> sampled_spec: bool;
// The last BSDF sample went through the surface (glass: refraction, a delta lobe).
var<private> sampled_trans: bool;

fn pcg(v: u32) -> u32 {
    let s = v * 747796405u + 2891336453u;
    let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
    return (w >> 22u) ^ w;
}


// Buckets of the emitter CDF's guide table (lib.rs EMITTER_GUIDE).
const EMITTER_GUIDE: u32 = 65536u;

fn emitter_guide(k: u32) -> u32 {
    return bitcast<u32>(emitter_at(P.counts.y + k / 4u)[k % 4u]);
}

// The table's header, after the guide (lib.rs `emitter_header`): x the total weight, y the share of it outside the
// light tree. Requires counts.y > 0.
fn emitter_totals() -> vec4<f32> { return emitter_at(P.counts.y + EMITTER_GUIDE / 4u + 1u); }

// Whether the light list has an emitter that weighs something now: counts.y is its size, the total the table's.
fn emitters_on() -> bool {
    if (P.counts.y == 0u) { return false; }
    return emitter_totals().x > 0.0;
}

// One emitter CDF entry: the first whose cumulative weight is not below u. The guide table bounds the binary search to
// u's bucket (u * EMITTER_GUIDE is exact for the 24-bit u), which holds the same entry a search over the whole CDF
// finds. Requires counts.y > 0.
fn emitter_pick_u(u: f32) -> vec4<f32> {
    let k = min(u32(u * f32(EMITTER_GUIDE)), EMITTER_GUIDE - 1u);
    var lo = emitter_guide(k);
    var hi = emitter_guide(k + 1u);
    while (lo < hi) {
        let mid = (lo + hi) / 2u;
        if (emitter_at(mid).y < u) { lo = mid + 1u; } else { hi = mid; }
    }
    return emitter_at(min(lo, P.counts.y - 1u));
}

// Light tree (ltree.rs): nodes after the CDF in `emitters`, one vec4 each: pack2x16float(centre x, y),
// pack2x16float(centre z, radius), power, child word (the left child, the right one follows it; or LT_LEAF |
// (count - 1) << 29 | its first entry). The tree's emitters come first in the CDF in leaf order, the moving ones after
// them (from entry P.ltree.y).
const LT_LEAF: u32 = 0x80000000u;
const LT_PATH_BITS: u32 = 26u;
// A_FAR_EMITTERS: tree nodes wholly farther than this (m) from the shading point are not proposed. A city's emitters
// are mostly that far from any one point: Tokyo's aerial view traces in 4.7 ms with the cut, 9.2 without.
const LT_FAR: f32 = 120.0;

fn lt_on() -> bool { return P.ltree.w > 0.5; }


// Importance of a tree node seen from x on a surface with normal n (n = 0: no hemisphere, a fog point): power x the
// best cosine any point of its sphere can have at x / max(distance², radius²).
fn lt_imp(nd: vec4<f32>, x: vec3<f32>, n: vec3<f32>) -> f32 {
    let cxy = unpack2x16float(bitcast<u32>(nd.x));
    let czr = unpack2x16float(bitcast<u32>(nd.y));
    let dv = vec3<f32>(cxy, czr.x) - x;
    let d2 = dot(dv, dv);
    let r2 = czr.y * czr.y;
    var cb = 1.0;
    if (d2 > r2 && dot(n, n) > 0.0) {
        let inv = inverseSqrt(d2);
        let cos_t = dot(n, dv) * inv;
        let sin_b = czr.y * inv;
        let cos_b = sqrt(max(1.0 - sin_b * sin_b, 0.0));
        if (cos_t < cos_b) {
            cb = max(cos_t * cos_b + sqrt(max(1.0 - cos_t * cos_t, 0.0)) * sin_b, 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 city 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);
}

// A CDF entry by power within entries [lo, hi) (cumulative p0 .. p1): one guide-table lookup.
fn emitter_pick_range(lo: u32, hi: u32, r: f32) -> vec4<f32> {
    let p0 = select(0.0, emitter_at(max(lo, 1u) - 1u).y, lo > 0u);
    let p1 = emitter_at(hi - 1u).y;
    let u = min(p0 + r * (p1 - p0), p1);
    let k = min(u32(u * f32(EMITTER_GUIDE)), EMITTER_GUIDE - 1u);
    var l = emitter_guide(k);
    var h = emitter_guide(k + 1u);
    while (l < h) {
        let mid = (l + h) / 2u;
        if (emitter_at(mid).y < u) { l = mid + 1u; } else { h = mid; }
    }
    return emitter_at(clamp(l, lo, hi - 1u));
}

// An emitter entry for a point x (normal n), its selection probability `p` and its weight `w` (area x luminance x
// power, as the CDF weighs). With the tree: the moving emitters by power with probability `emitter_totals().y`, else the tree
// descended by importance to a leaf, and one of its few entries by weight. Without it: the CDF entry (p = weight /
// total).
struct EPick { e: vec4<f32>, p: f32, w: f32 };

fn emitter_draw(x: vec3<f32>, n: vec3<f32>, rd: u32) -> EPick {
    let r3 = rng3(rd);
    let tot = emitter_totals();
    if (!(tot.x > 0.0)) { return EPick(vec4<f32>(0.0), 0.0, 0.0); }
    if (!lt_on()) {
        let e = emitter_pick_u(r3.x);
        return EPick(e, e.z / tot.x, e.z);
    }
    if (r3.x < tot.y) {
        let e = emitter_pick_range(bitcast<u32>(P.ltree.y), P.counts.y, r3.y);
        return EPick(e, e.z / tot.x, e.z);
    }
    var p = 1.0 - tot.y;
    var u = r3.y;
    var w = bitcast<u32>(lt_node(0u).w);
    for (var k = 0u; k <= LT_PATH_BITS && (w & LT_LEAF) == 0u; k++) {
        let l = lt_node(w);
        let r = lt_node(w + 1u);
        let il = lt_imp(l, x, n);
        let ir = lt_imp(r, x, n);
        if (!(il + ir > 0.0)) { return EPick(vec4<f32>(0.0), 0.0, 0.0); }
        let pl = il / (il + ir);
        if (u < pl) { w = bitcast<u32>(l.w); p *= pl; u = u / pl; } else { w = bitcast<u32>(r.w); p *= 1.0 - pl; u = (u - pl) / (1.0 - pl); }
        u = clamp(u, 0.0, 0.99999994);
    }
    if ((w & LT_LEAF) == 0u) { return EPick(vec4<f32>(0.0), 0.0, 0.0); }
    let lo = w & 0x1fffffffu;
    let hi = lo + ((w >> 29u) & 3u) + 1u;
    var wsum = 0.0;
    for (var j = lo; j < hi; j++) { wsum += emitter_at(j).z; }
    var t = r3.z * wsum;
    var e = emitter_at(hi - 1u);
    for (var j = lo; j < hi; j++) {
        let c = emitter_at(j);
        if (t < c.z) { e = c; break; }
        t -= c.z;
    }
    return EPick(e, p * e.z / wsum, e.z);
}

// The probability that emitter_draw(x, n) picks emitter `ei` (`em`), from what the draw reads: one of the tree's
// (its code names its path) by the same choices down the path and its weight in its leaf; any other (its code is its
// entry in the CDF) by its entry's weight.
fn emitter_pmf(ei: u32, em: EmitterTri, x: vec3<f32>, n: vec3<f32>) -> f32 {
    let tot = emitter_totals();
    if (!(tot.x > 0.0)) { return 0.0; }
    let code = em.code & ~EMITTER_MOVES;
    if ((code >> LT_PATH_BITS) == 0u) { return emitter_at(code).z / tot.x; }
    let depth = (code >> LT_PATH_BITS) - 1u;
    var p = 1.0 - tot.y;
    var w = bitcast<u32>(lt_node(0u).w);
    for (var k = 0u; k < depth; k++) {
        let l = lt_node(w);
        let r = lt_node(w + 1u);
        let il = lt_imp(l, x, n);
        let ir = lt_imp(r, x, n);
        if (!(il + ir > 0.0)) { return 0.0; }
        let right = (code >> k) & 1u;
        p *= select(il, ir, right == 1u) / (il + ir);
        w = bitcast<u32>(select(l.w, r.w, right == 1u));
    }
    let lo = w & 0x1fffffffu;
    let hi = lo + ((w >> 29u) & 3u) + 1u;
    var wsum = 0.0;
    var we = 0.0;
    for (var j = lo; j < hi; j++) {
        let c = emitter_at(j);
        wsum += c.z;
        if (bitcast<u32>(c.x) == ei) { we = c.z; }
    }
    return p * we / wsum;
}

// ------------------------------------------------------------------------------------------------
// Intersection

// `inst`: the instance whose triangle `tri` is, in its mesh's space (a procedural hit's: its object's record; no
// hit: NO_INST). `part`: the section of its mesh the triangle is in (the acceleration structure's geometry; a
// unit's tree's leaf's id): its instance's row for it has its material.
// (What reads a hit's record tests `inst != NO_INST`, which every hit passes: without the test a frame is 1 to 3 %
// longer in some scenes, a crowd under the sky 6.36 -> 6.57 ms.)
struct Hit { t: f32, tri: u32, u: f32, v: f32, inst: u32, part: u32 };
const NO_INST: u32 = 0xffffffffu;

// ------------------------------------------------------------------------------------------------
// Procedural geometry (F_PROC; scene::ProcObject): a game's boxes and its geometry function (`gf_<name>`), which
// intersects the object-space ray with what one box holds; the hardware (or the software loop below) finds the boxes.
// A procedural object's record in `instances` follows the model instances': world rows, normal rows, info = (header
// word in proc_data, object, geometry function, casts shadows), the previous frame's world rows. Its hits are
// Hit(t, PROC_BIT | material << 23 | box, the object-space normal octahedral in (u, v), record).
const PROC_BIT: u32 = 0x80000000u;

// The geometry function's input: the ray in the object's space (d is not normalised: t is the world ray's parameter)
// and the interval a hit must lie in, the box (its index, min, max), where the object's data starts and its length in
// words (read it with `gdata` / `gdataf`), the object's customData and the scene time.
struct GIn { o: vec3<f32>, d: vec3<f32>, tmin: f32, tmax: f32, prim: u32, lo: vec3<f32>, hi: vec3<f32>, data: u32, count: u32, custom: vec4<f32>, time: f32 };
// Its output: t (none: outside (tmin, tmax), e.g. the default -1), the object-space normal (any length, facing either
// way), the material (an index into the mesh's materials; past the last: the last).
struct GOut { t: f32, normal: vec3<f32>, material: u32, attr: vec2<f32> };

// Procedural data (scene::proc_data): per object its header (`proc_vec`), materials, boxes (min xyz, max xyz) and the
// game's own data, 32-bit words.
// `pword`: the renderer's own reads (headers, boxes, materials). `gdata`: the geometry function's, of its object's data
// only, word i.data .. i.data + i.count - 1; anything else reads 0. The kernel is compiled without bounds checks (its
// indices come from the scene build) and the function is game code: it must not reach past its data.
fn pword(k: u32) -> u32 { return words[P.word_first[0].y + k]; }
fn pwordf(k: u32) -> f32 { return bitcast<f32>(pword(k)); }
var<private> gdata_first: u32;
var<private> gdata_count: u32;
fn gdata(k: u32) -> u32 {
    if (k - gdata_first >= gdata_count) { return 0u; }
    return pword(k);
}
fn gdataf(k: u32) -> f32 { return bitcast<f32>(gdata(k)); }

// @geometry-functions-begin
fn geometry_function(f: u32, i: GIn) -> GOut { return GOut(-1.0, vec3<f32>(0.0, 1.0, 0.0), 0u, vec2<f32>(0.0)); }
// @geometry-functions-end

fn is_proc(h: Hit) -> bool { return has(F_PROC) && h.tri != 0xffffffffu && (h.tri & PROC_BIT) != 0u; }

// Header words of a procedural object (scene::PROC_HEADER): box count, first box word, first data word, material count,
// bounds min xyz, first material word, bounds max xyz, data length.
fn proc_vec(w: u32) -> vec3<f32> { return vec3<f32>(pwordf(w), pwordf(w + 1u), pwordf(w + 2u)); }

// Octahedral unit vector in two floats (a hit's u, v).
fn proc_oct(v: vec3<f32>) -> vec2<f32> {
    let n = v / max(abs(v.x) + abs(v.y) + abs(v.z), 1e-30);
    let w = (1.0 - abs(n.yx)) * select(vec2<f32>(-1.0), vec2<f32>(1.0), n.xy >= vec2<f32>(0.0));
    return select(w, n.xy, n.z >= 0.0);
}
fn proc_unoct(e: vec2<f32>) -> vec3<f32> {
    var n = vec3<f32>(e, 1.0 - abs(e.x) - abs(e.y));
    let t = max(-n.z, 0.0);
    n.x += select(t, -t, n.x >= 0.0);
    n.y += select(t, -t, n.y >= 0.0);
    return normalize(n);
}

// World -> object space of a record: its world rows' inverse (the normal rows are the inverse transpose of its 3 x 3).
fn proc_dir(r: Instance, d: vec3<f32>) -> vec3<f32> { return r.n0.xyz * d.x + r.n1.xyz * d.y + r.n2.xyz * d.z; }
fn proc_point(r: Instance, p: vec3<f32>) -> vec3<f32> { return proc_dir(r, p - vec3<f32>(r.m0.w, r.m1.w, r.m2.w)); }

// Box `prim` of record `rec` against the object-space ray: the geometry function's hit in (tmin, tmax), else t = -1.
fn proc_box(rec: u32, prim: u32, o: vec3<f32>, d: vec3<f32>, tmin: f32, tmax: f32) -> GOut {
    let info = instance_at(rec).info;
    let b = pword(info.x + 1u) + prim * 6u;
    gdata_first = pword(info.x + 2u);
    gdata_count = pword(info.x + 11u);
    let g = geometry_function(info.z, GIn(o, d, tmin, tmax, prim, proc_vec(b), proc_vec(b + 3u), gdata_first, gdata_count, object_at(info.y * OBJECT_STRIDE + 2u), P.time.x));
    if (!(g.t > tmin && g.t < tmax)) { return GOut(-1.0, g.normal, 0u, g.attr); }
    return g;
}

// (u, v) carry 30 bits each as an ordinary float: exponent bits 01xxxxxx (64..127: never NaN, infinite or denormal,
// whose bits WGSL does not promise to keep through a bitcast), the payload in the sign bit and bits 28..0. u: the
// octahedral normal, 15 bits per component; v: the attribute, two half floats rounded to 15 bits (9-bit mantissa).
fn proc_word(p: u32) -> f32 { return bitcast<f32>(((p >> 29u) << 31u) | 0x20000000u | (p & 0x1fffffffu)); }
fn proc_bits(f: f32) -> u32 { let w = bitcast<u32>(f); return ((w >> 31u) << 29u) | (w & 0x1fffffffu); }

fn proc_hit(t: f32, g: GOut, prim: u32, rec: u32) -> Hit {
    let q = vec2<u32>(round(clamp(proc_oct(g.normal) * 0.5 + 0.5, vec2<f32>(0.0), vec2<f32>(1.0)) * 32767.0));
    let a = pack2x16float(g.attr);
    // Each half rounded to its upper 15 bits (a carry into the exponent is the right rounding; 0x7fff stays put).
    let ha = min(((a & 0xffffu) + 1u) >> 1u, 0x7fffu);
    let hb = min(((a >> 16u) + 1u) >> 1u, 0x7fffu);
    return Hit(t, PROC_BIT | (min(g.material, 255u) << 23u) | prim, proc_word(q.x | (q.y << 15u)), proc_word(ha | (hb << 15u)), rec, 0u);
}

// A procedural hit's attribute (GOut.attr): its material function's `i.uv`.
fn proc_attr(h: Hit) -> vec2<f32> {
    let p = proc_bits(h.v);
    return unpack2x16float(((p & 0x7fffu) << 1u) | (((p >> 15u) & 0x7fffu) << 17u));
}

// A procedural hit's world normal (geometric = shading) through its record's normal rows.
fn proc_normal(h: Hit) -> vec3<f32> {
    let r = instance_at(h.inst);
    let p = proc_bits(h.u);
    let n = proc_unoct(vec2<f32>(f32(p & 0x7fffu), f32(p >> 15u)) / 32767.0 * 2.0 - 1.0);
    return normalize(vec3<f32>(dot(r.n0.xyz, n), dot(r.n1.xyz, n), dot(r.n2.xyz, n)));
}

// Software traversal (without `hwrt`: trace_hw.wgsl's traversal is the hardware's).

@if(!hwrt) fn ray_aabb(o: vec3<f32>, inv_d: vec3<f32>, bmin: vec3<f32>, bmax: vec3<f32>, tmax: f32) -> f32 {
    let t0 = (bmin - o) * inv_d;
    let t1 = (bmax - o) * inv_d;
    let tmin_v = min(t0, t1);
    let tmax_v = max(t0, t1);
    let tn = max(max(tmin_v.x, tmin_v.y), max(tmin_v.z, 0.0));
    let tf = min(min(tmax_v.x, tmax_v.y), min(tmax_v.z, tmax));
    return select(INF, tn, tn <= tf);
}

@if(!hwrt) fn intersect_tri(o: vec3<f32>, d: vec3<f32>, i: u32, tmax: f32) -> vec3<f32> {
    let k = i * 3u;
    let v0 = leaves[k].xyz;
    let e1 = leaves[k + 1u].xyz;
    let e2 = leaves[k + 2u].xyz;
    let pv = cross(d, e2);
    let det = dot(e1, pv);
    if (abs(det) < 1e-12) { return vec3<f32>(INF, 0.0, 0.0); }
    let inv = 1.0 / det;
    let tv = o - v0;
    let u = dot(tv, pv) * inv;
    if (u < 0.0 || u > 1.0) { return vec3<f32>(INF, 0.0, 0.0); }
    let qv = cross(tv, e1);
    let v = dot(d, qv) * inv;
    if (v < 0.0 || u + v > 1.0) { return vec3<f32>(INF, 0.0, 0.0); }
    let t = dot(e2, qv) * inv;
    if (t <= 0.0 || t >= tmax) { return vec3<f32>(INF, 0.0, 0.0); }
    return vec3<f32>(t, u, v);
}

// mode: TRACE_CLOSEST, TRACE_SHADOW (any hit among shadow casters), TRACE_ANY (any hit on any surface). The scene's
// triangles are its units' (trace_units.wgsl), then the procedural objects.
@if(!hwrt) fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {
    var hit = Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);
    if (rays_off) { return hit; }
    @if(units) hit = trace_units(o, d, 1.0 / select(d, vec3<f32>(1e-20), abs(d) < vec3<f32>(1e-20)), hit, mode);
    if (has(F_PROC)) { return trace_procs(o, d, hit, mode); }
    return hit;
}

// Procedural geometry, software traversal (the reference the hardware one is checked against): each object's bounds,
// then its boxes through the object's BVH (scene::ProcLayout with `sw`: nodes as bvh::GpuNode words, and the box of
// each leaf slot, so the geometry function gets the box's own index).
@if(!hwrt) fn trace_procs(o: vec3<f32>, d: vec3<f32>, hit_in: Hit, mode: u32) -> Hit {
    var hit = hit_in;
    let first = P.procs.z;
    for (var k = 0u; k < P.procs.y; k++) {
        let rec = first + k;
        let r = instance_at(rec);
        if (mode == TRACE_SHADOW && r.info.w == 0u) { continue; }
        let lo = proc_point(r, o);
        let ld = proc_dir(r, d);
        let inv = 1.0 / select(ld, vec3<f32>(1e-20), abs(ld) < vec3<f32>(1e-20));
        let h = r.info.x;
        if (ray_aabb(lo, inv, proc_vec(h + 4u), proc_vec(h + 8u), hit.t) == INF) { continue; }
        let bw = pword(h + 1u);
        let nb = pword(h + 12u);
        let ob = pword(h + 13u);
        var stack: array<u32, 48>;
        var sp = 0u;
        var node = 0u;
        loop {
            let w = nb + node * 8u;
            let first_or_left = pword(w + 3u);
            let count = pword(w + 7u);
            if (count > 0u) {
                for (var q = 0u; q < count; q++) {
                    let p = pword(ob + first_or_left + q);
                    if (ray_aabb(lo, inv, proc_vec(bw + p * 6u), proc_vec(bw + p * 6u + 3u), hit.t) == INF) { continue; }
                    let g = proc_box(rec, p, lo, ld, 0.0, hit.t);
                    if (g.t >= 0.0) {
                        hit = proc_hit(g.t, g, p, rec);
                        if (mode != TRACE_CLOSEST) { return hit; }
                    }
                }
                if (sp == 0u) { break; }
                sp--;
                node = stack[sp];
                continue;
            }
            let wl = nb + first_or_left * 8u;
            var tl = ray_aabb(lo, inv, proc_vec(wl), proc_vec(wl + 4u), hit.t);
            var tr = ray_aabb(lo, inv, proc_vec(wl + 8u), proc_vec(wl + 12u), hit.t);
            if (tl == INF && tr == INF) {
                if (sp == 0u) { break; }
                sp--;
                node = stack[sp];
                continue;
            }
            var near = first_or_left;
            var far = first_or_left + 1u;
            if (tr < tl) {
                near = far;
                far = first_or_left;
                let tmp = tl; tl = tr; tr = tmp;
            }
            node = near;
            if (tr != INF && sp < 48u) {
                stack[sp] = far;
                sp++;
            }
        }
    }
    return hit;
}


// What a shadow ray keeps of its light: a weight, 0 where a surface stops it, and every caller multiplies by it.
// (Until 2026-11-16 a pass / stop decision; the glass's colour then reached only the callers that asked for it, and
// fog and volume points took its largest channel.)
//
// The analytic lights' and the sky's: objects that cast no shadow (castShadow = false, glass) let the ray through,
// the glass it crosses at its transmission's share and colour (`glass_tr`; in full with A_GLASS_SHADOWS), the media
// at their transmittance. `sky`: as `glass_tr` takes it.
fn shadow_tr(o: vec3<f32>, d: vec3<f32>, tmax: f32, sky: bool, rd: u32) -> vec3<f32> {
    shadow_hole = false;
    if (trace(o, d, tmax, TRACE_SHADOW).tri != 0xffffffffu) { return vec3<f32>(0.0); }
    var tr = vec3<f32>(1.0);
    if (!approx(A_GLASS_SHADOWS) && has(F_GLASS)) {
        tr = glass_tr(o, d, tmax, sky);
        if (all(tr <= vec3<f32>(0.0))) { return tr; }
    }
    return tr * media_shadow(o, d, tmax, rd);
}

// Whether a shadow ray's light can be less than whole in this kernel (glass that tints, media). Elsewhere the weight
// is 0 or 1, and `tr3` / `tr1` make it a constant 1 past the caller's test for 0, which the compiler folds away: such
// scenes' code is as it was with a decision (Bistro's trace is 2 % slower with the products left in, and 1 % with
// the callers' two tests side by side instead of nested).
fn shadow_weighted() -> bool { return (!approx(A_GLASS_SHADOWS) && has(F_GLASS)) || has(F_MEDIA) || has(F_HMEDIA); }
fn tr3(v: vec3<f32>) -> vec3<f32> {
    if (shadow_weighted()) { return v; }
    return vec3<f32>(1.0);
}
fn tr1(v: f32) -> f32 {
    if (shadow_weighted()) { return v; }
    return 1.0;
}

// The media's transmittance along a shadow ray: every medium's (ratio tracking: an unbiased estimate), or with
// A_MEDIA_SHADOWS the homogeneous ones' (water) alone, analytic.
fn media_shadow(o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> f32 {
    if (media_shadows()) { return media_tr(o, d, tmax, rd); }
    if (approx(A_MEDIA_SHADOWS) && has(F_HMEDIA)) { return media_homogeneous(o, d, tmax, false, rd).tr; }
    return 1.0;
}

// 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 (sky_tr). 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).
fn glass_tr(o_in: vec3<f32>, d: vec3<f32>, tmax: f32, sky: bool) -> vec3<f32> {
    var o = o_in;
    var left = tmax;
    var tr = vec3<f32>(1.0);
    var odd = false;
    var t0 = 0.0;
    for (var k = 0u; k < 8u; k++) {
        let h = trace(o, d, left, TRACE_CLOSEST);
        if (h.tri == 0xffffffffu) { break; }
        t0 += h.t;
        let g = glass_hit(h, d, t0);
        if (g.share > 0.0) {
            tr *= g.share * g.tint;
            odd = !odd;
        }
        o = offset_origin(o + d * h.t, select(g.ng, -g.ng, dot(g.ng, d) < 0.0));
        left -= h.t;
        if (left <= 0.0 || all(tr <= vec3<f32>(0.0))) { break; }
    }
    if (sky && odd) { return vec3<f32>(0.0); }
    return tr;
}

// What reaches a lit point from an analytic light (`shadow_tr`). `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) {
        shadow_hole = false;
        return vec3<f32>(1.0);
    }
    return shadow_tr(o, d, tmax, false, rd);
}

// Glass at a hit along d, `t` from the ray's start (texture LOD): its geometric normal, the share of the ray its
// transmission takes at that angle (transmission (x its texture) x (1 - a Schlick specular albedo); 0: not glass), its
// tint (base colour x texture: what the transmission lobe passes), and whether a ray from that side is totally
// reflected.
struct GlassAt { ng: vec3<f32>, share: f32, tir: bool, tint: vec3<f32> };

// `glass_at` of any hit: procedural surfaces are opaque (`surface_proc`). (Kept out of glass_at itself: there, even
// compiled out, it changed how Metal compiled the glass path, and glass scenes rendered 0.08 % of values differently.)
fn glass_hit(h: Hit, d: vec3<f32>, t: f32) -> GlassAt {
    if (is_proc(h)) { return GlassAt(proc_normal(h), 0.0, false, vec3<f32>(1.0)); }
    return glass_at(h, d, t);
}

fn glass_at(h: Hit, d: vec3<f32>, t: f32) -> GlassAt {
    let td = tri_data(h.tri, h.inst, h.part);
    var a = td.a;
    var e1 = td.e1;
    var e2 = td.e2;
    var side = 1.0;
    if (has(F_INST) && h.inst != NO_INST) {
        let r = instance_at(h.inst);
        e1 = inst_vec(r, e1);
        e2 = inst_vec(r, e2);
        a = inst_attr(r, a);
        side = inst_sign(r);
    }
    let m = material_at(material_of(a, h.inst));
    var g = GlassAt(normalize(cross(e1, e2)) * side, 0.0, false, vec3<f32>(1.0));
    var tr = clamp(m.layer.x, 0.0, 1.0) * (1.0 - clamp(m.params.x, 0.0, 1.0));
    if (tr <= 0.0) { return g; }
    g.tint = m.base_color.rgb;
    if (has(F_TINT)) { g.tint *= obj_tint(object_of(a)); }
    if (has(F_VCOLOR) && m.uv.w > 0.0) { g.tint *= vcolor(h.tri, h.u, h.v); }
    if (has(F_TEX) && (m.tex0.x >= 0 || m.uv.z > 0.5)) {
        let uv = mesh_uv(a, m, h.u, h.v);
        let fp = max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7);
        let lod = mesh_lod(mesh_density(e1, e2, a, m), fp * fp, 1.0) - LOD_BIAS;
        if (m.tex0.x >= 0) { g.tint *= srgb_to_linear(tex(m.tex0.x, uv, lod).rgb); }
        if (m.uv.z > 0.5) { tr *= tex(i32(m.uv.z) - 1, uv, lod).r; }
    }
    let c = abs(dot(g.ng, d));
    let ior = max(m.layer.y, 1.0001);
    let eta = select(1.0 / ior, ior, dot(g.ng, d) > 0.0);
    g.tir = eta * eta * (1.0 - c * c) >= 1.0;
    // (Schlick from either side, no total reflection: the ray goes straight where the light it stands for refracts,
    // glass_tr. With the dielectric's own reflectance a surface seen past the critical angle let the whole sky
    // through: water/furnace 1.16.)
    let r = (ior - 1.0) / (ior + 1.0);
    let f0 = r * r;
    // What the interface lets through: all but the specular lobe's directional albedo at this roughness and angle (as
    // `lobes` has it: `spec_terms`).
    g.share = tr * (1.0 - spec_terms(vec3<f32>(f0), energy_lookup(clamp(m.params.y, 0.02, 1.0), c), P.misc.z).e.x);
    return g;
}

// Shadow rays toward the environment: `shadow_tr` with `sky`, where glass that bends the ray (an odd number of glass
// surfaces: a water surface, the shading point inside a glass solid) blocks it. The sky there is the refracted paths'
// (the path loop counts it in full past such glass), which find it where it is (Snell's window from under water).
fn sky_tr(o: vec3<f32>, d: vec3<f32>, rd: u32) -> vec3<f32> {
    return shadow_tr(o, d, INF, true, rd);
}

// Live homogeneous media (VolumeMesh `homogeneous`: constant coefficients, Coeff = albedo rgb + extinction, Emission rgb,
// in the function's first parameters) along o + d t, t < tmax, without the volume function: transmittance, and with
// `light` the emission and the in-scattering from the volume voxels at each crossing's middle. The live megakernel's
// only media code: water and other constant media attenuate reflection, refraction and shadow rays; other media are
// the camera rays' alone (media_composite).
fn media_homogeneous(o: vec3<f32>, d: vec3<f32>, tmax: f32, light: bool, rd: u32) -> March {
    var r = March(1.0, vec3<f32>(0.0), vec2<f32>(1.0, 0.0));
    let n = min(u32(P.time.w), 32u);
    if (!light) {
        // Transmittance alone: the media's product, in any order.
        for (var k = 0u; k < n; k++) {
            let m = medium_at(k);
            if (m.a.z == 0u) { continue; }
            let sp = medium_span(m, o, d);
            let a = max(sp.x, 0.0);
            let b = min(sp.y, tmax);
            if (a < b) { r.tr *= exp(-m.p[0].w * (b - a)); }
        }
        return r;
    }
    // With their light: along the ray, a stretch at a time between the points where it enters or leaves a medium, the
    // coefficients of the media it is in there summed (media may overlap, and the table's order is not the ray's).
    var t = 0.0;
    for (var s = 0u; s <= 2u * n; s++) {
        var st = 0.0;
        var sc = vec3<f32>(0.0);
        var em = vec3<f32>(0.0);
        var end = tmax;
        var inside = false;
        for (var k = 0u; k < n; k++) {
            let m = medium_at(k);
            if (m.a.z == 0u) { continue; }
            let sp = medium_span(m, o, d);
            let a = max(sp.x, 0.0);
            let b = min(sp.y, tmax);
            if (a >= b) { continue; }
            if (a > t) {
                end = min(end, a);
            } else if (b > t) {
                inside = true;
                end = min(end, b);
                st += m.p[0].w;
                sc += m.p[0].rgb * m.p[0].w;
                em += m.p[1].rgb;
            }
        }
        if (inside) {
            let len = end - t;
            let tr = exp(-st * len);
            // In-scattering at two points stratified by transmittance (half of what scatters toward o happens before
            // the first, ...): one lookup in the middle lit a deep crossing with its dimmer depth.
            var lin = vec3<f32>(0.0);
            if (cache_on()) {
                let u2 = rng2(rng_sub(rd, 0x100u + s));
                for (var j = 0u; j < 2u; j++) {
                    let q = (f32(j) + u2[j]) * 0.5 * (1.0 - tr);
                    let tt = select(-log(1.0 - q) / st, (f32(j) + 0.5) * 0.5 * len, st <= 1e-6);
                    lin += 0.5 * cache_point(o + d * (t + tt)).rgb;
                }
            }
            let w = select(len, (1.0 - tr) / st, st > 1e-6);
            r.light += r.tr * (sc * lin + em) * w;
            r.tr *= tr;
        }
        if (end >= tmax) { break; }
        t = end;
    }
    return r;
}

// 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 (the homogeneous ones are what is left: `media_shadow`).
var<private> media_voxels: bool = false;
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). A_CUTOUT_EMITTERS: at a camera hit it asks an alpha-cutout's
// triangles of their maps (cutout.rs: a lattice of cells a triangle, each solid or a hole, made once from the
// texture's alpha), in the one query it is: no read of a triangle's corners, its material or its texture, and no
// second query past a hole (trace_hw.wgsl). A cutout without maps is opaque to it, as every cutout is to the rays of
// deeper vertices (`cutouts_opaque`). Offline rendering always tests the alpha.
// Until 2026-12-02 every cutout was opaque to these rays at camera hits too, the leaves of a tree blocking as whole
// cards: a bias accepted on 2026-11-09 for the Bistro crowd's 60 fps (the alpha tests of these rays were ~0.9 ms of
// its frame), measured then at ~1.7 % of the light under foliage at one pose. Beside the potted bushes and the hedge
// of Bistro's walk it was more: 0.78 and 0.71 of the offline render's light there (an M4 at half resolution), and
// by the maps 0.97 and 0.99, which is what the alpha test itself reads. The frame at the street's first view and
// over the walk: 15.5 and 16.8 ms as it was, 16.0 and 17.9 by the maps, 18.2 and 20.6 with the alpha tested, each
// hole then passed by a query of its own (Bistro's leaf cards are 2,200 texels across and three fifths hole).
fn emitter_tr(o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> f32 {
    shadow_hole = false;
    if (trace(o, d, tmax, select(TRACE_ANY, TRACE_ANY_OPAQUE, approx(A_CUTOUT_EMITTERS))).tri != 0xffffffffu) { return 0.0; }
    return media_shadow(o, d, tmax, rd);
}

// A shadow ray any surface stops (fog and volume points toward emitters).
fn any_tr(o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> f32 {
    shadow_hole = false;
    if (trace(o, d, tmax, TRACE_ANY).tri != 0xffffffffu) { return 0.0; }
    return media_shadow(o, d, tmax, rd);
}

// ------------------------------------------------------------------------------------------------
// Surface

struct Surface {
    p: vec3<f32>,
    ng: vec3<f32>,
    n: vec3<f32>,
    base: vec3<f32>,
    metallic: f32,
    roughness: f32,
    specular: f32,
    emissive: vec3<f32>,
    front: bool,
    card: bool,
    // Shading changes over time (animated emission, rain ripples): the live viewport keeps a short history here.
    anim: bool,
    // Glass (transmission share, index of refraction) and clearcoat (amount, perceptual roughness).
    transmission: f32,
    ior: f32,
    coat: f32,
    coat_rough: f32,
};

fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
    return select(pow((c + 0.055) / 1.055, vec3<f32>(2.4)), c / 12.92, c <= vec3<f32>(0.04045));
}

// Texture pages: `lod` is log2 of the ray footprint in texture-UV units; the mip level adds the texture's resolution.
fn tex_level(id: i32, uv: vec2<f32>, level: f32) -> vec4<f32> {
    let a = tex_info_at(u32(id) * 2u);
    let b = tex_info_at(u32(id) * 2u + 1u);
    let f = select(clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)), fract(uv), b.y > 0.5);
    return textureSampleLevel(textures, samp, a.xy + f * a.zw, i32(b.x), clamp(level, 0.0, TEX_MAX_LEVEL));
}

fn tex(id: i32, uv: vec2<f32>, lod: f32) -> vec4<f32> {
    let b = tex_info_at(u32(id) * 2u + 1u);
    return tex_level(id, uv, lod + 0.5 * log2(b.z * b.w));
}

fn mesh_uv(a: TriAttr, m: Material, u: f32, v: f32) -> vec2<f32> {
    let w = 1.0 - u - v;
    return (vec2<f32>(a.n0.w, a.n1.w) * w + vec2<f32>(a.n2.w, a.uv.x) * u + a.uv.yz * v) * m.uv.xy + m.uv2.xy;
}

// The square of a triangle's texel density (texture-UV units per metre, incl. material repeat) as the two it is the
// ratio of, from the triangle where it is hit: (its UV area x the repeat, its area), its edges e1, e2 as it stands in
// the world; (the repeat, 1) where one of the two has no size.
fn mesh_density(e1: vec3<f32>, e2: vec3<f32>, a: TriAttr, m: Material) -> vec2<f32> {
    let uv0 = vec2<f32>(a.n0.w, a.n1.w);
    let d1 = vec2<f32>(a.n2.w, a.uv.x) - uv0;
    let d2 = a.uv.yz - uv0;
    // (Twice each area: the halves cancel.)
    let uv_area = abs(d1.x * d2.y - d2.x * d1.y);
    let area = length(cross(e1, e2));
    let rep = max(abs(m.uv.x * m.uv.y), 1e-12);
    let sized = area > 2e-12 && uv_area > 2e-14;
    return vec2<f32>(select(rep, uv_area * rep, sized), select(1.0, area, sized));
}
// The level a texture is read at, less its own size's: half the log of the density times a footprint's square (m^2)
// over `over` (1: nothing more).
fn mesh_lod(density: vec2<f32>, footprint2: f32, over: f32) -> f32 { return 0.5 * log2(max(density.x * footprint2 / (density.y * over), 1e-30)); }

// ------------------------------------------------------------------------------------------------
// Material functions: scene-supplied WGSL (like a UE Custom-HLSL material), docs/MATERIAL_FUNCTIONS.md.
// Inputs in world space (metres, Y up); helpers convert to UE space (cm, Z up) for ported UE code.

struct MatIn {
    wp: vec3<f32>,   // world position, m
    n: vec3<f32>,    // vertex normal (facing the viewer)
    ng: vec3<f32>,   // geometric normal (facing the viewer)
    t: vec3<f32>,    // tangent (+u)
    b: vec3<f32>,    // bitangent (image up = -v)
    uv: vec2<f32>,   // mesh UV0 (image convention: v down)
    uvd: f32,        // log2(mesh UV units per metre): msample(..., exp2(i.uvd)) for mesh-UV lookups
    view: vec3<f32>, // unit vector toward the viewer / ray origin
    op: vec3<f32>,   // object pivot, m
    ob: vec3<f32>,   // object world bounds size, m
    time: f32,
    wetness: f32,
    rain: f32,
    lod: f32,        // log2 of the ray footprint, m
    depth: u32,      // path vertex (0 = camera hit)
    power: f32,      // instance power (UE "Power"): scale the emission by it
    near: bool,      // seen directly or in mirror-like reflections (puddles, glass): where fine detail shows
    custom: vec4<f32>, // per-instance data (UE PerInstanceCustomData): the object's `customData`, or its particle's
};

struct MatOut {
    base: vec3<f32>,
    roughness: f32,
    metallic: f32,
    specular: f32,
    emissive: vec3<f32>,
    normal: vec3<f32>, // world-space shading normal
    opacity: f32,      // alpha-tested against the material's alphaTest
    animated: bool,    // the shading here moves with time (live: short history, as for animated emission)
};

// Texture slot `slot` of the material function at `uv`, mip from the ray footprint and `uv_per_m` (uv units / m).
fn msample(m: Material, i: MatIn, slot: u32, uv: vec2<f32>, uv_per_m: f32) -> vec4<f32> {
    let id = m.mt[slot];
    if (id < 0) { return vec4<f32>(1.0); }
    return tex(id, uv, i.lod + log2(max(uv_per_m, 1e-9)) - LOD_BIAS);
}

// Colour texture (sRGB-encoded) -> linear rgb, alpha as stored.
fn msample_color(m: Material, i: MatIn, slot: u32, uv: vec2<f32>, uv_per_m: f32) -> vec4<f32> {
    let c = msample(m, i, slot, uv, uv_per_m);
    return vec4<f32>(srgb_to_linear(c.rgb), c.a);
}

// Tangent-space normal (x along +u, y image-up, z out) -> world.
fn tangent_normal(i: MatIn, tn: vec3<f32>) -> vec3<f32> {
    let w = i.t * tn.x + i.b * tn.y + i.n * tn.z;
    if (dot(w, w) < 1e-12) { return i.n; }
    let nn = normalize(w);
    return select(i.n, nn, dot(nn, i.ng) > 0.0);
}

// Unreal space: (X, Y, Z) cm, Z up = ours (x, z, y) * 100.
fn ue_pos(p: vec3<f32>) -> vec3<f32> { return vec3<f32>(p.x, p.z, p.y) * 100.0; }
fn ue_vec(v: vec3<f32>) -> vec3<f32> { return vec3<f32>(v.x, v.z, v.y); }
fn from_ue_vec(v: vec3<f32>) -> vec3<f32> { return vec3<f32>(v.x, v.z, v.y); }

// @material-functions-begin
fn material_function(f: i32, i: MatIn, m: Material, base: MatOut) -> MatOut { return base; }
fn translucent_material_function(f: i32, i: MatIn, m: Material, base: MatOut) -> MatOut { return base; }
fn alpha_material_function(f: i32, i: MatIn, m: Material, base: MatOut) -> MatOut { return base; }
fn emissive_material_function(f: i32, i: MatIn, m: Material, base: MatOut) -> MatOut { return base; }
// @material-functions-end

fn object_of(a: TriAttr) -> u32 { return bitcast<u32>(a.x.y); }
// vec4s per object (scene.rs OBJECT_STRIDE): (pivot, power), (bounds size, time of the last power edit), per-instance
// data (`MatIn.custom`).
override OBJECT_STRIDE: u32 = select(3u, 4u, (FEAT & F_TINT) != 0u);
// An instanced object's instance colour (three.js `instanceColor`), white for every other object.
fn obj_tint(oi: u32) -> vec3<f32> { return object_at(oi * OBJECT_STRIDE + 3u).rgb; }
// Instance power (UE material "Power", scripts animate it): scales the emission of everything the node draws.
fn obj_power(a: TriAttr) -> f32 { return object_at(object_of(a) * OBJECT_STRIDE).w; }

// Inputs at a point of triangle ti (barycentrics u, v) for material functions outside full shading (alpha, NEE).
// `inst`: the instance the triangle is placed by (as `surface` places it); `part`: as a hit's. (By F_IFUNC, not by
// F_INST: where no instanced mesh has a function the placement is not compiled in.)
fn mat_in_at(ti: u32, inst: u32, part: u32, u: f32, v: f32, view: vec3<f32>, lod: f32) -> MatIn {
    let td = tri_data(ti, inst, part);
    var a = td.a;
    var v0 = td.v0;
    var e1 = td.e1;
    var e2 = td.e2;
    var side = 1.0;
    if (has(F_IFUNC) && inst != NO_INST) {
        let r = instance_at(inst);
        v0 = inst_vec(r, v0) + vec3<f32>(r.m0.w, r.m1.w, r.m2.w);
        e1 = inst_vec(r, e1);
        e2 = inst_vec(r, e2);
        a = inst_attr(r, a);
        side = inst_sign(r);
    }
    let m = material_at(material_of(a, inst));
    let w = 1.0 - u - v;
    let p = v0 + e1 * u + e2 * v;
    let ng = normalize(cross(e1, e2)) * side;
    var n = normalize(a.n0.xyz * w + a.n1.xyz * u + a.n2.xyz * v);
    // (Its frame placed as its attributes are: by F_IFUNC.)
    var placed = NO_INST;
    if (has(F_IFUNC)) { placed = inst; }
    let tw = hit_tangent(td, placed, u, v);
    let t = normalize(tw.xyz - n * dot(n, tw.xyz) + vec3<f32>(1e-9));
    let oi = object_of(a);
    return MatIn(p, n, ng, t, cross(n, t) * tw.w, mesh_uv(a, m, u, v), mesh_lod(mesh_density(e1, e2, a, m), 1.0, 1.0), view, object_at(oi * OBJECT_STRIDE).xyz, object_at(oi * OBJECT_STRIDE + 1u).xyz,
                 P.time.x, P.time.y, P.time.z, lod, cur_depth, object_at(oi * OBJECT_STRIDE).w, cur_depth == 0u || mirror_path,
                 object_at(oi * OBJECT_STRIDE + 2u));
}

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);
}

// 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 approx(A_CUTOUT_PATHS) && cur_depth >= 1u && !mirror_path;
}

// A path stays mirror-like (`mirror_path`) through specular samples off surfaces smoother than this.
const MIRROR_ROUGHNESS: f32 = 0.3;

// Whether a cutout let the last shadow ray through (the shadow rays' functions clear it, `trace` sets it).
var<private> shadow_hole: bool = false;

// Set around a `direct_light` that no BSDF ray follows (where a path ends without the cache): its light samples
// take the whole of their light. Weighed against a BSDF ray that is never traced they kept their MIS share alone:
// of a uniform sky on a Lambert surface, ln 17 / 16 = 18 %.
var<private> nee_alone: bool = false;

// Which of a vertex's direct light `direct_light` takes: all of it; or, where a live frame's camera hit has the lights
// it resamples (one of many chosen, then its shadow ray: the emitters, and the local lights past those summed
// exactly, `local_lights`) in a pass of their own (`direct`), all but those (`main`: the directional lights, the
// local lights summed exactly, the sky) or those alone (the pass).
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<private> dl_part: u32 = 0u;

// `direct_light` without the sky: a surface seen in a reflection lights itself from the lights, the sky's light
// there is the radiance cache's.
var<private> lights_only: bool = false;

// Alpha-cutout test for candidate hits on masked triangles (mesh UVs, footprint of a camera ray at distance t). `inst`:
// the instance the triangle belongs to (it places the triangle's edges: its texel density); `part`: as a hit's.
fn alpha_pass(ti: u32, inst: u32, part: u32, u: f32, v: f32, t: f32) -> bool {
    let td = tri_data(ti, inst, part);
    let a = td.a;
    let m = material_at(material_of(a, inst));
    var alpha = m.base_color.a;
    if (has(F_TEX) && m.tex0.x >= 0) {
        var e1 = td.e1;
        var e2 = td.e2;
        if (has(F_INST) && inst != NO_INST) {
            let r = instance_at(inst);
            e1 = inst_vec(r, e1);
            e2 = inst_vec(r, e2);
        }
        let fp = max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7);
        let lod = mesh_lod(mesh_density(e1, e2, a, m), fp * fp, 1.0) - LOD_BIAS;
        alpha *= tex(m.tex0.x, mesh_uv(a, m, u, v), lod).a;
    }
    if (has(F_FUNC) && m.tex1.w > 0) {
        let i = mat_in_at(ti, inst, part, u, v, vec3<f32>(0.0, 1.0, 0.0), log2(max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7)));
        var b = mat_base(m);
        b.opacity = alpha;
        alpha = alpha_material_function(m.tex1.w - 1, i, m, b).opacity;
    }
    return alpha >= m.uv2.w;
}

// Emitted radiance at `uv`: factor x emissive map.
fn emission(m: Material, uv: vec2<f32>, lod: f32) -> vec3<f32> {
    var em = m.emissive.rgb;
    if (all(em <= vec3<f32>(0.0))) { return em; }
    if (has(F_TEX) && m.tex1.x >= 0) { em *= srgb_to_linear(tex(m.tex1.x, uv, lod).rgb); }
    return em;
}

// `width` = ray-cone footprint (m) at the hit, for texture LOD.
fn surface(o: vec3<f32>, d: vec3<f32>, h: Hit, width: f32) -> Surface {
    if (is_proc(h)) { return surface_proc(o, d, h, width); }
    let i = h.tri;
    let td = tri_data(i, h.inst, h.part);
    var e1 = td.e1;
    var e2 = td.e2;
    var a = td.a;
    var side = 1.0;
    if (has(F_INST) && h.inst != NO_INST) {
        let r = instance_at(h.inst);
        e1 = inst_vec(r, e1);
        e2 = inst_vec(r, e2);
        a = inst_attr(r, a);
        side = inst_sign(r);
    }
    let w = 1.0 - h.u - h.v;
    var ng = normalize(cross(e1, e2)) * side;
    var n = normalize(a.n0.xyz * w + a.n1.xyz * h.u + a.n2.xyz * h.v);
    let mi = material_of(a, h.inst);
    let m = material_at(mi);
    let front = dot(ng, d) < 0.0;
    if (!front) { ng = -ng; }
    if (dot(n, ng) < 0.0) { n = -n; }
    let p = o + d * h.t;

    let uv = mesh_uv(a, m, h.u, h.v);
    let density = mesh_density(e1, e2, a, m);
    let fp = max(width, 1e-7);
    let lod = mesh_lod(density, fp * fp, max(abs(dot(ng, d)), 1e-3)) - LOD_BIAS;

    var s: Surface;
    s.p = p;
    s.front = front;
    s.card = m.tex1.z == MAT_EMITTER_CARD;
    var base = m.base_color.rgb;
    if (has(F_TINT)) { base *= obj_tint(object_of(a)); }
    if (has(F_VCOLOR) && m.uv.w > 0.0) { base *= vcolor(i, h.u, h.v); }
    var rough = m.params.y;
    var metal = m.params.x;
    var spec = m.params.z;
    if (has(F_TEX)) {
        if (m.tex0.x >= 0) { base *= srgb_to_linear(tex(m.tex0.x, uv, lod).rgb); }
        if (m.tex0.z >= 0) { rough *= tex(m.tex0.z, uv, lod).g; }
        if (m.tex0.w >= 0) { metal *= tex(m.tex0.w, uv, lod).b; }
    }
    s.emissive = emission(m, uv, lod) * obj_power(a);
    // three.js MeshBasicMaterial: its colour to camera rays and mirror-like paths, lit by nothing, lighting nothing.
    if (has(F_UNLIT) && m.tex1.z == MAT_UNLIT) {
        s.emissive = select(vec3<f32>(0.0), base, cur_depth == 0u || mirror_path);
        base = vec3<f32>(0.0);
        spec = 0.0;
        metal = 0.0;
    }
    // Power just changed by a script / gameplay (objects[1].w = scene time of the edit): short history.
    s.anim = P.time.x - object_at(object_of(a) * OBJECT_STRIDE + 1u).w < 0.5;
    // Detail that only matters where it is seen directly or in mirror-like reflections (puddles, glass, chrome).
    let near = cur_depth == 0u || mirror_path;
    if (has(F_TEX) && m.tex0.y >= 0 && near) {
        let tn = tex(m.tex0.y, uv, lod).xyz * 2.0 - 1.0;
        let tw = hit_tangent(td, h.inst, h.u, h.v);
        let tp = tw.xyz - n * dot(n, tw.xyz);
        if (dot(tp, tp) > 1e-12) {
            let t = normalize(tp);
            let b = cross(n, t) * tw.w;
            let pn = t * (tn.x * m.params.w) + b * (tn.y * m.params.w) + n * tn.z;
            if (dot(pn, pn) > 1e-12 && dot(pn, ng) > 0.0) { n = normalize(pn); }
        }
    }
    if (has(F_FUNC) && m.tex1.w > 0) {
        let oi = object_of(a);
        let tw = hit_tangent(td, h.inst, h.u, h.v);
        var t = normalize(tw.xyz - n * dot(n, tw.xyz) + vec3<f32>(1e-9));
        let nv = normalize(a.n0.xyz * w + a.n1.xyz * h.u + a.n2.xyz * h.v) * select(-1.0, 1.0, front || dot(a.n0.xyz, ng) > 0.0);
        let i = MatIn(p, select(-nv, nv, dot(nv, ng) >= 0.0), ng, t, cross(n, t) * tw.w, mesh_uv(a, m, h.u, h.v), mesh_lod(density, 1.0, 1.0), -d,
                      object_at(oi * OBJECT_STRIDE).xyz, object_at(oi * OBJECT_STRIDE + 1u).xyz, P.time.x, P.time.y, P.time.z,
                      log2(max(width, 1e-7)) - 0.5 * log2(max(abs(dot(ng, d)), 1e-3)), cur_depth, object_at(oi * OBJECT_STRIDE).w, near,
                      object_at(oi * OBJECT_STRIDE + 2u));
        let r = material_function(m.tex1.w - 1, i, m, MatOut(base, rough, metal, spec, s.emissive, n, m.base_color.a, false));
        base = r.base;
        rough = r.roughness;
        metal = r.metallic;
        spec = r.specular;
        s.emissive = r.emissive;
        n = r.normal;
        // Shading the function says moves with time (wave normals) is as animated as emission is: short history.
        s.anim = s.anim || any(r.emissive > vec3<f32>(0.0)) || r.animated;
    }
    s.base = base;
    s.roughness = clamp(rough, 0.02, 1.0);
    s.metallic = clamp(metal, 0.0, 1.0);
    s.specular = spec;
    s.ng = ng;
    s.n = n;
    s.ior = 1.5;
    if (has(F_GLASS)) {
        s.transmission = clamp(m.layer.x, 0.0, 1.0);
        // glTF transmissionTexture (R), its index + 1 in uv.z.
        if (has(F_TEX) && m.uv.z > 0.5) { s.transmission *= tex(i32(m.uv.z) - 1, uv, lod).r; }
        s.ior = max(m.layer.y, 1.0001);
    }
    if (has(F_COAT)) {
        s.coat = clamp(m.layer.z, 0.0, 1.0);
        s.coat_rough = clamp(m.layer.w, 0.02, 1.0);
    }
    return s;
}

// A procedural hit's surface: the material its geometry function picked, the normal it gave (geometric and shading,
// two-sided), the object's power and customData. No textures (no uv: material functions get uv 0 and can work from
// `i.wp`), no transmission.
fn surface_proc(o: vec3<f32>, d: vec3<f32>, h: Hit, width: f32) -> Surface {
    let r = instance_at(h.inst);
    let hd = r.info.x;
    let mi = pword(pword(hd + 7u) + min((h.tri >> 23u) & 0xffu, pword(hd + 3u) - 1u));
    let m = material_at(mi);
    let oi = r.info.y;
    var ng = proc_normal(h);
    let front = dot(ng, d) < 0.0;
    if (!front) { ng = -ng; }
    var n = ng;
    let p = o + d * h.t;
    var s: Surface;
    s.p = p;
    s.front = front;
    s.card = false;
    var base = m.base_color.rgb;
    if (has(F_TINT)) { base *= obj_tint(oi); }
    var rough = m.params.y;
    var metal = m.params.x;
    var spec = m.params.z;
    s.emissive = m.emissive.rgb * object_at(oi * OBJECT_STRIDE).w;
    s.anim = P.time.x - object_at(oi * OBJECT_STRIDE + 1u).w < 0.5;
    if (has(F_FUNC) && m.tex1.w > 0) {
        let near = cur_depth == 0u || mirror_path;
        let a = select(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 1.0, 0.0), abs(n.x) > 0.9);
        let t = normalize(cross(a, n));
        let i = MatIn(p, n, ng, t, cross(n, t), proc_attr(h), 0.0, -d, object_at(oi * OBJECT_STRIDE).xyz, object_at(oi * OBJECT_STRIDE + 1u).xyz,
                      P.time.x, P.time.y, P.time.z, log2(max(width, 1e-7)) - 0.5 * log2(max(abs(dot(ng, d)), 1e-3)), cur_depth,
                      object_at(oi * OBJECT_STRIDE).w, near, object_at(oi * OBJECT_STRIDE + 2u));
        let f = material_function(m.tex1.w - 1, i, m, MatOut(base, rough, metal, spec, s.emissive, n, m.base_color.a, false));
        base = f.base;
        rough = f.roughness;
        metal = f.metallic;
        spec = f.specular;
        s.emissive = f.emissive;
        n = f.normal;
        s.anim = s.anim || any(f.emissive > vec3<f32>(0.0)) || f.animated;
    }
    s.base = base;
    s.roughness = clamp(rough, 0.02, 1.0);
    s.metallic = clamp(metal, 0.0, 1.0);
    s.specular = spec;
    s.ng = ng;
    s.n = n;
    s.ior = 1.5;
    if (has(F_COAT)) {
        s.coat = clamp(m.layer.z, 0.0, 1.0);
        s.coat_rough = clamp(m.layer.w, 0.02, 1.0);
    }
    return s;
}

// ------------------------------------------------------------------------------------------------
// BSDF

// The specular lobe's directional albedo at a roughness and cos(view), as the two terms of the split sum (Karis,
// "Real Shading in Unreal Engine 4", SIGGRAPH 2013 course notes, "Environment BRDF"; with f90: Lagarde & de Rousiers
// 2014, eq. 58): with Schlick's Fresnel the lobe (`d_ggx` x `vis_smith_joint_approx`, single scattering) reflects
// f0 x .x + f90 x .y of a uniform surround, .x + .y at F = 1.
// From the table lib.rs `energy_lut` computes (`specular_albedo`): ENERGY_N x ENERGY_N nodes over sqrt(cos(view))
// (along a row) and the roughness, two nodes a vec4 (32 x 32 over sqrt(cos) and sqrt(alpha): the tables' shape of
// Kulla & Conty 2017 and Turquin 2019, section 3.1.1); between the nodes, bilinear.
const ENERGY_N: u32 = 32u;
fn energy_node(i: u32) -> vec2<f32> {
    let v = energy_at(i >> 1u);
    return select(v.xy, v.zw, (i & 1u) == 1u);
}
fn energy_lookup(roughness: f32, nov: f32) -> vec2<f32> {
    let x = sqrt(clamp(nov, 0.0, 1.0)) * f32(ENERGY_N - 1u);
    let y = clamp(roughness, 0.0, 1.0) * f32(ENERGY_N - 1u);
    let x0 = min(u32(x), ENERGY_N - 2u);
    let y0 = min(u32(y), ENERGY_N - 2u);
    let i = y0 * ENERGY_N + x0;
    let fx = x - f32(x0);
    return mix(mix(energy_node(i), energy_node(i + 1u), fx), mix(energy_node(i + ENERGY_N), energy_node(i + ENERGY_N + 1u), fx), y - f32(y0));
}

// The specular lobe's Fresnel and energy terms for a reflectance at normal incidence `f0`, from the lobe's albedo terms
// `e` (`energy_lookup`).
// f90, the reflectance at grazing incidence: 1, fading to 0 as f0 falls below 2 %, less than any real material has, so
// that a material can switch its specular off: saturate(50 x the mean of f0) (Lagarde & de Rousiers, "Moving Frostbite
// to Physically Based Rendering", SIGGRAPH 2014 course notes, section 4.10.3, Listing 27, after Schuler, "An Efficient
// and Physically Plausible Real-Time Shading Model", ShaderX7; Filament's documentation, "Specular occlusion").
// w, the lobe's scale for the light that leaves the microsurface after more than one bounce, which the single-
// scattering lobe lacks: 1 + f0 (1 - E) / E, E = e.x + e.y the lobe's albedo at F = 1 (Turquin, "Practical multiple
// scattering compensation for microfacet models", 2019, eq. 16; the energy to return: Kulla & Conty, "Revisiting
// Physically Based Shading at Imageworks", SIGGRAPH 2017 course; Filament's documentation, "Energy loss in specular
// reflectance"). `comp` (P.misc.z) of it: at 0 the lobe is single scattering, at 1 a white (f0 = 1) lobe reflects all
// it receives (the white furnace test).
// e, the lobe's directional albedo with both: (f0 e.x + f90 e.y) w.
struct SpecTerms { f90: f32, w: vec3<f32>, e: vec3<f32> };
fn spec_terms(f0: vec3<f32>, e: vec2<f32>, comp: f32) -> SpecTerms {
    let f90 = clamp(dot(f0, vec3<f32>(50.0 / 3.0)), 0.0, 1.0);
    let w = 1.0 + f0 * (comp * (1.0 / max(e.x + e.y, 1e-3) - 1.0));
    return SpecTerms(f90, w, (f0 * e.x + f90 * e.y) * w);
}

// Base layer: diffuse + GGX specular (e_spec: the specular's directional albedo; kd: what it leaves the diffuse
// under it; p_spec: the specular share of the base's samples). Over it a clearcoat (GGX, F0 0.04; the base gets what
// the coat's directional albedo e_coat lets through). Glass: a share of the base is a dielectric interface (below,
// "The dielectric"), the rest keeps the diffuse and the specular. p_coat / p_trans: the coat's and the dielectric's
// shares of all samples.
struct Lobes {
    diffuse: vec3<f32>, f0: vec3<f32>, f90: vec3<f32>, w: vec3<f32>, e_spec: vec3<f32>, kd: vec3<f32>, a2: f32, p_spec: f32,
    coat: f32, coat_alpha: f32, e_coat: f32, p_coat: f32, tint: vec3<f32>, p_trans: f32,
    // The dielectric: its share of the base under the coat x its energy compensation (reflection's factor), `tint`
    // the same x the base colour (transmission's); n(far side) / n(view side); whether its transmission has a density;
    // its directional reflection albedo (before the coat).
    t: f32, eta: f32, rough_t: bool, e_glass: f32,
};

// ------------------------------------------------------------------------------------------------
// The dielectric (glass): a rough interface between two indices of refraction, Walter et al. 2007 (GGX): light
// reflects off a microfacet or refracts through it by the Fresnel reflectance there, exact (total internal
// reflection is reflection, untinted). Both have a value and a density, so lights are sampled through frosted glass
// and weighed against the BSDF's rays. Below GLASS_DELTA its transmission is a delta lobe (a clear pane: what lies
// behind is seen straight, `through` in the path loop); its reflection keeps the microfacet lobe. Single scattering
// loses energy as the roughness grows (leaving glass at 0.6: a quarter); the whole is scaled by 1 / (R + T) from a
// table (Turquin 2019, as Cycles), P.misc.z of it.
// Not here: the radiance scaling by the indices' ratio squared (as Cycles and glTF's formula: it cancels over a
// closed solid, and a single-sheet pane, which refracts as a solid here, would be scaled once); thin walls;
// absorption by distance.
// Smoother than this a reflection or refraction is sharp enough that an emitter seen through it needs no denoising
// (`delta_path`; a polished floor's 0.035 still spreads it over pixels).
const DELTA_ROUGHNESS: f32 = 0.025;
const GLASS_DELTA: f32 = 0.05; // roughness (RTXPT 0.04, Falcor 0.08)

// Unpolarised Fresnel reflectance: `c` the cosine on the incident side, `eta` = n(far) / n(incident); 1 at total
// internal reflection (Walter eq. 22).
fn fresnel_dielectric(c: f32, eta: f32) -> f32 {
    let g2 = eta * eta - 1.0 + c * c;
    if (g2 <= 0.0) { return 1.0; }
    let g = sqrt(g2);
    let a = (g - c) / (g + c);
    let b = (c * (g + c) - 1.0) / (c * (g - c) + 1.0);
    return 0.5 * a * a * (1.0 + b * b);
}

// Smith's Lambda (GGX) at |cosine| c: g1 = 1 / (1 + Lambda).
fn lambda_ggx(a2: f32, c: f32) -> f32 {
    let c2 = c * c;
    return 0.5 * (sqrt(1.0 + a2 * (1.0 - c2) / max(c2, 1e-8)) - 1.0);
}

// The glass energy table (lib.rs `glass_energy_lut`, `GLASS_E`): R + T of the interface at GLASS_E_MU nodes over
// sqrt(cos), GLASS_E_ROUGH over the roughness, GLASS_E_IOR over sqrt((ior - 1) / (ior + 1)) up to GLASS_E_ZMAX
// (ior 3); entering, then leaving.
const GLASS_E_MU: u32 = 16u;
const GLASS_E_ROUGH: u32 = 16u;
const GLASS_E_IOR: u32 = 8u;
const GLASS_E_ZMAX: f32 = 0.70710678;
// (A select chain: the vec4 indexed by a variable cost the glass scene's trace 1.5 %.)
fn glass_e_at(i: u32) -> f32 {
    let v = glass_energy_at(i / 4u);
    let k = i & 3u;
    return select(select(v.x, v.y, k == 1u), select(v.z, v.w, k == 3u), k >= 2u);
}
// One (roughness, ior, side) row of it at x, between the nodes.
fn glass_e_row(row: u32, x: f32) -> f32 {
    let x0 = u32(x);
    return mix(glass_e_at(row * GLASS_E_MU + x0), glass_e_at(row * GLASS_E_MU + min(x0 + 1u, GLASS_E_MU - 1u)), x - f32(x0));
}
fn glass_energy(nov: f32, roughness: f32, ior: f32, leaving: bool) -> f32 {
    let x = clamp(sqrt(nov), 0.0, 1.0) * f32(GLASS_E_MU - 1u);
    let y = clamp(roughness, 0.0, 1.0) * f32(GLASS_E_ROUGH - 1u);
    let z = clamp(sqrt(max(ior - 1.0, 0.0) / (ior + 1.0)) / GLASS_E_ZMAX, 0.0, 1.0) * f32(GLASS_E_IOR - 1u);
    let y0 = u32(y);
    let y1 = min(y0 + 1u, GLASS_E_ROUGH - 1u);
    let z0 = select(0u, GLASS_E_IOR, leaving) + u32(z);
    let z1 = select(0u, GLASS_E_IOR, leaving) + min(u32(z) + 1u, GLASS_E_IOR - 1u);
    let e0 = mix(glass_e_row(z0 * GLASS_E_ROUGH + y0, x), glass_e_row(z0 * GLASS_E_ROUGH + y1, x), y - f32(y0));
    let e1 = mix(glass_e_row(z1 * GLASS_E_ROUGH + y0, x), glass_e_row(z1 * GLASS_E_ROUGH + y1, x), y - f32(y0));
    return mix(e0, e1, z - floor(z));
}

// Whether lights on both sides of the surface reach it: rough glass.
fn two_sided(lb: Lobes) -> bool { return has(F_GLASS) && lb.rough_t; }

// The dielectric's transmission toward l (the far side; nov, nol: |cosines|) x |n.l|: Walter eq. 21 from the view
// side. `h` = the microfacet normal that refracts v to l, on the shading normal's side.
fn dielectric_t(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>, nov: f32, nol: f32) -> vec3<f32> {
    if (!lb.rough_t) { return vec3<f32>(0.0); }
    var h = normalize(v + lb.eta * l);
    if (dot(h, s.n) < 0.0) { h = -h; }
    let voh = dot(v, h);
    let loh = dot(l, h);
    if (voh <= 0.0 || loh >= 0.0) { return vec3<f32>(0.0); }
    let den = voh + lb.eta * loh;
    let g2 = 1.0 / (1.0 + lambda_ggx(lb.a2, nov) + lambda_ggx(lb.a2, nol));
    return lb.tint * ((1.0 - fresnel_dielectric(voh, lb.eta)) * d_ggx(lb.a2, max(dot(s.n, h), 0.0)) * g2 * voh * lb.eta * lb.eta * -loh / (nov * max(den * den, 1e-12)));
}

// Density of l under the dielectric's sampling (`sample_bsdf`: a visible microfacet normal, the ray reflected or
// refracted by the Fresnel reflectance there; at the shading normal's for smooth glass), x its share of the samples.
fn pdf_dielectric(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> f32 {
    let nov = max(dot(s.n, v), 1e-4);
    if (dot(s.n, l) > 0.0) {
        let h = normalize(v + l);
        let voh = max(dot(v, h), 1e-6);
        let f = fresnel_dielectric(select(nov, voh, lb.rough_t), lb.eta);
        return lb.p_trans * f * g1(lb.a2, nov) * d_ggx(lb.a2, max(dot(s.n, h), 0.0)) / (4.0 * nov);
    }
    if (!lb.rough_t) { return 0.0; }
    var h = normalize(v + lb.eta * l);
    if (dot(h, s.n) < 0.0) { h = -h; }
    let voh = dot(v, h);
    let loh = dot(l, h);
    if (voh <= 0.0 || loh >= 0.0) { return 0.0; }
    let den = voh + lb.eta * loh;
    return lb.p_trans * (1.0 - fresnel_dielectric(voh, lb.eta)) * g1(lb.a2, nov) * voh * d_ggx(lb.a2, max(dot(s.n, h), 0.0)) * lb.eta * lb.eta * -loh / (nov * max(den * den, 1e-12));
}

fn lobes(s: Surface, nov: f32) -> Lobes {
    var l: Lobes;
    let t = s.transmission * (1.0 - s.metallic);
    l.diffuse = s.base * (1.0 - s.metallic) * (1.0 - t);
    // The dielectric's reflectance at normal incidence: `specular` 0..1 is 0..8 % (Burley, "Physically-Based Shading at
    // Disney", SIGGRAPH 2012 course notes, section 5.4: 0.5 is the 4 % of common dielectrics, ior 1.5).
    var f0 = 0.08 * s.specular;
    if (t > 0.0) {
        // Glass: F0 from the index of refraction.
        let r = (s.ior - 1.0) / (s.ior + 1.0);
        f0 = r * r;
    }
    l.f0 = mix(vec3<f32>(f0), s.base, s.metallic);
    // The specular lobe's grazing reflectance, its multiple-scattering scale (P.misc.z of it) and its directional
    // albedo (`spec_terms`); the diffuse under it gets what the lobe does not reflect toward the view, 1 - E_spec
    // (the specular's missing energy modulates the diffuse: Kulla & Conty 2017, "Microfacet Dielectrics - Diffuse
    // Term"; here by the view's albedo alone, not theirs of both directions).
    let st = spec_terms(l.f0, energy_lookup(s.roughness, nov), P.misc.z);
    l.f90 = vec3<f32>(st.f90);
    l.w = st.w;
    l.e_spec = st.e;
    l.kd = 1.0 - l.e_spec;
    if (has(F_GLASS) && t > 0.0) {
        // The share that is not the dielectric keeps this specular lobe (the diffuse, 1 - t of it already, under it).
        l.w *= 1.0 - t;
        l.e_spec *= 1.0 - t;
    }
    let r = s.roughness;
    l.a2 = r * r * r * r;
    let ws = dot(l.e_spec, vec3<f32>(0.3, 0.6, 0.1));
    let wd = dot(l.diffuse * l.kd, vec3<f32>(0.3, 0.6, 0.1));
    l.p_spec = clamp(ws / max(ws + wd, 1e-6), 0.05, 1.0);
    if (wd <= 0.0) { l.p_spec = 1.0; }
    l.coat_alpha = 1.0;
    if (has(F_COAT) && s.coat > 0.0) {
        l.coat = s.coat;
        // The coat's directional albedo: a single-scattering lobe of F0 0.04 (ior 1.5), F90 1, at its own roughness.
        let ec = energy_lookup(s.coat_rough, nov);
        l.e_coat = s.coat * (0.04 * ec.x + ec.y);
        l.coat_alpha = s.coat_rough * s.coat_rough;
    }
    let under = 1.0 - l.e_coat;
    var wt = 0.0;
    if (has(F_GLASS) && t > 0.0) {
        l.eta = select(1.0 / s.ior, s.ior, s.front);
        l.rough_t = s.roughness > GLASS_DELTA && abs(s.ior - 1.0) > 1e-3;
        var comp = 1.0;
        if (l.rough_t) { comp = mix(1.0, 1.0 / glass_energy(nov, s.roughness, s.ior, !s.front), P.misc.z); }
        l.t = t * under * comp;
        l.tint = s.base * l.t;
        l.e_glass = t * fresnel_dielectric(nov, l.eta);
        wt = under * (l.e_glass + (t - l.e_glass) * dot(s.base, vec3<f32>(0.3, 0.6, 0.1)));
    }
    let total = (ws + wd) * under + l.e_coat + wt;
    l.p_coat = l.e_coat / max(total, 1e-6);
    l.p_trans = wt / max(total, 1e-6);
    return l;
}

// The microfacet terms of the specular lobes (a2 = alpha^2, alpha = roughness^2: Burley 2012).
// The GGX (Trowbridge-Reitz) distribution of microfacet normals: Walter et al., "Microfacet Models for Refraction
// through Rough Surfaces", EGSR 2007, eq. 33, written over cos(theta_h): a2 / (pi ((n.h)^2 (a2 - 1) + 1)^2), the
// denominator arranged as in Lagarde & de Rousiers 2014, Listing 2 (`D_GGX`). (In f32 a mirror's a2, 1.6e-7 at the
// roughness floor of 0.02, is a few steps of n.h below 1: light samples see such a lobe coarsely whatever the
// arrangement; BSDF samples divide by the same D.)
fn d_ggx(a2: f32, noh: f32) -> f32 {
    let d = (noh * a2 - noh) * noh + 1.0;
    return a2 / (PI * d * d);
}

// The visibility V = G2 / (4 n.v n.l) of the height-correlated Smith masking-shadowing for GGX (Heitz, "Understanding
// the Masking-Shadowing Function in Microfacet-Based BRDFs", JCGT 2014: G2 = 1 / (1 + Lambda(v) + Lambda(l)), which is
// V = 0.5 / (n.l sqrt(a2 + (1 - a2) (n.v)^2) + n.v sqrt(a2 + (1 - a2) (n.l)^2))), with each square root
// sqrt(a2 + (1 - a2) c^2) replaced by alpha + (1 - alpha) c, exact at c = 0, c = 1, alpha = 0 and alpha = 1: the
// denominator becomes a blend of 2 n.l n.v and n.l + n.v by alpha (Hammon, "PBR Diffuse Lighting for GGX+Smith
// Microsurfaces", GDC 2017; Filament, `V_SmithGGXCorrelated_Fast`, Apache-2.0,
// https://github.com/google/filament/blob/main/shaders/src/surface_brdf.fs). No square root over the directions; the
// one here turns the lobes' a2 back into alpha. (lib.rs `specular_albedo` and `glass_energy` integrate this form.)
fn vis_smith_joint_approx(a2: f32, nov: f32, nol: f32) -> f32 {
    return 0.5 / max(mix(2.0 * nol * nov, nol + nov, sqrt(a2)), 1e-7);
}

// Fresnel reflectance by Schlick's approximation ("An Inexpensive BRDF Model for Physically-based Rendering", 1994)
// with a reflectance at grazing incidence: f0 + (f90 - f0) (1 - v.h)^5.
fn f_schlick(f0: vec3<f32>, f90: vec3<f32>, voh: f32) -> vec3<f32> {
    let c = 1.0 - voh;
    let c2 = c * c;
    return f0 + (f90 - f0) * (c2 * c2 * c);
}

// BSDF * NoL with the specular lobe scaled (per-light specular scale)
fn eval_bsdf_k(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>, k: f32) -> vec3<f32> {
    let nol = dot(s.n, l);
    let nov = max(dot(s.n, v), 1e-4);
    if (two_sided(lb) && nol < 0.0 && dot(s.ng, l) < 0.0) {
        split_frac = vec3<f32>(1.0);
        return dielectric_t(s, lb, v, l, nov, -nol);
    }
    if (nol <= 0.0 || dot(s.ng, l) <= 0.0) { return vec3<f32>(0.0); }
    let h = normalize(v + l);
    let noh = max(dot(s.n, h), 0.0);
    let voh = max(dot(v, h), 0.0);
    let dv = d_ggx(lb.a2, noh) * vis_smith_joint_approx(lb.a2, nov, nol);
    var spec = dv * f_schlick(lb.f0, lb.f90, voh) * lb.w * k;
    // (The dielectric's reflection: lb.t holds the coat's share already, so it joins after the coat's layering.)
    var glass = 0.0;
    if (has(F_GLASS) && lb.t > 0.0) { glass = lb.t * fresnel_dielectric(voh, lb.eta) * dv * k; }
    var diff = lb.diffuse * (1.0 / PI) * lb.kd;
    if (has(F_COAT) && lb.coat > 0.0) {
        let ca2 = lb.coat_alpha * lb.coat_alpha;
        let coat = d_ggx(ca2, noh) * vis_smith_joint_approx(ca2, nov, nol) * f_schlick(vec3<f32>(0.04), vec3<f32>(1.0), voh).x * lb.coat * k;
        diff *= 1.0 - lb.e_coat;
        spec = spec * (1.0 - lb.e_coat) + vec3<f32>(coat);
    }
    spec += vec3<f32>(glass);
    split_frac = spec / max(diff + spec, vec3<f32>(1e-12));
    return (diff + spec) * nol;
}

// BSDF * NoL
fn eval_bsdf(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> vec3<f32> {
    return eval_bsdf_k(s, lb, v, l, 1.0);
}

fn g1(a2: f32, nov: f32) -> f32 {
    return 2.0 * nov / (nov + sqrt(a2 + (1.0 - a2) * nov * nov));
}

fn pdf_bsdf(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> f32 {
    let nol = dot(s.n, l);
    var pg = 0.0;
    if (has(F_GLASS) && lb.p_trans > 0.0) { pg = pdf_dielectric(s, lb, v, l); }
    if (nol <= 0.0) { return pg; }
    let nov = max(dot(s.n, v), 1e-4);
    let h = normalize(v + l);
    let noh = max(dot(s.n, h), 0.0);
    let voh = max(dot(v, h), 1e-6);
    let dv = g1(lb.a2, nov) * voh * d_ggx(lb.a2, noh) / nov;
    let ps = dv / (4.0 * voh);
    let pd = nol / PI;
    var pc = 0.0;
    if (has(F_COAT) && lb.coat > 0.0) {
        let ca2 = lb.coat_alpha * lb.coat_alpha;
        pc = g1(ca2, nov) * d_ggx(ca2, noh) / (4.0 * nov);
    }
    // (Smooth glass's transmission is a delta lobe, without a density: its samples only lower the others' share.)
    return pg + lb.p_coat * pc + (1.0 - lb.p_coat - lb.p_trans) * (lb.p_spec * ps + (1.0 - lb.p_spec) * pd);
}

// MIS weight of a light sample (solid-angle pdf `pdf_l`) against BSDF sampling. A_CUTOUT_PATHS: light that reached
// the sample through a cutout (`shadow_hole`) is light this vertex's BSDF ray cannot bring, a cutout being opaque to
// it, unless it is a specular or coat sample that keeps the path mirror-like (`mirror_path`). The sample takes the
// BSDF ray's weight for the rest: 1 - (the share of pdf_bsdf that still tests cutouts) x (the BSDF ray's weight).
// (Until 2026-11-15 the weight was the plain heuristic: under a card cut out everywhere a uniform sky lit a Lambert
// plane with 18 % of its light.)
fn light_mis(pdf_l: f32, s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> f32 {
    if (nee_alone) { return 1.0; }
    let pb = pdf_bsdf(s, lb, v, l);
    let w = power_heuristic(pdf_l, pb);
    if (!approx(A_CUTOUT_PATHS) || !has(F_MASKED) || !shadow_hole) { return w; }
    var see = 0.0;
    if ((cur_depth == 0u || mirror_path) && s.roughness < MIRROR_ROUGHNESS && pb > 0.0) {
        // pdf_bsdf's specular and coat terms.
        let nov = max(dot(s.n, v), 1e-4);
        let h = normalize(v + l);
        let noh = max(dot(s.n, h), 0.0);
        var p = (1.0 - lb.p_coat - lb.p_trans) * lb.p_spec * g1(lb.a2, nov) * d_ggx(lb.a2, noh) / (4.0 * nov);
        if (has(F_COAT) && lb.coat > 0.0) {
            let ca2 = lb.coat_alpha * lb.coat_alpha;
            p += lb.p_coat * g1(ca2, nov) * d_ggx(ca2, noh) / (4.0 * nov);
        }
        if (has(F_GLASS) && lb.p_trans > 0.0) { p += pdf_dielectric(s, lb, v, l); }
        see = min(p / pb, 1.0);
    }
    return 1.0 - see * (1.0 - w);
}

fn basis(n: vec3<f32>) -> mat3x3<f32> {
    let sgn = select(-1.0, 1.0, n.z >= 0.0);
    let a = -1.0 / (sgn + n.z);
    let b = n.x * n.y * a;
    let t = vec3<f32>(1.0 + sgn * n.x * n.x * a, sgn * b, -sgn * n.x);
    let bt = vec3<f32>(b, sgn + n.y * n.y * a, -n.y);
    return mat3x3<f32>(t, bt, n);
}

// Heitz 2018 VNDF sampling (isotropic), returns world-space half vector.
fn sample_vndf(v: vec3<f32>, tbn: mat3x3<f32>, alpha: f32, u1: f32, u2: f32) -> vec3<f32> {
    let vl = transpose(tbn) * v;
    let vh = normalize(vec3<f32>(alpha * vl.x, alpha * vl.y, vl.z));
    let lensq = vh.x * vh.x + vh.y * vh.y;
    let t1 = select(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(-vh.y, vh.x, 0.0) / sqrt(lensq), lensq > 0.0);
    let t2 = cross(vh, t1);
    let r = sqrt(u1);
    let phi = 2.0 * PI * u2;
    let p1 = r * cos(phi);
    var p2 = r * sin(phi);
    let s = 0.5 * (1.0 + vh.z);
    p2 = (1.0 - s) * sqrt(1.0 - p1 * p1) + s * p2;
    let nh = p1 * t1 + p2 * t2 + sqrt(max(0.0, 1.0 - p1 * p1 - p2 * p2)) * vh;
    let hl = normalize(vec3<f32>(alpha * nh.x, alpha * nh.y, max(0.0, nh.z)));
    return tbn * hl;
}

// A direction by the BSDF's lobes (`pdf_bsdf` its density; which lobe: sampled_spec, sampled_trans). The zero vector:
// no sample (every value and density of it is 0).
fn sample_bsdf(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
    let tbn = basis(s.n);
    let r = rng4(rng_dim(D_BSDF));
    sampled_trans = false;
    if (has(F_COAT) || has(F_GLASS)) {
        let u = r.x;
        if (u < lb.p_coat) {
            sampled_spec = true;
            return reflect(-v, sample_vndf(v, tbn, lb.coat_alpha, r.z, r.w));
        }
        if (u < lb.p_coat + lb.p_trans) {
            // The dielectric: a visible microfacet normal; reflected off it, or refracted through it (smooth glass:
            // through the shading normal), by the Fresnel reflectance there.
            let h = sample_vndf(v, tbn, s.roughness * s.roughness, r.z, r.w);
            var m = s.n;
            if (lb.rough_t) { m = h; }
            let t = refract(-v, m, 1.0 / lb.eta);
            sampled_spec = u - lb.p_coat < fresnel_dielectric(max(dot(v, m), 1e-4), lb.eta) * lb.p_trans || all(t == vec3<f32>(0.0));
            // A ray reflected under the surface, or refracted and still above it, is one the microfacets' masking
            // stops: no sample.
            if (sampled_spec) {
                let rl = reflect(-v, h);
                return select(rl, vec3<f32>(0.0), dot(rl, s.n) <= 0.0);
            }
            sampled_trans = true;
            return select(t, vec3<f32>(0.0), dot(t, s.n) >= 0.0);
        }
    }
    sampled_spec = r.y < lb.p_spec;
    if (sampled_spec) {
        let h = sample_vndf(v, tbn, s.roughness * s.roughness, r.z, r.w);
        return reflect(-v, h);
    }
    let rr = sqrt(r.z);
    let phi = 2.0 * PI * r.w;
    return tbn * vec3<f32>(rr * cos(phi), rr * sin(phi), sqrt(max(0.0, 1.0 - rr * rr)));
}

// ------------------------------------------------------------------------------------------------
// Environment

fn env_uv(d: vec3<f32>) -> vec2<f32> {
    let u = atan2(d.x, -d.z) / (2.0 * PI) + 0.5;
    let v = acos(clamp(d.y, -1.0, 1.0)) / PI;
    return vec2<f32>(u, v);
}

fn env_radiance(d: vec3<f32>) -> vec3<f32> {
    if (P.env.x < 0.5) { return P.sky_color.rgb; }
    return textureSampleLevel(env_tex, samp, env_uv(d), 0.0).rgb;
}

fn env_pdf(d: vec3<f32>) -> f32 {
    if (P.env.x < 0.5) { return 1.0 / (4.0 * PI); }
    let w = u32(P.env.y); let h = u32(P.env.z);
    let uv = env_uv(d);
    let x = min(u32(uv.x * f32(w)), w - 1u);
    let y = min(u32(uv.y * f32(h)), h - 1u);
    @if(!strict) let row_p = env_cdf_at(y) - select(0.0, env_cdf_at(y - 1u), y > 0u);
    @if(strict) let row_p = env_cdf_at(y) - select(0.0, env_cdf_at(max(y, 1u) - 1u), y > 0u);
    let base = h + y * w;
    @if(!strict) let col_p = env_cdf_at(base + x) - select(0.0, env_cdf_at(base + x - 1u), x > 0u);
    @if(strict) let col_p = env_cdf_at(base + x) - select(0.0, env_cdf_at(base + max(x, 1u) - 1u), x > 0u);
    let sin_t = sin((f32(y) + 0.5) / f32(h) * PI);
    return row_p * col_p * f32(w) * f32(h) / (2.0 * PI * PI * max(sin_t, 1e-4));
}

fn lower_bound(start: u32, count: u32, x: f32) -> u32 {
    var lo = 0u;
    var hi = count;
    while (lo < hi) {
        let mid = (lo + hi) / 2u;
        if (env_cdf_at(start + mid) < x) { lo = mid + 1u; } else { hi = mid; }
    }
    return min(lo, count - 1u);
}

fn sample_env(rd: u32) -> vec3<f32> {
    let u4 = rng4(rd);
    if (P.env.x < 0.5) {
        let z = 1.0 - 2.0 * u4.x;
        let r = sqrt(max(0.0, 1.0 - z * z));
        let phi = 2.0 * PI * u4.y;
        return vec3<f32>(r * cos(phi), z, r * sin(phi));
    }
    let w = u32(P.env.y); let h = u32(P.env.z);
    let y = lower_bound(0u, h, u4.x);
    let x = lower_bound(h + y * w, w, u4.y);
    let u = (f32(x) + u4.z) / f32(w);
    let v = (f32(y) + u4.w) / f32(h);
    let theta = v * PI;
    let phi = (u - 0.5) * 2.0 * PI;
    return vec3<f32>(sin(theta) * sin(phi), cos(theta), -sin(theta) * cos(phi));
}

fn power_heuristic(a: f32, b: f32) -> f32 {
    let a2 = a * a;
    return a2 / max(a2 + b * b, 1e-20);
}

fn non_finite(v: vec3<f32>) -> bool {
    let b = bitcast<vec3<u32>>(v) & vec3<u32>(0x7fffffffu);
    return any(b >= vec3<u32>(0x7f800000u));
}

fn luminance(c: vec3<f32>) -> f32 {
    return dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
}

fn offset_origin(p: vec3<f32>, n: vec3<f32>) -> vec3<f32> {
    return p + n * (1e-4 * max(1.0, max(abs(p.x), max(abs(p.y), abs(p.z)))));
}

// What a BSDF-sampled ray (solid-angle pdf `pdf`; 0 = the camera ray, no MIS) that left the scene brings back: the
// environment and the directional lights' disks, MIS-weighted against their sampling in `direct_light`.
fn sky_mis(d: vec3<f32>, pdf: f32) -> vec3<f32> {
    // three.js scene.background: what camera rays (and paths bent straight through glass) see where nothing is.
    if (has(F_BACKGROUND) && pdf <= 0.0) { return P.background.rgb; }
    var wgt = 1.0;
    if (pdf > 0.0 && P.counts2.y != 0u) {
        wgt = power_heuristic(pdf, env_pdf(d));
    }
    var c = env_radiance(d) * wgt;
    // (On a planet the camera sees the bake itself: space, the limb, black below the dipped horizon.)
    if (has(F_AERIAL) && pdf <= 0.0 && P.aerial.w <= 0.0) { c = aerial_light(d); }
    if (pdf > 0.0) { c += sun_disks(d, pdf); }
    return c;
}

// The directional lights' disks a BSDF ray (pdf `pdf`) falls in, MIS-weighted against their cones' sampling.
fn sun_disks(d: vec3<f32>, pdf: f32) -> vec3<f32> {
    var c = vec3<f32>(0.0);
    for (var i = 0u; i < P.counts2.x; i++) {
        let li = light_at(i);
        if (dot(d, -li.dir.xyz) >= li.dir.w) {
            let omega = 2.0 * PI * (1.0 - li.dir.w);
            c += (li.color.rgb / omega) * power_heuristic(pdf, 1.0 / omega);
        }
    }
    return c;
}

// What light sampling reads of an emitter's attributes (UVs, material, object), as shading has them at a hit of it:
// its triangle's, with its instance's object. (Not the normals and the tangent, which stay the mesh's:
// a light sample reads none, and placing them is work a sample. Its texel density is from the list's own edges.)
fn emitter_attrs(em: EmitterTri) -> TriAttr {
    var a = tri_data(em.tri, em.inst, em.part).a;
    if (has(F_INST) && em.inst != NO_INST) { a.x = inst_x(instance_at(em.inst).info, a.x); }
    return a;
}

// A mesh's triangle's index in its section. Hardware traversal: from the section's first triangle (the instance's
// row for it, the word a hit's triangle is found by: trace_hw.wgsl `hit_tri`). Software traversal's units: its
// leaf's id (a tree has a mesh's triangles in its own order).
@if(hwrt) fn hit_rank(h: Hit, rows: u32) -> u32 { return h.tri - row_word(rows, h.part, 1u); }
@if(!hwrt) fn hit_rank(h: Hit, rows: u32) -> u32 { return leaf_id(h.tri, 1u); }

// The MIS weight of a BSDF ray's (pdf `pdf`) hit on an emitter against light sampling in `direct_light`: by the
// density light sampling has for the point, the probability it picks the emitter (`emitter_pmf`, at the vertex the
// ray left) over the triangle's area. One it never picks (no entry, no weight: switched off, culled, a procedural
// surface) is the BSDF ray's alone.
fn emit_mis(hit: Hit, d: vec3<f32>, pdf: f32) -> f32 {
    if (is_proc(hit) || !has(F_INST) || !emitters_on()) { return 1.0; }
    // The hit triangle's emitter: its index in its section, counted from the section's first entry (its instance's
    // row's; none: it is not light-sampled).
    let rows = instance_at(hit.inst).info.w;
    let first = row_word(rows, hit.part, 2u);
    if (first == NO_EMITTER) { return 1.0; }
    let entry = first + hit_rank(hit, rows);
    let em = emitter_tri_at(entry);
    let cr = cross(em.e1, em.e2);
    let area = 0.5 * length(cr);
    let cos_l = abs(dot(normalize(cr), d));
    let sel = emitter_pmf(entry, em, mis_x, mis_n);
    if (!(sel > 0.0)) { return 1.0; }
    return power_heuristic(pdf, sel / max(area, 1e-12) * hit.t * hit.t / max(cos_l, 1e-6));
}

// Light LOD factor of an emitter (lib.rs emitter_lod): the emitter CDF's weights carry it, so every pdf of an
// emitter point does too. Moving ones have none (lib.rs EmitterTri::moves).
fn emitter_lod(em: EmitterTri) -> f32 {
    if (P.light_lod.w <= 0.0 || (em.code & EMITTER_MOVES) != 0u) { return 1.0; }
    let c = em.v0 + (em.e1 + em.e2) / 3.0;
    let k = P.light_lod.w / max(distance(c, P.light_lod.xyz), P.light_lod.w);
    return k * k;
}

// ------------------------------------------------------------------------------------------------
// Direct lighting (NEE)

struct LS { c: vec3<f32>, l: vec3<f32>, sl: vec3<f32>, dist: f32 };

// Point / spot light seen from x: punctual intensity x attenuation (unshadowed), direction to the light centre `l`,
// and a shadow ray toward a point sampled on the light's sphere (soft shadows).
fn local_light(li: Light, x: vec3<f32>, u: vec2<f32>) -> LS {
    if (u32(li.pos.w) == 3u) {
        // Rect (UE RectLight): uniform point on the rectangle; luminance x area x cos_light / d^2 (Lambertian),
        // cut beyond the barn-door angle.
        let n = li.dir.xyz;
        let ux = li.ext.xyz;
        let uy = normalize(cross(n, ux)) * li.dir.w;
        let lp = li.pos.xyz + ux * (2.0 * u.x - 1.0) + uy * (2.0 * u.y - 1.0);
        let dl = lp - x;
        let d2 = max(dot(dl, dl), 1e-8);
        let dist = sqrt(d2);
        let l = dl / dist;
        let cos_l = dot(n, -l);
        var k = 0.0;
        if (cos_l > 0.0) {
            let area = 4.0 * length(ux) * li.dir.w;
            k = area * cos_l / d2 * smoothstep(li.x.z - 0.04, li.x.z + 0.04, cos_l);
            let range = li.color.w;
            if (range > 0.0) {
                let q = d2 / (range * range);
                let win = clamp(1.0 - q * q, 0.0, 1.0);
                k *= win * win;
            }
        }
        return LS(li.color.rgb * k, l, l, dist);
    }
    var lp = li.pos.xyz;
    let radius = li.dir.w;
    if (radius > 0.0) {
        let z = 1.0 - 2.0 * u.x;
        let r = sqrt(max(0.0, 1.0 - z * z));
        let phi = 2.0 * PI * u.y;
        lp += radius * vec3<f32>(r * cos(phi), r * sin(phi), z);
    }
    let dl = li.pos.xyz - x;
    let d2 = max(dot(dl, dl), 1e-8);
    let l = dl * inverseSqrt(d2);
    var atten = 1.0 / d2;
    let range = li.color.w;
    if (range > 0.0) {
        let q = d2 / (range * range);
        let win = clamp(1.0 - q * q, 0.0, 1.0);
        atten *= win * win;
    }
    if (u32(li.pos.w) == 2u) {
        // The cone: nothing outside its half angle (ext.x its cosine), all of the light inside the inner cone, and
        // between them linear in the cosine of the angle from the axis (ext.y = 1 / the two cosines' difference),
        // squared: the angular attenuation of glTF 2.0 KHR_lights_punctual (its reference code, which is `getAngleAtt`
        // of Lagarde & de Rousiers, "Moving Frostbite to Physically Based Rendering", SIGGRAPH 2014 course notes,
        // Listing 4). The inner cone from `penumbra`: scene.rs `spot_cone`.
        let cone = clamp((dot(-l, li.dir.xyz) - li.ext.x) * li.ext.y, 0.0, 1.0);
        atten *= cone * cone;
    }
    let ls = lp - x;
    let dist = max(length(ls), 1e-6);
    return LS(li.color.rgb * atten, l, ls / dist, dist);
}

// Local lights (after the directional ones; unshadowed before shadowed, P.counts2.w = first shadowed). At camera-ray
// hits every unshadowed light is evaluated exactly, as UE's deferred lights are (no sampling noise), and the shadowed
// ones too when there are few (one shadow ray each). Otherwise: resampled importance sampling (Talbot 2005) of RIS_M
// uniform candidates by unshadowed contribution, then one shadow ray. `vol` = in-scattering in the fog (phase
// function) instead of the surface BSDF. Surface results add their specular part to `dl_spec`.
// Light tiles (live; what guides MegaLights' draws and RTXPT's): each camera pixel reports the local light its
// resampled shadow ray found (direct_out's w: `lt_fb`, a light-table index; LT_NONE: none), live.wgsl `light_tiles`
// makes each 8 x 8 tile's reports a list in `light_lists` (the lights found, each once: index, reports; ascending;
// the last vec4 their number), and the next frame's paths take resampling candidates
// from the list of the tile their camera hit was seen in then (`lt_list_start`: where the point was, through that
// frame's camera), spread over it without repeats (all of it when it is short). The candidates drawn uniformly, as
// before, then stand for the lights the list lacks (`lt_in_list`). A list is a guide: whatever it holds the estimate
// is the same sum, so one gone stale (the table reordered, a surface newly in view) costs noise, not light.
// Compiled in for scenes whose shadow-casting local lights are resampled (F_LISTS). (LT_TILE, LT_LIST, LT_NONE:
// records.wgsl.)
var<private> lt_list: u32;
var<private> lt_list_n: u32;
var<private> lt_fb: u32;

// The list of the tile that point `p` (the camera hit, where it was when the lists were built) was seen in then, and
// how many lights it holds: the nearest tile's when it was off screen, none when it was behind the camera.
fn lt_list_start(p: vec3<f32>) {
    lt_list_n = 0u;
    if (!LIVE || P.ltile.x == 0u) { return; }
    let d = p - P.lt_cam[0].xyz;
    let z = dot(d, P.lt_cam[1].xyz);
    if (z <= 1e-4) { return; }
    let ndc = vec2<f32>(dot(d, P.lt_cam[2].xyz) / (z * P.lt_cam[0].w * P.lt_cam[1].w), dot(d, P.lt_cam[3].xyz) / (z * P.lt_cam[0].w));
    let uv = clamp(vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5), vec2<f32>(0.0), vec2<f32>(1.0));
    let q = min(vec2<u32>(uv * vec2<f32>(P.ltile2.xy)), P.ltile2.xy - 1u);
    let c = q + vec2<u32>(P.ltile.z & 0xffffu, P.ltile.z >> 16u);
    lt_list = ((c.y / LT_TILE) * P.ltile.y + c.x / LT_TILE) * LT_LIST;
    if (lt_list + LT_LIST > lists_len()) { return; }
    lt_list_n = min(u32(list_load(lt_list + LT_LIST - 1u).x), LT_LIST - 1u);
}

// Whether the pixel's list holds light `i`.
fn lt_in_list(i: u32) -> bool {
    var lo = 0u;
    var hi = lt_list_n;
    for (var k = 0u; k < 7u; k++) {
        if (lo >= hi) { break; }
        let mid = (lo + hi) / 2u;
        let km = u32(list_load(lt_list + mid).x);
        if (km == i) { return true; }
        if (km < i) { lo = mid + 1u; } else { hi = mid; }
    }
    return false;
}

// A shadow ray's origin toward l at a surface: on the side l leaves it from (`o`: the near side's, as computed once).
// Only a surface that lets light through has a value for the far side, so only a kernel with glass has the code
// (in every kernel, at its five inlined sites, it cost Bistro's trace 4 %).
fn light_origin(s: Surface, o: vec3<f32>, l: vec3<f32>) -> vec3<f32> {
    if (has(F_GLASS) && dot(l, s.ng) < 0.0) { return offset_origin(s.p, -s.ng); }
    return o;
}

fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>, vol: bool, d: vec3<f32>, rd: u32) -> vec3<f32> {
    let nd = P.counts2.x;
    let nl = P.counts.x - nd;
    if (nl == 0u) { return vec3<f32>(0.0); }
    var sum = vec3<f32>(0.0);
    var first = nd;
    var count = nl;
    if (!vol && (seen_directly() || nl <= RIS_EXACT)) {
        let ns = P.counts2.w;
        let n_sh = P.counts.x - ns;
        let end = select(ns, P.counts.x, n_sh <= RIS_EXACT || nl <= RIS_EXACT);
        // In groups of LIGHT_GROUP (spatially sorted; a sphere holding all their light per group: lib.rs
        // light_groups): a group x is outside of is skipped whole.
        // (Not for the pass that takes the resampled lights alone: `dl_part`.)
        var i = select(nd, end, dl_part == DL_SAMPLED);
        loop {
            if (i >= end) { break; }
            let gs = light_group_at((i - nd) / LIGHT_GROUP);
            let gend = min(i + LIGHT_GROUP, end);
            if (distance(x, gs.xyz) > gs.w) {
                i = gend;
                continue;
            }
            for (; i < gend; i++) {
                let li = light_at(i);
                // Cheap rejects before sampling the light: black (off, or hidden), beyond its attenuation range (the
                // window is zero there), or entirely behind the surface.
                if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; }
                let dc = li.pos.xyz - x;
                let reach = li.color.w + select(li.dir.w, length(li.ext.xyz) + li.dir.w, u32(li.pos.w) == 3u);
                if (li.color.w > 0.0 && dot(dc, dc) > reach * reach) { continue; }
                if (u32(li.pos.w) != 3u && dot(dc, s.ng) < -li.dir.w && !two_sided(lb)) { continue; } // eval_bsdf rejects it anyway
                let ls = local_light(li, x, rng2(rng_sub(rd, i)));
                if (all(ls.c <= vec3<f32>(0.0))) { continue; }
                let f = eval_bsdf_k(s, lb, v, ls.l, li.x.y);
                if (any(f > vec3<f32>(0.0))) {
                    let vis = light_vis(li.ext.w >= 0.5, light_origin(s, o, ls.l), ls.sl, ls.dist * 0.999, rng_sub(rd ^ 0x40000000u, i));
                    if (any(vis > vec3<f32>(0.0))) {
                        sum += ls.c * f * tr3(vis);
                        dl_spec += ls.c * f * tr3(vis) * split_frac;
                    }
                }
            }
        }
        if (end == P.counts.x) { return sum; }
        first = ns;
        count = n_sh;
    }
    if (dl_part == DL_REST) { return sum; }
    // Target: unshadowed intensity x cosine (cheap; the full BSDF / phase is applied to the chosen light only).
    let m_cand = select(3u, RIS_M, seen_directly());
    // With the pixel's list (light tiles), `nt` candidates more come from it, one in each `step` of its lights, and
    // the uniform ones keep the lights it lacks. A uniform candidate stands for count / m_cand lights (weight 1 here,
    // the factor applied at the end, as without a list), one of the list's for `step` (`listed`, relative to that).
    var nt = 0u;
    if (has(F_LISTS) && !vol && lt_list_n > 0u) { nt = min(select(P.ltile.w / 2u, P.ltile.w, seen_directly()), lt_list_n); }
    let step = f32(lt_list_n) / f32(max(nt, 1u));
    let listed = step * f32(m_cand) / f32(count);
    var at = 0.0;
    if (nt > 0u) { at = rng1(rng_sub(rd ^ 0x80000000u, 0x2000u)); }
    var wsum = 0.0;
    var pick = 0u;
    var pick_ph = 0.0;
    var pick_ls: LS;
    for (var k = 0u; k < m_cand + nt; k++) {
        var r4: vec4<f32>;
        var idx: u32;
        var stands = 1.0;
        if (k < m_cand) {
            r4 = rng4(rng_sub(rd ^ 0x80000000u, k));
            idx = first + min(u32(r4.x * f32(count)), count - 1u);
        } else {
            r4 = rng4(rng_sub(rd ^ 0x80000000u, 0x1000u + k));
            idx = u32(list_load(lt_list + min(u32((f32(k - m_cand) + at) * step), lt_list_n - 1u)).x);
            if (idx < first || idx >= first + count) { continue; }
            stands = listed;
        }
        let ls = local_light(light_at(idx), x, r4.yz);
        var ph = luminance(ls.c);
        if (vol) { ph *= light_at(idx).x.x; } else if (two_sided(lb)) { ph *= abs(dot(s.n, ls.l)); } else { ph *= max(dot(s.n, ls.l), 0.0) + 0.05 * max(dot(s.ng, ls.l), 0.0); }
        if (ph <= 0.0) { continue; }
        if (nt > 0u && k < m_cand && lt_in_list(idx)) { continue; }
        let w = ph * stands;
        wsum += w;
        if (r4.w * wsum < w) {
            pick = idx;
            pick_ph = ph;
            pick_ls = ls;
        }
    }
    if (pick_ph > 0.0) {
        var c: vec3<f32>;
        let lk = light_at(pick).x;
        if (vol) { c = pick_ls.c * hg_phase(P.vol.y, dot(pick_ls.l, d)) * lk.x; } else { c = pick_ls.c * eval_bsdf_k(s, lb, v, pick_ls.l, lk.y); }
        if (any(c > vec3<f32>(0.0))) {
            let vis = light_vis(light_at(pick).ext.w >= 0.5, light_origin(s, o, pick_ls.l), pick_ls.sl, pick_ls.dist * 0.999, rng_sub(rd, 0xffffffffu));
            if (any(vis > vec3<f32>(0.0))) {
                let r = c * tr3(vis) * (wsum * f32(count) / (f32(m_cand) * pick_ph));
                sum += r;
                if (!vol) { dl_spec += r * split_frac; }
                // The light tiles' report: the light the camera hit's ray found.
                if (has(F_LISTS) && !vol && cur_depth == 0u) { lt_fb = pick; }
            }
        }
    }
    return sum;
}

// An emitter sample: radiance, direction, distance, its source pdf (solid angle; MIS weights) and its contribution
// weight `w` (1 / pdf, or the RIS weight).
struct ES { le: vec3<f32>, l: vec3<f32>, dist: f32, pdf_w: f32, w: f32 };

// Emitted radiance of an emitter at (b1, b2) toward -l (emissive map, animation, material function, node power).
fn emitter_radiance(em: EmitterTri, b1: f32, b2: f32, l: vec3<f32>) -> vec3<f32> {
    let a = emitter_attrs(em);
    let m = material_at(material_of(a, em.inst));
    // 5 cm footprint: a blurred texel is plenty for lighting and keeps NEE cheap.
    let pw = obj_power(a);
    var le = emission(m, mesh_uv(a, m, b1, b2), mesh_lod(mesh_density(em.e1, em.e2, a, m), 0.0025, 1.0)) * pw;
    if (has(F_FUNC) && m.tex1.w > 0) {
        var mb = mat_base(m);
        mb.emissive *= pw;
        le = emissive_material_function(m.tex1.w - 1, mat_in_at(em.tri, em.inst, em.part, b1, b2, -l, log2(0.05)), m, mb).emissive;
    }
    return le;
}

// Camera-ray hits: RIS over `m` candidates from the emitter CDF, resampled by emitted luminance x geometry term at x
// (with m > 1 the receiving side's cosine is the surface's BSDF x cosine toward the candidate, `eval_bsdf`: a glossy
// surface then picks the lights in its specular lobe, not only the bright and near ones. The string lights on the
// crowd's moving van roofs were sparse sparkles; live specular in motion 0.88 -> 0.91 of our offline render, layer B
// Bistro 3.47 -> 3.34. The target is free to choose: the estimate stays unbiased, tools/unbiased-check.ts within 0.1 %)
// (the CDF knows emitted power, and with light LOD the distance to the camera; without it, it mostly proposes signs
// far down the street). The target leaves the light LOD out, so the light LOD only changes which candidates are
// proposed. A candidate's weight and the MIS against the BSDF rays (emit_mis) are by the density the point was drawn
// with: the probability of its emitter's pick over the triangle's own area, whatever the CDF weighed the emitter by
// (a triangle that changed size since, a particle's nominal area). With light LOD every surface vertex samples this
// way (deeper ones with 2 candidates): a single draw from the LOD'd CDF would make far emitters rare and heavy, which
// the radiance cache's clamps cut.
fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes, v: vec3<f32>, rd: u32) -> ES {
    var r = ES(vec3<f32>(0.0), vec3<f32>(0.0, 1.0, 0.0), 0.0, 0.0, 0.0);
    var wsum = 0.0;
    var pick_b = vec2<f32>(0.0);
    var pick_ph = 0.0;
    var pick_i = 0u;
    var pick_pdf = 0.0;
    for (var k = 0u; k < m; k++) {
        let dk = rng_sub(rd, k);
        let pk = emitter_draw(x, n, dk);
        let e = pk.e;
        let bb = rng3(rng_sub(dk, 1u));
        var b1 = bb.x;
        var b2 = bb.y;
        if (pk.p <= 0.0) { continue; }
        if (b1 + b2 > 1.0) { b1 = 1.0 - b1; b2 = 1.0 - b2; }
        let em = emitter_tri_at(bitcast<u32>(e.x));
        let e1 = em.e1;
        let e2 = em.e2;
        let lp = em.v0 + e1 * b1 + e2 * b2;
        let cr = cross(e1, e2);
        // Twice the triangle's own area (none: a particle not shown).
        let a2 = length(cr);
        if (!(a2 > 0.0)) { continue; }
        let ln = cr / a2;
        let dl = lp - x;
        let d2 = max(dot(dl, dl), 1e-8);
        let l = dl * inverseSqrt(d2);
        var g = abs(dot(ln, l)) * select(max(dot(n, l), 0.0), 1.0, dot(n, n) == 0.0) / d2;
        if (m > 1u) { g = abs(dot(ln, l)) * luminance(eval_bsdf(sf, lb, v, l)) / d2; }
        // The target: emitted luminance x power (the entry's weight over the area and the light LOD it was weighed
        // with) x G. The weight: the target over the density of the point.
        let ph = pk.w / (e.w * emitter_lod(em)) * g;
        let pdf_a = pk.p / (0.5 * a2);
        let w = ph / pdf_a;
        if (!(w > 0.0)) { continue; }
        wsum += w;
        if (bb.z * wsum < w) {
            pick_b = vec2<f32>(b1, b2);
            pick_ph = ph;
            pick_i = bitcast<u32>(e.x);
            pick_pdf = pdf_a;
        }
    }
    if (pick_ph <= 0.0) { return r; }
    let em = emitter_tri_at(pick_i);
    let e1 = em.e1;
    let e2 = em.e2;
    let lp = em.v0 + e1 * pick_b.x + e2 * pick_b.y;
    let ln = normalize(cross(e1, e2));
    let dl = lp - x;
    let d2 = dot(dl, dl);
    let dist = sqrt(d2);
    let l = dl / dist;
    var cos_l = dot(ln, -l);
    let m_card = emitter_is_card(em);
    if (!m_card) { cos_l = abs(cos_l); }
    if (cos_l <= 0.0) { return r; }
    r.le = emitter_radiance(em, pick_b.x, pick_b.y, l);
    r.l = l;
    r.dist = dist;
    r.pdf_w = pick_pdf * d2 / cos_l;
    r.w = (wsum / f32(m)) / pick_ph * cos_l / d2;
    return r;
}

// One emissive triangle point by the emitter CDF (area x emissive-factor luminance); radiance includes the emissive
// map (coarse mip) and animation, so signs spill their own colours.
fn sample_emitter(x: vec3<f32>, n: vec3<f32>, rd: u32) -> ES {
    var r = ES(vec3<f32>(0.0), vec3<f32>(0.0, 1.0, 0.0), 0.0, 0.0, 0.0);
    let pk = emitter_draw(x, n, rd);
    let e = pk.e;
    if (pk.p <= 0.0) { return r; } // switched off (power 0)
    let em = emitter_tri_at(bitcast<u32>(e.x));
    let v0 = em.v0;
    let e1 = em.e1;
    let e2 = em.e2;
    let bb = rng2(rng_sub(rd, 1u));
    var b1 = bb.x;
    var b2 = bb.y;
    if (b1 + b2 > 1.0) { b1 = 1.0 - b1; b2 = 1.0 - b2; }
    let lp = v0 + e1 * b1 + e2 * b2;
    let cr = cross(e1, e2);
    let area = 0.5 * length(cr);
    let ln = cr / (2.0 * area);
    let dl = lp - x;
    let d2 = dot(dl, dl);
    let dist = sqrt(d2);
    let l = dl / dist;
    var cos_l = dot(ln, -l);
    if (!emitter_is_card(em)) { cos_l = abs(cos_l); }
    if (cos_l <= 0.0 || (has(F_PEMIT) && !(cos_l > 0.0))) { return r; } // also a particle not shown (no area: NaN)
    r.le = emitter_radiance(em, b1, b2, l);
    r.l = l;
    r.dist = dist;
    r.pdf_w = pk.p / area * d2 / cos_l;
    r.w = 1.0 / r.pdf_w;
    return r;
}

fn hg_phase(g: f32, c: f32) -> f32 {
    let d = 1.0 + g * g - 2.0 * g * c;
    return (1.0 - g * g) / (4.0 * PI * d * sqrt(d));
}

// gpu.rs `KernelSwitches::last_sun`: the directional lights alone, as `direct_light` takes them (one shadow ray a
// light), for the path's last vertex.
@if(last_sun && !last_direct) fn sun_light(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
    var sum = vec3<f32>(0.0);
    let o = offset_origin(s.p, s.ng);
    for (var i = 0u; i < P.counts2.x; i++) {
        let li = light_at(i);
        if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; }
        let cos_max = li.dir.w;
        let to_light = -li.dir.xyz;
        let u = rng2(rng_sub(rng_dim(D_SUN), i));
        let cos_t = 1.0 - u.x * (1.0 - cos_max);
        let sin_t = sqrt(max(0.0, 1.0 - cos_t * cos_t));
        let phi = 2.0 * PI * u.y;
        let l = basis(to_light) * vec3<f32>(sin_t * cos(phi), sin_t * sin(phi), cos_t);
        let f = eval_bsdf_k(s, lb, v, l, li.x.y);
        if (any(f > vec3<f32>(0.0))) {
            let vis = light_vis(li.ext.w >= 0.5, light_origin(s, o, l), l, INF, rng_sub(rng_dim(D_SUN_VIS), i));
            if (any(vis > vec3<f32>(0.0))) {
                let pdf_l = 1.0 / (2.0 * PI * (1.0 - cos_max));
                sum += li.color.rgb * f * light_mis(pdf_l, s, lb, v, l) * tr3(vis);
            }
        }
    }
    return sum;
}

// Whether the sky is light-sampled.
fn env_sampled() -> bool { return P.counts2.y != 0u && (P.env.x > 0.5 || luminance(P.sky_color.rgb) > 0.0); }

// The sky's light sample at a surface (`o`: its shadow rays' origin): one direction by the map, MIS against the BSDF.
fn env_light(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>) -> vec3<f32> {
    let l = sample_env(rng_dim(D_ENV));
    let f = eval_bsdf(s, lb, v, l);
    if (any(f > vec3<f32>(0.0))) {
        let pdf_e = env_pdf(l);
        if (pdf_e > 0.0) {
            let vis = sky_tr(light_origin(s, o, l), l, rng_dim(D_ENV_VIS));
            if (any(vis > vec3<f32>(0.0))) { return env_radiance(l) * f * light_mis(pdf_e, s, lb, v, l) / pdf_e * tr3(vis); }
        }
    }
    return vec3<f32>(0.0);
}

fn direct_light(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
    var sum = vec3<f32>(0.0);
    dl_spec = vec3<f32>(0.0);
    let o = offset_origin(s.p, s.ng);
    // Directional lights: uniformly sampled cone (soft shadows), MIS against BSDF sampling.
    for (var i = 0u; i < select(P.counts2.x, 0u, dl_part == DL_SAMPLED); i++) {
        let li = light_at(i);
        let cos_max = li.dir.w;
        let to_light = -li.dir.xyz;
        let u = rng2(rng_sub(rng_dim(D_SUN), i));
        let cos_t = 1.0 - u.x * (1.0 - cos_max);
        let sin_t = sqrt(max(0.0, 1.0 - cos_t * cos_t));
        let phi = 2.0 * PI * u.y;
        let tb = basis(to_light);
        let l = tb * vec3<f32>(sin_t * cos(phi), sin_t * sin(phi), cos_t);
        // A light gone black (a moon that has set, the sun at night) costs neither its BSDF nor its shadow ray.
        if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; }
        let f = eval_bsdf_k(s, lb, v, l, li.x.y);
        if (any(f > vec3<f32>(0.0))) {
            let vis = light_vis(li.ext.w >= 0.5, light_origin(s, o, l), l, INF, rng_sub(rng_dim(D_SUN_VIS), i));
            if (any(vis > vec3<f32>(0.0))) {
                let pdf_l = 1.0 / (2.0 * PI * (1.0 - cos_max));
                let frac = split_frac;
                let wgt = light_mis(pdf_l, s, lb, v, l);
                sum += li.color.rgb * f * wgt * tr3(vis);
                dl_spec += li.color.rgb * f * wgt * tr3(vis) * frac;
            }
        }
    }
    if (cur_depth == 0u) {
        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;
    @if(light_pick) let has_emit = emitters_on();
    @if(light_pick) let has_env = P.counts2.y != 0u && (P.env.x > 0.5 || luminance(P.sky_color.rgb) > 0.0);
    @if(light_pick) var take_local = true;
    @if(light_pick) var take_emit = true;
    @if(light_pick) var take_env = true;
    @if(light_pick) var pick_w = 1.0;
    @if(light_pick) let kinds = u32(has_local) + u32(has_emit) + u32(has_env);
    @if(light_pick) if (cur_depth > 0u && kinds > 1u) {
        var k = min(u32(rng1(rng_dim(D_PICK)) * f32(kinds)), kinds - 1u);
        take_local = has_local && k == 0u;
        if (has_local) { k -= 1u; }
        take_emit = has_emit && k == 0u;
        if (has_emit) { k -= 1u; }
        take_env = has_env && k == 0u;
        pick_w = f32(kinds);
    }
    @if(light_pick) let sum_sun = sum;
    @if(light_pick) let spec_sun = dl_spec;
    @if(!light_pick) sum += local_lights(s, lb, v, o, s.p, false, vec3<f32>(0.0), rng_dim(D_LOCAL));
    @if(light_pick) if (take_local) { sum += local_lights(s, lb, v, o, s.p, false, vec3<f32>(0.0), rng_dim(D_LOCAL)); }
    // Emissive triangles (incl. rect lights)
    // (Rough glass takes emitters from both sides: as a point without a hemisphere does, the samples and `emit_mis`
    // alike. The tree's bound has no two-sided cosine; without one the estimate is the same, its noise a little more.)
    var ne = s.n;
    if (two_sided(lb)) { ne = vec3<f32>(0.0); }
    mis_x = o;
    mis_n = ne;
    var emitters = select(0u, P.counts.y, emitters_on());
    @if(light_pick) if (!take_emit) { emitters = 0u; }
    if (dl_part == DL_REST) { emitters = 0u; }
    if (emitters > 0u) {
        var es: ES;
        // With the light tree its candidates are already near the point: P.ltree.y of them at camera hits, one elsewhere.
        if (lt_on()) { es = sample_emitter_ris(o, ne, select(1u, u32(P.ltree.w), cur_depth == 0u), s, lb, v, rng_dim(D_EMIT)); } else if (seen_directly()) { es = sample_emitter_ris(o, ne, select(EMIT_RIS_M / 2u, EMIT_RIS_M, cur_depth == 0u), s, lb, v, rng_dim(D_EMIT)); } else if (P.light_lod.w > 0.0) { es = sample_emitter_ris(o, ne, 2u, s, lb, v, rng_dim(D_EMIT)); } else { es = sample_emitter(o, ne, rng_dim(D_EMIT)); }
        if (es.pdf_w > 0.0) {
            let f = eval_bsdf(s, lb, v, es.l);
            if (any(f > vec3<f32>(0.0))) {
                let vis = emitter_tr(light_origin(s, o, es.l), es.l, es.dist * 0.999, rng_dim(D_EMIT_VIS));
                if (vis > 0.0) {
                    let frac = split_frac;
                    let wgt = light_mis(es.pdf_w, s, lb, v, es.l) * tr1(vis);
                    sum += es.le * f * wgt * es.w;
                    dl_spec += es.le * f * wgt * es.w * frac;
                }
            }
        }
    }
    // Environment
    var env_on = env_sampled() && !lights_only && dl_part != DL_SAMPLED;
    @if(light_pick) env_on = take_env && has_env && !lights_only && dl_part != DL_SAMPLED;
    if (env_on) {
        // (`split_frac` is the sky sample's where its BSDF was not 0; where it was, e is 0.)
        let e = env_light(s, lb, v, o);
        sum += e;
        dl_spec += e * split_frac;
    }
    @if(light_pick) if (pick_w > 1.0) {
        sum = sum_sun + (sum - sum_sun) * pick_w;
        dl_spec = spec_sun + (dl_spec - spec_sun) * pick_w;
    }
    return sum;
}

// ------------------------------------------------------------------------------------------------
// The sky's aerial perspective (F_AERIAL): the atmosphere between a viewer and a surface. Its extinction is the
// SkyAtmosphere's own (sky.rs Atmosphere::earth): Rayleigh 5.8 / 13.6 / 33.1 per 1000 km and Mie 4.0 x scale + 0.44 per
// 1000 km at sea level (y = 0), thinning with scale heights of 8 km and 1.2 km, times P.aerial.x. The light it
// scatters toward the viewer is taken as the sky's own radiance at the horizon in the ray's direction, (1 - T) of it:
// a horizontal ray through the same air ends on that horizon, so far land fades into the sky behind it.
fn aerial_od(y0: f32, dy: f32, t: f32, h: f32) -> f32 {
    // the integral of exp(-(y0 + dy s) / h) over s < t
    let a = exp(-max(y0, -500.0) / h);
    let k = dy / h;
    if (abs(k * t) < 1e-4) { return a * t; }
    return a * (1.0 - exp(clamp(-k * t, -80.0, 80.0))) / k;
}

fn aerial_tr(o: vec3<f32>, d: vec3<f32>, t: f32) -> vec3<f32> {
    let rayleigh = vec3<f32>(5.802e-6, 13.558e-6, 33.1e-6) * P.aerial.y;
    let mie = 3.996e-6 * P.aerial.z + 0.444e-6;
    if (P.aerial.w > 0.0) {
        let c = aerial_planet(o - P.cam_pos.xyz, d, t, P.aerial.w);
        return exp(-P.aerial.x * (rayleigh * c.x + mie * c.y));
    }
    return exp(-P.aerial.x * (rayleigh * aerial_od(o.y, d.y, t, 8000.0) + mie * aerial_od(o.y, d.y, t, 1200.0)));
}

// On a planet (SkyAtmosphere.altitude: P.aerial.w, the camera's altitude in m): the air over a sphere of the sky's
// ground radius whose centre is straight below the camera, so that from high up the haze thins with altitude instead of
// lying at sea-level density around the camera. The columns of air and haze (m at sea-level density) along the
// segment from the camera-relative point `q`, by Chapman's function as an erfcx; the derivation, its sources and the
// tests that hold it to a quadrature: sky.rs `aerial_columns`, of which this is a copy line by line.
const AERIAL_R: f32 = 6.36e6;

fn aerial_erfcx(y: f32) -> f32 {
    return 1.1283792 / (y + sqrt(y * y + 0.6166356 * y + 1.2732395)) * (1.0 + 0.0295 * y * y / (1.0 + 0.312 * y * y * y));
}

fn aerial_column(h: f32, mu: f32, scale: f32) -> f32 {
    let x = (AERIAL_R + h) / scale;
    return scale * exp(-max(h, -500.0) / scale) * sqrt(0.5 * PI * x) * aerial_erfcx(max(mu, 0.0) * sqrt(0.5 * x));
}

// A point's altitude and the zenith cosine of `d` there (`q`: the point less the camera).
fn aerial_at(q: vec3<f32>, d: vec3<f32>, h0: f32) -> vec2<f32> {
    let up = q.y + h0;
    let s2 = q.x * q.x + q.z * q.z;
    let y = up + AERIAL_R;
    let r = sqrt(y * y + s2);
    return vec2<f32>(up + s2 / (r + y), (q.x * d.x + y * d.y + q.z * d.z) / r);
}

fn aerial_planet(q: vec3<f32>, d: vec3<f32>, t: f32, h0: f32) -> vec2<f32> {
    let a = aerial_at(q, d, h0);
    let b = aerial_at(q + d * t, d, h0);
    let lowest = -(q.x * d.x + (q.y + h0 + AERIAL_R) * d.y + q.z * d.z);
    let p = aerial_at(q + d * clamp(lowest, 0.0, t), d, h0);
    var od = vec2<f32>(0.0);
    for (var i = 0u; i < 2u; i++) {
        let scale = select(1200.0, 8000.0, i == 0u);
        var c: f32;
        if (lowest <= 0.0) {
            c = aerial_column(a.x, a.y, scale) - aerial_column(b.x, b.y, scale);
        } else if (lowest >= t) {
            c = aerial_column(b.x, -b.y, scale) - aerial_column(a.x, -a.y, scale);
        } else {
            c = 2.0 * aerial_column(p.x, 0.0, scale) - aerial_column(a.x, -a.y, scale) - aerial_column(b.x, b.y, scale);
        }
        od[i] = max(c, 0.0);
    }
    return od;
}

// The sky a little above the horizon (2.3 degrees: clear of the baked sky's fade to its black lower half), or where
// the ray points if higher: the haze's light, and what camera rays see of the sky near the horizon with F_AERIAL, so
// that the hazed land meets the sky without the fade's dark seam.
// On a planet (P.aerial.w > 0) the bake is black below its dipped horizon; the haze's light is the limb's, the air
// seen edge on in the ray's azimuth: the bake's row the horizon crosses (P.sky_color.w, its v), read back whole (its
// alpha: the share of the row the sky covers; sky.rs `Horizon::Planet`), for rays up to a row above its centre too (the
// globe's own silhouette may be there, and the map read between the limb and the row above it is darker than either).
// Higher, the sky where the ray points.
fn aerial_light(d: vec3<f32>) -> vec3<f32> {
    if (P.aerial.w > 0.0 && P.sky_color.w > 0.0 && P.env.x > 0.5) {
        let uv = env_uv(d);
        if (uv.y < P.sky_color.w - 1.0 / P.env.z) { return env_radiance(d); }
        let l = textureSampleLevel(env_tex, samp, vec2<f32>(uv.x, P.sky_color.w), 0.0);
        return l.rgb / max(l.a, 1e-3);
    }
    return env_radiance(normalize(vec3<f32>(d.x, max(d.y, 0.04), d.z)));
}

// Exponential height fog: extinction density * exp(-falloff * (y - height)).

fn fog_base(o: vec3<f32>, d: vec3<f32>, t0: f32) -> f32 {
    return P.fog.x * exp(clamp(-P.fog.y * (o.y + d.y * t0 - P.fog.z), -80.0, 80.0));
}

// Optical depth along o + d t, t in [t0, t1].
fn fog_depth(o: vec3<f32>, d: vec3<f32>, t0: f32, t1: f32) -> f32 {
    let len = t1 - t0;
    if (len <= 0.0) { return 0.0; }
    let a = fog_base(o, d, t0);
    let k = P.fog.y * d.y;
    if (abs(k * len) < 1e-4) { return a * len; }
    return a * (1.0 - exp(clamp(-k * len, -80.0, 80.0))) / k;
}

// Single scattering along a camera ray segment: one distance sampled by optical depth, then lights (RIS), one
// emissive point and the directional lights, each with a shadow ray. `tr` = segment transmittance.
fn fog_scatter(o: vec3<f32>, d: vec3<f32>, t0: f32, t1: f32, tr: f32, rd: u32) -> vec3<f32> {
    let r2 = rng2(rd);
    let pe = 1.0 - tr;
    if (pe < 1e-4) { return vec3<f32>(0.0); }
    let tau = -log(max(1.0 - r2.x * pe, 1e-8));
    let a = fog_base(o, d, t0) * max(P.vol.z, 1e-3);
    let k = P.fog.y * d.y;
    var t = tau / max(a, 1e-12);
    if (abs(k) > 1e-6) { t = -log(max(1.0 - tau * k / a, 1e-8)) / k; }
    let x = o + d * (t0 + clamp(t, 0.0, t1 - t0));
    var ls = vec3<f32>(0.0);
    for (var i = 0u; i < P.counts2.x; i++) {
        let li = light_at(i);
        let l = -li.dir.xyz;
        if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; } // black: no shadow ray (direct_light)
        let vis = light_vis(li.ext.w >= 0.5, x, l, INF, rng_sub(rd, 0x30u + i));
        if (any(vis > vec3<f32>(0.0))) { ls += li.color.rgb * hg_phase(P.vol.y, dot(l, d)) * li.x.x * tr3(vis); }
    }
    // One shadow ray: either the local lights (RIS) or one emissive point, chosen with equal odds when both exist.
    let has_l = P.counts.x > P.counts2.x;
    let has_e = emitters_on();
    let both = has_l && has_e;
    let use_e = has_e && (!has_l || r2.y < 0.5);
    let wk = select(1.0, 2.0, both);
    if (use_e) {
        // Emitters picked by global power are mostly far away from a fog point: resample 4 candidates by their
        // unshadowed contribution here (RIS), one shadow ray for the winner.
        var wsum = 0.0;
        var pick: ES;
        var pick_t = 0.0;
        for (var c = 0u; c < 4u; c++) {
            mis_x = x;
            mis_n = vec3<f32>(0.0);
            let es = sample_emitter(x, vec3<f32>(0.0), rng_sub(rd, 0x10u + c));
            if (es.pdf_w <= 0.0) { continue; }
            let t = luminance(es.le) * hg_phase(P.vol.y, dot(es.l, d));
            let w = t / es.pdf_w;
            if (w <= 0.0) { continue; }
            wsum += w;
            if (rng1(rng_sub(rd, 0x20u + c)) * wsum < w) {
                pick = es;
                pick_t = t;
            }
        }
        if (pick_t > 0.0) {
            let vis = any_tr(x, pick.l, pick.dist * 0.999, rng_sub(rd, 0x40u));
            if (vis > 0.0) { ls += wk * pick.le * hg_phase(P.vol.y, dot(pick.l, d)) * (wsum / (4.0 * pick_t)) * tr1(vis); }
        }
    } else if (has_l) {
        var dummy_s: Surface;
        var dummy_l: Lobes;
        ls += wk * local_lights(dummy_s, dummy_l, -d, x, x, true, d, rng_sub(rd, 0x50u));
    }
    return P.vol.x * P.vol2.rgb * pe * ls;
}

// ------------------------------------------------------------------------------------------------
// Bounded participating media (F_MEDIA): `VolumeMesh` nodes, a box or sphere each, whose volume function gives
// extinction, albedo and emission at a point (docs/MATERIAL_FUNCTIONS.md, "Volume functions"). Paths sample them by
// delta tracking, shadow rays by ratio tracking (Novák et al. 2018); single and multiple scattering, emission.

struct VIn {
    p: vec3<f32>,      // world position, m
    lp: vec3<f32>,     // position in the volume's own space: the box [-0.5, 0.5]^3 / the sphere of radius 0.5
    time: f32,         // scene time, s
    custom: vec4<f32>, // the node's customData
    grid: vec2<u32>, // the node's density grid: its first layer in the atlas, its cells (10 bits an axis; 0: none)
};

struct VOut {
    extinction: f32,    // 1/m (clamped to the volume's majorant)
    albedo: vec3<f32>,  // scattering / extinction
    emission: vec3<f32>, // emitted radiance per metre (absorption x emitted radiance)
};

// The node's density grid at `lp` (the volume's own space, the box [-0.5, 0.5]^3): field A's four numbers, trilinear
// between cell centres, the border cells' beyond them; zeros for a node without a grid.
fn vgrid(i: VIn, lp: vec3<f32>) -> vec4<f32> {
    if (i.grid.y == 0u) { return vec4<f32>(0.0); }
    let n = vec3<f32>(vec3<u32>(i.grid.y & 1023u, (i.grid.y >> 10u) & 1023u, (i.grid.y >> 20u) & 1023u));
    let c = clamp((lp + 0.5) * n, vec3<f32>(0.5), n - 0.5) + vec3<f32>(0.0, 0.0, f32(i.grid.x));
    return textureSampleLevel(grid_tex, samp, c / vec3<f32>(textureDimensions(grid_tex)), 0.0);
}

// @volume-functions-begin
fn volume_function(f: u32, i: VIn, p: array<vec4<f32>, 8>) -> VOut { return VOut(0.0, vec3<f32>(1.0), vec3<f32>(0.0)); }
// @volume-functions-end

fn medium_local(m: Medium, x: vec3<f32>) -> vec3<f32> {
    return vec3<f32>(dot(m.w0.xyz, x) + m.w0.w, dot(m.w1.xyz, x) + m.w1.w, dot(m.w2.xyz, x) + m.w2.w);
}

// The ray's (o + d t) parameter interval inside medium m (x > y: it misses).
fn medium_span(m: Medium, o: vec3<f32>, d: vec3<f32>) -> vec2<f32> {
    let lo = medium_local(m, o);
    let ld = vec3<f32>(dot(m.w0.xyz, d), dot(m.w1.xyz, d), dot(m.w2.xyz, d));
    // (Its node hidden: scene.rs MEDIUM_HIDDEN. No ray crosses it.)
    if (m.a.y >= 2u) { return vec2<f32>(1.0, 0.0); }
    if (m.a.y == 1u) {
        let a = dot(ld, ld);
        let b = dot(lo, ld);
        let disc = b * b - a * (dot(lo, lo) - 0.25);
        if (disc < 0.0 || a <= 0.0) { return vec2<f32>(1.0, 0.0); }
        let r = sqrt(disc);
        return vec2<f32>((-b - r) / a, (-b + r) / a);
    }
    let inv = 1.0 / select(ld, vec3<f32>(1e-20), abs(ld) < vec3<f32>(1e-20));
    let ta = (vec3<f32>(-0.5) - lo) * inv;
    let tb = (vec3<f32>(0.5) - lo) * inv;
    let lo_t = min(ta, tb);
    let hi_t = max(ta, tb);
    return vec2<f32>(max(max(lo_t.x, lo_t.y), lo_t.z), min(min(hi_t.x, hi_t.y), hi_t.z));
}

fn medium_eval(k: u32, x: vec3<f32>) -> VOut {
    let m = medium_at(k);
    var i: VIn;
    i.p = x;
    i.lp = medium_local(m, x);
    i.time = P.time.x;
    i.custom = m.c;
    i.grid = vec2<u32>(bitcast<u32>(m.b.z), bitcast<u32>(m.b.w));
    var r = volume_function(m.a.x, i, m.p);
    r.extinction = clamp(r.extinction, 0.0, m.b.x);
    return r;
}

struct Track { t: f32, albedo: vec3<f32>, g: f32, emission: vec3<f32> };

// Delta tracking along o + d t, t < tmax: the first real collision (t < 0: none) with its albedo and HG anisotropy,
// and the emission met on the way (emission / majorant at every tentative collision). The ray is taken a stretch at
// a time, between the points where it enters or leaves a medium: in each the media it is in are one medium, their
// majorants and their coefficients summed (media may overlap). A collision is one of theirs, by extinction.
// (Until 2026-11-13 each medium was tracked whole, in the order the ray entered them: a collision in the first hid
// what a medium inside it emitted or scattered before that point: a fire inside smoke was drawn behind the smoke.)
fn media_track(o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> Track {
    var stp = 0u;
    var r = Track(-1.0, vec3<f32>(1.0), 0.0, vec3<f32>(0.0));
    let n = min(u32(P.time.w), 32u);
    var t = 0.0;
    for (var s = 0u; s <= 2u * n; s++) {
        var mask = 0u;
        var mj = 0.0;
        var end = tmax;
        for (var k = 0u; k < n; k++) {
            let sp = medium_span(medium_at(k), o, d);
            let a = max(sp.x, 0.0);
            let b = min(sp.y, tmax);
            if (a >= b) { continue; }
            if (a > t) {
                end = min(end, a);
            } else if (b > t) {
                mask |= 1u << k;
                mj += medium_at(k).b.x;
                end = min(end, b);
            }
        }
        if (mask != 0u && mj > 0.0) {
            loop {
                let r3 = rng_hash3(rng_sub(rd, stp));
                stp++;
                t -= log(1.0 - r3.x) / mj;
                if (t >= end) { break; }
                var st = 0.0;
                var em = vec3<f32>(0.0);
                for (var k = 0u; k < n; k++) {
                    if (((mask >> k) & 1u) == 0u) { continue; }
                    let v = medium_eval(k, o + d * t);
                    st += v.extinction;
                    em += v.emission;
                    // The medium a collision here is in: each by its extinction (the first without a draw).
                    if (v.extinction > 0.0 && (st <= v.extinction || rng_hash(rng_sub(rng_sub(rd, stp), k), 0u) * st < v.extinction)) {
                        r.albedo = v.albedo;
                        r.g = medium_at(k).b.y;
                    }
                }
                r.emission += em / mj;
                if (r3.z * mj < st) {
                    r.t = t;
                    return r;
                }
            }
        }
        if (end >= tmax) { break; }
        t = end;
    }
    r.albedo = vec3<f32>(1.0);
    r.g = 0.0;
    return r;
}

// Transmittance through the media along o + d t, t < tmax (ratio tracking; an unbiased estimate).
fn media_tr(o: vec3<f32>, d: vec3<f32>, tmax: f32, rd: u32) -> f32 {
    var tr = 1.0;
    let n = min(u32(P.time.w), 32u);
    for (var k = 0u; k < n; k++) {
        let sp = medium_span(medium_at(k), o, d);
        let b = min(sp.y, tmax);
        let mj = medium_at(k).b.x;
        if (max(sp.x, 0.0) >= b || mj <= 0.0) { continue; }
        var t = max(sp.x, 0.0);
        var step = 0u;
        loop {
            t -= log(1.0 - rng_hash(rng_sub(rd, (k << 24u) + step), 0u)) / mj;
            step++;
            if (t >= b) { break; }
            tr *= 1.0 - medium_eval(k, o + d * t).extinction / mj;
            if (tr < 1e-4) { return 0.0; }
        }
    }
    return tr;
}

// Live camera rays through media: transmittance and in-scattered light by ray marching (MEDIA_STEPS jittered steps
// per volume) instead of delta tracking, so the surface behind stays the pixel's first hit for the temporal filter.
// In-scattering takes the radiance cache's volume voxels (the mean incident radiance: isotropic scattering) plus the
// medium's emission. The voxels are trained by `media_train`, a pass of its own (point_radiance inlined here would
// copy surface shading and every material function into the kernel: minutes of compile on Kabukichō).
const MEDIA_STEPS: u32 = 8u;
const MEDIA_STEPS_INDIRECT: u32 = 4u; // later segments: transmittance only
const MEDIA_TRAIN_POINTS: u32 = 4096u;
// tr, light: the transmittance and the light of every medium on the ray; moving: those of the media that change with
// time alone (their transmittance, their light's luminance).
struct March { tr: f32, light: vec3<f32>, moving: vec2<f32> };

fn media_march(o: vec3<f32>, d: vec3<f32>, tmax: f32, camera: bool, rd: u32) -> March {
    var r = March(1.0, vec3<f32>(0.0), vec2<f32>(1.0, 0.0));
    let n = min(u32(P.time.w), 32u);
    let u = rng1(rd);
    let per = f32(select(MEDIA_STEPS_INDIRECT, MEDIA_STEPS, camera));
    let lw = vec3<f32>(0.2126, 0.7152, 0.0722);
    // A stretch at a time, between the points where the ray enters or leaves a medium (as `media_track`): the media
    // it is in there are marched together, their coefficients summed, at the finest of their steps: a medium's is its
    // crossing over `per`, and an eighth of that with a density grid (b.w: its cells; a grid has detail 8 steps miss).
    var t = 0.0;
    for (var s = 0u; s <= 2u * n; s++) {
        var mask = 0u;
        var end = tmax;
        var dt = 1.0e30;
        var gridded = false;
        for (var k = 0u; k < n; k++) {
            let sp = medium_span(medium_at(k), o, d);
            let a = max(sp.x, 0.0);
            let b = min(sp.y, tmax);
            if (a >= b) { continue; }
            if (a > t) {
                end = min(end, a);
            } else if (b > t) {
                mask |= 1u << k;
                end = min(end, b);
                let grid = bitcast<u32>(medium_at(k).b.w) != 0u;
                gridded = gridded || grid;
                dt = min(dt, (b - a) / (per * select(1.0, 8.0, grid)));
            }
        }
        if (mask != 0u) {
            let steps = max(u32(ceil((end - t) / dt - 1e-3)), 1u);
            let ds = (end - t) / f32(steps);
            for (var j = 0u; j < steps; j++) {
                let x = o + d * (t + (f32(j) + u) * ds);
                // All the media here, and those of them that change with time (`March::moving`).
                var st = 0.0;
                var sc = vec3<f32>(0.0);
                var em = vec3<f32>(0.0);
                var st_m = 0.0;
                var sc_m = vec3<f32>(0.0);
                var em_m = vec3<f32>(0.0);
                for (var k = 0u; k < n; k++) {
                    if (((mask >> k) & 1u) == 0u) { continue; }
                    let v = medium_eval(k, x);
                    st += v.extinction;
                    sc += v.albedo * v.extinction;
                    em += v.emission;
                    if (medium_at(k).a.w != 0u) {
                        st_m += v.extinction;
                        sc_m += v.albedo * v.extinction;
                        em_m += v.emission;
                    }
                }
                let ti = exp(-st * ds);
                // Over the step (constant medium): emitted + scattered radiance x (1 - e^-st dt) / st.
                let w = select(ds, (1.0 - ti) / st, st > 1e-6);
                var lin = vec3<f32>(0.0);
                // (No lookup where a step through a grid finds nothing: most of a grid is empty air.)
                if (camera && cache_on() && (st > 0.0 || !gridded)) {
                    // Looked up at a point jittered within a voxel: the accumulation filters the voxels instead of
                    // showing them as blocks. A jitter out of the medium finds a voxel no training point reached (dark):
                    // then the voxel of the point itself. Near the boundary that lost light, at every scattering order
                    // through the training's feedback (volume/furnace-live 0.931 of 1 without the emission clamp).
                    let vs = exp2(floor(log2(max(length(x - P.cam_pos.xyz) * CACHE_ANGLE, CACHE_MIN_VOXEL))) + VOLUME_FINE);
                    let jv = cache_point(x + (rng3(rng_sub(rd, (s << 16u) + j)) - 0.5) * vs);
                    lin = jv.rgb;
                    if (jv.w < CACHE_WARM) { lin = cache_point(x).rgb; }
                }
                r.light += r.tr * (sc * lin + em) * w;
                r.moving = vec2<f32>(r.moving.x * exp(-st_m * ds), r.moving.y + dot(r.tr * (sc_m * lin + em_m) * w, lw));
                r.tr *= ti;
            }
        }
        if (end >= tmax) { break; }
        t = end;
    }
    return r;
}

// A direction scattered from `d` by the Henyey-Greenstein phase function (its pdf: hg_phase(g, dot(d, result))).
fn sample_hg(d: vec3<f32>, g: f32) -> vec3<f32> {
    let r = rng2(rng_dim(D_PHASE));
    let u = r.x;
    var ct = 1.0 - 2.0 * u;
    if (abs(g) > 1e-3) {
        let q = (1.0 - g * g) / (1.0 - g + 2.0 * g * u);
        ct = (1.0 + g * g - q * q) / (2.0 * g);
    }
    let st = sqrt(max(0.0, 1.0 - ct * ct));
    let phi = 2.0 * PI * r.y;
    return basis(d) * vec3<f32>(st * cos(phi), st * sin(phi), ct);
}

// Direct light scattered at x along a path travelling in direction d (phase function HG g; shadow rays through the
// media), MIS against phase sampling where the light can also be hit: directional disks, emitters, the environment.
fn phase_direct(x: vec3<f32>, d: vec3<f32>, g: f32, rd: u32) -> vec3<f32> {
    var sum = vec3<f32>(0.0);
    for (var i = 0u; i < P.counts2.x; i++) {
        let li = light_at(i);
        let cos_max = li.dir.w;
        let u = rng2(rng_sub(rd, i));
        let cos_t = 1.0 - u.x * (1.0 - cos_max);
        let sin_t = sqrt(max(0.0, 1.0 - cos_t * cos_t));
        let phi = 2.0 * PI * u.y;
        let l = basis(-li.dir.xyz) * vec3<f32>(sin_t * cos(phi), sin_t * sin(phi), cos_t);
        if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; } // black: no shadow ray (direct_light)
        let ph = hg_phase(g, dot(l, d));
        let vis = light_vis(li.ext.w >= 0.5, x, l, INF, rng_sub(rd, 0x100u + i));
        if (any(vis > vec3<f32>(0.0))) {
            sum += li.color.rgb * tr3(vis) * ph * power_heuristic(1.0 / (2.0 * PI * (1.0 - cos_max)), ph);
        }
    }
    let nd = P.counts2.x;
    let nl = P.counts.x - nd;
    if (nl > 0u) {
        var wsum = 0.0;
        var pick = 0u;
        var pick_w = 0.0;
        var pick_ls: LS;
        for (var k = 0u; k < 3u; k++) {
            let r4 = rng4(rng_sub(rd, 0x200u + k));
            let idx = nd + min(u32(r4.x * f32(nl)), nl - 1u);
            let ls = local_light(light_at(idx), x, r4.yz);
            let wk = luminance(ls.c) * hg_phase(g, dot(ls.l, d));
            if (wk <= 0.0) { continue; }
            wsum += wk;
            if (r4.w * wsum < wk) {
                pick = idx;
                pick_w = wk;
                pick_ls = ls;
            }
        }
        if (pick_w > 0.0) {
            let vis = light_vis(light_at(pick).ext.w >= 0.5, x, pick_ls.sl, pick_ls.dist * 0.999, rng_sub(rd, 0x300u));
            if (any(vis > vec3<f32>(0.0))) { sum += pick_ls.c * tr3(vis) * hg_phase(g, dot(pick_ls.l, d)) * (wsum * f32(nl) / (3.0 * pick_w)); }
        }
    }
    if (emitters_on()) {
        mis_x = x;
        mis_n = vec3<f32>(0.0);
        let es = sample_emitter(x, vec3<f32>(0.0), rng_sub(rd, 0x400u));
        if (es.pdf_w > 0.0) {
            let vis = any_tr(x, es.l, es.dist * 0.999, rng_sub(rd, 0x401u));
            if (vis > 0.0) {
                let ph = hg_phase(g, dot(es.l, d));
                sum += es.le * ph * power_heuristic(es.pdf_w, ph) * es.w * tr1(vis);
            }
        }
    }
    if (P.counts2.y != 0u && (P.env.x > 0.5 || luminance(P.sky_color.rgb) > 0.0)) {
        let l = sample_env(rng_sub(rd, 0x500u));
        let pdf_e = env_pdf(l);
        if (pdf_e > 0.0) {
            let vis = sky_tr(x, l, rng_sub(rd, 0x501u));
            if (any(vis > vec3<f32>(0.0))) {
                let ph = hg_phase(g, dot(l, d));
                sum += env_radiance(l) * ph * power_heuristic(pdf_e, ph) / pdf_e * tr3(vis);
            }
        }
    }
    return sum;
}

// ------------------------------------------------------------------------------------------------
// Volume voxels of the radiance cache (translucent.wgsl, participating media in the live viewport).
// Lighting at points in the air (translucency now, participating media later): keyed by position alone
// (non-directional) and coarser than surface voxels at the same distance (UE's translucency lighting volume has ~0.5 m
// cells near the camera). Value: the mean radiance arriving from all directions, i.e. what a white isotropic scatterer
// there sends back. Two levels are trained together; lookups take the fine one once it is warm.
const VOLUME_FINE: f32 = 2.0;   // levels above the surface voxel at the same distance
const VOLUME_COARSE: f32 = 4.0;

fn cache_key_point(p: vec3<f32>, coarser: f32) -> vec2<u32> {
    let lvl = floor(log2(max(length(p - P.cam_pos.xyz) * CACHE_ANGLE, CACHE_MIN_VOXEL))) + coarser;
    let q = bitcast<vec3<u32>>(vec3<i32>(floor(p * exp2(-lvl))));
    // Side code 6: no surface side (surface voxels use 0..5).
    let tag = (u32(lvl + 64.0) << 3u) | 6u;
    let h = pcg(q.x ^ pcg(q.y ^ pcg(q.z ^ pcg(tag))));
    let c = pcg((q.x * 73856093u) ^ (q.y * 19349663u) ^ (q.z * 83492791u) ^ (tag * 2654435761u)) | 1u;
    return vec2<u32>(h, c);
}

// Mean incident radiance at p (w = history samples, 0: none yet).
fn cache_point(p: vec3<f32>) -> vec4<f32> {
    let f = cache_find(cache_key_point(p, VOLUME_FINE), false);
    var v = vec4<f32>(0.0);
    if (f != 0xffffffffu) { v = cache_val_load(f * 2u); }
    if (v.w >= CACHE_WARM) { return v; }
    let c = cache_find(cache_key_point(p, VOLUME_COARSE), false);
    if (c != 0xffffffffu) {
        let cv = cache_val_load(c * 2u);
        if (cv.w > v.w) { return cv; }
    }
    return v;
}

// Direct light at a point for an isotropic receiver (phase 1 / 4π): the directional lights (cone), the local lights
// and the sampled emitters (each resampled from a few candidates, one shadow ray). The environment and emission that
// no light sampling covers come from the sphere ray of `point_radiance`.
fn point_direct(x: vec3<f32>, rd: u32) -> vec3<f32> {
    let ph = 1.0 / (4.0 * PI);
    var sum = vec3<f32>(0.0);
    for (var i = 0u; i < P.counts2.x; i++) {
        let li = light_at(i);
        let cos_max = li.dir.w;
        let u = rng2(rng_sub(rd, i));
        let cos_t = 1.0 - u.x * (1.0 - cos_max);
        let sin_t = sqrt(max(0.0, 1.0 - cos_t * cos_t));
        let phi = 2.0 * PI * u.y;
        let l = basis(-li.dir.xyz) * vec3<f32>(sin_t * cos(phi), sin_t * sin(phi), cos_t);
        if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; } // black: no shadow ray (direct_light)
        let vis = light_vis(li.ext.w >= 0.5, x, l, INF, rng_sub(rd, 0x100u + i));
        if (any(vis > vec3<f32>(0.0))) { sum += li.color.rgb * ph * tr3(vis); }
    }
    let nd = P.counts2.x;
    let nl = P.counts.x - nd;
    if (nl > 0u) {
        var wsum = 0.0;
        var pick = 0u;
        var pick_w = 0.0;
        var pick_ls: LS;
        for (var k = 0u; k < 3u; k++) {
            let r4 = rng4(rng_sub(rd, 0x200u + k));
            let idx = nd + min(u32(r4.x * f32(nl)), nl - 1u);
            let ls = local_light(light_at(idx), x, r4.yz);
            let wk = luminance(ls.c);
            if (wk <= 0.0) { continue; }
            wsum += wk;
            if (r4.w * wsum < wk) {
                pick = idx;
                pick_w = wk;
                pick_ls = ls;
            }
        }
        if (pick_w > 0.0) {
            let vis = light_vis(light_at(pick).ext.w >= 0.5, x, pick_ls.sl, pick_ls.dist * 0.999, rng_sub(rd, 0x300u));
            if (any(vis > vec3<f32>(0.0))) { sum += pick_ls.c * ph * (wsum * f32(nl) / (3.0 * pick_w)) * tr3(vis); }
        }
    }
    if (emitters_on()) {
        var wsum = 0.0;
        var pick: ES;
        var pick_t = 0.0;
        for (var c = 0u; c < 4u; c++) {
            mis_x = x;
            mis_n = vec3<f32>(0.0);
            let es = sample_emitter(x, vec3<f32>(0.0), rng_sub(rd, 0x400u + c));
            if (es.pdf_w <= 0.0) { continue; }
            let t = luminance(es.le);
            let w = t / es.pdf_w;
            if (w <= 0.0) { continue; }
            wsum += w;
            if (rng1(rng_sub(rd, 0x410u + c)) * wsum < w) {
                pick = es;
                pick_t = t;
            }
        }
        if (pick_t > 0.0) {
            let vis = any_tr(x, pick.l, pick.dist * 0.999, rng_sub(rd, 0x420u));
            if (vis > 0.0) { sum += pick.le * ph * (wsum / (4.0 * pick_t)) * tr1(vis); }
        }
    }
    return sum;
}

// One estimate of the mean incident radiance at x: the direct light, plus one uniformly sampled direction for the
// rest (the environment, emission that light sampling does not cover, and light reflected off the surface it hits:
// that surface's cached irradiance when warm, else its direct light).
fn point_radiance(x: vec3<f32>) -> vec3<f32> {
    cur_depth = 2u;
    let e = point_direct(x, rng_dim(D_VOL_LIGHT));
    return e + point_sphere(x, false);
}

// A training estimate for the volume voxels: point_radiance with the firefly clamp (`clamp_v`, luminance) on the sphere
// ray alone. Direct light is sampled and needs no clamp; clamping it lost the light of bright lamps and suns
// (volume/box-sun-scatter-live: 1000 lux at EV100 0 read 21 % low).
fn point_radiance_train(x: vec3<f32>, clamp_v: f32) -> vec3<f32> {
    cur_depth = 2u;
    let e = point_direct(x, rng_dim(D_VOL_LIGHT));
    // Scattering orders past the first only when the scene allows bounces (max bounces 0: direct light only).
    var r = point_sphere(x, media_voxels && P.counts.z > 0u);
    let lum = luminance(r);
    if (lum > clamp_v) { r *= clamp_v / lum; }
    return e + r;
}

// The sphere-ray part of point_radiance. In the media voxel training (`media`) the ray crosses the media too: it is
// attenuated and gathers their in-scattered light from the voxels. Trained frame after frame, that feedback adds every
// scattering order, so the voxels converge to multiple scattering (a lamp inside a sphere of albedo-0.9 medium read 22 %
// of the offline reference with single scattering alone).
fn point_sphere(x: vec3<f32>, media: bool) -> vec3<f32> {
    let r2 = rng2(rng_dim(D_VOXEL));
    let z = 1.0 - 2.0 * r2.x;
    let r = sqrt(max(0.0, 1.0 - z * z));
    let phi = 2.0 * PI * r2.y;
    var l = vec3<f32>(r * cos(phi), r * sin(phi), z);
    var o = x;
    var light = vec3<f32>(0.0);
    var tr = 1.0;
    for (var k = 0u; k < 4u; k++) {
        let hit = trace(o, l, INF, TRACE_CLOSEST);
        if (media) {
            let mm = media_march(o, l, select(hit.t, 1.0e30, hit.tri == 0xffffffffu), true, rng_sub(rng_dim(D_VOXEL), 0x20u + k));
            light += tr * mm.light;
            tr *= mm.tr;
        }
        // In the media training, glass (a water surface over its body) passes the ray or reflects it, as the paths'
        // BSDF does (transmission share 1 - E_spec, none past the critical angle): stopped there, the voxels under
        // water saw neither the sky through the surface nor what it reflects back (a white furnace read 0.29).
        if (media && has(F_GLASS) && hit.tri != 0xffffffffu && k < 3u) {
            let g = glass_hit(hit, l, hit.t);
            if (g.share > 0.0) {
                let p = o + l * hit.t;
                if (g.tir || rng1(rng_sub(rng_dim(D_VOXEL), 0x10u + k)) >= g.share) { l = reflect(l, g.ng); }
                o = offset_origin(p, select(g.ng, -g.ng, dot(g.ng, l) < 0.0));
                continue;
            }
        }
        return light + tr * sphere_hit(o, l, hit);
    }
    return light;
}

// Light arriving at x along l from the sphere ray's hit (the environment where it hits nothing).
fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
    var e = vec3<f32>(0.0);
    if (hit.tri == 0xffffffffu) {
        return env_radiance(l);
    }
    cur_depth = 3u;
    let s = surface(x, l, hit, hit.t * 0.05);
    // Emission that emitter sampling covers is in the direct part (its MIS weight against any other pdf is below 1).
    mis_x = x;
    mis_n = vec3<f32>(0.0);
    if (any(s.emissive > vec3<f32>(0.0)) && (s.front || !s.card) && emit_mis(hit, l, 1.0 / (4.0 * PI)) >= 1.0) {
        e += s.emissive;
    }
    if (s.card) { return e; }
    let c = cache_get(s, false);
    var irr = c.rgb;
    if (!cache_on() || c.w < CACHE_WARM) {
        nee_alone = true;
        irr = direct_light(s, white_lobes(), -l);
        nee_alone = false;
    }
    return e + cache_reflectance(lobes(s, max(dot(s.n, -l), 1e-4))) * irr;
}

// ------------------------------------------------------------------------------------------------
// What a live trace leaves the live passes (live.wgsl).

// Group 1, the buffers the kernel writes, used through the functions below in every layout:
//  - refl: reflection resolve inputs (live; live.wgsl `refl`), 2 per traced pixel: the camera hit's specular-lobe ray
//    (radiance it brought back, its lobe pdf; pdf 0 = the pixel sampled another lobe), (specular albedo E at the hit,
//    octahedral ray direction). Neighbours reuse each other's rays weighted by their own BRDF (Lumen / SSSR);
//  - motion_out: live motion vectors per traced pixel: where the camera hit was the previous frame, as a world-space
//    offset (w = 1: on a moving triangle);
//  - direct_out: live deterministic direct light per traced pixel (`dl_det` at the camera hit; w: the light it
//    reports, "Light tiles");
//  - light_lists: the light tiles' lists, 64 vec4s a tile, as the live pass `light_tiles` made them last frame;
//  - first_hits: a live frame's camera hits, 2 per traced pixel (`first_store`): `first_hit` writes them, `main`
//    starts its paths from them;
//  - cache_keys, cache_acc, cache_val: the radiance cache (below, at `cache_on`);
//  - loop_guard_trips: the loop guard's count (first word: the invocations a loop of which was stopped).
@if(merged) {
    // The merged layout (merged.rs: a browser's eight storage buffers): one buffer (gpu.rs `KernelBufs`; heap.rs
    // `Live` places its parts). The radiance cache's atomic words and the loop guard's count are at fixed places (the
    // cache's size is the kernel's own constant); the vec4 arrays follow as the sections of `vecs`, each from the
    // vec4 `P.live_first` names and as long as `P.live_len` says, so a view of another size is the same kernel. What
    // the live passes read of it they bind as buffers of their own (a section starts at a multiple of 256 bytes).
    struct MergedLive {
        cache_keys: array<atomic<u32>, CACHE_SIZE>,
        @align(256) cache_acc: array<atomic<u32>, CACHE_SIZE * 8u>,
        @align(256) @size(512) loop_guard_trips: array<atomic<u32>, GUARD_WORDS>,
        @align(256) vecs: array<vec4<f32>>,
    };
    @group(1) @binding(1) var<storage, read_write> ML: MergedLive;
    fn refl_len() -> u32 { return P.live_len.x; }
    fn refl_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[0].y + i]; }
    fn refl_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].y + i] = v; }
    fn motion_len() -> u32 { return P.live_len.y; }
    fn motion_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[0].z + i]; }
    fn motion_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].z + i] = v; }
    fn direct_len() -> u32 { return P.live_len.z; }
    fn direct_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[0].w + i]; }
    fn direct_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].w + i] = v; }
    fn lists_len() -> u32 { return P.live_len.w; }
    fn list_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[1].x + i]; }
    fn first_len() -> u32 { return P.live_first[1].z; }
    fn first_vec_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[1].y + i]; }
    fn first_vec_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[1].y + i] = v; }
    fn cache_key_load(i: u32) -> u32 { return atomicLoad(&ML.cache_keys[i]); }
    fn cache_key_claim(i: u32, k: u32) -> bool { let r = atomicCompareExchangeWeak(&ML.cache_keys[i], 0u, k); return r.exchanged || r.old_value == k; }
    fn cache_key_clear(i: u32) { atomicStore(&ML.cache_keys[i], 0u); }
    fn cache_acc_add(i: u32, v: u32) -> u32 { return atomicAdd(&ML.cache_acc[i], v); }
    fn cache_acc_load(i: u32) -> u32 { return atomicLoad(&ML.cache_acc[i]); }
    fn cache_acc_clear(i: u32) { atomicStore(&ML.cache_acc[i], 0u); }
    // (The cache's values are `vecs`' first section: from vec4 0.)
    fn cache_val_load(i: u32) -> vec4<f32> { return ML.vecs[i]; }
    fn cache_val_store(i: u32, v: vec4<f32>) { ML.vecs[i] = v; }
    @if(guard) fn loop_guard_stopped() { atomicAdd(&ML.loop_guard_trips[0], 1u); }
} @else {
    @group(1) @binding(1) var<storage, read_write> cache_keys: array<atomic<u32>>;
    @group(1) @binding(2) var<storage, read_write> cache_acc: array<atomic<u32>>;
    @group(1) @binding(3) var<storage, read_write> cache_val: array<vec4<f32>>;
    @group(1) @binding(4) var<storage, read> light_lists: array<vec4<f32>>;
    @group(1) @binding(5) var<storage, read_write> refl: array<vec4<f32>>;
    @group(1) @binding(6) var<storage, read_write> motion_out: array<vec4<f32>>;
    @group(1) @binding(7) var<storage, read_write> direct_out: array<vec4<f32>>;
    fn refl_len() -> u32 { return arrayLength(&refl); }
    fn refl_load(i: u32) -> vec4<f32> { return refl[i]; }
    fn refl_store(i: u32, v: vec4<f32>) { refl[i] = v; }
    fn motion_len() -> u32 { return arrayLength(&motion_out); }
    fn motion_load(i: u32) -> vec4<f32> { return motion_out[i]; }
    fn motion_store(i: u32, v: vec4<f32>) { motion_out[i] = v; }
    fn direct_len() -> u32 { return arrayLength(&direct_out); }
    fn direct_load(i: u32) -> vec4<f32> { return direct_out[i]; }
    fn direct_store(i: u32, v: vec4<f32>) { direct_out[i] = v; }
    fn lists_len() -> u32 { return arrayLength(&light_lists); }
    fn list_load(i: u32) -> vec4<f32> { return light_lists[i]; }
    fn cache_key_load(i: u32) -> u32 { return atomicLoad(&cache_keys[i]); }
    fn cache_key_claim(i: u32, k: u32) -> bool { let r = atomicCompareExchangeWeak(&cache_keys[i], 0u, k); return r.exchanged || r.old_value == k; }
    fn cache_key_clear(i: u32) { atomicStore(&cache_keys[i], 0u); }
    fn cache_acc_add(i: u32, v: u32) -> u32 { return atomicAdd(&cache_acc[i], v); }
    fn cache_acc_load(i: u32) -> u32 { return atomicLoad(&cache_acc[i]); }
    fn cache_acc_clear(i: u32) { atomicStore(&cache_acc[i], 0u); }
    fn cache_val_load(i: u32) -> vec4<f32> { return cache_val[i]; }
    fn cache_val_store(i: u32, v: vec4<f32>) { cache_val[i] = v; }
    @if(guard) {
        @group(1) @binding(8) var<storage, read_write> loop_guard_trips: array<atomic<u32>, GUARD_WORDS>;
        fn loop_guard_stopped() { atomicAdd(&loop_guard_trips[0], 1u); }
    }
    // The pixels of this sample that `finish` ends (below `cache_end`): their number, then a record each.
    struct Deferred { n: atomic<u32>, recs: array<vec4<u32>> };
    @group(1) @binding(9) var<storage, read_write> deferred: Deferred;
    @group(1) @binding(10) var<storage, read_write> first_hits: array<vec4<f32>>;
    fn first_len() -> u32 { return arrayLength(&first_hits); }
    fn first_vec_load(i: u32) -> vec4<f32> { return first_hits[i]; }
    fn first_vec_store(i: u32, v: vec4<f32>) { first_hits[i] = v; }
}

// A camera hit as the first-hit pass leaves it: (t, u, v, triangle low) (triangle high, instance low, instance high,
// part + 65536 x its mirror chain). The integers as 16-bit halves: a float keeps those exactly, and its bits are not
// an integer's to keep. The chain: how many mirrors the pixel's ray goes on through (`mirror_alone`); what the last
// one shows is the surface the pixel has for the passes after (`Chain`).
struct FirstHit { hit: Hit, chain: u32 };
fn hit_store(at: u32, h: Hit, chain: u32) {
    first_vec_store(at, vec4<f32>(h.t, h.u, h.v, f32(h.tri & 0xffffu)));
    first_vec_store(at + 1u, vec4<f32>(f32(h.tri >> 16u), f32(h.inst & 0xffffu), f32(h.inst >> 16u), f32(h.part | (chain << 16u))));
}
fn hit_load(at: u32) -> FirstHit {
    let a = first_vec_load(at);
    let b = first_vec_load(at + 1u);
    let pc = u32(b.w);
    return FirstHit(Hit(a.x, u32(a.w) | (u32(b.x) << 16u), a.y, a.z, u32(b.y) | (u32(b.z) << 16u), pc & 0xffffu), pc >> 16u);
}
fn first_store(pix: u32, h: Hit, chain: u32) { hit_store(pix * 2u, h, chain); }
fn first_load(pix: u32) -> FirstHit { return hit_load(pix * 2u); }
// The distance to the camera hit itself (0: none), whatever its ray went on to: what stands before a mirror is nearer
// than this.
fn first_depth(pix: u32) -> f32 {
    let a = first_vec_load(pix * 2u);
    let b = first_vec_load(pix * 2u + 1u);
    return select(a.x, 0.0, a.w == 65535.0 && b.x == 65535.0);
}
// A mirror chain as the first pass leaves it where there is one, six vec4s a traced pixel after the hits (a scene with
// F_MIRROR has the room): what the paths start from in the camera hit's place.
//  - `seen`, `o`: the hit the last mirror shows and where its ray starts; the ray's direction is the camera ray's
//    turned back through `xf`;
//  - `xf`: what takes a direction at the surface shown to where the pixel sees it, each mirror's reflection in turn
//    from the camera's (orthonormal: two columns kept, the third their cross product, turned for an odd chain);
//  - `way`: the distance to the last mirror, along the camera ray and from mirror to mirror;
//  - `weight`, `light`: what the mirrors and the segments that end at one leave of the light (the mirrors' Fresnel
//    reflectance; the fog's and the haze's attenuation, water's between mirrors), and the light those add on the way
//    (the mirrors' own emission, the fog's and the haze's ambient light). The segment the last mirror shows is
//    `main`'s first: it has there what a camera's segment has.
struct Chain { seen: Hit, o: vec3<f32>, way: f32, xf: mat3x3<f32>, weight: vec3<f32>, light: vec3<f32> };
const CHAIN_VECS: u32 = 6u;
fn chain_at(pix: u32) -> u32 { return 2u * P.size.x * P.size.y + pix * CHAIN_VECS; }
fn chain_store(pix: u32, c: Chain) {
    let at = chain_at(pix);
    hit_store(at, c.seen, 0u);
    first_vec_store(at + 2u, vec4<f32>(c.o, c.way));
    first_vec_store(at + 3u, vec4<f32>(c.xf[0], c.weight.x));
    first_vec_store(at + 4u, vec4<f32>(c.xf[1], c.weight.y));
    first_vec_store(at + 5u, vec4<f32>(c.light, c.weight.z));
}
fn chain_load(pix: u32, chain: u32) -> Chain {
    let at = chain_at(pix);
    let a = first_vec_load(at + 2u);
    let b = first_vec_load(at + 3u);
    let c = first_vec_load(at + 4u);
    let d = first_vec_load(at + 5u);
    return Chain(hit_load(at).hit, a.xyz, a.w, mat3x3<f32>(b.xyz, c.xyz, cross(b.xyz, c.xyz) * select(1.0, -1.0, (chain & 1u) == 1u)), vec3<f32>(b.w, c.w, d.w), d.xyz);
}
// The longest chain (and all but one of a path's bounces at most: the surface it shows is lit and has its bounce).
const MIRROR_CHAIN: u32 = 8u;

// The surface a live path's camera hit has (the one a mirror chain shows), as `main` evaluated it, with what a pass
// after needs to light it without reading its material again: four vec4s a traced pixel after the hits and the
// chains (gpu.rs `SURFACE_BYTES`; a scene with F_MIRROR has the chains' room before them).
//  - (place, shading normal) (base colour, geometric normal) (`thr`, the pixel's list of the light tiles and its
//    length) (roughness and metalness, specular and transmission, coat's roughness and coat, flags and the index of
//    refraction);
//  - `thr`: what reaches the camera of the light it reflects (a chain's weight, the fog's and the haze's
//    attenuation);
//  - the place, the colour and `thr` as they are; a normal as an octahedral pair of 12 bits a side; the material's
//    numbers in the bits a float's whole number keeps (24): a roughness 16, the index of refraction 16 over 1..5,
//    the others 8 or 12;
//  - not its emission, which no light sample asks for, nor the way to the viewer, which the pass has from the
//    pixel's camera ray (and a chain's turns: `SURF_CHAIN`, `SURF_ODD`).
// `lit`: `main` reached the hit's lighting this frame (not a pixel of sky, an emitter's card, a path without a bounce).
struct Lit { s: Surface, thr: vec3<f32>, list: u32, list_n: u32, chain: bool, odd: bool, lit: bool };
const SURF_VECS: u32 = 4u;
const SURF_LIT: u32 = 1u;
const SURF_FRONT: u32 = 2u;
const SURF_ANIM: u32 = 4u;
const SURF_CHAIN: u32 = 8u;
const SURF_ODD: u32 = 16u;
fn surf_at(pix: u32) -> u32 { return (2u + select(0u, CHAIN_VECS, has(F_MIRROR))) * P.size.x * P.size.y + pix * SURF_VECS; }
// (Where the frame says it runs the pass, `P.jitter.w`, and there are such lights now: emitters that are on, more
// shadow-casting local lights than a camera hit sums exactly. Else the paths leave no surface and the pass has
// nothing to do: a sunlit garden paid 9 % of its frame for both, a softbox over glass 4 % for a light it sums
// exactly, a house by day 3 % for lamps that are off. The buffer's length alone does not say that the pass runs: a
// view traced at half its size has the room whatever was asked for.)
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);
    return round(saturate(a) * (f32(1u << (24u - bits)) - 1.0)) * nb + round(saturate(b) * (nb - 1.0));
}
fn pair_unpack(v: f32, bits: u32) -> vec2<f32> {
    let nb = f32(1u << bits);
    let hi = floor(v / nb);
    return vec2<f32>(hi / (f32(1u << (24u - bits)) - 1.0), (v - hi * nb) / (nb - 1.0));
}
fn dir_pack(n: vec3<f32>) -> f32 {
    let p = n.xy / (abs(n.x) + abs(n.y) + abs(n.z));
    let q = select(p, (1.0 - abs(p.yx)) * select(vec2<f32>(-1.0), vec2<f32>(1.0), p >= vec2<f32>(0.0)), n.z < 0.0);
    return pair_pack(q.x * 0.5 + 0.5, q.y * 0.5 + 0.5, 12u);
}
fn dir_unpack(v: f32) -> vec3<f32> {
    let q = pair_unpack(v, 12u) * 2.0 - 1.0;
    let z = 1.0 - abs(q.x) - abs(q.y);
    let t = max(-z, 0.0);
    return normalize(vec3<f32>(q - select(vec2<f32>(-t), vec2<f32>(t), q >= vec2<f32>(0.0)), z));
}
fn surf_none(pix: u32) { first_vec_store(surf_at(pix) + 3u, vec4<f32>(0.0)); }
fn surf_store(pix: u32, s: Surface, thr: vec3<f32>, chain: u32) {
    let at = surf_at(pix);
    first_vec_store(at, vec4<f32>(s.p, dir_pack(s.n)));
    first_vec_store(at + 1u, vec4<f32>(s.base, dir_pack(s.ng)));
    // (The list's first entry is a multiple of LT_LIST, its length under it: one number, as `finish`'s record has it.)
    first_vec_store(at + 2u, vec4<f32>(thr, f32(lt_list + lt_list_n)));
    let fl = SURF_LIT | select(0u, SURF_FRONT, s.front) | select(0u, SURF_ANIM, s.anim) | select(0u, SURF_CHAIN, chain > 0u) | select(0u, SURF_ODD, (chain & 1u) == 1u);
    first_vec_store(at + 3u, vec4<f32>(pair_pack(s.roughness, s.metallic, 8u), pair_pack(s.specular, s.transmission, 12u), pair_pack(s.coat_rough, s.coat, 8u),
                                         f32(fl) * 65536.0 + round(saturate((s.ior - 1.0) * 0.25) * 65535.0)));
}
fn surf_load(pix: u32) -> Lit {
    let at = surf_at(pix);
    let d = first_vec_load(at + 3u);
    let fl = u32(d.w / 65536.0);
    var s: Surface;
    if ((fl & SURF_LIT) == 0u) { return Lit(s, vec3<f32>(0.0), 0u, 0u, false, false, false); }
    let a = first_vec_load(at);
    let b = first_vec_load(at + 1u);
    let c = first_vec_load(at + 2u);
    let rm = pair_unpack(d.x, 8u);
    let st = pair_unpack(d.y, 12u);
    let cc = pair_unpack(d.z, 8u);
    s.p = a.xyz;
    s.n = dir_unpack(a.w);
    s.base = b.xyz;
    s.ng = dir_unpack(b.w);
    s.roughness = rm.x;
    s.metallic = rm.y;
    s.specular = st.x;
    s.transmission = st.y;
    s.coat_rough = cc.x;
    s.coat = cc.y;
    s.ior = 1.0 + 4.0 * (d.w - f32(fl) * 65536.0) / 65535.0;
    s.emissive = vec3<f32>(0.0);
    s.front = (fl & SURF_FRONT) != 0u;
    s.card = false;
    s.anim = (fl & SURF_ANIM) != 0u;
    let list = u32(c.w);
    return Lit(s, c.xyz, list & ~(LT_LIST - 1u), list & (LT_LIST - 1u), (fl & SURF_CHAIN) != 0u, (fl & SURF_ODD) != 0u, true);
}

// The loop guard (gpu.rs `loop_guard_of`; docs/RUNTIME.md "The engine in a browser"): every loop of the kernel, the
// scene's functions' too, begins with `if (loop_guard()) { break; }` (gpu.rs `guard_loops`, a pass over the variant's
// syntax tree). The kernel's traversals follow indices they read from buffers and end only on sound data; with the
// guard a dispatch always ends: an invocation's iterations are counted over all its loops together, past
// LOOP_GUARD_LIMIT it leaves them, and the invocations stopped are counted for the renderer to read back.
@if(guard) var<private> LOOP_GUARD_N: u32 = 0u;
@if(guard) fn loop_guard() -> bool {
    LOOP_GUARD_N += 1u;
    if (LOOP_GUARD_N == LOOP_GUARD_LIMIT + 1u) { loop_guard_stopped(); }
    return LOOP_GUARD_N > LOOP_GUARD_LIMIT;
}

fn resolve_bound() -> bool { return LIVE && refl_len() >= 2u * P.size.x * P.size.y; }
fn resolve_on() -> bool { return resolve_bound() && P.motion.y == 0.0; }

// Density of l under the base specular lobe alone (VNDF sampling).
fn pdf_spec(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> f32 {
    let nov = max(dot(s.n, v), 1e-4);
    let noh = max(dot(s.n, normalize(v + l)), 0.0);
    return g1(lb.a2, nov) * d_ggx(lb.a2, noh) / (4.0 * nov);
}

// A unit vector, octahedral (snorm16x2).
fn oct_enc(n: vec3<f32>) -> u32 {
    let p = n.xy / (abs(n.x) + abs(n.y) + abs(n.z));
    let q = select(p, (1.0 - abs(p.yx)) * select(vec2<f32>(-1.0), vec2<f32>(1.0), p >= vec2<f32>(0.0)), n.z < 0.0);
    return pack2x16snorm(q);
}

// ------------------------------------------------------------------------------------------------
// World-space radiance cache (live; docs/ROADMAP.md § 1, step 1). Spatially hashed voxels, sized by distance to the
// camera (CACHE_ANGLE, rounded down to a power of two), x 6 normal directions. Each holds the cosine-weighted incident
// radiance (irradiance / π, direct + indirect) at its surfaces: a surface that ends a path there reflects its diffuse +
// directional specular albedo times that. Training paths start at those surfaces: white-Lambert next-event estimation
// plus one cosine-sampled ray per vertex, CACHE_DEPTH vertices deep, ending in the cache again (so it holds every
// bounce); each vertex's estimate is added. Sums are fixed point with stochastic rounding (`cache_acc`);
// `cache_resolve` folds them into `cache_val` once per frame.

const CACHE_SIZE: u32 = 262144u;     // entries, a power of two (gpu.rs CACHE_SIZE)
const CACHE_PROBE: u32 = 8u;         // linear probing window
const CACHE_ANGLE: f32 = 0.02;       // voxel size / distance to the camera
const CACHE_MIN_VOXEL: f32 = 0.0625; // m
const CACHE_FACE: f32 = 0.0625;      // a surface's key is taken this far (in voxels) in front of it
const CACHE_WARM: f32 = 4.0;         // samples before lookups trust an entry
const CACHE_TRAIN_MASK: u32 = 7u;    // 1 in 8 tiles of 8x4 pixels (one SIMD group: the others really skip) per frame
const CACHE_FRAME_CAP: u32 = 255u;   // samples per entry per frame (fixed-point headroom)
const CACHE_TRAIN_CLAMP: f32 = 4.0;  // training samples' clamp, in indirect clamps (cache_fixed's headroom)
const CACHE_DEPTH: u32 = 2u;         // vertices per training path
const CACHE_EVICT: f32 = 120.0;      // frames without samples before an entry is freed

// cache_keys[i]: checksum of the voxel key (0 = free). cache_acc[8i ..]: this frame's sums (fixed point) of the total
// r, g, b, of its indirect part r, g, b, and the sample count. cache_val[2i] = (irradiance / π, history samples),
// cache_val[2i + 1] = (its indirect part: all but the lights' samples there, the sky's light in it; frames since the
// last sample).
// (Declared with the trace's outputs, group 1, above `resolve_bound`.)

fn cache_on() -> bool { return LIVE && P.cache.x > 0.5; }

// (slot hash, checksum) of the voxel holding p, on the side ng faces most.
fn cache_key(p: vec3<f32>, ng: vec3<f32>) -> vec2<u32> {
    return cache_key_at(p, ng, 0.0);
}

// The key `step` levels coarser (negative: finer) than p's own. The voxel is the one just in front of the surface
// (CACHE_FACE): a floor at y = 0 lies on a face of every level's voxels, and the rounding of its hits put them on
// either side, two keys sharing its samples (a floor's bounce 16 % dark at 160 x 90 for 11 % a little higher up).
fn cache_key_at(p: vec3<f32>, ng: vec3<f32>, step: f32) -> vec2<u32> {
    let lvl = floor(log2(max(length(p - P.cam_pos.xyz) * CACHE_ANGLE, CACHE_MIN_VOXEL))) + step;
    let q = bitcast<vec3<u32>>(vec3<i32>(floor(p * exp2(-lvl) + ng * CACHE_FACE)));
    let a = abs(ng);
    let axis = select(select(2u, 1u, a.y >= a.z), 0u, a.x >= a.y && a.x >= a.z);
    let neg = select(select(ng.z, ng.y, axis == 1u), ng.x, axis == 0u) < 0.0;
    let tag = (u32(lvl + 64.0) << 3u) | (axis * 2u + u32(neg));
    let h = pcg(q.x ^ pcg(q.y ^ pcg(q.z ^ pcg(tag))));
    let c = pcg((q.x * 73856093u) ^ (q.y * 19349663u) ^ (q.z * 83492791u) ^ (tag * 2654435761u)) | 1u;
    return vec2<u32>(h, c);
}

// Slot of voxel `k`; 0xffffffff when absent (or, inserting, when its probe window is full). Lookups scan the whole
// window: eviction leaves holes in it.
fn cache_find(k: vec2<u32>, insert: bool) -> u32 {
    var free = 0xffffffffu;
    for (var i = 0u; i < CACHE_PROBE; i++) {
        let s = (k.x + i) & (CACHE_SIZE - 1u);
        let c = cache_key_load(s);
        if (c == k.y) { return s; }
        if (c == 0u && free == 0xffffffffu) { free = s; }
    }
    if (!insert || free == 0xffffffffu) { return 0xffffffffu; }
    if (cache_key_claim(free, k.y)) { return free; }
    return 0xffffffffu;
}

// Cached irradiance / π at the surface (or its indirect part), w = history samples (0: none).
fn cache_get(s: Surface, indirect: bool) -> vec4<f32> {
    var best = cache_entry(cache_key(s.p, s.ng), indirect);
    if (best.w >= CACHE_WARM) { return best; }
    // Voxel sizes follow the distance to the camera in powers of two: a surface the camera comes closer to (or moves
    // away from) gets a new, cold voxel while the one a level coarser (finer) is warm. Use the warmer meanwhile; the
    // training tiles warm the new one. Pixels on cold voxels traced a fresh estimate each: Bistro's camera path cost
    // 2 ms more trace moving than held still at the same poses (now only after a reset or a cut, see the path).
    for (var k = 0u; k < 2u; k++) {
        let e = cache_entry(cache_key_at(s.p, s.ng, select(-1.0, 1.0, k == 0u)), indirect);
        if (e.w > best.w) { best = e; }
    }
    // Still cold: the coarser levels every training sample is added to beside its own (`cache_train`). A voxel with
    // 16 or 256 times the area is seldom without samples where the own one is: far from the camera's paths, at low
    // resolutions. (Without them such a lookup read black past a view's first frames: a floor's bounce 11 % dark
    // at 160 x 90; SHaRC goes on tracing there, GI-1.0 reads a coarser mip.)
    if (best.w < CACHE_WARM) {
        let e = cache_entry(cache_key_at(s.p, s.ng, 2.0), indirect);
        if (e.w > best.w) { best = e; }
    }
    if (best.w < CACHE_WARM) {
        let e = cache_entry(cache_key_at(s.p, s.ng, 4.0), indirect);
        if (e.w > best.w) { best = e; }
    }
    return best;
}

fn cache_entry(k: vec2<u32>, indirect: bool) -> vec4<f32> {
    let i = cache_find(k, false);
    if (i == 0xffffffffu) { return vec4<f32>(0.0); }
    let v = cache_val_load(i * 2u);
    if (indirect) { return vec4<f32>(cache_val_load(i * 2u + 1u).rgb, v.w); }
    return v;
}

// Fixed point: 2^21 units per firefly clamp, so 255 samples of up to 4 clamps per channel fit 32 bits.
fn cache_fixed(e: vec3<f32>, rd: u32) -> vec3<u32> {
    return vec3<u32>(min(e, vec3<f32>(4.0 * P.misc.x)) * (2097152.0 / P.misc.x) + rng3(rd));
}

fn cache_add(i: u32, total: vec3<f32>, indirect: vec3<f32>) {
    if (i == 0xffffffffu || non_finite(total) || non_finite(indirect)) { return; }
    if (cache_acc_add(i * 8u + 6u, 1u) >= CACHE_FRAME_CAP) { return; }
    let a = cache_fixed(total, rng_sub(rng_dim(D_CACHE), i * 2u));
    let b = cache_fixed(indirect, rng_sub(rng_dim(D_CACHE), i * 2u + 1u));
    cache_acc_add(i * 8u, a.x);
    cache_acc_add(i * 8u + 1u, a.y);
    cache_acc_add(i * 8u + 2u, a.z);
    cache_acc_add(i * 8u + 3u, b.x);
    cache_acc_add(i * 8u + 4u, b.y);
    cache_acc_add(i * 8u + 5u, b.z);
}

// White Lambertian lobes: lighting gathered with them is irradiance / π, and a cosine-sampled ray has weight 1.
fn white_lobes() -> Lobes {
    var l: Lobes;
    l.diffuse = vec3<f32>(1.0);
    l.f0 = vec3<f32>(0.0);
    l.f90 = vec3<f32>(0.0);
    l.w = vec3<f32>(1.0);
    l.e_spec = vec3<f32>(0.0);
    l.kd = vec3<f32>(1.0);
    l.a2 = 1.0;
    l.p_spec = 0.0;
    l.coat_alpha = 1.0;
    return l;
}

// What a surface reflects of irradiance / π toward the viewer, the lighting taken as uniform over the hemisphere:
// diffuse + directional specular albedo, under the coat's (as `eval_bsdf_k` layers them; without the coat's term a
// coated surface reflected e_coat (1 - the rest) too little).
fn cache_reflectance(lb: Lobes) -> vec3<f32> {
    var r = lb.diffuse * lb.kd + lb.e_spec;
    if (has(F_GLASS)) { r += vec3<f32>(lb.e_glass); }
    if (has(F_COAT)) { return r * (1.0 - lb.e_coat) + lb.e_coat; }
    return r;
}

struct Fresh { total: vec3<f32>, direct: vec3<f32> };

// A fresh irradiance / π estimate at surface s0 (reached along d0; ray-cone width there + spread) and its direct part,
// by a path of `depth` (1 ..= CACHE_DEPTH) vertices, also added to the cache at each of them.
// `insert`: whether the path's voxels are inserted when absent (training tiles), or only trained when present (a
// cold pixel's fresh estimate).
fn cache_train(s0: Surface, d0: vec3<f32>, cone0: vec2<f32>, depth: u32, insert: bool) -> Fresh {
    var slot: array<u32, CACHE_DEPTH>;
    var coarse: array<u32, 4>; // each vertex's voxels two and four levels coarser (4 and 16 times the size)
    // Per vertex: its direct light; that + the emission / sky its ray brought back; what the next vertex reflects.
    var direct: array<vec3<f32>, CACHE_DEPTH>;
    var gather: array<vec3<f32>, CACHE_DEPTH>;
    var refl: array<vec3<f32>, CACHE_DEPTH>;
    let wl = white_lobes();
    RNG_PATH = 1u;
    var s = s0;
    var d = d0;
    var cone = cone0;
    var tail = vec3<f32>(0.0);
    var n = 0u;
    for (var k = 0u; k < depth; k++) {
        cur_depth = 2u + k;
        let v = -d;
        slot[k] = cache_find(cache_key(s.p, s.ng), insert);
        coarse[2u * k] = cache_find(cache_key_at(s.p, s.ng, 2.0), insert);
        coarse[2u * k + 1u] = cache_find(cache_key_at(s.p, s.ng, 4.0), insert);
        // `direct`: the lights' samples (not the sky's): what a surface seen in a reflection takes afresh.
        lights_only = true;
        var g = direct_light(s, wl, v);
        lights_only = false;
        direct[k] = g;
        if (env_sampled()) { g += env_light(s, wl, v, offset_origin(s.p, s.ng)); }
        refl[k] = vec3<f32>(0.0);
        gather[k] = g;
        n = k + 1u;
        let l = sample_bsdf(s, wl, v);
        let pdf = pdf_bsdf(s, wl, v, l);
        if (pdf <= 0.0) { break; }
        let o = offset_origin(s.p, s.ng);
        let hit = trace(o, l, INF, TRACE_CLOSEST);
        let miss = hit.tri == 0xffffffffu;
        // Height fog on the segment (attenuation + ambient inscattering; no lit volumetrics off camera rays).
        var tr = 1.0;
        if (has(F_FOG) && P.fog.x > 0.0) {
            tr = max(exp(-fog_depth(o, l, 0.0, select(hit.t, 2.0e4, miss))), 1.0 - P.fog_color.w);
            g += (1.0 - tr) * P.fog_color.rgb;
        }
        if (has(F_AERIAL) && !miss) {
            let ta = aerial_tr(o, l, hit.t);
            g += tr * (1.0 - ta) * aerial_light(l);
            tr *= dot(ta, vec3<f32>(1.0 / 3.0));
        }
        // Homogeneous media (water) on the segment, as on the paths: without them the voxels under water gathered
        // their surroundings unattenuated (a canal bed read 2.4x the offline image).
        if (LIVE && has(F_HMEDIA)) {
            let mh = media_homogeneous(o, l, select(hit.t, 1.0e30, miss), true, rng_sub(rng_dim(D_MEDIA), 1u));
            g += tr * mh.light;
            tr *= mh.tr;
        }
        if (miss) {
            gather[k] = g + tr * sky_mis(l, pdf);
            break;
        }
        cur_depth = 3u + k;
        cone = vec2<f32>(cone.x + (cone.y + 2.0) * hit.t, cone.y + 2.0);
        let s2 = surface(o, l, hit, cone.x);
        if (any(s2.emissive > vec3<f32>(0.0)) && (s2.front || !s2.card)) {
            g += tr * s2.emissive * emit_mis(hit, l, pdf);
        }
        gather[k] = g;
        if (s2.card) { break; }
        refl[k] = tr * cache_reflectance(lobes(s2, max(dot(s2.n, -l), 1e-4)));
        // Every vertex is traced (each update carries `depth` more bounces into the cache, so multiple bounces build up
        // quickly); the path ends in the cache, or on a cold voxel in that vertex's direct light.
        if (k + 1u == depth) {
            let c = cache_get(s2, false);
            if (c.w >= CACHE_WARM) {
                tail = c.rgb;
            } else {
                nee_alone = true;
                tail = direct_light(s2, wl, -l);
                nee_alone = false;
            }
            break;
        }
        s = s2;
        d = l;
    }
    var e = tail;
    for (var j = i32(n) - 1; j >= 0; j--) {
        e = gather[j] + refl[j] * e;
        let lum = luminance(e);
        // Training samples are clamped at CACHE_TRAIN_CLAMP x the indirect clamp, what the fixed-point sums leave room
        // for (cache_fixed). At 1 x the voxels near bright small lights stored their light clamped, and every pixel
        // reading them inherited the loss: the Bistro crowd's held frame read diffuse 0.81 of our offline render,
        // 0.86 at 4 x; layer B 3.50 -> 3.47.
        let tcl = CACHE_TRAIN_CLAMP * P.misc.x;
        if (lum > tcl) { e *= tcl / lum; }
        cache_add(slot[j], e, max(e - direct[j], vec3<f32>(0.0)));
        cache_add(coarse[2 * j], e, max(e - direct[j], vec3<f32>(0.0)));
        cache_add(coarse[2 * j + 1], e, max(e - direct[j], vec3<f32>(0.0)));
    }
    return Fresh(e, min(direct[0], e));
}

// What a live path ends with at its first bounce, surface `s` (reached along d; ray-cone width there + spread; path
// weight `thr`): what `s` reflects of the cache. Surfaces seen in mirror-like reflections (`hit_light`: specular lobe
// below roughness 0.4, where UE traces reflections) get direct light of their own, as UE's hit lighting does, and the
// cache's indirect part; others reflect the cache's total. Rotating tiles train the cache (`train`). A pixel that
// finds its voxel cold at every level (`cache_get`) traces a fresh estimate and uses it, without inserting the voxel:
// the low-sample entries such pixels inserted kept later frames slower until evicted (the crowd's square ~2 ms).
// (Until 2026-11-16 that held for a view's first 30 frames; later a cold voxel was read as it was, black where there
// was none. With the coarser levels few lookups are cold, and the rule's own test cost more than their traces:
// Bistro 9.05 ms with it, 8.87 without.)
fn cache_end(s: Surface, d: vec3<f32>, cone: vec2<f32>, thr: vec3<f32>, depth: u32, train: bool, hit_light: bool, straight: bool) -> vec3<f32> {
    let v1 = -d;
    let lb1 = lobes(s, max(dot(s.n, v1), 1e-4));
    var e = cache_get(s, hit_light);
    if (train || e.w < CACHE_WARM) {
        // Training tiles trace deep (coherent: whole SIMD groups); scattered cold pixels one vertex.
        let fresh = cache_train(s, d, cone, select(1u, CACHE_DEPTH, train), train);
        RNG_PATH = 0u;
        if (e.w < CACHE_WARM) { e = vec4<f32>(select(fresh.total, fresh.total - fresh.direct, hit_light), 1.0); }
    }
    cur_depth = depth;
    var c = thr * cache_reflectance(lb1) * e.rgb;
    // Resampled lights, not the exact loop camera hits get (that costs 2x here: mirror pixels are scattered).
    mirror_path = false;
    // (The lights alone: the sky's light is in the cache's indirect part, whole. Its samples taken afresh
    // here against the white-lobe ones the cache left out do not add up on a glossy surface: a white metal
    // ground in a mirror read 0.80 of a uniform sky. The lights' still are: weights of two lobes, right for a
    // Lambert surface and for small lights; as light samples alone they were fireflies on Kabukichō's wet
    // street, flicker + 22 %.)
    if (hit_light) {
        lights_only = true;
        c += thr * direct_light(s, lb1, v1);
        lights_only = false;
    }
    let lum = luminance(c);
    if (lum > P.misc.x && !straight) { c *= P.misc.x / lum; }
    return c;
}

// A pixel `main` left for `finish`, DEFERRED_VECS vec4<u32>s (floats as their bits): (pixel, DF_ flags | depth << 8
// (255 at most) | an instance's hit's section << 16 (scene.rs `MESH_SECTIONS`), light list + its length, hit triangle)
// (hit instance, u, v, k_spec.x) (hit point, cone width) (ray direction, cone spread) (path weight, k_spec.y) (the
// specular ray's weight, k_spec.z).
const DEFERRED_VECS: u32 = 6u;
const DEFERRED_ROW: u32 = 16384u; // `finish` invocations a dispatch row (gpu.rs DEFERRED_ROW)
const DF_TRAIN: u32 = 1u;     // of a training tile
const DF_OUT: u32 = 2u;       // its light is still to add (a cold voxel, a reflection hit's lights)
const DF_HIT_LIGHT: u32 = 4u;
const DF_STRAIGHT: u32 = 8u;
const DF_MIRROR: u32 = 16u;
const DF_RESOLVE: u32 = 32u;  // the reflection resolve takes the specular share
const DF_REFL_RAY: u32 = 64u; // the camera hit's sample was a specular-lobe ray

// Live, after each sample's trace: the pixels that had more to trace than a warm voxel's lookup (`cache_end`: a
// training path, a cold voxel's fresh estimate, a reflection hit's lights), one invocation each. `main` left them a
// record and wrote the pixel without that light; this adds it, split as the epilogue of `main` splits it. Such pixels
// are few and scattered (a third of a glossy scene's, an eighth for training): traced in `main`, the others' lanes
// idled beside them, and the code cost every pixel (Bistro 8.06 -> 6.54 ms without it, before this pass's own work).
// The layout as written only: the merged one ends its paths in `main`.
@if(!merged) @compute @workgroup_size(64, 1, 1)
fn finish(@builtin(global_invocation_id) gid: vec3<u32>) {
    let at = (gid.y * DEFERRED_ROW + gid.x) * DEFERRED_VECS;
    if (gid.y * DEFERRED_ROW + gid.x >= atomicLoad(&deferred.n) || at + DEFERRED_VECS > arrayLength(&deferred.recs)) { return; }
    let r0 = deferred.recs[at];
    let r1 = deferred.recs[at + 1u];
    let r2 = bitcast<vec4<f32>>(deferred.recs[at + 2u]);
    let r3 = bitcast<vec4<f32>>(deferred.recs[at + 3u]);
    let r4 = bitcast<vec4<f32>>(deferred.recs[at + 4u]);
    let r5 = bitcast<vec4<f32>>(deferred.recs[at + 5u]);
    let pix = r0.x;
    let fl = r0.y;
    rng_start(vec2<u32>(pix % P.size.x, pix / P.size.x), P.size.z, P.size.w, 0u);
    let depth = (fl >> 8u) & 0xffu;
    cur_depth = depth;
    mirror_path = (fl & DF_MIRROR) != 0u;
    rays_off = LIVE && P.jitter.z > 0.5;
    if (has(F_LISTS)) {
        lt_list = r0.z & ~(LT_LIST - 1u);
        lt_list_n = r0.z & (LT_LIST - 1u);
        lt_fb = LT_NONE;
    }
    // (The hit point as the ray's origin, at distance 0.)
    let s = surface(r2.xyz, r3.xyz, Hit(0.0, r0.w, bitcast<f32>(r1.y), bitcast<f32>(r1.z), r1.x, fl >> 16u), r2.w);
    let c = cache_end(s, r3.xyz, vec2<f32>(r2.w, r3.w), r4.xyz, depth, (fl & DF_TRAIN) != 0u, (fl & DF_HIT_LIGHT) != 0u, (fl & DF_STRAIGHT) != 0u);
    if ((fl & DF_OUT) == 0u || non_finite(c)) { return; }
    let cs = c * vec3<f32>(bitcast<f32>(r1.w), r4.w, r5.w);
    var px = accum[pix];
    px.color = vec4<f32>(px.color.rgb + (c - cs), px.color.w);
    if ((fl & DF_RESOLVE) == 0u) {
        px.spec = vec4<f32>(px.spec.rgb + cs, px.spec.w);
    } else if (P.misc.w < 0.5 && resolve_bound()) {
        var li = cs;
        if ((fl & DF_REFL_RAY) != 0u) { li = select(c / r5.xyz, vec3<f32>(0.0), r5.xyz < vec3<f32>(1e-6)); }
        if (!non_finite(li)) { refl[pix * 2u] += vec4<f32>(li, 0.0); }
    }
    accum[pix] = px;
}

// Live, after each sample's paths: the lights a camera hit resamples (the emitters, the local lights past those
// summed exactly; `DL_SAMPLED`), at the surface `main` left (`surf_store`), added to the pixel's signals as `main`'s
// epilogue splits them. The sample's own numbers at the camera hit: what `main` drew there. Both layouts.
@compute @workgroup_size(8, 8, 1)
fn direct(@builtin(global_invocation_id) gid: vec3<u32>) {
    let w = P.size.x;
    let h = P.size.y;
    if (gid.x >= w || gid.y >= h || !surf_room()) { return; }
    let pix = gid.y * w + gid.x;
    let at = surf_load(pix);
    if (!at.lit) { return; }
    rng_start(gid.xy, P.size.z, P.size.w, 0u);
    cur_depth = 0u;
    mirror_path = false;
    rays_off = LIVE && P.jitter.z > 0.5;
    lt_list = at.list;
    lt_list_n = at.list_n;
    if (has(F_LISTS)) { lt_fb = LT_NONE; }
    // The way to the viewer, as `main` had it: against the pixel's camera ray, turned back through a mirror chain.
    var v = -camera_ray(gid.xy, vec4<f32>(0.0)).d;
    if (at.chain) {
        let x = first_vec_load(chain_at(pix) + 3u).xyz;
        let y = first_vec_load(chain_at(pix) + 4u).xyz;
        v = transpose(mat3x3<f32>(x, y, cross(x, y) * select(1.0, -1.0, at.odd))) * v;
    }
    dl_part = DL_SAMPLED;
    let c = at.thr * direct_light(at.s, lobes(at.s, max(dot(at.s.n, v), 1e-4)), v);
    let cs = at.thr * dl_spec;
    // The light tiles' report, beside the deterministic light `main` wrote there.
    if (has(F_LISTS) && P.misc.w < 0.5 && direct_len() >= w * h) { direct_store(pix, vec4<f32>(direct_load(pix).rgb, f32(lt_fb))); }
    // (The two signals alone are read and written, not the pixel's whole record, and neither where no light was found.)
    if (non_finite(c) || non_finite(cs) || all(c == vec3<f32>(0.0))) { return; }
    let diffuse = accum[pix].color;
    accum[pix].color = vec4<f32>(diffuse.rgb + max(c - cs, vec3<f32>(0.0)), diffuse.w);
    let specular = accum[pix].spec;
    accum[pix].spec = vec4<f32>(specular.rgb + cs, specular.w);
}

// Deterministic reconstruction guides at smooth reflectors. Using the random BSDF sample makes
// glass alternate between two different materials and leaves a hole wherever a diffuse lobe was drawn.
struct GuideHit { albedo: vec3<f32>, normal: vec3<f32>, rough: f32, distance: f32 };
fn guide_color(radiance: vec3<f32>) -> vec3<f32> {
    // Keep a dark background dark and preserve the hue of bright emitters in the albedo guide.
    return radiance / max(1.0, max(radiance.r, max(radiance.g, radiance.b)));
}
fn guide_hit(origin: vec3<f32>, dir: vec3<f32>, footprint: f32, through_glass: bool) -> GuideHit {
    var o = offset_origin(origin, dir);
    var d = dir;
    var first = 0.0;
    for (var i = 0u; i < 2u; i++) {
        let h = trace(o, d, INF, TRACE_CLOSEST);
        if (h.tri == 0xffffffffu) {
            var sky = env_radiance(d);
            if (through_glass) { sky = sky_mis(d, 0.0); }
            return GuideHit(guide_color(sky), -d, 1.0, select(first, 1e4, i == 0u));
        }
        if (i == 0u) { first = h.t; }
        let s = surface(o, d, h, footprint + h.t * 2.0 * P.cam_pos.w / lod_height());
        // Continue through the back face of a clear solid to the material visible behind it.
        if (i == 0u && through_glass && !s.front && s.transmission > 0.0 && s.roughness < GLASS_DELTA) {
            let exit_d = refract(d, s.n, s.ior);
            d = select(reflect(d, s.n), exit_d, dot(exit_d, exit_d) > 0.0);
            o = offset_origin(s.p, d);
            continue;
        }
        let m = lobes(s, max(dot(s.n, -d), 1e-4));
        let emission = guide_color(s.emissive);
        return GuideHit(clamp(max(cache_reflectance(m), emission), vec3<f32>(0.0), vec3<f32>(1.0)), s.n, s.roughness, first);
    }
    return GuideHit(vec3<f32>(1.0), -d, 1.0, first);
}

@compute @workgroup_size(8, 8) fn surface_guides(@builtin(global_invocation_id) gid: vec3<u32>) {
    if (any(gid.xy >= P.size.xy)) { return; }
    let q = gid.y * P.size.x + gid.x;
    let px = accum[q];
    let diffuse = refl_load(2u*q);
    let specular = refl_load(2u*q+1u);
    var alb = diffuse.rgb;
    var normal = px.normal.xyz;
    var rough = px.emit.w;
    // Rough surfaces have no single reflected point. A stochastic second-bounce hit would move
    // their guide even when both the object and camera stand still.
    accum[q].spec.w = 0.0;
    // (Not behind a mirror chain: there the pixel's guides are already the surface shown.)
    if (px.color.w > 0.0 && rough < MIRROR_ROUGHNESS && P.jitter.z == 0.0 && (!has(F_MIRROR) || first_load(q).chain == 0u) &&
        (any(specular.rgb > vec3<f32>(0.005)) || diffuse.w > 0.0)) {
        cur_depth = 1u;
        mirror_path = true;
        let ndc = ((vec2<f32>(gid.xy) + P.jitter.xy) / vec2<f32>(P.size.xy) * 2.0 - 1.0) * vec2<f32>(1.0, -1.0);
        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 x = P.cam_pos.xyz + d * px.color.w;
        let width = px.color.w * 2.0 * P.cam_pos.w / lod_height();
        let reflected = guide_hit(x, reflect(d, normal), width, false);
        accum[q].spec.w = reflected.distance;
        // At a mirror or clear pane the visible material is the secondary surface. Preserve primary
        // depth and motion for silhouettes, disocclusions and post; only the denoiser gets virtual guides.
        let sharp = 1.0 - smoothstep(GLASS_DELTA, 0.18, rough);
        let reflection = clamp(max(specular.r, max(specular.g, specular.b)), 0.0, 1.0);
        var virtual_n = reflect(reflected.normal, normal);
        var virtual_r = reflected.rough;
        var share = reflection;
        alb += sharp * specular.rgb * reflected.albedo;
        if (diffuse.w > 0.0 && specular.w > 0.0) {
            let refracted = refract(d, normal, specular.w);
            if (dot(refracted, refracted) > 0.0) {
                let transmitted = guide_hit(x, refracted, width, true);
                let weight = diffuse.w * (1.0 - reflection);
                alb += sharp * weight * px.albedo.rgb * transmitted.albedo;
                if (weight > reflection) { virtual_n = transmitted.normal; virtual_r = transmitted.rough; }
                share += weight;
            }
        }
        if (dot(virtual_n, normal) < 0.0) { virtual_n = -virtual_n; }
        normal = normalize(mix(normal, virtual_n, sharp * min(share, 1.0)));
        rough = mix(rough, virtual_r, sharp * min(share, 1.0));
    }
    refl_store(2u*q, vec4<f32>(alb, bitcast<f32>(oct_enc(select(vec3<f32>(0.0, 0.0, 1.0), normal, dot(normal, normal) > 0.0)))));
    refl_store(2u*q+1u, vec4<f32>(specular.rgb, rough));
}

// Live, after the trace: MEDIA_TRAIN_POINTS fresh estimates (point_radiance) into the volume voxels, each at a random
// point where a camera ray toward a random traced pixel crosses the media before its first hit.
@compute @workgroup_size(64, 1, 1)
fn media_train(@builtin(global_invocation_id) gid: vec3<u32>) {
    if (!has(F_MEDIA) || !cache_on() || P.time.w < 0.5 || gid.x >= MEDIA_TRAIN_POINTS) { return; }
    media_voxels = true; // the voxels' light is shadowed by the media
    rng_start(vec2<u32>(gid.x, 0u), P.size.z, P.size.w ^ 0x2545f491u, 2u);
    cur_depth = 0u;
    let r4 = rng4(rng_dim(D_CAMERA));
    mirror_path = false;
    let w = P.size.x;
    let h = P.size.y;
    let px = min(u32(r4.x * f32(w)), w - 1u);
    let py = min(u32(r4.y * f32(h)), h - 1u);
    let ndc = vec2<f32>((f32(px) + r4.z) / f32(w) * 2.0 - 1.0, 1.0 - (f32(py) + r4.w) / f32(h) * 2.0);
    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 o = P.cam_pos.xyz;
    let fd = first_depth(py * w + px);
    let tmax = select(1.0e30, fd, fd > 0.0);
    // Homogeneous media (water) lie behind the glass the camera sees them through: their points are taken along the
    // straight ray up to the first opaque surface (stopped at the glass, the voxels learned the water's top layer
    // alone, and its light lit the whole depth: 2.5x the offline single scattering).
    var tmax_h = tmax;
    if (has(F_HMEDIA)) {
        let hh = trace(o, d, INF, TRACE_SHADOW);
        tmax_h = select(1.0e30, hh.t, hh.tri != 0xffffffffu);
    }
    let n = min(u32(P.time.w), 32u);
    var total = 0.0;
    for (var k = 0u; k < n; k++) {
        let sp = medium_span(medium_at(k), o, d);
        total += max(min(sp.y, select(tmax, tmax_h, medium_at(k).a.z != 0u)) - max(sp.x, 0.0), 0.0);
    }
    if (total <= 0.0) { return; }
    var u = rng1(rng_dim(D_MEDIA)) * total;
    var x = o;
    for (var k = 0u; k < n; k++) {
        let sp = medium_span(medium_at(k), o, d);
        let a = max(sp.x, 0.0);
        let len = max(min(sp.y, select(tmax, tmax_h, medium_at(k).a.z != 0u)) - a, 0.0);
        if (u < len) {
            x = o + d * (a + u);
            break;
        }
        u -= len;
    }
    let e = point_radiance_train(x, P.misc.x);
    cache_add(cache_find(cache_key_point(x, VOLUME_FINE), true), e, e);
    cache_add(cache_find(cache_key_point(x, VOLUME_COARSE), true), e, e);
}

// Live participating media, a pass of its own after the frame's last trace sample. Per traced pixel the camera ray
// of its samples (the frame's jitter) is marched up to the pixel's first hit (media_march). The medium's light joins
// what the camera sees directly (the emission signal, once per sample), and the transmittance scales that signal and
// the deterministic direct light, which no history holds. The diffuse and specular lighting and the reflection
// resolve's rays are accumulated over frames (live.wgsl): they stay the surface's own, and the transmittance goes with
// 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. 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;
    let h = P.size.y;
    if (!has(F_MEDIA) || P.time.w < 0.5 || gid.x >= w || gid.y >= h) { return; }
    let pix = gid.y * w + gid.x;
    rng_start(gid.xy, P.size.z, P.size.w ^ 0x51ed27u, 3u);
    cur_depth = 0u;
    mirror_path = false;
    var px = accum[pix];
    let ndc = vec2<f32>((f32(gid.x) + P.jitter.x) / f32(w) * 2.0 - 1.0, 1.0 - (f32(gid.y) + P.jitter.y) / f32(h) * 2.0);
    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));
    // (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<f32>(0.0))) {
        if (apart) { direct_store(seen_medium_at(pix), vec4<f32>(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<f32>(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;
    let share = max(1.0 - mm.moving.x, mm.moving.y / max(mm.moving.y + max(rest, 0.0), 1e-9));
    px.normal = vec4<f32>(px.normal.xyz, floor(clamp(share, 0.0, 1.0) * 255.0) + 0.5 * clamp(mm.tr, 0.0, 1.0));
    px.emit = vec4<f32>(px.emit.rgb * mm.tr + mm.light * samples, px.emit.w);
    accum[pix] = px;
    if (apart) { direct_store(seen_medium_at(pix), vec4<f32>(mm.light, clamp(mm.tr, 0.0, 1.0))); }
    if (direct_len() >= w * h) { direct_store(pix, vec4<f32>(direct_load(pix).rgb * mm.tr, direct_load(pix).w)); }
}

// Once per frame after the trace: folds the frame's training sums into each entry (history capped at P.cache.y
// samples and P.cache.z frames, so lighting changes show within a few frames), ages entries, frees stale ones.
@compute @workgroup_size(256, 1, 1)
fn cache_resolve(@builtin(global_invocation_id) gid: vec3<u32>) {
    let i = gid.x;
    if (i >= CACHE_SIZE || cache_key_load(i) == 0u) { return; }
    let n = min(cache_acc_load(i * 8u + 6u), CACHE_FRAME_CAP);
    var v = cache_val_load(i * 2u);
    var ind = cache_val_load(i * 2u + 1u);
    if (n > 0u) {
        var sum: array<f32, 6>;
        for (var c = 0u; c < 6u; c++) { sum[c] = f32(cache_acc_load(i * 8u + c)) * (P.misc.x / 2097152.0) / f32(n); }
        let hist = min(v.w + f32(n), P.cache.y);
        // The frame cap counts frames, also those without samples since the last update (sparse voxels).
        let a = max(f32(n) / hist, min((ind.w + 1.0) / P.cache.z, 1.0));
        v = vec4<f32>(mix(v.rgb, vec3<f32>(sum[0], sum[1], sum[2]), a), hist);
        ind = vec4<f32>(mix(ind.rgb, vec3<f32>(sum[3], sum[4], sum[5]), a), 0.0);
        for (var c = 0u; c < 8u; c++) { cache_acc_clear(i * 8u + c); }
    } else {
        ind.w += 1.0;
        if (ind.w > CACHE_EVICT) {
            cache_key_clear(i);
            v = vec4<f32>(0.0);
            ind = vec4<f32>(0.0);
        }
    }
    cache_val_store(i * 2u, v);
    cache_val_store(i * 2u + 1u, ind);
}

// ------------------------------------------------------------------------------------------------

// What a live frame's first pass follows: a surface with a mirror's lobe alone (no diffuse lobe, no glass, no coat).
fn mirror_alone(s: Surface) -> bool {
    return s.roughness < DELTA_ROUGHNESS && s.metallic >= 1.0 && s.transmission <= 0.0 && s.coat <= 0.0 && !s.card;
}
// Whether a material's own numbers leave that possible (gpu.rs `mirror_possible`, which makes F_MIRROR of it): read
// before its textures and its function are, which the surfaces of other materials so never are for this. A material
// that is a mirror by its texture or its function alone is not followed.
fn mirror_possible(m: Material) -> bool {
    return m.params.y < DELTA_ROUGHNESS && m.params.x >= 1.0 && m.layer.x <= 0.0;
}

// The camera hit's motion: from the hit point `p` to where that surface point was the previous frame (w = 1), zeros
// where it stands still.
fn first_motion(hit: Hit, p: vec3<f32>) -> vec4<f32> {
    var mv = vec4<f32>(0.0);
    // A deforming mesh keeps its previous vertices in model space, where its instance's record says.
    var deforms = false;
    if (LIVE && P.motion.x > 0.5 && !is_proc(hit) && has(F_INST)) {
        deforms = has(F_DEFORM) && (bitcast<u32>(instance_at(hit.inst).n1.w) & INST_DEFORMS) != 0u;
    }
    if (LIVE && P.motion.x > 0.5 && is_proc(hit)) {
        // Procedural geometry: its object-space hit point through the previous frame's rows.
        let r = instance_at(hit.inst);
        if (any(r.p0 != r.m0) || any(r.p1 != r.m1) || any(r.p2 != r.m2)) {
            let lp = vec4<f32>(proc_point(r, p), 1.0);
            mv = vec4<f32>(vec3<f32>(dot(r.p0, lp), dot(r.p1, lp), dot(r.p2, lp)) - p, 1.0);
        }
    } else if (LIVE && P.motion.x > 0.5 && has(F_INST)) {
        // A movable instance: its model-space hit point (the previous pose's for a deforming mesh) through the
        // previous frame's transform (p rows; the same as m when it did not move).
        let r = instance_at(hit.inst);
        if (deforms || any(r.p0 != r.m0) || any(r.p1 != r.m1) || any(r.p2 != r.m2)) {
            let ix = tri_indices(hit.tri);
            let now = (ix + vec3<u32>(r.info.z)) * VERTEX_VEC4;
            var q0 = vertices[now.x].xyz;
            var q1 = vertices[now.y].xyz;
            var q2 = vertices[now.z].xyz;
            // (A deforming mesh's previous positions are where its record says, n2.w, its vertices as the
            // mesh has them. F_DEFORM: a scene with such a mesh.)
            if (has(F_DEFORM) && deforms) {
                let before = (ix + vec3<u32>(bitcast<u32>(r.n2.w))) * VERTEX_VEC4;
                q0 = prev_verts[before.x].xyz;
                q1 = prev_verts[before.y].xyz;
                q2 = prev_verts[before.z].xyz;
            }
            let lp = vec4<f32>(q0 + (q1 - q0) * hit.u + (q2 - q0) * hit.v, 1.0);
            mv = vec4<f32>(vec3<f32>(dot(r.p0, lp), dot(r.p1, lp), dot(r.p2, lp)) - p, 1.0);
        }
    }
    return mv;
}

// A pixel's camera ray. `cam`: its random numbers (the jitter offline, the lens).
struct CamRay { o: vec3<f32>, d: vec3<f32> };
fn camera_ray(gid: vec2<u32>, cam: vec4<f32>) -> CamRay {
    let w = P.size.x;
    let h = P.size.y;
    // Live: one sub-pixel jitter a frame for the whole image (live/frame.rs: Halton 2, 3), which the temporal upscaler
    // resolves (live.wgsl `upscale`). Offline, every sample draws its own.
    var jx = cam.x;
    var jy = cam.y;
    if (LIVE) {
        jx = P.jitter.x;
        jy = P.jitter.y;
    }
    let ndc = vec2<f32>((f32(gid.x) + jx) / f32(w) * 2.0 - 1.0, 1.0 - (f32(gid.y) + jy) / f32(h) * 2.0);
    var 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));
    var o = P.cam_pos.xyz;
    if (P.cam_right.w > 0.0) {
        let focus = o + d * (P.cam_up.w / dot(d, P.cam_fwd.xyz));
        let r = sqrt(cam.z) * P.cam_right.w;
        let phi = 2.0 * PI * cam.w;
        o += P.cam_right.xyz * (r * cos(phi)) + P.cam_up.xyz * (r * sin(phi));
        d = normalize(focus - o);
    }
    return CamRay(o, d);
}

// A live frame's first pass: every pixel's camera ray, which is the frame's (one jitter, no lens: its samples share
// it). It leaves the hit for `main`'s paths (`first_hits`) and the hit's motion vector, which needs no material: what
// runs between the two passes has this frame's depth (the hit's t) and motion.
// 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<f32> };
fn follow_mirrors(o: vec3<f32>, d: vec3<f32>, hit: Hit, longest: u32) -> Followed {
    var seen = hit;
    var so = o;
    var sd = d;
    var chain = 0u;
    var way = 0.0;
    var weight = vec3<f32>(1.0);
    var light = vec3<f32>(0.0);
    var cone_w = 0.0;
    var cone_a = 2.0 * P.cam_pos.w / lod_height();
    var xf = mat3x3<f32>(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(0.0, 0.0, 1.0));
    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; }
        let width = cone_w + cone_a * seen.t;
        let s = surface(so, sd, seen, width);
        if (!mirror_alone(s)) { break; }
        // The segment that ends at this mirror (the camera's own first): its fog and haze as `main` has a segment's,
        // less the camera segment's sampled scattering; water between mirrors.
        if (has(F_FOG) && P.fog.x > 0.0) {
            // (The fog's start distance and its volumetric range are the camera's: along a chain, what is left of
            // them after the way so far.)
            let t0 = max(P.fog.w - way, 0.0);
            var od = fog_depth(so, sd, t0, seen.t);
            if (has(F_VOLUME) && P.vol.x > 0.0) {
                let tv = select(seen.t, min(seen.t, max(P.vol2.w - way, 0.0)), P.vol2.w > 0.0);
                od += fog_depth(so, sd, t0, max(tv, t0)) * (P.vol.z - 1.0);
            }
            let tr = max(exp(-od), 1.0 - P.fog_color.w);
            light += weight * (1.0 - tr) * P.fog_color.rgb;
            weight *= tr;
        }
        if (has(F_AERIAL)) {
            let ta = aerial_tr(so, sd, seen.t);
            light += weight * (1.0 - ta) * aerial_light(sd);
            weight *= ta;
        }
        if (has(F_HMEDIA) && chain > 0u) { weight *= media_homogeneous(so, sd, seen.t, false, 0u).tr; }
        way += seen.t;
        chain += 1u;
        cone_w = width;
        cone_a += 2.0 * s.roughness * s.roughness;
        // The mirror: its own light, then its Fresnel reflectance (a metal's: its colour at F0); I - 2 n n^T.
        light += weight * s.emissive;
        weight *= f_schlick(s.base, vec3<f32>(1.0), max(dot(s.n, -sd), 1e-4));
        xf = xf * mat3x3<f32>(vec3<f32>(1.0, 0.0, 0.0) - 2.0 * s.n * s.n.x, vec3<f32>(0.0, 1.0, 0.0) - 2.0 * s.n * s.n.y, vec3<f32>(0.0, 0.0, 1.0) - 2.0 * s.n * s.n.z);
        let l = reflect(sd, s.n);
        so = offset_origin(s.p, select(s.ng, -s.ng, dot(l, s.ng) < 0.0));
        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<u32>) {
    let w = P.size.x;
    let h = P.size.y;
    if (gid.x >= w || gid.y >= h || first_len() < 2u * w * h) { return; }
    rng_start(gid.xy, P.size.z, P.size.w, 0u);
    cur_depth = 0u;
    mirror_path = false;
    let pix = gid.y * w + gid.x;
    let cr = camera_ray(gid.xy, rng4(rng_dim(D_CAMERA)));
    let hit = trace(cr.o, cr.d, INF, TRACE_CLOSEST);
    // 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<f32>(0.0);
    // (The hit point as `surface` has it.)
    if (seen.tri != 0xffffffffu) { mv = first_motion(seen, so + sd * seen.t); }
    if (chain > 0u) {
        mv = vec4<f32>(xf * mv.xyz, mv.w);
        chain_store(pix, f.c);
    }
    if (motion_len() >= w * h) { motion_store(pix, select(vec4<f32>(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<u32>) {
    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<f32>(1.0);
    var e0 = vec3<f32>(0.0);
    var way = 0.0;
    var chain = 0u;
    var weight = vec3<f32>(1.0);
    var xf = mat3x3<f32>(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(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<f32>(0.0);
    var normal = vec3<f32>(0.0);
    var sun = vec3<f32>(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<f32>(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<f32>(0.0); }
    if (non_finite(sun)) { sun = vec3<f32>(0.0); }
    if (non_finite(albedo)) { albedo = vec3<f32>(0.0); }
    if (non_finite(normal) || dot(normal, normal) < 1e-12) { normal = vec3<f32>(0.0, 1.0, 0.0); }
    if (non_finite(vec3<f32>(first_t))) { first_t = 0.0; }
    direct_store(guide_at(pix), vec4<f32>(e0 + sun, first_t));
    direct_store(guide_at(pix) + 1u, vec4<f32>(albedo, dir_pack(normal)));
}

@compute @workgroup_size(8, 8, 1)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
    let w = P.size.x;
    let h = P.size.y;
    if (gid.x >= w || gid.y >= h) { return; }
    let pix = gid.y * w + gid.x;
    // Every pixel's deterministic direct light is written each frame (0 unless the camera hits a surface): a pixel that
    // turned to sky must not keep what a surface left there.
    if (LIVE && P.misc.w < 0.5 && direct_len() >= w * h) { direct_store(pix, vec4<f32>(0.0, 0.0, 0.0, select(0.0, f32(LT_NONE), has(F_LISTS)))); }
    if (has(F_LISTS)) { lt_fb = LT_NONE; }
    // A live frame's camera hit has the lights it resamples in a pass of their own (`direct`), which lights the
    // surface left for it below (`surf_store`): none, unless the path reaches the hit's lighting.
    let apart = surf_room();
    if (apart && P.misc.w < 0.5) { surf_none(pix); }
    rng_start(gid.xy, P.size.z, P.size.w, 0u);
    cur_depth = 0u;
    let cr = camera_ray(gid.xy, rng4(rng_dim(D_CAMERA)));
    var d = cr.d;
    var o = cr.o;

    var radiance = vec3<f32>(0.0);
    var first_t = 0.0;
    var thr = vec3<f32>(1.0);
    var albedo = vec3<f32>(0.0);
    var normal = vec3<f32>(0.0);
    var anim = false;
    var e0 = vec3<f32>(0.0); // emission / sky seen directly (camera ray): the live denoiser leaves it unfiltered
    // Diffuse / specular split at the first hit: specular direct light, the specular share of the first BSDF sample
    // (everything gathered after it scales the same way), radiance before it, roughness, reflection hit distance.
    var spec0 = vec3<f32>(0.0);
    var k_spec = vec3<f32>(0.0);
    var rad0 = vec3<f32>(0.0);
    var split = false;
    var rough0 = 1.0;
    var spec_lobe = false;
    var spec_t = 0.0;
    var last_pdf = 0.0;
    // The camera hit's specular-lobe sample for the reflection resolve: direction, lobe pdf, path weight, albedo E;
    // and whether the camera hit's sample went through glass.
    var refl_l = vec3<f32>(0.0);
    var refl_pdf = 0.0;
    var refl_w = vec3<f32>(0.0);
    var refl_e = vec3<f32>(0.0);
    var guide_diffuse = vec3<f32>(0.0);
    var guide_glass = vec2<f32>(0.0); // transmitted share and incident/transmitted index ratio
    var through0 = false;
    // The camera hit is transmissive (glass, water): its reflections stay in the specular signal too (the resolve's
    // neighbours there mostly went through, so it had no rays to rebuild them from: live glass lost its reflection).
    var glass0 = false;
    dl_det = vec3<f32>(0.0);
    dl_det_spec = vec3<f32>(0.0);
    var specular_bounce = true;
    // Every bounce so far a delta sample off a smooth mirror or clear glass: an emitter the path then hits is seen
    // sharply (MetalFX denoised takes it as emission: upscaled, not denoised).
    var delta_path = true;
    // Glass passed since the last scattering vertex: any (behind_glass), and whether an odd number of surfaces (bent).
    // The vertex's shadow rays toward emitters stopped at the glass and those toward the sky at bending glass, so
    // what the path finds there counts in full; behind glass that does not bend (a pane) the sky and the directional
    // lights' disks are weighed against the vertex's samples, which passed it (counted in full, they were counted
    // twice: a white furnace through water read 1.53).
    var behind_glass = false;
    var bent = false;
    // Only glass passed so far (straight through): what lies behind is seen directly, not clamped as indirect.
    var straight = true;
    let clamp_v = P.misc.x;
    // Ray cone (Akenine-Moller et al. 2019) for texture LOD: footprint width at the origin + spread angle.
    var cone_w = 0.0;
    var cone_a = 2.0 * P.cam_pos.w / lod_height();

    mirror_path = false;
    // A live frame's mirror chain (`first_hit` followed it, `Chain`): `chain`, its mirrors, each taking one of the
    // path's bounces; `way`, the distance to its last one.
    var chain = 0u;
    var way = 0.0;
    var last = P.counts.z;
    for (var depth = 0u; depth <= last; depth++) {
        cur_depth = depth;
        var hit = Hit(INF, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);
        if (LIVE && depth == 0u) {
            // A live frame's camera hit is its first pass's (`first_hit`). Where a mirror chain follows it, the path
            // starts at the surface the chain shows, with what the chain left of the light and added to it: that
            // surface has what a camera hit has below (the guides, the light seen directly, the signals' split).
            let f = first_load(pix);
            hit = f.hit;
            if (has(F_MIRROR) && f.chain > 0u) {
                let c = chain_load(pix, f.chain);
                chain = f.chain;
                way = c.way;
                last -= chain;
                radiance += c.light;
                e0 += c.light;
                thr *= c.weight;
                cone_w = cone_a * way;
                o = c.o;
                d = transpose(c.xf) * d;
                hit = c.seen;
            }
        } else {
            hit = trace(o, d, INF, TRACE_CLOSEST);
        }
        // Ray tracing off: the camera ray above was the last one traced for this pixel.
        if (depth == 0u) { rays_off = LIVE && P.jitter.z > 0.5; }
        if (has(F_FOG) && P.fog.x > 0.0) {
            // Height fog on every segment (attenuation + ambient inscattering); lit volumetric scattering on camera rays.
            // (The fog's start distance and its volumetric range are the camera's: behind a mirror chain, what is
            // left of them after the way to its last mirror.)
            let t0 = select(0.0, max(P.fog.w - way, 0.0), depth == 0u);
            let t1 = select(hit.t, 2.0e4, hit.tri == 0xffffffffu);
            // Inside the volumetric range (camera rays) the medium is denser by the extinction scale (UE).
            var od = fog_depth(o, d, t0, t1);
            var tv = t1;
            var trv = 1.0;
            if (has(F_VOLUME) && depth == 0u && P.vol.x > 0.0) {
                tv = select(t1, min(t1, max(P.vol2.w - way, 0.0)), P.vol2.w > 0.0);
                let odv = fog_depth(o, d, t0, max(tv, t0));
                od += odv * (P.vol.z - 1.0);
                trv = exp(-odv * P.vol.z);
            }
            let tr = max(exp(-od), 1.0 - P.fog_color.w);
            // Interleaved over 8x4 tiles (one SIMD group each, so skipped tiles really idle), rotating per sample:
            // a quarter of the pixels at 4x weight; the low-frequency fog converges in the accumulation.
            if (has(F_VOLUME) && depth == 0u && P.vol.x > 0.0 && (((gid.x >> 3u) + 2u * (gid.y >> 2u) + pcg(P.size.z)) & VOL_RATE_MASK) == 0u) {
                // Firefly clamp: a fog point next to a bright sign is rare and huge; haze is a few nits.
                var fs = f32(VOL_RATE_MASK + 1u) * fog_scatter(o, d, t0, max(tv, t0), trv, rng_dim(D_FOG));
                let fl = luminance(fs);
                let fmax = 0.02 * clamp_v;
                if (fl > fmax) { fs *= fmax / fl; }
                radiance += thr * fs;
            }
            let ambient = thr * (1.0 - tr) * P.fog_color.rgb;
            radiance += ambient;
            // Live: the camera ray's fog light is light the camera sees directly, not the surface's (as its haze
            // below): it joins the emission signal, unfiltered, and is not divided by the surface's albedo.
            if (depth == 0u) { e0 += ambient; }
            thr *= tr;
        }
        if (has(F_AERIAL) && hit.tri != 0xffffffffu) {
            let ta = aerial_tr(o, d, hit.t);
            let haze = thr * (1.0 - ta) * aerial_light(d);
            radiance += haze;
            // Live: the camera ray's haze is light the camera sees directly, not the surface's: it joins the emission
            // signal (left out of the diffuse one, which the denoiser divides by the albedo).
            if (depth == 0u) { e0 += haze; }
            thr *= ta;
        }
        // Live media are composited after the trace (media_composite); past the camera ray, homogeneous ones (water)
        // attenuate and light the path here. Offline paths track every medium.
        // (The segment a mirror chain's last mirror shows is one of those.)
        if (LIVE && has(F_HMEDIA) && (depth > 0u || (has(F_MIRROR) && chain > 0u))) {
            let mh = media_homogeneous(o, d, select(hit.t, 1.0e30, hit.tri == 0xffffffffu), true, rng_sub(rng_dim(D_MEDIA), 1u));
            radiance += thr * mh.light;
            thr *= mh.tr;
        }
        if (!LIVE && has(F_MEDIA) && P.time.w > 0.5) {
            // Media on this segment: emission on the way; a real collision scatters the path there.
            let tk = media_track(o, d, select(hit.t, 1.0e30, hit.tri == 0xffffffffu), rng_dim(D_MEDIA));
            radiance += thr * tk.emission;
            if (tk.t >= 0.0) {
                let x = o + d * tk.t;
                thr *= tk.albedo;
                if (depth == 0u) {
                    first_t = tk.t;
                    albedo = tk.albedo;
                    normal = -d;
                }
                var c = thr * phase_direct(x, d, tk.g, rng_dim(D_VOL_LIGHT));
                if (depth > 0u && !straight) {
                    let lum = luminance(c);
                    if (lum > clamp_v) { c *= clamp_v / lum; }
                }
                radiance += c;
                if (depth == last) { break; }
                let nd = sample_hg(d, tk.g);
                last_pdf = hg_phase(tk.g, dot(nd, d));
                specular_bounce = false;
                behind_glass = false;
                bent = false;
                straight = false;
                mirror_path = false;
                delta_path = false;
                cone_w += cone_a * tk.t;
                cone_a += 2.0;
                if (depth >= P.counts.w) {
                    let q = min(max(thr.x, max(thr.y, thr.z)), 0.95);
                    if (rng1(rng_dim(D_RR)) > q) { break; }
                    thr /= q;
                }
                o = x;
                d = nd;
                continue;
            }
        }
        if (hit.tri == 0xffffffffu) {
            var c = thr * sky_mis(d, select(0.0, last_pdf, depth > 0u && !bent));
            if (depth > 1u && !straight) {
                let lum = luminance(c);
                if (lum > clamp_v) { c *= clamp_v / lum; }
            }
            if (depth == 0u) { e0 += c; }
            if (depth == 1u && spec_lobe) { spec_t = 1.0e4; }
            radiance += c;
            break;
        }
        let width = cone_w + cone_a * hit.t;
        let s = surface(o, d, hit, width);
        if (depth == 0u) {
            // (Behind mirrors: where the pixel sees it, the whole way along the camera ray, its normal turned.)
            first_t = way + hit.t;
            if (has(F_LISTS)) {
                // (Where the hit was the previous frame: the first pass's motion vector.)
                var before = s.p;
                if (has(F_MIRROR) && chain > 0u) { before = cr.o + cr.d * first_t; }
                if (LIVE && motion_len() >= w * h) { before += motion_load(pix).xyz; }
                lt_list_start(before);
            }
            albedo = select(s.base, s.emissive / max(max(s.emissive.r, max(s.emissive.g, s.emissive.b)), 1e-6), s.card);
            normal = s.n;
            anim = s.anim;
            rough0 = s.roughness;
        }
        if (depth == 1u && spec_lobe) { spec_t = hit.t; }
        // Emission (one-sided for rect light cards)
        if (any(s.emissive > vec3<f32>(0.0)) && (s.front || !s.card)) {
            var wgt = 1.0;
            // Behind glass an emitter counts in full: shadow rays toward emitters stop at glass (emitter_tr).
            if (depth > 0u && !specular_bounce && !behind_glass) {
                wgt = emit_mis(hit, d, last_pdf);
            }
            var c = thr * s.emissive * wgt;
            if (depth > 1u && !straight) {
                let lum = luminance(c);
                if (lum > clamp_v) { c *= clamp_v / lum; }
            }
            if (depth == 0u || (LIVE && P.motion.y > 0.5 && delta_path)) { e0 += c; }
            radiance += c;
        }
        if (s.card) { break; }
        @if(!last_direct && !last_sun) if (depth == last) { break; }
        @if(last_sun && !last_direct) if (depth == last) {
            // gpu.rs `KernelSwitches::last_sun`: the last vertex's light from the directional lights alone.
            // (Or what a mirror chain shows, the chain having taken the path's bounces.)
            if (depth > 0u || chain > 0u) {
                var dz = thr * sun_light(s, lobes(s, max(dot(s.n, -d), 1e-4)), -d);
                let lum = luminance(dz);
                if (lum > clamp_v && !straight) { dz *= clamp_v / lum; }
                radiance += dz;
            }
            break;
        }
        @if(last_direct) if (depth == last) {
            // gpu.rs `KernelSwitches::last_direct`: the last vertex's direct light.
            // (Or what a mirror chain shows, the chain having taken the path's bounces.)
            if (depth > 0u || chain > 0u) {
                var dz = thr * direct_light(s, lobes(s, max(dot(s.n, -d), 1e-4)), -d);
                let lum = luminance(dz);
                if (lum > clamp_v && !straight) { dz *= clamp_v / lum; }
                radiance += dz;
            }
            break;
        }
        // Live: the path ends in the radiance cache at its first bounce (`cache_end`).
        if (cache_on() && depth >= 1u && !(has(F_GLASS) && s.transmission > 0.0)) {
            let hit_light = spec_lobe && rough0 < 0.4 && depth == 1u;
            let train = (((gid.x >> 3u) + 3u * (gid.y >> 2u) + pcg(P.size.z)) & CACHE_TRAIN_MASK) == 0u;
            @if(merged) { radiance += cache_end(s, d, vec2<f32>(width, cone_a), thr, depth, train, hit_light, straight); }
            @if(!merged) {
                // Here only what a warm voxel holds; a pixel with more to trace is left for `finish`.
                let e = cache_get(s, hit_light);
                let later = hit_light || e.w < CACHE_WARM;
                if (later || train) {
                    let at = atomicAdd(&deferred.n, 1u) * DEFERRED_VECS;
                    if (at + DEFERRED_VECS <= arrayLength(&deferred.recs)) {
                        let fl = (min(depth, 255u) << 8u) | (hit.part << 16u) | select(0u, DF_TRAIN, train) | select(0u, DF_OUT, later) | select(0u, DF_HIT_LIGHT, hit_light) | select(0u, DF_STRAIGHT, straight)
                            | select(0u, DF_MIRROR, mirror_path) | select(0u, DF_RESOLVE, resolve_on() && !through0 && !glass0) | select(0u, DF_REFL_RAY, refl_pdf > 0.0);
                        var lt = 0u;
                        if (has(F_LISTS) && lt_list_n > 0u) { lt = lt_list + lt_list_n; }
                        deferred.recs[at] = vec4<u32>(pix, fl, lt, hit.tri);
                        deferred.recs[at + 1u] = vec4<u32>(hit.inst, bitcast<u32>(hit.u), bitcast<u32>(hit.v), bitcast<u32>(k_spec.x));
                        deferred.recs[at + 2u] = bitcast<vec4<u32>>(vec4<f32>(s.p, width));
                        deferred.recs[at + 3u] = bitcast<vec4<u32>>(vec4<f32>(d, cone_a));
                        deferred.recs[at + 4u] = bitcast<vec4<u32>>(vec4<f32>(thr, k_spec.y));
                        deferred.recs[at + 5u] = bitcast<vec4<u32>>(vec4<f32>(refl_w, k_spec.z));
                    }
                }
                if (!later) {
                    var c = thr * cache_reflectance(lobes(s, max(dot(s.n, -d), 1e-4))) * e.rgb;
                    let lum = luminance(c);
                    if (lum > clamp_v && !straight) { c *= clamp_v / lum; }
                    radiance += c;
                }
            }
            break;
        }

        let v = -d;
        let nov = max(dot(s.n, v), 1e-4);
        let lb = lobes(s, nov);
        if (apart && depth == 0u) {
            dl_part = DL_REST;
            if (P.misc.w < 0.5) { surf_store(pix, s, thr, chain); }
        }
        var dl = thr * direct_light(s, lb, v);
        dl_part = DL_ALL;
        if (depth > 0u && !straight) {
            let lum = luminance(dl);
            if (lum > clamp_v) { dl *= clamp_v / lum; }
        }
        radiance += dl;
        // Live: the deterministic direct light leaves the radiance (and its specular part the specular) for a signal of
        // its own, written here so nothing more stays live through the path. It carries the transmittance to the camera
        // (fog, media) as the radiance did: left out, the diffuse signal's clamp at 0 dropped the attenuation.
        if (LIVE && depth == 0u && direct_len() >= P.size.x * P.size.y && !non_finite(dl_det) && !non_finite(dl_det_spec)) {
            radiance -= thr * dl_det;
            dl_spec = max(dl_spec - dl_det_spec, vec3<f32>(0.0));
            if (P.misc.w < 0.5) { direct_store(gid.y * P.size.x + gid.x, vec4<f32>(thr * dl_det, select(0.0, f32(lt_fb), has(F_LISTS)))); }
        }

        let l = sample_bsdf(s, lb, v);
        // Through smooth glass: a delta lobe (weight tint / its sampling share, no MIS: what lies behind counts in full).
        // Rough glass's transmission has a density like any lobe. Either way the live viewport files the light with
        // the specular, like a reflection.
        let through = has(F_GLASS) && sampled_trans && !lb.rough_t;
        var pdf = 0.0;
        var wgt = lb.tint / max(lb.p_trans, 1e-6);
        if (through) {
            split_frac = vec3<f32>(1.0);
        } else {
            pdf = pdf_bsdf(s, lb, v, l);
            wgt = eval_bsdf(s, lb, v, l) / max(pdf, 1e-20);
        }
        if (depth == 0u) {
            spec0 = thr * dl_spec;
            k_spec = split_frac;
            rad0 = radiance;
            split = true;
            spec_lobe = sampled_spec || sampled_trans;
            through0 = through;
            glass0 = has(F_GLASS) && s.transmission > 0.0;
            refl_e = lb.e_spec;
            if (LIVE && P.motion.y > 0.5) {
                // MetalFX takes the directional reflectances of the layered BSDF, including glass and coat.
                guide_diffuse = lb.diffuse * lb.kd * (1.0 - lb.e_coat);
                refl_e = cache_reflectance(lb) - guide_diffuse;
                if (has(F_GLASS)) { guide_glass = vec2<f32>(s.transmission * (1.0 - s.metallic), lb.eta); }
            }
            if (sampled_spec && !through && lb.coat <= 0.0) {
                refl_l = l;
                refl_pdf = pdf_spec(s, lb, v, l);
                refl_w = wgt;
            }
        }
        if ((!through && pdf <= 0.0) || all(wgt <= vec3<f32>(0.0))) { break; }
        thr *= wgt;
        if (through && dot(l, s.ng) < 0.0) {
            behind_glass = true;
            bent = !bent;
        } else if (through) {
            // (A refracted direction the geometric normal keeps on this side: a specular vertex.)
            last_pdf = 0.0;
            specular_bounce = true;
            behind_glass = false;
            bent = false;
        } else {
            last_pdf = pdf;
            specular_bounce = false;
            behind_glass = false;
            bent = false;
        }
        straight = straight && through;
        cone_w = width;
        cone_a += 2.0 * s.roughness * s.roughness;
        mirror_path = (depth == 0u || mirror_path) && s.roughness < MIRROR_ROUGHNESS && (sampled_spec || sampled_trans);
        delta_path = delta_path && s.roughness < DELTA_ROUGHNESS && (sampled_spec || sampled_trans);
        if (depth >= P.counts.w) {
            let q = min(max(thr.x, max(thr.y, thr.z)), 0.95);
            if (rng1(rng_dim(D_RR)) > q) { break; }
            thr /= q;
        }
        o = offset_origin(s.p, select(s.ng, -s.ng, dot(l, s.ng) < 0.0));
        d = l;
    }

    if (has(F_MIRROR) && chain > 0u) {
        // Behind a mirror chain, what the surface shown left for the passes after is as the pixel sees it: its
        // normal and its specular ray turned by the chain, its albedo under the chain's weight. (Read again here:
        // nothing of the chain is kept through the loop but its length and its way.)
        let c = chain_load(pix, chain);
        albedo *= c.weight;
        normal = c.xf * normal;
        refl_l = c.xf * refl_l;
        if (P.motion.y > 0.5) {
            guide_diffuse *= c.weight;
            refl_e *= c.weight;
        }
    }
    // Integer tests: Metal's fast-math folds `x != x` away, so float NaN checks are unreliable.
    if (non_finite(radiance)) { radiance = vec3<f32>(0.0); }
    if (non_finite(albedo)) { albedo = vec3<f32>(0.0); }
    if (non_finite(normal)) { normal = vec3<f32>(0.0, 1.0, 0.0); }
    if (non_finite(vec3<f32>(first_t))) { first_t = 0.0; }
    if (LIVE) {
        if (non_finite(e0)) { e0 = vec3<f32>(0.0); }
        var spec = spec0;
        // With the reflection resolve, the sampled ray's specular share is left out of both signals: the resolve
        // estimates the whole specular integral from the neighbourhood's specular-lobe rays. Its diffuse share stays.
        let resolve = resolve_on() && split && !through0 && !glass0;
        var dropped = vec3<f32>(0.0);
        if (split) {
            if (resolve) { dropped = (radiance - rad0) * k_spec; } else { spec += (radiance - rad0) * k_spec; }
        }
        if (non_finite(spec)) { spec = vec3<f32>(0.0); }
        if (non_finite(dropped)) { dropped = vec3<f32>(0.0); }
        spec = clamp(spec, vec3<f32>(0.0), max(radiance - e0, vec3<f32>(0.0)));
        let diff = max(radiance - e0 - spec - dropped, vec3<f32>(0.0));
        if (P.motion.y > 0.5 && P.misc.w < 0.5 && resolve_bound()) {
            // The reconstruction consumes the noisy path itself. Its material guides reuse the idle ray slots.
            refl_store(pix * 2u, vec4<f32>(guide_diffuse, guide_glass.x));
            refl_store(pix * 2u + 1u, vec4<f32>(refl_e, guide_glass.y));
        } else if (resolve_bound() && P.misc.w < 0.5) {
            // Radiance along the specular ray: what the path gathered after it, over the ray's weight.
            var li = vec3<f32>(0.0);
            if (resolve && refl_pdf > 0.0) {
                li = select((radiance - rad0) / refl_w, vec3<f32>(0.0), refl_w < vec3<f32>(1e-6));
            }
            if (non_finite(li)) { li = vec3<f32>(0.0); }
            // A sample that took the diffuse lobe leaves its specular share (dropped) for the resolve to return when no
            // specular-lobe ray around it can stand in (w = -1 marks it).
            if (resolve && !(refl_pdf > 0.0)) { li = dropped; }
            refl_store(pix * 2u, vec4<f32>(li, select(select(0.0, -1.0, resolve), min(refl_pdf, 1e6), resolve && refl_pdf > 0.0)));
            refl_store(pix * 2u + 1u, vec4<f32>(select(vec3<f32>(0.0), refl_e, resolve), bitcast<f32>(oct_enc(select(vec3<f32>(0.0, 0.0, 1.0), refl_l, refl_pdf > 0.0)))));
        }
        // misc.w = index of this sample within the frame: the first one also writes the g-buffer.
        if (P.misc.w < 0.5) {
            // normal.w: no medium before the hit (`media_composite` writes it where there is one).
            let jit = 0.5;
            accum[pix] = Pixel(vec4<f32>(diff, first_t), vec4<f32>(albedo, select(1.0, 2.0, anim)), vec4<f32>(normal, jit), vec4<f32>(e0, rough0), vec4<f32>(spec, spec_t));
        } else {
            var px = accum[pix];
            px.color = vec4<f32>(px.color.rgb + diff, px.color.w);
            px.emit = vec4<f32>(px.emit.rgb + e0, px.emit.w);
            px.spec = vec4<f32>(px.spec.rgb + spec, px.spec.w);
            accum[pix] = px;
        }
        return;
    }
    var px = accum[pix];
    px.color += vec4<f32>(radiance, 1.0);
    let lum = luminance(radiance);
    px.albedo += vec4<f32>(albedo, lum);
    px.normal += vec4<f32>(normal, lum * lum);
    // `render --signals` (P.motion.y, a live-only lane otherwise): what the camera ray saw directly and the specular
    // share at the camera hit, split as the live denoiser splits them (no reflection resolve), in the slots only live
    // renders use. The diffuse signal is the rest.
    if (P.motion.y > 0.5) {
        var sp = spec0;
        if (split) { sp += (radiance - rad0) * k_spec; }
        let em = select(e0, vec3<f32>(0.0), non_finite(e0));
        sp = select(clamp(sp, vec3<f32>(0.0), max(radiance - em, vec3<f32>(0.0))), vec3<f32>(0.0), non_finite(sp));
        px.emit += vec4<f32>(em, 0.0);
        px.spec += vec4<f32>(sp, 0.0);
    }
    accum[pix] = px;
}