Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

LightBench LB6: a sun with an angular size, sky light from bounce rays that leave, and --scene room

shinyobjectzec015699017f
diff --git a/bench/lightbench/src/light.wgsl b/bench/lightbench/src/light.wgsl
index 7d05f520..58fd8650 100644
--- a/bench/lightbench/src/light.wgsl
+++ b/bench/lightbench/src/light.wgsl
@@ -27,6 +27,11 @@ struct Params {
grid_dims: vec4<u32>,
// diffuse bounces a pixel follows (0 none), 0, 0, 0
gi: vec4<u32>,
+ // the sun (LB6): xyz the unit direction toward it, w its angular radius in radians; its irradiance (rgb, 0 off)
+ sun: vec4<f32>,
+ sun_e: vec4<f32>,
+ // the sky's radiance (rgb): what a bounce ray that leaves the scene brings back
+ sky: vec4<f32>,
}
struct Node { mn: vec3<f32>, a: u32, mx: vec3<f32>, count: u32 }
@@ -65,17 +70,6 @@ const STACK: u32 = 48u;
var<private> seed: u32;
var<private> rays: u32;
-fn pcg(v: u32) -> u32 {
- let s = v * 747796405u + 2891336453u;
- let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
- return (w >> 22u) ^ w;
-}
-
-fn rnd() -> f32 {
- seed = pcg(seed);
- return f32(seed >> 8u) / 16777216.0;
-}
-
// Bevy's octahedral_decode (bevy_render utils), for the deferred prepass's normal
fn oct_decode(v: vec2<f32>) -> vec3<f32> {
let f = v * 2.0 - 1.0;
@@ -86,135 +80,6 @@ fn oct_decode(v: vec2<f32>) -> vec3<f32> {
return normalize(n);
}
-fn hit_box(o: vec3<f32>, inv: vec3<f32>, mn: vec3<f32>, mx: vec3<f32>, tmax: f32) -> bool {
- let t0 = (mn - o) * inv;
- let t1 = (mx - o) * inv;
- let lo = min(t0, t1);
- let hi = max(t0, t1);
- let near = max(max(lo.x, lo.y), max(lo.z, 0.0));
- let far = min(min(hi.x, hi.y), min(hi.z, tmax));
- return near <= far;
-}
-
-const MISS: f32 = 3.4e38;
-
-// Möller-Trumbore, both sides: how far along the ray triangle i is, MISS if it isn't on it
-fn tri_t(o: vec3<f32>, d: vec3<f32>, i: u32) -> f32 {
- let v0 = tris[3u * i].xyz;
- let e1 = tris[3u * i + 1u].xyz;
- let e2 = tris[3u * i + 2u].xyz;
- let pv = cross(d, e2);
- let det = dot(e1, pv);
- if abs(det) < 1e-12 {
- return MISS;
- }
- let inv = 1.0 / det;
- let tv = o - v0;
- let u = dot(tv, pv) * inv;
- if u < 0.0 || u > 1.0 {
- return MISS;
- }
- let qv = cross(tv, e1);
- let v = dot(d, qv) * inv;
- if v < 0.0 || u + v > 1.0 {
- return MISS;
- }
- let t = dot(e2, qv) * inv;
- return select(MISS, t, t > 0.0);
-}
-
-fn hit_tri(o: vec3<f32>, d: vec3<f32>, i: u32, tmax: f32) -> bool {
- return tri_t(o, d, i) < tmax;
-}
-
-// whether anything lies on the ray before tmax: the BVH, or every triangle when brute force is asked for
-fn occluded(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> bool {
- rays += 1u;
- if p.mode.w != 0u {
- let n = arrayLength(&tris) / 3u;
- for (var i = 0u; i < n; i++) {
- if hit_tri(o, d, i, tmax) {
- return true;
- }
- }
- return false;
- }
- let inv = 1.0 / select(d, vec3(1e-12), abs(d) < vec3(1e-12));
- var stack: array<u32, STACK>;
- var sp = 0u;
- var i = 0u;
- loop {
- let n = nodes[i];
- if hit_box(o, inv, n.mn, n.mx, tmax) {
- if n.count > 0u {
- for (var t = n.a; t < n.a + n.count; t++) {
- if hit_tri(o, d, t, tmax) {
- return true;
- }
- }
- } else if sp < STACK {
- stack[sp] = n.a;
- sp++;
- i++;
- continue;
- }
- }
- if sp == 0u {
- break;
- }
- sp--;
- i = stack[sp];
- }
- return false;
-}
-
-struct Hit { t: f32, i: u32 }
-
-// the nearest triangle on the ray before tmax (i 0xFFFFFFFF if none): the BVH walked as `occluded` walks it, the
-// ray shortening at each hit so farther boxes drop out; every triangle with brute force
-fn closest(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> Hit {
- rays += 1u;
- var best = Hit(tmax, 0xFFFFFFFFu);
- if p.mode.w != 0u {
- let n = arrayLength(&tris) / 3u;
- for (var i = 0u; i < n; i++) {
- let t = tri_t(o, d, i);
- if t < best.t {
- best = Hit(t, i);
- }
- }
- return best;
- }
- let inv = 1.0 / select(d, vec3(1e-12), abs(d) < vec3(1e-12));
- var stack: array<u32, STACK>;
- var sp = 0u;
- var i = 0u;
- loop {
- let n = nodes[i];
- if hit_box(o, inv, n.mn, n.mx, best.t) {
- if n.count > 0u {
- for (var t = n.a; t < n.a + n.count; t++) {
- let h = tri_t(o, d, t);
- if h < best.t {
- best = Hit(h, t);
- }
- }
- } else if sp < STACK {
- stack[sp] = n.a;
- sp++;
- i++;
- continue;
- }
- }
- if sp == 0u {
- break;
- }
- sp--;
- i = stack[sp];
- }
- return best;
-}
-
// a light's light at a point before its shadow: its power times the cosine and the falloff (an inverse square that
// stops growing inside its radius and fades to nothing at its range); all zero where it can't reach
fn unshadowed(l: Light, pos: vec3<f32>, n: vec3<f32>) -> vec3<f32> {
@@ -313,26 +178,19 @@ fn lit_at(pos: vec3<f32>, n: vec3<f32>, o: vec3<f32>, k: u32) -> vec3<f32> {
c /= f32(k);
}
}
+ // the sun, the same in every mode: one shadow ray to a point on its disc, so its shadows soften with its size
+ let ns = dot(n, p.sun.xyz);
+ if ns > 0.0 && lum(p.sun_e.rgb) > 0.0 && !occluded(o, cone_dir(p.sun.xyz, cos(p.sun.w)), 1e4) {
+ c += p.sun_e.rgb * ns;
+ }
return c;
}
-// a direction about n, chosen in proportion to its cosine (Duff et al.'s basis)
-fn cosine_dir(n: vec3<f32>) -> vec3<f32> {
- let phi = 2.0 * PI * rnd();
- let r2 = rnd();
- let r = sqrt(r2);
- let s = select(-1.0, 1.0, n.z >= 0.0);
- let a = -1.0 / (s + n.z);
- let b = n.x * n.y * a;
- let t = vec3(1.0 + s * n.x * n.x * a, s * b, -s * n.x);
- let bt = vec3(b, s + n.y * n.y * a, -n.y);
- return normalize(t * (r * cos(phi)) + bt * (r * sin(phi)) + n * sqrt(max(0.0, 1.0 - r2)));
-}
-
// the light reaching a point by way of other surfaces, p.gi.x bounces deep: from the point a cosine-chosen ray to the
// nearest triangle, that point lit as a pixel is (one light sample, or every light in the reference), and on from
// there. A cosine-chosen ray's pdf cancels the cosine and the 1 / PI of the hit's diffuse light, so each bounce adds
-// the albedos so far times the light at the hit. Rays that leave the scene bring nothing (it has no sky).
+// the albedos so far times the light at the hit. A ray that leaves the scene brings the sky: PI times its radiance,
+// for the same reason.
fn bounced(n0: vec3<f32>, o0: vec3<f32>) -> vec3<f32> {
var e = vec3(0.0);
var through = vec3(1.0);
@@ -342,6 +200,7 @@ fn bounced(n0: vec3<f32>, o0: vec3<f32>) -> vec3<f32> {
let d = cosine_dir(n);
let h = closest(o, d, 1e4);
if h.i == 0xFFFFFFFFu {
+ e += through * PI * p.sky.rgb;
break;
}
let v0 = tris[3u * h.i];
diff --git a/bench/lightbench/src/main.rs b/bench/lightbench/src/main.rs
index 89aba96e..0c4e5a58 100644
--- a/bench/lightbench/src/main.rs
+++ b/bench/lightbench/src/main.rs
@@ -43,7 +43,12 @@ const HELP: &str = "lightbench [switches]
--camera still|orbit|cut the camera holds, circles slowly, or jumps to a second view at lit frame --cut-at (still)
--cut-at N the lit frame --camera cut jumps on (8)
--view history frames of history at each pixel, white when full
- --scene knot|field one knot by a wall (lighting), or rows of knots into the distance (detail) (knot)
+ --scene knot|field|room one knot by a wall (lighting), rows of knots into the distance (detail), or the knot
+ and wall in a closed room lit by the sun through a window (bounce: --sun on, --sky
+ 0.25, --bounce 2 unless given) (knot)
+ --sun on|off a low sun from the left, one shadow ray to a point on its disc a pixel (off)
+ --sun-size DEG the sun's angular diameter: larger, softer shadows (0.53)
+ --sky X the sky's radiance (a blue-white), brought by bounce rays that leave the scene (0)
--rows N the field's rows (6)
--detail full|adaptive every finest triangle, or the clusters each knot's distance asks for (adaptive)
--tau PX the error in pixels a cluster may show (1)
@@ -79,10 +84,15 @@ pub struct Opts {
pub fov: f32,
pub grid: bool,
pub bounces: u32,
+ pub sun: bool,
+ pub sun_size: f32,
+ pub sky: f32,
}
fn opts() -> Result<Opts, String> {
- let mut o = Opts { mode: 0, k: 4, lights: 16, view: 0, brute: false, detail: 0, size: UVec2::new(1280, 720), t: None, exposure: 1.0, shot: None, frames: 4, bench: 0, pillar: true, raw: false, history: 32, camera: 0, cut_at: 8, scene: 0, rows: 6, full: false, tau: 1.0, fov: 45.0, grid: true, bounces: 0 };
+ let mut o = Opts { mode: 0, k: 4, lights: 16, view: 0, brute: false, detail: 0, size: UVec2::new(1280, 720), t: None, exposure: 1.0, shot: None, frames: 4, bench: 0, pillar: true, raw: false, history: 32, camera: 0, cut_at: 8, scene: 0, rows: 6, full: false, tau: 1.0, fov: 45.0, grid: true, bounces: 0, sun: false, sun_size: 0.53, sky: 0.0 };
+ // what --scene room turns on, unless the switches say otherwise
+ let (mut sun, mut sky, mut bounces) = (None, None, None);
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
let mut val = || args.next().ok_or(format!("{a} needs a value"));
@@ -109,13 +119,16 @@ fn opts() -> Result<Opts, String> {
}
"--scene" => {
let v = val()?;
- o.scene = ["knot", "field"].iter().position(|m| *m == v).ok_or("--scene: knot or field")? as u32;
+ o.scene = ["knot", "field", "room"].iter().position(|m| *m == v).ok_or("--scene: knot, field or room")? as u32;
}
"--rows" => o.rows = (num(val()?)? as u32).max(1),
"--tau" => o.tau = num(val()?)?.max(0.0),
"--fov" => o.fov = num(val()?)?.clamp(1.0, 170.0),
"--grid" => o.grid = val()? != "off",
- "--bounce" => o.bounces = (num(val()?)? as u32).min(8),
+ "--bounce" => bounces = Some((num(val()?)? as u32).min(8)),
+ "--sun" => sun = Some(val()? != "off"),
+ "--sun-size" => o.sun_size = num(val()?)?.clamp(0.0, 30.0),
+ "--sky" => sky = Some(num(val()?)?.max(0.0)),
"--size" => {
let v = val()?;
let (w, h) = v.split_once('x').ok_or("--size: WxH")?;
@@ -138,6 +151,8 @@ fn opts() -> Result<Opts, String> {
_ => return Err(format!("unknown switch {a}\n{HELP}")),
}
}
+ let room = o.scene == 2;
+ (o.sun, o.sky, o.bounces) = (sun.unwrap_or(room), sky.unwrap_or(if room { 0.25 } else { 0.0 }), bounces.unwrap_or(if room { 2 } else { 0 }));
if o.detail == 0 {
o.detail = if o.scene == 1 { 512 } else { 2048 };
}
@@ -161,6 +176,7 @@ fn main() {
std::process::exit(if e == HELP { 0 } else { 2 });
}
};
+ let (sky, x) = (o.sky, o.exposure);
let mut app = App::new();
// timing runs ask the GPU for timestamps at a pass's start and end (Apple's GPUs have no others), for its time
let mut wgpu = bevy::render::settings::WgpuSettings::default();
@@ -182,7 +198,8 @@ fn main() {
}
app.insert_resource(o)
.insert_resource(DefaultOpaqueRendererMethod::deferred())
- .insert_resource(ClearColor(Color::srgb(0.02, 0.025, 0.035)))
+ // the sky seen past the scene: the bounce's sky, exposed as the lighting pass exposes, else near black
+ .insert_resource(ClearColor(if sky > 0.0 { Color::linear_rgb(SKY.x * sky * x, SKY.y * sky * x, SKY.z * sky * x) } else { Color::srgb(0.02, 0.025, 0.035) }))
.add_plugins(pass::LightPass)
.add_systems(Startup, (scene::spawn, camera))
.init_resource::<field::Counts>()
@@ -211,6 +228,12 @@ fn camera(mut commands: Commands, o: Res<Opts>, mut images: ResMut<Assets<Image>
}
}
+/// The sun (LB6): toward it from the scene, low on the left and a little behind the knot, so in --scene room it comes
+/// through the window onto the floor in front of the knot; its irradiance, warm; the sky's colour, which --sky scales.
+const SUN_TO: Vec3 = Vec3::new(-1.0, 0.55, -0.45);
+const SUN_E: Vec3 = Vec3::new(3.2, 2.9, 2.5);
+const SKY: Vec3 = Vec3::new(0.55, 0.75, 1.0);
+
const EYE: Vec3 = Vec3::new(0.0, 2.2, 7.0);
const LOOK: Vec3 = Vec3::new(0.0, 1.3, 0.0);
@@ -255,6 +278,9 @@ fn tick(o: Res<Opts>, time: Res<Time>, mut frame: ResMut<pass::Frame>, mut cam:
cut,
history: o.history,
bounces: o.bounces,
+ sun: SUN_TO.normalize().extend((o.sun_size * 0.5).to_radians()),
+ sun_e: if o.sun { SUN_E.extend(0.0) } else { Vec4::ZERO },
+ sky: (SKY * o.sky).extend(0.0),
};
}
diff --git a/bench/lightbench/src/pass.rs b/bench/lightbench/src/pass.rs
index 9517d4ec..8a1732e8 100644
--- a/bench/lightbench/src/pass.rs
+++ b/bench/lightbench/src/pass.rs
@@ -60,13 +60,17 @@ pub struct Frame {
pub grid_idx: Vec<u32>,
/// diffuse bounces a pixel follows (LB5)
pub bounces: u32,
+ /// the sun (LB6): the unit direction toward it and its angular radius; its irradiance (zero: none); the sky's
+ /// radiance, which bounce rays that leave the scene bring back
+ pub sun: Vec4,
+ pub sun_e: Vec4,
+ pub sky: Vec4,
}
pub struct LightPass;
impl Plugin for LightPass {
fn build(&self, app: &mut App) {
- bevy::asset::embedded_asset!(app, "light.wgsl");
app.init_resource::<Frame>().add_plugins((ExtractResourcePlugin::<Frame>::default(), ExtractResourcePlugin::<SceneGpu>::default()));
let Some(render) = app.get_sub_app_mut(RenderApp) else { return };
// timing a run (--bench): each frame waits for the GPU, so the frame time counts the GPU's work too
@@ -92,6 +96,9 @@ struct Params {
grid_min: Vec4,
grid_dims: UVec4,
gi: UVec4,
+ sun: Vec4,
+ sun_e: Vec4,
+ sky: Vec4,
}
#[derive(Resource)]
@@ -140,7 +147,8 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCac
let id = cache.queue_compute_pipeline(ComputePipelineDescriptor {
label: Some("lightbench_light".into()),
layout: vec![layout.clone()],
- shader: assets.load("embedded://lightbench/light.wgsl"),
+ // the lighting and the rays it traces, one module
+ shader: assets.add(bevy::shader::Shader::from_wgsl(concat!(include_str!("light.wgsl"), "\n", include_str!("trace.wgsl")), "lightbench/light.wgsl")),
entry_point: Some("main".into()),
..default()
});
@@ -233,6 +241,9 @@ fn light(
grid_min: frame.grid_min,
grid_dims: frame.grid_dims,
gi: UVec4::new(frame.bounces, 0, 0, 0),
+ sun: frame.sun,
+ sun_e: frame.sun_e,
+ sky: frame.sky,
});
params.write_buffer(&device, &queue);
let group = device.create_bind_group(
diff --git a/bench/lightbench/src/scene.rs b/bench/lightbench/src/scene.rs
index dd3fea0a..5d32253e 100644
--- a/bench/lightbench/src/scene.rs
+++ b/bench/lightbench/src/scene.rs
@@ -51,7 +51,26 @@ pub fn spawn(mut commands: Commands, opts: Res<Opts>, mut meshes: ResMut<Assets<
commands.spawn((Mesh3d(meshes.add(mesh)), MeshMaterial3d(material), at));
};
put(Plane3d::default().mesh().size(160.0, 160.0).build(), Transform::IDENTITY, Color::srgb(0.62, 0.62, 0.6), &mut tris);
- if opts.scene == 0 {
+ if opts.scene == 2 {
+ // the room (LB6): 8 x 3.6 x 11 m inside (the knot reaches 3.4), walls 0.2 thick, a window 3 m wide and 1.6
+ // tall in the left wall
+ let shell: [([f32; 3], [f32; 3]); 9] = [
+ ([0.0, 1.9, -3.1], [8.4, 3.8, 0.2]),
+ ([0.0, 1.9, 8.1], [8.4, 3.8, 0.2]),
+ ([4.1, 1.9, 2.5], [0.2, 3.8, 11.4]),
+ ([-4.1, 0.45, 2.5], [0.2, 0.9, 11.4]),
+ ([-4.1, 3.15, 2.5], [0.2, 1.3, 11.4]),
+ ([-4.1, 1.7, -1.85], [0.2, 1.6, 2.7]),
+ ([-4.1, 1.7, 5.35], [0.2, 1.6, 5.7]),
+ ([0.0, 3.7, 2.5], [8.4, 0.2, 11.4]),
+ ([0.0, 0.01, 2.5], [8.0, 0.02, 11.0]),
+ ];
+ for (k, (at, size)) in shell.iter().enumerate() {
+ let colour = if k == 8 { Color::srgb(0.55, 0.42, 0.3) } else { Color::srgb(0.82, 0.8, 0.76) };
+ put(Cuboid::new(size[0], size[1], size[2]).mesh().build(), Transform::from_translation(Vec3::from(*at)), colour, &mut tris);
+ }
+ }
+ if opts.scene != 1 {
put(knot(2, 3, opts.detail, opts.detail / 32, 0.33), Transform::from_xyz(0.0, 1.75, 0.0).with_scale(Vec3::splat(0.5)), Color::srgb(0.85, 0.42, 0.18), &mut tris);
put(Cuboid::new(0.2, 2.5, 3.0).mesh().build(), Transform::from_xyz(-2.5, 1.25, 0.0), Color::srgb(0.35, 0.42, 0.55), &mut tris);
}
diff --git a/bench/lightbench/src/trace.wgsl b/bench/lightbench/src/trace.wgsl
new file mode 100644
index 00000000..413c49bb
--- /dev/null
+++ b/bench/lightbench/src/trace.wgsl
@@ -0,0 +1,166 @@
+// LightBench's rays (joined after light.wgsl, whose bindings and private state they use): the random stream, the
+// BVH's walks (any hit for shadow rays, the nearest hit for bounces) and the directions rays are chosen in.
+
+fn pcg(v: u32) -> u32 {
+ let s = v * 747796405u + 2891336453u;
+ let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
+ return (w >> 22u) ^ w;
+}
+
+fn rnd() -> f32 {
+ seed = pcg(seed);
+ return f32(seed >> 8u) / 16777216.0;
+}
+
+fn hit_box(o: vec3<f32>, inv: vec3<f32>, mn: vec3<f32>, mx: vec3<f32>, tmax: f32) -> bool {
+ let t0 = (mn - o) * inv;
+ let t1 = (mx - o) * inv;
+ let lo = min(t0, t1);
+ let hi = max(t0, t1);
+ let near = max(max(lo.x, lo.y), max(lo.z, 0.0));
+ let far = min(min(hi.x, hi.y), min(hi.z, tmax));
+ return near <= far;
+}
+
+const MISS: f32 = 3.4e38;
+
+// Möller-Trumbore, both sides: how far along the ray triangle i is, MISS if it isn't on it
+fn tri_t(o: vec3<f32>, d: vec3<f32>, i: u32) -> f32 {
+ let v0 = tris[3u * i].xyz;
+ let e1 = tris[3u * i + 1u].xyz;
+ let e2 = tris[3u * i + 2u].xyz;
+ let pv = cross(d, e2);
+ let det = dot(e1, pv);
+ if abs(det) < 1e-12 {
+ return MISS;
+ }
+ let inv = 1.0 / det;
+ let tv = o - v0;
+ let u = dot(tv, pv) * inv;
+ if u < 0.0 || u > 1.0 {
+ return MISS;
+ }
+ let qv = cross(tv, e1);
+ let v = dot(d, qv) * inv;
+ if v < 0.0 || u + v > 1.0 {
+ return MISS;
+ }
+ let t = dot(e2, qv) * inv;
+ return select(MISS, t, t > 0.0);
+}
+
+fn hit_tri(o: vec3<f32>, d: vec3<f32>, i: u32, tmax: f32) -> bool {
+ return tri_t(o, d, i) < tmax;
+}
+
+// whether anything lies on the ray before tmax: the BVH, or every triangle when brute force is asked for
+fn occluded(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> bool {
+ rays += 1u;
+ if p.mode.w != 0u {
+ let n = arrayLength(&tris) / 3u;
+ for (var i = 0u; i < n; i++) {
+ if hit_tri(o, d, i, tmax) {
+ return true;
+ }
+ }
+ return false;
+ }
+ let inv = 1.0 / select(d, vec3(1e-12), abs(d) < vec3(1e-12));
+ var stack: array<u32, STACK>;
+ var sp = 0u;
+ var i = 0u;
+ loop {
+ let n = nodes[i];
+ if hit_box(o, inv, n.mn, n.mx, tmax) {
+ if n.count > 0u {
+ for (var t = n.a; t < n.a + n.count; t++) {
+ if hit_tri(o, d, t, tmax) {
+ return true;
+ }
+ }
+ } else if sp < STACK {
+ stack[sp] = n.a;
+ sp++;
+ i++;
+ continue;
+ }
+ }
+ if sp == 0u {
+ break;
+ }
+ sp--;
+ i = stack[sp];
+ }
+ return false;
+}
+
+struct Hit { t: f32, i: u32 }
+
+// the nearest triangle on the ray before tmax (i 0xFFFFFFFF if none): the BVH walked as `occluded` walks it, the
+// ray shortening at each hit so farther boxes drop out; every triangle with brute force
+fn closest(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> Hit {
+ rays += 1u;
+ var best = Hit(tmax, 0xFFFFFFFFu);
+ if p.mode.w != 0u {
+ let n = arrayLength(&tris) / 3u;
+ for (var i = 0u; i < n; i++) {
+ let t = tri_t(o, d, i);
+ if t < best.t {
+ best = Hit(t, i);
+ }
+ }
+ return best;
+ }
+ let inv = 1.0 / select(d, vec3(1e-12), abs(d) < vec3(1e-12));
+ var stack: array<u32, STACK>;
+ var sp = 0u;
+ var i = 0u;
+ loop {
+ let n = nodes[i];
+ if hit_box(o, inv, n.mn, n.mx, best.t) {
+ if n.count > 0u {
+ for (var t = n.a; t < n.a + n.count; t++) {
+ let h = tri_t(o, d, t);
+ if h < best.t {
+ best = Hit(h, t);
+ }
+ }
+ } else if sp < STACK {
+ stack[sp] = n.a;
+ sp++;
+ i++;
+ continue;
+ }
+ }
+ if sp == 0u {
+ break;
+ }
+ sp--;
+ i = stack[sp];
+ }
+ return best;
+}
+
+// an orthonormal basis about unit n (Duff et al.): its columns are two tangents and n
+fn basis(n: vec3<f32>) -> mat3x3<f32> {
+ let s = select(-1.0, 1.0, n.z >= 0.0);
+ let a = -1.0 / (s + n.z);
+ let b = n.x * n.y * a;
+ return mat3x3(vec3(1.0 + s * n.x * n.x * a, s * b, -s * n.x), vec3(b, s + n.y * n.y * a, -n.y), n);
+}
+
+// a direction about n, chosen in proportion to its cosine
+fn cosine_dir(n: vec3<f32>) -> vec3<f32> {
+ let phi = 2.0 * PI * rnd();
+ let r2 = rnd();
+ let r = sqrt(r2);
+ return normalize(basis(n) * vec3(r * cos(phi), r * sin(phi), sqrt(max(0.0, 1.0 - r2))));
+}
+
+// a direction within the cone about unit axis whose half-angle has cosine cos_max, every direction in it as likely
+fn cone_dir(axis: vec3<f32>, cos_max: f32) -> vec3<f32> {
+ let phi = 2.0 * PI * rnd();
+ let ct = 1.0 - rnd() * (1.0 - cos_max);
+ let st = sqrt(max(0.0, 1.0 - ct * ct));
+ return normalize(basis(axis) * vec3(st * cos(phi), st * sin(phi), ct));
+}
diff --git a/docs/lightbench.feature b/docs/lightbench.feature
index 761493e7..9a2fdc56 100644
--- a/docs/lightbench.feature
+++ b/docs/lightbench.feature
@@ -53,6 +53,13 @@ Feature: LightBench: a small Rust + Bevy renderer that proves raea's lighting an
And the sampled bounce converges to the reference as frames grow (RMSE against it, written down) with no bias
And a sampled pixel traces at most K + 2N rays whatever the number of lights
+ Scenario: LB6 a sun and a sky, in a closed room lit through a window
+ When LightBench draws --scene room, or --sun on and --sky X
+ Then the sun is one shadow ray a lit point to a point on its disc, the same in every mode, so its shadows soften
+ as --sun-size grows; a bounce ray that leaves the scene brings the sky
+ And in the room the bounce lights what the sun patch and the window don't, and converges to the reference
+ And a sampled pixel traces at most K + 1 + 3N rays
+
# LB4: instrumentation and acceptance
Scenario: LB4 sweeps
Then camera and light-count sweeps at a fixed resolution print triangles drawn, rays a pixel and pass timings