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
LT3: the world cache, built and timed on Berlin before anything rests on it
shinyobjectzda31c4b3c6fd
diff --git a/docs/realism.feature b/docs/realism.featureindex 631fad42..d24bf70e 100644--- a/docs/realism.feature+++ b/docs/realism.feature@@ -281,12 +281,25 @@ Feature: raea Light: raea's own real-time realism renderer, measured against raesurface (LT4) a cell sees LT2's stand-in (albedo 0.5) and is keyed by the side a ray meets (its normal facesthe ray); LT2's probe rays seed it, the screen's 8x8-tile paths come after; behind RAEA_GI=1, timed per pass| crate | file | lines | job |- | raea-sys-rt | src/cache.rs | 260 | the cache's buffers (2^20 cells, 84 bytes each), its passes in order |+ | raea-sys-rt | src/cache.rs | 130 | the cache's buffers (2^20 cells, 84 bytes each), its passes in order || raea-sys-rt | src/cache.wesl | 170 | the hash grid: cell size by distance, key and checksum, claim, read |- | raea-sys-rt | src/cache_update.wesl | 150 | each live cell: sun and sky, one bounce into last frame's cache, blend || raea-sys-rt | src/compact.wesl | 80 | cells age out; the live ones listed (a two-level prefix sum) |- | raea-sys-rt | src/gi.wesl | +20 | a probe ray's hit reads its cell in place of the flat stand-in |+ | raea-sys-rt | src/gi.wesl | +90 | a probe ray's hit reads its cell; `learn` and `blend`, the update || raea-sys-rt | src/gi.rs | +40 | the cache's GPU ms per pass and its live cells in RAEA_GI_STATS |+ And so far (11-17, branch realism; not done): the cache runs behind RAEA_GI=1 before the probes each frame, in+ two compute passes (upkeep: cells age, the live ones listed; update: 40000 cells learn the sun and one bounce+ into last frame's cache, and blend), and the probes' hits read it. Measured on Berlin's walk (light-walk) at+ 1080p by GPU timestamps, 131072 probe rays a frame:+ | smallest cell | cache ms p50 | p90 | probes ms p50 | live cells p50 | max |+ | 0.15 m | 0.931 | 1.211 | 0.310 | 541,923 | 1,032,116 |+ | 0.5 m | 0.512 | 0.688 | 0.259 | 210,165 | 479,631 |+ | 1 m | 0.456 | 0.541 | 0.241 | 99,018 | 189,480 |+ | 0.5 m, 524288 rays | 0.594 | 0.718 | 0.799 | 289,538 | 488,563 |+ And what they say: 0.5 m is the default; 0.15 m fills the table. Decay and listing over all 2^20 cells set a floor+ near 0.4 ms; the frame's work p50 moves about 5 ms run to run (raster alone 45.4 ms), so the timestamps are the+ measure. LT2's probes cost 0.253 ms at 131072 rays. Open: the cache lights nothing on screen yet (as LT2's+ grid: Metal's sampler limit), so its light is unchecked; the persistent TLAS, compaction and the screen's+ 8x8-tile paths are still to buildScenario: LT4. What a ray hit seesGiven every MaterialExtension writes the deferred G-buffer with its own surface code (D4; procmat's is first,diff --git a/systems/rt/src/cache.rs b/systems/rt/src/cache.rsnew file mode 100644index 00000000..3c25b795--- /dev/null+++ b/systems/rt/src/cache.rs@@ -0,0 +1,125 @@+//! raea GI's world cache, its buffers and passes (docs/realism.feature LT3; cache.wesl, compact.wesl, and gi.wesl's+//! `learn` and `blend`): 2^20 cells of 84 bytes (84 MiB) on the surfaces rays hit. Each frame, before the probes, every+//! cell ages and the live ones are listed (compact.wesl); about RAEA_GI_UPDATES of them (40000) learn one bounce more+//! and take it into their means. The probes then read it where their rays hit (gi.wesl). The list's length becomes the+//! update's dispatch on the GPU: wgpu won't take a buffer as a dispatch's arguments while that dispatch binds it for+//! writing, so the arguments are copied out between the two passes (`args`), as Solari's world cache does.+//! RAEA_GI_CELL: the smallest cell (m, 0.5; Solari's 0.15 suits screen pixels, but 131072 probe rays a frame filled all+//! 2^20 cells on Berlin's walk, where 0.5 peaks at 480k and costs 0.51 ms against 0.93). RAEA_GI_CELL_DOUBLE: the+//! distance from the eye over which a cell's size doubles (m, 15). RAEA_GI_HISTORY: the most frames a cell's mean holds+//! (32).++use bevy::{+ prelude::*,+ render::{+ render_resource::{+ binding_types::{storage_buffer_sized, uniform_buffer},+ *,+ },+ renderer::RenderDevice,+ },+};++/// cells in all: 1024 blocks of 1024 (cache.wesl's CELLS; compact.wesl lists them in two levels)+pub(crate) const CELLS: u64 = 1 << 20;++/// the cache's buffers in binding order, each `(label, bytes)`: a cell's 84 bytes are a checksum, a life, its light,+/// where it is and its side, its light's change, its place in the list's block sum, its place in the list, its new light+const BUFFERS: [(&str, u64); 11] = [+ ("raea gi cache checksums", 4 * CELLS),+ ("raea gi cache life", 4 * CELLS),+ ("raea gi cache radiance", 16 * CELLS),+ ("raea gi cache cells", 32 * CELLS),+ ("raea gi cache deltas", 4 * CELLS),+ ("raea gi cache a", 4 * CELLS),+ ("raea gi cache b", 4 * (CELLS / 1024)),+ ("raea gi cache live", 4 * CELLS),+ ("raea gi cache count", 4),+ ("raea gi cache dispatch", 16),+ ("raea gi cache learned", 16 * CELLS),+];+/// where the list's length and its dispatch are among BUFFERS+pub(crate) const COUNT: usize = 8;+const DISPATCH: usize = 9;++/// cache.wesl's Upkeep: the eye; the smallest cell, the distance a cell's size doubles over, the most frames a mean+/// holds; the frame's salt, the cells a frame aims to update, 1 to forget every mean+#[derive(ShaderType, Clone, Copy)]+pub(crate) struct Upkeep {+ eye: Vec4,+ size: Vec4,+ run: UVec4,+}++impl Upkeep {+ pub(crate) fn new(eye: Vec3, frame: u32, reset: bool) -> Self {+ let env = |name: &str, or: f32| std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(or);+ let updates = std::env::var("RAEA_GI_UPDATES").ok().and_then(|v| v.parse().ok()).unwrap_or(40000u32);+ Upkeep {+ eye: eye.extend(0.0),+ size: Vec4::new(env("RAEA_GI_CELL", 0.5), env("RAEA_GI_CELL_DOUBLE", 15.0), env("RAEA_GI_HISTORY", 32.0).max(1.0), 0.0),+ run: UVec4::new(frame.wrapping_mul(0x9e37_79b9), updates, reset as u32, 0),+ }+ }+}++/// the cache's bindings: group 1 of every pass that reads or keeps it+pub(crate) fn layout() -> BindGroupLayoutDescriptor {+ let s = || storage_buffer_sized(false, None);+ BindGroupLayoutDescriptor::new("raea_gi_cache_layout", &BindGroupLayoutEntries::sequential(ShaderStages::COMPUTE, (s(), s(), s(), s(), s(), s(), s(), s(), s(), s(), s(), uniform_buffer::<Upkeep>(false))))+}++/// the cache's six passes, in the order they run+pub(crate) struct Passes(pub [CachedComputePipelineId; 6]);++/// decay, the two sums and the list (compact.wesl), then learn and blend (gi.wesl), each on the probes' group 0 and the+/// cache's group 1+pub(crate) fn queue(cache: &PipelineCache, assets: &AssetServer, layouts: &[BindGroupLayoutDescriptor]) -> Passes {+ let (compact, gi) = (assets.load("embedded://raea_sys_rt/compact.wesl"), assets.load("embedded://raea_sys_rt/gi.wesl"));+ Passes([(&compact, "decay"), (&compact, "scan_cells"), (&compact, "scan_blocks"), (&compact, "list"), (&gi, "learn"), (&gi, "blend")].map(|(shader, entry)| {+ cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some(format!("raea_gi_cache_{entry}").into()), layout: layouts.to_vec(), shader: shader.clone(), entry_point: Some(entry.into()), ..default() })+ }))+}++/// The cache's buffers (zeroed: every cell empty) and the update's arguments, copied from the list's.+pub(crate) struct Buffers {+ pub all: Vec<Buffer>,+ args: Buffer,+}++pub(crate) fn buffers(device: &RenderDevice) -> Buffers {+ let all = BUFFERS.map(|(label, size)| device.create_buffer(&BufferDescriptor { label: Some(label), size, usage: BufferUsages::STORAGE | BufferUsages::COPY_DST | BufferUsages::COPY_SRC, mapped_at_creation: false })).to_vec();+ let args = device.create_buffer(&BufferDescriptor { label: Some("raea gi cache args"), size: 16, usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST, mapped_at_creation: false });+ Buffers { all, args }+}++pub(crate) fn bind(device: &RenderDevice, layout: &BindGroupLayout, b: &Buffers, upkeep: BindingResource) -> BindGroup {+ let mut entries: Vec<BindGroupEntry> = b.all.iter().enumerate().map(|(i, buffer)| BindGroupEntry { binding: i as u32, resource: buffer.as_entire_binding() }).collect();+ entries.push(BindGroupEntry { binding: BUFFERS.len() as u32, resource: upkeep });+ device.create_bind_group("raea_gi_cache", layout, &entries)+}++/// A frame of the cache into `enc`: the upkeep pass, the update's arguments copied out, the update pass. Both groups+/// are set on each; `times` are the timestamps at the upkeep's start and the update's end.+pub(crate) fn run(enc: &mut wgpu::CommandEncoder, p: &[&ComputePipeline; 6], groups: [&BindGroup; 2], b: &Buffers, times: Option<(&wgpu::QuerySet, u32)>) {+ let blocks = (CELLS / 1024) as u32;+ {+ let writes = times.map(|(set, at)| wgpu::ComputePassTimestampWrites { query_set: set, beginning_of_pass_write_index: Some(at), end_of_pass_write_index: None });+ let mut pass = enc.begin_compute_pass(&ComputePassDescriptor { label: Some("raea_gi_cache_upkeep"), timestamp_writes: writes });+ pass.set_bind_group(0, groups[0], &[]);+ pass.set_bind_group(1, groups[1], &[]);+ for (pipeline, n) in [(p[0], blocks), (p[1], blocks), (p[2], 1), (p[3], blocks)] {+ pass.set_pipeline(pipeline);+ pass.dispatch_workgroups(n, 1, 1);+ }+ }+ enc.copy_buffer_to_buffer(&b.all[DISPATCH], 0, &b.args, 0, 12);+ let writes = times.map(|(set, at)| wgpu::ComputePassTimestampWrites { query_set: set, beginning_of_pass_write_index: None, end_of_pass_write_index: Some(at + 1) });+ let mut pass = enc.begin_compute_pass(&ComputePassDescriptor { label: Some("raea_gi_cache_update"), timestamp_writes: writes });+ pass.set_bind_group(0, groups[0], &[]);+ pass.set_bind_group(1, groups[1], &[]);+ for pipeline in [p[4], p[5]] {+ pass.set_pipeline(pipeline);+ pass.dispatch_workgroups_indirect(&b.args, 0);+ }+}diff --git a/systems/rt/src/cache.wesl b/systems/rt/src/cache.weslnew file mode 100644index 00000000..49e2d555--- /dev/null+++ b/systems/rt/src/cache.wesl@@ -0,0 +1,122 @@+// raea GI's world cache (cache.rs; docs/realism.feature LT3): a hash grid of cells on the surfaces rays hit, each+// holding the light arriving at it (irradiance, lux: an albedo over pi turns it into the light the surface sends+// back), learned over frames. A cell is found by its place, quantised by a size that doubles with distance from the+// eye, and by its side (the normal, quantised to an octant), so a wall's two faces and a corner's two walls don't+// share. A read that finds no cell claims an empty one, and a read keeps a cell alive: one unread for LIFE frames+// empties (compact.wesl). Each frame some of the live cells learn from one bounce more (cache_update.wesl), so the+// light settles to every bounce over frames. From vendor/bevy_solari's world_cache_query.wesl, made raea's.+//+// Until hits know their surface (LT4) a cell is keyed by the side a ray meets it from: its normal faces the ray.++/// where a cell was claimed, and the normal it was claimed with (w unused)+struct Cell {+ at: vec4<f32>,+ n: vec4<f32>,+}++struct Upkeep {+ /// the eye (xyz)+ eye: vec4<f32>,+ /// the smallest cell (m), the distance over which a cell's size doubles (m), the most frames a cell's mean holds+ size: vec4<f32>,+ /// the frame's salt, how many cells a frame aims to update, 1 to forget every mean (a cut), unused+ run: vec4<u32>,+}++@group(1) @binding(0) var<storage, read_write> checksums: array<atomic<u32>>;+@group(1) @binding(1) var<storage, read_write> life: array<atomic<u32>>;+// what the cell has learned (rgb) and over how many frames (a)+@group(1) @binding(2) var<storage, read_write> radiance: array<vec4<f32>>;+@group(1) @binding(3) var<storage, read_write> cells: array<Cell>;+// how fast a cell's light is changing (a running mean of its luminance step), so a changing cell forgets faster+@group(1) @binding(4) var<storage, read_write> deltas: array<f32>;+// the live cells' list: each cell's place among the live ones in its block (a), each block's first place (b), the+// list, its length and the update's indirect dispatch (compact.wesl writes them)+@group(1) @binding(5) var<storage, read_write> a: array<u32>;+@group(1) @binding(6) var<storage, read_write> b: array<u32>;+@group(1) @binding(7) var<storage, read_write> live: array<u32>;+@group(1) @binding(8) var<storage, read_write> count: u32;+@group(1) @binding(9) var<storage, read_write> dispatch: vec3<u32>;+// each listed cell's new light this frame, before the blend+@group(1) @binding(10) var<storage, read_write> learned: array<vec4<f32>>;+@group(1) @binding(11) var<uniform> upkeep: Upkeep;++/// cells in all (cache.rs CELLS): 1024 blocks of 1024+const CELLS: u32 = 1048576u;+/// the most frames a cell lives unread+const LIFE: u32 = 10u;+/// the most cells tried after a collision+const SEARCH: u32 = 3u;+const EMPTY: u32 = 0u;++fn hash(v: u32) -> u32 {+ let s = v * 747796405u + 2891336453u;+ let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;+ return (w >> 22u) ^ w;+}+// a second hash, independent of the first, for the checksum that tells two places sharing a key apart+fn hash2(v: u32) -> u32 {+ let n = (v << 13u) ^ v;+ return n * (n * n * 15731u + 789221u) + 1376312589u;+}+/// a number in [0, 1) from a running seed+fn rand(seed: ptr<function, u32>) -> f32 {+ *seed = hash(*seed);+ return f32(*seed >> 8u) / 16777216.0;+}++/// A cell's size at a place: the smallest near the eye, doubling every `size.y` metres or so (log2 of the distance),+/// the step to the next size taken at random near the boundary so the sizes blend rather than step.+fn cell_size(at: vec3<f32>, seed: ptr<function, u32>) -> f32 {+ let lod = log2(1.0 + distance(upkeep.eye.xyz, at) / upkeep.size.y);+ let f = fract(lod);+ return upkeep.size.x * exp2(floor(lod) + select(0.0, 1.0, rand(seed) < f * f * f));+}++/// A place and side's key into the cells (where to look first) and its checksum (whether a cell found is this one).+fn key_of(at: vec3<f32>, n: vec3<f32>, size: f32) -> vec2<u32> {+ let p = bitcast<vec3<u32>>(floor(at / size + 0.0001));+ let s = bitcast<vec3<u32>>(floor(n + 0.0001));+ var k = hash(p.x);+ var c = hash2(p.x);+ k = hash(k + p.y);+ c = hash2(c + p.y);+ k = hash(k + p.z);+ c = hash2(c + p.z);+ k = hash(k + s.x);+ c = hash2(c + s.x);+ k = hash(k + s.y);+ c = hash2(c + s.y);+ k = hash(k + s.z);+ c = hash2(c + s.z);+ return vec2(k & (CELLS - 1u), max(c, 1u));+}++/// The light a cell holds at a place and side (rgb) and over how many frames (a: 0 for a cell new this frame, or+/// none to be had), keeping it alive `keep` frames. The place is jittered across the surface by up to half a cell,+/// so the cache reads as a blur rather than a grid. A cell not found is claimed, empty: some update learns it.+fn read(at_in: vec3<f32>, n: vec3<f32>, keep: u32, seed: ptr<function, u32>) -> vec4<f32> {+ var at = at_in;+ var size = cell_size(at, seed);+ let t = normalize(cross(n, select(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), abs(n.x) > 0.9)));+ let bt = cross(n, t);+ at += ((rand(seed) * 2.0 - 1.0) * t + (rand(seed) * 2.0 - 1.0) * bt) * size * 0.5;+ size = cell_size(at, seed);+ let kc = key_of(at, n, size);+ var key = kc.x;+ for (var i = 0u; i < SEARCH; i++) {+ let cas = atomicCompareExchangeWeak(&checksums[key], EMPTY, kc.y);+ if (cas.old_value == kc.y || cas.old_value == EMPTY) {+ atomicMax(&life[key], keep);+ }+ if (cas.old_value == kc.y) {+ return radiance[key];+ }+ if (cas.old_value == EMPTY && cas.exchanged) {+ cells[key] = Cell(vec4(at, 0.0), vec4(n, 0.0));+ return vec4(0.0);+ }+ key = (key + 1u) & (CELLS - 1u);+ }+ return vec4(0.0);+}diff --git a/systems/rt/src/compact.wesl b/systems/rt/src/compact.weslnew file mode 100644index 00000000..23baefdf--- /dev/null+++ b/systems/rt/src/compact.wesl@@ -0,0 +1,71 @@+// raea GI's world cache, its upkeep each frame (cache.rs; docs/realism.feature LT3): every cell ages a frame, one no+// ray has read for LIFE frames empties, and the live ones are listed for the update (cache_update.wesl) to walk. The+// list is a prefix sum over the cells' liveness in two levels: within each block of 1024 cells, then over the blocks'+// totals (CELLS is 1024 blocks of 1024). From vendor/bevy_solari's world_cache_compact.wesl, made raea's.++import raea_sys_rt::cache::{checksums, life, radiance, deltas, a, b, live, count, dispatch, EMPTY};++var<workgroup> w1: array<u32, 1024u>;+var<workgroup> w2: array<u32, 1024u>;++// a cell a frame older; one that reaches 0 empties+@compute @workgroup_size(1024, 1, 1)+fn decay(@builtin(global_invocation_id) id: vec3<u32>) {+ var l = atomicLoad(&life[id.x]);+ if (l > 0u) {+ l -= 1u;+ atomicStore(&life[id.x], l);+ if (l == 0u) {+ atomicStore(&checksums[id.x], EMPTY);+ radiance[id.x] = vec4(0.0);+ deltas[id.x] = 0.0;+ }+ }+}++// An exclusive prefix sum of 1024 values in w1 (Hillis-Steele, ping-ponged through w2), left in w1 for thread t+// to read: ten doublings.+fn scan(t: u32) -> u32 {+ workgroupBarrier();+ for (var stride = 1u; stride < 1024u; stride = stride << 1u) {+ let here = w1[t];+ // (select reads both sides: the index is clamped, the value dropped)+ let back = select(0u, w1[select(0u, t - stride, t >= stride)], t >= stride);+ workgroupBarrier();+ w2[t] = here + back;+ workgroupBarrier();+ w1[t] = w2[t];+ workgroupBarrier();+ }+ return w1[t];+}++// within each block: how many live cells come before this one+@compute @workgroup_size(1024, 1, 1)+fn scan_cells(@builtin(global_invocation_id) id: vec3<u32>, @builtin(local_invocation_index) t: u32) {+ w1[t] = select(0u, u32(atomicLoad(&life[max(id.x, 1u) - 1u]) != 0u), t > 0u);+ a[id.x] = scan(t);+}++// over the blocks: how many live cells come before each block (one workgroup, a thread a block)+@compute @workgroup_size(1024, 1, 1)+fn scan_blocks(@builtin(local_invocation_index) t: u32) {+ let last = max(t * 1024u, 1u) - 1u;+ w1[t] = select(0u, a[last] + u32(atomicLoad(&life[last]) != 0u), t > 0u);+ b[t] = scan(t);+}++// each live cell into its place in the list; the last thread writes the count and the update's dispatch+@compute @workgroup_size(1024, 1, 1)+fn list(@builtin(global_invocation_id) id: vec3<u32>, @builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) t: u32) {+ let at = a[id.x] + b[wg.x];+ let on = atomicLoad(&life[id.x]) != 0u;+ if (on) {+ live[at] = id.x;+ }+ if (t == 1023u && wg.x == 1023u) {+ let n = at + u32(on);+ count = n;+ dispatch = vec3((n + 63u) / 64u, 1u, 1u);+ }+}diff --git a/systems/rt/src/gi.rs b/systems/rt/src/gi.rsindex f981f15b..b2339ad1 100644--- a/systems/rt/src/gi.rs+++ b/systems/rt/src/gi.rs@@ -6,7 +6,9 @@//! 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.+//! The probes' rays read the world cache where they hit (cache.rs, LT3), which runs first each frame.+//! RAEA_GI_STATS=FILE: the timed frames' GPU milliseconds, the cache's passes and the probes' apart (each pass's own+//! timestamps), and the cache's live cells, written there once a second.//! RAEA_GI_SHOW=volume: the probes light the scene through Bevy's irradiance volume (see `install`). Unset, nothing//! changes.@@ -50,6 +52,8 @@ pub fn install(app: &mut App) {if std::env::var("RAEA_GI").as_deref() != Ok("1") {return;}+ bevy::shader::load_shader_library!(app, "cache.wesl");+ bevy::asset::embedded_asset!(app, "compact.wesl");bevy::asset::embedded_asset!(app, "gi.wesl");crate::install(app);let res = grid_res();@@ -71,7 +75,7 @@ pub fn install(app: &mut App) {} 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 })+ app.insert_resource(Grid { center: Vec3::ZERO, eye: 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));let Some(render) = app.get_sub_app_mut(RenderApp) else { return };@@ -83,6 +87,8 @@ pub fn install(app: &mut App) {#[extract_app(bevy::render::RenderApp)]struct Grid {center: Vec3,+ /// the camera, where the cache's cells are smallest+ eye: Vec3,spacing: f32,res: UVec3,voxels: Handle<Image>,@@ -109,6 +115,9 @@ fn follow(if grid.center != center {grid.center = center;}+ if grid.eye != cam.translation() {+ grid.eye = cam.translation();+ }for mut t in &mut volume {if t.translation != center {t.translation = center;@@ -149,6 +158,9 @@ struct Pipeline {id: CachedComputePipelineId,resolve: CachedComputePipelineId,sampler: Sampler,+ /// the world cache's group 1, and its passes+ cache_layout: BindGroupLayoutDescriptor,+ cache: crate::cache::Passes,}fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCache>, device: Res<RenderDevice>) {@@ -169,11 +181,14 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCac),);let shader = assets.load("embedded://raea_sys_rt/gi.wesl");+ let cache_layout = crate::cache::layout();+ let layouts = vec![layout.clone(), cache_layout.clone()];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() })+ cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some(format!("raea_gi_{entry}").into()), layout: layouts.clone(), shader: shader.clone(), entry_point: Some(entry.into()), ..default() })});+ let passes = crate::cache::queue(&cache, &assets, &layouts);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, resolve, sampler });+ commands.insert_resource(Pipeline { layout, id, resolve, sampler, cache_layout, cache: passes });}/// The cache between frames: its means and which probe each slot holds (gi.wesl's `cubes` and `tags`), where the next@@ -181,10 +196,12 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCac#[derive(Resource, Default)]struct State {cubes: Option<(Buffer, Buffer, u32)>,+ cache: Option<crate::cache::Buffers>,frame: u32,key: Option<[u32; 9]>,timer: Option<Timer>,- seen: Vec<f64>,+ /// each timed frame's GPU milliseconds, the cache's and the probes', and the cache's live cells+ seen: Vec<(f64, f64, u32)>,written: Option<std::time::Instant>,}@@ -220,6 +237,8 @@ fn update() {let (Some(grid), Some(scene), Some(p)) = (grid, scene, p) else { return };let (Some(pipeline), Some(resolve)) = (cache.get_compute_pipeline(p.id), cache.get_compute_pipeline(p.resolve)) else { return };+ let Some(passes) = p.cache.0.iter().map(|id| cache.get_compute_pipeline(*id)).collect::<Option<Vec<_>>>() else { return };+ let Ok(passes) = <[&ComputePipeline; 6]>::try_from(passes) 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)) {@@ -253,6 +272,10 @@ fn update(};let mut uniform = UniformBuffer::from(params);uniform.write_buffer(&device, &queue);+ let mut upkeep = UniformBuffer::from(crate::cache::Upkeep::new(grid.eye, state.frame, fresh));+ upkeep.write_buffer(&device, &queue);+ let cells = state.cache.get_or_insert_with(|| crate::cache::buffers(&device));+ let cache_group = crate::cache::bind(&device, &cache.get_bind_group_layout(&p.cache_layout), cells, upkeep.binding().unwrap());if state.timer.is_none() && device.features().contains(WgpuFeatures::TIMESTAMP_QUERY) {state.timer = Some(timer(&device, &queue));}@@ -269,10 +292,13 @@ fn update(enc.clear_buffer(cubes, 0, None);enc.clear_buffer(tags, 0, None);}+ let cells = state.cache.as_ref().unwrap();+ crate::cache::run(&mut enc, &passes, [&group, &cache_group], cells, state.timer.as_ref().filter(|_| timed).map(|t| (&t.set, 0)));{- 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 writes = state.timer.as_ref().filter(|_| timed).map(|t| wgpu::ComputePassTimestampWrites { query_set: &t.set, beginning_of_pass_write_index: Some(2), end_of_pass_write_index: Some(3) });let mut pass = enc.begin_compute_pass(&ComputePassDescriptor { label: Some("raea_gi"), timestamp_writes: writes });pass.set_bind_group(0, &group, &[]);+ pass.set_bind_group(1, &cache_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@@ -280,8 +306,9 @@ fn update(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);- enc.copy_buffer_to_buffer(&t.resolve, 0, &t.read, 0, 16);+ enc.resolve_query_set(&t.set, 0..4, &t.resolve, 0);+ enc.copy_buffer_to_buffer(&t.resolve, 0, &t.read, 0, 32);+ enc.copy_buffer_to_buffer(&cells.all[crate::cache::COUNT], 0, &t.read, 32, 4);}queue.submit([enc.finish()]);if let Some(t) = state.timer.as_mut().filter(|_| timed) {@@ -295,9 +322,10 @@ fn update(fn timer(device: &RenderDevice, queue: &RenderQueue) -> Timer {let d = device.wgpu_device();- let set = d.create_query_set(&wgpu::QuerySetDescriptor { label: Some("raea gi timer"), ty: wgpu::QueryType::Timestamp, count: 2 });- let resolve = d.create_buffer(&wgpu::BufferDescriptor { label: Some("raea gi timer resolve"), size: 16, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });- let read = d.create_buffer(&wgpu::BufferDescriptor { label: Some("raea gi timer read"), size: 16, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });+ // the cache's start and end, the probes' start and end; the read-back also takes the cache's live cells+ let set = d.create_query_set(&wgpu::QuerySetDescriptor { label: Some("raea gi timer"), ty: wgpu::QueryType::Timestamp, count: 4 });+ let resolve = d.create_buffer(&wgpu::BufferDescriptor { label: Some("raea gi timer resolve"), size: 32, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });+ let read = d.create_buffer(&wgpu::BufferDescriptor { label: Some("raea gi timer read"), size: 48, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });Timer { set, resolve, read, period: queue.get_timestamp_period() as f64, pending: None }}@@ -308,15 +336,16 @@ fn collect(state: &mut State) {if !done.load(Ordering::Acquire) {return;}- let ms = {+ let (cache_ms, probes_ms, cells) = {let Ok(view) = t.read.slice(..).get_mapped_range() else { return };- let ts: [u64; 2] = [u64::from_le_bytes(view[0..8].try_into().unwrap()), u64::from_le_bytes(view[8..16].try_into().unwrap())];- ts[1].saturating_sub(ts[0]) as f64 * t.period / 1e6+ let ts = |i: usize| u64::from_le_bytes(view[8 * i..8 * i + 8].try_into().unwrap());+ let ms = |a: usize, b: usize| ts(b).saturating_sub(ts(a)) as f64 * t.period / 1e6;+ (ms(0, 1), ms(2, 3), u32::from_le_bytes(view[32..36].try_into().unwrap()))};t.read.unmap();t.pending = None;- if ms > 0.0 {- state.seen.push(ms);+ if probes_ms > 0.0 {+ state.seen.push((cache_ms, probes_ms, cells));}}@@ -327,22 +356,33 @@ fn report(state: &mut State, budget: u32, total: u32) {return;}state.written = Some(std::time::Instant::now());- 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];+ // each column sorted on its own: the cache's ms, the probes', both, the live cells+ let col = |f: &dyn Fn(&(f64, f64, u32)) -> f64| {+ let mut v: Vec<f64> = state.seen.iter().map(f).collect();+ v.sort_by(f64::total_cmp);+ v+ };+ let (c, pr, all, live) = (col(&|s| s.0), col(&|s| s.1), col(&|s| s.0 + s.1), col(&|s| s.2 as f64));+ let at = |v: &[f64], 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},\"cpu_ms_gather\":{},\"cpu_ms_tlas\":{},\"cpu_ms_blas_batch\":{},\"blas_batches\":{}}}\n",+ "{{\"rays_a_frame\":{},\"probes\":{total},\"probes_a_frame\":{},\"frames\":{},\"gpu_ms_p50\":{:.3},\"gpu_ms_p90\":{:.3},\"gpu_ms_max\":{:.3},\"cache_ms_p50\":{:.3},\"cache_ms_p90\":{:.3},\"probes_ms_p50\":{:.3},\"probes_ms_p90\":{:.3},\"cache_cells_p50\":{},\"cache_cells_max\":{},\"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),+ all.len(),+ at(&all, 0.5),+ at(&all, 0.9),+ at(&all, 1.0),+ at(&c, 0.5),+ at(&c, 0.9),+ at(&pr, 0.5),+ at(&pr, 0.9),+ at(&live, 0.5),+ at(&live, 1.0),cpu(0),cpu(1),cpu(2),diff --git a/systems/rt/src/gi.wesl b/systems/rt/src/gi.weslindex d2574e72..28b571bb 100644--- a/systems/rt/src/gi.wesl+++ b/systems/rt/src/gi.wesl@@ -1,9 +1,12 @@-// raea GI's world radiance cache, its first form (gi.rs; docs/realism.feature LT2): a grid of probes around the-// camera, each refreshed by 64 rays through the scene's TLAS. A ray that misses sees the sky (the camera's-// environment); one that hits sees a flat stand-in surface (albedo 0.5, facing the ray) lit by the sun through one-// shadow ray and by the sky's diffuse light, unshadowed, until hits know their surface (LT3, LT4). Each probe keeps a-// running mean of its ambient cube (the light arriving along +-x, +-y, +-z) and writes it into Bevy's irradiance-// volume, which every standard material samples in place of its environment's diffuse light.+// raea GI's probes (gi.rs; docs/realism.feature LT2, LT3): a grid of probes around the camera, each refreshed by 64+// rays through the scene's TLAS. A ray that misses sees the sky (the camera's environment); one that hits sees a flat+// stand-in surface (albedo 0.5, facing the ray) until hits know their surface (LT4), lit by what the world cache has+// learned there (cache.wesl: the sun and every bounce, the sky shadowed by what's around), or, where its cell is new,+// by the sun through one shadow ray and the sky's diffuse light, unshadowed. Each probe keeps a running mean of its+// ambient cube (the light arriving along +-x, +-y, +-z) and writes it into Bevy's irradiance volume, which every+// standard material samples in place of its environment's diffuse light. `learn` and `blend` are the cache's update.+import raea_sys_rt::cache::{read, rand, hash, radiance, cells, deltas, life, live, count, learned, upkeep, LIFE};+enable wgpu_ray_query;struct Params {@@ -64,11 +67,6 @@ fn grid_ijk(i: u32) -> vec3<u32> {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;- let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;- return (w >> 22u) ^ w;-}fn unit(h: u32) -> f32 {return f32(h >> 8u) / 16777216.0;}@@ -135,6 +133,41 @@ fn sky_irradiance(n: vec3<f32>) -> vec3<f32> {return textureSampleLevel(sky_diffuse, sky_sampler, sky_dir(n), 0.0).rgb * p.sun.w;}+// The light arriving at a stand-in surface (irradiance, lux): what the cache has learned there, or where its cell is+// new, the sun through one shadow ray and the sky's diffuse light, unshadowed (LT2's stand-in).+fn irradiance_at(hit: vec3<f32>, n: vec3<f32>, keep: u32, seed: ptr<function, u32>) -> vec3<f32> {+ let cached = read(hit, n, keep, seed);+ if (cached.a > 0.0) {+ return cached.rgb;+ }+ let ndl = dot(n, p.sun_dir.xyz);+ var e = PI * sky_irradiance(n);+ if (ndl > 0.0 && sees_sun(hit + n * 0.02, p.sun_dir.xyz)) {+ e += p.sun.xyz * ndl;+ }+ return e;+}++// a direction about n, by the cosine (Malley: a point on the disc lifted to the hemisphere)+fn cosine(n: vec3<f32>, seed: ptr<function, u32>) -> vec3<f32> {+ let r = sqrt(rand(seed));+ let a = 2.0 * PI * rand(seed);+ let t = normalize(cross(n, select(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), abs(n.x) > 0.9)));+ let b = cross(n, t);+ return normalize(t * (r * cos(a)) + b * (r * sin(a)) + n * sqrt(max(1.0 - r * r, 0.0)));+}++fn luma(c: vec3<f32>) -> f32 {+ return dot(c, vec3(0.2126, 0.7152, 0.0722));+}++// whether a listed cell learns this frame: about upkeep.run.y of the live cells do, the same ones in `learn` and+// `blend` (the same first draw from the cell's seed)+fn learns(cell: u32, seed: ptr<function, u32>) -> bool {+ *seed = hash(cell ^ upkeep.run.x);+ return rand(seed) < f32(upkeep.run.y) / f32(max(count, 1u));+}+// 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) {@@ -161,13 +194,8 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) ll = sky_radiance(d);} else {let hit = at + d * t;- let n = -d;- let ndl = dot(n, p.sun_dir.xyz);- var sun = vec3(0.0);- if (ndl > 0.0 && sees_sun(hit + n * 0.02, p.sun_dir.xyz)) {- sun = p.sun.xyz * ndl / PI;- }- l = ALBEDO * (sun + sky_irradiance(n));+ var seed = hash(p.run.z * 7919u + round * 104729u + probe * RAYS + li);+ l = ALBEDO / PI * irradiance_at(hit, -d, LIFE, &seed);}light[li] = l;dirs[li] = d;@@ -213,3 +241,60 @@ fn resolve(@builtin(global_invocation_id) id: vec3<u32>) {textureStore(voxels, vec3<u32>(ijk.x, ijk.y + r.y * (face & 1u), ijk.z + r.z * (face / 2u)), vec4(c, 1.0));}}++// The cache's update, a thread a listed cell (an indirect dispatch: compact.wesl's count): the light arriving at the+// cell this frame, from the sun through one shadow ray and one bounce by the cosine, which sees the cell it meets+// (last frame's light there, times the stand-in's albedo) or the sky. Over frames that is every bounce.+@compute @workgroup_size(64, 1, 1)+fn learn(@builtin(global_invocation_id) id: vec3<u32>) {+ if (id.x >= count) {+ return;+ }+ let cell = live[id.x];+ var seed = 0u;+ if (!learns(cell, &seed)) {+ return;+ }+ let c = cells[cell];+ let n = c.n.xyz;+ let o = c.at.xyz + n * 0.02;+ var e = vec3(0.0);+ let ndl = dot(n, p.sun_dir.xyz);+ if (ndl > 0.0 && sees_sun(o, p.sun_dir.xyz)) {+ e = p.sun.xyz * ndl;+ }+ let d = cosine(n, &seed);+ let t = first_hit(o, d);+ if (t < 0.0) {+ // a cosine sample's irradiance: pi times the radiance it sees+ e += PI * sky_radiance(d);+ } else {+ // the cell met lives as long as the one reading it+ e += ALBEDO * irradiance_at(o + d * t, -d, atomicLoad(&life[cell]), &seed);+ }+ learned[id.x] = vec4(e, 1.0);+}++// Each cell that learned this frame takes its new light into its mean: up to upkeep.size.z frames, fewer while its+// light is changing (its luminance step against its light), so a door opening or a sky changing shows within frames.+@compute @workgroup_size(64, 1, 1)+fn blend(@builtin(global_invocation_id) id: vec3<u32>) {+ if (id.x >= count) {+ return;+ }+ let cell = live[id.x];+ var seed = 0u;+ if (!learns(cell, &seed)) {+ return;+ }+ let old = radiance[cell];+ let now = learned[id.x].rgb;+ let delta = deltas[cell];+ let n = min(old.a + 1.0, upkeep.size.z);+ let most = mix(upkeep.size.z, 1.0, pow(saturate(abs(delta) / max(luma(old.rgb), 0.001)), 1.0 / 8.0));+ let reset = upkeep.run.z == 1u;+ let w = select(1.0 / min(n, most), 1.0, reset);+ let mixed = mix(old.rgb, now, w);+ deltas[cell] = select(mix(delta, luma(mixed) - luma(old.rgb), 1.0 / 8.0), 0.0, reset);+ radiance[cell] = vec4(mixed, n);+}diff --git a/systems/rt/src/lib.rs b/systems/rt/src/lib.rsindex ca9611a8..502206f7 100644--- a/systems/rt/src/lib.rs+++ b/systems/rt/src/lib.rs@@ -7,6 +7,8 @@// traced ambient occlusion, the TLAS's first reader; raea GI's world probes (RAEA_GI=1, docs/realism.feature LT2)pub mod gi;+// raea GI's world cache: a hash grid of the light on the surfaces rays hit (LT3)+pub(crate) mod cache;pub mod traced_ao;/// Every traced pass asked for: traced AO (RAEA_TRACED_AO), raea GI's probes (RAEA_GI). Nothing when neither is.