From ee1be7dcca68ddf04692d5a20b458cb80ee34b62 Mon Sep 17 00:00:00 2001 From: shinyobjectz Date: Mon, 23 Nov 2026 20:29:56 -0800 Subject: [PATCH] BK3: a texel's light comes from over the texel, and the trace is its own crate raea-sys-lighttrace holds the kernel (lib.rs, wgsl/), a facility systems/rt and LT5's path tracer may build on; the lightbake crate keeps the texels and calls it. The samples of a texel start from the open ones of 16 points over its footprint (on its triangle, clear of its edges, not inside other geometry as BK2's rays judge it), in place of its centre, so a ledge narrower than a texel counts as the part of it that can be seen, and a texel partly inside a block is lit by its open part. Two tests fail with centre starts. A sample's random seed no longer repeats when the count isn't a multiple of the pass. lightbake.py (the blender guide, another lane's, uncommitted here) has an opt-in --no-adaptive, used for the references of this comparison: Cycles' adaptive sampling bakes dark pockets up to 2x too dark. Not @done. --- Cargo.lock | 13 +++- Cargo.toml | 1 + docs/bake.feature | 19 +++--- systems/lightbake/Cargo.toml | 7 +-- systems/lightbake/src/lib.rs | 4 +- systems/lightbake/src/own.rs | 28 ++++++--- systems/lightbake/src/own/tests.rs | 35 +++++------ systems/lightbake/src/texels.rs | 49 ++++++++++++--- systems/lightbake/src/texels/tests.rs | 8 +-- .../src/{trace/tests.rs => trace_tests.rs} | 63 ++++++++++++++----- systems/lighttrace/Cargo.toml | 14 +++++ .../src/trace.rs => lighttrace/src/lib.rs} | 22 ++++--- .../src/wgsl/diffuse.wgsl | 0 .../src/wgsl/trace.wgsl | 32 +++++++--- tools/layers.toml | 3 + 15 files changed, 206 insertions(+), 92 deletions(-) rename systems/lightbake/src/{trace/tests.rs => trace_tests.rs} (74%) create mode 100644 systems/lighttrace/Cargo.toml rename systems/{lightbake/src/trace.rs => lighttrace/src/lib.rs} (93%) rename systems/{lightbake => lighttrace}/src/wgsl/diffuse.wgsl (100%) rename systems/{lightbake => lighttrace}/src/wgsl/trace.wgsl (85%) diff --git a/Cargo.lock b/Cargo.lock index cb855691..9f333d51 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -16360,15 +16360,22 @@ dependencies = [ name = "raea-sys-lightbake" version = "0.1.0" dependencies = [ - "bytemuck", "gltf", "image", "parry3d", - "pollster 0.4.0", - "raea-gpu-device", "raea-sys-atlas", + "raea-sys-lighttrace", "rayon", "serde_json", +] + +[[package]] +name = "raea-sys-lighttrace" +version = "0.1.0" +dependencies = [ + "bytemuck", + "pollster 0.4.0", + "raea-gpu-device", "wgpu", ] diff --git a/Cargo.toml b/Cargo.toml index 87068116..6a4e7cd2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -208,6 +208,7 @@ members = [ "apps/ask", "apps/lightbake", "systems/lightbake", + "systems/lighttrace", "systems/atlas", "apps/double", "apps/check", diff --git a/docs/bake.feature b/docs/bake.feature index daad0ecb..61edf8fe 100644 --- a/docs/bake.feature +++ b/docs/bake.feature @@ -32,6 +32,7 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac Background: Given systems/rt (raea-sys-rt): BLAS per mesh from Bevy's own buffers, a TLAS of visible opaque instances, glass left out so sky and sun reach through windows; its traced AO, raea GI's world probes and cache (LT2, LT3) + And raea-sys-lighttrace, the kernel of BK3, split from the bake so systems/rt and LT5's path tracer can build on it And tools/cycles-port/cycles_bsdf.wgsl: GGX/Beckmann D, G2, Fresnel, F82 conductors, VNDF sampling, passing against Cycles on an M5 Pro; diffuse and energy-conserving Oren-Nayar next And (sdk/render/src/bevy3d/lightmap.tsx, systems/material lightmap.rs): Bevy's lightmap on a 's @@ -178,12 +179,12 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac Scenario: BK3. The light that bounces, traced on raea's ray tracer Given the plan | crate | file | lines | job | - | raea-sys-lightbake | systems/lightbake/src/trace/tests.rs | 185 | a white furnace, a wall's form factor, a glowing box, a red wall's bleed, the sun at a texel and at a hit, a panorama's direction, a ray straight up, a textured floor, the same bytes twice; the measured run | - | raea-sys-lightbake | systems/lightbake/src/own.rs | 165 | a model read on its own second UVs (a map a mesh, as lightbake.py lays them): its world triangles, base colour and textures, and each map's texels | + | raea-sys-lightbake | systems/lightbake/src/trace_tests.rs | 240 | a white furnace, a wall's form factor, a glowing box, a red wall's bleed, the sun at a texel and at a hit, a panorama's direction, a ray straight up, a textured floor, the same bytes twice; the measured run | + | raea-sys-lightbake | systems/lightbake/src/own.rs | 185 | a model read on its own second UVs (a map a mesh, as lightbake.py lays them): its world triangles, base colour and textures, and each map's texels | | raea-sys-lightbake | systems/lightbake/src/own/tests.rs | 145 | its texels on a known quad; the ignored run against a Cycles bake of the same .glb | - | raea-sys-lightbake | systems/lightbake/src/wgsl/diffuse.wgsl | 40 | the diffuse BSDF and the paths' random numbers, a module systems/rt and LT5's path tracer can include as it is | - | raea-sys-lightbake | systems/lightbake/src/trace.rs | 260 | the passes: dispatch per atlas, samples accumulated over passes, progress, cancel | - | raea-sys-lightbake | systems/lightbake/src/wgsl/trace.wgsl | 250 | per texel: cosine-weighted paths against the bake's own TLAS; the sky from the composition's , emissives, baked lights; Russian roulette; Cycles' BSDFs from cycles-port at each bounce | + | raea-sys-lighttrace | systems/lighttrace/src/wgsl/diffuse.wgsl | 40 | the diffuse BSDF and the paths' random numbers, a module systems/rt and LT5's path tracer can include as it is | + | raea-sys-lighttrace | systems/lighttrace/src/lib.rs | 260 | the passes: dispatch per atlas, samples accumulated over passes, progress, cancel | + | raea-sys-lighttrace | systems/lighttrace/src/wgsl/trace.wgsl | 250 | per texel: cosine-weighted paths against the bake's own TLAS; the sky from the composition's , emissives, baked lights; Russian roulette; Cycles' BSDFs from cycles-port at each bounce | Then each texel integrates the incoming diffuse light over its hemisphere along paths of up to `bounces` (default 4) through a BLAS and TLAS the bake builds itself from the meshes raea draws, by the wgpu ray queries systems/rt uses. (Not rt's own: a bake runs offline, before any frame, with no Bevy render world to hold them, @@ -236,9 +237,11 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac And the 8, by the trace's light over Cycles': 4 are the footprint. The trace starts every ray at the texel's centre, and Cycles jitters its samples over the texel; on 30 mm texels a sheet's 6 mm ledge is all or nothing. Traced 8x8 points a texel and averaged, over the same texels: bench_stock 0.333 -> 0.960, bench_mat 1.333 -> - 1.006, dt_ledge 1.291 -> 0.997, dt_rule 0.765 -> 1.068; bench_strips only 0.616 -> 0.679. To be built: jittered - starts in the kernel, kept on the triangle, with the samples that start inside other geometry left out of - the mean (a partly buried texel is half seen) + 1.006, dt_ledge 1.291 -> 0.997, dt_rule 0.765 -> 1.068; bench_strips only 0.616 -> 0.679. Built after it: + a texel starts from the open ones of 16 points over its footprint (on its triangle, clear of its edges, not + inside other geometry, as BK2's rays judge them), so a partly buried texel is lit by what can be seen of it. A texel + under a sheet's edge, three quarters of it covered, reads 0.2495 for 0.249 where its centre alone reads 0; one + three quarters inside a block reads 0.52 from its open quarter And the other 4 are the reference's: Cycles' adaptive sampling (on by default, threshold 0.01; lightbake.py doesn't turn it off) stops a dark pocket's pixel before it has seen the light, so a cup or a shelf's back bakes too dark. With it off (1024 samples, the same meshes, raw floats): mug_coffee 1.94 -> 1.012, books_5 1.279 -> 1.021, meet_tea diff --git a/systems/lightbake/Cargo.toml b/systems/lightbake/Cargo.toml index 7b28a5e5..c5bb7973 100644 --- a/systems/lightbake/Cargo.toml +++ b/systems/lightbake/Cargo.toml @@ -13,11 +13,8 @@ raea-sys-atlas = { path = "../atlas" } parry3d = "0.31" rayon = "1" serde_json = "1" -# the process's one shared GPU device, and wgpu's ray queries on it (BK3) -raea-gpu-device = { path = "../../gpu/device" } -wgpu = "=30.0.1" -bytemuck = "1" -pollster = "0.4" +# the paths the light is traced along (BK3) +raea-sys-lighttrace = { path = "../lighttrace" } # a model read on its own second UVs (own.rs): its meshes, and its base colour textures decoded gltf = { version = "1.4", default-features = false, features = ["utils", "names"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } diff --git a/systems/lightbake/src/lib.rs b/systems/lightbake/src/lib.rs index fa8cfa5d..1f76fe11 100644 --- a/systems/lightbake/src/lib.rs +++ b/systems/lightbake/src/lib.rs @@ -7,5 +7,5 @@ // each texel's ray origin and the texels inside other geometry (BK2) pub mod own; pub mod texels; -// the light that bounces, traced on the GPU (BK3) -pub mod trace; +#[cfg(test)] +mod trace_tests; diff --git a/systems/lightbake/src/own.rs b/systems/lightbake/src/own.rs index cad040e0..573671c3 100644 --- a/systems/lightbake/src/own.rs +++ b/systems/lightbake/src/own.rs @@ -7,8 +7,11 @@ use parry3d::glamx::{Mat4, Vec2, Vec3}; use std::collections::HashMap; use std::ops::Range; -use crate::texels::off_edges; -use crate::trace::{Image, Surface}; +use parry3d::shape::TriMesh; +use rayon::prelude::*; + +use crate::texels::starts; +use raea_sys_lighttrace::{Image, Surface}; pub struct Mesh { pub name: String, @@ -16,7 +19,7 @@ pub struct Mesh { pub triangles: Range, } -/// A .glb's meshes in the world, as trace::World takes them, with each vertex's second UV. +/// A .glb's meshes in the world, as World takes them, with each vertex's second UV. #[derive(Default)] pub struct Model { pub positions: Vec<[f32; 3]>, @@ -33,8 +36,10 @@ pub struct Model { pub struct At { pub x: u32, pub y: u32, - /// its ray origin, off its triangle's edges and its plane + /// its point off the surface, the sides of its footprint and its open starts (texels::starts) pub origin: [f32; 3], + pub sides: [[f32; 3]; 2], + pub open: u32, /// the shading normal there (the vertices', interpolated), on the plane's side pub normal: [f32; 3], } @@ -116,7 +121,7 @@ fn texture(m: &mut Model, image: &gltf::Image, blob: &[u8], images: &mut HashMap /// A mesh's texels on its second UVs at `side` by `side`, each once (the first triangle over its centre); `offset` as /// Texels' own. -pub fn texels(m: &Model, mesh: &Mesh, side: u32, offset: f32) -> Vec { +pub fn texels(m: &Model, mesh: &Mesh, world: &TriMesh, side: u32, offset: f32) -> Vec { let mut taken = vec![false; (side * side) as usize]; let mut out = vec![]; for tri in &m.triangles[mesh.triangles.clone()] { @@ -128,8 +133,9 @@ pub fn texels(m: &Model, mesh: &Mesh, side: u32, offset: f32) -> Vec { if area.abs() < 1e-9 || plane.length_squared() < 1e-24 { continue; } - // half a texel, in metres on this triangle - let half = 0.5 * (plane.length() / area.abs()).sqrt(); + // a texel's sides on this triangle, metres + let (e1, e2) = (Vec2::from(uv[1]) - Vec2::from(uv[0]), Vec2::from(uv[2]) - Vec2::from(uv[0])); + let sides = [((pos[1] - pos[0]) * e2.y - (pos[2] - pos[0]) * e1.y) / area, ((pos[2] - pos[0]) * e1.x - (pos[1] - pos[0]) * e2.x) / area]; let span = |k: usize| { let (lo, hi) = uv.iter().fold((f32::MAX, f32::MIN), |(l, h), q| (l.min(q[k]), h.max(q[k]))); ((lo - 0.5).ceil().max(0.0) as u32, ((hi - 0.5).floor() as i64).clamp(-1, side as i64 - 1)) @@ -150,12 +156,14 @@ pub fn texels(m: &Model, mesh: &Mesh, side: u32, offset: f32) -> Vec { if n.dot(shade) < 0.0 { n = -n; } - let origin = off_edges(pos, p, 4.0 * offset, half) + n * offset; - out.push(At { x: x as u32, y: y as u32, origin: origin.to_array(), normal: if shade == Vec3::ZERO { n } else { shade }.to_array() }); + out.push((At { x: x as u32, y: y as u32, origin: p.to_array(), sides: sides.map(|s| s.to_array()), open: 0, normal: if shade == Vec3::ZERO { n } else { shade }.to_array() }, n, pos)); } } } - out + out.into_par_iter().enumerate().map(|(k, (a, n, pos))| { + let (origin, open) = starts(world, pos, Vec3::from(a.origin), n, a.sides.map(Vec3::from), offset, k as u32); + At { origin, open, ..a } + }).collect() } #[cfg(test)] diff --git a/systems/lightbake/src/own/tests.rs b/systems/lightbake/src/own/tests.rs index 55eafb11..e83369a5 100644 --- a/systems/lightbake/src/own/tests.rs +++ b/systems/lightbake/src/own/tests.rs @@ -1,8 +1,6 @@ use super::*; use crate::texels::tests::{cuboid, glb}; -use crate::texels::inside; -use crate::trace::{Settings, Sky, Starts, Sun, World, trace}; -use rayon::prelude::*; +use raea_sys_lighttrace::{Settings, Sky, Starts, Sun, World, trace}; #[test] fn a_model_reads_in_the_world_with_what_its_metal_leaves() { @@ -27,12 +25,14 @@ fn texels_lie_where_the_second_uvs_put_them() { meshes: vec![Mesh { name: "wall".into(), triangles: 0..2 }], ..Model::default() }; - let t = texels(&m, &m.meshes[0], 16, 1e-4); + let world = parry3d::shape::TriMesh::new(m.positions.iter().map(|p| Vec3::from(*p)).collect(), m.triangles.clone()).unwrap(); + let t = texels(&m, &m.meshes[0], &world, 16, 1e-4); assert_eq!(t.len(), 8 * 8, "a quarter of 16 x 16, each once"); for a in &t { let want = [(a.x as f32 + 0.5) / 8.0 * 2.0, 1.0 - (a.y as f32 + 0.5 - 8.0) / 8.0]; assert!((a.origin[0] - want[0]).abs() < 1e-2 && (a.origin[1] - want[1]).abs() < 1e-2 && (a.origin[2] - 3.0001).abs() < 1e-5, "{},{} at {:?}", a.x, a.y, a.origin); assert_eq!(a.normal, [0.0, 0.0, 1.0]); + assert_eq!(a.sides, [[0.25, 0.0, 0.0], [0.0, -0.125, 0.0]], "a texel's sides"); } } @@ -56,7 +56,7 @@ fn smooth(side: usize, map: &mut Vec>, passes: usize) { /// .blend held, and each map against Cycles' (compare.rs's map_stops: the mean distance in stops and the signed one, /// over the texels both cover, Cycles' clipped ones out). RAEA_BAKE_DIR holds set.glb, set.lightmaps.json and /// lightmaps/, RAEA_BAKE_SKY the panorama; _RUNS ("512x4": samples x bounces, each in turn), _STRENGTH, _ROTATION, _SMOOTH, _SUN ("x,y,z,r,g,b") -/// _ONLY (mesh names), _FINE (points a side of each texel), _DUMP (a folder: each map's luminances, raea's and Cycles', and the texel's place, as f32 threes) +/// _ONLY (mesh names), _DUMP (a folder: each map's luminances, raea's and Cycles', and the texel's place, as f32 threes) /// and _OUT (each run's table, OUT-RUN.json). #[test] #[ignore] @@ -73,8 +73,7 @@ fn against_cycles() { let v: Vec = s.split(',').map(|x| x.parse().unwrap()).collect(); Sun { dir: [v[0], v[1], v[2]], irradiance: [v[3], v[4], v[5]], half_angle: 0.00459 } }); - // each texel traced as fine x fine points of its footprint, then averaged (what Cycles' jittered samples see) - let fine = number("RAEA_BAKE_FINE", 1.0) as u32; + let world = parry3d::shape::TriMesh::new(m.positions.iter().map(|p| Vec3::from(*p)).collect(), m.triangles.clone()).unwrap(); let mut maps = vec![]; for l in listed["meshes"].as_array().unwrap() { let name = l["mesh"].as_str().unwrap(); @@ -83,20 +82,20 @@ fn against_cycles() { } let mesh = m.meshes.iter().find(|x| x.name == name).unwrap_or_else(|| panic!("no mesh {name}")); let side = l["size"].as_u64().unwrap() as u32; - maps.push((name.to_string(), mesh, side, l["lightmap_exposure"].as_f64().unwrap() as f32 / 683.0, texels(&m, mesh, side * fine, offset))); + maps.push((name.to_string(), mesh, side, l["lightmap_exposure"].as_f64().unwrap() as f32 / 683.0, texels(&m, mesh, &world, side, offset))); } let origin: Vec<[f32; 3]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.origin)).collect(); + let sides: Vec<[[f32; 3]; 2]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.sides)).collect(); + let open: Vec = maps.iter().flat_map(|x| x.4.iter().map(|a| a.open)).collect(); let normal: Vec<[f32; 3]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.normal)).collect(); - let mesh = parry3d::shape::TriMesh::new(m.positions.iter().map(|p| Vec3::from(*p)).collect(), m.triangles.clone()).unwrap(); - let hid: Vec = (0..origin.len()).into_par_iter().map(|i| inside(&mesh, Vec3::from(origin[i]), Vec3::from(normal[i]), i as u32)).collect(); - println!("{} meshes, {} triangles, {} texels, {} inside, {} textures; read and laid in {:.1} s", m.meshes.len(), m.triangles.len(), origin.len(), hid.iter().filter(|h| **h).count(), m.textures.len(), t0.elapsed().as_secs_f64()); + println!("{} meshes, {} triangles, {} texels, {} inside, {} textures; read and laid in {:.1} s", m.meshes.len(), m.triangles.len(), origin.len(), open.iter().filter(|m| **m == 0).count(), m.textures.len(), t0.elapsed().as_secs_f64()); let runs = std::env::var("RAEA_BAKE_RUNS").unwrap_or("512x4".into()); let w = World { positions: &m.positions, triangles: &m.triangles, surfaces: &m.surfaces, uvs: &m.uvs, textures: &m.textures }; for run in runs.split(',') { let [samples, bounces] = run.split('x').collect::>().try_into().expect("SAMPLESxBOUNCES"); let s = Settings { samples: samples.parse().unwrap(), bounces: bounces.parse().unwrap(), per_pass: 8, sky: sky.clone(), sun }; let t1 = std::time::Instant::now(); - let light = trace(&w, &Starts { origin: &origin, normal: &normal, inside: &hid, offset }, &s, &mut |_, _| {}).unwrap(); + let light = trace(&w, &Starts { origin: &origin, normal: &normal, sides: &sides, open: &open, offset }, &s, &mut |_, _| {}).unwrap(); let seconds = t1.elapsed().as_secs_f64(); println!("{} values that aren't finite", light.iter().flatten().filter(|v| !v.is_finite()).count()); println!("{run}: traced {} samples, {} bounces in {seconds:.1} s", s.samples, s.bounces); @@ -106,16 +105,10 @@ fn against_cycles() { for (name, mesh, side, scale, at) in &maps { let side = *side as usize; let mut mine = vec![None; side * side]; - let (mut got, mut open) = (vec![([0.0f32; 3], 0u32); side * side], vec![false; side * side]); for (k, a) in at.iter().enumerate() { - let i = (a.y / fine) as usize * side + (a.x / fine) as usize; - // a point inside other geometry is dark, and counts: a texel half buried is half lit - let v = if hid[first + k] { [0.0; 3] } else { light[first + k] }; - open[i] |= !hid[first + k]; - got[i] = ([got[i].0[0] + v[0], got[i].0[1] + v[1], got[i].0[2] + v[2]], got[i].1 + 1); - } - for i in (0..side * side).filter(|&i| open[i]) { - mine[i] = Some(got[i].0.map(|c| c / got[i].1 as f32)); + if open[first + k] != 0 { + mine[a.y as usize * side + a.x as usize] = Some(light[first + k]); + } } first += at.len(); smooth(side, &mut mine, passes); diff --git a/systems/lightbake/src/texels.rs b/systems/lightbake/src/texels.rs index e5c28000..bc42e616 100644 --- a/systems/lightbake/src/texels.rs +++ b/systems/lightbake/src/texels.rs @@ -13,6 +13,7 @@ use rayon::prelude::*; use serde_json::{Value, json}; use raea_sys_atlas::rays::{hemi, sample}; +use raea_sys_lighttrace::CENTRE; pub use raea_sys_atlas::{Layout, Texel}; /// Rays each texel casts for the inside test: cosine-weighted, the atlas's rotated R2 sequence per texel. @@ -23,8 +24,10 @@ pub struct Texels { pub layout: Layout, /// each texel's ray origin: its surface point, four offsets in from its triangle's edges, moved `offset` along its normal pub origin: Vec<[f32; 3]>, - /// the texels inside other geometry (their rays meet back faces), left for BK4 to fill - pub inside: Vec, + /// the two sides of each texel's footprint, and which of the points over it are open (0 inside other geometry: their + /// rays meet back faces, left for BK4 to fill), as raea_sys_lighttrace::Starts takes them + pub sides: Vec<[[f32; 3]; 2]>, + pub open: Vec, /// metres off the surface: 1e-5 of the model's size or of its farthest coordinate, at least 10 microns pub offset: f32, /// the model's triangles in world space, for the trace (BK3) @@ -37,6 +40,13 @@ pub fn request(texels: f32, max_side: u32) -> Value { json!({ "env": { "density": texels, "max_side": max_side } }) } +impl Texels { + /// Which texels are inside other geometry, in the layout's order. + pub fn inside(&self) -> Vec { + self.open.iter().map(|&m| m == 0).collect() + } +} + /// Every texel of the model's atlas in the world: its origin and whether it's inside other geometry. pub fn texels(glb: &[u8], req: &Value) -> Result { let (layout, mesh) = raea_sys_atlas::laid(glb, req)?; @@ -45,13 +55,17 @@ pub fn texels(glb: &[u8], req: &Value) -> Result { (lo, hi, far) = (lo.min(v), hi.max(v), far.max(v.abs().max_element())); } let offset = (1e-5 * (hi - lo).length().max(far)).max(1e-5); - let half = 0.5 / layout.density; - let origin: Vec<[f32; 3]> = layout.texels.iter().map(|t| { - let tri = mesh.indices()[t.tri as usize].map(|v| mesh.vertices()[v as usize]); - (off_edges(tri, Vec3::from(t.p), 4.0 * offset, half) + Vec3::from(t.n) * offset).to_array() + // a texel of the atlas is a square of its density; its turn on the surface doesn't matter to its footprint + let sides: Vec<[[f32; 3]; 2]> = layout.texels.iter().map(|t| { + let n = Vec3::from(t.n); + let u = n.any_orthonormal_vector() / layout.density; + [u.to_array(), n.cross(u).to_array()] }).collect(); - let inside = layout.texels.par_iter().zip(&origin).enumerate().map(|(i, (t, &o))| inside(&mesh, Vec3::from(o), Vec3::from(t.n), i as u32)).collect(); - Ok(Texels { layout, origin, inside, offset, mesh }) + let (origin, open) = layout.texels.par_iter().zip(&sides).enumerate().map(|(i, (t, s))| { + let tri = mesh.indices()[t.tri as usize].map(|v| mesh.vertices()[v as usize]); + starts(&mesh, tri, Vec3::from(t.p), Vec3::from(t.n), s.map(Vec3::from), offset, i as u32) + }).unzip(); + Ok(Texels { layout, origin, sides, open, offset, mesh }) } /// Whether a texel is inside other geometry: of its rays that meet anything, at least half meet a back face and more @@ -69,6 +83,25 @@ pub(crate) fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool { back * 2 >= RAYS && back > front } +/// Where a texel's samples start: its point off the surface, and which of the 4 x 4 points of its footprint are open +/// (on its triangle, clear of its edges, not inside other geometry). A texel half buried keeps only its open half: +/// what it's averaged over is what can be seen. A corner and the centre that agree stand for the rest. +pub(crate) fn starts(mesh: &TriMesh, tri: [Vec3; 3], p: Vec3, n: Vec3, [u, v]: [Vec3; 2], offset: f32, seed: u32) -> ([f32; 3], u32) { + let gap = 4.0 * offset; + let centre = off_edges(tri, p, gap, 0.5 * u.length().max(v.length())) + n * offset; + let at = |c: u32| p + u * ((c % 4) as f32 / 4.0 - 0.375) + v * ((c / 4) as f32 / 4.0 - 0.375); + let cells: Vec = (0..16).filter(|&c| off_edges(tri, at(c), gap, f32::MAX).distance(at(c)) < 0.5 * offset).collect(); + let hid = inside(mesh, centre, n, seed); + let buried = |c: u32| inside(mesh, at(c) + n * offset, n, seed ^ (c + 1).wrapping_mul(0x9e37_79b9)); + if cells.is_empty() { + return (centre.to_array(), if hid { 0 } else { CENTRE }); + } + let corners: Vec = cells.iter().copied().filter(|c| [0, 3, 12, 15].contains(c)).collect(); + let mixed = corners.iter().any(|&c| buried(c) != hid) || (corners.is_empty() && cells.len() < 16); + let open = if !mixed { if hid { 0 } else { cells.iter().fold(0, |m, c| m | 1 << c) } } else { cells.iter().filter(|&&c| !buried(c)).fold(0, |m, c| m | 1 << c) }; + if open == 0 { (centre.to_array(), if hid { 0 } else { CENTRE }) } else { ((p + n * offset).to_array(), open) } +} + /// p moved along its triangle until it's `gap` from each edge, or by `most` (half a texel: its own footprint; a needle /// narrower than the gap would send it to its far end). A chart's /// edge band takes its texels from the edge itself, and a point on the edge of a floor is in the plane of the wall diff --git a/systems/lightbake/src/texels/tests.rs b/systems/lightbake/src/texels/tests.rs index 1b10471a..51848b33 100644 --- a/systems/lightbake/src/texels/tests.rs +++ b/systems/lightbake/src/texels/tests.rs @@ -100,7 +100,7 @@ fn a_point_on_an_edge_is_moved_off_it_and_never_far() { fn texels_inside_the_slab_are_marked_and_those_in_the_open_are_not() { let t = texels(&set(), &request(16.0, 1024)).unwrap(); let (mut sunk, mut open, mut under) = (0, 0, 0); - for (x, &inside) in t.layout.texels.iter().zip(&t.inside) { + for (x, &inside) in t.layout.texels.iter().zip(&t.inside()) { let [px, py, pz] = x.p; if (-0.18..-0.02).contains(&py) && px.abs() < 0.26 && pz.abs() < 0.26 { // the block's sides within the slab's thickness, away from its faces @@ -123,7 +123,7 @@ fn texels_inside_the_slab_are_marked_and_those_in_the_open_are_not() { #[test] fn the_same_model_gives_the_same_texels() { let (a, b) = (texels(&set(), &request(16.0, 1024)).unwrap(), texels(&set(), &request(16.0, 1024)).unwrap()); - assert!(a.layout == b.layout && a.origin == b.origin && a.inside == b.inside); + assert!(a.layout == b.layout && a.origin == b.origin && a.open == b.open); } #[test] @@ -143,11 +143,11 @@ fn measured() { let layout = raea_sys_atlas::layout(&glb, &request(64.0, 4096)).unwrap(); let t1 = std::time::Instant::now(); let t = texels(&glb, &request(64.0, 4096)).unwrap(); - let inside = t.inside.iter().filter(|&&i| i).count(); + let inside = t.inside().iter().filter(|&&i| i).count(); if let Ok(out) = std::env::var("RAEA_BAKE_OUT") { // the atlas: grey where a texel is in the open, red where it's inside, black where there's none (a PPM) let mut img = vec![0u8; (layout.w * layout.h * 3) as usize]; - for (x, &i) in t.layout.texels.iter().zip(&t.inside) { + for (x, &i) in t.layout.texels.iter().zip(&t.inside()) { let k = 3 * (x.y as usize * layout.w as usize + x.x as usize); img[k..k + 3].copy_from_slice(if i { &[230, 40, 30] } else { &[150, 150, 150] }); } diff --git a/systems/lightbake/src/trace/tests.rs b/systems/lightbake/src/trace_tests.rs similarity index 74% rename from systems/lightbake/src/trace/tests.rs rename to systems/lightbake/src/trace_tests.rs index 3956f712..bd8a5e6b 100644 --- a/systems/lightbake/src/trace/tests.rs +++ b/systems/lightbake/src/trace_tests.rs @@ -1,6 +1,7 @@ -use super::*; +use raea_sys_lighttrace::*; use crate::texels::tests::{cuboid, glb, set}; -use crate::texels::{request, texels}; +use crate::texels::{request, starts, texels}; +use parry3d::glamx::Vec3; fn world(mesh: &parry3d::shape::TriMesh, surfaces: &[Surface]) -> (Vec<[f32; 3]>, Vec<[u32; 3]>, Vec) { (mesh.vertices().iter().map(|v| v.to_array()).collect(), mesh.indices().to_vec(), surfaces.to_vec()) @@ -12,7 +13,7 @@ fn run(t: &crate::texels::Texels, surface: impl Fn([f32; 3]) -> Surface, s: &Set let surfaces: Vec = t.mesh.indices().iter().map(|i| surface(std::array::from_fn(|k| i.iter().map(|&j| v[j as usize][k]).sum::() / 3.0))).collect(); let (p, i, s2) = world(&t.mesh, &surfaces); let normal: Vec<[f32; 3]> = t.layout.texels.iter().map(|x| x.n).collect(); - let starts = Starts { origin: &t.origin, normal: &normal, inside: &t.inside, offset: t.offset }; + let starts = Starts { origin: &t.origin, normal: &normal, sides: &t.sides, open: &t.open, offset: t.offset }; trace(&World { positions: &p, triangles: &i, surfaces: &s2, uvs: &[], textures: &[] }, &starts, s, &mut |_, _| {}).unwrap() } @@ -23,7 +24,7 @@ fn a_white_furnace_is_the_sky_at_every_texel() { let t = texels(&set(), &request(8.0, 1024)).unwrap(); let s = Settings { samples: 64, bounces: 64, per_pass: 16, sky: Sky::even([1.0; 3]), ..Settings::default() }; let light = run(&t, |_| Surface { albedo: [1.0; 3], emission: [0.0; 3], texture: None }, &s); - let open: Vec<[f32; 3]> = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| *l).collect(); + let open: Vec<[f32; 3]> = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| *l).collect(); let off = open.iter().filter(|l| l.iter().any(|c| (c - 1.0).abs() > 0.01)).count(); println!("furnace: {off} of {} off by more than 1%", open.len()); let worst = open.iter().flatten().fold(0.0f32, |m, c| m.max((c - 1.0).abs())); @@ -53,8 +54,8 @@ fn a_glowing_box_adds_up_its_bounces() { let inward = cuboid([-1.0; 3], [1.0; 3]).into_iter().map(|[a, b, c]| [a, c, b]).collect(); let t = texels(&glb(&[(inward, [0.0; 3])]), &request(8.0, 1024)).unwrap(); let light = run(&t, |_| Surface { albedo: [0.5; 3], emission: [1.0; 3], texture: None }, &Settings { samples: 64, bounces: 64, per_pass: 16, sky: Sky::even([0.0; 3]), ..Settings::default() }); - let mean = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| l[0]).sum::() / t.inside.iter().filter(|i| !**i).count() as f32; - println!("box: {mean:.4} for 2, {} of {} texels marked inside", t.inside.iter().filter(|i| **i).count(), t.inside.len()); + let mean = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| l[0]).sum::() / t.inside().iter().filter(|i| !**i).count() as f32; + println!("box: {mean:.4} for 2, {} of {} texels marked inside", t.inside().iter().filter(|i| **i).count(), t.inside().len()); assert!((mean - 2.0).abs() < 0.01, "the glowing box's light is {mean}, not 2"); } @@ -68,7 +69,7 @@ fn a_red_wall_bleeds_onto_the_floor() { let light = run(&t, red, &Settings { samples: 128, bounces: 4, per_pass: 32, sky: Sky::even([1.0; 3]), ..Settings::default() }); // floor top texels near the wall (x -0.9..-0.7) and far (x > 0.6) let mean = |near: bool| { - let v: Vec = t.layout.texels.iter().zip(&light).zip(&t.inside).filter(|((x, _), i)| !**i && x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && if near { x.p[0] < -0.7 } else { x.p[0] > 0.6 }).map(|((_, l), _)| l[1] / l[0]).collect(); + let v: Vec = t.layout.texels.iter().zip(&light).zip(&t.inside()).filter(|((x, _), i)| !**i && x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && if near { x.p[0] < -0.7 } else { x.p[0] > 0.6 }).map(|((_, l), _)| l[1] / l[0]).collect(); v.iter().sum::() / v.len() as f32 }; let (near, far) = (mean(true), mean(false)); @@ -87,10 +88,44 @@ fn the_same_bake_gives_the_same_bytes() { #[test] fn mismatched_inputs_are_refused() { - let starts = Starts { origin: &[[0.0; 3]], normal: &[], inside: &[], offset: 1e-4 }; + let starts = Starts { origin: &[[0.0; 3]], normal: &[], sides: &[], open: &[], offset: 1e-4 }; assert!(trace(&World { positions: &[], triangles: &[], surfaces: &[], uvs: &[], textures: &[] }, &starts, &Settings::default(), &mut |_, _| {}).is_err()); } +/// A floor, and something on it: the light on a texel 0.4 m a side whose centre is 0.1 m under its edge at x = 0, by +/// its starts, and which of them are open. +fn half_covered(on_it: &[crate::texels::tests::Tri], samples_at_centre: bool) -> (f32, u32) { + let floor = [[-40.0, 0.0, -40.0], [-40.0, 0.0, 80.0], [80.0, 0.0, -40.0]]; + let mesh = parry3d::shape::TriMesh::new(std::iter::once(floor).chain(on_it.iter().copied()).flatten().map(Vec3::from).collect(), (0..on_it.len() as u32 + 1).map(|k| [3 * k, 3 * k + 1, 3 * k + 2]).collect()).unwrap(); + let sides = [[0.4, 0.0, 0.0], [0.0, 0.0, 0.4]]; + let (origin, open) = starts(&mesh, floor.map(Vec3::from), Vec3::new(0.1, 0.0, 0.0), Vec3::Y, sides.map(Vec3::from), 1e-4, 7); + let (p, i, s) = world(&mesh, &vec![Surface::default(); mesh.indices().len()]); + let st = Starts { origin: &[origin], normal: &[[0.0, 1.0, 0.0]], sides: &[sides], open: &[if samples_at_centre { CENTRE } else { open }], offset: 1e-4 }; + let l = trace(&World { positions: &p, triangles: &i, surfaces: &s, uvs: &[], textures: &[] }, &st, &Settings { samples: 4096, ..Settings::default() }, &mut |_, _| {}).unwrap(); + (l[0][0], open) +} + +/// A texel with a sheet 0.2 mm over three quarters of it (a stack's ledge): a quarter of the sky, as Cycles' jittered +/// samples see, where its centre alone sees nothing. +#[test] +fn a_texel_under_a_sheets_edge_sees_the_part_that_is_open() { + let sheet = cuboid([0.0, 0.0002, -10.0], [10.0, 0.0052, 10.0]); + let (centre, _) = half_covered(&sheet, true); + let (over, open) = half_covered(&sheet, false); + println!("ledge: centre {centre:.4}, over the texel {over:.4} for 0.249, open {open:#x}"); + assert!(centre < 0.01 && (over - 0.249).abs() < 0.01 && open == 0xffff, "{centre} {over} {open:#x}"); +} + +/// A texel three quarters inside a block sunk in the floor: only its open quarter counts, not that quarter averaged with +/// the dark inside. +#[test] +fn a_texel_half_buried_is_lit_by_its_open_part() { + let block = cuboid([0.0, -1.0, -10.0], [10.0, 1.0, 10.0]); + let (over, open) = half_covered(&block, false); + println!("block: {over:.4} over its open part, open {open:#x}"); + assert!(open == 0x1111 && (0.48..0.58).contains(&over), "{over} {open:#x}"); +} + /// A 40 m floor lit by the sun at 45 degrees and nothing else: a point 0.1 m over it looking down gets the sunlit /// floor's light, albedo x irradiance x cos 45 / pi; a point on the floor gets nothing, its own sun being live. #[test] @@ -98,7 +133,7 @@ fn the_sun_lights_what_it_bounces_to_and_not_the_texel_itself() { let p = [[-20.0, 0.0, -20.0], [20.0, 0.0, -20.0], [20.0, 0.0, 20.0], [-20.0, 0.0, 20.0]]; let surfaces = [Surface { albedo: [0.5; 3], ..Surface::default() }; 2]; let world = World { positions: &p, triangles: &[[0, 2, 1], [0, 3, 2]], surfaces: &surfaces, uvs: &[], textures: &[] }; - let starts = Starts { origin: &[[0.0, 0.1, 0.0], [8.0, 1e-4, 0.0]], normal: &[[0.0, -1.0, 0.0], [0.0, 1.0, 0.0]], inside: &[false; 2], offset: 1e-4 }; + let starts = Starts { origin: &[[0.0, 0.1, 0.0], [8.0, 1e-4, 0.0]], normal: &[[0.0, -1.0, 0.0], [0.0, 1.0, 0.0]], sides: &[[[0.0; 3]; 2]; 2], open: &[CENTRE; 2], offset: 1e-4 }; let sun = Sun { dir: [1.0, 1.0, 0.0], irradiance: [std::f32::consts::PI, 0.0, 0.0], half_angle: 0.0046 }; let s = Settings { samples: 4096, per_pass: 64, bounces: 1, sky: Sky::even([0.0; 3]), sun: Some(sun), ..Settings::default() }; let l = trace(&world, &starts, &s, &mut |_, _| {}).unwrap(); @@ -133,8 +168,8 @@ fn a_ray_straight_up_sees_the_sky() { let p = [[0.0, -5.0, 0.0], [1.0, -5.0, 0.0], [0.0, -5.0, 1.0]]; let world = World { positions: &p, triangles: &[[0, 1, 2]], surfaces: &[Surface::default()], uvs: &[], textures: &[] }; let n = 16384; - let (origin, normal, inside) = (vec![[0.0; 3]; n], vec![[0.0, 1.0, 0.0]; n], vec![false; n]); - let l = trace(&world, &Starts { origin: &origin, normal: &normal, inside: &inside, offset: 1e-4 }, &Settings { samples: 8192, per_pass: 128, ..Settings::default() }, &mut |_, _| {}).unwrap(); + let (origin, normal, sides, open) = (vec![[0.0; 3]; n], vec![[0.0, 1.0, 0.0]; n], vec![[[0.0; 3]; 2]; n], vec![CENTRE; n]); + let l = trace(&world, &Starts { origin: &origin, normal: &normal, sides: &sides, open: &open, offset: 1e-4 }, &Settings { samples: 8192, per_pass: 128, ..Settings::default() }, &mut |_, _| {}).unwrap(); assert_eq!(l.iter().flatten().filter(|v| !v.is_finite()).count(), 0, "values that aren't finite"); assert!(l.iter().all(|c| (c[0] - 1.0).abs() < 1e-3), "not the sky: {:?}", l.iter().find(|c| (c[0] - 1.0).abs() >= 1e-3)); } @@ -152,7 +187,7 @@ fn a_textured_floor_bounces_its_texture() { let image = Image { width: 2, height: 1, rgba: vec![0xff00_00bc, 0xff00_bc00] }; let surfaces = vec![Surface { albedo: [1.0; 3], emission: [0.0; 3], texture: Some(0) }; 2]; let origin: Vec<[f32; 3]> = [-10.0, 10.0].into_iter().map(|x| [x, 0.1, 0.0]).collect(); - let starts = Starts { origin: &origin, normal: &[[0.0, -1.0, 0.0]; 2], inside: &[false; 2], offset: 1e-4 }; + let starts = Starts { origin: &origin, normal: &[[0.0, -1.0, 0.0]; 2], sides: &[[[0.0; 3]; 2]; 2], open: &[CENTRE; 2], offset: 1e-4 }; let s = Settings { samples: 4096, per_pass: 64, bounces: 2, ..Settings::default() }; let l = trace(&World { positions: &p, triangles: &tri, surfaces: &surfaces, uvs: &uv, textures: &[image] }, &starts, &s, &mut |_, _| {}).unwrap(); println!("textured: {l:?}"); @@ -163,7 +198,7 @@ fn a_textured_floor_bounces_its_texture() { /// The measured run (docs/bake.feature BK3): RAEA_BAKE_GLB at 64 texels a metre, every surface 0.7 grey under a white /// sky, RAEA_BAKE_SAMPLES (default 512) a texel: the trace's time alone. -/// `cargo test -p raea-sys-lightbake trace::tests::measured -- --ignored --nocapture` +/// `cargo test -p raea-sys-lightbake trace_tests::measured -- --ignored --nocapture` #[test] #[ignore] fn measured() { @@ -172,6 +207,6 @@ fn measured() { let t = texels(&glb, &request(64.0, 4096)).unwrap(); let t0 = std::time::Instant::now(); let light = run(&t, |_| Surface { albedo: [0.7; 3], emission: [0.0; 3], texture: None }, &Settings { samples, ..Settings::default() }); - let lit = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| l[0]).collect::>(); + let lit = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| l[0]).collect::>(); println!("{} texels, {} triangles, {samples} samples, 4 bounces: {:.2} s, mean light {:.3}", light.len(), t.mesh.indices().len(), t0.elapsed().as_secs_f64(), lit.iter().sum::() / lit.len() as f32); } diff --git a/systems/lighttrace/Cargo.toml b/systems/lighttrace/Cargo.toml new file mode 100644 index 00000000..774c163b --- /dev/null +++ b/systems/lighttrace/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "raea-sys-lighttrace" +version = "0.1.0" +edition = "2024" +license = "FSL-1.1-ALv2" +publish = false +description = "Light paths traced on the GPU: what a triangle bounces, the sky, the sun and emission, by wgpu's ray queries (docs/bake.feature BK3)" + +[dependencies] +# the process's one shared GPU device, and wgpu's ray queries on it +raea-gpu-device = { path = "../../gpu/device" } +wgpu = "=30.0.1" +bytemuck = "1" +pollster = "0.4" diff --git a/systems/lightbake/src/trace.rs b/systems/lighttrace/src/lib.rs similarity index 93% rename from systems/lightbake/src/trace.rs rename to systems/lighttrace/src/lib.rs index 37fe535a..95972228 100644 --- a/systems/lightbake/src/trace.rs +++ b/systems/lighttrace/src/lib.rs @@ -61,12 +61,17 @@ pub struct Sun { pub half_angle: f32, } -/// What's traced from: each texel's origin (BK2, already off its surface), its normal, and whether it's inside other -/// geometry (left at zero for BK4 to fill), and the offset each bounce leaves its surface by. +/// A texel that starts only at its point (`Starts::open`). +pub const CENTRE: u32 = 1 << 16; + +/// What's traced from: each texel's point (BK2, already off its surface) and normal; the two sides of its footprint, +/// and which of the 4 x 4 points over it are open (a bit each, row by row; `CENTRE` alone for its point only, 0 when it's +/// inside other geometry and left at zero for BK4 to fill); and the offset each bounce leaves its surface by. pub struct Starts<'a> { pub origin: &'a [[f32; 3]], pub normal: &'a [[f32; 3]], - pub inside: &'a [bool], + pub sides: &'a [[[f32; 3]; 2]], + pub open: &'a [u32], pub offset: f32, } @@ -94,8 +99,8 @@ const CHUNK: u32 = 1 << 18; /// The light reaching each texel (the mean its cosine-weighted rays bring back), in `from`'s order; inside texels 0. pub fn trace(world: &World, from: &Starts, s: &Settings, progress: &mut dyn FnMut(u32, u32)) -> Result, String> { let n = from.origin.len(); - if from.normal.len() != n || from.inside.len() != n || world.surfaces.len() != world.triangles.len() { - return Err("trace: the texels' origins, normals and inside marks, and the triangles' surfaces, must match".into()); + if from.normal.len() != n || from.open.len() != n || from.sides.len() != n || world.surfaces.len() != world.triangles.len() { + return Err("trace: the texels' origins, normals, sides and open starts, and the triangles' surfaces, must match".into()); } if s.sky.rgb.is_empty() || s.sky.rgb.len() != (s.sky.width * s.sky.height) as usize { return Err("trace: the sky's picture doesn't match its size".into()); @@ -146,7 +151,7 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St images.push(0); } let sky: Vec<[f32; 4]> = s.sky.rgb.iter().map(|c| vec4(c.map(|x| x * s.sky.strength), 0.0)).collect(); - let texels: Vec<[f32; 4]> = (0..n).flat_map(|i| [vec4(from.origin[i], from.inside[i] as u32 as f32), vec4(from.normal[i], 0.0)]).collect(); + let texels: Vec<[f32; 4]> = (0..n).flat_map(|i| [vec4(from.origin[i], f32::from_bits(from.open[i])), vec4(from.normal[i], 0.0), vec4(from.sides[i][0], 0.0), vec4(from.sides[i][1], 0.0)]).collect(); let storage = |label: &str, bytes: &[u8], usage: wgpu::BufferUsages| device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: bytes, usage: wgpu::BufferUsages::STORAGE | usage }); let index: Vec = world.triangles.iter().flatten().copied().collect(); let bufs = [ @@ -182,7 +187,7 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St p[3] = sun.half_angle.cos().to_bits(); } let end = (first + CHUNK).min(n as u32); - (p[8], p[9], p[10], p[11], p[12], p[13]) = (end, pass, per, s.bounces, from.offset.to_bits(), first); + (p[8], p[9], p[10], p[11], p[12], p[13]) = (end, pass * s.per_pass.max(1), per, s.bounces, from.offset.to_bits(), first); (p[14], p[15], p[16]) = (s.sky.width, s.sky.height, s.sky.rotation.to_bits()); queue.write_buffer(¶ms, 0, bytemuck::cast_slice(&p)); let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("lightbake pass") }); @@ -237,6 +242,3 @@ fn read(device: &wgpu::Device, queue: &wgpu::Queue, buf: &wgpu::Buffer, size: us let bytes = back.slice(..).get_mapped_range().map_err(|e| format!("the light bake's readback: {e}"))?.to_vec(); Ok(bytes) } - -#[cfg(test)] -mod tests; diff --git a/systems/lightbake/src/wgsl/diffuse.wgsl b/systems/lighttrace/src/wgsl/diffuse.wgsl similarity index 100% rename from systems/lightbake/src/wgsl/diffuse.wgsl rename to systems/lighttrace/src/wgsl/diffuse.wgsl diff --git a/systems/lightbake/src/wgsl/trace.wgsl b/systems/lighttrace/src/wgsl/trace.wgsl similarity index 85% rename from systems/lightbake/src/wgsl/trace.wgsl rename to systems/lighttrace/src/wgsl/trace.wgsl index 4c85d08e..0b1f5a8c 100644 --- a/systems/lightbake/src/wgsl/trace.wgsl +++ b/systems/lighttrace/src/wgsl/trace.wgsl @@ -9,7 +9,8 @@ struct Params { sun_dir: vec4, sun: vec4, count: u32, - pass_index: u32, + // the first sample of this pass (the random numbers are a sample's own) + base: u32, per_pass: u32, bounces: u32, offset: f32, @@ -35,7 +36,8 @@ struct Surface { @group(0) @binding(1) var positions: array>; @group(0) @binding(2) var indices: array; @group(0) @binding(3) var surfaces: array; -// per texel: origin (w: 1 when inside other geometry), hemisphere's normal +// per texel: its point off the surface (w: which starts are open, see `start`), the hemisphere's normal, and its +// footprint's two sides @group(0) @binding(4) var texels: array>; @group(0) @binding(5) var accum: array>; @group(0) @binding(6) var params: Params; @@ -93,21 +95,37 @@ fn image_at(tex: vec4, uv: vec2) -> vec3 { return select(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, c <= vec3(0.04045)); } +// Where a sample starts: one of the texel's 4 x 4 points, the open ones in turn (Cycles jitters its samples over the +// texel too: a ledge narrower than a texel is half of it, not all or nothing). Bit 16 alone is the centre. +fn start(i: u32, at: vec3, open: u32, turn: u32) -> vec3 { + var left = open & 0xffffu; + if (left == 0u) { + return at; + } + for (var k = turn % countOneBits(left); k > 0u; k = k - 1u) { + left = left & (left - 1u); + } + let c = firstTrailingBit(left); + let q = (vec2(f32(c % 4u), f32(c / 4u)) + 0.5) / 4.0 - 0.5; + return at + texels[4u * i + 2u].xyz * q.x + texels[4u * i + 3u].xyz * q.y; +} + @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) gid: vec3) { let i = params.first + gid.x; if (i >= params.count) { return; } - let at = texels[2u * i]; - if (at.w > 0.5) { + let at = texels[4u * i]; + let open = bitcast(at.w); + if (open == 0u) { return; } - let n0 = texels[2u * i + 1u].xyz; + let n0 = texels[4u * i + 1u].xyz; var sum = vec3(0.0); for (var s = 0u; s < params.per_pass; s = s + 1u) { - var rng = raea_hash(i * 0x9e3779b9u ^ raea_hash(params.pass_index * params.per_pass + s)); - var o = at.xyz; + var rng = raea_hash(i * 0x9e3779b9u ^ raea_hash(params.base + s)); + var o = start(i, at.xyz, open, params.base + s + raea_hash(i)); var n = n0; var weight = vec3(1.0); var light = vec3(0.0); diff --git a/tools/layers.toml b/tools/layers.toml index 1c373ff9..a469abc6 100644 --- a/tools/layers.toml +++ b/tools/layers.toml @@ -222,6 +222,7 @@ raea-app-scene = "apps" # raea scene lint|explain|light|stage raea-app-voice = "apps" # raea voice: speech to speech on this computer, as lines of JSON raea-app-ask = "apps" raea-app-lightbake = "apps" # raea bake light (docs/bake.feature) +raea-sys-lighttrace = "systems" # light paths on the GPU by wgpu ray queries: the kernel the bake, rt and the path tracer share (docs/bake.feature BK3) raea-sys-lightbake = "systems" # light baked over raea/wear's atlas on raea's ray tracer (docs/bake.feature) raea-app-double = "apps" raea-app-solid = "apps" @@ -336,3 +337,5 @@ raea-sys-damage = true raea-sys-glb = true # the atlas raea's bakes share: charts, packing, each texel's point (the cause maps and the light bake lie over it) raea-sys-atlas = true +# the paths a bake traces its light along (the kernel and its Settings), which systems/rt and the path tracer may build on too +raea-sys-lighttrace = true