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
LT8: screen probes, a probe every 16 pixels tracing the ray scene, pooled on its own surface, filled in by depth and normal (the first step)
shinyobjectz59bfe93107ed
diff --git a/Cargo.lock b/Cargo.lockindex 2add7c8c..71b78ed5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15985,6 +15985,7 @@ dependencies = ["bevy","raea-sys-compose","raea-sys-rt",+ "wgpu",][[package]]diff --git a/docs/realism.feature b/docs/realism.featureindex 5fab982f..d3a0de51 100644--- a/docs/realism.feature+++ b/docs/realism.feature@@ -471,6 +471,21 @@ Feature: raea Light: raea's own real-time realism renderer, measured against raeAnd indirect diffuse is applied per pixel in place of the irradiance volume, as a correction to the baseline(D9); Berlin within 0.25 stops mean and 0.5 worst tile of its reference in every sky, with no more flickerthan raster+ And so far (11-18, the first step, raea-sys-gi): a probe every 16 pixels on the surface its tile shows traces+ 16 cosine rays a frame through the TLAS with gi.wesl's own functions (a hit is its record lit by the cache, a+ miss the sky), keeps a running mean over up to 24 frames found by where it stood last frame (kept only on the+ same surface), and is pooled with the probes up to two tiles around it on its own plane (probe space); each+ pixel takes the four around it by depth and normal, and reads the cache at its own surface only where none is+ on it. Not yet: the screen trace before the TLAS, a quarter refreshed a frame. LT2's probe grid is traced only+ when shown (RAEA_GI_SHOW=volume): its rays claimed cells all over the volume, so the cache's updates went to+ cells no pixel reads (Berlin's walk 250k live cells to 149k). Filtered, gi path, before (LT4's first tier) and+ after: FLOOR3 mean 2.381 to 0.617 stops, bias -2.118 to -0.547, worst 6.012 to 5.170, flicker 0.415 to 0.131+ (raster 1.392, -0.816, 3.392, 0.111), live 16.1 to 14.4 ms; glade 1.319 to 1.292, bias 1.074 to 1.041 (its+ reference unreliable, LT3). FLOOR3's worst tile is its ceiling: lit only by what the floor sends up, and the+ floor's cells rarely find a lens with one cosine ray (D7, LT6). Flicker is still a fifth above raster's. Live+ at 1080p: Berlin's walk 38.9 ms gi against 39.1 raster, raea GI 1.32 ms of GPU (the cache 0.31, the screen+ probes, their pooling and the pixels 1.01); the kitchen 52.1 ms, 1.91 of it GI (no reference). Berlin's shaded+ fronts are smooth where each pixel's own cell was blotchy (fd442f2b48); posted to ShaneScenario: LT9. Reflections, glass and fogThen SSR runs first and hands what it can't find to traced rays below a roughness of 0.4, hits shaded by D5'sdiff --git a/engine/light/src/lib.rs b/engine/light/src/lib.rsindex 50e10e2c..acfcc0a0 100644--- a/engine/light/src/lib.rs+++ b/engine/light/src/lib.rs@@ -251,7 +251,9 @@ fn table(reports: &[Value]) -> String {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}"));- let gi = v["live"]["full"]["gi"]["gpu_ms_p50"].as_f64().map_or("-".to_string(), |x| format!("{x:.2}"));+ // the cache's passes and the screen's (its probes, their filter, the screen), each a median+ let g = &v["live"]["full"]["gi"];+ let gi = g["gpu_ms_p50"].as_f64().map_or("-".to_string(), |x| format!("{:.2}", x + g["screen_ms_p50"].as_f64().unwrap_or(0.0)));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) {diff --git a/systems/gi/Cargo.toml b/systems/gi/Cargo.tomlindex 29020e3a..6f0b859b 100644--- a/systems/gi/Cargo.toml+++ b/systems/gi/Cargo.toml@@ -10,3 +10,5 @@ description = "raea GI's screen side: each pixel's indirect diffuse light from traea-sys-rt = { path = "../rt" }raea-sys-compose = { path = "../compose" }bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }+# the screen passes' GPU timestamps (as raea-sys-rt times its own)+wgpu = "=30.0.1"diff --git a/systems/gi/src/frame.wesl b/systems/gi/src/frame.weslnew file mode 100644index 00000000..c48b9abb--- /dev/null+++ b/systems/gi/src/frame.wesl@@ -0,0 +1,54 @@+// What raea GI's screen probes (probes.wesl) and its screen pass (screen.wesl) share, group 2 of both (lib.rs): the+// view's surfaces from its prepasses, the screen the main pass reads, the probes (this frame's and last frame's) and+// the frame's parameters.+import bevy_render::view::View;++@group(2) @binding(0) var<uniform> view: View;+@group(2) @binding(1) var depth_tex: texture_depth_2d;+@group(2) @binding(2) var normal_tex: texture_2d<f32>;+@group(2) @binding(3) var out_tex: texture_storage_2d<rgba16float, write>;++// A probe: where it stands (xyz) and how many frames its mean holds (w; 0 where its tile shows only sky), its+// surface's normal, and the light arriving there (irradiance, lux), less the sun on the probe itself (raster draws it).+struct Probe {+ at: vec4<f32>,+ n: vec4<f32>,+ e: vec4<f32>,+}+@group(2) @binding(4) var<storage, read_write> now: array<Probe>;+@group(2) @binding(5) var<storage, read> then: array<Probe>;++struct Params {+ /// toward the sun (xyz)+ sun_dir: vec4<f32>,+ /// the sun's light (rgb, lux), as the cache's cells were lit by it+ sun: vec4<f32>,+ /// the frame's salt; probes across and down; 1 when `then` holds last frame's probes+ run: vec4<u32>,+ /// last frame's clip_from_world, where a probe finds its history+ then_clip: mat4x4<f32>,+}+@group(2) @binding(6) var<uniform> p: Params;+// this frame's probes filtered in probe space (probes.wesl `filter`), which the screen pass reads; `now` keeps each+// probe's own mean, so the filter doesn't feed back into its history+@group(2) @binding(7) var<storage, read_write> soft: array<Probe>;++/// pixels a probe, across and down+const TILE: u32 = 16u;++/// A pixel's surface: where it is (xyz; w 1, or 0 where the pixel shows sky or lies outside the view) and its normal.+struct Surface {+ at: vec4<f32>,+ n: vec3<f32>,+}+fn surface(px: vec2<i32>) -> Surface {+ let uv = (vec2<f32>(px) + 0.5 - view.viewport.xy) / view.viewport.zw;+ let d = textureLoad(depth_tex, px, 0);+ // sky (reverse z: 0 is infinitely far), or outside the view+ if (d <= 0.0 || any(uv < vec2(0.0)) || any(uv > vec2(1.0))) {+ return Surface(vec4(0.0), vec3(0.0, 1.0, 0.0));+ }+ let w = view.world_from_clip * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d, 1.0);+ let n = normalize(textureLoad(normal_tex, px, 0).xyz * 2.0 - 1.0);+ return Surface(vec4(w.xyz / w.w, 1.0), n);+}diff --git a/systems/gi/src/lib.rs b/systems/gi/src/lib.rsindex f2bc00f2..107822ca 100644--- a/systems/gi/src/lib.rs+++ b/systems/gi/src/lib.rs@@ -3,14 +3,17 @@//! RaeaGiScreen, the mesh view group's binding 41, read texel for pixel: no sampler, so a hooked material at Metal's 16//! keeps building, where Bevy's irradiance volume took a 17th).//!-//! Its first form is a measuring step, as LT2's irradiance volume was meant to be: each pixel reads the world cache-//! (raea-sys-rt cache.wesl) at its own surface, from the depth and normal prepasses, and takes out the sun's share,-//! which raster draws with its shadows. What the cache learned from the sky and from a bounce more reaches the screen,-//! so its light can be measured against the reference (LT1). A pixel whose cell is new this frame draws Bevy's own-//! light until the cell has learned. Screen probes come after (LT8): a probe every 16 pixels tracing the screen, then-//! the TLAS, ending in the cache.+//! Screen probes (probes.wesl): one every 16 pixels, on the surface its tile shows, tracing 16 rays a frame through+//! raea-sys-rt's ray scene with gi.wesl's own functions, a hit lit by what the world cache has learned there; each+//! keeps a running mean, its history found where it stood last frame, and is filtered with its neighbours on its own+//! surface (probe space). The screen pass (screen.wesl) fills the pixels between from the four probes around each, by+//! depth and normal; where none is on a pixel's surface (a thing smaller+//! than a tile), it reads the cache at the pixel's own surface less the sun's share (LT3's measuring step), and where+//! that cell is new the main pass draws Bevy's own light. Not yet (LT8): the screen trace before the TLAS, a quarter+//! of the probes refreshed a frame.//!-//! On with RAEA_GI=1, on every 3D camera, which gets its depth and normal prepasses, with MSAA off.+//! On with RAEA_GI=1, on every 3D camera, which gets its depth and normal prepasses, with MSAA off. The screen passes'+//! GPU milliseconds go into RAEA_GI_STATS beside the cache's (raea-sys-rt gi.rs SCREEN_MS), a frame timed at a time.use bevy::{core_pipeline::{@@ -20,20 +23,26 @@ use bevy::{},diagnostic::FrameCount,pbr::RaeaGiScreen,+ platform::collections::HashMap,prelude::*,render::{camera::ExtractedCamera,extract_component::{ExtractComponent, ExtractComponentPlugin},render_resource::{- binding_types::{texture_2d, texture_depth_2d, texture_storage_2d, uniform_buffer, uniform_buffer_sized},+ binding_types::{storage_buffer_read_only_sized, storage_buffer_sized, texture_2d, texture_depth_2d, texture_storage_2d, uniform_buffer, uniform_buffer_sized},*,},renderer::{RenderContext, RenderDevice, ViewQuery},texture::{CachedTexture, TextureCache},- view::{ViewUniform, ViewUniformOffset, ViewUniforms},+ view::{ExtractedView, ViewUniform, ViewUniformOffset, ViewUniforms},Render, RenderApp, RenderStartup, RenderSystems,},};+use std::sync::{+ atomic::{AtomicU8, Ordering},+ Arc,+};+use raea_sys_rt::gi::WorldCache;/// A camera whose pixels take raea GI's light (RAEA_GI=1). Brings the prepasses it reads.@@ -49,11 +58,14 @@ pub fn install(app: &mut App) {if std::env::var("RAEA_GI").as_deref() != Ok("1") {return;}+ bevy::shader::load_shader_library!(app, "frame.wesl");+ bevy::asset::embedded_asset!(app, "probes.wesl");bevy::asset::embedded_asset!(app, "screen.wesl");app.add_plugins(ExtractComponentPlugin::<GiScreen>::default()).add_systems(PostUpdate, cameras);let Some(render) = app.get_sub_app_mut(RenderApp) else { return };render- .add_systems(RenderStartup, init)+ .init_resource::<Kept>()+ .add_systems(RenderStartup, (init, clock)).add_systems(Render, textures.in_set(RenderSystems::PrepareResources)).add_systems(Core3d, draw.after(Core3dSystems::Prepass).before(Core3dSystems::MainPass));}@@ -66,32 +78,76 @@ fn cameras(mut commands: Commands, q: Query<Entity, (With<Camera3d>, Without<GiS}}-/// a view's screen and this frame's parameters+/// pixels a probe, across and down (frame.wesl's TILE); bytes a probe (its Probe: three vec4s)+const TILE: u32 = 16;+const PROBE_BYTES: u64 = 48;++/// a view's screen, its probes (this frame's, last frame's, and this frame's filtered) and this frame's parameters#[derive(Component)]struct GiFrame {screen: CachedTexture,params: Buffer,+ now: Buffer,+ then: Buffer,+ soft: Buffer,+ probes: u32,+}++/// Each view's probes between frames: how many across and down, the two buffers they swap between, which is this+/// frame's, the filtered probes, and the view's clip_from_world last frame.+#[derive(Resource, Default)]+struct Kept(HashMap<Entity, Probes>);+struct Probes {+ tiles: UVec2,+ a: Buffer,+ b: Buffer,+ soft: Buffer,+ flip: bool,+ then_clip: Option<Mat4>,}-/// screen.wesl's Params, three vec4s: toward the sun, the sun's light (lux), the frame's salt-const PARAMS_BYTES: u64 = 48;+fn probes(device: &RenderDevice, tiles: UVec2) -> Probes {+ let buffer = |label| device.create_buffer(&BufferDescriptor { label: Some(label), size: (tiles.x * tiles.y) as u64 * PROBE_BYTES, usage: BufferUsages::STORAGE, mapped_at_creation: false });+ Probes { tiles, a: buffer("raea_gi_probes_a"), b: buffer("raea_gi_probes_b"), soft: buffer("raea_gi_probes_soft"), flip: false, then_clip: None }+}++/// frame.wesl's Params: toward the sun, the sun's light (lux), the run (the frame's salt, probes across and down, 1+/// when last frame's probes are there to take from), and last frame's clip_from_world+const PARAMS_BYTES: u64 = 112;-/// Each view's screen, at its target's size, and the lighting's binding to it. None until the world cache has run (its-/// first frame), so the main pass draws Bevy's own light until then.+/// Each view's screen, at its target's size, its probes and the lighting's binding to the screen. None until the world+/// cache has run (its first frame), so the main pass draws Bevy's own light until then.+#[allow(clippy::too_many_arguments)]fn textures(mut commands: Commands,mut cache: ResMut<TextureCache>,+ mut kept: ResMut<Kept>,device: Res<RenderDevice>,frame: Res<FrameCount>,world: Option<Res<WorldCache>>,- views: Query<(Entity, &ExtractedCamera), With<GiScreen>>,+ clock: Option<Res<Clock>>,+ views: Query<(Entity, &ExtractedCamera, &ExtractedView), With<GiScreen>>,) {+ if let Some(c) = clock {+ c.read();+ }let Some(world) = world else { return };+ kept.0.retain(|e, _| views.contains(*e));let (d, l) = (world.sun_dir, world.sun_light);- let words: [u32; 12] = [d.x.to_bits(), d.y.to_bits(), d.z.to_bits(), 0, l.x.to_bits(), l.y.to_bits(), l.z.to_bits(), 0, frame.0.wrapping_mul(0x9e37_79b9), 0, 0, 0];- let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();- for (e, camera) in &views {+ for (e, camera, view) in &views {let Some(size) = camera.physical_target_size else { continue };+ let tiles = (size + UVec2::splat(TILE - 1)) / TILE;+ let kept = kept.0.entry(e).or_insert_with(|| probes(&device, tiles));+ if kept.tiles != tiles {+ *kept = probes(&device, tiles);+ }+ kept.flip = !kept.flip;+ let (now, then) = if kept.flip { (kept.a.clone(), kept.b.clone()) } else { (kept.b.clone(), kept.a.clone()) };+ let clip = view.clip_from_world.unwrap_or_else(|| view.clip_from_view * Mat4::from(view.world_from_view.affine().inverse()));+ let then_clip = kept.then_clip.replace(clip);+ let mut words = vec![d.x.to_bits(), d.y.to_bits(), d.z.to_bits(), 0, l.x.to_bits(), l.y.to_bits(), l.z.to_bits(), 0, frame.0.wrapping_mul(0x9e37_79b9), tiles.x, tiles.y, then_clip.is_some() as u32];+ words.extend(then_clip.unwrap_or(clip).to_cols_array().map(f32::to_bits));+ let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();let screen = cache.get(&device,TextureDescriptor {@@ -106,14 +162,16 @@ fn textures(},);let params = device.create_buffer_with_data(&BufferInitDescriptor { label: Some("raea_gi_screen_params"), contents: &bytes, usage: BufferUsages::UNIFORM });- commands.entity(e).insert((RaeaGiScreen(screen.default_view.clone()), GiFrame { screen, params }));+ commands.entity(e).insert((RaeaGiScreen(screen.default_view.clone()), GiFrame { screen, params, now, then, soft: kept.soft.clone(), probes: tiles.x * tiles.y }));}}#[derive(Resource)]struct GiPipeline {layout: BindGroupLayoutDescriptor,- id: CachedComputePipelineId,+ probes: CachedComputePipelineId,+ filter: CachedComputePipelineId,+ screen: CachedComputePipelineId,}fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCache>) {@@ -126,42 +184,129 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCactexture_depth_2d(),texture_2d(TextureSampleType::Float { filterable: false }),texture_storage_2d(FORMAT, StorageTextureAccess::WriteOnly),+ storage_buffer_sized(false, None),+ storage_buffer_read_only_sized(false, None),uniform_buffer_sized(false, core::num::NonZero::new(PARAMS_BYTES)),+ storage_buffer_sized(false, None),),),);- // group 1 is the world cache's own (raea-sys-rt cache.rs), bound as raea-sys-rt bound it this frame- let id = cache.queue_compute_pipeline(ComputePipelineDescriptor {- label: Some("raea_gi_screen".into()),- layout: vec![layout.clone(), raea_sys_rt::cache::layout()],- shader: assets.load("embedded://raea_sys_gi/screen.wesl"),- entry_point: Some("main".into()),- ..default()+ // group 0 is gi.wesl's (its TLAS, sky and records), group 1 the world cache's (raea-sys-rt cache.rs), both bound as+ // raea-sys-rt bound them this frame; group 2 is frame.wesl's+ let layouts = vec![raea_sys_rt::gi::layout(), raea_sys_rt::cache::layout(), layout.clone()];+ let [probes, filter, screen] = [("probes", "main"), ("probes", "pool"), ("screen", "main")].map(|(file, entry)| {+ cache.queue_compute_pipeline(ComputePipelineDescriptor {+ label: Some(format!("raea_gi_{file}_{entry}").into()),+ layout: layouts.clone(),+ shader: assets.load(format!("embedded://raea_sys_gi/{file}.wesl")),+ entry_point: Some(entry.into()),+ ..default()+ })});- commands.insert_resource(GiPipeline { layout, id });+ commands.insert_resource(GiPipeline { layout, probes, filter, screen });}-/// Each view's screen from its prepasses and this frame's world cache, before the main pass reads it.+/// Each view's probes, then its screen, from its prepasses and this frame's world cache, before the main pass reads it.fn draw(view: ViewQuery<(&ViewPrepassTextures, &ViewUniformOffset, &GiFrame)>,pipeline: Option<Res<GiPipeline>>,world: Option<Res<WorldCache>>,uniforms: Res<ViewUniforms>,cache: Res<PipelineCache>,+ clock: Option<Res<Clock>>,+ mut told: Local<bool>,mut ctx: RenderContext,) {let (Some(p), Some(world), Some(view_binding)) = (pipeline, world, uniforms.uniforms.binding()) else { return };let (prepass, offset, f) = view.into_inner();- let (Some(rp), Some(depth), Some(normal)) = (cache.get_compute_pipeline(p.id), prepass.depth_only_view(), prepass.normal_view()) else { return };+ // a pipeline that failed to build says so once: otherwise the frame quietly draws Bevy's own light (11-18: a WGSL+ // reserved word in probes.wesl measured as raster)+ if !*told && [p.probes, p.filter, p.screen].iter().any(|id| matches!(cache.get_compute_pipeline_state(*id), CachedPipelineState::Err(_))) {+ *told = true;+ eprintln!("raea gi: effect dropped (gi-pipeline): a raea GI shader failed to build (its error is in the log above); the main pass draws Bevy's own light");+ }+ let (Some(probes), Some(filter), Some(screen)) = (cache.get_compute_pipeline(p.probes), cache.get_compute_pipeline(p.filter), cache.get_compute_pipeline(p.screen)) else { return };+ let (Some(depth), Some(normal)) = (prepass.depth_only_view(), prepass.normal_view()) else { return };let group = ctx.render_device().create_bind_group("raea_gi_screen",&cache.get_bind_group_layout(&p.layout),- &BindGroupEntries::sequential((view_binding, depth, normal, &f.screen.default_view, f.params.as_entire_binding())),+ &BindGroupEntries::sequential((view_binding, depth, normal, &f.screen.default_view, f.now.as_entire_binding(), f.then.as_entire_binding(), f.params.as_entire_binding(), f.soft.as_entire_binding())),);let size = f.screen.texture.size();- let mut pass = ctx.command_encoder().begin_compute_pass(&ComputePassDescriptor { label: Some("raea_gi_screen"), timestamp_writes: None });- pass.set_pipeline(rp);- pass.set_bind_group(0, &group, &[offset.offset]);+ // timed when the last timed frame's times are read+ let timed = clock.filter(|c| c.step.load(Ordering::Acquire) == IDLE);+ let writes = timed.as_ref().map(|c| wgpu::ComputePassTimestampWrites { query_set: &c.set, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) });+ let enc = ctx.command_encoder();+ let mut pass = enc.begin_compute_pass(&ComputePassDescriptor { label: Some("raea_gi_screen"), timestamp_writes: writes });+ pass.set_bind_group(0, &world.rays, &[]);pass.set_bind_group(1, &world.group, &[]);+ pass.set_bind_group(2, &group, &[offset.offset]);+ // four probes a workgroup, then a thread a probe, then a thread a pixel+ pass.set_pipeline(probes);+ pass.dispatch_workgroups(f.probes.div_ceil(4), 1, 1);+ pass.set_pipeline(filter);+ pass.dispatch_workgroups(f.probes.div_ceil(64), 1, 1);+ pass.set_pipeline(screen);pass.dispatch_workgroups(size.width.div_ceil(8), size.height.div_ceil(8), 1);+ drop(pass);+ if let Some(c) = timed {+ enc.resolve_query_set(&c.set, 0..2, &c.resolve, 0);+ enc.copy_buffer_to_buffer(&c.resolve, 0, &c.read, 0, 16);+ c.step.store(COPIED, Ordering::Release);+ }+}++/// The screen passes' timer: a frame's two timestamps, on their way back. `step` goes IDLE (time the next frame),+/// COPIED (its times are in a submitted frame), MAPPING, MAPPED, then IDLE again once read.+#[derive(Resource)]+struct Clock {+ set: wgpu::QuerySet,+ resolve: wgpu::Buffer,+ read: wgpu::Buffer,+ period: f64,+ step: Arc<AtomicU8>,+}+const IDLE: u8 = 0;+const COPIED: u8 = 1;+const MAPPING: u8 = 2;+const MAPPED: u8 = 3;++/// a clock where the GPU has timestamps and RAEA_GI_STATS asks for them+fn clock(mut commands: Commands, device: Res<RenderDevice>, queue: Res<bevy::render::renderer::RenderQueue>) {+ if std::env::var_os("RAEA_GI_STATS").is_none() || !device.features().contains(WgpuFeatures::TIMESTAMP_QUERY) {+ return;+ }+ let d = device.wgpu_device();+ let set = d.create_query_set(&wgpu::QuerySetDescriptor { label: Some("raea gi screen timer"), ty: wgpu::QueryType::Timestamp, count: 2 });+ let resolve = d.create_buffer(&wgpu::BufferDescriptor { label: Some("raea gi screen 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 screen timer read"), size: 16, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });+ commands.insert_resource(Clock { set, resolve, read, period: queue.get_timestamp_period() as f64, step: Arc::new(AtomicU8::new(IDLE)) });+}++impl Clock {+ /// Each frame before the passes: map last frame's copy (it has been submitted since), or take its times once mapped.+ fn read(&self) {+ match self.step.load(Ordering::Acquire) {+ COPIED => {+ self.step.store(MAPPING, Ordering::Release);+ let step = self.step.clone();+ self.read.slice(..).map_async(wgpu::MapMode::Read, move |r| step.store(if r.is_ok() { MAPPED } else { IDLE }, Ordering::Release));+ }+ MAPPED => {+ let ms = {+ let Ok(view) = self.read.slice(..).get_mapped_range() else { return };+ let ts = |i: usize| u64::from_le_bytes(view[8 * i..8 * i + 8].try_into().unwrap());+ ts(1).saturating_sub(ts(0)) as f64 * self.period / 1e6+ };+ self.read.unmap();+ if ms > 0.0+ && let Ok(mut v) = raea_sys_rt::gi::SCREEN_MS.lock()+ {+ v.push(ms);+ }+ self.step.store(IDLE, Ordering::Release);+ }+ _ => {}+ }+ }}diff --git a/systems/gi/src/probes.wesl b/systems/gi/src/probes.weslnew file mode 100644index 00000000..6b6ace83--- /dev/null+++ b/systems/gi/src/probes.wesl@@ -0,0 +1,139 @@+// raea GI's screen probes (lib.rs; docs/realism.feature LT8, D6): one every 16 pixels, on the surface its tile's middle+// pixel shows (or where that is sky, the first of its quarters' middles that isn't). Each traces 16 rays a frame by the+// cosine about its normal through the ray scene, as raea-sys-rt's gi.wesl does: a hit sees its instance's record, lit+// by what the world cache has learned there; a miss sees the sky. The light arriving (irradiance, lux; the sun on the+// probe itself left out, raster draws it) is kept as a running mean over up to HISTORY frames. Its history is the+// probe that stood where it stands last frame (its place through last frame's view), kept only when that one was on+// the same surface. `pool` then takes each probe with its neighbours on its own surface (probe space, D6), and the+// screen pass (screen.wesl) fills the pixels between by depth and normal.+import raea_sys_rt::cache::{hash, LIFE};+import raea_sys_rt::gi::{first_hit, irradiance_at, sky_radiance, cosine, records};+import raea_sys_gi::frame::{surface, view, now, then, soft, p, Probe, Surface, TILE};++enable wgpu_ray_query;++const PI: f32 = 3.14159265;+/// rays a probe a frame; a workgroup holds four probes+const RAYS: u32 = 16u;+const HISTORY: f32 = 24.0;++var<workgroup> light: array<vec3<f32>, 64>;+var<workgroup> spot: array<vec4<f32>, 4>;+var<workgroup> facing: array<vec3<f32>, 4>;++/// where in its tile a probe looks for a surface, in order+const SPOTS = array<vec2<i32>, 5>(vec2(8, 8), vec2(4, 4), vec2(12, 4), vec2(4, 12), vec2(12, 12));++/// how far a probe may move and still be the one it was (m), at a distance from the camera+fn near(dist: f32) -> f32 {+ return 0.05 + 0.03 * dist;+}++@compute @workgroup_size(64, 1, 1)+fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) li: u32) {+ let local = li / RAYS;+ let probe = wg.x * 4u + local;+ let tiles = p.run.yz;+ let inside = probe < tiles.x * tiles.y;+ let tile = vec2<i32>(vec2<u32>(probe % tiles.x, probe / tiles.x) * TILE);+ if (li % RAYS == 0u) {+ var s = Surface(vec4(0.0), vec3(0.0, 1.0, 0.0));+ if (inside) {+ for (var k = 0u; k < 5u; k++) {+ s = surface(tile + SPOTS[k]);+ if (s.at.w > 0.0) {+ break;+ }+ }+ }+ spot[local] = s.at;+ facing[local] = s.n;+ }+ workgroupBarrier();+ let at = spot[local];+ let n = facing[local];+ let dist = length(at.xyz - view.world_position);+ var l = vec3(0.0);+ if (at.w > 0.0) {+ var seed = hash(probe * 7919u + (li % RAYS) * 104729u + p.run.x);+ let o = at.xyz + n * (0.02 + 0.002 * dist);+ let d = cosine(n, &seed);+ let h = first_hit(o, d);+ if (h.t < 0.0) {+ l = sky_radiance(d);+ } else {+ let r = records[h.rec];+ l = r.albedo.rgb / PI * irradiance_at(o + d * h.t, -d, LIFE, &seed) + r.emission.rgb;+ }+ }+ light[li] = l;+ workgroupBarrier();+ if (li % RAYS != 0u || !inside) {+ return;+ }+ if (at.w <= 0.0) {+ now[probe] = Probe(vec4(0.0), vec4(0.0), vec4(0.0));+ return;+ }+ // cosine samples' irradiance: pi times the mean radiance they see+ var e = vec3(0.0);+ for (var k = 0u; k < RAYS; k++) {+ e += light[li + k];+ }+ e *= PI / f32(RAYS);+ var held = 0.0;+ var old = vec3(0.0);+ if (p.run.w == 1u) {+ let c = p.then_clip * vec4(at.xyz, 1.0);+ if (c.w > 0.0) {+ let uv = vec2(c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5);+ let t = vec2<i32>(floor((view.viewport.xy + uv * view.viewport.zw) / f32(TILE)));+ if (all(t >= vec2(0)) && all(t < vec2<i32>(tiles))) {+ let was = then[u32(t.x) + u32(t.y) * tiles.x];+ if (was.at.w > 0.0 && length(was.at.xyz - at.xyz) < near(dist) && dot(was.n.xyz, n) > 0.8) {+ held = was.at.w;+ old = was.e.rgb;+ }+ }+ }+ }+ let k = min(held + 1.0, HISTORY);+ now[probe] = Probe(vec4(at.xyz, k), vec4(n, 0.0), vec4(mix(old, e, 1.0 / k), 0.0));+}++// Each probe with the probes up to two tiles around it that stand on its surface (their planes and normals alike), the+// nearer and the longer held counting more: a probe's 16 rays a frame rarely find a small bright light (FLOOR3's+// ceiling lenses), so alone neighbouring probes disagree and show as tiles.+@compute @workgroup_size(64, 1, 1)+fn pool(@builtin(global_invocation_id) id: vec3<u32>) {+ let tiles = vec2<i32>(p.run.yz);+ if (id.x >= u32(tiles.x * tiles.y)) {+ return;+ }+ let c = now[id.x];+ if (c.at.w <= 0.0) {+ soft[id.x] = c;+ return;+ }+ let t = vec2<i32>(i32(id.x) % tiles.x, i32(id.x) / tiles.x);+ let reach = near(length(c.at.xyz - view.world_position));+ var sum = vec3(0.0);+ var weight = 0.0;+ for (var dy = -2; dy <= 2; dy++) {+ for (var dx = -2; dx <= 2; dx++) {+ let u = t + vec2(dx, dy);+ if (any(u < vec2(0)) || any(u >= tiles)) {+ continue;+ }+ let q = now[u32(u.x + u.y * tiles.x)];+ if (q.at.w <= 0.0) {+ continue;+ }+ let same = pow(max(dot(c.n.xyz, q.n.xyz), 0.0), 8.0) * exp(-abs(dot(c.n.xyz, q.at.xyz - c.at.xyz)) / reach);+ let w = same * exp(-f32(dx * dx + dy * dy) / 4.5) * q.at.w;+ sum += q.e.rgb * w;+ weight += w;+ }+ }+ soft[id.x] = Probe(c.at, c.n, vec4(sum / weight, 0.0));+}diff --git a/systems/gi/src/screen.wesl b/systems/gi/src/screen.weslindex 56760e08..864ec297 100644--- a/systems/gi/src/screen.wesl+++ b/systems/gi/src/screen.wesl@@ -1,24 +1,12 @@-// raea GI's screen pass (lib.rs; docs/realism.feature LT8): each pixel's indirect diffuse light, read from the world-// cache (raea-sys-rt cache.wesl) at the pixel's own surface, with the sun's share taken out (raster draws the sun, its-// shadows with it). Written as the irradiance volume's light is (irradiance over pi), and 1 in alpha where a cell had-// any; 0 where the pixel is sky, outside the view, or its cell is new, so the main pass draws Bevy's own light there.-import bevy_render::view::View;+// raea GI's screen pass (lib.rs; docs/realism.feature LT8): each pixel's indirect diffuse light, from the four screen+// probes around it (probes.wesl, filtered), each weighed by how near the pixel lies to it on the screen, how alike their normals+// are and how near the pixel is to the probe's plane, so light doesn't cross an edge. Where no probe is on the pixel's+// surface (a thing smaller than a probe's tile), the world cache is read at the pixel's own surface with the sun's+// share taken out (raster draws the sun, its shadows with it). Written as the irradiance volume's light is (irradiance+// over pi), and 1 in alpha where there was light to take; 0 where the pixel is sky, outside the view, or its cell is+// new, so the main pass draws Bevy's own light there.import raea_sys_rt::cache::{find, hash, radiance, cells, sunlit, LIFE, NONE};--@group(0) @binding(0) var<uniform> view: View;-@group(0) @binding(1) var depth_tex: texture_depth_2d;-@group(0) @binding(2) var normal_tex: texture_2d<f32>;-@group(0) @binding(3) var out_tex: texture_storage_2d<rgba16float, write>;--struct Params {- /// toward the sun (xyz)- sun_dir: vec4<f32>,- /// the sun's light (rgb, lux), as the cache's cells were lit by it- sun: vec4<f32>,- /// the frame's salt- run: vec4<u32>,-}-@group(0) @binding(4) var<uniform> p: Params;+import raea_sys_gi::frame::{surface, view, soft, out_tex, p, TILE};const PI: f32 = 3.14159265;@@ -29,29 +17,53 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {return;}let px = vec2<i32>(id.xy);- let at_px = vec2<f32>(id.xy) + 0.5;- let uv = (at_px - view.viewport.xy) / view.viewport.zw;- let d = textureLoad(depth_tex, px, 0);- // sky (reverse z: 0 is infinitely far), or outside the view- if (d <= 0.0 || any(uv < vec2(0.0)) || any(uv > vec2(1.0))) {+ let s = surface(px);+ if (s.at.w <= 0.0) {textureStore(out_tex, px, vec4(0.0));return;}- let w = view.world_from_clip * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d, 1.0);- let at = w.xyz / w.w;- let n = normalize(textureLoad(normal_tex, px, 0).xyz * 2.0 - 1.0);+ let at = s.at.xyz;+ let n = s.n;+ let reach = 0.05 + 0.02 * length(at - view.world_position);+ let tiles = vec2<i32>(p.run.yz);+ // where the pixel lies between the middles of the tiles around it+ let g = (vec2<f32>(id.xy) + 0.5) / f32(TILE) - 0.5;+ let i0 = vec2<i32>(floor(g));+ let f = g - floor(g);+ var sum = vec3(0.0);+ var weight = 0.0;+ var best = 0.0;+ for (var k = 0; k < 4; k++) {+ let o = vec2(k & 1, k >> 1);+ let t = clamp(i0 + o, vec2(0), tiles - 1);+ let q = soft[u32(t.x + t.y * tiles.x)];+ if (q.at.w <= 0.0) {+ continue;+ }+ let b = select(1.0 - f.x, f.x, o.x == 1) * select(1.0 - f.y, f.y, o.y == 1);+ let same = pow(max(dot(q.n.xyz, n), 0.0), 8.0) * exp(-abs(dot(q.n.xyz, at - q.at.xyz)) / reach);+ // a little of each probe whatever the distance, so one on another surface can be stood in for by its neighbour+ let w = (b + 0.02) * same;+ sum += q.e.rgb * w;+ weight += w;+ best = max(best, same);+ }+ if (best > 0.1) {+ textureStore(out_tex, px, vec4(sum / weight / PI, 1.0));+ return;+ }var seed = hash(id.x * 1973u + id.y * 9277u + p.run.x);- let k = find(at + n * 0.02, n, LIFE, &seed);- if (k == NONE) {+ let c = find(at + n * 0.02, n, LIFE, &seed);+ if (c == NONE) {textureStore(out_tex, px, vec4(0.0));return;}- let r = radiance[k];+ let r = radiance[c];if (r.a < 1.0) {textureStore(out_tex, px, vec4(0.0));return;}// the sun as the cell saw it: on its own side, the share of its learning the sun was in view- let sun = p.sun.xyz * max(dot(cells[k].n.xyz, p.sun_dir.xyz), 0.0) * sunlit[k];+ let sun = p.sun.xyz * max(dot(cells[c].n.xyz, p.sun_dir.xyz), 0.0) * sunlit[c];textureStore(out_tex, px, vec4(max(r.rgb - sun, vec3(0.0)) / PI, 1.0));}diff --git a/systems/rt/src/gi.rs b/systems/rt/src/gi.rsindex 2fe8607f..8b41ba2e 100644--- a/systems/rt/src/gi.rs+++ b/systems/rt/src/gi.rs@@ -39,6 +39,10 @@ use bevy::{/// rays a probe each round (gi.wesl's RAYS: a workgroup a probe, a ray a thread)const RAYS: u32 = 64;+/// raea-sys-gi's screen passes' GPU milliseconds (the screen probes, their filter and the screen), each timed frame's,+/// reported beside the cache's (`report`)+pub static SCREEN_MS: std::sync::Mutex<Vec<f64>> = std::sync::Mutex::new(Vec::new());+fn env<T: std::str::FromStr>(name: &str, or: T) -> T {std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(or)}@@ -54,7 +58,8 @@ pub fn install(app: &mut App) {}bevy::shader::load_shader_library!(app, "cache.wesl");bevy::asset::embedded_asset!(app, "compact.wesl");- bevy::asset::embedded_asset!(app, "gi.wesl");+ // a library too: raea-sys-gi's screen probes trace with its functions (first_hit, irradiance_at, sky_radiance)+ bevy::shader::load_shader_library!(app, "gi.wesl");crate::install(app);let res = grid_res();let mut voxels = Image::new_fill(@@ -161,10 +166,15 @@ struct Pipeline {/// the world cache's group 1, and its passescache_layout: BindGroupLayoutDescriptor,cache: crate::cache::Passes,+ /// whether the probes light anything (RAEA_GI_SHOW=volume): raea-sys-gi's screen probes stand in for them, so+ /// otherwise they aren't traced+ shown: bool,}-fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCache>, device: Res<RenderDevice>) {- let layout = BindGroupLayoutDescriptor::new(+/// gi.wesl's group 0: the probes' parameters, the TLAS, the sky, the probes' cubes, volume and tags, and the records.+/// Passes outside raea-sys-rt that trace with gi.wesl's functions bind WorldCache::rays here.+pub fn layout() -> BindGroupLayoutDescriptor {+ BindGroupLayoutDescriptor::new("raea_gi_layout",&BindGroupLayoutEntries::sequential(ShaderStages::COMPUTE,@@ -181,7 +191,11 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCacstorage_buffer_read_only_sized(false, None),),),- );+ )+}++fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCache>, device: Res<RenderDevice>) {+ let layout = layout();let shader = assets.load("embedded://raea_sys_rt/gi.wesl");let cache_layout = crate::cache::layout();let layouts = vec![layout.clone(), cache_layout.clone()];@@ -190,7 +204,8 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCac});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, cache_layout, cache: passes });+ let shown = std::env::var("RAEA_GI_SHOW").as_deref() == Ok("volume");+ commands.insert_resource(Pipeline { layout, id, resolve, sampler, cache_layout, cache: passes, shown });}/// The cache between frames: its means and which probe each slot holds (gi.wesl's `cubes` and `tags`), where the next@@ -226,10 +241,12 @@ fn key(g: &Grid) -> [u32; 9] {}/// This frame's world cache for passes outside raea-sys-rt (raea-sys-gi's screen pass, after this frame's update): its-/// group 1 (cache::layout), and the sun its cells were lit by, toward it and its light (lux)+/// group 1 (cache::layout), gi.wesl's group 0 to trace with (`layout`), and the sun its cells were lit by, toward it+/// and its light (lux)#[derive(Resource, Clone)]pub struct WorldCache {pub group: BindGroup,+ pub rays: BindGroup,pub sun_dir: Vec3,pub sun_light: Vec3,}@@ -266,7 +283,7 @@ fn update(state.cubes = Some((buffer("raea gi cubes", 6), buffer("raea gi tags", 1), total));state.key = None;}- collect(&mut state);+ collect(&mut state, p.shown);let k = key(&grid);let fresh = state.key != Some(k);state.key = Some(k);@@ -289,7 +306,6 @@ fn update(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());- commands.insert_resource(WorldCache { group: cache_group.clone(), sun_dir: grid.sun.truncate(), sun_light: grid.sun_light });if state.timer.is_none() && device.features().contains(WgpuFeatures::TIMESTAMP_QUERY) {state.timer = Some(timer(&device, &queue));}@@ -299,6 +315,7 @@ fn update(&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, tags.as_entire_binding(), records.0.as_entire_binding())),);+ commands.insert_resource(WorldCache { group: cache_group.clone(), rays: group.clone(), sun_dir: grid.sun.truncate(), sun_light: grid.sun_light });// 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") });@@ -308,16 +325,20 @@ fn update(}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)));+ // The probes, only where they light something. Unshown, their pass keeps one workgroup of `resolve`: on the Mac the+ // cache's last pass writes its end time only when a timed pass follows it (11-18: without one it read 0).{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);+ if p.shown {+ 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 toopass.set_pipeline(resolve);- pass.dispatch_workgroups(total.div_ceil(64), 1, 1);+ pass.dispatch_workgroups(if p.shown { total.div_ceil(64) } else { 1 }, 1, 1);}if let Some(t) = state.timer.as_ref().filter(|_| timed) {enc.resolve_query_set(&t.set, 0..4, &t.resolve, 0);@@ -344,7 +365,7 @@ fn timer(device: &RenderDevice, queue: &RenderQueue) -> Timer {}/// the last timed frame's GPU milliseconds, once its readback is done-fn collect(state: &mut State) {+fn collect(state: &mut State, shown: bool) {let Some(t) = state.timer.as_mut() else { return };let Some(done) = t.pending.as_ref() else { return };if !done.load(Ordering::Acquire) {@@ -354,11 +375,13 @@ fn collect(state: &mut State) {let Ok(view) = t.read.slice(..).get_mapped_range() else { return };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()))+ // unshown, the cache runs to the end of the marker pass after it (its own end time reads 0 there)+ (if shown { ms(0, 1) } else { ms(0, 3) }, if shown { ms(2, 3) } else { 0.0 }, u32::from_le_bytes(view[32..36].try_into().unwrap()))};t.read.unmap();t.pending = None;- if probes_ms > 0.0 {+ // a frame whose times came back (the probes' pass may be empty: not shown)+ if cache_ms > 0.0 {state.seen.push((cache_ms, probes_ms, cells));}}@@ -378,13 +401,18 @@ fn report(state: &mut State, budget: u32, total: u32) {};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];+ let mut screen = SCREEN_MS.lock().map(|v| v.clone()).unwrap_or_default();+ screen.sort_by(f64::total_cmp);+ let screen_at = |q: f64| if screen.is_empty() { 0.0 } else { at(&screen, q) };// 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},\"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\":{},\"tlas_builds\":{},\"tlas_instances\":{}}}\n",+ "{{\"screen_ms_p50\":{:.3},\"screen_ms_p90\":{:.3},\"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\":{},\"tlas_builds\":{},\"tlas_instances\":{}}}\n",+ screen_at(0.5),+ screen_at(0.9),(budget / RAYS).min(total) * RAYS,(budget / RAYS).min(total),all.len(),