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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
LT2: raea GI measured on Berlin's walk at 1080p: the probe rays cost 0.26 ms of GPU at 128k a frame and 0.9 ms at 512k, the TLAS 0.83 ms of CPU a frame (5,518 instances, 707 BLAS). Probes are kept by their place in the world, so a moving grid keeps what it learned and a probe new to it traces the warm rounds; a resolve pass writes the volume each frame. The volume lights the scene only with RAEA_GI_SHOW=volume, since on the Mac it is a 17th fragment sampler for hooked materials (D19 warning). raea light check gets a gi path with the pass's GPU ms; Berlin's live and flicker scene is gambit's light-walk, people-ingame being a contact sheet.
shinyobjectzc4cb327b8588
diff --git a/bench/light/scenes.json b/bench/light/scenes.jsonindex ecb944b0..5eb084a7 100644--- a/bench/light/scenes.json+++ b/bench/light/scenes.json@@ -18,10 +18,25 @@],"reference": false,"why": "its city is drawn by shader hooks the path tracer can't run and its people aren't traced (M3, M5): after LT2, LT3 and LT5",+ "live": false,+ "live_why": "a contact sheet: every frame cuts to another view or sky, so its live frames are scene changes and its frames 0-4 are cuts, not a moving shot; gambit-walk measures both"+ },+ {+ "name": "gambit-walk",+ "dir": "~/Studio/raea/projects/gambit",+ "file": "compositions/light-walk.tsx",+ "composition": "light-walk-day",+ "stills": [+ 0,+ 96,+ 191+ ],+ "reference": false,+ "why": "as gambit-street: the city's shader hooks and the people (M3, M5), after LT2, LT3 and LT5","live": true,"shot": [- 0,- 4+ 84,+ 107]},{diff --git a/docs/manual/reference/cli/light.md b/docs/manual/reference/cli/light.mdindex 568e25d6..4b5fcda7 100644--- a/docs/manual/reference/cli/light.md+++ b/docs/manual/reference/cli/light.md@@ -7,7 +7,8 @@ sources: ["engine/light/src/lib.rs", "engine/light/src/metric.rs", "engine/rende`raea light check` is the bar raea's lighting is held to (docs/realism.feature LT1). Each scene in a list isrendered on each light path (raster as the composition has it; `traced-ao`, raster with traced occlusion in place of-SSAO on a camera with `<AmbientOcclusion>`; and Solari) and against its reference: the same frames path-traced, each+SSAO on a camera with `<AmbientOcclusion>`; Solari; and `gi`, raster with raea GI's probes traced, its GPU+milliseconds a frame reported beside the frame's) and against its reference: the same frames path-traced, eachdrawn `--spp` times so it converges. For each path it reports:- how far the stills are from the reference, in stops: the mean, the bias (brighter is positive) and the worst@@ -44,7 +45,7 @@ raea light check bench/light/scenes.json -o out/light/ --scene kitchen --paths s## Usage```sh-raea light check SCENES.json -o DIR [--scene NAME] [--paths raster,traced-ao,solari] [--spp N] [--fresh] (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)+raea light check SCENES.json -o DIR [--scene NAME] [--paths raster,traced-ao,solari,gi] [--spp N] [--fresh] (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)```Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.@@ -54,7 +55,7 @@ Headless: it needs nothing running and opens no window. Takes up to 2 arguments| Flag | Takes | What it does || --- | --- | --- || `--fresh` | – | Make the references again, even where they're kept from an earlier check. |-| `--paths` | `raster,traced-ao,solari` | The light paths to measure, comma-separated (all three by default). |+| `--paths` | `raster,traced-ao,solari,gi` | The light paths to measure, comma-separated (all four by default). || `--scene` | `NAME` | Check only the scene with this name. || `--spp` | `N` | How many times each reference frame is path-traced: its samples a pixel (256 by default). || `-o` | `DIR` | The folder for each scene's frames and report.json. |diff --git a/engine/light/src/lib.rs b/engine/light/src/lib.rsindex b07e9d2a..c98f0cec 100644--- a/engine/light/src/lib.rs+++ b/engine/light/src/lib.rs@@ -18,16 +18,18 @@ use serde_json::{json, Value};use std::path::{Path, PathBuf};use std::time::Instant;-pub const USAGE: &str = "raea light check SCENES.json -o DIR [--scene NAME] [--paths raster,traced-ao,solari] [--spp N] [--fresh]";+pub const USAGE: &str = "raea light check SCENES.json -o DIR [--scene NAME] [--paths raster,traced-ao,solari,gi] [--spp N] [--fresh]";/// The light paths a check compares: RAEA_LIGHT's, and traced-ao, raster with systems/rt's traced occlusion in place/// of SSAO (on a camera with <AmbientOcclusion>; on any other it draws as raster).-const PATHS: [&str; 3] = ["raster", "traced-ao", "solari"];+const PATHS: [&str; 4] = ["raster", "traced-ao", "solari", "gi"];-/// The switches a path is drawn with (the reference is `pathtracer`).+/// The switches a path is drawn with (the reference is `pathtracer`). `gi` is raster with raea GI's probes traced+/// (systems/rt gi.rs; RAEA_GI_RAYS and the rest pass through from the check's own environment).fn switches(path: &str) -> Vec<(&'static str, String)> {match path {"traced-ao" => vec![("RAEA_LIGHT", "raster".into()), ("RAEA_TRACED_AO", "0.5".into())],+ "gi" => vec![("RAEA_LIGHT", "raster".into()), ("RAEA_GI", "1".into())],p => vec![("RAEA_LIGHT", p.to_string())],}}@@ -98,14 +100,17 @@ fn render(scene: &Scene, path: &str, spp: u32, at: &[i64], out: &Path) -> R<f64>/// The scene played live on `path` at `size`, headless and unthrottled (`raea play --offscreen --no-vsync --3d`): what/// a frame costs, from play's report (DIR/PATH-live-WxH.json): the frames presented a second as milliseconds a frame,-/// and each frame's work at the median and the 99th percentile.+/// and each frame's work at the median and the 99th percentile; on `gi`, the probe pass's own GPU time (RAEA_GI_STATS).fn live(scene: &Scene, path: &str, size: (i64, i64), out: &Path) -> R<Value> {let exe = std::env::current_exe().map_err(|e| e.to_string())?;let size = format!("{}x{}", size.0, size.1);let json_out = out.join(format!("{path}-live-{size}.json"));+ let gi_out = out.join(format!("{path}-gi-{size}.json"));+ let _ = std::fs::remove_file(&gi_out);let run = std::process::Command::new(exe).current_dir(&scene.dir).envs(switches(path))+ .env("RAEA_GI_STATS", &gi_out).env("RAEA_AUDIO_MUTE", "1").args(["play", &scene.file, "--offscreen", "--no-vsync", "--3d", "--seconds", LIVE_SECONDS, "--size", &size, "--json"]).arg(&json_out)@@ -121,6 +126,7 @@ fn live(scene: &Scene, path: &str, size: (i64, i64), out: &Path) -> R<Value> {"size": size,"ms_a_frame": if fps > 0.0 { json!(((1000.0 / fps) * 10.0).round() / 10.0) } else { Value::Null },"work_ms_p50": r["work_ms"]["p50"], "work_ms_p99": r["work_ms"]["p99"], "presented": r["presented"], "error": r["error"],+ "gi": std::fs::read_to_string(&gi_out).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()),}))}@@ -211,14 +217,15 @@ fn check(scene: &Scene, paths: &[String], spp: u32, out: &Path, fresh: bool) ->/// The table a person reads: a line a scene and path.fn table(reports: &[Value]) -> String {- let mut s = format!("{:<18} {:<9} {:>7} {:>7} {:>7} {:>8} {:>7} {:>8} {:>8}\n", "scene", "path", "mean", "bias", "worst", "flicker", "raw", "s/still", "live ms");+ let mut s = format!("{:<18} {:<9} {:>7} {:>7} {:>7} {:>8} {:>7} {:>8} {:>8} {:>8}\n", "scene", "path", "mean", "bias", "worst", "flicker", "raw", "s/still", "live ms", "gi gpu");for r in reports {let name = r["name"].as_str().unwrap_or("");let Some(paths) = r["paths"].as_object() else { continue };for (p, v) in paths {let f = |k: &str| v[k].as_f64().map_or("-".to_string(), |x| format!("{x:.3}"));let ms = |k: &str| v["live"][k]["ms_a_frame"].as_f64().map_or("-".to_string(), |x| format!("{x:.1}"));- s += &format!("{name:<18} {p:<9} {:>7} {:>7} {:>7} {:>8} {:>7} {:>8} {:>8}\n", f("mean_stops"), f("bias_stops"), f("worst_tile_stops"), f("flicker_stops"), f("flicker_raw"), f("seconds_a_still"), ms("full"));+ let gi = v["live"]["full"]["gi"]["gpu_ms_p50"].as_f64().map_or("-".to_string(), |x| format!("{x:.2}"));+ s += &format!("{name:<18} {p:<9} {:>7} {:>7} {:>7} {:>8} {:>7} {:>8} {:>8} {gi:>8}\n", f("mean_stops"), f("bias_stops"), f("worst_tile_stops"), f("flicker_stops"), f("flicker_raw"), f("seconds_a_still"), ms("full"));}if r["reference"]["made"] == json!(false) {s += &format!("{name:<18} (no reference: {})\n", r["reference"]["why"].as_str().unwrap_or(""));diff --git a/systems/rt/src/gi.rs b/systems/rt/src/gi.rsindex 0b9eaa2a..f981f15b 100644--- a/systems/rt/src/gi.rs+++ b/systems/rt/src/gi.rs@@ -2,10 +2,13 @@//! costs on this GPU, and the light they give through Bevy's irradiance volume. A grid of probes around the camera//! (RAEA_GI_GRID, 32x16x32 by default; RAEA_GI_SPACING metres apart, 2) is refreshed by a ray budget a frame//! (RAEA_GI_RAYS, 131072): 64 rays a probe, so the budget sets how many probes a frame (gi.wesl). The grid moves with-//! the camera a probe at a time; when it moves, or the sun or the sky changes, its means start again and every probe-//! traces RAEA_GI_WARM rounds (16) that frame, so a still is lit from its first frame. Those frames aren't timed.+//! the camera a probe at a time, each probe kept by its place in the world, so what the probes still covered have+//! learned stays; a probe new to the grid traces RAEA_GI_WARM rounds (16) when first reached. When the sun or the sky+//! changes, every mean starts again and every probe traces the warm rounds that frame, so a still is lit from its+//! first frame. Those frames aren't timed.//! RAEA_GI_STATS=FILE: the timed frames' GPU milliseconds (the pass's own timestamps), written there once a second.-//! Unset, nothing changes.+//! RAEA_GI_SHOW=volume: the probes light the scene through Bevy's irradiance volume (see `install`). Unset, nothing+//! changes.use std::sync::{atomic::{AtomicBool, Ordering},@@ -60,7 +63,14 @@ pub fn install(app: &mut App) {voxels.texture_descriptor.usage |= TextureUsages::STORAGE_BINDING;let voxels = app.world_mut().resource_mut::<Assets<Image>>().add(voxels);let spacing = env("RAEA_GI_SPACING", 2.0f32);- app.world_mut().spawn((Name::new("raea gi"), LightProbe::default(), IrradianceVolume { voxels: voxels.clone(), intensity: 1.0, affects_lightmapped_meshes: false }, Transform::from_scale(res.as_vec3() * spacing)));+ // Shown through Bevy's irradiance volume only when asked: it takes one more sampler in every material's fragment+ // stage, and a hooked material over StandardMaterial already has Metal's 16 (Bevy's view 9, StandardMaterial 6, the+ // hook's own), so on the Mac the pipeline fails to build (11-17, Berlin). The deferred lighting pass (D4) has room.+ if std::env::var("RAEA_GI_SHOW").as_deref() == Ok("volume") {+ app.world_mut().spawn((Name::new("raea gi"), LightProbe::default(), IrradianceVolume { voxels: voxels.clone(), intensity: 1.0, affects_lightmapped_meshes: false }, Transform::from_scale(res.as_vec3() * spacing)));+ } else {+ eprintln!("raea gi: effect dropped (gi-not-shown): the probes are traced and timed but light nothing; Bevy's irradiance volume would take a 17th fragment sampler on Metal (RAEA_GI_SHOW=volume tries it)");+ }app.insert_resource(Grid { center: Vec3::ZERO, spacing, res, voxels, sky: None, sun: Vec4::ZERO, sun_light: Vec3::ZERO }).add_plugins(ExtractResourcePlugin::<Grid>::default()).add_systems(PostUpdate, follow.after(bevy::transform::TransformSystems::Propagate));@@ -135,7 +145,9 @@ struct Params {#[derive(Resource)]struct Pipeline {layout: BindGroupLayoutDescriptor,+ /// the probes' rays (gi.wesl `main`), and their cubes into the volume (`resolve`)id: CachedComputePipelineId,+ resolve: CachedComputePipelineId,sampler: Sampler,}@@ -152,26 +164,25 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCacsampler(SamplerBindingType::Filtering),storage_buffer_sized(false, None),texture_storage_3d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),+ storage_buffer_sized(false, None),),),);- let id = cache.queue_compute_pipeline(ComputePipelineDescriptor {- label: Some("raea_gi".into()),- layout: vec![layout.clone()],- shader: assets.load("embedded://raea_sys_rt/gi.wesl"),- entry_point: Some("main".into()),- ..default()+ let shader = assets.load("embedded://raea_sys_rt/gi.wesl");+ let [id, resolve] = ["main", "resolve"].map(|entry| {+ cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some(format!("raea_gi_{entry}").into()), layout: vec![layout.clone()], shader: shader.clone(), entry_point: Some(entry.into()), ..default() })});let sampler = device.create_sampler(&SamplerDescriptor { label: Some("raea gi sky"), mag_filter: FilterMode::Linear, min_filter: FilterMode::Linear, ..default() });- commands.insert_resource(Pipeline { layout, id, sampler });+ commands.insert_resource(Pipeline { layout, id, resolve, sampler });}-/// The cache between frames: its means, where the next frame's probes start, what it was last lit by, and its timer.+/// The cache between frames: its means and which probe each slot holds (gi.wesl's `cubes` and `tags`), where the next+/// frame's probes start, what it was last lit by, and its timer.#[derive(Resource, Default)]struct State {- cubes: Option<(Buffer, u32)>,+ cubes: Option<(Buffer, Buffer, u32)>,frame: u32,- key: Option<[u32; 12]>,+ key: Option<[u32; 9]>,timer: Option<Timer>,seen: Vec<f64>,written: Option<std::time::Instant>,@@ -186,12 +197,13 @@ struct Timer {pending: Option<Arc<AtomicBool>>,}-/// what the grid is lit from: its place, the sun and the sky; any change starts its means again-fn key(g: &Grid) -> [u32; 12] {+/// what the grid is lit from: the sun and the sky (and its size); any change starts every mean again. Not its place:+/// a probe is kept by where it is in the world, so the grid moving starts only the probes new to it (gi.wesl `tags`).+fn key(g: &Grid) -> [u32; 9] {let (s, i) = g.sky.map(|(s, _, i, _)| (s, i)).unwrap_or((AssetId::default(), 0.0));let h = { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); s.hash(&mut h); h.finish() as u32 };let f = |v: f32| v.to_bits();- [f(g.center.x), f(g.center.y), f(g.center.z), f(g.sun.x), f(g.sun.y), f(g.sun.z), f(g.sun_light.x), f(g.sun_light.y), f(g.sun_light.z), h, f(i), g.res.x ^ (g.res.y << 10) ^ (g.res.z << 20)]+ [f(g.sun.x), f(g.sun.y), f(g.sun.z), f(g.sun_light.x), f(g.sun_light.y), f(g.sun_light.z), h, f(i), g.res.x ^ (g.res.y << 10) ^ (g.res.z << 20)]}#[allow(clippy::too_many_arguments)]@@ -207,7 +219,7 @@ fn update(mut state: ResMut<State>,) {let (Some(grid), Some(scene), Some(p)) = (grid, scene, p) else { return };- let Some(pipeline) = cache.get_compute_pipeline(p.id) else { return };+ let (Some(pipeline), Some(resolve)) = (cache.get_compute_pipeline(p.id), cache.get_compute_pipeline(p.resolve)) else { return };let Some(voxels) = images.get(grid.voxels.id()) else { return };let (sky, sky_diffuse) = match grid.sky {Some((s, d, _, _)) => match (images.get(s), images.get(d)) {@@ -217,9 +229,9 @@ fn update(None => (&fallback.cube.texture_view, &fallback.cube.texture_view),};let total = grid.res.x * grid.res.y * grid.res.z;- if state.cubes.as_ref().is_none_or(|(_, n)| *n != total) {- let b = device.create_buffer(&BufferDescriptor { label: Some("raea gi cubes"), size: total as u64 * 6 * 16, usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, mapped_at_creation: false });- state.cubes = Some((b, total));+ if state.cubes.as_ref().is_none_or(|(_, _, n)| *n != total) {+ let buffer = |label: &'static str, faces: u64| device.create_buffer(&BufferDescriptor { label: Some(label), size: total as u64 * faces * 16, usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, mapped_at_creation: false });+ state.cubes = Some((buffer("raea gi cubes", 6), buffer("raea gi tags", 1), total));state.key = None;}collect(&mut state);@@ -227,13 +239,14 @@ fn update(let fresh = state.key != Some(k);state.key = Some(k);let budget = env("RAEA_GI_RAYS", 131072u32).max(RAYS);- let (start, probes, rounds) = if fresh { (0, total, env("RAEA_GI_WARM", 16u32).max(1)) } else { ((state.frame.wrapping_mul(budget / RAYS)) % total, (budget / RAYS).min(total), 1) };+ let warm = env("RAEA_GI_WARM", 16u32).max(1);+ let (start, probes, rounds) = if fresh { (0, total, warm) } else { ((state.frame.wrapping_mul(budget / RAYS)) % total, (budget / RAYS).min(total), 1) };state.frame = state.frame.wrapping_add(1);let (turn, intensity) = grid.sky.map(|(_, _, i, q)| (Vec4::from(q), i)).unwrap_or((Vec4::W, 0.0));let params = Params {grid: grid.center.extend(grid.spacing),res: grid.res.extend(total),- run: UVec4::new(start, rounds, state.frame, 0),+ run: UVec4::new(start, rounds, state.frame, warm),sun_dir: grid.sun,sun: grid.sun_light.extend(intensity),sky_turn: turn,@@ -243,24 +256,28 @@ fn update(if state.timer.is_none() && device.features().contains(WgpuFeatures::TIMESTAMP_QUERY) {state.timer = Some(timer(&device, &queue));}- let cubes = &state.cubes.as_ref().unwrap().0;+ let (cubes, tags, _) = state.cubes.as_ref().unwrap();let group = device.create_bind_group("raea_gi",&cache.get_bind_group_layout(&p.layout),- &BindGroupEntries::sequential((uniform.binding().unwrap(), scene.0.as_binding(), sky, sky_diffuse, &p.sampler, cubes.as_entire_binding(), &voxels.texture_view)),+ &BindGroupEntries::sequential((uniform.binding().unwrap(), scene.0.as_binding(), sky, sky_diffuse, &p.sampler, cubes.as_entire_binding(), &voxels.texture_view, tags.as_entire_binding())),);// a steady frame is timed when the last one's times are inlet timed = !fresh && state.timer.as_ref().is_some_and(|t| t.pending.is_none());let mut enc = device.create_command_encoder(&CommandEncoderDescriptor { label: Some("raea gi") });if fresh {enc.clear_buffer(cubes, 0, None);+ enc.clear_buffer(tags, 0, None);}{let writes = state.timer.as_ref().filter(|_| timed).map(|t| wgpu::ComputePassTimestampWrites { query_set: &t.set, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) });let mut pass = enc.begin_compute_pass(&ComputePassDescriptor { label: Some("raea_gi"), timestamp_writes: writes });- pass.set_pipeline(pipeline);pass.set_bind_group(0, &group, &[]);+ pass.set_pipeline(pipeline);pass.dispatch_workgroups(probes, 1, 1);+ // every probe's cube into the volume (the grid may have moved), timed with the rays: it is the pass's cost too+ pass.set_pipeline(resolve);+ pass.dispatch_workgroups(total.div_ceil(64), 1, 1);}if let Some(t) = state.timer.as_ref().filter(|_| timed) {enc.resolve_query_set(&t.set, 0..2, &t.resolve, 0);@@ -313,14 +330,23 @@ fn report(state: &mut State, budget: u32, total: u32) {let mut v = state.seen.clone();v.sort_by(f64::total_cmp);let at = |q: f64| v[((v.len() - 1) as f64 * q).round() as usize];+ // the ray scene's CPU milliseconds a call: the instance list, the TLAS, a BLAS batch (lib.rs CPU_US)+ let cpu = |k: usize| {+ let (us, n) = (crate::CPU_US[2 * k].load(Ordering::Relaxed), crate::CPU_US[2 * k + 1].load(Ordering::Relaxed));+ format!("{:.3}", us as f64 / n.max(1) as f64 / 1000.0)+ };let text = format!(- "{{\"rays_a_frame\":{},\"probes\":{total},\"probes_a_frame\":{},\"frames\":{},\"gpu_ms_p50\":{:.3},\"gpu_ms_p90\":{:.3},\"gpu_ms_max\":{:.3}}}\n",+ "{{\"rays_a_frame\":{},\"probes\":{total},\"probes_a_frame\":{},\"frames\":{},\"gpu_ms_p50\":{:.3},\"gpu_ms_p90\":{:.3},\"gpu_ms_max\":{:.3},\"cpu_ms_gather\":{},\"cpu_ms_tlas\":{},\"cpu_ms_blas_batch\":{},\"blas_batches\":{}}}\n",(budget / RAYS).min(total) * RAYS,(budget / RAYS).min(total),v.len(),at(0.5),at(0.9),- at(1.0)+ at(1.0),+ cpu(0),+ cpu(1),+ cpu(2),+ crate::CPU_US[5].load(Ordering::Relaxed));let _ = std::fs::write(path, text);}diff --git a/systems/rt/src/gi.wesl b/systems/rt/src/gi.weslindex d289f0af..d2574e72 100644--- a/systems/rt/src/gi.wesl+++ b/systems/rt/src/gi.wesl@@ -11,7 +11,7 @@ struct Params {grid: vec4<f32>,/// probes along x, y, z; probes in allres: vec4<u32>,- /// the first probe this dispatch, rounds each probe traces, the frame's salt+ /// the first probe this dispatch, rounds each probe traces, the frame's salt, rounds a probe new to its slot tracesrun: vec4<u32>,/// toward the sun; 1 when there's a sky to seesun_dir: vec4<f32>,@@ -26,8 +26,12 @@ struct Params {@group(0) @binding(2) var sky: texture_cube<f32>;@group(0) @binding(3) var sky_diffuse: texture_cube<f32>;@group(0) @binding(4) var sky_sampler: sampler;+// each probe's six faces (rgb and how many rounds its mean holds), kept by its place in the world (`slot`), so the grid+// can move a probe at a time and keep what the probes it still covers have learned@group(0) @binding(5) var<storage, read_write> cubes: array<vec4<f32>>;@group(0) @binding(6) var voxels: texture_storage_3d<rgba16float, write>;+// which world probe each slot holds (xyz) and whether it holds one (w), so a slot taken over starts afresh+@group(0) @binding(7) var<storage, read_write> tags: array<vec4<i32>>;const PI = 3.14159265;const RAYS = 64u;@@ -39,6 +43,26 @@ const ALL = 2u;var<workgroup> light: array<vec3<f32>, 64>;var<workgroup> dirs: array<vec3<f32>, 64>;+var<workgroup> fresh: u32;++// The probe at a place in the grid: its world position, and its slot (its place on a world lattice, wrapped into the+// grid: the same probe keeps its slot while the grid moves around it).+fn probe_at(ijk: vec3<u32>) -> vec3<f32> {+ return p.grid.xyz + ((vec3<f32>(ijk) + 0.5) - vec3<f32>(p.res.xyz) * 0.5) * p.grid.w;+}+// its cell on the world lattice, in integers (the grid's centre is a whole number of spacings: follow() rounds it)+fn cell_of(ijk: vec3<u32>) -> vec3<i32> {+ return vec3<i32>(round(p.grid.xyz / p.grid.w)) - vec3<i32>(p.res.xyz / 2u) + vec3<i32>(ijk);+}+fn slot_of(l: vec3<i32>) -> u32 {+ let r = vec3<i32>(p.res.xyz);+ let s = ((l % r) + r) % r;+ return u32(s.x) + u32(s.y) * p.res.x + u32(s.z) * p.res.x * p.res.y;+}+fn grid_ijk(i: u32) -> vec3<u32> {+ let r = p.res.xyz;+ return vec3<u32>(i % r.x, (i / r.x) % r.y, i / (r.x * r.y));+}fn hash(v: u32) -> u32 {let s = v * 747796405u + 2891336453u;@@ -114,11 +138,21 @@ fn sky_irradiance(n: vec3<f32>) -> vec3<f32> {// one workgroup a probe, one ray a thread each round@compute @workgroup_size(64, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) li: u32) {- let r = p.res.xyz;- let probe = (p.run.x + wg.x) % p.res.w;- let ijk = vec3<u32>(probe % r.x, (probe / r.x) % r.y, probe / (r.x * r.y));- let at = p.grid.xyz + ((vec3<f32>(ijk) + 0.5) - vec3<f32>(r) * 0.5) * p.grid.w;- for (var round = 0u; round < p.run.y; round++) {+ let ijk = grid_ijk((p.run.x + wg.x) % p.res.w);+ let at = probe_at(ijk);+ let cell = cell_of(ijk);+ let probe = slot_of(cell);+ // a slot that held another probe (the grid moved over it) or none starts its means again+ if (li == 0u) {+ let tag = tags[probe];+ fresh = select(0u, 1u, tag.w == 0 || any(tag.xyz != cell));+ tags[probe] = vec4(cell, 1);+ }+ workgroupBarrier();+ let restart = workgroupUniformLoad(&fresh) == 1u;+ // a probe new to its slot traces the warm rounds (run.w), so it is lit the frame it is first reached+ let rounds = select(p.run.y, max(p.run.y, p.run.w), restart);+ for (var round = 0u; round < rounds; round++) {let q = random_turn(hash(p.run.z * 7919u + round * 104729u + probe));let d = turn(q, fib(li, RAYS));var l = vec3(0.0);@@ -149,13 +183,33 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) l}e *= 4.0 / f32(RAYS);let slot = probe * 6u + li;- let old = cubes[slot];+ var old = cubes[slot];+ if (restart && round == 0u) {+ old = vec4(0.0);+ }let count = min(old.w + 1.0, HISTORY);- let mean = mix(old.rgb, e, 1.0 / count);- cubes[slot] = vec4(mean, count);- // Bevy's layout: (x, y, z) a probe, the negative face's half below in y, each axis a third of z- textureStore(voxels, vec3<u32>(ijk.x, ijk.y + r.y * neg, ijk.z + r.z * axis), vec4(mean, 1.0));+ cubes[slot] = vec4(mix(old.rgb, e, 1.0 / count), count);}workgroupBarrier();}}++// Every probe's cube into Bevy's irradiance volume, each frame (the grid may have moved, so every texel may now be+// another probe's): (x, y, z) a probe, the negative face's half below in y, each axis a third of z. A slot not yet+// holding its probe writes nothing new.+@compute @workgroup_size(64, 1, 1)+fn resolve(@builtin(global_invocation_id) id: vec3<u32>) {+ if (id.x >= p.res.w) {+ return;+ }+ let ijk = grid_ijk(id.x);+ let cell = cell_of(ijk);+ let probe = slot_of(cell);+ let tag = tags[probe];+ let held = tag.w == 1 && all(tag.xyz == cell);+ let r = p.res.xyz;+ for (var face = 0u; face < 6u; face++) {+ let c = select(vec3(0.0), cubes[probe * 6u + face].rgb, held);+ textureStore(voxels, vec3<u32>(ijk.x, ijk.y + r.y * (face & 1u), ijk.z + r.z * (face / 2u)), vec4(c, 1.0));+ }+}diff --git a/systems/rt/src/lib.rs b/systems/rt/src/lib.rsindex 0529ce64..ca9611a8 100644--- a/systems/rt/src/lib.rs+++ b/systems/rt/src/lib.rs@@ -53,6 +53,14 @@ pub struct Sun(pub Vec3);#[derive(Resource, Default)]struct Blases(HashMap<AssetId<Mesh>, Blas>);+/// The ray scene's CPU cost so far, for raea GI's stats (gi.rs `report`; LT2): microseconds and calls of `gather`+/// (the main world's instance list), `build_tlas` and `build_blas` (counted only when it builds), in that order.+pub(crate) static CPU_US: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];+fn spent(k: usize, since: std::time::Instant) {+ CPU_US[2 * k].fetch_add(since.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed);+ CPU_US[2 * k + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);+}+/// This frame's TLAS, for the traced passes to bind.#[derive(Resource)]pub struct Scene(pub Tlas);@@ -92,6 +100,7 @@ fn gather(mut instances: ResMut<Instances>,mut sun: ResMut<Sun>,) {+ let t0 = std::time::Instant::now();instances.0.clear();for (mesh, t, vis, mat, no_shadow) in &meshes {if !vis.get() || mat.and_then(|m| mats.get(&m.0)).is_some_and(see_through) {@@ -102,6 +111,7 @@ fn gather(if let Some((_, t)) = lights.iter().find(|(l, _)| l.shadow_maps_enabled).or_else(|| lights.iter().next()) {sun.0 = t.back().as_vec3();}+ spent(0, t0);if std::env::var_os("RAEA_RT_DEBUG").is_some() {let all: Vec<_> = lights.iter().map(|(l, t)| (l.shadow_maps_enabled, t.back().as_vec3())).collect();let skipped = meshes.iter().filter(|(_, _, v, m, _)| v.get() && m.and_then(|m| mats.get(&m.0)).is_some_and(see_through)).count();@@ -129,6 +139,7 @@ fn build_blas(if !device.features().contains(WgpuFeatures::EXPERIMENTAL_RAY_QUERY) {return;}+ let t0 = std::time::Instant::now();for id in extracted.removed.iter().chain(extracted.modified.iter()) {blases.0.remove(id);}@@ -193,6 +204,7 @@ fn build_blas(let mut enc = device.create_command_encoder(&CommandEncoderDescriptor { label: Some("raea rt blas") });enc.build_acceleration_structures(&entries, &[]);queue.submit([enc.finish()]);+ spent(2, t0);}/// the TLAS: every instance whose mesh has a BLAS, rebuilt each frame (things move)@@ -201,6 +213,7 @@ fn build_tlas(mut commands: Commands, instances: Option<Res<Instances>>, blases:if !device.features().contains(WgpuFeatures::EXPERIMENTAL_RAY_QUERY) {return;}+ let t0 = std::time::Instant::now();let present: Vec<_> = instances.0.iter().filter_map(|(id, m, mask)| blases.0.get(id).map(|b| (b, m, *mask))).collect();if std::env::var_os("RAEA_RT_DEBUG").is_some() {for (id, _, _) in instances.0.iter().filter(|(id, _, _)| !blases.0.contains_key(id)) {@@ -220,6 +233,7 @@ fn build_tlas(mut commands: Commands, instances: Option<Res<Instances>>, blases:let mut enc = device.create_command_encoder(&CommandEncoderDescriptor { label: Some("raea rt tlas") });enc.build_acceleration_structures(&[], [&tlas]);queue.submit([enc.finish()]);+ spent(1, t0);if std::env::var_os("RAEA_RT_DEBUG").is_some() {eprintln!("raea rt: {} instances, {} with a BLAS ({} BLAS)", instances.0.len(), present.len(), blases.0.len());}