diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 084ad09..653f67e 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -2776,6 +2776,27 @@ in-place tests' world, rows given back; two models in a shared pose posed again (tests/render/data/arm.glb, a skinned strip of two materials); `geometry/emitter-model-live` (a model's emitting section that is not its first, the model a unit under software traversal). +**A triangle's texel density is the hit's to compute (2026-11-22).** Every triangle carried a constant for its mip +choice, half the log of its UV area over its area, made when the scene was built; an instance added an offset for +its scale, the skinning pass and the particle passes wrote it again each pose and frame. Now the kernel takes it +from the triangle where it is hit, from its two edges as it stands in the world and its UVs (`mesh_lod`), and +nothing stores or writes it: the attributes' first `x` word and the record's third `info` word are spare. +What changes in a picture: nothing under a uniform scale but rounding (five scenes offline against the build +before: four the same bytes, one with 21 of 921,600 pixels off by 6 steps at most). An instance scaled otherwise +has its triangles' own density now; its offset was the cube root of its volume's scale. +A fault found on the way: a shadow ray through glass on a scaled instance added the instance's offset twice, so a +pane's colour or transmission map was read some levels off (a pane scaled to 1 / 32: five too high). +The cutout test of a candidate hit reads its triangle's edges now too, where its material has an alpha map. +Tests: the kernel's own `mesh_lod`, its text run on the GPU for 512 triangles (a millimetre to a hundred metres, +UVs a hundredth of the texture to a hundred repeats, ones without area) against 64-bit values; a checker on an +instance scaled 32 times, a square's inside reading its colour (a level five too high reads grey); the checker in +a cutout's alpha on one scaled 256 times; a shadow through a pane with a colour map, the pane scaled 1 / 32 and 32 +times (the first fails on the build before). Not held by a test: the density a light sample, a material function's input and a +translucent particle read (a wrong level there changes noise, not a mean). +10 mutations: six of the formula fail the unit test, four of the places that use it fail a render test. One did not at +first: a cutout three levels too high still has each square's middle on its side of the test, so that test's +instance is scaled 256 times. + **A posed skinned model is posed in place under software traversal (2026-11-22).** Under software traversal a mesh that deforms was written out into the still scene's tree, so every pose rebuilt the scene. Now it is a unit as any mesh. Its tree has the shape of a tree built once over its model's bind pose, one shape for every placement of the diff --git a/renderer/shaders/gpu_particles.wgsl b/renderer/shaders/gpu_particles.wgsl index 01909a7..d6f1403 100644 --- a/renderer/shaders/gpu_particles.wgsl +++ b/renderer/shaders/gpu_particles.wgsl @@ -140,7 +140,7 @@ fn collide(s_in: PState, dt: f32, flags: f32, d: vec4) -> PState { } // One triangle of a quad (particles.wgsl `put_tri`, opaque particles only). -fn put_tri(t: u32, dyn_first: u32, a: vec3, b: vec3, c: vec3, n: vec3, tg: vec3, lod_k: f32) { +fn put_tri(t: u32, dyn_first: u32, a: vec3, b: vec3, c: vec3, n: vec3, tg: vec3) { let flags = verts[t * 3u].w; let now = array, 3>(vec4(a, flags), vec4(b - a, 0.0), vec4(c - a, 0.0)); let first = PPS.env.x > 0.5; @@ -160,7 +160,6 @@ fn put_tri(t: u32, dyn_first: u32, a: vec3, b: vec3, c: vec3, n: attrs[t].n2.y = n.y; attrs[t].n2.z = n.z; attrs[t].t = vec4(tg, 1.0); - attrs[t].x.x = lod_k; let corners = array, 3>(a, b, c); for (var k = 0u; k < 3u; k++) { for (var j = 0u; j < 3u; j++) { @@ -238,10 +237,9 @@ fn gpu_particles(@builtin(global_invocation_id) gid: vec3) { let area = length(uxv); let n = select(to_cam, uxv / area, area > 1e-12); let tg = select(vec3(1.0, 0.0, 0.0), normalize(u), dot(u, u) > 1e-24); - let lod_k = select(0.0, 0.5 * log2(1.0 / (4.0 * area)), area > 1e-12); let t = sys.a.x + 2u * k; - put_tri(t, sys.b.y, c00, c10, c11, n, tg, lod_k); - put_tri(t + 1u, sys.b.y, c00, c11, c01, n, tg, lod_k); + put_tri(t, sys.b.y, c00, c10, c11, n, tg); + put_tri(t + 1u, sys.b.y, c00, c11, c01, n, tg); let oi = (sys.a.z + k) * OBJECT_STRIDE; objects[oi] = vec4(s.pos, objects[oi].w); objects[oi + 1u] = vec4(vec3(4.0 * half), objects[oi + 1u].w); diff --git a/renderer/shaders/particles.wgsl b/renderer/shaders/particles.wgsl index 3995fec..27db7b9 100644 --- a/renderer/shaders/particles.wgsl +++ b/renderer/shaders/particles.wgsl @@ -74,11 +74,11 @@ fn unit(h: u32) -> f32 { return f32(h >> 8u) * (1.0 / 16777216.0); } fn particle_function(f: u32, i: PIn, p: array, 8>) -> POut { return POut(i.pivot, vec3(0.0), vec3(0.0), false, vec4(0.0)); } // @particle-functions-end -// One triangle of a quad: positions, last frame's as prev_verts, shading normal / tangent / texel density (`lod_k`, as -// scene.rs tri_attr), BLAS input. +// One triangle of a quad: positions, last frame's as prev_verts, shading normal / tangent (as scene.rs tri_attr), +// BLAS input. // Translucent triangles (`trans` = first translucent triangle) have no motion vectors (the pass draws them over the // image each frame) and their own BLAS input. -fn put_tri(t: u32, dyn_first: u32, trans: u32, a: vec3, b: vec3, c: vec3, n: vec3, tg: vec3, lod_k: f32, first: bool) { +fn put_tri(t: u32, dyn_first: u32, trans: u32, a: vec3, b: vec3, c: vec3, n: vec3, tg: vec3, first: bool) { let flags = verts[t * 3u].w; let now = array, 3>(vec4(a, flags), vec4(b - a, 0.0), vec4(c - a, 0.0)); for (var k = 0u; k < 3u; k++) { @@ -100,7 +100,6 @@ fn put_tri(t: u32, dyn_first: u32, trans: u32, a: vec3, b: vec3, c: ve attrs[t].n2.y = n.y; attrs[t].n2.z = n.z; attrs[t].t = vec4(tg, 1.0); - attrs[t].x.x = lod_k; let corners = array, 3>(a, b, c); for (var k = 0u; k < 3u; k++) { for (var j = 0u; j < 3u; j++) { @@ -141,17 +140,16 @@ fn particles(@builtin(global_invocation_id) gid: vec3) { let c10 = o.center + o.u - o.v; let c11 = o.center + o.u + o.v; let c01 = o.center - o.u + o.v; - // Normal u x v, tangent (dP/du) along u, bitangent (image up) along v; uv area 1 over world area 4 |u x v|. + // Normal u x v, tangent (dP/du) along u, bitangent (image up) along v. let uxv = cross(o.u, o.v); let area = length(uxv); let n = select(vec3(0.0, 0.0, 1.0), uxv / area, area > 1e-12); let tg = select(vec3(1.0, 0.0, 0.0), normalize(o.u), dot(o.u, o.u) > 1e-24); - let lod_k = select(0.0, 0.5 * log2(1.0 / (4.0 * area)), area > 1e-12); let t = s.a.x + 2u * k; let trans = select(0xffffffffu, s.b.w, s.b.z == 1u); let first = PPS.env.z > 0.5 || s.c.w > 1.5; - put_tri(t, s.b.y, trans, c00, c10, c11, n, tg, lod_k, first); - put_tri(t + 1u, s.b.y, trans, c00, c11, c01, n, tg, lod_k, first); + put_tri(t, s.b.y, trans, c00, c10, c11, n, tg, first); + put_tri(t + 1u, s.b.y, trans, c00, c11, c01, n, tg, first); let oi = (s.a.z + k) * OBJECT_STRIDE; objects[oi] = vec4(o.center, objects[oi].w); objects[oi + 1u] = vec4(2.0 * (abs(o.u) + abs(o.v)), objects[oi + 1u].w); diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl index 26c8035..2116f62 100644 --- a/renderer/shaders/pathtrace.wgsl +++ b/renderer/shaders/pathtrace.wgsl @@ -159,7 +159,7 @@ fn env_cdf_at(i: u32) -> f32 { return bitcast(words[i]); } @group(0) @binding(11) var accum: array; // The dynamic triangles' vertices (kernel layout, from triangle P.group_first[1].x on) as they were the previous frame. @group(0) @binding(6) var prev_verts: array>; -// Instances (scene::GpuInstance): world matrix rows, normal matrix rows, (first triangle, object, LOD offset bits, its rows' first). +// Instances (scene::GpuInstance): world matrix rows, normal matrix rows, (first triangle, object, a spare word, its rows' first). struct Instance { m0: vec4, m1: vec4, m2: vec4, n0: vec4, n1: vec4, n2: vec4, info: vec4, p0: vec4, p1: vec4, p2: vec4 }; // 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 @@ -290,10 +290,9 @@ fn inst_sign(r: Instance) -> f32 { return select(1.0, -1.0, (bitcast(r.n1.w fn inst_normal(r: Instance, n: vec4) -> vec4 { return vec4(normalize(vec3(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` (texel density, object, ...) as its instance has it: the instance's texture LOD offset -// and object (the record's `info`). +// A model-space triangle's `x` as its instance has it: the instance's object (the record's `info`). fn inst_x(info: vec4, x: vec4) -> vec4 { - return vec4(x.x + bitcast(info.z), bitcast(info.y), x.z, x.w); + return vec4(x.x, bitcast(info.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). A triangle of @@ -911,8 +910,7 @@ fn glass_at(h: Hit, d: vec3, t: f32) -> GlassAt { 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); - var lod = mesh_lod(a, m) + log2(max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7)) - LOD_BIAS; - if (has(F_INST) && h.inst != NO_INST) { lod += bitcast(instance_at(h.inst).info.z); } + let lod = mesh_lod(e1, e2, a, m) + log2(max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7)) - 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; } } @@ -1083,9 +1081,18 @@ fn mesh_uv(a: TriAttr, m: Material, u: f32, v: f32) -> vec2 { return (vec2(a.n0.w, a.n1.w) * w + vec2(a.n2.w, a.uv.x) * u + a.uv.yz * v) * m.uv.xy + m.uv2.xy; } -// log2(texture-UV units per metre) of a triangle's mesh UVs (incl. material repeat). -fn mesh_lod(a: TriAttr, m: Material) -> f32 { - return a.x.x + 0.5 * log2(max(abs(m.uv.x * m.uv.y), 1e-12)); +// log2(texture-UV units per metre) of a triangle's mesh UVs (incl. material repeat), from the triangle where it is +// hit: its edges e1, e2 as it stands in the world, its UVs: 0.5 log2(uv area / area), 0 where one of the two has no +// size. +fn mesh_lod(e1: vec3, e2: vec3, a: TriAttr, m: Material) -> f32 { + let uv0 = vec2(a.n0.w, a.n1.w); + let d1 = vec2(a.n2.w, a.uv.x) - uv0; + let d2 = a.uv.yz - uv0; + let uv_area = 0.5 * abs(d1.x * d2.y - d2.x * d1.y); + let area = 0.5 * length(cross(e1, e2)); + var k = 0.0; + if (area > 1e-12 && uv_area > 1e-14) { k = 0.5 * log2(uv_area / area); } + return k + 0.5 * log2(max(abs(m.uv.x * m.uv.y), 1e-12)); } // ------------------------------------------------------------------------------------------------ @@ -1190,7 +1197,7 @@ fn mat_in_at(ti: u32, inst: u32, u: f32, v: f32, view: vec3, lod: f32) -> M var n = normalize(a.n0.xyz * w + a.n1.xyz * u + a.n2.xyz * v); let t = normalize(a.t.xyz - n * dot(n, a.t.xyz) + vec3(1e-9)); let oi = object_of(a); - return MatIn(p, n, ng, t, cross(n, t) * a.t.w, mesh_uv(a, m, u, v), mesh_lod(a, m), view, object_at(oi * OBJECT_STRIDE).xyz, object_at(oi * OBJECT_STRIDE + 1u).xyz, + return MatIn(p, n, ng, t, cross(n, t) * a.t.w, mesh_uv(a, m, u, v), mesh_lod(e1, e2, a, m), 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)); } @@ -1225,14 +1232,20 @@ var nee_alone: bool = false; var 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 model instance a pool triangle belongs to (its scale shifts the texel density, as in `inst_attr`), or NO_INST. +// the model instance a pool triangle belongs to (it places the triangle's edges: its texel density), or NO_INST. fn alpha_pass(ti: u32, inst: u32, u: f32, v: f32, t: f32) -> bool { let a = attrs[ti]; let m = material_at(material_of(a, inst)); var alpha = m.base_color.a; - var lod = mesh_lod(a, m) + log2(max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7)) - LOD_BIAS; - if (has(F_INST) && inst != NO_INST) { lod += bitcast(instance_at(inst).info.z); } if (has(F_TEX) && m.tex0.x >= 0) { + var e1 = tri_verts[ti * 3u + 1u].xyz; + var e2 = tri_verts[ti * 3u + 2u].xyz; + if (has(F_INST) && inst != NO_INST) { + let r = instance_at(inst); + e1 = inst_vec(r, e1); + e2 = inst_vec(r, e2); + } + let lod = mesh_lod(e1, e2, a, m) + log2(max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7)) - LOD_BIAS; alpha *= tex(m.tex0.x, mesh_uv(a, m, u, v), lod).a; } if (has(F_FUNC) && m.tex1.w > 0) { @@ -1278,7 +1291,8 @@ fn surface(o: vec3, d: vec3, h: Hit, width: f32) -> Surface { let p = o + d * h.t; let uv = mesh_uv(a, m, h.u, h.v); - let lod = mesh_lod(a, m) + log2(max(width, 1e-7)) - 0.5 * log2(max(abs(dot(ng, d)), 1e-3)) - LOD_BIAS; + let mesh_k = mesh_lod(e1, e2, a, m); + let lod = mesh_k + log2(max(width, 1e-7)) - 0.5 * log2(max(abs(dot(ng, d)), 1e-3)) - LOD_BIAS; var s: Surface; s.p = p; @@ -1321,7 +1335,7 @@ fn surface(o: vec3, d: vec3, h: Hit, width: f32) -> Surface { let oi = object_of(a); var t = normalize(a.t.xyz - n * dot(n, a.t.xyz) + vec3(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) * a.t.w, mesh_uv(a, m, h.u, h.v), mesh_lod(a, m), -d, + let i = MatIn(p, select(-nv, nv, dot(nv, ng) >= 0.0), ng, t, cross(n, t) * a.t.w, mesh_uv(a, m, h.u, h.v), mesh_k, -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)); @@ -1869,9 +1883,9 @@ fn sun_disks(d: vec3, pdf: f32) -> vec3 { return c; } -// What light sampling reads of an emitter's attributes (UVs, material, object, texel density), as shading has them -// at a hit of it: its triangle's, with its instance's object and texture LOD offset if it has one. (Not the normals -// and the tangent, which stay the mesh's: a light sample reads none, and placing them is work a sample.) +// 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 if it has one. (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 = attrs[em.tri]; if (has(F_INST) && em.inst != NO_INST) { a.x = inst_x(instance_at(em.inst).info, a.x); } @@ -2146,7 +2160,7 @@ fn emitter_radiance(em: EmitterTri, b1: f32, b2: f32, l: vec3) -> vec3 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(a, m) + log2(0.05)) * pw; + var le = emission(m, mesh_uv(a, m, b1, b2), mesh_lod(em.e1, em.e2, a, m) + log2(0.05)) * pw; if (has(F_FUNC) && m.tex1.w > 0) { var mb = mat_base(m); mb.emissive *= pw; diff --git a/renderer/shaders/records.wgsl b/renderer/shaders/records.wgsl index 0470feb..074ae21 100644 --- a/renderer/shaders/records.wgsl +++ b/renderer/shaders/records.wgsl @@ -3,8 +3,8 @@ // `live_source`, build.rs). // A triangle's shading attributes (scene.rs GpuTriAttr): normals (w: uv parts), uv parts (w: material index, bits), -// tangent (w: bitangent sign), x: (texel density, object (bits), a particle's area, its emitter entry + 1 (bits; 0: it -// is not light-sampled)). A triangle of a mesh with sections: uv.w its section, x.w its index in it (its instance's +// tangent (w: bitangent sign), x: (a spare word, object (bits), a particle's area, its emitter entry + 1 (bits; 0: it +// is not light-sampled)). (Its texel density is computed where it is hit: pathtrace.wgsl `mesh_lod`.) A triangle of a mesh with sections: uv.w its section, x.w its index in it (its instance's // row has the material and where the section's emitters start: pathtrace.wgsl `material_of`, `row_word`). struct TriAttr { n0: vec4, n1: vec4, n2: vec4, uv: vec4, t: vec4, x: vec4 }; diff --git a/renderer/shaders/skin.wgsl b/renderer/shaders/skin.wgsl index f824d9c..b4607fa 100644 --- a/renderer/shaders/skin.wgsl +++ b/renderer/shaders/skin.wgsl @@ -152,18 +152,10 @@ fn main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) l } } } - // Texel density for the mip choice: 0.5 log2(uv area / area). - let area = 0.5 * length(area2); - let uv_area = 0.5 * abs(det); - var lod = 0.0; - if area > 1e-12 && uv_area > 1e-14 { - lod = 0.5 * log2(uv_area / area); - } at.n0 = vec4(n0, at.n0.w); at.n1 = vec4(n1, at.n1.w); at.n2 = vec4(n2, at.n2.w); at.t = vec4(t, hand); - at.x.x = lod; attrs[k] = at; // (The flag word: the kernel takes a deforming mesh's motion from the previous frame's vertices.) verts[k * 3u] = vec4(c0.p, bitcast(TRI_DYNAMIC)); diff --git a/renderer/shaders/translucent.wgsl b/renderer/shaders/translucent.wgsl index 466f49e..e24ea12 100644 --- a/renderer/shaders/translucent.wgsl +++ b/renderer/shaders/translucent.wgsl @@ -61,7 +61,7 @@ // (A particle's triangle is in the world: no instance.) let m = material_at(material_of(a, NO_INST)); let uv = mesh_uv(a, m, b.x, b.y); - let tl = mesh_lod(a, m) + lod - LOD_BIAS; + let tl = mesh_lod(tri_verts[ti * 3u + 1u].xyz, tri_verts[ti * 3u + 2u].xyz, a, m) + lod - LOD_BIAS; var r = mat_base(m); if (has(F_TEX) && m.tex0.x >= 0) { let c = tex(m.tex0.x, uv, tl); diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs index bc8ec56..572650a 100644 --- a/renderer/src/gpu.rs +++ b/renderer/src/gpu.rs @@ -3892,6 +3892,96 @@ mod tests { } } + /// The kernel's texel density of a triangle (`mesh_lod`, its own text, run on the GPU): half the log of its UV area + /// over its area, from its two edges and its UVs, with the material's repeat; 0 for the first term where the + /// triangle or its UVs have no area. Triangles of every size and UV scale against the same in 64-bit floats. + #[test] + fn the_kernels_texel_density_is_the_triangles() { + use wgpu::util::DeviceExt; + let g = match super::Gpu::new() { + Ok(g) => g, + Err(e) => return eprintln!("skipped: {e}"), + }; + let part = |src: &'static str, from: &str, to: &str| { + let at = src.find(from).unwrap_or_else(|| panic!("the kernel has `{from}`")); + &src[at..at + src[at..].find(to).expect("its end") + to.len()] + }; + let attr = part(include_str!("../shaders/records.wgsl"), "struct TriAttr {", "};"); + let density = part(include_str!("../shaders/pathtrace.wgsl"), "fn mesh_lod(e1: vec3, e2: vec3, a: TriAttr, m: Material) -> f32 {", "\n}\n"); + let src = format!( + "{attr}\nstruct Material {{ uv: vec4 }};\nstruct In {{ e1: vec4, e2: vec4, a: TriAttr, m: vec4 }};\n\ + @group(0) @binding(0) var input: array;\n@group(0) @binding(1) var out: array;\n{density}\n\ + @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) {{\n if (id.x >= arrayLength(&input)) {{ return; }}\n let i = input[id.x];\n out[id.x] = mesh_lod(i.e1.xyz, i.e2.xyz, i.a, Material(i.m));\n}}\n" + ); + // A deterministic stream in [0, 1). + let mut seed = 0x9e3779b97f4a7c15u64; + let mut f = move || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((seed >> 40) as f32) / (1u64 << 24) as f32 + }; + let (mut rows, mut want): (Vec<[f32; 36]>, Vec) = (vec![], vec![]); + for k in 0..512 { + // Sizes from a millimetre to a hundred metres, UVs from a hundredth of the texture to a hundred repeats. + let (size, uvs) = (10f32.powf(f() * 5.0 - 3.0), 10f32.powf(f() * 4.0 - 2.0)); + let mut v = |s: f32| [(f() - 0.5) * s, (f() - 0.5) * s, (f() - 0.5) * s]; + let (mut e1, mut e2) = (v(size), v(size)); + let (uv0, mut uv1, mut uv2) = ([f() * uvs, f() * uvs], [f() * uvs, f() * uvs], [f() * uvs, f() * uvs]); + let rep = if k % 4 == 0 { [10f32.powf(f() * 2.0 - 1.0), -10f32.powf(f() * 2.0 - 1.0)] } else { [1.0, 1.0] }; + match k % 16 { + // A triangle without area (its edges along one line, or none), UVs without area. + 5 => e2 = e1.map(|x| x * 2.0), + 6 => (e1, e2) = ([0.0; 3], [0.0; 3]), + 7 => (uv1, uv2) = (uv0, uv0), + 8 => uv2 = [uv0[0] + (uv1[0] - uv0[0]) * 3.0, uv0[1] + (uv1[1] - uv0[1]) * 3.0], + _ => {} + } + let mut row = [0f32; 36]; + row[..3].copy_from_slice(&e1); + row[4..7].copy_from_slice(&e2); + // (The attributes' UV words: n0.w, n1.w = uv0; n2.w, uv.x = uv1; uv.y, uv.z = uv2.) + (row[8 + 3], row[8 + 7], row[8 + 11], row[8 + 12], row[8 + 13], row[8 + 14]) = (uv0[0], uv0[1], uv1[0], uv1[1], uv2[0], uv2[1]); + (row[32], row[33]) = (rep[0], rep[1]); + rows.push(row); + let d = |a: [f32; 3]| a.map(|x| x as f64); + let (a, b) = (d(e1), d(e2)); + let cross = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + let area = 0.5 * (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt(); + let (d1, d2) = ([(uv1[0] - uv0[0]) as f64, (uv1[1] - uv0[1]) as f64], [(uv2[0] - uv0[0]) as f64, (uv2[1] - uv0[1]) as f64]); + let uv_area = 0.5 * (d1[0] * d2[1] - d2[0] * d1[1]).abs(); + let k0 = if area > 1e-12 && uv_area > 1e-14 { 0.5 * (uv_area / area).log2() } else { 0.0 }; + want.push(k0 + 0.5 * ((rep[0] * rep[1]).abs() as f64).max(1e-12).log2()); + } + let d = &g.device; + let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("texel density"), source: wgpu::ShaderSource::Wgsl(src.into()) }); + let pipeline = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: None, layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None }); + let input = d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, contents: bytemuck::cast_slice(&rows), usage: wgpu::BufferUsages::STORAGE }); + let bytes = (rows.len() * 4) as u64; + let out = d.create_buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }); + let to = d.create_buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + let bg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &pipeline.get_bind_group_layout(0), entries: &[wgpu::BindGroupEntry { binding: 0, resource: input.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: out.as_entire_binding() }] }); + let mut e = d.create_command_encoder(&Default::default()); + { + let mut pass = e.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bg, &[]); + pass.dispatch_workgroups(rows.len().div_ceil(64) as u32, 1, 1); + } + e.copy_buffer_to_buffer(&out, 0, &to, 0, bytes); + g.queue.submit([e.finish()]); + to.slice(..).map_async(wgpu::MapMode::Read, |_| {}); + d.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let got: Vec = bytemuck::pod_collect_to_vec(&to.slice(..).get_mapped_range().unwrap()); + let (mut flat, mut spread) = (0, (f64::MAX, f64::MIN)); + for (k, (g, w)) in got.iter().zip(&want).enumerate() { + // (A triangle or UVs at the edge of having an area may fall on either side of it in 32 bits: not those.) + let edge = matches!(k % 16, 5 | 8); + assert!(edge || (*g as f64 - w).abs() <= 2e-4 + 2e-5 * w.abs(), "triangle {k}: the kernel's {g}, {w} in 64 bits"); + flat += (k % 16 == 6 || k % 16 == 7) as usize; + spread = (spread.0.min(*w), spread.1.max(*w)); + } + assert!(flat > 40 && spread.0 < -8.0 && spread.1 > 8.0, "the triangles span the densities ({spread:?}) and {flat} have no area"); + } + fn naga_valid(src: &str) { let m = naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{}", e.emit_to_string(src))); naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all()).validate(&m).unwrap_or_else(|e| panic!("{}", e.emit_to_string(src))); diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs index d087753..cdde495 100644 --- a/renderer/src/scene.rs +++ b/renderer/src/scene.rs @@ -209,7 +209,7 @@ pub struct Instance { } /// Kernel record of an instance (`instances` binding): world matrix rows, normal matrix rows (inverse transpose), -/// (first triangle in the GPU order, object index, texture-LOD offset bits, its rows' first), and the +/// (first triangle in the GPU order, object index, a spare word, its rows' first), and the /// world matrix rows of the previous frame (a movable instance's motion vectors; the same rows when it did not move). #[repr(C)] #[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)] @@ -229,7 +229,7 @@ impl Instance { let row = |r: usize| [w.x_axis[r], w.y_axis[r], w.z_axis[r], w.w_axis[r]]; let nrow = |r: usize, w: f32| [nm.x_axis[r], nm.y_axis[r], nm.z_axis[r], w]; let bits = f32::from_bits(self.bits | if mirrors(w) { INST_MIRRORED } else { 0 }); - GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0, 0.0), nrow(1, bits), nrow(2, f32::from_bits(self.prev))], info: [first, self.object, lod_offset(w).to_bits(), self.rows], p: [row(0), row(1), row(2)] } + GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0, 0.0), nrow(1, bits), nrow(2, f32::from_bits(self.prev))], info: [first, self.object, 0, self.rows], p: [row(0), row(1), row(2)] } } /// A triangle's attributes as a flattened triangle has them: the material its row names in place of the /// section, and no index in it (`rows`: the instance's). @@ -497,14 +497,8 @@ pub fn node_ranges<'a>(tri_nodes: &'a [(String, u32, u32)], id: &'a str) -> impl tri_nodes.iter().filter(move |(n, _, _)| n == id).map(|(_, a, b)| *a as usize..*b as usize) } -/// Texture-LOD constant change of a transform: texel density per metre scales with 1 / linear size, approximated by -/// the cube root of the volume scale (exact for uniform scale). -pub fn lod_offset(w: Mat4) -> f32 { - -glam::Mat3::from_mat4(w).determinant().abs().max(1e-30).log2() / 3.0 -} - /// Model-space shading attributes of a pool triangle placed by `w` (normals by the inverse transpose, tangent by the -/// matrix, its frame's hand changed by a mirroring one, texture-LOD constant by the scale), object `object`. +/// matrix, its frame's hand changed by a mirroring one), object `object`. pub fn instance_attr(a: &GpuTriAttr, w: Mat4, object: u32) -> GpuTriAttr { let m3 = glam::Mat3::from_mat4(w); let nm = m3.inverse().transpose(); @@ -514,7 +508,7 @@ pub fn instance_attr(a: &GpuTriAttr, w: Mat4, object: u32) -> GpuTriAttr { }; let t = (m3 * Vec3::new(a.t[0], a.t[1], a.t[2])).normalize_or_zero(); let hand = if mirrors(w) { -a.t[3] } else { a.t[3] }; - GpuTriAttr { n0: n(a.n0), n1: n(a.n1), n2: n(a.n2), uv: a.uv, t: [t.x, t.y, t.z, hand], x: [a.x[0] + lod_offset(w), f32::from_bits(object), a.x[2], a.x[3]] } + GpuTriAttr { n0: n(a.n0), n1: n(a.n1), n2: n(a.n2), uv: a.uv, t: [t.x, t.y, t.z, hand], x: [a.x[0], f32::from_bits(object), a.x[2], a.x[3]] } } #[repr(C)] @@ -525,7 +519,7 @@ pub struct GpuTriAttr { pub n2: [f32; 4], // normal2, w = uv1.x pub uv: [f32; 4], // uv1.y, uv2.x, uv2.y, material (bits) pub t: [f32; 4], // tangent (dP/du), w = bitangent sign - pub x: [f32; 4], // texture LOD constant 0.5*log2(uv area / world area), object index (bits), a particle's area, its emitter entry + 1 (bits; 0: not light-sampled) + pub x: [f32; 4], // a spare word, object index (bits), a particle's area, its emitter entry + 1 (bits; 0: not light-sampled) } #[repr(C)] @@ -2729,18 +2723,14 @@ pub fn tri_attr(p: [Vec3; 3], n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<(Vec3 let w = if n[0].cross(t).dot(b) < 0.0 { 1.0 } else { -1.0 }; (t, w) }); - // Texel density for ray-cone mip selection: lod = log2(cone width) + 0.5*log2(uv area / world area) + log2(size). - let world_area = 0.5 * (p[1] - p[0]).cross(p[2] - p[0]).length(); - let (d1, d2) = (uv[1] - uv[0], uv[2] - uv[0]); - let uv_area = 0.5 * (d1.x * d2.y - d2.x * d1.y).abs(); - let lod_k = if world_area > 1e-12 && uv_area > 1e-14 { 0.5 * (uv_area / world_area).log2() } else { 0.0 }; + // (Its texel density, for the mip choice, is the hit's to compute: pathtrace.wgsl `mesh_lod`.) GpuTriAttr { n0: [n[0].x, n[0].y, n[0].z, uv[0].x], n1: [n[1].x, n[1].y, n[1].z, uv[0].y], n2: [n[2].x, n[2].y, n[2].z, uv[1].x], uv: [uv[1].y, uv[2].x, uv[2].y, f32::from_bits(mat)], t: [t.x, t.y, t.z, sign], - x: [lod_k, 0.0, 0.0, 0.0], + x: [0.0, 0.0, 0.0, 0.0], } } @@ -2847,9 +2837,6 @@ mod instance_tests { } assert_eq!(got.uv, flat.uv, "mirrored {mirrored}"); assert_eq!(got_colors, Some(order.map(|k| colors[k])), "mirrored {mirrored}: the vertex colours follow their vertices"); - // Uniform scale 2: texel density per metre halves (LOD constant - 1), exactly as the world-space triangle. - assert!((got.x[0] - flat.x[0]).abs() < 1e-5); - assert!((lod_offset(w) + 1.0).abs() < 1e-5); assert_eq!(got.x[1].to_bits(), 3); } } diff --git a/renderer/src/skin.rs b/renderer/src/skin.rs index bc309c6..a46631b 100644 --- a/renderer/src/skin.rs +++ b/renderer/src/skin.rs @@ -747,7 +747,7 @@ mod bench { let mut x = 0.0; for _ in 0..100 { for t in &tris { - x += crate::scene::tri_attr(t.p, t.n, t.uv, t.tangent, 0).x[0]; + x += crate::scene::tri_attr(t.p, t.n, t.uv, t.tangent, 0).t[0]; } } eprintln!("tri_attr: {:.3} ms per pose ({x})", t0.elapsed().as_secs_f64() * 1000.0 / 100.0); diff --git a/tests/render/shadow-glass-map-instance-large.ts b/tests/render/shadow-glass-map-instance-large.ts new file mode 100644 index 0000000..771ea24 --- /dev/null +++ b/tests/render/shadow-glass-map-instance-large.ts @@ -0,0 +1,8 @@ +// shadow/glass-map-instance with the instance scaled 32 times (its geometry 3 cm): the map's level from the pane's own +// size would be five too high. +import { type TestMeta } from "./lib.ts"; +import { build, test as base } from "./shadow-glass-map-instance.ts"; + +export const test: TestMeta = { ...base, id: "shadow/glass-map-instance-large", note: "pane 1 x 1 m (a box of 3.1 cm scaled 32 times) at y = 1 under a light at y = 2" }; + +export default () => build(32); diff --git a/tests/render/shadow-glass-map-instance.ts b/tests/render/shadow-glass-map-instance.ts new file mode 100644 index 0000000..efa3040 --- /dev/null +++ b/tests/render/shadow-glass-map-instance.ts @@ -0,0 +1,36 @@ +// shadow/glass-tint with a clear pane whose colour map is white in a square at its middle (24 of 64 texels) and black +// around it, the pane an instance scaled to 1 / 32 of its geometry: the shadow rays from the patch under its middle +// pass the white square at each of its two surfaces, and the plane reads 0.5 I / 4 / pi x 0.96^2. The map's level +// is the pane's as it stands (pathtrace.wgsl `glass_at`): five levels too high the square is a seventh grey. +import { BoxGeometry, Color, DataTexture, Mesh, MeshPhysicalMaterial, PointLight } from "@threert/scene"; +import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts"; +import { CLEAR, test as base } from "./shadow-glass-tint.ts"; + +export const test: TestMeta = { + ...base, id: "shadow/glass-map-instance", features: [...base.features, "textures", "instancing"], + metric: { kind: "radiance", region: [0.48, 0.48, 0.52, 0.52], expected: CLEAR * 0.96 ** 2, tolerance: 0.02 }, + note: "pane 1 x 1 m (a box of 32 m scaled 1 / 32) at y = 1 under a light at y = 2; the white square is 37.5 cm (the patch's rays cross 17 cm of it)", +}; + +/** The scene with the pane's geometry 1 / `scale` of the pane and its instance scaled by `scale`. */ +export function build(scale: number) { + const scene = sceneWithSky(0); + const l = new PointLight(0xffffff, 1000, 0); + l.radius = 0.001; + l.position.set(0, 2, 0); + const px = new Uint8Array(64 * 64 * 4); + for (let y = 0; y < 64; y++) { + for (let x = 0; x < 64; x++) { + const on = x >= 20 && x < 44 && y >= 20 && y < 44 ? 255 : 0; + px.set([on, on, on, 255], (y * 64 + x) * 4); + } + } + const glass = new MeshPhysicalMaterial({ name: "pane", color: new Color().setRGB(1, 1, 1), map: new DataTexture(64, 64, px, "srgb"), transmission: 1, ior: 1.5, roughness: 0, metalness: 0 }); + const pane = new Mesh(new BoxGeometry(1 / scale, 0.05 / scale, 1 / scale), glass); + pane.name = "pane"; + pane.scale.setScalar(scale); + pane.position.set(0, 1, 0); + return result(scene, camera(scene, [0, 0.6, 3], [0, 0, 0]), [l, pane, plane(20, lambert(0.5))]); +} + +export default () => build(1 / 32); diff --git a/tests/render/texture-level-instance-cutout.ts b/tests/render/texture-level-instance-cutout.ts new file mode 100644 index 0000000..4075e5e --- /dev/null +++ b/tests/render/texture-level-instance-cutout.ts @@ -0,0 +1,18 @@ +// texture/level-instance for the alpha test of a candidate hit (pathtrace.wgsl `alpha_pass`): the same quad, black, +// its checker in the alpha (test at 0.5), its geometry 8 mm scaled 256 times. A square that is kept reads 0, a hole +// shows the sky, 1. From the quad's own size the level would be eight too high: the alpha 0.5 all over, the quad all +// there or all gone. (Three levels too high a square's middle is still its own: a test at 0.5 sees no less.) +import { Color, MeshPhysicalMaterial } from "@threert/scene"; +import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts"; +import { LEFT, RIGHT, checker, quad } from "./texture-level-instance.ts"; + +export const test: TestMeta = { + id: "texture/level-instance-cutout", features: ["textures", "instancing", "cutout"], reference: "analytic", temporal: false, + metric: { kind: "ratio", a: LEFT, b: RIGHT, expected: 0, tolerance: 0.03 }, +}; + +export default function () { + const scene = sceneWithSky(1); + const m = new MeshPhysicalMaterial({ color: new Color().setRGB(0, 0, 0), map: checker(true), roughness: 1, specularIntensity: 0, alphaTest: 0.5, side: "double" }); + return result(scene, camera(scene, [0, 0, 3], [0, 0, 0]), [quad(m, 256)]); +} diff --git a/tests/render/texture-level-instance.ts b/tests/render/texture-level-instance.ts new file mode 100644 index 0000000..0b2f70f --- /dev/null +++ b/tests/render/texture-level-instance.ts @@ -0,0 +1,42 @@ +// A texture on an instance is as sharp as its triangles are large in the world, whatever the instance's scale: the +// texel density is taken from the triangle as it stands (pathtrace.wgsl `mesh_lod`). A quad of 6.25 cm scaled 32 +// times (2 m), a checker of 8 x 8 squares (64 x 64 texels) on a Lambert surface under a uniform sky of 1 nit, seen +// straight on: a square is 14 pixels wide, the texture magnified. A black square reads 0 and a white one 1; from the +// quad's own size the level would be five too high and both would read 0.5. +import { Color, DataTexture, Mesh, MeshPhysicalMaterial, PlaneGeometry } from "@threert/scene"; +import { camera, result, sceneWithSky, type Region, type TestMeta } from "./lib.ts"; + +/** The insides of the two squares above the centre: left of it a white one (a kept one), right of it a black one (a hole). */ +export const LEFT: Region = [0.44, 0.39, 0.47, 0.455]; +export const RIGHT: Region = [0.53, 0.39, 0.56, 0.455]; + +export const test: TestMeta = { + id: "texture/level-instance", features: ["textures", "instancing"], reference: "analytic", temporal: false, + metric: { kind: "ratio", a: RIGHT, b: LEFT, expected: 0, tolerance: 0.03 }, +}; + +/** 64 x 64 texels, 8 x 8 squares; `alpha`: the checker in the alpha (white all over), else in the colour. */ +export function checker(alpha = false): DataTexture { + const px = new Uint8Array(64 * 64 * 4); + for (let y = 0; y < 64; y++) { + for (let x = 0; x < 64; x++) { + const on = ((x >> 3) + (y >> 3)) % 2 === 0 ? 255 : 0; + px.set(alpha ? [255, 255, 255, on] : [on, on, on, 255], (y * 64 + x) * 4); + } + } + return new DataTexture(64, 64, px, "srgb"); +} + +/** The quad: 2 m, its geometry 1 / `scale` of that. */ +export function quad(material: MeshPhysicalMaterial, scale: number): Mesh { + const m = new Mesh(new PlaneGeometry(2 / scale, 2 / scale), material); + m.name = "quad"; + m.scale.setScalar(scale); + return m; +} + +export default function () { + const scene = sceneWithSky(1); + const m = new MeshPhysicalMaterial({ color: new Color().setRGB(1, 1, 1), map: checker(), roughness: 1, specularIntensity: 0 }); + return result(scene, camera(scene, [0, 0, 3], [0, 0, 0]), [quad(m, 32)]); +}