Skip to content

armgit / raea

Public Imported from GitHub
0

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

Ray tracing: see-through materials, uv_transform and a panorama's sun under Solari and the path tracer

shinyobjectzb301c65570e0
diff --git a/Cargo.lock b/Cargo.lock
index f9bb1166..eea02b57 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3602,8 +3602,6 @@ dependencies = [
[[package]]
name = "bevy_solari"
version = "0.20.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6884816ec199c45499cc33bb5a992a89662b87dffb797e54e627dbd2d9bba618"
dependencies = [
"bevy_anti_alias",
"bevy_app",
@@ -3616,6 +3614,7 @@ dependencies = [
"bevy_ecs",
"bevy_image",
"bevy_light",
+ "bevy_material",
"bevy_math",
"bevy_mesh",
"bevy_pbr",
diff --git a/Cargo.toml b/Cargo.toml
index d7c5ed88..58a2e713 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -269,6 +269,10 @@ bevy_seedling = { path = "vendor/bevy_seedling" }
bevy_text = { path = "vendor/bevy_text" }
# bevy_ui 0.20.0 on Taffy 0.15, Blitz's, so one Taffy builds (changes marked "raea:", docs/bevy-upgrade.md)
bevy_ui = { path = "vendor/bevy_ui" }
+# bevy_solari 0.20.0 with alpha-tested and alpha-blended materials traced by their alpha, StandardMaterial's
+# uv_transform, and a panorama's sun sampled as a light rather than found by reflection rays alone (changes marked
+# "raea:", docs/raytracing.feature RT6). Back to upstream once Solari has these.
+bevy_solari = { path = "vendor/bevy_solari" }
# bevy_ui_widgets 0.20.0 on parley 0.12, Blitz's (docs/blitz-bevy.feature B0a)
bevy_ui_widgets = { path = "vendor/bevy_ui_widgets" }
# blitz-paint 0.3.0-beta.4 with angled gradients in tiles laid out around the tile, many-tile gradient layers drawn
diff --git a/engine/render/src/engine/raea_plugins.rs b/engine/render/src/engine/raea_plugins.rs
index 7dc1c110..cabc25c6 100644
--- a/engine/render/src/engine/raea_plugins.rs
+++ b/engine/render/src/engine/raea_plugins.rs
@@ -112,7 +112,7 @@ pub fn scene3d_systems() -> ScheduleConfigs<ScheduleSystem> {
super::scene3d::instance_models,
super::scene3d::model_shadow_markers,
super::scene3d::toon_models,
- ((super::scene3d::sync_meshes, super::scene3d::sync_pictures, super::shader_ext::sync_shaded, raea_sys_sampler::arrays::sync_arrays, raea_sys_sampler::sync_samplers).chain(), super::toon::sync_toon, super::scene3d::sync_camera, super::motion_blur::sync_motion_blur, (super::environment::sync_environment, super::environment::sync_prefiltered).chain(), super::scene3d::sync_lights, super::scene3d::sync_fog_volumes, super::scene3d::sync_fog_dither, super::scene3d::sync_models, super::scene3d::sync_morphs, super::scene3d::sync_attach, super::grid::grid_models, super::scene3d::sync_bones, super::look::sync_frame_look, super::look::sync_looks, super::compose::sync_passes, super::look::sync_flat, super::paint::sync_paint, super::decal::sync_decals, super::text3d::sync_texts).chain(),
+ ((super::scene3d::sync_meshes, super::scene3d::sync_pictures, super::shader_ext::sync_shaded, raea_sys_sampler::arrays::sync_arrays, raea_sys_sampler::sync_samplers).chain(), super::toon::sync_toon, super::scene3d::sync_camera, super::motion_blur::sync_motion_blur, (super::environment::sync_environment, super::environment::sync_prefiltered, super::environment::sync_suns).chain(), super::scene3d::sync_lights, super::scene3d::sync_fog_volumes, super::scene3d::sync_fog_dither, super::scene3d::sync_models, super::scene3d::sync_morphs, super::scene3d::sync_attach, super::grid::grid_models, super::scene3d::sync_bones, super::look::sync_frame_look, super::look::sync_looks, super::compose::sync_passes, super::look::sync_flat, super::paint::sync_paint, super::decal::sync_decals, super::text3d::sync_texts).chain(),
// --clay and --review's clay half: every standard surface grey, after the rows set their colours
super::scene3d::clay::clay_materials,
)
diff --git a/systems/environment/Cargo.toml b/systems/environment/Cargo.toml
index f630f9ca..3d78fb78 100644
--- a/systems/environment/Cargo.toml
+++ b/systems/environment/Cargo.toml
@@ -11,4 +11,4 @@ serde_json = "1"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "hdr"] }
raea-sys-frame = { path = "../frame" }
raea-core-program = { path = "../../core/program" }
-bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "bevy_solari"] }
diff --git a/systems/environment/src/lib.rs b/systems/environment/src/lib.rs
index 10c2ab2e..254e8c46 100644
--- a/systems/environment/src/lib.rs
+++ b/systems/environment/src/lib.rs
@@ -32,6 +32,9 @@ use bevy::render::render_resource::{Extent3d, TextureDimension, TextureViewDescr
mod prefiltered;
use prefiltered::prefiltered;
pub use prefiltered::{sync_prefiltered, Prefiltered};
+/// A panorama's sun, for traced lighting (RT6)
+mod sun;
+pub use sun::{sync_suns, Suns};
/// The camera's panoramas as cubemaps, in env_srcs' order, and each one's bake entity (its filtered light).
#[derive(Component)]
@@ -315,6 +318,7 @@ pub fn environment(world: &mut World, e: Entity, vals: &BTreeMap<String, V>, ins
world.entity_mut(e).insert((
EnvironmentMapLight { diffuse_map: at.diffuse_map.clone(), specular_map: at.specular_map.clone(), intensity: if num(vals, "env_i", 0.0) < -0.5 { 0.0 } else { num(vals, "env_k", 1000.0) }, rotation: rot, ..default() },
EnvMaps(maps.clone(), bakes),
+ Suns(eqs.iter().map(Equirect::sun).collect()),
));
if vals.contains_key("sky_k") {
let k = num(vals, "sky_k", 0.0);
@@ -353,6 +357,9 @@ fn grow(world: &mut World, e: Entity, vals: &BTreeMap<String, V>, inserted: &[Tu
let mut m = world.get_mut::<EnvMaps>(e).ok_or("camera: its environment went")?;
m.0.push(map);
m.1.push(bake);
+ if let Some(mut s) = world.get_mut::<Suns>(e) {
+ s.0.push(q.sun());
+ }
}
Ok(())
}
diff --git a/systems/environment/src/sun.rs b/systems/environment/src/sun.rs
new file mode 100644
index 00000000..fb67db1a
--- /dev/null
+++ b/systems/environment/src/sun.rs
@@ -0,0 +1,158 @@
+//! A panorama's sun (docs/raytracing.feature RT6): a small disk far brighter than the rest of the sky, found when the
+//! panorama is decoded, from its own floats (the cubemap's halves clamp at 65504, and a clear sky's sun is brighter).
+//! Solari samples it as a directional light (bevy_solari's EnvironmentSun, vendored), so a glossy surface gets its
+//! highlight and the ground its shadows under traced lighting; reflection rays alone find a disk that small too rarely
+//! for the denoiser to keep. The raster passes don't read it.
+
+use bevy::prelude::*;
+use bevy::solari::scene::EnvironmentSun;
+use std::f32::consts::PI;
+
+use super::{num, Equirect, FrameRows};
+
+/// Each panorama's sun, in env_srcs' order (None: no sun stands out).
+#[derive(Component)]
+pub struct Suns(pub Vec<Option<EnvironmentSun>>);
+
+/// The brightest pixel must be this many times the panorama's mean radiance to be a sun: a clear sky's sun is
+/// thousands of times it, a lamp in a room or an overcast sky well under.
+const STANDOUT: f32 = 50.0;
+/// A sun's pixels: within this angle of the brightest, and at least this share of its radiance.
+const REACH: f32 = 10.0 * PI / 180.0;
+const SHARE: f32 = 0.05;
+
+fn lum(p: [f32; 3]) -> f32 {
+ 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]
+}
+
+impl Equirect {
+ /// A pixel's world direction (Bevy's: +Y up, -Z ahead; `sample`'s mapping inverted) and its solid angle.
+ fn texel(&self, x: usize, y: usize) -> (Vec3, f32) {
+ let lon = ((x as f32 + 0.5) / self.w as f32 - 0.5) * 2.0 * PI;
+ let theta = (y as f32 + 0.5) / self.h as f32 * PI;
+ let d = Vec3::new(theta.sin() * lon.sin(), theta.cos(), -theta.sin() * lon.cos());
+ (d, (2.0 * PI / self.w as f32) * (PI / self.h as f32) * theta.sin())
+ }
+
+ /// Every pixel within `reach` of `d`, with its direction and solid angle (only the rows that can be).
+ fn near(&self, d: Vec3, reach: f32) -> impl Iterator<Item = ([f32; 3], Vec3, f32)> + '_ {
+ let theta = d.y.clamp(-1.0, 1.0).acos();
+ let row = |t: f32| ((t / PI * self.h as f32) as isize).clamp(0, self.h as isize - 1) as usize;
+ let (top, bottom) = (row(theta - reach - 0.01), row(theta + reach + 0.01));
+ let cos_reach = reach.cos();
+ (top..=bottom).flat_map(move |y| (0..self.w).map(move |x| (x, y))).filter_map(move |(x, y)| {
+ let (t, sa) = self.texel(x, y);
+ (t.dot(d) >= cos_reach).then(|| (self.px[y * self.w + x], t, sa))
+ })
+ }
+
+ /// The panorama's sun, if one stands out: its direction (the light-weighted middle of its pixels), its disk (out to
+ /// its farthest pixel, half a pixel more), the sky's radiance in a ring around it, and the light above that sky it
+ /// adds (what the traced environment map then leaves out of the disk).
+ pub(super) fn sun(&self) -> Option<EnvironmentSun> {
+ let (mut total, mut peak, mut at) = (0.0f32, 0.0f32, (0, 0));
+ for y in 0..self.h {
+ let (_, sa) = self.texel(0, y);
+ for x in 0..self.w {
+ let l = lum(self.px[y * self.w + x]);
+ total += l * sa;
+ if l > peak {
+ (peak, at) = (l, (x, y));
+ }
+ }
+ }
+ let mean = total / (4.0 * PI);
+ if !(peak > STANDOUT * mean) || !peak.is_finite() {
+ return None;
+ }
+ let (brightest, _) = self.texel(at.0, at.1);
+ let floor = SHARE * peak;
+ let mut middle = Vec3::ZERO;
+ for (p, d, sa) in self.near(brightest, REACH) {
+ if lum(p) >= floor {
+ middle += d * lum(p) * sa;
+ }
+ }
+ let direction = middle.try_normalize()?;
+ let half_pixel = PI / self.h as f32 * 0.5;
+ let radius = self
+ .near(direction, REACH)
+ .filter(|(p, _, _)| lum(*p) >= floor)
+ .map(|(_, d, _)| d.dot(direction).clamp(-1.0, 1.0).acos())
+ .fold(0.0f32, f32::max)
+ + half_pixel;
+ // the sky: the ring from one and a half to three radii out
+ let (mut sky, mut ring) = (Vec3::ZERO, 0.0);
+ let (inner, outer) = ((1.5 * radius).cos(), (3.0 * radius + 2.0 * half_pixel).cos());
+ for (p, d, sa) in self.near(direction, 3.0 * radius + 2.0 * half_pixel) {
+ let c = d.dot(direction);
+ if c <= inner && c >= outer {
+ sky += Vec3::from(p) * sa;
+ ring += sa;
+ }
+ }
+ let sky = if ring > 0.0 { sky / ring } else { Vec3::ZERO };
+ let mut illuminance = Vec3::ZERO;
+ for (p, _, sa) in self.near(direction, radius) {
+ illuminance += (Vec3::from(p) - sky).max(Vec3::ZERO) * sa;
+ }
+ Some(EnvironmentSun { direction, angular_size: 2.0 * radius, illuminance, sky })
+ }
+}
+
+/// Each frame's sun: the one of the panorama the camera's row picks, on the camera while its environment is on.
+pub fn sync_suns(mut commands: Commands, frame: Res<FrameRows>, q: Query<(Entity, &Suns, Option<&EnvironmentSun>)>) {
+ for (e, suns, has) in &q {
+ let Some(v) = frame.vals(e) else { continue };
+ let at = num(&v, "env_i", 0.0).round();
+ let want = (at > -0.5).then(|| suns.0.get((at.max(0.0) as usize).min(suns.0.len().saturating_sub(1))).copied().flatten()).flatten();
+ match (want, has) {
+ (Some(s), Some(h)) if s == *h => {}
+ (Some(s), _) => {
+ commands.entity(e).insert(s);
+ }
+ (None, Some(_)) => {
+ commands.entity(e).remove::<EnvironmentSun>();
+ }
+ (None, None) => {}
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A flat sky with one small hot disk straight up and a little to the north.
+ fn sky_with_sun(sun: f32) -> Equirect {
+ let (w, h) = (512, 256);
+ let mut px = vec![[0.5, 0.6, 0.9]; w * h];
+ let toward = Vec3::new(0.0, 0.8, -0.6).normalize();
+ let eq = Equirect { w, h, px: px.clone() };
+ for y in 0..h {
+ for x in 0..w {
+ if eq.texel(x, y).0.dot(toward) > (1.5f32).to_radians().cos() {
+ px[y * w + x] = [sun, sun, sun];
+ }
+ }
+ }
+ Equirect { w, h, px }
+ }
+
+ #[test]
+ fn a_hot_disk_is_the_sun() {
+ let s = sky_with_sun(50_000.0).sun().expect("a sun");
+ assert!(s.direction.dot(Vec3::new(0.0, 0.8, -0.6).normalize()) > 0.9995, "{:?}", s.direction);
+ assert!((s.angular_size - 3.0f32.to_radians()).abs() < 1.5f32.to_radians(), "{}", s.angular_size.to_degrees());
+ assert!((s.sky - Vec3::new(0.5, 0.6, 0.9)).length() < 1e-3, "{:?}", s.sky);
+ // the disk's light above the sky: (50000 - sky) over its solid angle
+ let disk = 2.0 * PI * (1.0 - (1.5f32).to_radians().cos());
+ assert!((s.illuminance.x / ((50_000.0 - 0.5) * disk) - 1.0).abs() < 0.15, "{:?}", s.illuminance);
+ }
+
+ #[test]
+ fn an_even_sky_has_none() {
+ assert!(sky_with_sun(5.0).sun().is_none());
+ }
+}
+
diff --git a/vendor/bevy_solari/Cargo.toml b/vendor/bevy_solari/Cargo.toml
new file mode 100644
index 00000000..54d27ff1
--- /dev/null
+++ b/vendor/bevy_solari/Cargo.toml
@@ -0,0 +1,183 @@
+# raea: bevy_solari 0.20.0 from crates.io, with alpha-tested and alpha-blended materials traced by their alpha,
+# StandardMaterial's uv_transform, and a panorama's sun sampled as a light. Changes are marked "raea:"; see
+# vendor/vendor.toml for what lets it go.
+
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2024"
+name = "bevy_solari"
+version = "0.20.0"
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "Provides raytraced lighting for Bevy Engine"
+homepage = "https://bevy.org"
+readme = "README.md"
+keywords = ["bevy"]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/bevyengine/bevy"
+
+[package.metadata.docs.rs]
+rustdoc-args = [
+ "-Zunstable-options",
+ "--generate-link-to-definition",
+ "--generate-macro-expansion",
+]
+all-features = true
+
+[package.metadata.wgsl-analyzer]
+edition = "2026_pre"
+root = "src"
+
+[package.metadata.wgsl-analyzer.dependencies.bevy_render]
+path = "../bevy_render"
+
+[package.metadata.wgsl-analyzer.dependencies.bevy_pbr]
+path = "../bevy_pbr"
+
+[package.metadata.wgsl-analyzer.dependencies.bevy_core_pipeline]
+path = "../bevy_core_pipeline"
+
+[package.metadata.wgsl-analyzer.dependencies.constants]
+path = "../../constants"
+
+[features]
+dlss = ["bevy_anti_alias/dlss"]
+force_disable_dlss = ["bevy_anti_alias/force_disable_dlss"]
+
+[lib]
+name = "bevy_solari"
+path = "src/lib.rs"
+
+[dependencies.bevy_anti_alias]
+version = "0.20.0"
+
+[dependencies.bevy_app]
+version = "0.20.0"
+
+[dependencies.bevy_asset]
+version = "0.20.0"
+
+[dependencies.bevy_camera]
+version = "0.20.0"
+
+[dependencies.bevy_color]
+version = "0.20.0"
+
+[dependencies.bevy_core_pipeline]
+version = "0.20.0"
+
+[dependencies.bevy_derive]
+version = "0.20.0"
+
+[dependencies.bevy_diagnostic]
+version = "0.20.0"
+
+[dependencies.bevy_ecs]
+version = "0.20.0"
+
+[dependencies.bevy_image]
+version = "0.20.0"
+
+[dependencies.bevy_light]
+version = "0.20.0"
+
+# raea: StandardMaterial's AlphaMode, read into the traced material (scene/binder/assets.rs)
+[dependencies.bevy_material]
+version = "0.20.0"
+
+[dependencies.bevy_math]
+version = "0.20.0"
+
+[dependencies.bevy_mesh]
+version = "0.20.0"
+
+[dependencies.bevy_pbr]
+version = "0.20.0"
+features = ["dfg_lut"]
+
+[dependencies.bevy_platform]
+version = "0.20.0"
+features = ["std"]
+default-features = false
+
+[dependencies.bevy_reflect]
+version = "0.20.0"
+
+[dependencies.bevy_render]
+version = "0.20.0"
+
+[dependencies.bevy_shader]
+version = "0.20.0"
+
+[dependencies.bevy_transform]
+version = "0.20.0"
+
+[dependencies.bevy_utils]
+version = "0.20.0"
+
+[dependencies.bytemuck]
+version = "1"
+
+[dependencies.derive_more]
+version = "2"
+features = ["from"]
+default-features = false
+
+[dependencies.tracing]
+version = "0.1"
+features = ["std"]
+default-features = false
+
+[dependencies.wgpu]
+version = "30"
+default-features = false
+
+[lints.clippy]
+alloc_instead_of_core = "warn"
+allow_attributes = "warn"
+allow_attributes_without_reason = "warn"
+doc_markdown = "warn"
+manual_let_else = "warn"
+match_same_arms = "warn"
+needless_lifetimes = "allow"
+nonstandard_macro_braces = "warn"
+print_stderr = "warn"
+print_stdout = "warn"
+ptr_as_ptr = "warn"
+ptr_cast_constness = "warn"
+redundant_closure_for_method_calls = "warn"
+redundant_else = "warn"
+ref_as_ptr = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "allow"
+too_long_first_doc_paragraph = "allow"
+too_many_arguments = "allow"
+type_complexity = "allow"
+undocumented_unsafe_blocks = "warn"
+unwrap_or_default = "warn"
+
+[lints.rust]
+missing_docs = "warn"
+unsafe_code = "deny"
+unsafe_op_in_unsafe_fn = "warn"
+unused_qualifications = "warn"
+
+[lints.rust.unexpected_cfgs]
+level = "warn"
+priority = 0
+check-cfg = ["cfg(docsrs_dep)"]
diff --git a/vendor/bevy_solari/LICENSE-APACHE b/vendor/bevy_solari/LICENSE-APACHE
new file mode 100644
index 00000000..d9a10c0d
--- /dev/null
+++ b/vendor/bevy_solari/LICENSE-APACHE
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/vendor/bevy_solari/LICENSE-MIT b/vendor/bevy_solari/LICENSE-MIT
new file mode 100644
index 00000000..9cf10627
--- /dev/null
+++ b/vendor/bevy_solari/LICENSE-MIT
@@ -0,0 +1,19 @@
+MIT License
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/vendor/bevy_solari/README.md b/vendor/bevy_solari/README.md
new file mode 100644
index 00000000..089418e6
--- /dev/null
+++ b/vendor/bevy_solari/README.md
@@ -0,0 +1,9 @@
+# Bevy Solari
+
+[![License](https://img.shields.io/badge/license-MIT%2FApache-blue.svg)](https://github.com/bevyengine/bevy#license)
+[![Crates.io](https://img.shields.io/crates/v/bevy_solari.svg)](https://crates.io/crates/bevy_solari)
+[![Downloads](https://img.shields.io/crates/d/bevy_solari.svg)](https://crates.io/crates/bevy_solari)
+[![Docs](https://docs.rs/bevy_solari/badge.svg)](https://docs.rs/bevy_solari/latest/bevy_solari/)
+[![Discord](https://img.shields.io/discord/691052431525675048.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/bevy)
+
+![Logo](../../assets/branding/bevy_solari.svg)
diff --git a/vendor/bevy_solari/src/lib.rs b/vendor/bevy_solari/src/lib.rs
new file mode 100644
index 00000000..0b2e7319
--- /dev/null
+++ b/vendor/bevy_solari/src/lib.rs
@@ -0,0 +1,58 @@
+#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
+
+//! Provides raytraced lighting.
+//!
+//! See [`SolariPlugins`] for more info.
+//!
+//! ![`bevy_solari` logo](https://raw.githubusercontent.com/bevyengine/bevy/refs/heads/main/assets/branding/bevy_solari.svg)
+
+extern crate alloc;
+
+pub mod pathtracer;
+pub mod realtime;
+pub mod scene;
+
+/// The solari prelude.
+///
+/// This includes the most common types in this crate, re-exported for your convenience.
+pub mod prelude {
+ pub use super::SolariPlugins;
+ pub use crate::realtime::SolariLighting;
+ pub use crate::scene::RaytracingMesh3d;
+}
+
+use crate::realtime::SolariLightingPlugin;
+use crate::scene::RaytracingScenePlugin;
+use bevy_app::{PluginGroup, PluginGroupBuilder};
+use bevy_render::settings::WgpuFeatures;
+
+/// An experimental set of plugins for raytraced lighting.
+///
+/// This plugin group provides:
+/// * [`SolariLightingPlugin`] - Raytraced direct and indirect lighting.
+/// * [`RaytracingScenePlugin`] - BLAS building, resource and lighting binding.
+///
+/// There's also:
+/// * [`pathtracer::PathtracingPlugin`] - A non-realtime pathtracer for validation purposes (not added by default).
+///
+/// To get started, add this plugin to your app, and then add `RaytracingMesh3d` and `MeshMaterial3d::<StandardMaterial>` to your entities.
+pub struct SolariPlugins;
+
+impl PluginGroup for SolariPlugins {
+ fn build(self) -> PluginGroupBuilder {
+ PluginGroupBuilder::start::<Self>()
+ .add(RaytracingScenePlugin)
+ .add(SolariLightingPlugin)
+ }
+}
+
+impl SolariPlugins {
+ /// [`WgpuFeatures`] required for these plugins to function.
+ pub fn required_wgpu_features() -> WgpuFeatures {
+ WgpuFeatures::EXPERIMENTAL_RAY_QUERY
+ | WgpuFeatures::BUFFER_BINDING_ARRAY
+ | WgpuFeatures::TEXTURE_BINDING_ARRAY
+ | WgpuFeatures::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
+ | WgpuFeatures::PARTIALLY_BOUND_BINDING_ARRAY
+ }
+}
diff --git a/vendor/bevy_solari/src/pathtracer/extract.rs b/vendor/bevy_solari/src/pathtracer/extract.rs
new file mode 100644
index 00000000..19db4f33
--- /dev/null
+++ b/vendor/bevy_solari/src/pathtracer/extract.rs
@@ -0,0 +1,36 @@
+use super::{prepare::PathtracerAccumulationTexture, Pathtracer};
+use bevy_camera::Camera;
+use bevy_ecs::{
+ change_detection::DetectChanges,
+ system::{Commands, Query},
+ world::Ref,
+};
+use bevy_render::{sync_world::RenderEntity, Extract};
+use bevy_transform::components::GlobalTransform;
+
+pub fn extract_pathtracer(
+ cameras_3d: Extract<
+ Query<(
+ RenderEntity,
+ &Camera,
+ Ref<GlobalTransform>,
+ Option<&Pathtracer>,
+ )>,
+ >,
+ mut commands: Commands,
+) {
+ for (entity, camera, global_transform, pathtracer) in &cameras_3d {
+ let mut entity_commands = commands
+ .get_entity(entity)
+ .expect("Camera entity wasn't synced.");
+ if let Some(pathtracer) = pathtracer
+ && camera.is_active
+ {
+ let mut pathtracer = pathtracer.clone();
+ pathtracer.reset |= global_transform.is_changed();
+ entity_commands.insert(pathtracer);
+ } else {
+ entity_commands.remove::<(Pathtracer, PathtracerAccumulationTexture)>();
+ }
+ }
+}
diff --git a/vendor/bevy_solari/src/pathtracer/mod.rs b/vendor/bevy_solari/src/pathtracer/mod.rs
new file mode 100644
index 00000000..74021359
--- /dev/null
+++ b/vendor/bevy_solari/src/pathtracer/mod.rs
@@ -0,0 +1,72 @@
+mod extract;
+mod node;
+mod prepare;
+
+use crate::{scene::RaytracingSceneBindings, SolariPlugins};
+use bevy_app::{App, Plugin};
+use bevy_asset::embedded_asset;
+use bevy_camera::Hdr;
+use bevy_core_pipeline::{
+ schedule::{Core3d, Core3dSystems},
+ tonemapping::tonemapping,
+};
+use bevy_ecs::{component::Component, reflect::ReflectComponent, schedule::IntoScheduleConfigs};
+use bevy_reflect::{std_traits::ReflectDefault, Reflect};
+use bevy_render::{
+ init_gpu_resource, renderer::RenderDevice, ExtractSchedule, Render, RenderApp, RenderStartup,
+ RenderSystems,
+};
+use extract::extract_pathtracer;
+use node::{init_pathtracer_pipelines, pathtracer};
+use prepare::prepare_pathtracer_accumulation_texture;
+use tracing::warn;
+
+/// Non-realtime pathtracing.
+///
+/// This plugin is meant to generate reference screenshots to compare against,
+/// and is not intended to be used by games.
+pub struct PathtracingPlugin;
+
+impl Plugin for PathtracingPlugin {
+ fn build(&self, app: &mut App) {
+ embedded_asset!(app, "pathtracer.wesl");
+ }
+
+ fn finish(&self, app: &mut App) {
+ let render_app = app.sub_app_mut(RenderApp);
+
+ let render_device = render_app.world().resource::<RenderDevice>();
+ let features = render_device.features();
+ if !features.contains(SolariPlugins::required_wgpu_features()) {
+ warn!(
+ "PathtracingPlugin not loaded. GPU lacks support for required features: {:?}.",
+ SolariPlugins::required_wgpu_features().difference(features)
+ );
+ return;
+ }
+
+ render_app
+ .add_systems(
+ RenderStartup,
+ init_pathtracer_pipelines.after(init_gpu_resource::<RaytracingSceneBindings>),
+ )
+ .add_systems(ExtractSchedule, extract_pathtracer)
+ .add_systems(
+ Render,
+ prepare_pathtracer_accumulation_texture.in_set(RenderSystems::PrepareResources),
+ )
+ .add_systems(
+ Core3d,
+ pathtracer
+ .after(Core3dSystems::MainPass)
+ .before(tonemapping),
+ );
+ }
+}
+
+#[derive(Component, Reflect, Default, Clone)]
+#[reflect(Component, Default, Clone)]
+#[require(Hdr)]
+pub struct Pathtracer {
+ pub reset: bool,
+}
diff --git a/vendor/bevy_solari/src/pathtracer/node.rs b/vendor/bevy_solari/src/pathtracer/node.rs
new file mode 100644
index 00000000..be638b0f
--- /dev/null
+++ b/vendor/bevy_solari/src/pathtracer/node.rs
@@ -0,0 +1,118 @@
+use super::{prepare::PathtracerAccumulationTexture, Pathtracer};
+use crate::scene::RaytracingSceneBindings;
+use bevy_asset::{load_embedded_asset, AssetServer};
+use bevy_ecs::{prelude::*, resource::Resource, system::Commands};
+use bevy_render::{
+ camera::ExtractedCamera,
+ render_resource::{
+ binding_types::{texture_storage_2d, uniform_buffer},
+ BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries,
+ CachedComputePipelineId, ComputePassDescriptor, ComputePipelineDescriptor,
+ ImageSubresourceRange, PipelineCache, ShaderStages, StorageTextureAccess, TextureFormat,
+ },
+ renderer::{RenderContext, RenderDevice, ViewQuery},
+ view::{ViewTarget, ViewUniform, ViewUniformOffset, ViewUniforms},
+};
+use bevy_utils::default;
+
+/// Resource holding the pathtracer pipeline configuration.
+#[derive(Resource)]
+pub struct PathtracerPipelines {
+ bind_group_layout: BindGroupLayoutDescriptor,
+ pipeline: CachedComputePipelineId,
+}
+
+/// Initializes the pathtracer pipelines at render startup.
+pub fn init_pathtracer_pipelines(
+ mut commands: Commands,
+ pipeline_cache: Res<PipelineCache>,
+ scene_bindings: Res<RaytracingSceneBindings>,
+ asset_server: Res<AssetServer>,
+) {
+ let bind_group_layout = BindGroupLayoutDescriptor::new(
+ "pathtracer_bind_group_layout",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ texture_storage_2d(TextureFormat::Rgba32Float, StorageTextureAccess::ReadWrite),
+ texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
+ uniform_buffer::<ViewUniform>(true),
+ ),
+ ),
+ );
+
+ let pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
+ label: Some("pathtracer_pipeline".into()),
+ layout: vec![
+ scene_bindings.bind_group_layout.clone(),
+ bind_group_layout.clone(),
+ ],
+ shader: load_embedded_asset!(asset_server.as_ref(), "pathtracer.wesl"),
+ ..default()
+ });
+
+ commands.insert_resource(PathtracerPipelines {
+ bind_group_layout,
+ pipeline,
+ });
+}
+
+pub fn pathtracer(
+ view: ViewQuery<(
+ &Pathtracer,
+ &PathtracerAccumulationTexture,
+ &ExtractedCamera,
+ &ViewTarget,
+ &ViewUniformOffset,
+ )>,
+ pathtracer_pipelines: Option<Res<PathtracerPipelines>>,
+ pipeline_cache: Res<PipelineCache>,
+ scene_bindings: Res<RaytracingSceneBindings>,
+ view_uniforms: Res<ViewUniforms>,
+ render_device: Res<RenderDevice>,
+ mut ctx: RenderContext,
+) {
+ let (pathtracer_settings, accumulation_texture, camera, view_target, view_uniform_offset) =
+ view.into_inner();
+
+ let Some(pathtracer_pipelines) = pathtracer_pipelines else {
+ return;
+ };
+
+ let (Some(pipeline), Some(scene_bind_group), Some(viewport), Some(view_uniforms_binding)) = (
+ pipeline_cache.get_compute_pipeline(pathtracer_pipelines.pipeline),
+ &scene_bindings.bind_group,
+ camera.physical_viewport_size,
+ view_uniforms.uniforms.binding(),
+ ) else {
+ return;
+ };
+
+ let bind_group = render_device.create_bind_group(
+ "pathtracer_bind_group",
+ &pipeline_cache.get_bind_group_layout(&pathtracer_pipelines.bind_group_layout),
+ &BindGroupEntries::sequential((
+ &accumulation_texture.0.default_view,
+ view_target.get_unsampled_color_attachment().view,
+ view_uniforms_binding,
+ )),
+ );
+
+ let command_encoder = ctx.command_encoder();
+
+ if pathtracer_settings.reset {
+ command_encoder.clear_texture(
+ &accumulation_texture.0.texture,
+ &ImageSubresourceRange::default(),
+ );
+ }
+
+ let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
+ label: Some("pathtracer"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(pipeline);
+ pass.set_bind_group(0, scene_bind_group, &[]);
+ pass.set_bind_group(1, &bind_group, &[view_uniform_offset.offset]);
+ pass.dispatch_workgroups(viewport.x.div_ceil(8), viewport.y.div_ceil(8), 1);
+}
diff --git a/vendor/bevy_solari/src/pathtracer/pathtracer.wesl b/vendor/bevy_solari/src/pathtracer/pathtracer.wesl
new file mode 100644
index 00000000..767dea6c
--- /dev/null
+++ b/vendor/bevy_solari/src/pathtracer/pathtracer.wesl
@@ -0,0 +1,116 @@
+import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
+import bevy_pbr::render::utils::{rand_f, rand_vec2f};
+import bevy_render::view::View;
+import package::scene::brdf::{evaluate_brdf, evaluate_and_sample_brdf, brdf_pdf, F_AB};
+import package::scene::sampling::{sample_random_light, random_emissive_light_pdf, power_heuristic, sample_environment_map_light_and_sun};
+import package::scene::bindings::{trace_ray, resolve_ray_hit_full, RAY_T_MIN, RAY_T_MAX, MIRROR_ROUGHNESS_THRESHOLD, materials, material_ids, material_alpha, coat_albedo, facing_normal, ALPHA_PREMULTIPLIED};
+
+enable wgpu_ray_query;
+
+@group(1) @binding(0) var accumulation_texture: texture_storage_2d<rgba32float, read_write>;
+@group(1) @binding(1) var view_output: texture_storage_2d<rgba16float, write>;
+@group(1) @binding(2) var<uniform> view: View;
+
+@compute @workgroup_size(8, 8, 1)
+fn pathtrace(@builtin(global_invocation_id) global_id: vec3<u32>) {
+ if any(global_id.xy >= vec2u(view.viewport.zw)) {
+ return;
+ }
+
+ let old_color = textureLoad(accumulation_texture, global_id.xy);
+
+ // Setup RNG
+ let pixel_index = global_id.x + global_id.y * u32(view.viewport.z);
+ let frame_index = u32(old_color.a) * 5782582u;
+ var rng = pixel_index + frame_index;
+
+ // Shoot the first ray from the camera
+ let pixel_center = vec2<f32>(global_id.xy) + 0.5;
+ let jitter = rand_vec2f(&rng) - 0.5;
+ let pixel_uv = (pixel_center + jitter) / view.viewport.zw;
+ let pixel_ndc = (pixel_uv * 2.0) - 1.0;
+ let primary_ray_target = view.world_from_clip * vec4(pixel_ndc.x, -pixel_ndc.y, 1.0, 1.0);
+ var ray_origin = view.world_position;
+ var ray_direction = normalize((primary_ray_target.xyz / primary_ray_target.w) - ray_origin);
+ var ray_t_min = 0.0;
+
+ // Path trace
+ var radiance = vec3(0.0);
+ var throughput = vec3(1.0);
+ var p_bounce = 0.0;
+ // raea: whether this ray samples no lights, so sees the environment map's sun itself (a camera ray, one off a mirror)
+ var sees_sun = true;
+ loop {
+ let ray = trace_ray(ray_origin, ray_direction, ray_t_min, RAY_T_MAX, RAY_FLAG_NONE);
+ if ray.kind != RAY_QUERY_INTERSECTION_NONE {
+ var ray_hit = resolve_ray_hit_full(ray);
+ // raea: a premultiplied surface the ray stopped at: shaded in full for its alpha's share of the stops, else as
+ // its clear coat alone, weighted back to the coat's full strength (bindings.wesl alpha_accepts)
+ let hit_material = materials[material_ids[ray.instance_custom_data]];
+ if hit_material.alpha_mode == ALPHA_PREMULTIPLIED {
+ let alpha = material_alpha(hit_material, ray_hit.uv);
+ let coat = coat_albedo(hit_material.reflectance, abs(dot(ray_hit.geometric_world_normal, ray_direction)));
+ if rand_f(&rng) * (alpha + (1.0 - alpha) * coat) >= alpha {
+ ray_hit.material.base_color = vec3(0.0);
+ ray_hit.material.metallic = 0.0;
+ throughput /= coat;
+ }
+ }
+ let wo = -ray_direction;
+ ray_hit.world_normal = facing_normal(ray_hit.world_normal, ray_hit.geometric_world_normal, wo);
+ let NdotV = max(dot(ray_hit.world_normal, wo), 0.0001);
+ let F_ab = F_AB(ray_hit.material.perceptual_roughness, NdotV);
+
+ // Emissive contribution
+ var mis_weight = 1.0;
+ if p_bounce != 0.0 { // Not first bounce
+ let p_light = random_emissive_light_pdf(ray_hit, ray.t, NdotV);
+ mis_weight = power_heuristic(p_bounce, p_light);
+ }
+ if dot(ray_hit.world_normal, wo) > 0.0 {
+ radiance += mis_weight * throughput * ray_hit.material.emissive;
+ }
+
+ // Sample direct lighting, but only if the surface is not mirror-like
+ let is_perfectly_specular = ray_hit.material.roughness <= MIRROR_ROUGHNESS_THRESHOLD && ray_hit.material.metallic > 0.9999;
+ sees_sun = is_perfectly_specular;
+ if !is_perfectly_specular {
+ let direct_lighting = sample_random_light(ray_hit.world_position, ray_hit.world_normal, &rng);
+
+ mis_weight = 1.0;
+ if direct_lighting.brdf_rays_can_hit {
+ let pdf_of_bounce = brdf_pdf(wo, direct_lighting.wi, ray_hit.world_normal, ray_hit.material, F_ab);
+ mis_weight = power_heuristic(1.0 / direct_lighting.inverse_solid_angle_pdf, pdf_of_bounce);
+ }
+
+ let direct_lighting_brdf = evaluate_brdf(wo, direct_lighting.wi, ray_hit.world_normal, ray_hit.material, F_ab);
+ radiance += mis_weight * throughput * direct_lighting.radiance * direct_lighting.inverse_pdf * direct_lighting_brdf;
+ }
+
+ // Sample new ray direction from the material BRDF for next bounce and apply BRDF
+ let next_bounce = evaluate_and_sample_brdf(wo, ray_hit.world_normal, ray_hit.material, F_ab, &rng);
+ if next_bounce.pdf == 0.0 { break; }
+ ray_direction = next_bounce.wi;
+ ray_origin = ray_hit.world_position + (ray_hit.geometric_world_normal * RAY_T_MIN);
+ ray_t_min = RAY_T_MIN;
+ p_bounce = next_bounce.pdf;
+ throughput *= next_bounce.throughput;
+
+ // Russian roulette for early termination
+ let rr = saturate(luminance(throughput));
+ if rand_f(&rng) >= rr { break; }
+ throughput /= rr;
+ } else {
+ radiance += throughput * sample_environment_map_light_and_sun(ray_direction, sees_sun);
+ break;
+ }
+ }
+
+ // Camera exposure
+ radiance *= view.exposure;
+
+ // Accumulation over time via running average
+ let new_color = mix(old_color.rgb, radiance, 1.0 / (old_color.a + 1.0));
+ textureStore(accumulation_texture, global_id.xy, vec4(new_color, old_color.a + 1.0));
+ textureStore(view_output, global_id.xy, vec4(new_color, 1.0));
+}
diff --git a/vendor/bevy_solari/src/pathtracer/prepare.rs b/vendor/bevy_solari/src/pathtracer/prepare.rs
new file mode 100644
index 00000000..ddef9652
--- /dev/null
+++ b/vendor/bevy_solari/src/pathtracer/prepare.rs
@@ -0,0 +1,47 @@
+use super::Pathtracer;
+use bevy_ecs::{
+ component::Component,
+ entity::Entity,
+ query::With,
+ system::{Commands, Query, Res, ResMut},
+};
+use bevy_image::ToExtents;
+use bevy_render::{
+ camera::ExtractedCamera,
+ render_resource::{TextureDescriptor, TextureDimension, TextureFormat, TextureUsages},
+ renderer::RenderDevice,
+ texture::{CachedTexture, TextureCache},
+};
+
+#[derive(Component)]
+pub struct PathtracerAccumulationTexture(pub CachedTexture);
+
+pub fn prepare_pathtracer_accumulation_texture(
+ query: Query<(Entity, &ExtractedCamera), With<Pathtracer>>,
+ mut texture_cache: ResMut<TextureCache>,
+ render_device: Res<RenderDevice>,
+ mut commands: Commands,
+) {
+ for (entity, camera) in &query {
+ let Some(viewport) = camera.physical_viewport_size else {
+ continue;
+ };
+
+ let descriptor = TextureDescriptor {
+ label: Some("pathtracer_accumulation_texture"),
+ size: viewport.to_extents(),
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: TextureDimension::D2,
+ format: TextureFormat::Rgba32Float,
+ usage: TextureUsages::STORAGE_BINDING,
+ view_formats: &[],
+ };
+
+ commands
+ .entity(entity)
+ .insert(PathtracerAccumulationTexture(
+ texture_cache.get(&render_device, descriptor),
+ ));
+ }
+}
diff --git a/vendor/bevy_solari/src/realtime/bindings.wesl b/vendor/bevy_solari/src/realtime/bindings.wesl
new file mode 100644
index 00000000..86e83e8b
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/bindings.wesl
@@ -0,0 +1,113 @@
+import bevy_render::view::View;
+import bevy_pbr::prepass::bindings::PreviousViewUniforms;
+import package::scene::sampling::{LightSample, NULL_LIGHT_ID};
+
+enable wgpu_ray_query;
+
+@group(1) @binding(0) var view_output: texture_storage_2d<rgba16float, read_write>;
+@group(1) @binding(1) var<storage, read_write> light_tile_samples: array<LightSample>;
+@group(1) @binding(2) var<storage, read_write> light_tile_resolved_samples: array<ResolvedLightSamplePacked>;
+@group(1) @binding(3) var gbuffer: texture_2d<u32>;
+@group(1) @binding(4) var depth_buffer: texture_depth_2d;
+@if(MOTION_VECTORS_READ_WRITE)
+@group(1) @binding(5) var motion_vectors: texture_storage_2d<rg16float, read_write>;
+@if(!MOTION_VECTORS_READ_WRITE)
+@group(1) @binding(5) var motion_vectors: texture_2d<f32>;
+@group(1) @binding(6) var<uniform> view: View;
+@group(1) @binding(7) var<uniform> previous_view: PreviousViewUniforms;
+@group(1) @binding(8) var<storage, read_write> world_cache: WorldCache;
+@group(1) @binding(9) var<uniform> constants: SolariLightingSettings;
+
+@if(RESTIR) {
+@group(1) @binding(10) var previous_gbuffer: texture_2d<u32>;
+@group(1) @binding(11) var previous_depth_buffer: texture_depth_2d;
+@group(1) @binding(12) var<storage, read_write> reservoirs_a: array<Reservoir>;
+@group(1) @binding(13) var<storage, read_write> reservoirs_b: array<Reservoir>;
+}
+
+@if(DLSS_RR_GUIDE_BUFFERS) {
+@group(2) @binding(0) var diffuse_albedo: texture_storage_2d<rgba8unorm, write>;
+@group(2) @binding(1) var specular_albedo: texture_storage_2d<rgba8unorm, write>;
+@group(2) @binding(2) var normal_roughness: texture_storage_2d<rgba16float, write>;
+@group(2) @binding(3) var dlss_rr_depth: texture_storage_2d<r32float, write>;
+@group(2) @binding(4) var specular_motion_vectors: texture_storage_2d<rg16float, write>;
+}
+
+fn load_motion_vector(pixel_id: vec2<u32>) -> vec2<f32> {
+ @if(MOTION_VECTORS_READ_WRITE)
+ return textureLoad(motion_vectors, pixel_id).xy;
+ @if(!MOTION_VECTORS_READ_WRITE)
+ return textureLoad(motion_vectors, pixel_id, 0).xy;
+}
+
+/// User-configurable settings from the `SolariLighting` component, plus per-frame
+/// state. Field order and types must match `SolariLightingUniforms` in `prepare.rs`.
+struct SolariLightingSettings {
+ confidence_weight_cap: f32,
+ primary_di_samples: u32,
+ secondary_di_samples: u32,
+ max_bounces: u32,
+ world_cache_max_temporal_samples: f32,
+ world_cache_direct_light_sample_count: u32,
+ world_cache_max_gi_ray_distance: f32,
+ world_cache_cell_updates_soft_target: u32,
+ world_cache_position_base_cell_size: f32,
+ world_cache_position_lod_scale: f32,
+ frame_rng: u32,
+ reset: u32,
+}
+
+/// Don't adjust the size of this struct without also adjusting `prepare::RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE`.
+struct ResolvedLightSamplePacked {
+ world_position_x: f32,
+ world_position_y: f32,
+ world_position_z: f32,
+ world_normal: u32,
+ radiance: u32,
+ inverse_pdf: f32,
+}
+
+/// Don't adjust the size of this struct without also adjusting `prepare::RESERVOIR_STRUCT_SIZE`.
+struct Reservoir {
+ sample_point_world_position: vec3<f32>,
+ unbiased_contribution_weight: f32,
+ radiance: vec3<f32>,
+ confidence_weight: f32,
+ sample_point_world_normal: vec2<f32>,
+ light_sample: LightSample,
+}
+
+fn empty_reservoir() -> Reservoir {
+ return Reservoir(
+ vec3(0.0),
+ 0.0,
+ vec3(0.0),
+ 0.0,
+ vec2(0.0),
+ LightSample(NULL_LIGHT_ID, 0u),
+ );
+}
+
+struct WorldCacheGeometryData {
+ world_position: vec3<f32>,
+ padding_a: u32,
+ world_normal: vec3<f32>,
+ padding_b: u32,
+}
+
+/// Keep in sync with the packed world-cache layout constants in `prepare.rs`.
+struct WorldCache {
+ checksums: array<atomic<u32>, constants::WORLD_CACHE_SIZE>,
+ @if(WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER)
+ life: array<u32, constants::WORLD_CACHE_SIZE>,
+ @if(!WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER)
+ life: array<atomic<u32>, constants::WORLD_CACHE_SIZE>,
+ radiance: array<vec4<f32>, constants::WORLD_CACHE_SIZE>,
+ geometry_data: array<WorldCacheGeometryData, constants::WORLD_CACHE_SIZE>,
+ luminance_deltas: array<f32, constants::WORLD_CACHE_SIZE>,
+ active_cells_new_radiance: array<vec3<f32>, constants::WORLD_CACHE_SIZE>,
+ a: array<u32, constants::WORLD_CACHE_SIZE>,
+ b: array<u32, 1024u>,
+ active_cell_indices: array<u32, constants::WORLD_CACHE_SIZE>,
+ active_cells_count: u32,
+}
diff --git a/vendor/bevy_solari/src/realtime/extract.rs b/vendor/bevy_solari/src/realtime/extract.rs
new file mode 100644
index 00000000..d2c1212d
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/extract.rs
@@ -0,0 +1,27 @@
+use super::{prepare::SolariLightingResources, SolariLighting};
+use bevy_camera::Camera;
+use bevy_ecs::system::{Commands, ResMut};
+use bevy_pbr::deferred::SkipDeferredLighting;
+use bevy_render::{sync_world::RenderEntity, MainWorld};
+
+pub fn extract_solari_lighting(mut main_world: ResMut<MainWorld>, mut commands: Commands) {
+ let mut cameras_3d = main_world.query::<(RenderEntity, &Camera, Option<&mut SolariLighting>)>();
+
+ for (entity, camera, solari_lighting) in cameras_3d.iter_mut(&mut main_world) {
+ let mut entity_commands = commands
+ .get_entity(entity)
+ .expect("Camera entity wasn't synced.");
+ if let Some(mut solari_lighting) = solari_lighting
+ && camera.is_active
+ {
+ entity_commands.insert((solari_lighting.clone(), SkipDeferredLighting));
+ solari_lighting.reset = false;
+ } else {
+ entity_commands.remove::<(
+ SolariLighting,
+ SolariLightingResources,
+ SkipDeferredLighting,
+ )>();
+ }
+ }
+}
diff --git a/vendor/bevy_solari/src/realtime/gbuffer_utils.wesl b/vendor/bevy_solari/src/realtime/gbuffer_utils.wesl
new file mode 100644
index 00000000..b6dceba7
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/gbuffer_utils.wesl
@@ -0,0 +1,56 @@
+import bevy_pbr::deferred::types::unpack_24bit_normal;
+import bevy_pbr::render::rgb9e5::rgb9e5_to_vec3_;
+import bevy_render::utils::octahedral_decode;
+import bevy_render::view::{View, depth_ndc_to_view_z};
+import package::scene::bindings::ResolvedMaterial;
+
+struct ResolvedGPixel {
+ world_position: vec3<f32>,
+ world_normal: vec3<f32>,
+ material: ResolvedMaterial,
+}
+
+fn gpixel_resolve(gpixel: vec4<u32>, depth: f32, pixel_id: vec2<u32>, view_size: vec2<f32>, world_from_clip: mat4x4<f32>) -> ResolvedGPixel {
+ let world_position = reconstruct_world_position(pixel_id, depth, view_size, world_from_clip);
+ let world_normal = octahedral_decode(unpack_24bit_normal(gpixel.a));
+
+ let base_rough = unpack4x8unorm(gpixel.r);
+ let base_color = pow(base_rough.rgb, vec3(2.2));
+ let perceptual_roughness = base_rough.a;
+ let roughness = perceptual_roughness * perceptual_roughness;
+ let props = unpack4x8unorm(gpixel.b);
+ let reflectance = props.r;
+ let metallic = props.g;
+ let emissive = rgb9e5_to_vec3_(gpixel.g);
+ let material = ResolvedMaterial(base_color, emissive, reflectance, perceptual_roughness, roughness, metallic);
+
+ return ResolvedGPixel(world_position, world_normal, material);
+}
+
+fn reconstruct_world_position(pixel_id: vec2<u32>, depth: f32, view_size: vec2<f32>, world_from_clip: mat4x4<f32>) -> vec3<f32> {
+ let uv = (vec2<f32>(pixel_id) + 0.5) / view_size;
+ let xy_ndc = (uv - vec2(0.5)) * vec2(2.0, -2.0);
+ let world_pos = world_from_clip * vec4(xy_ndc, depth, 1.0);
+ return world_pos.xyz / world_pos.w;
+}
+
+/// Reject if tangent plane differs more than 0.3% or angle between normals more than 90 degrees
+fn pixel_dissimilar(depth: f32, world_position: vec3<f32>, other_world_position: vec3<f32>, normal: vec3<f32>, other_normal: vec3<f32>, view: View) -> bool {
+ // https://developer.download.nvidia.com/video/gputechconf/gtc/2020/presentations/s22699-fast-denoising-with-self-stabilizing-recurrent-blurs.pdf#page=45
+ let tangent_plane_distance = abs(dot(normal, other_world_position - world_position));
+ let view_z = -depth_ndc_to_view_z(depth, view.clip_from_view, view.view_from_clip);
+
+ return tangent_plane_distance / view_z > 0.003 || dot(normal, other_normal) < 0.0;
+}
+
+fn permute_pixel(pixel_id: vec2<u32>, frame_index: u32, view_size: vec2<f32>) -> vec2<u32> {
+ let r = frame_index;
+ let offset = vec2<i32>(i32(r & 3u), i32((r >> 2u) & 3u));
+ var shifted_pixel_id = vec2<i32>(pixel_id) + offset;
+ shifted_pixel_id ^= vec2<i32>(3);
+ shifted_pixel_id -= offset;
+ if any(shifted_pixel_id < vec2<i32>(0)) || any(shifted_pixel_id >= vec2<i32>(view_size)) {
+ return pixel_id;
+ }
+ return vec2<u32>(shifted_pixel_id);
+}
diff --git a/vendor/bevy_solari/src/realtime/initial_path.wesl b/vendor/bevy_solari/src/realtime/initial_path.wesl
new file mode 100644
index 00000000..ba0efb13
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/initial_path.wesl
@@ -0,0 +1,493 @@
+import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
+import bevy_pbr::render::utils::{rand_f, rand_range_u};
+import bevy_render::maths::PI;
+import bevy_render::utils::octahedral_encode;
+import package::scene::brdf::{brdf_pdf, evaluate_and_sample_brdf, evaluate_brdf, EvaluateAndSampleBrdfResult, F_AB};
+import package::realtime::presample_light_tiles::unpack_resolved_light_sample;
+import package::realtime::bindings::{empty_reservoir, light_tile_resolved_samples, light_tile_samples, Reservoir, constants, view};
+import package::scene::sampling::{calculate_resolved_light_contribution, isinf, LightSample, NULL_LIGHT_ID, power_heuristic, trace_visibility, sample_environment_map_light_and_sun};
+import package::scene::bindings::{light_sources, RAY_T_MAX, RAY_T_MIN, resolve_ray_hit_full, ResolvedMaterial, ResolvedRayHitFull, trace_ray};
+import package::realtime::world_cache_query::{get_cell_size, query_world_cache, WORLD_CACHE_CELL_LIFETIME};
+
+@if(DLSS_RR_GUIDE_BUFFERS)
+import package::realtime::resolve_dlss_rr_textures::{is_delta_mirror, primary_surface_glossy, psr_bounce_reflectance, psr_chain_mirror, psr_environment_miss, psr_init, replace_primary_surface};
+
+enable wgpu_ray_query;
+
+const RECONNECTION_FOOTPRINT_KAPPA = 0.02;
+const RECONNECTION_ROUGHNESS_MIN = 0.6;
+const RECONNECTION_RELAX_DISTANCE = 1.0;
+
+const CACHE_TERMINATION_MIN_SOLID_ANGLE = PI;
+
+/// What tracing one path produced.
+///
+/// `radiance` is shaded straight into the pixel. With ReSTIR the reservoir additionally carries the
+/// candidate chosen for reuse, and `radiance` holds the radiance that can not be reused.
+/// Without ReSTIR there is no reservoir and `radiance` is the entire estimate.
+struct InitialSamplingResult {
+ @if(RESTIR) reservoir: Reservoir,
+ radiance: vec3<f32>,
+}
+
+/// Path vertices use the following convention: x0 = camera, x1 = primary ray hit (the G-buffer
+/// surface), x2 = first BRDF-sampled hit (the reconnection vertex).
+struct PathState {
+ ray_origin: vec3<f32>,
+ normal: vec3<f32>,
+ wo: vec3<f32>,
+ material: ResolvedMaterial,
+ /// Throughput past x1. With ReSTIR the brdf*cos at x1 is factored out of it, see x1_brdf.
+ throughput_past_first_hit: vec3<f32>,
+ /// Reconnection vertex x2, the first BRDF-sampled hit shared by every length >= 2 candidate
+ @if(RESTIR) x2_position: vec3<f32>,
+ @if(RESTIR) x2_normal: vec3<f32>,
+ /// If false, candidates built on x2 are shaded directly into radiance instead of
+ /// published to the reservoir
+ @if(RESTIR) x2_reusable: bool,
+ /// brdf*cos at x1 for the direction toward x2, applied at shade time
+ @if(RESTIR) x1_brdf: vec3<f32>,
+ /// Radiance shaded directly at this pixel
+ radiance: vec3<f32>,
+ @if(RESTIR) reservoir: Reservoir,
+ @if(RESTIR) weight_sum: f32,
+ @if(RESTIR) selected_target_function: f32,
+}
+
+fn new_path_state(world_position: vec3<f32>, world_normal: vec3<f32>, wo: vec3<f32>, material: ResolvedMaterial) -> PathState {
+ var path: PathState;
+ path.ray_origin = world_position + (world_normal * RAY_T_MIN);
+ path.normal = world_normal;
+ path.wo = wo;
+ path.material = material;
+ path.throughput_past_first_hit = vec3(1.0);
+ path.radiance = vec3(0.0);
+ @if(RESTIR) {
+ path.x1_brdf = vec3(0.0);
+ path.x2_position = vec3(0.0);
+ path.x2_normal = vec3(0.0);
+ path.x2_reusable = false;
+ path.reservoir = empty_reservoir();
+ path.reservoir.confidence_weight = 1.0;
+ path.weight_sum = 0.0;
+ path.selected_target_function = 0.0;
+ }
+ return path;
+}
+
+fn generate_initial_path(world_position: vec3<f32>, world_normal: vec3<f32>, material: ResolvedMaterial, workgroup_id: vec2<u32>, pixel_id: vec2<u32>, rng: ptr<function, u32>) -> InitialSamplingResult {
+ let wo = normalize(view.world_position - world_position);
+ let primary_NdotV = max(dot(world_normal, wo), 0.0001);
+ let primary_F_ab = F_AB(material.perceptual_roughness, primary_NdotV);
+
+ var path = new_path_state(world_position, world_normal, wo, material);
+
+ @if(DLSS_RR_GUIDE_BUFFERS)
+ var psr = psr_init(world_normal, material);
+
+ for (var bounce = 0u; bounce < constants.max_bounces; bounce++) {
+ let NdotV = max(dot(path.normal, path.wo), 0.0001);
+ let F_ab = F_AB(path.material.perceptual_roughness, NdotV);
+
+ // Stochastic NEE, with probability proportional to how diffuse the vertex is. Mirror-like
+ // metals have too narrow a lobe for NEE to help, so mostly skip it there and let
+ // BRDF-sampled emissive do the work. Pure dielectrics always run NEE.
+ let p_nee = mix(1.0, path.material.perceptual_roughness, path.material.metallic);
+ let di_samples = select(constants.secondary_di_samples, constants.primary_di_samples, bounce == 0u);
+ generate_nee_candidate(&path, F_ab, p_nee, di_samples, workgroup_id, bounce, rng);
+
+ // Sample the BRDF and trace the next ray
+ let next_bounce = evaluate_and_sample_brdf(path.wo, path.normal, path.material, F_ab, rng);
+ if next_bounce.pdf == 0.0 { break; }
+ let ray = trace_ray(path.ray_origin, next_bounce.wi, RAY_T_MIN, RAY_T_MAX, RAY_FLAG_NONE);
+
+ if ray.kind == RAY_QUERY_INTERSECTION_NONE {
+ @if(DLSS_RR_GUIDE_BUFFERS)
+ if !psr.finished && !next_bounce.diffuse_selected {
+ psr_environment_miss(pixel_id, wo);
+ }
+
+ // raea: the sun only where this vertex never samples lights (a mirror); elsewhere light sampling finds it
+ let environment_map_light_radiance = sample_environment_map_light_and_sun(next_bounce.wi, p_nee <= 0.0);
+ @if(RESTIR) {
+ generate_environment_map_light_candidate(&path, next_bounce, environment_map_light_radiance, primary_F_ab, bounce, rng);
+ } @else {
+ path.radiance += path.throughput_past_first_hit * next_bounce.throughput * environment_map_light_radiance;
+ }
+
+ break;
+ }
+
+ let ray_hit = resolve_ray_hit_full(ray);
+ let p_brdf = next_bounce.pdf;
+
+ @if(DLSS_RR_GUIDE_BUFFERS)
+ if !psr.finished {
+ if next_bounce.diffuse_selected {
+ // Took the non-specular lobe, so not a mirror reflection. Keep the guide-buffer defaults.
+ psr.finished = true;
+ } else {
+ psr.throughput *= psr_bounce_reflectance(path.wo, next_bounce.wi, path.normal, path.material, F_ab, isinf(p_brdf));
+ psr.reflection_length += ray.t;
+
+ if !primary_surface_glossy(material) && is_delta_mirror(ray_hit.material) {
+ // Still in the mirror chain, fold this mirror's reflection into the chain.
+ psr = psr_chain_mirror(psr, ray_hit.world_normal);
+ } else {
+ psr.finished = true;
+ replace_primary_surface(pixel_id, psr, ray_hit, material, world_position, world_normal, wo, primary_F_ab);
+ }
+ }
+ }
+
+ // Capture x2, the first BRDF-sampled hit
+ if bounce == 0u {
+ @if(RESTIR) {
+ path.x2_position = ray_hit.world_position;
+ path.x2_normal = ray_hit.world_normal;
+
+ path.x1_brdf = evaluate_brdf(wo, next_bounce.wi, world_normal, material, primary_F_ab);
+
+ path.x2_reusable = reconnection_reusable(ray.t, p_brdf, next_bounce.wi, next_bounce.diffuse_selected, ray_hit, world_position, material.perceptual_roughness, primary_NdotV);
+
+ // The primary brdf*cos is applied at shade time, so divide it out of next_bounce.throughput
+ // to leave 1/pdf (or 1/specular_weight for mirrors, avoiding the 1/INF = 0 that would kill
+ // mirror GI).
+ path.throughput_past_first_hit *= next_bounce.throughput / max(path.x1_brdf, vec3(0.0001));
+ } @else {
+ // Nothing is reused, so there is no shade-time reconnection to factor the primary
+ // brdf*cos out for.
+ path.throughput_past_first_hit *= next_bounce.throughput;
+ }
+ } else {
+ // Later bounces keep the full brdf*cos/pdf for L_at_reconnection.
+ path.throughput_past_first_hit *= next_bounce.throughput;
+ }
+
+ // Resample emissive hits
+ if any(ray_hit.material.emissive > vec3(0.0)) && dot(ray_hit.world_normal, -next_bounce.wi) > 0.0 {
+ generate_emissive_candidate(&path, ray_hit, next_bounce.wi, p_brdf, ray.t, p_nee, di_samples, bounce, rng);
+ }
+
+ // Try terminating into the world cache
+ if terminate_into_cache(&path, ray_hit, ray.t, p_brdf, bounce, rng) {
+ break;
+ }
+
+ // Advance to the next vertex
+ path.ray_origin = ray_hit.world_position + (ray_hit.geometric_world_normal * RAY_T_MIN);
+ path.normal = ray_hit.world_normal;
+ path.wo = -next_bounce.wi;
+ path.material = ray_hit.material;
+
+ // Russian roulette for early termination
+ if bounce > 0u {
+ // With ReSTIR, throughput_past_first_hit has the primary brdf*cos divided out (so it can be
+ // re-applied at shade time), which inflates it. Multiply x1_brdf back in to get the true
+ // energy-bounded path throughput, which is the correct quantity for the RR survival
+ // probability. Without ReSTIR it already is that quantity.
+ var full_throughput = path.throughput_past_first_hit;
+ @if(RESTIR)
+ full_throughput *= max(path.x1_brdf, vec3(0.0001));
+ let rr = saturate(luminance(full_throughput));
+ if rand_f(rng) >= rr { break; }
+ path.throughput_past_first_hit /= rr;
+ }
+ }
+
+ var result: InitialSamplingResult;
+ result.radiance = path.radiance;
+ @if(RESTIR) {
+ if path.selected_target_function > 0.0 {
+ path.reservoir.unbiased_contribution_weight = path.weight_sum / path.selected_target_function;
+ }
+ result.reservoir = path.reservoir;
+ }
+ return result;
+}
+
+fn generate_nee_candidate(
+ path: ptr<function, PathState>,
+ F_ab: vec2<f32>,
+ p_nee: f32,
+ di_samples: u32,
+ workgroup_id: vec2<u32>,
+ bounce: u32,
+ rng: ptr<function, u32>,
+) {
+ if rand_f(rng) >= p_nee { return; }
+
+ let di = sample_light_ris((*path).ray_origin, (*path).normal, (*path).wo, (*path).material, F_ab, di_samples, workgroup_id, bounce, rng);
+ let di_target_function = luminance(di.brdf_radiance);
+ if di_target_function <= 0.0 { return; }
+
+ // MIS against the BRDF strategy. RIS over N candidates makes the effective NEE pdf at the
+ // winner roughly N * light_pdf(winner), so scale by p_nee for the stochastic gate.
+ var nee_mis_weight = 1.0;
+ if di.brdf_rays_can_hit && di.inverse_solid_angle_pdf > 0.0 {
+ let p_nee_strategy = f32(di_samples) * (1.0 / di.inverse_solid_angle_pdf) * p_nee;
+ let p_brdf_at_nee = brdf_pdf((*path).wo, di.wi, (*path).normal, (*path).material, F_ab);
+ nee_mis_weight = power_heuristic(p_nee_strategy, p_brdf_at_nee);
+ }
+
+ if bounce == 0u {
+ @if(RESTIR) {
+ // Bounce 0: Candidate is the light sample, stored by reference and re-resolved each frame
+ // nee_mis_weight goes into the target function since it gets recomputed per-pixel during reuse
+ let target_function = di_target_function * nee_mis_weight;
+ let resampling_weight = target_function * di.unbiased_contribution_weight / p_nee;
+
+ (*path).weight_sum += resampling_weight;
+ if rand_f(rng) * (*path).weight_sum < resampling_weight {
+ (*path).reservoir.light_sample = di.light_sample;
+ (*path).selected_target_function = target_function;
+ }
+ } @else {
+ (*path).radiance += di.brdf_radiance * di.unbiased_contribution_weight * nee_mis_weight / p_nee;
+ }
+ } else {
+ // Deeper bounces: Candidate is the reconnection radiance at x2
+ let L_at_reconnection = (*path).throughput_past_first_hit * di.brdf_radiance * di.unbiased_contribution_weight * nee_mis_weight / p_nee;
+
+ @if(RESTIR) {
+ resample_reconnection_candidate(path, L_at_reconnection, rng);
+ } @else {
+ (*path).radiance += L_at_reconnection;
+ }
+ }
+}
+
+struct DiSample {
+ unbiased_contribution_weight: f32,
+ light_sample: LightSample,
+ wi: vec3<f32>,
+ brdf_radiance: vec3<f32>,
+ inverse_solid_angle_pdf: f32,
+ brdf_rays_can_hit: bool,
+}
+
+fn sample_light_ris(ray_origin: vec3<f32>, normal: vec3<f32>, wo: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>, di_samples: u32, workgroup_id: vec2<u32>, bounce: u32, rng: ptr<function, u32>) -> DiSample {
+ var workgroup_rng = (workgroup_id.x * 5782582u) + workgroup_id.y + bounce;
+ let light_tile_start = rand_range_u(128u, &workgroup_rng) * 1024u;
+
+ var weight_sum = 0.0;
+ var selected_target_function = 0.0;
+ var selected_tile_sample = 0u;
+ var selected_world_position = vec4(0.0);
+ var selected_wi = vec3(0.0);
+ var selected_brdf_radiance = vec3(0.0);
+ var selected_inverse_solid_angle_pdf = 0.0;
+ var selected_brdf_rays_can_hit = false;
+ let mis_weight = 1.0 / f32(di_samples);
+ for (var i = 0u; i < di_samples; i++) {
+ let tile_sample = light_tile_start + rand_range_u(1024u, rng);
+ let resolved_light_sample = unpack_resolved_light_sample(light_tile_resolved_samples[tile_sample], view.exposure);
+ let light_contribution = calculate_resolved_light_contribution(resolved_light_sample, ray_origin, normal);
+ let brdf_current = evaluate_brdf(wo, light_contribution.wi, normal, material, F_ab);
+ let brdf_radiance = brdf_current * light_contribution.radiance;
+
+ let target_function = luminance(brdf_radiance);
+ let resampling_weight = mis_weight * (target_function * light_contribution.inverse_pdf);
+
+ weight_sum += resampling_weight;
+
+ if rand_f(rng) * weight_sum < resampling_weight {
+ selected_target_function = target_function;
+ selected_tile_sample = tile_sample;
+ selected_world_position = resolved_light_sample.world_position;
+ selected_wi = light_contribution.wi;
+ selected_inverse_solid_angle_pdf = light_contribution.inverse_solid_angle_pdf;
+ selected_brdf_rays_can_hit = light_contribution.brdf_rays_can_hit;
+ selected_brdf_radiance = brdf_radiance;
+ }
+ }
+
+ var unbiased_contribution_weight = 0.0;
+ if selected_target_function > 0.0 {
+ unbiased_contribution_weight = weight_sum / selected_target_function;
+ unbiased_contribution_weight *= trace_visibility(ray_origin, selected_world_position);
+ }
+
+ return DiSample(unbiased_contribution_weight, light_tile_samples[selected_tile_sample], selected_wi, selected_brdf_radiance, selected_inverse_solid_angle_pdf, selected_brdf_rays_can_hit);
+}
+
+fn generate_emissive_candidate(
+ path: ptr<function, PathState>,
+ ray_hit: ResolvedRayHitFull,
+ wi: vec3<f32>,
+ p_brdf: f32,
+ ray_t: f32,
+ p_nee: f32,
+ di_samples: u32,
+ bounce: u32,
+ rng: ptr<function, u32>,
+) {
+ let NdotV_hit = max(dot(ray_hit.world_normal, -wi), 0.0001);
+ let light_count = arrayLength(&light_sources);
+ let area_pdf = 1.0 / (f32(light_count) * f32(ray_hit.triangle_count) * ray_hit.triangle_area);
+ let p_light = area_pdf * ray_t * ray_t / NdotV_hit;
+ let emissive_mis_weight = power_heuristic(p_brdf, p_light * p_nee * f32(di_samples));
+
+ @if(RESTIR) {
+ if !(*path).x2_reusable {
+ // x1 -> x2 not reuse-safe (mirror/sharp lobe or failed gate): shade directly at this pixel
+ // instead of publishing, since a reuse shift would waste it or make a firefly. Mirror lobes
+ // always land here (p_brdf = INF, footprint 0), where emissive_mis_weight is 1.
+ (*path).radiance += (*path).x1_brdf * (*path).throughput_past_first_hit * ray_hit.material.emissive * emissive_mis_weight;
+ } else if bounce == 0u {
+ // Bounce 0: Candidate is the emissive hit
+ let target_function = luminance((*path).x1_brdf * ray_hit.material.emissive) * emissive_mis_weight;
+ let resampling_weight = luminance((*path).x1_brdf * (*path).throughput_past_first_hit * ray_hit.material.emissive) * emissive_mis_weight;
+
+ (*path).weight_sum += resampling_weight;
+ if rand_f(rng) * (*path).weight_sum < resampling_weight {
+ (*path).reservoir.light_sample = LightSample(NULL_LIGHT_ID, bitcast<u32>(area_pdf));
+ (*path).reservoir.sample_point_world_position = (*path).x2_position;
+ (*path).reservoir.sample_point_world_normal = octahedral_encode((*path).x2_normal);
+ (*path).reservoir.radiance = ray_hit.material.emissive;
+ (*path).selected_target_function = target_function;
+ }
+ } else {
+ // Deeper bounces: Candidate is the reconnection radiance at x2
+ let emissive_L_at_reconnection = (*path).throughput_past_first_hit * ray_hit.material.emissive * emissive_mis_weight;
+ resample_reconnection_candidate(path, emissive_L_at_reconnection, rng);
+ }
+ } @else {
+ (*path).radiance += (*path).throughput_past_first_hit * ray_hit.material.emissive * emissive_mis_weight;
+ }
+}
+
+@if(RESTIR)
+fn generate_environment_map_light_candidate(
+ path: ptr<function, PathState>,
+ next_bounce: EvaluateAndSampleBrdfResult,
+ environment_map_light_radiance: vec3<f32>,
+ primary_F_ab: vec2<f32>,
+ bounce: u32,
+ rng: ptr<function, u32>,
+) {
+ if all(environment_map_light_radiance == vec3(0.0)) { return; }
+
+ if bounce == 0u {
+ // Bounce 0: Candidate is the sky direction
+ if !x1_lobe_reusable(next_bounce.pdf, next_bounce.diffuse_selected, (*path).material.perceptual_roughness) {
+ (*path).radiance += next_bounce.throughput * environment_map_light_radiance;
+ return;
+ }
+
+ // Publish the candidate as a point RAY_T_MAX along wi.
+ // Neighbors see almost the same direction, and the reconnection jacobian evaluates to ~1.
+ //
+ // TODO: Once the environment map light is a proper LightSource that we sample during NEE,
+ // store this as a LightSample instead.
+ let x1_brdf = evaluate_brdf((*path).wo, next_bounce.wi, (*path).normal, (*path).material, primary_F_ab);
+ let target_function = luminance(x1_brdf * environment_map_light_radiance);
+ let resampling_weight = luminance(next_bounce.throughput * environment_map_light_radiance);
+
+ (*path).weight_sum += resampling_weight;
+ if rand_f(rng) * (*path).weight_sum < resampling_weight {
+ (*path).reservoir.light_sample = LightSample(NULL_LIGHT_ID, 0u);
+ (*path).reservoir.sample_point_world_position = (*path).ray_origin + next_bounce.wi * RAY_T_MAX;
+ (*path).reservoir.sample_point_world_normal = octahedral_encode(-next_bounce.wi);
+ (*path).reservoir.radiance = environment_map_light_radiance;
+ (*path).selected_target_function = target_function;
+ }
+ } else {
+ // Deeper bounces: Candidate is the reconnection radiance at x2
+ let L_at_reconnection = (*path).throughput_past_first_hit * next_bounce.throughput * environment_map_light_radiance;
+ resample_reconnection_candidate(path, L_at_reconnection, rng);
+ }
+}
+
+fn terminate_into_cache(
+ path: ptr<function, PathState>,
+ ray_hit: ResolvedRayHitFull,
+ ray_t: f32,
+ p_brdf: f32,
+ bounce: u32,
+ rng: ptr<function, u32>,
+) -> bool {
+ // Only terminate into the world cache when the bounce was from a wide-enough BRDF sample
+ // because the cache is less noisy than continuing the path for rough surfaces,
+ // but less accurate for smooth surfaces
+ let lobe_solid_angle = 1.0 / p_brdf;
+ let broad_enough_to_terminate = lobe_solid_angle >= CACHE_TERMINATION_MIN_SOLID_ANGLE;
+ let forced_terminate = bounce == constants.max_bounces - 1u;
+ if !(broad_enough_to_terminate || forced_terminate) { return false; }
+
+ // Only use the cache when the ray cleared the cache cell (diagonal = sqrt(3) * cell_size). Short
+ // rays land in a cell that may straddle occluders and leak light through corners.
+ var rng_copy = *rng;
+ let world_cache_cell_size = get_cell_size(ray_hit.world_position, view.world_position, ray_t, &rng_copy);
+ if ray_t <= sqrt(3.0) * world_cache_cell_size { return false; }
+
+ let cached_radiance = query_world_cache(ray_hit.world_position, ray_hit.geometric_world_normal, view.world_position, ray_t, WORLD_CACHE_CELL_LIFETIME, rng);
+
+ let cache_outgoing = (ray_hit.material.base_color / PI) * cached_radiance;
+ let cache_L_at_reconnection = (*path).throughput_past_first_hit * cache_outgoing;
+
+ @if(RESTIR) {
+ resample_reconnection_candidate(path, cache_L_at_reconnection, rng);
+ } @else {
+ (*path).radiance += cache_L_at_reconnection;
+ }
+
+ return true;
+}
+
+/// Resample radiance arriving at x1 through the reconnection vertex x2. `L_at_reconnection` excludes the
+/// brdf*cos at x1, which is re-applied at shade time from whichever pixel ends up reusing the candidate.
+@if(RESTIR)
+fn resample_reconnection_candidate(path: ptr<function, PathState>, L_at_reconnection: vec3<f32>, rng: ptr<function, u32>) {
+ if !(*path).x2_reusable {
+ // x1 -> x2 not reuse-safe: shade directly at this pixel instead of publishing.
+ (*path).radiance += (*path).x1_brdf * L_at_reconnection;
+ return;
+ }
+
+ let target_function = luminance((*path).x1_brdf * L_at_reconnection);
+ let resampling_weight = target_function;
+
+ (*path).weight_sum += resampling_weight;
+ if rand_f(rng) * (*path).weight_sum < resampling_weight {
+ (*path).reservoir.light_sample = LightSample(NULL_LIGHT_ID, 0u);
+ (*path).reservoir.sample_point_world_position = (*path).x2_position;
+ (*path).reservoir.sample_point_world_normal = octahedral_encode((*path).x2_normal);
+ (*path).reservoir.radiance = L_at_reconnection;
+ (*path).selected_target_function = target_function;
+ }
+}
+
+/// ReSTIR PT Enhanced: Algorithmic Advances for Faster and More Robust ReSTIR Path Tracing
+/// Section 4 (sorta)
+/// https://research.nvidia.com/labs/rtr/publication/lin2026restirptenhanced/lin2026restirptenhanced.pdf
+@if(RESTIR)
+fn reconnection_reusable(ray_t: f32, p_brdf: f32, wi: vec3<f32>, diffuse_selected: bool, ray_hit: ResolvedRayHitFull, world_position: vec3<f32>, x1_perceptual_roughness: f32, primary_NdotV: f32) -> bool {
+ // ray_footprint = t^2 / (p_brdf * cos_x2) is the area a sample represents at x2. It goes to 0 for
+ // mirror lobes (p_brdf = INF) and shrinks for sharp lobes or short segments. Compared against a
+ // uniform 1/(4*PI) primary footprint, so the test trades roughness against distance.
+ let cos_x2 = max(dot(ray_hit.world_normal, -wi), 0.0001);
+ let ray_footprint = (ray_t * ray_t) / (p_brdf * cos_x2);
+ let primary_dist = length(view.world_position - world_position);
+ let primary_footprint = 4.0 * PI * primary_dist * primary_dist / primary_NdotV;
+ let footprint_ok = ray_footprint >= (RECONNECTION_FOOTPRINT_KAPPA / 100.0) * primary_footprint;
+
+ let x1_lobe_ok = x1_lobe_reusable(p_brdf, diffuse_selected, x1_perceptual_roughness);
+
+ // Guard at x2. A sharp reflector there makes the stored radiance view-dependent and wrong to
+ // reuse from a neighbor's direction. The roughness floor relaxes with segment length: a distant
+ // glossy x2 is seen by neighbors from nearly the same direction, so the view-dependence washes out.
+ // Diffuse, rough, and emissive vertices are always reuse-safe.
+ let x2_is_light = any(ray_hit.material.emissive > vec3(0.0));
+ let x2_roughness = mix(1.0, ray_hit.material.perceptual_roughness, ray_hit.material.metallic);
+ let x2_roughness_floor = RECONNECTION_ROUGHNESS_MIN * saturate(RECONNECTION_RELAX_DISTANCE / ray_t);
+ let x2_end_ok = x2_is_light || x2_roughness >= x2_roughness_floor;
+
+ return footprint_ok && x1_lobe_ok && x2_end_ok;
+}
+
+/// Whether the lobe sampled at x1 is wide enough for its candidates to be reused by neighbors.
+@if(RESTIR)
+fn x1_lobe_reusable(p_brdf: f32, diffuse_selected: bool, x1_perceptual_roughness: f32) -> bool {
+ return !isinf(p_brdf) && (diffuse_selected || x1_perceptual_roughness >= RECONNECTION_ROUGHNESS_MIN);
+}
diff --git a/vendor/bevy_solari/src/realtime/mod.rs b/vendor/bevy_solari/src/realtime/mod.rs
new file mode 100644
index 00000000..7300f813
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/mod.rs
@@ -0,0 +1,267 @@
+mod extract;
+mod node;
+mod prepare;
+
+use crate::{
+ scene::{prepare_raytracing_scene_resources, RaytracingSceneBindings},
+ SolariPlugins,
+};
+use bevy_app::{App, Plugin, PostUpdate};
+use bevy_asset::embedded_asset;
+use bevy_camera::Hdr;
+use bevy_core_pipeline::{
+ core_3d::main_opaque_pass_3d,
+ prepass::{
+ DeferredPrepass, DeferredPrepassDoubleBuffer, DepthPrepass, DepthPrepassDoubleBuffer,
+ MotionVectorPrepass,
+ },
+ schedule::{Core3d, Core3dSystems},
+};
+use bevy_ecs::{
+ component::Component,
+ entity::Entity,
+ query::Has,
+ reflect::ReflectComponent,
+ schedule::IntoScheduleConfigs,
+ system::{Commands, Query},
+};
+use bevy_pbr::DefaultOpaqueRendererMethod;
+use bevy_reflect::{std_traits::ReflectDefault, Reflect};
+use bevy_render::{
+ init_gpu_resource, renderer::RenderDevice, ExtractSchedule, Render, RenderApp, RenderStartup,
+ RenderSystems,
+};
+use bevy_shader::load_shader_library;
+use extract::extract_solari_lighting;
+use node::{init_solari_lighting_pipelines, solari_lighting};
+use prepare::{
+ prepare_solari_lighting_resources, setup_raytracing_scene_needs_previous_frame_data,
+};
+use tracing::warn;
+
+/// Raytraced direct and indirect lighting.
+///
+/// When using this plugin, it's highly recommended to set `shadow_maps_enabled: false` on all lights, as Solari replaces
+/// traditional shadow mapping.
+pub struct SolariLightingPlugin;
+
+impl Plugin for SolariLightingPlugin {
+ fn build(&self, app: &mut App) {
+ load_shader_library!(app, "gbuffer_utils.wesl");
+ load_shader_library!(app, "bindings.wesl");
+ load_shader_library!(app, "presample_light_tiles.wesl");
+ load_shader_library!(app, "initial_path.wesl");
+ embedded_asset!(app, "restir.wesl");
+ embedded_asset!(app, "no_restir.wesl");
+ load_shader_library!(app, "world_cache_query.wesl");
+ embedded_asset!(app, "world_cache_compact.wesl");
+ embedded_asset!(app, "world_cache_update.wesl");
+
+ load_shader_library!(app, "resolve_dlss_rr_textures.wesl");
+
+ app.insert_resource(DefaultOpaqueRendererMethod::deferred());
+ }
+
+ fn finish(&self, app: &mut App) {
+ let features = app
+ .sub_app(RenderApp)
+ .world()
+ .resource::<RenderDevice>()
+ .features();
+ if !features.contains(SolariPlugins::required_wgpu_features()) {
+ warn!(
+ "SolariLightingPlugin not loaded. GPU lacks support for required features: {:?}.",
+ SolariPlugins::required_wgpu_features().difference(features)
+ );
+ return;
+ }
+
+ app.add_systems(PostUpdate, manage_prepass_double_buffers);
+
+ app.sub_app_mut(RenderApp)
+ .add_systems(
+ RenderStartup,
+ init_solari_lighting_pipelines.after(init_gpu_resource::<RaytracingSceneBindings>),
+ )
+ .add_systems(ExtractSchedule, extract_solari_lighting)
+ .add_systems(
+ Render,
+ (
+ prepare_solari_lighting_resources,
+ setup_raytracing_scene_needs_previous_frame_data
+ .before(prepare_raytracing_scene_resources),
+ )
+ .in_set(RenderSystems::PrepareResources),
+ )
+ .add_systems(
+ Core3d,
+ solari_lighting
+ .before(main_opaque_pass_3d)
+ .in_set(Core3dSystems::MainPass),
+ );
+ }
+}
+
+/// A component for a 3d camera entity to enable the Solari raytraced lighting system.
+///
+/// Must be used with `CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING)`, and
+/// `Msaa::Off`.
+#[derive(Component, Reflect, Clone)]
+#[reflect(Component, Default, Clone)]
+#[require(Hdr, DeferredPrepass, DepthPrepass, MotionVectorPrepass)]
+pub struct SolariLighting {
+ /// [ReSTIR](https://en.wikipedia.org/wiki/Spatiotemporal_reservoir_resampling) is a technique to reuse path samples
+ /// between pixels and frames. This dramatically reduces noise, at the cost of a few extra rays per pixel.
+ ///
+ /// However, modern denoisers cope well with very noisy input. In many cases, turning this on
+ /// won't dramatically improve quality after denoising.
+ ///
+ /// If you want more fine shadow detail, or have scenes with more difficult lighting conditions,
+ /// turning this on may improve quality and stability, at the cost of a decent chunk of performance.
+ ///
+ /// Whether to enable this setting or not will be very scene dependent.
+ ///
+ /// Defaults to `false`.
+ pub restir: bool,
+
+ /// Maximum confidence weight (effective temporal history length) a pixel
+ /// can accumulate during temporal resampling.
+ ///
+ /// Has no effect when [`SolariLighting::restir`] is `false`.
+ ///
+ /// Higher values are more stable but slower to react to lighting changes
+ /// and will lead to increased artifacts.
+ pub confidence_weight_cap: f32,
+
+ /// Number of direct light samples taken for the camera's primary hit during
+ /// initial sampling.
+ ///
+ /// Higher values reduce noise in directly-lit areas at the cost of more work
+ /// per frame. Lower values are faster but noisier.
+ pub primary_di_samples: u32,
+
+ /// Number of direct light samples taken at each indirect bounce during
+ /// initial sampling.
+ ///
+ /// Higher values reduce noise in indirect lighting at the cost of more work
+ /// per frame. Lower values are faster but noisier.
+ pub secondary_di_samples: u32,
+
+ /// Maximum number of bounces traced when generating an initial path.
+ ///
+ /// Higher values capture more detail in nested reflections and more indirect lighting,
+ /// at the cost of more rays traced per frame. Lower values are faster but lose
+ /// multi-bounce lighting for specular paths.
+ pub max_bounces: u32,
+
+ /// How responsive the world cache is to changes in lighting.
+ ///
+ /// Higher values accumulate more temporal history, giving more stable but
+ /// less responsive (slower to update) lighting. Lower values react faster
+ /// but are noisier and less stable.
+ pub world_cache_max_temporal_samples: f32,
+
+ /// How many direct light samples each world cache cell takes when updating
+ /// each frame.
+ ///
+ /// Higher values reduce noise in cached lighting at the cost of more work
+ /// per frame. Lower values are faster but noisier.
+ pub world_cache_direct_light_sample_count: u32,
+
+ /// Maximum distance to trace GI rays between two world cache cells.
+ ///
+ /// Higher values capture indirect light from farther away for more accurate
+ /// GI at the cost of longer (more expensive) ray traversal and increased noise.
+ /// Lower values are faster and less noisy but may miss distant lighting or leak sky lighting.
+ ///
+ /// Rays that miss within this distance are treated as reaching the environment
+ /// map light, and leak sky lighting into the cache.
+ pub world_cache_max_gi_ray_distance: f32,
+
+ /// Soft upper limit on the number of world cache cells to update each frame.
+ ///
+ /// Higher values let the cache converge faster after lighting changes at the
+ /// cost of more work per frame. Lower values are cheaper but make the cache
+ /// slower to update.
+ ///
+ /// This is a stochastic target that only takes effect when the number of
+ /// active cells exceeds it: each active cell is then updated with
+ /// probability `target / active_cells`, so on average this many cells
+ /// update, though individual frames may update more or fewer. When there
+ /// are fewer active cells than the target, all of them update every frame.
+ pub world_cache_cell_updates_soft_target: u32,
+
+ /// Size of a world cache cell at the lowest LOD, in meters.
+ ///
+ /// Smaller values give finer spatial resolution and more detailed indirect
+ /// lighting at the cost of more cells to fill and update. Larger values are
+ /// cheaper but coarser, which can cause light leaking.
+ pub world_cache_position_base_cell_size: f32,
+
+ /// How fast the world cache transitions between LODs as a function of
+ /// distance to the camera.
+ ///
+ /// Higher values keep cells small (high detail) out to greater distances for
+ /// better quality at the cost of more cells to fill. Lower values transition
+ /// to larger cells sooner, which is cheaper but coarser farther from the
+ /// camera.
+ pub world_cache_position_lod_scale: f32,
+
+ /// Set to true to delete the saved temporal history (past frames).
+ ///
+ /// Useful for preventing ghosting when the history is no longer
+ /// representative of the current frame, such as in sudden camera cuts.
+ ///
+ /// After setting this to true, it will automatically be toggled
+ /// back to false at the end of the frame.
+ pub reset: bool,
+}
+
+impl Default for SolariLighting {
+ fn default() -> Self {
+ Self {
+ restir: false,
+ confidence_weight_cap: 8.0,
+ primary_di_samples: 8,
+ secondary_di_samples: 4,
+ max_bounces: 3,
+ world_cache_max_temporal_samples: 32.0,
+ world_cache_direct_light_sample_count: 32,
+ world_cache_max_gi_ray_distance: 50.0,
+ world_cache_cell_updates_soft_target: 40000,
+ world_cache_position_base_cell_size: 0.15,
+ world_cache_position_lod_scale: 15.0,
+ reset: true, // No temporal history on the first frame
+ }
+ }
+}
+
+/// Adds or removes the prepass double-buffer components according to [`SolariLighting::restir`].
+fn manage_prepass_double_buffers(
+ views: Query<(
+ Entity,
+ &SolariLighting,
+ Has<DeferredPrepassDoubleBuffer>,
+ Has<DepthPrepassDoubleBuffer>,
+ )>,
+ mut commands: Commands,
+) {
+ for (entity, solari_lighting, deferred_double_buffered, depth_double_buffered) in &views {
+ let mut entity = commands.entity(entity);
+ if solari_lighting.restir {
+ if !deferred_double_buffered {
+ entity.insert(DeferredPrepassDoubleBuffer);
+ }
+ if !depth_double_buffered {
+ entity.insert(DepthPrepassDoubleBuffer);
+ }
+ } else {
+ if deferred_double_buffered {
+ entity.remove::<DeferredPrepassDoubleBuffer>();
+ }
+ if depth_double_buffered {
+ entity.remove::<DepthPrepassDoubleBuffer>();
+ }
+ }
+ }
+}
diff --git a/vendor/bevy_solari/src/realtime/no_restir.wesl b/vendor/bevy_solari/src/realtime/no_restir.wesl
new file mode 100644
index 00000000..f15fcd02
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/no_restir.wesl
@@ -0,0 +1,30 @@
+import package::realtime::gbuffer_utils::gpixel_resolve;
+import package::realtime::initial_path::generate_initial_path;
+import package::realtime::bindings::{constants, depth_buffer, gbuffer, view, view_output};
+import package::scene::bindings::RAY_T_MAX;
+import package::realtime::world_cache_query::{query_world_cache, WORLD_CACHE_CELL_LIFETIME};
+
+enable wgpu_ray_query;
+
+@compute @workgroup_size(8, 8, 1)
+fn initial_and_shade(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) global_id: vec3<u32>) {
+ if any(global_id.xy >= vec2u(view.main_pass_viewport.zw)) { return; }
+
+ let pixel_index = global_id.x + global_id.y * u32(view.main_pass_viewport.z);
+ var rng = pixel_index + constants.frame_rng;
+
+ let depth = textureLoad(depth_buffer, global_id.xy, 0);
+ if depth == 0.0 { return; }
+
+ let surface = gpixel_resolve(textureLoad(gbuffer, global_id.xy, 0), depth, global_id.xy, view.main_pass_viewport.zw, view.world_from_clip);
+
+ let path = generate_initial_path(surface.world_position, surface.world_normal, surface.material, workgroup_id.xy, global_id.xy, &rng);
+
+ var pixel_color = path.radiance;
+ pixel_color += surface.material.emissive;
+ pixel_color *= view.exposure;
+ textureStore(view_output, global_id.xy, vec4(pixel_color, 1.0));
+
+ @if(VISUALIZE_WORLD_CACHE)
+ textureStore(view_output, global_id.xy, vec4(query_world_cache(surface.world_position, surface.world_normal, view.world_position, RAY_T_MAX, WORLD_CACHE_CELL_LIFETIME, &rng) * view.exposure, 1.0));
+}
diff --git a/vendor/bevy_solari/src/realtime/node.rs b/vendor/bevy_solari/src/realtime/node.rs
new file mode 100644
index 00000000..7c2ee5e4
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/node.rs
@@ -0,0 +1,670 @@
+use super::prepare::{
+ SolariLightingResources, LIGHT_TILE_BLOCKS, WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET,
+ WORLD_CACHE_SIZE,
+};
+use crate::scene::RaytracingSceneBindings;
+#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+use bevy_anti_alias::dlss::ViewDlssRayReconstructionTextures;
+use bevy_asset::{load_embedded_asset, AssetServer, Handle};
+use bevy_core_pipeline::prepass::{
+ PreviousViewData, PreviousViewUniformOffset, PreviousViewUniforms, ViewPrepassTextures,
+ MOTION_VECTOR_PREPASS_FORMAT,
+};
+use bevy_ecs::{prelude::*, resource::Resource, system::Commands};
+use bevy_render::{
+ diagnostic::RecordDiagnostics as _,
+ render_resource::{
+ binding_types::{
+ storage_buffer_sized, texture_2d, texture_depth_2d, texture_storage_2d, uniform_buffer,
+ uniform_buffer_sized,
+ },
+ BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries,
+ CachedComputePipelineId, ComputePassDescriptor, ComputePipelineDescriptor, LoadOp,
+ PipelineCache, RenderPassDescriptor, ShaderStages, StorageTextureAccess, TextureFormat,
+ TextureFormatFeatureFlags, TextureSampleType,
+ },
+ renderer::{RenderAdapter, RenderContext, RenderDevice, ViewQuery},
+ view::{ViewTarget, ViewUniform, ViewUniformOffset, ViewUniforms},
+};
+use bevy_shader::{Shader, ShaderDefVal};
+use bevy_utils::default;
+
+/// Resource holding the Solari lighting pipeline configuration.
+#[derive(Resource)]
+pub struct SolariLightingPipelines {
+ bind_group_layout: BindGroupLayoutDescriptor,
+ bind_group_layout_restir: BindGroupLayoutDescriptor,
+ bind_group_layout_world_cache_active_cells_dispatch: BindGroupLayoutDescriptor,
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ bind_group_layout_resolve_dlss_rr_textures: BindGroupLayoutDescriptor,
+ decay_world_cache_pipeline: CachedComputePipelineId,
+ compact_world_cache_single_block_pipeline: CachedComputePipelineId,
+ compact_world_cache_blocks_pipeline: CachedComputePipelineId,
+ compact_world_cache_write_active_cells_pipeline: CachedComputePipelineId,
+ sample_di_for_world_cache_pipeline: CachedComputePipelineId,
+ sample_gi_for_world_cache_pipeline: CachedComputePipelineId,
+ blend_new_world_cache_samples_pipeline: CachedComputePipelineId,
+ presample_light_tiles_pipeline: CachedComputePipelineId,
+ restir: RestirPipelines,
+ no_restir: NoRestirPipelines,
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ resolve_dlss_rr_textures_pipeline: CachedComputePipelineId,
+}
+
+struct RestirPipelines {
+ initial_and_temporal: CachedComputePipelineId,
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ initial_and_temporal_with_psr: CachedComputePipelineId,
+ spatial_and_shade: CachedComputePipelineId,
+}
+
+struct NoRestirPipelines {
+ initial_and_shade: CachedComputePipelineId,
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ initial_and_shade_with_psr: CachedComputePipelineId,
+}
+
+#[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
+type SolariLightingViewQuery = (
+ &'static SolariLightingResources,
+ &'static ViewTarget,
+ &'static ViewPrepassTextures,
+ &'static ViewUniformOffset,
+ &'static PreviousViewUniformOffset,
+);
+
+#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+type SolariLightingViewQuery = (
+ &'static SolariLightingResources,
+ &'static ViewTarget,
+ &'static ViewPrepassTextures,
+ &'static ViewUniformOffset,
+ &'static PreviousViewUniformOffset,
+ Option<&'static ViewDlssRayReconstructionTextures>,
+);
+
+pub fn solari_lighting(
+ view: ViewQuery<SolariLightingViewQuery>,
+ solari_pipelines: Option<Res<SolariLightingPipelines>>,
+ pipeline_cache: Res<PipelineCache>,
+ scene_bindings: Res<RaytracingSceneBindings>,
+ view_uniforms: Res<ViewUniforms>,
+ previous_view_uniforms: Res<PreviousViewUniforms>,
+ render_device: Res<RenderDevice>,
+ mut ctx: RenderContext,
+) {
+ #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
+ let (
+ solari_lighting_resources,
+ view_target,
+ view_prepass_textures,
+ view_uniform_offset,
+ previous_view_uniform_offset,
+ ) = view.into_inner();
+
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ let (
+ solari_lighting_resources,
+ view_target,
+ view_prepass_textures,
+ view_uniform_offset,
+ previous_view_uniform_offset,
+ view_dlss_rr_textures,
+ ) = view.into_inner();
+
+ let Some(pipelines) = solari_pipelines else {
+ return;
+ };
+
+ let restir = solari_lighting_resources.reservoirs.as_ref().zip(
+ view_prepass_textures
+ .previous_deferred_view()
+ .zip(view_prepass_textures.previous_depth_only_view()),
+ );
+
+ #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
+ let (initial_pipeline_id, spatial_pipeline_id) = if restir.is_some() {
+ (
+ pipelines.restir.initial_and_temporal,
+ Some(pipelines.restir.spatial_and_shade),
+ )
+ } else {
+ (pipelines.no_restir.initial_and_shade, None)
+ };
+
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ let (initial_pipeline_id, spatial_pipeline_id) =
+ match (restir.is_some(), view_dlss_rr_textures.is_some()) {
+ (true, true) => (
+ pipelines.restir.initial_and_temporal_with_psr,
+ Some(pipelines.restir.spatial_and_shade),
+ ),
+ (true, false) => (
+ pipelines.restir.initial_and_temporal,
+ Some(pipelines.restir.spatial_and_shade),
+ ),
+ (false, true) => (pipelines.no_restir.initial_and_shade_with_psr, None),
+ (false, false) => (pipelines.no_restir.initial_and_shade, None),
+ };
+
+ let (
+ Some(decay_world_cache_pipeline),
+ Some(compact_world_cache_single_block_pipeline),
+ Some(compact_world_cache_blocks_pipeline),
+ Some(compact_world_cache_write_active_cells_pipeline),
+ Some(sample_di_for_world_cache_pipeline),
+ Some(sample_gi_for_world_cache_pipeline),
+ Some(blend_new_world_cache_samples_pipeline),
+ Some(presample_light_tiles_pipeline),
+ Some(initial_pipeline),
+ Some(scene_bind_group),
+ Some(gbuffer),
+ Some(depth_buffer),
+ Some(motion_vectors),
+ Some(view_uniforms_binding),
+ Some(previous_view_uniforms_binding),
+ ) = (
+ pipeline_cache.get_compute_pipeline(pipelines.decay_world_cache_pipeline),
+ pipeline_cache.get_compute_pipeline(pipelines.compact_world_cache_single_block_pipeline),
+ pipeline_cache.get_compute_pipeline(pipelines.compact_world_cache_blocks_pipeline),
+ pipeline_cache
+ .get_compute_pipeline(pipelines.compact_world_cache_write_active_cells_pipeline),
+ pipeline_cache.get_compute_pipeline(pipelines.sample_di_for_world_cache_pipeline),
+ pipeline_cache.get_compute_pipeline(pipelines.sample_gi_for_world_cache_pipeline),
+ pipeline_cache.get_compute_pipeline(pipelines.blend_new_world_cache_samples_pipeline),
+ pipeline_cache.get_compute_pipeline(pipelines.presample_light_tiles_pipeline),
+ pipeline_cache.get_compute_pipeline(initial_pipeline_id),
+ &scene_bindings.bind_group,
+ view_prepass_textures.deferred_view(),
+ view_prepass_textures.depth_only_view(),
+ view_prepass_textures.motion_vectors_view(),
+ view_uniforms.uniforms.binding(),
+ previous_view_uniforms.uniforms.binding(),
+ )
+ else {
+ return;
+ };
+
+ let spatial_and_shade_pipeline = match spatial_pipeline_id {
+ Some(id) => match pipeline_cache.get_compute_pipeline(id) {
+ None => return,
+ pipeline => pipeline,
+ },
+ None => None,
+ };
+
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ let Some(resolve_dlss_rr_textures_pipeline) =
+ pipeline_cache.get_compute_pipeline(pipelines.resolve_dlss_rr_textures_pipeline)
+ else {
+ return;
+ };
+
+ // Past every bail-out, so this view's reservoirs will be brought up to this frame's light ids
+ if restir.is_some() {
+ scene_bindings.note_light_translations_consumed();
+ }
+
+ let view_target_attachment = view_target.get_unsampled_color_attachment();
+
+ let s = solari_lighting_resources;
+ let bind_group = render_device.create_bind_group(
+ "solari_lighting_bind_group",
+ &pipeline_cache.get_bind_group_layout(&pipelines.bind_group_layout),
+ &BindGroupEntries::sequential((
+ view_target_attachment.view,
+ s.light_tile_samples.as_entire_binding(),
+ s.light_tile_resolved_samples.as_entire_binding(),
+ gbuffer,
+ depth_buffer,
+ motion_vectors,
+ view_uniforms_binding.clone(),
+ previous_view_uniforms_binding.clone(),
+ s.world_cache.as_entire_binding(),
+ s.constants.as_entire_binding(),
+ )),
+ );
+
+ let bind_group_restir =
+ restir.map(|(reservoirs, (previous_gbuffer, previous_depth_buffer))| {
+ render_device.create_bind_group(
+ "solari_lighting_bind_group_restir",
+ &pipeline_cache.get_bind_group_layout(&pipelines.bind_group_layout_restir),
+ &BindGroupEntries::sequential((
+ view_target_attachment.view,
+ s.light_tile_samples.as_entire_binding(),
+ s.light_tile_resolved_samples.as_entire_binding(),
+ gbuffer,
+ depth_buffer,
+ motion_vectors,
+ view_uniforms_binding,
+ previous_view_uniforms_binding,
+ s.world_cache.as_entire_binding(),
+ s.constants.as_entire_binding(),
+ previous_gbuffer,
+ previous_depth_buffer,
+ reservoirs.a.as_entire_binding(),
+ reservoirs.b.as_entire_binding(),
+ )),
+ )
+ });
+
+ let bind_group_world_cache_active_cells_dispatch = render_device.create_bind_group(
+ "solari_lighting_bind_group_world_cache_active_cells_dispatch",
+ &pipeline_cache
+ .get_bind_group_layout(&pipelines.bind_group_layout_world_cache_active_cells_dispatch),
+ &BindGroupEntries::single(s.world_cache_active_cells_dispatch.as_entire_binding()),
+ );
+
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ let bind_group_resolve_dlss_rr_textures = view_dlss_rr_textures.map(|d| {
+ render_device.create_bind_group(
+ "solari_lighting_bind_group_resolve_dlss_rr_textures",
+ &pipeline_cache
+ .get_bind_group_layout(&pipelines.bind_group_layout_resolve_dlss_rr_textures),
+ &BindGroupEntries::sequential((
+ &d.diffuse_albedo.default_view,
+ &d.specular_albedo.default_view,
+ &d.normal_roughness.default_view,
+ &d.depth.default_view,
+ &d.specular_motion_vectors.default_view,
+ )),
+ )
+ });
+
+ let diagnostics = ctx.diagnostic_recorder();
+ let diagnostics = diagnostics.as_deref();
+
+ let command_encoder = ctx.command_encoder();
+
+ // Clear the view target if we're the first node to write to it
+ if matches!(view_target_attachment.ops.load, LoadOp::Clear(_)) {
+ command_encoder.begin_render_pass(&RenderPassDescriptor {
+ label: Some("solari_lighting_clear"),
+ color_attachments: &[Some(view_target_attachment)],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ }
+
+ let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
+ label: Some("solari_lighting"),
+ timestamp_writes: None,
+ });
+
+ let dx = solari_lighting_resources.view_size.x.div_ceil(8);
+ let dy = solari_lighting_resources.view_size.y.div_ceil(8);
+
+ pass.set_bind_group(0, scene_bind_group, &[]);
+ pass.set_bind_group(
+ 1,
+ &bind_group,
+ &[
+ view_uniform_offset.offset,
+ previous_view_uniform_offset.offset,
+ ],
+ );
+
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ if let Some(bind_group_resolve_dlss_rr_textures) = &bind_group_resolve_dlss_rr_textures {
+ pass.set_bind_group(2, bind_group_resolve_dlss_rr_textures, &[]);
+ pass.set_pipeline(resolve_dlss_rr_textures_pipeline);
+ pass.dispatch_workgroups(dx, dy, 1);
+ }
+
+ let d = diagnostics.time_span(&mut pass, "solari_lighting/presample_light_tiles");
+ pass.set_pipeline(presample_light_tiles_pipeline);
+ pass.dispatch_workgroups(LIGHT_TILE_BLOCKS as u32, 1, 1);
+ d.end(&mut pass);
+
+ let d = diagnostics.time_span(&mut pass, "solari_lighting/world_cache");
+
+ pass.set_bind_group(2, &bind_group_world_cache_active_cells_dispatch, &[]);
+
+ pass.set_pipeline(decay_world_cache_pipeline);
+ pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1);
+
+ pass.set_pipeline(compact_world_cache_single_block_pipeline);
+ pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1);
+
+ pass.set_pipeline(compact_world_cache_blocks_pipeline);
+ pass.dispatch_workgroups(1, 1, 1);
+
+ pass.set_pipeline(compact_world_cache_write_active_cells_pipeline);
+ pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1);
+
+ pass.set_bind_group(2, None, &[]);
+
+ pass.set_pipeline(sample_di_for_world_cache_pipeline);
+ pass.dispatch_workgroups_indirect(
+ &solari_lighting_resources.world_cache_active_cells_dispatch,
+ 0,
+ );
+
+ pass.set_pipeline(sample_gi_for_world_cache_pipeline);
+ pass.dispatch_workgroups_indirect(
+ &solari_lighting_resources.world_cache_active_cells_dispatch,
+ 0,
+ );
+
+ pass.set_pipeline(blend_new_world_cache_samples_pipeline);
+ pass.dispatch_workgroups_indirect(
+ &solari_lighting_resources.world_cache_active_cells_dispatch,
+ 0,
+ );
+
+ d.end(&mut pass);
+
+ let d = diagnostics.time_span(&mut pass, "solari_lighting/lighting");
+
+ if let Some(bind_group_restir) = &bind_group_restir {
+ pass.set_bind_group(
+ 1,
+ bind_group_restir,
+ &[
+ view_uniform_offset.offset,
+ previous_view_uniform_offset.offset,
+ ],
+ );
+ }
+
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ if let Some(bind_group_resolve_dlss_rr_textures) = &bind_group_resolve_dlss_rr_textures {
+ pass.set_bind_group(2, bind_group_resolve_dlss_rr_textures, &[]);
+ }
+ pass.set_pipeline(initial_pipeline);
+ pass.dispatch_workgroups(dx, dy, 1);
+
+ if let Some(spatial_and_shade_pipeline) = spatial_and_shade_pipeline {
+ pass.set_pipeline(spatial_and_shade_pipeline);
+ pass.dispatch_workgroups(dx, dy, 1);
+ }
+
+ d.end(&mut pass);
+
+ drop(pass);
+
+ // Active cell count readback.
+ diagnostics.record_u32(
+ ctx.command_encoder(),
+ &s.world_cache.slice(
+ WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET
+ ..WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET + size_of::<u32>() as u64,
+ ),
+ "solari_lighting/world_cache_active_cells_count",
+ );
+}
+
+/// Initializes the Solari lighting pipelines at render startup.
+pub fn init_solari_lighting_pipelines(
+ mut commands: Commands,
+ pipeline_cache: Res<PipelineCache>,
+ scene_bindings: Res<RaytracingSceneBindings>,
+ asset_server: Res<AssetServer>,
+ render_adapter: Res<RenderAdapter>,
+) {
+ let motion_vectors_storage_read_write = render_adapter
+ .get_texture_format_features(MOTION_VECTOR_PREPASS_FORMAT)
+ .flags
+ .contains(TextureFormatFeatureFlags::STORAGE_READ_WRITE);
+ let motion_vectors_binding = if motion_vectors_storage_read_write {
+ texture_storage_2d(TextureFormat::Rg16Float, StorageTextureAccess::ReadWrite)
+ } else {
+ texture_2d(TextureSampleType::Float { filterable: false })
+ };
+
+ let bind_group_layout = BindGroupLayoutDescriptor::new(
+ "solari_lighting_bind_group_layout",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::ReadWrite),
+ storage_buffer_sized(false, None),
+ storage_buffer_sized(false, None),
+ texture_2d(TextureSampleType::Uint),
+ texture_depth_2d(),
+ motion_vectors_binding,
+ uniform_buffer::<ViewUniform>(true),
+ uniform_buffer::<PreviousViewData>(true),
+ storage_buffer_sized(false, None),
+ uniform_buffer_sized(false, None),
+ ),
+ ),
+ );
+
+ let bind_group_layout_restir = BindGroupLayoutDescriptor::new(
+ "solari_lighting_bind_group_layout_restir",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::ReadWrite),
+ storage_buffer_sized(false, None),
+ storage_buffer_sized(false, None),
+ texture_2d(TextureSampleType::Uint),
+ texture_depth_2d(),
+ motion_vectors_binding,
+ uniform_buffer::<ViewUniform>(true),
+ uniform_buffer::<PreviousViewData>(true),
+ storage_buffer_sized(false, None),
+ uniform_buffer_sized(false, None),
+ texture_2d(TextureSampleType::Uint),
+ texture_depth_2d(),
+ storage_buffer_sized(false, None),
+ storage_buffer_sized(false, None),
+ ),
+ ),
+ );
+
+ let bind_group_layout_world_cache_active_cells_dispatch = BindGroupLayoutDescriptor::new(
+ "solari_lighting_bind_group_layout_world_cache_active_cells_dispatch",
+ &BindGroupLayoutEntries::single(ShaderStages::COMPUTE, storage_buffer_sized(false, None)),
+ );
+
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ let bind_group_layout_resolve_dlss_rr_textures = BindGroupLayoutDescriptor::new(
+ "solari_lighting_bind_group_layout_resolve_dlss_rr_textures",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ texture_storage_2d(TextureFormat::Rgba8Unorm, StorageTextureAccess::WriteOnly),
+ texture_storage_2d(TextureFormat::Rgba8Unorm, StorageTextureAccess::WriteOnly),
+ texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
+ texture_storage_2d(TextureFormat::R32Float, StorageTextureAccess::WriteOnly),
+ texture_storage_2d(TextureFormat::Rg16Float, StorageTextureAccess::WriteOnly),
+ ),
+ ),
+ );
+
+ let create_pipeline = |label: &'static str,
+ entry_point: &'static str,
+ shader: Handle<Shader>,
+ restir: bool,
+ extra_bind_group: ExtraBindGroup,
+ extra_shader_defs: Vec<ShaderDefVal>| {
+ let group_1 = if restir {
+ &bind_group_layout_restir
+ } else {
+ &bind_group_layout
+ };
+ let mut layout = vec![scene_bindings.bind_group_layout.clone(), group_1.clone()];
+ match extra_bind_group {
+ ExtraBindGroup::None => {}
+ ExtraBindGroup::WorldCacheDispatch => {
+ layout.push(bind_group_layout_world_cache_active_cells_dispatch.clone());
+ }
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ ExtraBindGroup::DlssRrGuideBuffers => {
+ layout.push(bind_group_layout_resolve_dlss_rr_textures.clone());
+ }
+ }
+
+ let mut shader_defs = vec![ShaderDefVal::UInt(
+ "WORLD_CACHE_SIZE".into(),
+ WORLD_CACHE_SIZE as u32,
+ )];
+ if motion_vectors_storage_read_write {
+ shader_defs.push("MOTION_VECTORS_READ_WRITE".into());
+ }
+ if restir {
+ shader_defs.push("RESTIR".into());
+ }
+ match extra_bind_group {
+ ExtraBindGroup::None => {}
+ ExtraBindGroup::WorldCacheDispatch => {
+ shader_defs.push("WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER".into());
+ }
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ ExtraBindGroup::DlssRrGuideBuffers => {
+ shader_defs.push("DLSS_RR_GUIDE_BUFFERS".into());
+ }
+ }
+ shader_defs.extend_from_slice(&extra_shader_defs);
+
+ pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
+ label: Some(label.into()),
+ layout,
+ shader,
+ shader_defs,
+ entry_point: Some(entry_point.into()),
+ ..default()
+ })
+ };
+
+ commands.insert_resource(SolariLightingPipelines {
+ bind_group_layout: bind_group_layout.clone(),
+ bind_group_layout_restir: bind_group_layout_restir.clone(),
+ bind_group_layout_world_cache_active_cells_dispatch:
+ bind_group_layout_world_cache_active_cells_dispatch.clone(),
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ bind_group_layout_resolve_dlss_rr_textures: bind_group_layout_resolve_dlss_rr_textures
+ .clone(),
+ decay_world_cache_pipeline: create_pipeline(
+ "solari_lighting_decay_world_cache_pipeline",
+ "decay_world_cache",
+ load_embedded_asset!(asset_server.as_ref(), "world_cache_compact.wesl"),
+ false,
+ ExtraBindGroup::WorldCacheDispatch,
+ vec![],
+ ),
+ compact_world_cache_single_block_pipeline: create_pipeline(
+ "solari_lighting_compact_world_cache_single_block_pipeline",
+ "compact_world_cache_single_block",
+ load_embedded_asset!(asset_server.as_ref(), "world_cache_compact.wesl"),
+ false,
+ ExtraBindGroup::WorldCacheDispatch,
+ vec![],
+ ),
+ compact_world_cache_blocks_pipeline: create_pipeline(
+ "solari_lighting_compact_world_cache_blocks_pipeline",
+ "compact_world_cache_blocks",
+ load_embedded_asset!(asset_server.as_ref(), "world_cache_compact.wesl"),
+ false,
+ ExtraBindGroup::WorldCacheDispatch,
+ vec![],
+ ),
+ compact_world_cache_write_active_cells_pipeline: create_pipeline(
+ "solari_lighting_compact_world_cache_write_active_cells_pipeline",
+ "compact_world_cache_write_active_cells",
+ load_embedded_asset!(asset_server.as_ref(), "world_cache_compact.wesl"),
+ false,
+ ExtraBindGroup::WorldCacheDispatch,
+ vec![],
+ ),
+ sample_di_for_world_cache_pipeline: create_pipeline(
+ "solari_lighting_sample_di_for_world_cache_pipeline",
+ "sample_di",
+ load_embedded_asset!(asset_server.as_ref(), "world_cache_update.wesl"),
+ false,
+ ExtraBindGroup::None,
+ vec![],
+ ),
+ sample_gi_for_world_cache_pipeline: create_pipeline(
+ "solari_lighting_sample_gi_for_world_cache_pipeline",
+ "sample_gi",
+ load_embedded_asset!(asset_server.as_ref(), "world_cache_update.wesl"),
+ false,
+ ExtraBindGroup::None,
+ vec!["WORLD_CACHE_QUERY_ATOMIC_MAX_LIFETIME".into()],
+ ),
+ blend_new_world_cache_samples_pipeline: create_pipeline(
+ "solari_lighting_blend_new_world_cache_samples_pipeline",
+ "blend_new_samples",
+ load_embedded_asset!(asset_server.as_ref(), "world_cache_update.wesl"),
+ false,
+ ExtraBindGroup::None,
+ vec![],
+ ),
+ presample_light_tiles_pipeline: create_pipeline(
+ "solari_lighting_presample_light_tiles_pipeline",
+ "presample_light_tiles",
+ load_embedded_asset!(asset_server.as_ref(), "presample_light_tiles.wesl"),
+ false,
+ ExtraBindGroup::None,
+ vec![],
+ ),
+ restir: RestirPipelines {
+ initial_and_temporal: create_pipeline(
+ "solari_lighting_initial_and_temporal_pipeline",
+ "initial_and_temporal",
+ load_embedded_asset!(asset_server.as_ref(), "restir.wesl"),
+ true,
+ ExtraBindGroup::None,
+ vec![],
+ ),
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ initial_and_temporal_with_psr: create_pipeline(
+ "solari_lighting_initial_and_temporal_with_psr_pipeline",
+ "initial_and_temporal",
+ load_embedded_asset!(asset_server.as_ref(), "restir.wesl"),
+ true,
+ ExtraBindGroup::DlssRrGuideBuffers,
+ vec![],
+ ),
+ spatial_and_shade: create_pipeline(
+ "solari_lighting_spatial_and_shade_pipeline",
+ "spatial_and_shade",
+ load_embedded_asset!(asset_server.as_ref(), "restir.wesl"),
+ true,
+ ExtraBindGroup::None,
+ vec!["SPATIAL_MERGE".into()],
+ ),
+ },
+ no_restir: NoRestirPipelines {
+ initial_and_shade: create_pipeline(
+ "solari_lighting_initial_and_shade_pipeline",
+ "initial_and_shade",
+ load_embedded_asset!(asset_server.as_ref(), "no_restir.wesl"),
+ false,
+ ExtraBindGroup::None,
+ vec![],
+ ),
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ initial_and_shade_with_psr: create_pipeline(
+ "solari_lighting_initial_and_shade_with_psr_pipeline",
+ "initial_and_shade",
+ load_embedded_asset!(asset_server.as_ref(), "no_restir.wesl"),
+ false,
+ ExtraBindGroup::DlssRrGuideBuffers,
+ vec![],
+ ),
+ },
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ resolve_dlss_rr_textures_pipeline: create_pipeline(
+ "solari_lighting_resolve_dlss_rr_textures_pipeline",
+ "resolve_dlss_rr_textures",
+ load_embedded_asset!(asset_server.as_ref(), "resolve_dlss_rr_textures.wesl"),
+ false,
+ ExtraBindGroup::DlssRrGuideBuffers,
+ vec![],
+ ),
+ });
+}
+
+enum ExtraBindGroup {
+ None,
+ WorldCacheDispatch,
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ DlssRrGuideBuffers,
+}
diff --git a/vendor/bevy_solari/src/realtime/prepare.rs b/vendor/bevy_solari/src/realtime/prepare.rs
new file mode 100644
index 00000000..95f52f64
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/prepare.rs
@@ -0,0 +1,340 @@
+use super::SolariLighting;
+use crate::scene::RaytracingSceneNeedsPreviousFrameData;
+#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+use bevy_anti_alias::dlss::{
+ Dlss, DlssRayReconstructionFeature, ViewDlssRayReconstructionTextures,
+};
+use bevy_camera::MainPassResolutionOverride;
+use bevy_diagnostic::FrameCount;
+#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+use bevy_ecs::query::Has;
+use bevy_ecs::{
+ component::Component,
+ entity::Entity,
+ system::{Commands, Query, Res},
+};
+#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+use bevy_image::ToExtents;
+use bevy_math::UVec2;
+use bevy_render::{
+ camera::ExtractedCamera,
+ render_resource::{Buffer, BufferDescriptor, BufferInitDescriptor, BufferUsages},
+ renderer::{RenderDevice, RenderQueue},
+};
+#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+use bevy_render::{
+ render_resource::{
+ TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, TextureViewDescriptor,
+ },
+ texture::CachedTexture,
+};
+use bytemuck::{Pod, Zeroable};
+
+/// Size of the `LightSample` shader struct in bytes.
+const LIGHT_SAMPLE_STRUCT_SIZE: u64 = 8;
+
+/// Size of the `ResolvedLightSamplePacked` shader struct in bytes.
+const RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE: u64 = 24;
+
+/// Size of the `Reservoir` shader struct in bytes.
+const RESERVOIR_STRUCT_SIZE: u64 = 48;
+
+pub const LIGHT_TILE_BLOCKS: u64 = 128;
+pub const LIGHT_TILE_SAMPLES_PER_BLOCK: u64 = 1024;
+
+/// Amount of entries in the world cache (must be a power of 2, and >= 2^10)
+pub const WORLD_CACHE_SIZE: u64 = 2u64.pow(20);
+/// Sum of per-cell field sizes in `WorldCache`. Keep in sync with `realtime_bindings.wgsl`.
+const WORLD_CACHE_ENTRY_SIZE: u64 = 84;
+/// Size of the fixed `b` array (`array<u32, WORLD_CACHE_SIZE / 1024>`).
+const WORLD_CACHE_B_SIZE: u64 = (WORLD_CACHE_SIZE / 1024) * size_of::<u32>() as u64;
+/// Offset of `active_cells_count`.
+pub const WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET: u64 =
+ WORLD_CACHE_SIZE * WORLD_CACHE_ENTRY_SIZE + WORLD_CACHE_B_SIZE;
+/// Must stay under wgpu's default `max_storage_buffer_binding_size` (128 MiB or 2^27 bytes).
+pub const WORLD_CACHE_BUFFER_SIZE: u64 =
+ (WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET + size_of::<u32>() as u64).next_multiple_of(16);
+
+/// GPU representation of the user-configurable [`SolariLighting`] settings, plus
+/// per-frame state.
+///
+/// Field order and types must match the `SolariLightingSettings` struct in
+/// `realtime_bindings.wgsl`.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct SolariLightingUniforms {
+ confidence_weight_cap: f32,
+ primary_di_samples: u32,
+ secondary_di_samples: u32,
+ max_bounces: u32,
+ world_cache_max_temporal_samples: f32,
+ world_cache_direct_light_sample_count: u32,
+ world_cache_max_gi_ray_distance: f32,
+ world_cache_cell_updates_soft_target: u32,
+ world_cache_position_base_cell_size: f32,
+ world_cache_position_lod_scale: f32,
+ frame_rng: u32,
+ reset: u32,
+}
+
+impl SolariLightingUniforms {
+ fn new(settings: &SolariLighting, frame_count: u32, force_reset: bool) -> Self {
+ Self {
+ confidence_weight_cap: settings.confidence_weight_cap,
+ primary_di_samples: settings.primary_di_samples,
+ secondary_di_samples: settings.secondary_di_samples,
+ max_bounces: settings.max_bounces,
+ world_cache_max_temporal_samples: settings.world_cache_max_temporal_samples,
+ world_cache_direct_light_sample_count: settings.world_cache_direct_light_sample_count,
+ world_cache_max_gi_ray_distance: settings.world_cache_max_gi_ray_distance,
+ world_cache_cell_updates_soft_target: settings.world_cache_cell_updates_soft_target,
+ world_cache_position_base_cell_size: settings.world_cache_position_base_cell_size,
+ world_cache_position_lod_scale: settings.world_cache_position_lod_scale,
+ frame_rng: frame_count.wrapping_mul(5782582),
+ reset: (settings.reset || force_reset) as u32,
+ }
+ }
+}
+
+/// Declares to the raytracing scene whether any view needs last frame's TLAS and light ids.
+pub fn setup_raytracing_scene_needs_previous_frame_data(
+ views: Query<&SolariLighting>,
+ needs_previous_frame_data: Option<Res<RaytracingSceneNeedsPreviousFrameData>>,
+ mut commands: Commands,
+) {
+ let restir_used = views.iter().any(|solari_lighting| solari_lighting.restir);
+ match (restir_used, needs_previous_frame_data.is_some()) {
+ (true, false) => commands.insert_resource(RaytracingSceneNeedsPreviousFrameData),
+ (false, true) => commands.remove_resource::<RaytracingSceneNeedsPreviousFrameData>(),
+ _ => {}
+ }
+}
+
+/// Internal rendering resources used for Solari lighting.
+#[derive(Component)]
+pub struct SolariLightingResources {
+ pub constants: Buffer,
+ pub light_tile_samples: Buffer,
+ pub light_tile_resolved_samples: Buffer,
+ pub reservoirs: Option<SolariReservoirBuffers>,
+ pub world_cache: Buffer,
+ pub world_cache_active_cells_dispatch: Buffer,
+ pub view_size: UVec2,
+}
+
+pub struct SolariReservoirBuffers {
+ pub a: Buffer,
+ pub b: Buffer,
+}
+
+pub fn prepare_solari_lighting_resources(
+ #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))] query: Query<(
+ Entity,
+ &ExtractedCamera,
+ &SolariLighting,
+ Option<&SolariLightingResources>,
+ Option<&MainPassResolutionOverride>,
+ )>,
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] query: Query<(
+ Entity,
+ &ExtractedCamera,
+ &SolariLighting,
+ Option<&SolariLightingResources>,
+ Option<&MainPassResolutionOverride>,
+ Has<Dlss<DlssRayReconstructionFeature>>,
+ )>,
+ render_device: Res<RenderDevice>,
+ render_queue: Res<RenderQueue>,
+ frame_count: Res<FrameCount>,
+ mut commands: Commands,
+) {
+ for query_item in &query {
+ #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
+ let (entity, camera, solari_lighting, solari_lighting_resources, resolution_override) =
+ query_item;
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ let (
+ entity,
+ camera,
+ solari_lighting,
+ solari_lighting_resources,
+ resolution_override,
+ has_dlss_rr,
+ ) = query_item;
+
+ let Some(mut view_size) = camera.physical_viewport_size else {
+ continue;
+ };
+ if let Some(MainPassResolutionOverride(resolution_override)) = resolution_override {
+ view_size = *resolution_override;
+ }
+
+ let reusable = solari_lighting_resources.filter(|r| {
+ r.view_size == view_size && r.reservoirs.is_some() == solari_lighting.restir
+ });
+ let uniforms =
+ SolariLightingUniforms::new(solari_lighting, frame_count.0, reusable.is_none());
+
+ if let Some(solari_lighting_resources) = reusable {
+ // The constants uniform can change every frame, so always upload it.
+ render_queue.write_buffer(
+ &solari_lighting_resources.constants,
+ 0,
+ bytemuck::bytes_of(&uniforms),
+ );
+ continue;
+ }
+
+ let constants = render_device.create_buffer_with_data(&BufferInitDescriptor {
+ label: Some("solari_lighting_constants"),
+ contents: bytemuck::bytes_of(&uniforms),
+ usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
+ });
+
+ let light_tile_samples = render_device.create_buffer(&BufferDescriptor {
+ label: Some("solari_lighting_light_tile_samples"),
+ size: LIGHT_TILE_BLOCKS * LIGHT_TILE_SAMPLES_PER_BLOCK * LIGHT_SAMPLE_STRUCT_SIZE,
+ usage: BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ });
+
+ let light_tile_resolved_samples = render_device.create_buffer(&BufferDescriptor {
+ label: Some("solari_lighting_light_tile_resolved_samples"),
+ size: LIGHT_TILE_BLOCKS
+ * LIGHT_TILE_SAMPLES_PER_BLOCK
+ * RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE,
+ usage: BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ });
+
+ let reservoirs = solari_lighting.restir.then(|| {
+ let reservoirs_buffer = |name| {
+ render_device.create_buffer(&BufferDescriptor {
+ label: Some(name),
+ size: (view_size.x * view_size.y) as u64 * RESERVOIR_STRUCT_SIZE,
+ usage: BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ })
+ };
+ SolariReservoirBuffers {
+ a: reservoirs_buffer("solari_lighting_reservoirs_a"),
+ b: reservoirs_buffer("solari_lighting_reservoirs_b"),
+ }
+ });
+
+ let world_cache = render_device.create_buffer(&BufferDescriptor {
+ label: Some("solari_lighting_world_cache"),
+ size: WORLD_CACHE_BUFFER_SIZE,
+ usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
+ mapped_at_creation: false,
+ });
+
+ let world_cache_active_cells_dispatch = render_device.create_buffer(&BufferDescriptor {
+ label: Some("solari_lighting_world_cache_active_cells_dispatch"),
+ size: size_of::<[u32; 3]>() as u64,
+ usage: BufferUsages::INDIRECT | BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ });
+
+ commands.entity(entity).insert(SolariLightingResources {
+ constants,
+ light_tile_samples,
+ light_tile_resolved_samples,
+ reservoirs,
+ world_cache,
+ world_cache_active_cells_dispatch,
+ view_size,
+ });
+
+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
+ if has_dlss_rr {
+ let diffuse_albedo = render_device.create_texture(&TextureDescriptor {
+ label: Some("solari_lighting_diffuse_albedo"),
+ size: view_size.to_extents(),
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: TextureDimension::D2,
+ format: TextureFormat::Rgba8Unorm,
+ usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
+ view_formats: &[],
+ });
+ let diffuse_albedo_view = diffuse_albedo.create_view(&TextureViewDescriptor::default());
+
+ let specular_albedo = render_device.create_texture(&TextureDescriptor {
+ label: Some("solari_lighting_specular_albedo"),
+ size: view_size.to_extents(),
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: TextureDimension::D2,
+ format: TextureFormat::Rgba8Unorm,
+ usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
+ view_formats: &[],
+ });
+ let specular_albedo_view =
+ specular_albedo.create_view(&TextureViewDescriptor::default());
+
+ let normal_roughness = render_device.create_texture(&TextureDescriptor {
+ label: Some("solari_lighting_normal_roughness"),
+ size: view_size.to_extents(),
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: TextureDimension::D2,
+ format: TextureFormat::Rgba16Float,
+ usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
+ view_formats: &[],
+ });
+ let normal_roughness_view =
+ normal_roughness.create_view(&TextureViewDescriptor::default());
+
+ let dlss_rr_depth = render_device.create_texture(&TextureDescriptor {
+ label: Some("solari_lighting_dlss_rr_depth"),
+ size: view_size.to_extents(),
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: TextureDimension::D2,
+ format: TextureFormat::R32Float,
+ usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
+ view_formats: &[],
+ });
+ let dlss_rr_depth_view = dlss_rr_depth.create_view(&TextureViewDescriptor::default());
+
+ let specular_motion_vectors = render_device.create_texture(&TextureDescriptor {
+ label: Some("solari_lighting_specular_motion_vectors"),
+ size: view_size.to_extents(),
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: TextureDimension::D2,
+ format: TextureFormat::Rg16Float,
+ usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
+ view_formats: &[],
+ });
+ let specular_motion_vectors_view =
+ specular_motion_vectors.create_view(&TextureViewDescriptor::default());
+
+ commands
+ .entity(entity)
+ .insert(ViewDlssRayReconstructionTextures {
+ diffuse_albedo: CachedTexture {
+ texture: diffuse_albedo,
+ default_view: diffuse_albedo_view,
+ },
+ specular_albedo: CachedTexture {
+ texture: specular_albedo,
+ default_view: specular_albedo_view,
+ },
+ normal_roughness: CachedTexture {
+ texture: normal_roughness,
+ default_view: normal_roughness_view,
+ },
+ depth: CachedTexture {
+ texture: dlss_rr_depth,
+ default_view: dlss_rr_depth_view,
+ },
+ specular_motion_vectors: CachedTexture {
+ texture: specular_motion_vectors,
+ default_view: specular_motion_vectors_view,
+ },
+ });
+ }
+ }
+}
diff --git a/vendor/bevy_solari/src/realtime/presample_light_tiles.wesl b/vendor/bevy_solari/src/realtime/presample_light_tiles.wesl
new file mode 100644
index 00000000..be26d89a
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/presample_light_tiles.wesl
@@ -0,0 +1,40 @@
+// https://cwyman.org/papers/hpg21_rearchitectingReSTIR.pdf
+
+import bevy_pbr::render::rgb9e5::{vec3_to_rgb9e5_, rgb9e5_to_vec3_};
+import bevy_render::utils::{octahedral_encode, octahedral_decode};
+import package::scene::sampling::{generate_random_light_sample, ResolvedLightSample};
+import package::realtime::bindings::{light_tile_samples, light_tile_resolved_samples, view, constants, ResolvedLightSamplePacked};
+
+enable wgpu_ray_query;
+
+@compute @workgroup_size(1024, 1, 1)
+fn presample_light_tiles(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(local_invocation_index) sample_index: u32) {
+ let tile_id = workgroup_id.x;
+ var rng = (tile_id * 0x9E3779B9u) + sample_index + constants.frame_rng;
+
+ let sample = generate_random_light_sample(&rng);
+
+ let i = (tile_id * 1024u) + sample_index;
+ light_tile_samples[i] = sample.light_sample;
+ light_tile_resolved_samples[i] = pack_resolved_light_sample(sample.resolved_light_sample);
+}
+
+fn pack_resolved_light_sample(sample: ResolvedLightSample) -> ResolvedLightSamplePacked {
+ return ResolvedLightSamplePacked(
+ sample.world_position.x,
+ sample.world_position.y,
+ sample.world_position.z,
+ pack2x16unorm(octahedral_encode(sample.world_normal)),
+ vec3_to_rgb9e5_(log2(sample.radiance * view.exposure + 1.0)),
+ sample.inverse_pdf * select(1.0, -1.0, sample.world_position.w == 0.0),
+ );
+}
+
+fn unpack_resolved_light_sample(packed: ResolvedLightSamplePacked, exposure: f32) -> ResolvedLightSample {
+ return ResolvedLightSample(
+ vec4(packed.world_position_x, packed.world_position_y, packed.world_position_z, select(1.0, 0.0, packed.inverse_pdf < 0.0)),
+ octahedral_decode(unpack2x16unorm(packed.world_normal)),
+ (exp2(rgb9e5_to_vec3_(packed.radiance)) - 1.0) / exposure,
+ abs(packed.inverse_pdf),
+ );
+}
diff --git a/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.wesl b/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.wesl
new file mode 100644
index 00000000..906096f2
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.wesl
@@ -0,0 +1,269 @@
+import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
+import bevy_pbr::deferred::types::unpack_24bit_normal;
+import bevy_pbr::render::pbr_functions::{calculate_diffuse_color, calculate_F0, calculate_F0_dielectric};
+import bevy_render::utils::octahedral_decode;
+import package::realtime::gbuffer_utils::gpixel_resolve;
+import package::realtime::bindings::{gbuffer, depth_buffer, load_motion_vector, motion_vectors, previous_view, view, diffuse_albedo, specular_albedo, normal_roughness, dlss_rr_depth, specular_motion_vectors};
+import package::scene::brdf::{evaluate_specular_brdf, F_AB, lobe_reflectances};
+import package::scene::bindings::{MIRROR_ROUGHNESS_THRESHOLD, ResolvedMaterial, ResolvedRayHitFull};
+
+enable wgpu_ray_query;
+
+/// A surface is replaced outright only when nearly all of its reflectance leaves through the delta
+/// lobe.
+const FULL_REPLACEMENT_FRACTION = 0.9;
+
+/// How far a reflector's virtual image may shift between neighboring pixels, as a fraction of the
+/// virtual distance itself, before the surface is treated as too curved to replace.
+const MAX_VIRTUAL_DEPTH_JITTER = 0.002;
+
+/// Even a perfectly flat surface measures a small nonzero normal change, because G-buffer normals are
+/// 24-bit octahedral and neighboring texels round differently.
+const NORMAL_QUANTIZATION_FLOOR = 0.002;
+
+/// Distance, in meters, standing in for "infinitely far" when a mirror ray finds nothing.
+const ENVIRONMENT_VIRTUAL_DISTANCE = 10000.0;
+
+@compute @workgroup_size(8, 8, 1)
+fn resolve_dlss_rr_textures(@builtin(global_invocation_id) global_id: vec3<u32>) {
+ let pixel_id = global_id.xy;
+ if any(pixel_id >= vec2u(view.main_pass_viewport.zw)) { return; }
+
+ let depth = textureLoad(depth_buffer, global_id.xy, 0);
+ let surface_motion_vector = load_motion_vector(pixel_id);
+
+ textureStore(dlss_rr_depth, pixel_id, vec4(depth));
+
+ if depth == 0.0 {
+ textureStore(specular_motion_vectors, pixel_id, vec4(surface_motion_vector, vec2(0.0)));
+ textureStore(diffuse_albedo, pixel_id, vec4(0.0));
+ textureStore(specular_albedo, pixel_id, vec4(0.5));
+ textureStore(normal_roughness, pixel_id, vec4(0.0, 0.0, 1.0, 0.0));
+ return;
+ }
+
+ let surface = gpixel_resolve(textureLoad(gbuffer, pixel_id, 0), depth, pixel_id, view.main_pass_viewport.zw, view.world_from_clip);
+ let F0 = calculate_F0(surface.material.base_color, surface.material.metallic, vec3(surface.material.reflectance));
+ let wo = normalize(view.world_position - surface.world_position);
+
+ textureStore(diffuse_albedo, pixel_id, vec4(calculate_diffuse_color(surface.material.base_color, surface.material.metallic, 0.0, 0.0), 0.0));
+ textureStore(specular_albedo, pixel_id, vec4(env_brdf_approx2(F0, surface.material.roughness, surface.world_normal, wo), 0.0));
+ textureStore(normal_roughness, pixel_id, vec4(surface.world_normal, surface.material.perceptual_roughness));
+
+ // Resetting to the specular motion vector on the frames we draw a diffuse lobe means we
+ // wouldn't be writing the motion vectors that frame, so it would alternate the guide between
+ // to values, and the denoiser blurs the reflection rather than reprojecting it.
+ if !needs_specular_motion_vector(surface.material.roughness) {
+ textureStore(specular_motion_vectors, pixel_id, vec4(surface_motion_vector, vec2(0.0)));
+ }
+}
+
+fn needs_specular_motion_vector(roughness: f32) -> bool {
+ return roughness <= 0.0625;
+}
+
+/// Carried across every bounce of the path walk, so anything derivable from a value the walk already
+/// holds is derived at the end instead of stored. What is left is only what the walk itself produces.
+struct PsrState {
+ finished: bool,
+ /// Whether this pixel's surface is being swapped out for the reflected one, or is only having its
+ /// reflection's motion described. Keyed on the primary surface only, and false for anything glossy.
+ replace_fully: bool,
+ /// The chain's cumulative transform - the product of one Householder reflection per mirror, in
+ /// chain order - stored as a rotor plus the parity of the reflection count rather than as the 3x3
+ /// matrix it denotes.
+ mirror_rotor: vec4<f32>,
+ mirror_parity_odd: bool,
+ /// Distance traveled since the primary surface, camera through every mirror. Not the total path
+ /// length: keeping the reflection's own share means the primary distance is only ever added, never
+ /// subtracted back out, so it can be recovered at the end without the two disagreeing.
+ reflection_length: f32,
+ /// Product of the Fresnel term at each mirror in the chain: what the reflected surface's color is
+ /// multiplied by on its way back to the eye.
+ throughput: vec3<f32>,
+}
+
+fn psr_init(world_normal: vec3<f32>, material: ResolvedMaterial) -> PsrState {
+ var psr: PsrState;
+ psr.finished = !needs_specular_motion_vector(material.roughness);
+ psr.replace_fully = is_delta_mirror(material);
+ // The chain opens with the primary surface's own reflection, so parity starts odd.
+ psr.mirror_rotor = mirror_chain_rotor(world_normal, false);
+ psr.mirror_parity_odd = true;
+ psr.reflection_length = 0.0;
+ psr.throughput = vec3(1.0);
+ return psr;
+}
+
+/// Fold one more mirror into the chain, equivalent to right-multiplying the chain's matrix by this
+/// mirror's Householder reflection.
+/// https://en.wikipedia.org/wiki/Householder_transformation
+///
+/// A product of k Householder reflections is orthogonal with determinant (-1)^k, so it is a rotation
+/// when k is even, and a rotation composed with any one fixed reflection when k is odd.
+fn psr_chain_mirror(psr: PsrState, plane_normal: vec3<f32>) -> PsrState {
+ var chained = psr;
+ chained.mirror_rotor = quaternion_multiply(psr.mirror_rotor, mirror_chain_rotor(plane_normal, psr.mirror_parity_odd));
+ chained.mirror_parity_odd = !psr.mirror_parity_odd;
+ return chained;
+}
+
+fn psr_environment_miss(pixel_id: vec2<u32>, primary_wo: vec3<f32>) {
+ let far_position = view.world_position - (primary_wo * ENVIRONMENT_VIRTUAL_DISTANCE);
+ textureStore(specular_motion_vectors, pixel_id, vec4(calculate_motion_vector(far_position, far_position), vec2(0.0)));
+}
+
+/// Primary surface replacement for perfect mirrors. The reflection chain has been followed to its
+/// first non-mirror hit; write that surface's attributes, reflected into the mirror's virtual space,
+/// to the DLSS RR guide buffers so the denoiser treats this pixel as directly seeing it.
+/// https://developer.nvidia.com/blog/rendering-perfect-reflections-and-refractions-in-path-traced-games/#primary_surface_replacement
+fn replace_primary_surface(
+ pixel_id: vec2<u32>,
+ psr: PsrState,
+ ray_hit: ResolvedRayHitFull,
+ primary_material: ResolvedMaterial,
+ primary_world_position: vec3<f32>,
+ primary_normal: vec3<f32>,
+ primary_wo: vec3<f32>,
+ primary_F_ab: vec2<f32>,
+) {
+ let primary_distance = length(primary_world_position - view.world_position);
+ let path_length = primary_distance + psr.reflection_length;
+
+ // Too curved to track the reflection; fall back to the surface's own motion so the guide is not stale
+ if psr.replace_fully && 2.0 * reflector_curvature(pixel_id, primary_normal) * psr.reflection_length > MAX_VIRTUAL_DEPTH_JITTER * path_length {
+ textureStore(specular_motion_vectors, pixel_id, vec4(load_motion_vector(pixel_id), vec2(0.0)));
+ return;
+ }
+
+ let virtual_position = primary_world_position - (primary_wo * psr.reflection_length);
+ let world_motion = ray_hit.previous_frame_world_position - ray_hit.world_position;
+ let virtual_previous_position = virtual_position + apply_mirror_chain(psr, world_motion);
+ let specular_motion_vector = calculate_motion_vector(virtual_position, virtual_previous_position);
+
+ textureStore(specular_motion_vectors, pixel_id, vec4(specular_motion_vector, vec2(0.0)));
+
+ if !psr.replace_fully {
+ return;
+ }
+
+ let wo = normalize(view.world_position - virtual_position);
+ let virtual_normal = normalize(apply_mirror_chain(psr, ray_hit.world_normal));
+
+ let primary_depth = textureLoad(depth_buffer, pixel_id, 0);
+ textureStore(dlss_rr_depth, pixel_id, vec4(primary_depth * primary_distance / path_length));
+ @if(MOTION_VECTORS_READ_WRITE)
+ textureStore(motion_vectors, pixel_id, vec4(specular_motion_vector, vec2(0.0)));
+
+ let reflected_diffuse = calculate_diffuse_color(ray_hit.material.base_color, ray_hit.material.metallic, 0.0, 0.0);
+ let reflected_F0 = calculate_F0(ray_hit.material.base_color, ray_hit.material.metallic, vec3(ray_hit.material.reflectance));
+ let reflected_specular = env_brdf_approx2(reflected_F0, ray_hit.material.roughness, virtual_normal, wo);
+
+ let own_diffuse = calculate_diffuse_color(primary_material.base_color, primary_material.metallic, 0.0, 0.0);
+ let own_F0 = calculate_F0(primary_material.base_color, primary_material.metallic, vec3(primary_material.reflectance));
+ let own_specular = env_brdf_approx2(own_F0, primary_material.roughness, primary_normal, primary_wo);
+
+ let specular_fraction = specular_fraction(primary_material, primary_F_ab);
+
+ textureStore(diffuse_albedo, pixel_id, vec4(psr.throughput * reflected_diffuse + own_diffuse, 0.0));
+ textureStore(specular_albedo, pixel_id, vec4(mix(own_specular, psr.throughput * reflected_specular, specular_fraction), 0.0));
+ textureStore(normal_roughness, pixel_id, vec4(virtual_normal, ray_hit.material.perceptual_roughness));
+}
+
+fn primary_surface_glossy(material: ResolvedMaterial) -> bool {
+ return material.roughness > MIRROR_ROUGHNESS_THRESHOLD;
+}
+
+fn is_delta_mirror(material: ResolvedMaterial) -> bool {
+ return material.roughness <= MIRROR_ROUGHNESS_THRESHOLD
+ && specular_fraction(material, F_AB(material.perceptual_roughness, 1.0)) >= FULL_REPLACEMENT_FRACTION;
+}
+
+/// Share of a surface's total reflectance that leaves through the specular lobe, in 0..1.
+fn specular_fraction(material: ResolvedMaterial, F_ab: vec2<f32>) -> f32 {
+ let rho = lobe_reflectances(material.base_color, calculate_F0_dielectric(vec3(material.reflectance)), material, F_ab);
+ let specular_luminance = luminance(rho.specular);
+ return specular_luminance / max(specular_luminance + luminance(rho.diffuse), 0.0001);
+}
+
+fn psr_bounce_reflectance(wo: vec3<f32>, wi: vec3<f32>, normal: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>, delta: bool) -> vec3<f32> {
+ if delta {
+ return evaluate_specular_brdf(wo, wi, normal, material, F_ab);
+ }
+ return lobe_reflectances(material.base_color, calculate_F0_dielectric(vec3(material.reflectance)), material, F_ab).specular;
+}
+
+/// Angle, in radians, that the shading normal changes over one pixel in screen space.
+fn reflector_curvature(pixel_id: vec2<u32>, normal: vec3<f32>) -> f32 {
+ let max_pixel_id = vec2<u32>(view.main_pass_viewport.zw) - vec2(1u);
+ let right = load_gbuffer_normal(min(pixel_id + vec2(1u, 0u), max_pixel_id));
+ let down = load_gbuffer_normal(min(pixel_id + vec2(0u, 1u), max_pixel_id));
+ let min_cos = min(dot(normal, right), dot(normal, down));
+ let angle = sqrt(max(0.0, 2.0 * (1.0 - min_cos)));
+ return max(0.0, angle - NORMAL_QUANTIZATION_FLOOR);
+}
+
+fn load_gbuffer_normal(pixel_id: vec2<u32>) -> vec3<f32> {
+ return octahedral_decode(unpack_24bit_normal(textureLoad(gbuffer, pixel_id, 0).a));
+}
+
+fn apply_mirror_chain(psr: PsrState, v: vec3<f32>) -> vec3<f32> {
+ var reflected = v;
+ if psr.mirror_parity_odd {
+ reflected.z = -reflected.z;
+ }
+ let t = 2.0 * cross(psr.mirror_rotor.xyz, reflected);
+ return reflected + psr.mirror_rotor.w * t + cross(psr.mirror_rotor.xyz, t);
+}
+
+/// The rotation half of `H(n) * F` at even parity, or of `F * H(n)` at odd, where `H(n)` is the
+/// Householder reflection about `plane_normal` and `F` the fixed z-axis one.
+fn mirror_chain_rotor(plane_normal: vec3<f32>, parity_odd: bool) -> vec4<f32> {
+ if parity_odd {
+ return vec4(plane_normal.y, -plane_normal.x, 0.0, plane_normal.z);
+ }
+ return vec4(-plane_normal.y, plane_normal.x, 0.0, plane_normal.z);
+}
+
+fn quaternion_multiply(a: vec4<f32>, b: vec4<f32>) -> vec4<f32> {
+ return vec4(a.w * b.xyz + b.w * a.xyz + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz));
+}
+
+fn calculate_motion_vector(world_position: vec3<f32>, previous_world_position: vec3<f32>) -> vec2<f32> {
+ let clip_position_t = view.unjittered_clip_from_world * vec4(world_position, 1.0);
+ let clip_position = clip_position_t.xy / clip_position_t.w;
+ let previous_clip_position_t = previous_view.unjittered_clip_from_world * vec4(previous_world_position, 1.0);
+ let previous_clip_position = previous_clip_position_t.xy / previous_clip_position_t.w;
+ // Motion vectors are UV-space offsets in [-1, 1], from one corner to the diagonally-opposite one.
+ // A clip-space diagonal difference is in [-2, 2], so scale by 0.5, and flip y since V goes down
+ // where clip-space y goes up.
+ return (clip_position - previous_clip_position) * vec2(0.5, -0.5);
+}
+
+fn env_brdf_approx2(specular_color: vec3<f32>, alpha: f32, N: vec3<f32>, V: vec3<f32>) -> vec3<f32> {
+ let NoV = abs(dot(N, V));
+
+ var X: vec4<f32>;
+ X.x = 1.0;
+ X.y = NoV;
+ X.z = NoV * NoV;
+ X.w = NoV * X.z;
+
+ var Y: vec4<f32>;
+ Y.x = 1.0;
+ Y.y = alpha;
+ Y.z = alpha * alpha;
+ Y.w = alpha * Y.z;
+
+ let M1 = mat2x2<f32>(0.99044, 1.29678, -1.28514, -0.755907);
+ let M2 = mat3x3<f32>(1.0, 20.3225, 121.563, 2.92338, -27.0302, 626.13, 59.4188, 222.592, 316.627);
+ let M3 = mat2x2<f32>(0.0365463, 9.0632, 3.32707, -9.04756);
+ let M4 = mat3x3<f32>(1.0, 9.04401, 5.56589, 3.59685, -16.3174, 19.7886, -1.36772, 9.22949, -20.2123);
+
+ var bias = dot(M1 * X.xy, Y.xy) / dot(M2 * X.xyw, Y.xyw);
+ let scale = dot(M3 * X.xy, Y.xy) / dot(M4 * X.xzw, Y.xyw);
+
+ bias *= saturate(specular_color.g * 50.0);
+
+ return fma(specular_color, vec3(max(0.0, scale)), vec3(max(0.0, bias)));
+}
diff --git a/vendor/bevy_solari/src/realtime/restir.wesl b/vendor/bevy_solari/src/realtime/restir.wesl
new file mode 100644
index 00000000..8211b294
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/restir.wesl
@@ -0,0 +1,364 @@
+//! https://intro-to-restir.cwyman.org/presentations/2023ReSTIR_Course_Notes.pdf
+
+import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
+import bevy_pbr::render::utils::{rand_f, rand_u, sample_disk};
+import bevy_render::utils::octahedral_decode;
+import package::scene::brdf::{brdf_pdf, evaluate_brdf, F_AB};
+import package::realtime::gbuffer_utils::{gpixel_resolve, permute_pixel, pixel_dissimilar};
+import package::realtime::initial_path::{generate_initial_path, InitialSamplingResult};
+import package::realtime::bindings::{depth_buffer, empty_reservoir, gbuffer, load_motion_vector, previous_depth_buffer, previous_gbuffer, previous_view, reservoirs_a, reservoirs_b, Reservoir, constants, view, view_output};
+import package::scene::sampling::{balance_heuristic, calculate_resolved_light_contribution, isinf, isnan, LightSample, NULL_LIGHT_ID, power_heuristic, resolve_light_sample, ResolvedLightSample, trace_visibility, trace_visibility_previous_frame};
+import package::scene::bindings::{light_sources, LIGHT_NOT_PRESENT_THIS_FRAME, previous_frame_light_id_translations, RAY_T_MAX, RAY_T_MIN, ResolvedMaterial};
+import package::realtime::world_cache_query::{query_world_cache, WORLD_CACHE_CELL_LIFETIME};
+
+enable wgpu_ray_query;
+
+const SPATIAL_REUSE_RADIUS_PIXELS = 30.0;
+
+@compute @workgroup_size(8, 8, 1)
+fn initial_and_temporal(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) global_id: vec3<u32>) {
+ if any(global_id.xy >= vec2u(view.main_pass_viewport.zw)) { return; }
+
+ let pixel_index = global_id.x + global_id.y * u32(view.main_pass_viewport.z);
+ var rng = pixel_index + constants.frame_rng;
+
+ let depth = textureLoad(depth_buffer, global_id.xy, 0);
+ if depth == 0.0 {
+ reservoirs_b[pixel_index] = empty_reservoir();
+ return;
+ }
+ let surface = gpixel_resolve(textureLoad(gbuffer, global_id.xy, 0), depth, global_id.xy, view.main_pass_viewport.zw, view.world_from_clip);
+
+ let initial = generate_initial_path(surface.world_position, surface.world_normal, surface.material, workgroup_id.xy, global_id.xy, &rng);
+ textureStore(view_output, global_id.xy, vec4(initial.radiance, 0.0));
+
+ let temporal = load_temporal_reservoir(global_id.xy, depth, surface.world_position, surface.world_normal);
+ let previous_camera_homogeneous = previous_view.world_from_clip * (previous_view.clip_from_view * vec4(0.0, 0.0, 0.0, 1.0));
+ let previous_camera_world_position = previous_camera_homogeneous.xyz / previous_camera_homogeneous.w;
+ let merge_result = merge_reservoirs(initial.reservoir, surface.world_position, surface.world_normal, surface.material,
+ temporal.reservoir, temporal.world_position, temporal.world_normal, temporal.material, previous_camera_world_position, &rng);
+
+ reservoirs_b[pixel_index] = merge_result.merged_reservoir;
+}
+
+@compute @workgroup_size(8, 8, 1)
+fn spatial_and_shade(@builtin(global_invocation_id) global_id: vec3<u32>) {
+ if any(global_id.xy >= vec2u(view.main_pass_viewport.zw)) { return; }
+
+ let pixel_index = global_id.x + global_id.y * u32(view.main_pass_viewport.z);
+ var rng = pixel_index + constants.frame_rng + 0x6A09E667u;
+
+ let depth = textureLoad(depth_buffer, global_id.xy, 0);
+ if depth == 0.0 {
+ reservoirs_a[pixel_index] = empty_reservoir();
+ return;
+ }
+ let surface = gpixel_resolve(textureLoad(gbuffer, global_id.xy, 0), depth, global_id.xy, view.main_pass_viewport.zw, view.world_from_clip);
+
+ let input_reservoir = reservoirs_b[pixel_index];
+ let spatial = load_spatial_reservoir(global_id.xy, depth, surface.world_position, surface.world_normal, &rng);
+ let merge_result = merge_reservoirs(input_reservoir, surface.world_position, surface.world_normal, surface.material,
+ spatial.reservoir, spatial.world_position, spatial.world_normal, spatial.material, view.world_position, &rng);
+
+ reservoirs_a[pixel_index] = merge_result.merged_reservoir;
+
+ var pixel_color = merge_result.selected_sample_brdf_radiance * merge_result.merged_reservoir.unbiased_contribution_weight;
+ pixel_color += surface.material.emissive;
+ pixel_color += textureLoad(view_output, global_id.xy).rgb;
+ pixel_color *= view.exposure;
+ textureStore(view_output, global_id.xy, vec4(pixel_color, 1.0));
+
+ @if(VISUALIZE_WORLD_CACHE)
+ textureStore(view_output, global_id.xy, vec4(query_world_cache(surface.world_position, surface.world_normal, view.world_position, RAY_T_MAX, WORLD_CACHE_CELL_LIFETIME, &rng) * view.exposure, 1.0));
+}
+
+fn load_temporal_reservoir(pixel_id: vec2<u32>, depth: f32, world_position: vec3<f32>, world_normal: vec3<f32>) -> NeighborInfo {
+ if bool(constants.reset) {
+ return NeighborInfo(empty_reservoir(), vec3(0.0), vec3(0.0), empty_material());
+ }
+
+ let motion_vector = load_motion_vector(pixel_id);
+ let temporal_pixel_id_float = round(vec2<f32>(pixel_id) - (motion_vector * view.main_pass_viewport.zw));
+
+ // If reprojection lands off-screen, fall back to this pixel's own previous reservoir rather than
+ // dropping history. The dissimilarity check below still validates the surface, and a same-pixel
+ // guess that passes it beats restarting from a confidence-1 reservoir at the screen edge.
+ var point_temporal_pixel_id = pixel_id;
+ if all(temporal_pixel_id_float >= vec2(0.0)) && all(temporal_pixel_id_float < view.main_pass_viewport.zw) {
+ point_temporal_pixel_id = vec2<u32>(temporal_pixel_id_float);
+ }
+
+ var permute_rng = constants.frame_rng;
+ let permuted_temporal_pixel_id = permute_pixel(point_temporal_pixel_id, rand_u(&permute_rng), view.main_pass_viewport.zw);
+
+ // Check if the pixel features have changed heavily between the current and previous frame
+ let temporal_depth = textureLoad(previous_depth_buffer, permuted_temporal_pixel_id, 0);
+ let temporal_surface = gpixel_resolve(textureLoad(previous_gbuffer, permuted_temporal_pixel_id, 0), temporal_depth, permuted_temporal_pixel_id, view.main_pass_viewport.zw, previous_view.world_from_clip);
+ if pixel_dissimilar(depth, world_position, temporal_surface.world_position, world_normal, temporal_surface.world_normal, view) {
+ return NeighborInfo(empty_reservoir(), vec3(0.0), vec3(0.0), empty_material());
+ }
+
+ let temporal_pixel_index = permuted_temporal_pixel_id.x + permuted_temporal_pixel_id.y * u32(view.main_pass_viewport.z);
+ var temporal = NeighborInfo(reservoirs_a[temporal_pixel_index], temporal_surface.world_position, temporal_surface.world_normal, temporal_surface.material);
+
+ // Check if the light selected in the previous frame no longer exists in the current frame (e.g. entity despawned)
+ if temporal.reservoir.light_sample.light_id != NULL_LIGHT_ID {
+ let previous_light_id = temporal.reservoir.light_sample.light_id >> 16u;
+ let triangle_id = temporal.reservoir.light_sample.light_id & 0xFFFFu;
+ let light_id = previous_frame_light_id_translations[previous_light_id];
+ if light_id == LIGHT_NOT_PRESENT_THIS_FRAME {
+ return NeighborInfo(empty_reservoir(), vec3(0.0), vec3(0.0), empty_material());
+ }
+ temporal.reservoir.light_sample.light_id = (light_id << 16u) | triangle_id;
+ }
+
+ temporal.reservoir.confidence_weight = min(temporal.reservoir.confidence_weight, constants.confidence_weight_cap);
+
+ return temporal;
+}
+
+fn load_spatial_reservoir(pixel_id: vec2<u32>, depth: f32, world_position: vec3<f32>, world_normal: vec3<f32>, rng: ptr<function, u32>) -> NeighborInfo {
+ for (var i = 0u; i < 5u; i++) {
+ let spatial_pixel_id = get_neighbor_pixel_id(pixel_id, SPATIAL_REUSE_RADIUS_PIXELS, rng);
+
+ if all(spatial_pixel_id == pixel_id) {
+ continue;
+ }
+
+ let spatial_depth = textureLoad(depth_buffer, spatial_pixel_id, 0);
+ let spatial_surface = gpixel_resolve(textureLoad(gbuffer, spatial_pixel_id, 0), spatial_depth, spatial_pixel_id, view.main_pass_viewport.zw, view.world_from_clip);
+ if pixel_dissimilar(depth, world_position, spatial_surface.world_position, world_normal, spatial_surface.world_normal, view) {
+ continue;
+ }
+
+ let spatial_pixel_index = spatial_pixel_id.x + spatial_pixel_id.y * u32(view.main_pass_viewport.z);
+ return NeighborInfo(reservoirs_b[spatial_pixel_index], spatial_surface.world_position, spatial_surface.world_normal, spatial_surface.material);
+ }
+
+ return NeighborInfo(empty_reservoir(), world_position, world_normal, empty_material());
+}
+
+fn get_neighbor_pixel_id(center_pixel_id: vec2<u32>, search_radius: f32, rng: ptr<function, u32>) -> vec2<u32> {
+ var spatial_id = vec2<f32>(center_pixel_id) + sample_disk(search_radius, rng);
+ spatial_id = clamp(spatial_id, vec2(0.0), view.main_pass_viewport.zw - 1.0);
+ return vec2<u32>(spatial_id);
+}
+
+struct NeighborInfo {
+ reservoir: Reservoir,
+ world_position: vec3<f32>,
+ world_normal: vec3<f32>,
+ material: ResolvedMaterial,
+}
+
+fn empty_material() -> ResolvedMaterial {
+ return ResolvedMaterial(vec3(0.0), vec3(0.0), 0.0, 0.0, 0.0, 0.0);
+}
+
+fn jacobian(
+ new_world_position: vec3<f32>,
+ original_world_position: vec3<f32>,
+ sample_point_world_position: vec3<f32>,
+ sample_point_world_normal: vec3<f32>,
+) -> f32 {
+ let r = new_world_position - sample_point_world_position;
+ let q = original_world_position - sample_point_world_position;
+ let rl = length(r);
+ let ql = length(q);
+ let phi_r = saturate(dot(r / rl, sample_point_world_normal));
+ let phi_q = saturate(dot(q / ql, sample_point_world_normal));
+ let jacobian = (phi_r * ql * ql) / (phi_q * rl * rl);
+ return select(jacobian, 0.0, isinf(jacobian) || isnan(jacobian));
+}
+
+struct ReservoirMergeResult {
+ merged_reservoir: Reservoir,
+ selected_sample_brdf_radiance: vec3<f32>,
+}
+
+fn merge_reservoirs(
+ canonical_reservoir: Reservoir,
+ canonical_world_position: vec3<f32>,
+ canonical_world_normal: vec3<f32>,
+ canonical_material: ResolvedMaterial,
+ other_reservoir: Reservoir,
+ other_world_position: vec3<f32>,
+ other_world_normal: vec3<f32>,
+ other_material: ResolvedMaterial,
+ other_view_position: vec3<f32>,
+ rng: ptr<function, u32>,
+) -> ReservoirMergeResult {
+ var canonical_resolved: ResolvedLightSample;
+ if canonical_reservoir.light_sample.light_id != NULL_LIGHT_ID {
+ canonical_resolved = resolve_light_sample(canonical_reservoir.light_sample, light_sources[canonical_reservoir.light_sample.light_id >> 16u]);
+ }
+
+ let canonical_wo = normalize(view.world_position - canonical_world_position);
+ let canonical_NdotV = max(dot(canonical_world_normal, canonical_wo), 0.0001);
+ let canonical_F_ab = F_AB(canonical_material.perceptual_roughness, canonical_NdotV);
+ let canonical_sample_at_canonical = reservoir_contribution(canonical_reservoir, canonical_resolved, canonical_world_position, canonical_world_normal, canonical_wo, canonical_material, canonical_F_ab);
+
+ // Skip resampling empty reservoirs
+ if other_reservoir.confidence_weight == 0.0 {
+ return ReservoirMergeResult(canonical_reservoir, canonical_sample_at_canonical.brdf_radiance);
+ }
+
+ var other_resolved: ResolvedLightSample;
+ if other_reservoir.light_sample.light_id != NULL_LIGHT_ID {
+ other_resolved = resolve_light_sample(other_reservoir.light_sample, light_sources[other_reservoir.light_sample.light_id >> 16u]);
+ }
+ let other_wo = normalize(other_view_position - other_world_position);
+ let other_NdotV = max(dot(other_world_normal, other_wo), 0.0001);
+ let other_F_ab = F_AB(other_material.perceptual_roughness, other_NdotV);
+
+ // Contributions for resampling and MIS
+ var other_sample_at_canonical = reservoir_contribution(other_reservoir, other_resolved, canonical_world_position, canonical_world_normal, canonical_wo, canonical_material, canonical_F_ab);
+ var canonical_sample_at_other = reservoir_contribution(canonical_reservoir, canonical_resolved, other_world_position, other_world_normal, other_wo, other_material, other_F_ab);
+ let other_sample_at_other = reservoir_contribution(other_reservoir, other_resolved, other_world_position, other_world_normal, other_wo, other_material, other_F_ab);
+
+ // Jacobians for resampling and MIS. Light samples don't need a reprojection jacobian,
+ // since calculate_resolved_light_contribution already accounts for the shading point's geometry.
+ var other_sample_at_canonical_jacobian = 1.0;
+ if other_reservoir.light_sample.light_id == NULL_LIGHT_ID {
+ other_sample_at_canonical_jacobian = jacobian(
+ canonical_world_position,
+ other_world_position,
+ other_reservoir.sample_point_world_position,
+ octahedral_decode(other_reservoir.sample_point_world_normal)
+ );
+ }
+ var canonical_sample_at_other_jacobian = 1.0;
+ if canonical_reservoir.light_sample.light_id == NULL_LIGHT_ID {
+ canonical_sample_at_other_jacobian = jacobian(
+ other_world_position,
+ canonical_world_position,
+ canonical_reservoir.sample_point_world_position,
+ octahedral_decode(canonical_reservoir.sample_point_world_normal)
+ );
+ }
+
+ // Don't merge samples with huge jacobians, as it explodes the variance
+ if other_sample_at_canonical_jacobian < 0.125 || other_sample_at_canonical_jacobian > 8.0 {
+ other_sample_at_canonical_jacobian = 0.0;
+ }
+ if canonical_sample_at_other_jacobian < 0.125 || canonical_sample_at_other_jacobian > 8.0 {
+ canonical_sample_at_other_jacobian = 0.0;
+ }
+
+ // Visibility for the cross-domain targets
+ if other_sample_at_canonical.target_function > 0.0 && other_sample_at_canonical_jacobian > 0.0 {
+ let visibility = trace_visibility(canonical_world_position + canonical_world_normal * RAY_T_MIN, other_sample_at_canonical.sample_world_position);
+ other_sample_at_canonical.target_function *= visibility;
+ }
+ if canonical_sample_at_other.target_function > 0.0 && canonical_sample_at_other_jacobian > 0.0 {
+ @if(SPATIAL_MERGE)
+ let visibility = trace_visibility(other_world_position + other_world_normal * RAY_T_MIN, canonical_sample_at_other.sample_world_position);
+ @else
+ let visibility = trace_visibility_previous_frame(other_world_position + other_world_normal * RAY_T_MIN, canonical_sample_at_other.sample_world_position);
+ canonical_sample_at_other.target_function *= visibility;
+ }
+
+ // Defensive balance heuristic MIS (for spatial reuse only)
+ let total_confidence_weight = canonical_reservoir.confidence_weight + other_reservoir.confidence_weight;
+ var defensive_t_c = 0.0;
+ @if(SPATIAL_MERGE)
+ defensive_t_c = select(1.0, canonical_reservoir.confidence_weight / total_confidence_weight, total_confidence_weight > 0.0);
+
+ // Resampling weight for canonical sample
+ let canonical_balance_mis_weight = balance_heuristic(
+ canonical_reservoir.confidence_weight * canonical_sample_at_canonical.target_function,
+ other_reservoir.confidence_weight * canonical_sample_at_other.target_function * canonical_sample_at_other_jacobian,
+ );
+ let canonical_sample_mis_weight = mix(canonical_balance_mis_weight, 1.0, defensive_t_c);
+ let canonical_sample_resampling_weight = canonical_sample_mis_weight * canonical_sample_at_canonical.target_function * canonical_reservoir.unbiased_contribution_weight;
+
+ // Resampling weight for other sample
+ let other_balance_mis_weight = balance_heuristic(
+ other_reservoir.confidence_weight * other_sample_at_other.target_function,
+ canonical_reservoir.confidence_weight * other_sample_at_canonical.target_function * other_sample_at_canonical_jacobian,
+ );
+ let other_sample_mis_weight = mix(other_balance_mis_weight, 0.0, defensive_t_c);
+ let other_sample_resampling_weight = other_sample_mis_weight * other_sample_at_canonical.target_function * other_reservoir.unbiased_contribution_weight * other_sample_at_canonical_jacobian;
+
+ // Perform resampling
+ var combined_reservoir = empty_reservoir();
+ combined_reservoir.confidence_weight = canonical_reservoir.confidence_weight + other_reservoir.confidence_weight;
+ let weight_sum = canonical_sample_resampling_weight + other_sample_resampling_weight;
+
+ if rand_f(rng) * weight_sum < other_sample_resampling_weight {
+ combined_reservoir.sample_point_world_position = other_reservoir.sample_point_world_position;
+ combined_reservoir.sample_point_world_normal = other_reservoir.sample_point_world_normal;
+ combined_reservoir.radiance = other_reservoir.radiance;
+ combined_reservoir.light_sample = other_reservoir.light_sample;
+
+ let inverse_target_function = select(0.0, 1.0 / other_sample_at_canonical.target_function, other_sample_at_canonical.target_function > 0.0);
+ combined_reservoir.unbiased_contribution_weight = weight_sum * inverse_target_function;
+
+ return ReservoirMergeResult(combined_reservoir, other_sample_at_canonical.brdf_radiance);
+ } else {
+ combined_reservoir.sample_point_world_position = canonical_reservoir.sample_point_world_position;
+ combined_reservoir.sample_point_world_normal = canonical_reservoir.sample_point_world_normal;
+ combined_reservoir.radiance = canonical_reservoir.radiance;
+ combined_reservoir.light_sample = canonical_reservoir.light_sample;
+
+ let inverse_target_function = select(0.0, 1.0 / canonical_sample_at_canonical.target_function, canonical_sample_at_canonical.target_function > 0.0);
+ combined_reservoir.unbiased_contribution_weight = weight_sum * inverse_target_function;
+
+ return ReservoirMergeResult(combined_reservoir, canonical_sample_at_canonical.brdf_radiance);
+ }
+}
+
+struct ReservoirContribution {
+ brdf_radiance: vec3<f32>,
+ target_function: f32,
+ sample_world_position: vec4<f32>,
+}
+
+fn reservoir_contribution(reservoir: Reservoir, resolved: ResolvedLightSample, world_position: vec3<f32>, world_normal: vec3<f32>, wo: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>) -> ReservoirContribution {
+ if reservoir.light_sample.light_id != NULL_LIGHT_ID {
+ let light_contribution = calculate_resolved_light_contribution(resolved, world_position, world_normal);
+
+ // MIS weight against the bounce-0 BRDF-emissive strategy, recomputed from this surface's
+ // brdf and material rather than baked into the unbiased contribution weight at generation. Mirrors the bounce-0
+ // nee_mis_weight in generate_nee_candidate and generate_emissive_candidate, which puts the same factor in the target.
+ var nee_mis_weight = 1.0;
+ if light_contribution.brdf_rays_can_hit && light_contribution.inverse_solid_angle_pdf > 0.0 {
+ let light_count = arrayLength(&light_sources);
+ let inverse_solid_angle_pdf = light_contribution.inverse_solid_angle_pdf * f32(light_count);
+ let p_nee = mix(1.0, material.perceptual_roughness, material.metallic);
+ let p_nee_strategy = f32(constants.primary_di_samples) * (1.0 / inverse_solid_angle_pdf) * p_nee;
+ let p_brdf_at_nee = brdf_pdf(wo, light_contribution.wi, world_normal, material, F_ab);
+ nee_mis_weight = power_heuristic(p_nee_strategy, p_brdf_at_nee);
+ }
+
+ let brdf_radiance = light_contribution.radiance * evaluate_brdf(wo, light_contribution.wi, world_normal, material, F_ab) * nee_mis_weight;
+ return ReservoirContribution(brdf_radiance, luminance(brdf_radiance), resolved.world_position);
+ } else if any(reservoir.radiance != vec3(0.0)) {
+ let delta = reservoir.sample_point_world_position - (world_position + world_normal * RAY_T_MIN);
+ let sample_distance = length(delta);
+ let wi = delta / sample_distance;
+ var brdf_radiance = reservoir.radiance * evaluate_brdf(wo, wi, world_normal, material, F_ab);
+
+ // Bounce-0 BRDF-emissive sample (directly-visible light). The seed field carries the light
+ // triangle's bitcast area pdf, and the stored radiance is the raw emission. Rebuild the MIS
+ // weight against this surface's NEE strategy, the dual of nee_mis_weight above and a mirror
+ // of the emissive candidate in generate_initial_path.
+ if reservoir.light_sample.seed != 0u {
+ let area_pdf = bitcast<f32>(reservoir.light_sample.seed);
+ let light_normal = octahedral_decode(reservoir.sample_point_world_normal);
+ let cos_theta_light = dot(-wi, light_normal);
+ if cos_theta_light <= 0.0 {
+ brdf_radiance = vec3(0.0);
+ } else {
+ let p_light = area_pdf * sample_distance * sample_distance / cos_theta_light;
+ let p_nee = mix(1.0, material.perceptual_roughness, material.metallic);
+ let p_brdf = brdf_pdf(wo, wi, world_normal, material, F_ab);
+ brdf_radiance *= power_heuristic(p_brdf, p_light * p_nee * f32(constants.primary_di_samples));
+ }
+ }
+
+ return ReservoirContribution(brdf_radiance, luminance(brdf_radiance), vec4(reservoir.sample_point_world_position, 1.0));
+ } else {
+ return ReservoirContribution(vec3(0.0), 0.0, vec4(reservoir.sample_point_world_position, 1.0));
+ }
+}
diff --git a/vendor/bevy_solari/src/realtime/world_cache_compact.wesl b/vendor/bevy_solari/src/realtime/world_cache_compact.wesl
new file mode 100644
index 00000000..bdd4f80f
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/world_cache_compact.wesl
@@ -0,0 +1,79 @@
+import package::realtime::world_cache_query::WORLD_CACHE_EMPTY_CELL;
+import package::realtime::bindings::{
+ world_cache,
+};
+
+enable wgpu_ray_query;
+
+@group(2) @binding(0) var<storage, read_write> world_cache_active_cells_dispatch: vec3<u32>;
+
+var<workgroup> w1: array<u32, 1024u>;
+var<workgroup> w2: array<u32, 1024u>;
+
+@compute @workgroup_size(1024, 1, 1)
+fn decay_world_cache(@builtin(global_invocation_id) global_id: vec3<u32>) {
+ var life = world_cache.life[global_id.x];
+ if life > 0u {
+ life -= 1u;
+ world_cache.life[global_id.x] = life;
+
+ if life == 0u {
+ world_cache.checksums[global_id.x] = WORLD_CACHE_EMPTY_CELL;
+ world_cache.radiance[global_id.x] = vec4(0.0);
+ world_cache.luminance_deltas[global_id.x] = 0.0;
+ }
+ }
+}
+
+@compute @workgroup_size(1024, 1, 1)
+fn compact_world_cache_single_block(
+ @builtin(global_invocation_id) cell_id: vec3<u32>,
+ @builtin(local_invocation_index) t: u32,
+) {
+ if t == 0u { w1[0u] = 0u; } else { w1[t] = u32(world_cache.life[cell_id.x - 1u] != 0u); }; workgroupBarrier();
+ if t < 1u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 1u]; } workgroupBarrier();
+ if t < 2u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 2u]; } workgroupBarrier();
+ if t < 4u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 4u]; } workgroupBarrier();
+ if t < 8u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 8u]; } workgroupBarrier();
+ if t < 16u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 16u]; } workgroupBarrier();
+ if t < 32u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 32u]; } workgroupBarrier();
+ if t < 64u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 64u]; } workgroupBarrier();
+ if t < 128u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 128u]; } workgroupBarrier();
+ if t < 256u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 256u]; } workgroupBarrier();
+ if t < 512u { world_cache.a[cell_id.x] = w2[t]; } else { world_cache.a[cell_id.x] = w2[t] + w2[t - 512u]; }
+}
+
+@compute @workgroup_size(1024, 1, 1)
+fn compact_world_cache_blocks(@builtin(local_invocation_index) t: u32) {
+ if t == 0u { w1[0u] = 0u; } else { w1[t] = world_cache.a[t * 1024u - 1u] + u32(world_cache.life[t * 1024u - 1u] != 0u); }; workgroupBarrier();
+ if t < 1u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 1u]; } workgroupBarrier();
+ if t < 2u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 2u]; } workgroupBarrier();
+ if t < 4u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 4u]; } workgroupBarrier();
+ if t < 8u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 8u]; } workgroupBarrier();
+ if t < 16u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 16u]; } workgroupBarrier();
+ if t < 32u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 32u]; } workgroupBarrier();
+ if t < 64u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 64u]; } workgroupBarrier();
+ if t < 128u { w1[t] = w2[t]; } else { w1[t] = w2[t] + w2[t - 128u]; } workgroupBarrier();
+ if t < 256u { w2[t] = w1[t]; } else { w2[t] = w1[t] + w1[t - 256u]; } workgroupBarrier();
+ if t < 512u { world_cache.b[t] = w2[t]; } else { world_cache.b[t] = w2[t] + w2[t - 512u]; }
+}
+
+@compute @workgroup_size(1024, 1, 1)
+fn compact_world_cache_write_active_cells(
+ @builtin(global_invocation_id) cell_id: vec3<u32>,
+ @builtin(workgroup_id) workgroup_id: vec3<u32>,
+ @builtin(local_invocation_index) thread_index: u32,
+) {
+ let compacted_index = world_cache.a[cell_id.x] + world_cache.b[workgroup_id.x];
+ let cell_active = world_cache.life[cell_id.x] != 0u;
+
+ if cell_active {
+ world_cache.active_cell_indices[compacted_index] = cell_id.x;
+ }
+
+ if thread_index == 1023u && workgroup_id.x == 1023u {
+ let active_cell_count = compacted_index + u32(cell_active);
+ world_cache.active_cells_count = active_cell_count;
+ world_cache_active_cells_dispatch = vec3((active_cell_count + 63u) / 64u, 1u, 1u);
+ }
+}
diff --git a/vendor/bevy_solari/src/realtime/world_cache_query.wesl b/vendor/bevy_solari/src/realtime/world_cache_query.wesl
new file mode 100644
index 00000000..02a6b8c0
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/world_cache_query.wesl
@@ -0,0 +1,116 @@
+import constants::WORLD_CACHE_SIZE;
+import bevy_pbr::render::utils::{rand_f, rand_vec2f};
+import bevy_render::maths::orthonormalize;
+import package::realtime::bindings::{
+ world_cache,
+ constants,
+};
+
+enable wgpu_ray_query;
+
+/// Maximum amount of frames a cell can live for without being queried
+const WORLD_CACHE_CELL_LIFETIME: u32 = 10u;
+/// Maximum amount of attempts to find a cache entry after a hash collision
+const WORLD_CACHE_MAX_SEARCH_STEPS: u32 = 3u;
+
+/// Marker value for an empty cell
+const WORLD_CACHE_EMPTY_CELL: u32 = 0u;
+
+@if(!WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER)
+fn query_world_cache(world_position_in: vec3<f32>, world_normal: vec3<f32>, view_position: vec3<f32>, ray_t: f32, cell_lifetime: u32, rng: ptr<function, u32>) -> vec3<f32> {
+ var world_position = world_position_in;
+ var cell_size = get_cell_size(world_position, view_position, ray_t, rng);
+
+@if(!NO_JITTER_WORLD_CACHE) {
+ // Jitter query point, which essentially blurs the cache a bit so it's not so grid-like
+ // https://tomclabault.github.io/blog/2025/regir, jitter_world_position_tangent_plane
+ let TBN = orthonormalize(world_normal);
+ let offset = (rand_vec2f(rng) * 2.0 - 1.0) * cell_size * 0.5;
+ world_position += offset.x * TBN[0] + offset.y * TBN[1];
+ cell_size = get_cell_size(world_position, view_position, ray_t, rng);
+}
+
+ let world_position_quantized = bitcast<vec3<u32>>(quantize_position(world_position, cell_size));
+ let world_normal_quantized = bitcast<vec3<u32>>(quantize_normal(world_normal));
+ var key = compute_key(world_position_quantized, world_normal_quantized);
+ let checksum = compute_checksum(world_position_quantized, world_normal_quantized);
+
+ for (var i = 0u; i < WORLD_CACHE_MAX_SEARCH_STEPS; i++) {
+ let cas = atomicCompareExchangeWeak(&world_cache.checksums[key], WORLD_CACHE_EMPTY_CELL, checksum);
+ let existing_checksum = cas.old_value;
+
+ // Cell already exists or is empty - reset lifetime
+ if existing_checksum == checksum || existing_checksum == WORLD_CACHE_EMPTY_CELL {
+ @if(!WORLD_CACHE_QUERY_ATOMIC_MAX_LIFETIME)
+ atomicStore(&world_cache.life[key], cell_lifetime);
+ @else
+ atomicMax(&world_cache.life[key], cell_lifetime);
+ }
+
+ if existing_checksum == checksum {
+ // Cache entry already exists - get radiance
+ return world_cache.radiance[key].rgb;
+ } else if existing_checksum == WORLD_CACHE_EMPTY_CELL && cas.exchanged {
+ // Cell is empty - initialize it
+ world_cache.geometry_data[key].world_position = world_position;
+ world_cache.geometry_data[key].world_normal = world_normal;
+ return vec3(0.0);
+ } else {
+ // Collision - linear probe to next entry
+ key += 1u;
+ }
+ }
+
+ return vec3(0.0);
+}
+
+fn get_cell_size(world_position: vec3<f32>, view_position: vec3<f32>, ray_t: f32, rng: ptr<function, u32>) -> f32 {
+ let camera_distance = distance(view_position, world_position) / constants.world_cache_position_lod_scale;
+ let lod_f = log2(1.0 + camera_distance);
+ let lod_fract = fract(lod_f);
+ let lod = floor(lod_f) + select(0.0, 1.0, rand_f(rng) < lod_fract * lod_fract * lod_fract);
+ return constants.world_cache_position_base_cell_size * exp2(lod);
+}
+
+fn quantize_position(world_position: vec3<f32>, quantization_factor: f32) -> vec3<f32> {
+ return floor(world_position / quantization_factor + 0.0001);
+}
+
+fn quantize_normal(world_normal: vec3<f32>) -> vec3<f32> {
+ return floor(world_normal + 0.0001);
+}
+
+fn compute_key(world_position: vec3<u32>, world_normal: vec3<u32>) -> u32 {
+ var key = pcg_hash(world_position.x);
+ key = pcg_hash(key + world_position.y);
+ key = pcg_hash(key + world_position.z);
+ key = pcg_hash(key + world_normal.x);
+ key = pcg_hash(key + world_normal.y);
+ key = pcg_hash(key + world_normal.z);
+ return wrap_key(key);
+}
+
+fn compute_checksum(world_position: vec3<u32>, world_normal: vec3<u32>) -> u32 {
+ var key = iqint_hash(world_position.x);
+ key = iqint_hash(key + world_position.y);
+ key = iqint_hash(key + world_position.z);
+ key = iqint_hash(key + world_normal.x);
+ key = iqint_hash(key + world_normal.y);
+ key = iqint_hash(key + world_normal.z);
+ return max(key, 1u); // 0u is reserved for WORLD_CACHE_EMPTY_CELL
+}
+
+fn pcg_hash(input: u32) -> u32 {
+ let state = input * 747796405u + 2891336453u;
+ let word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
+ return (word >> 22u) ^ word;
+}
+
+fn iqint_hash(input: u32) -> u32 {
+ let n = (input << 13u) ^ input;
+ return n * (n * n * 15731u + 789221u) + 1376312589u;
+}
+
+fn wrap_key(key: u32) -> u32 {
+ return key & (u32(WORLD_CACHE_SIZE) - 1u);
+}
diff --git a/vendor/bevy_solari/src/realtime/world_cache_update.wesl b/vendor/bevy_solari/src/realtime/world_cache_update.wesl
new file mode 100644
index 00000000..d04b07f6
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/world_cache_update.wesl
@@ -0,0 +1,122 @@
+import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
+import bevy_pbr::render::utils::{rand_f, rand_range_u, sample_cosine_hemisphere};
+import bevy_render::maths::PI;
+import package::realtime::presample_light_tiles::unpack_resolved_light_sample;
+import package::scene::sampling::{calculate_resolved_light_contribution, trace_visibility, sample_environment_map_light};
+import package::scene::bindings::{trace_ray, resolve_ray_hit_full, RAY_T_MIN};
+import package::realtime::world_cache_query::query_world_cache;
+import package::realtime::bindings::{
+ light_tile_resolved_samples,
+ view,
+ constants,
+ world_cache,
+};
+
+enable wgpu_ray_query;
+
+@compute @workgroup_size(64, 1, 1)
+fn sample_di(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) active_cell_id: vec3<u32>) {
+ if active_cell_id.x >= world_cache.active_cells_count { return; }
+
+ let cell_index = world_cache.active_cell_indices[active_cell_id.x];
+ let geometry_data = world_cache.geometry_data[cell_index];
+ var rng = cell_index + constants.frame_rng;
+
+ if rand_f(&rng) >= f32(constants.world_cache_cell_updates_soft_target) / f32(world_cache.active_cells_count) { return; }
+
+ let new_radiance = sample_random_light_ris(geometry_data.world_position, geometry_data.world_normal, workgroup_id.xy, &rng);
+
+ world_cache.active_cells_new_radiance[active_cell_id.x] = new_radiance;
+}
+
+@compute @workgroup_size(64, 1, 1)
+fn sample_gi(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) active_cell_id: vec3<u32>) {
+ if active_cell_id.x >= world_cache.active_cells_count { return; }
+
+ let cell_index = world_cache.active_cell_indices[active_cell_id.x];
+ let geometry_data = world_cache.geometry_data[cell_index];
+ var rng = cell_index + constants.frame_rng;
+
+ if rand_f(&rng) >= f32(constants.world_cache_cell_updates_soft_target) / f32(world_cache.active_cells_count) { return; }
+
+ let ray_direction = sample_cosine_hemisphere(geometry_data.world_normal, &rng);
+ let ray = trace_ray(geometry_data.world_position + (geometry_data.world_normal * RAY_T_MIN), ray_direction, RAY_T_MIN, constants.world_cache_max_gi_ray_distance, RAY_FLAG_NONE);
+ if ray.kind != RAY_QUERY_INTERSECTION_NONE {
+ let ray_hit = resolve_ray_hit_full(ray);
+ let cell_life = atomicLoad(&world_cache.life[cell_index]);
+ let radiance = query_world_cache(ray_hit.world_position, ray_hit.geometric_world_normal, view.world_position, ray.t, cell_life, &rng);
+ world_cache.active_cells_new_radiance[active_cell_id.x] += ray_hit.material.base_color * radiance;
+ } else {
+ // The ray is cut short at world_cache_max_gi_ray_distance to save on traversal costs.
+ // A miss here may actually have been a surface further away if we kept tracing, and not actually have been a miss.
+ // We could be leaking sky light due to this if world_cache_max_gi_ray_distance is too small.
+ world_cache.active_cells_new_radiance[active_cell_id.x] += PI * sample_environment_map_light(ray_direction);
+ }
+}
+
+@compute @workgroup_size(64, 1, 1)
+fn blend_new_samples(@builtin(global_invocation_id) active_cell_id: vec3<u32>) {
+ if active_cell_id.x >= world_cache.active_cells_count { return; }
+
+ let cell_index = world_cache.active_cell_indices[active_cell_id.x];
+ var rng = cell_index + constants.frame_rng;
+
+ if rand_f(&rng) >= f32(constants.world_cache_cell_updates_soft_target) / f32(world_cache.active_cells_count) { return; }
+
+ let old_radiance = world_cache.radiance[cell_index];
+ let new_radiance = world_cache.active_cells_new_radiance[active_cell_id.x];
+ let luminance_delta = world_cache.luminance_deltas[cell_index];
+
+ // https://bsky.app/profile/gboisse.bsky.social/post/3m5blga3ftk2a
+ let sample_count = min(old_radiance.a + 1.0, constants.world_cache_max_temporal_samples);
+ let alpha = abs(luminance_delta) / max(luminance(old_radiance.rgb), 0.001);
+ let max_sample_count = mix(constants.world_cache_max_temporal_samples, 1.0, pow(saturate(alpha), 1.0 / 8.0));
+ var blend_amount = 1.0 / min(sample_count, max_sample_count);
+ if bool(constants.reset) {
+ blend_amount = 1.0;
+ }
+
+ let blended_radiance = mix(old_radiance.rgb, new_radiance, blend_amount);
+ let blended_luminance_delta = select(mix(luminance_delta, luminance(blended_radiance) - luminance(old_radiance.rgb), 1.0 / 8.0), 0.0, bool(constants.reset));
+
+ world_cache.radiance[cell_index] = vec4(blended_radiance, sample_count);
+ world_cache.luminance_deltas[cell_index] = blended_luminance_delta;
+}
+
+fn sample_random_light_ris(world_position: vec3<f32>, world_normal: vec3<f32>, workgroup_id: vec2<u32>, rng: ptr<function, u32>) -> vec3<f32> {
+ var workgroup_rng = (workgroup_id.x * 5782582u) + workgroup_id.y;
+ let light_tile_start = rand_range_u(128u, &workgroup_rng) * 1024u;
+
+ var weight_sum = 0.0;
+ var selected_sample_radiance = vec3(0.0);
+ var selected_sample_target_function = 0.0;
+ var selected_sample_world_position = vec4(0.0);
+ let mis_weight = 1.0 / f32(constants.world_cache_direct_light_sample_count);
+ for (var i = 0u; i < constants.world_cache_direct_light_sample_count; i++) {
+ let tile_sample = light_tile_start + rand_range_u(1024u, rng);
+ let resolved_light_sample = unpack_resolved_light_sample(light_tile_resolved_samples[tile_sample], view.exposure);
+ let light_contribution = calculate_resolved_light_contribution(resolved_light_sample, world_position, world_normal);
+
+ let contribution = light_contribution.radiance * saturate(dot(light_contribution.wi, world_normal));
+ let target_function = luminance(contribution);
+ let resampling_weight = mis_weight * (target_function * light_contribution.inverse_pdf);
+
+ weight_sum += resampling_weight;
+
+ if rand_f(rng) * weight_sum < resampling_weight {
+ selected_sample_radiance = contribution;
+ selected_sample_target_function = target_function;
+ selected_sample_world_position = resolved_light_sample.world_position;
+ }
+ }
+
+ var unbiased_contribution_weight = 0.0;
+ if any(selected_sample_radiance != vec3(0.0)) {
+ let inverse_target_function = select(0.0, 1.0 / selected_sample_target_function, selected_sample_target_function > 0.0);
+ unbiased_contribution_weight = weight_sum * inverse_target_function;
+
+ unbiased_contribution_weight *= trace_visibility(world_position + (world_normal * RAY_T_MIN), selected_sample_world_position);
+ }
+
+ return selected_sample_radiance * unbiased_contribution_weight;
+}
diff --git a/vendor/bevy_solari/src/scene/binder/allocator.rs b/vendor/bevy_solari/src/scene/binder/allocator.rs
new file mode 100644
index 00000000..e6476af4
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/binder/allocator.rs
@@ -0,0 +1,245 @@
+use bevy_platform::collections::HashMap;
+use core::{hash::Hash, num::NonZeroU32};
+
+/// A free-list allocator for `u32` array indices meant for GPU allocations.
+pub struct IndexAllocator {
+ free: Vec<u32>,
+ high_water_mark: u32,
+}
+
+impl IndexAllocator {
+ pub fn new() -> Self {
+ Self {
+ free: Vec::new(),
+ high_water_mark: 0,
+ }
+ }
+
+ /// An exclusive upper bound on every index handed out, for sizing and dispatching over the data
+ /// they key.
+ ///
+ /// Not a live count: released indices leave holes below it, and it never shrinks.
+ pub fn high_water_mark(&self) -> u32 {
+ self.high_water_mark
+ }
+
+ pub fn allocate(&mut self) -> u32 {
+ self.free.pop().unwrap_or_else(|| {
+ let index = self.high_water_mark;
+ self.high_water_mark += 1;
+ index
+ })
+ }
+
+ pub fn release(&mut self, index: u32) {
+ self.free.push(index);
+ }
+
+ /// How many more indices can be handed out before running past `capacity`.
+ fn vacancies(&self, capacity: u32) -> u32 {
+ capacity.saturating_sub(self.high_water_mark) + self.free.len() as u32
+ }
+}
+
+/// Assigns each key an index that stays put for as long as the key is live.
+pub struct SlotAllocator<K> {
+ slots: HashMap<K, u32>,
+ indices: IndexAllocator,
+}
+
+impl<K: Eq + Hash> SlotAllocator<K> {
+ pub fn new() -> Self {
+ Self {
+ slots: HashMap::default(),
+ indices: IndexAllocator::new(),
+ }
+ }
+
+ pub fn get(&self, key: &K) -> Option<u32> {
+ self.slots.get(key).copied()
+ }
+
+ pub fn contains(&self, key: &K) -> bool {
+ self.slots.contains_key(key)
+ }
+
+ pub fn keys(&self) -> impl Iterator<Item = &K> {
+ self.slots.keys()
+ }
+
+ pub fn get_or_allocate(&mut self, key: K) -> u32 {
+ if let Some(&slot) = self.slots.get(&key) {
+ return slot;
+ }
+
+ let slot = self.indices.allocate();
+ self.slots.insert(key, slot);
+ slot
+ }
+
+ pub fn remove(&mut self, key: &K) -> Option<u32> {
+ let slot = self.slots.remove(key)?;
+ self.indices.release(slot);
+ Some(slot)
+ }
+
+ /// How many more distinct keys can be taken on before running past `capacity`.
+ fn vacancies(&self, capacity: u32) -> u32 {
+ self.indices.vacancies(capacity)
+ }
+}
+
+/// One occupied slot of a [`RetainedBindingArray`].
+struct BindingSlot<T> {
+ item: T,
+ /// Live references to this slot. An occupied slot always has at least one live reference.
+ references: NonZeroU32,
+}
+
+/// A binding array whose indices are stable across frames.
+///
+/// Slots are reference counted by whatever points at them (e.g. materials for textures, instances for
+/// mesh slab buffers), and are reused once the last reference goes away.
+///
+/// `dirty` marks that the contents have changed and the bind group has to be rebuilt.
+pub struct RetainedBindingArray<K, T> {
+ allocator: SlotAllocator<K>,
+ slots: Vec<Option<BindingSlot<T>>>,
+ pub dirty: bool,
+}
+
+impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
+ pub fn new() -> Self {
+ Self {
+ allocator: SlotAllocator::new(),
+ slots: Vec::new(),
+ dirty: false,
+ }
+ }
+
+ pub fn contains(&self, key: &K) -> bool {
+ self.allocator.contains(key)
+ }
+
+ /// How many more distinct keys can be held before running past `capacity`.
+ pub fn vacancies(&self, capacity: u32) -> u32 {
+ self.allocator.vacancies(capacity)
+ }
+
+ /// Whether [`Self::acquire`] would be able to hand out a reference to `key`.
+ ///
+ /// Callers that need more than one slot at once check this for all of them before acquiring
+ /// any, so that they never have to hand a slot straight back.
+ pub fn has_room(&self, key: &K, capacity: u32) -> bool {
+ self.contains(key) || self.vacancies(capacity) > 0
+ }
+
+ /// The array's contents in slot order, with `None` for slots that are currently free.
+ pub fn iter(&self) -> impl Iterator<Item = Option<&T>> {
+ self.slots
+ .iter()
+ .map(|slot| slot.as_ref().map(|slot| &slot.item))
+ }
+
+ /// Takes a reference to `key`'s slot, allocating and filling it if this is the first one.
+ ///
+ /// Returns `None` if `key` would need a new slot and every slot below `capacity` is taken. The
+ /// bind group layout declares these arrays with a fixed length, so running past it makes
+ /// `create_bind_group` fail outright, and callers have to drop whatever wanted the slot.
+ pub fn acquire(&mut self, key: K, capacity: u32, item: impl FnOnce() -> T) -> Option<u32> {
+ if !self.has_room(&key, capacity) {
+ return None;
+ }
+
+ let slot = self.allocator.get_or_allocate(key);
+ let index = slot as usize;
+
+ if self.slots.len() <= index {
+ self.slots.resize_with(index + 1, || None);
+ }
+
+ if let Some(occupied) = self.slots[index].as_mut() {
+ occupied.references = occupied.references.saturating_add(1);
+ } else {
+ self.slots[index] = Some(BindingSlot {
+ item: item(),
+ references: NonZeroU32::MIN,
+ });
+ self.dirty = true;
+ }
+
+ Some(slot)
+ }
+
+ /// Drops a reference to `key`'s slot, freeing it if that was the last one.
+ pub fn release(&mut self, key: &K) {
+ let Some(slot) = self.allocator.get(key) else {
+ return;
+ };
+ let index = slot as usize;
+ let Some(occupied) = self.slots[index].as_mut() else {
+ return;
+ };
+
+ if let Some(remaining) = NonZeroU32::new(occupied.references.get() - 1) {
+ occupied.references = remaining;
+ return;
+ }
+
+ self.slots[index] = None;
+ self.allocator.remove(key);
+ self.dirty = true;
+ }
+
+ /// Repoints an already-allocated slot at a new value, leaving its index and refcount alone.
+ pub fn replace(&mut self, key: &K, item: T) {
+ if let Some(slot) = self.allocator.get(key)
+ && let Some(occupied) = self.slots[slot as usize].as_mut()
+ {
+ occupied.item = item;
+ self.dirty = true;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{IndexAllocator, RetainedBindingArray};
+
+ #[test]
+ fn index_allocator_reuses_released_slots_without_growing() {
+ let mut slots = IndexAllocator::new();
+
+ assert_eq!(slots.allocate(), 0);
+ assert_eq!(slots.allocate(), 1);
+ assert_eq!(slots.high_water_mark(), 2);
+
+ slots.release(0);
+ assert_eq!(slots.allocate(), 0);
+ assert_eq!(slots.high_water_mark(), 2);
+ }
+
+ #[test]
+ fn retained_binding_array_only_dirties_on_binding_changes() {
+ let mut bindings = RetainedBindingArray::new();
+
+ assert_eq!(bindings.acquire(7, 2, || 11), Some(0));
+ assert!(bindings.dirty);
+ bindings.dirty = false;
+
+ // Sharing the existing stable slot only changes its refcount
+ assert_eq!(bindings.acquire(7, 2, || 99), Some(0));
+ assert!(!bindings.dirty);
+ assert_eq!(bindings.iter().next(), Some(Some(&11)));
+
+ bindings.release(&7);
+ assert!(!bindings.dirty);
+ assert!(bindings.contains(&7));
+
+ // The final release changes the binding array and makes the slot reusable
+ bindings.release(&7);
+ assert!(bindings.dirty);
+ assert!(!bindings.contains(&7));
+ assert_eq!(bindings.acquire(8, 2, || 22), Some(0));
+ }
+}
diff --git a/vendor/bevy_solari/src/scene/binder/assets.rs b/vendor/bevy_solari/src/scene/binder/assets.rs
new file mode 100644
index 00000000..73223cc7
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/binder/assets.rs
@@ -0,0 +1,310 @@
+use super::{
+ allocator::{RetainedBindingArray, SlotAllocator},
+ instances::InstanceState,
+ StandardMaterialAssets,
+};
+use bevy_asset::AssetId;
+use bevy_color::{Alpha, ColorToComponents, LinearRgba};
+use bevy_image::Image;
+use bevy_material::AlphaMode;
+use bevy_math::{Vec3, Vec4};
+use bevy_pbr::StandardMaterial;
+use bevy_platform::collections::{HashMap, HashSet};
+use bevy_render::{
+ impl_atomic_pod,
+ render_asset::{ExtractedAssets, RenderAssets},
+ render_resource::{AtomicPod, AtomicSparseBufferVec, BufferUsages, Sampler, TextureView},
+ texture::GpuImage,
+};
+use bevy_utils::once;
+use bytemuck::{Pod, Zeroable};
+use core::num::NonZeroU32;
+use tracing::{info_span, warn};
+
+pub const MAX_TEXTURE_COUNT: NonZeroU32 = NonZeroU32::new(5_000).unwrap();
+const TEXTURE_MAP_NONE: u32 = u32::MAX;
+
+/// The four textures a [`StandardMaterial`] can reference, in [`GpuMaterial`] field order.
+type MaterialTextures = [Option<AssetId<Image>>; 4];
+
+#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
+#[repr(C)]
+pub struct GpuMaterial {
+ normal_map_texture_id: u32,
+ base_color_texture_id: u32,
+ emissive_texture_id: u32,
+ metallic_roughness_texture_id: u32,
+
+ base_color: Vec3,
+ perceptual_roughness: f32,
+ emissive: Vec3,
+ metallic: f32,
+ // raea: the base colour's alpha, how it's used (ALPHA_* below) and Mask's cutoff, in what was padding, so a ray can
+ // pass through what the raster passes draw see-through
+ alpha: f32,
+ alpha_mode: u32,
+ alpha_cutoff: f32,
+ reflectance: f32,
+ // raea: StandardMaterial's uv_transform (columns x and y, then the translation), applied to the mesh's UVs before
+ // its textures are read, as the raster passes do
+ uv_transform_xy: Vec4,
+ uv_transform_t: Vec4,
+}
+
+// raea: how a traced ray treats a material's alpha (bindings.wesl's alpha_accepts)
+pub const ALPHA_OPAQUE: u32 = 0;
+pub const ALPHA_MASK: u32 = 1;
+pub const ALPHA_BLEND: u32 = 2;
+pub const ALPHA_PREMULTIPLIED: u32 = 3;
+pub const ALPHA_ADD: u32 = 4;
+
+/// raea: a StandardMaterial's alpha mode as the tracer reads it, and its cutoff (Mask's).
+fn alpha_of(mode: AlphaMode) -> (u32, f32) {
+ match mode {
+ AlphaMode::Opaque => (ALPHA_OPAQUE, 0.0),
+ AlphaMode::Mask(cutoff) => (ALPHA_MASK, cutoff),
+ AlphaMode::AlphaToCoverage => (ALPHA_MASK, 0.5),
+ AlphaMode::Blend => (ALPHA_BLEND, 0.0),
+ AlphaMode::Premultiplied => (ALPHA_PREMULTIPLIED, 0.0),
+ AlphaMode::Add | AlphaMode::Multiply => (ALPHA_ADD, 0.0),
+ }
+}
+
+impl_atomic_pod!(GpuMaterial, GpuMaterialBlob);
+
+/// Stable material and texture slots, plus the retry state for assets that aren't ready yet.
+pub struct AssetState {
+ pub textures: RetainedBindingArray<AssetId<Image>, (TextureView, Sampler)>,
+ pub materials: AtomicSparseBufferVec<GpuMaterial>,
+ pub material_slots: SlotAllocator<AssetId<StandardMaterial>>,
+ material_textures: HashMap<AssetId<StandardMaterial>, MaterialTextures>,
+ pub emissive_materials: HashSet<AssetId<StandardMaterial>>,
+ /// raea: the materials a ray may pass through (any alpha mode but Opaque), whose instances go in the TLAS under
+ /// their own mask so only the alpha query tests them
+ pub alpha_materials: HashSet<AssetId<StandardMaterial>>,
+ /// Materials to retry because at least one required texture is not on the GPU yet.
+ unresolved_materials: HashSet<AssetId<StandardMaterial>>,
+ /// Bound images whose replacement GPU data has not landed yet.
+ pending_texture_updates: HashSet<AssetId<Image>>,
+}
+
+impl AssetState {
+ pub fn new() -> Self {
+ Self {
+ textures: RetainedBindingArray::new(),
+ materials: AtomicSparseBufferVec::new(BufferUsages::STORAGE, "solari_materials".into()),
+ material_slots: SlotAllocator::new(),
+ material_textures: HashMap::default(),
+ emissive_materials: HashSet::default(),
+ alpha_materials: HashSet::default(),
+ unresolved_materials: HashSet::default(),
+ pending_texture_updates: HashSet::default(),
+ }
+ }
+
+ pub fn update_materials(
+ &mut self,
+ instances: &mut InstanceState,
+ material_assets: &StandardMaterialAssets,
+ texture_assets: &RenderAssets<GpuImage>,
+ ) {
+ let _span = info_span!("update_materials").entered();
+
+ for material_id in &material_assets.removed {
+ self.remove_material(*material_id, instances);
+ }
+ for material_id in &material_assets.changed {
+ self.update_material(*material_id, instances, material_assets, texture_assets);
+ }
+ }
+
+ /// Swaps in uploaded replacements and retries materials waiting on images.
+ pub fn update_textures(
+ &mut self,
+ instances: &mut InstanceState,
+ extracted_images: &ExtractedAssets<GpuImage>,
+ texture_assets: &RenderAssets<GpuImage>,
+ material_assets: &StandardMaterialAssets,
+ ) {
+ let _span = info_span!("update_textures").entered();
+
+ let mut pending = core::mem::take(&mut self.pending_texture_updates);
+ pending.extend(extracted_images.added.iter().copied());
+
+ for image_id in pending {
+ if !self.textures.contains(&image_id) {
+ continue;
+ }
+
+ match texture_assets.get(image_id) {
+ Some(image) => self.textures.replace(
+ &image_id,
+ (image.texture_view.clone(), image.sampler.clone()),
+ ),
+ None => {
+ self.pending_texture_updates.insert(image_id);
+ }
+ }
+ }
+
+ for material_id in core::mem::take(&mut self.unresolved_materials) {
+ self.update_material(material_id, instances, material_assets, texture_assets);
+ }
+ }
+
+ /// Resolves a material's textures and writes it into its stable slot.
+ fn update_material(
+ &mut self,
+ material_id: AssetId<StandardMaterial>,
+ instances: &mut InstanceState,
+ material_assets: &StandardMaterialAssets,
+ texture_assets: &RenderAssets<GpuImage>,
+ ) {
+ let Some(material) = material_assets.get(&material_id) else {
+ self.remove_material(material_id, instances);
+ return;
+ };
+
+ let was_resolved = self.material_slots.contains(&material_id);
+ let handles = [
+ &material.normal_map_texture,
+ &material.base_color_texture,
+ &material.emissive_texture,
+ &material.metallic_roughness_texture,
+ ];
+
+ // Resolve first so a missing texture leaves no partially acquired slots
+ let mut textures: MaterialTextures = [None; 4];
+ for (slot, handle) in textures.iter_mut().zip(handles) {
+ let Some(handle) = handle else { continue };
+ let image_id = handle.id();
+ if texture_assets.get(image_id).is_none() {
+ self.defer_material(material_id, instances);
+ return;
+ }
+ *slot = Some(image_id);
+ }
+
+ if self.new_texture_count(&textures) > self.textures.vacancies(MAX_TEXTURE_COUNT.get()) {
+ // At the limit, release the old set once so a replacement can reuse those slots
+ self.release_material_textures(material_id);
+ self.material_textures.remove(&material_id);
+
+ if self.new_texture_count(&textures) > self.textures.vacancies(MAX_TEXTURE_COUNT.get())
+ {
+ once!(warn!(
+ "Solari scene needs more than {} textures. Materials past that limit will not \
+ be rendered.",
+ MAX_TEXTURE_COUNT.get()
+ ));
+ self.defer_material(material_id, instances);
+ return;
+ }
+ }
+
+ let mut texture_ids = [TEXTURE_MAP_NONE; 4];
+ for (texture_id, image_id) in texture_ids.iter_mut().zip(textures) {
+ let Some(image_id) = image_id else { continue };
+ let image = texture_assets.get(image_id).unwrap();
+ if let Some(slot) = self
+ .textures
+ .acquire(image_id, MAX_TEXTURE_COUNT.get(), || {
+ (image.texture_view.clone(), image.sampler.clone())
+ })
+ {
+ *texture_id = slot;
+ }
+ }
+
+ self.release_material_textures(material_id);
+ self.material_textures.insert(material_id, textures);
+ self.unresolved_materials.remove(&material_id);
+
+ let slot = self.material_slots.get_or_allocate(material_id);
+ let emissive = material.emissive.to_vec3();
+ let is_emissive = emissive != Vec3::ZERO;
+ let (alpha_mode, alpha_cutoff) = alpha_of(material.alpha_mode);
+ let uv = material.uv_transform;
+ self.materials.grow_and_set(
+ slot,
+ GpuMaterial {
+ normal_map_texture_id: texture_ids[0],
+ base_color_texture_id: texture_ids[1],
+ emissive_texture_id: texture_ids[2],
+ metallic_roughness_texture_id: texture_ids[3],
+ base_color: LinearRgba::from(material.base_color).to_vec3(),
+ perceptual_roughness: material.perceptual_roughness.clamp(0.0, 1.0),
+ emissive,
+ metallic: material.metallic.clamp(0.0, 1.0),
+ reflectance: material.reflectance,
+ alpha: material.base_color.alpha(),
+ alpha_mode,
+ alpha_cutoff,
+ uv_transform_xy: Vec4::new(uv.matrix2.x_axis.x, uv.matrix2.x_axis.y, uv.matrix2.y_axis.x, uv.matrix2.y_axis.y),
+ uv_transform_t: Vec4::new(uv.translation.x, uv.translation.y, 0.0, 0.0),
+ },
+ );
+ // raea: a material that turns see-through (or back) moves its instances between the TLAS masks
+ let is_alpha = alpha_mode != ALPHA_OPAQUE;
+ let was_alpha = if is_alpha { !self.alpha_materials.insert(material_id) } else { self.alpha_materials.remove(&material_id) };
+ if was_resolved && was_alpha != is_alpha {
+ instances.invalidate_material(material_id);
+ }
+
+ let was_emissive = if is_emissive {
+ !self.emissive_materials.insert(material_id)
+ } else {
+ self.emissive_materials.remove(&material_id)
+ };
+ if !was_resolved || was_emissive != is_emissive {
+ instances.invalidate_material(material_id);
+ }
+ }
+
+ fn new_texture_count(&self, textures: &MaterialTextures) -> u32 {
+ let mut count = 0;
+ for (index, image_id) in textures.iter().enumerate() {
+ let Some(image_id) = image_id else { continue };
+ let counted_already = textures[..index].contains(&Some(*image_id));
+ if !counted_already && !self.textures.contains(image_id) {
+ count += 1;
+ }
+ }
+ count
+ }
+
+ fn defer_material(
+ &mut self,
+ material_id: AssetId<StandardMaterial>,
+ instances: &mut InstanceState,
+ ) {
+ self.remove_material(material_id, instances);
+ self.unresolved_materials.insert(material_id);
+ }
+
+ fn remove_material(
+ &mut self,
+ material_id: AssetId<StandardMaterial>,
+ instances: &mut InstanceState,
+ ) {
+ self.unresolved_materials.remove(&material_id);
+ if self.material_slots.remove(&material_id).is_none() {
+ return;
+ }
+
+ self.release_material_textures(material_id);
+ self.material_textures.remove(&material_id);
+ self.emissive_materials.remove(&material_id);
+ self.alpha_materials.remove(&material_id);
+ instances.invalidate_material(material_id);
+ }
+
+ fn release_material_textures(&mut self, material_id: AssetId<StandardMaterial>) {
+ let Some(textures) = self.material_textures.get(&material_id).copied() else {
+ return;
+ };
+ for image_id in textures.into_iter().flatten() {
+ self.textures.release(&image_id);
+ }
+ }
+}
diff --git a/vendor/bevy_solari/src/scene/binder/bind_group.rs b/vendor/bevy_solari/src/scene/binder/bind_group.rs
new file mode 100644
index 00000000..7dc1fc01
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/binder/bind_group.rs
@@ -0,0 +1,450 @@
+use super::{
+ allocator::RetainedBindingArray, lights::GpuLightSource, RaytracingSceneBindings,
+ TlasInstanceSetupPipeline,
+};
+use crate::scene::extract::ExtractedEnvironmentMapLight;
+use bevy_ecs::system::{Res, ResMut};
+use bevy_math::{Mat3, Vec3};
+use bevy_pbr::DfgLut;
+use bevy_render::{
+ render_asset::RenderAssets,
+ render_resource::{
+ BindGroup, BindGroupEntries, BindGroupLayout, Buffer, BufferBinding, BufferDescriptor,
+ BufferId, BufferSize, BufferUsages, PipelineCache, Sampler, SamplerId, ShaderType,
+ SparseBufferUpdateBindGroups, SparseBufferUpdateJobs, SparseBufferUpdatePipelines,
+ StorageBuffer, TextureView, TextureViewId,
+ },
+ renderer::{RenderDevice, RenderQueue},
+ texture::{FallbackImage, GpuImage},
+};
+use core::{mem::size_of, ops::Deref};
+use tracing::info_span;
+
+pub struct BindGroupCacheState {
+ cached: [Option<BindGroup>; 2],
+ pub invalid: bool,
+ last_buffer_ids: [Option<BufferId>; 10],
+ last_light_count: u32,
+ last_dfg_ids: Option<(TextureViewId, SamplerId)>,
+ last_environment_map_light_id: Option<TextureViewId>,
+ pub dummy_buffer: Buffer,
+}
+
+impl BindGroupCacheState {
+ pub fn new(render_device: &RenderDevice) -> Self {
+ // Binding arrays are dense, so freed slots still need something valid bound into them
+ let dummy_buffer = render_device.create_buffer(&BufferDescriptor {
+ label: Some("solari_dummy_binding_array_buffer"),
+ size: 48,
+ usage: BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ });
+
+ Self {
+ cached: [None, None],
+ invalid: true,
+ last_buffer_ids: [None; 10],
+ last_light_count: 0,
+ last_dfg_ids: None,
+ last_environment_map_light_id: None,
+ dummy_buffer,
+ }
+ }
+}
+
+fn buffer_bindings<'a>(
+ buffers: &'a RetainedBindingArray<BufferId, Buffer>,
+ dummy: &'a Buffer,
+) -> Vec<BufferBinding<'a>> {
+ buffers
+ .iter()
+ .map(|buffer| buffer.unwrap_or(dummy).as_entire_buffer_binding())
+ .collect()
+}
+
+impl RaytracingSceneBindings {
+ /// Each sparse buffer's GPU buffer id, or `None` where it has not been created yet.
+ fn buffer_ids(&self) -> [Option<BufferId>; 10] {
+ [
+ self.assets.materials.buffer().map(Buffer::id),
+ self.instances.transforms.buffer().map(Buffer::id),
+ self.instances
+ .previous_frame_transforms
+ .buffer()
+ .map(Buffer::id),
+ self.instances.geometry_ids.buffer().map(Buffer::id),
+ self.instances.material_ids.buffer().map(Buffer::id),
+ self.instances.blas_refs.buffer().map(Buffer::id),
+ self.lights.sources.buffer().map(Buffer::id),
+ self.lights.directional_lights.buffer().map(Buffer::id),
+ self.lights
+ .previous_frame_id_translations
+ .buffer()
+ .map(Buffer::id),
+ self.environment_map_light_buffer.buffer().map(Buffer::id),
+ ]
+ }
+
+ fn take_bind_group_invalidation(
+ &mut self,
+ dfg_view: &TextureView,
+ dfg_sampler: &Sampler,
+ environment_map_light: &TextureView,
+ ) -> bool {
+ let mut invalid = self.bind_groups.invalid;
+ self.bind_groups.invalid = false;
+
+ for dirty in [
+ &mut self.instances.vertex_buffers.dirty,
+ &mut self.instances.index_buffers.dirty,
+ &mut self.assets.textures.dirty,
+ ] {
+ invalid |= core::mem::replace(dirty, false);
+ }
+
+ let buffer_ids = self.buffer_ids();
+ if self.bind_groups.last_buffer_ids != buffer_ids {
+ self.bind_groups.last_buffer_ids = buffer_ids;
+ invalid = true;
+ }
+
+ let light_count = self.lights.index.len() as u32;
+ if self.bind_groups.last_light_count != light_count {
+ self.bind_groups.last_light_count = light_count;
+ invalid = true;
+ }
+
+ let dfg_ids = Some((dfg_view.id(), dfg_sampler.id()));
+ if self.bind_groups.last_dfg_ids != dfg_ids {
+ self.bind_groups.last_dfg_ids = dfg_ids;
+ invalid = true;
+ }
+
+ let environment_map_light_id = Some(environment_map_light.id());
+ if self.bind_groups.last_environment_map_light_id != environment_map_light_id {
+ self.bind_groups.last_environment_map_light_id = environment_map_light_id;
+ invalid = true;
+ }
+
+ invalid
+ }
+
+ fn create_bind_group(
+ &self,
+ current_index: usize,
+ render_device: &RenderDevice,
+ layout: &BindGroupLayout,
+ fallback_texture: &FallbackImage,
+ dfg_view: &TextureView,
+ dfg_sampler: &Sampler,
+ environment_map_light: &TextureView,
+ ) -> BindGroup {
+ let _span = info_span!("create_bind_group").entered();
+ let dummy = &self.bind_groups.dummy_buffer;
+ let vertex_buffers = buffer_bindings(&self.instances.vertex_buffers, dummy);
+ let index_buffers = buffer_bindings(&self.instances.index_buffers, dummy);
+
+ let (mut textures, mut samplers): (Vec<_>, Vec<_>) = self
+ .assets
+ .textures
+ .iter()
+ .map(|texture| match texture {
+ Some((view, sampler)) => (view.deref(), sampler.deref()),
+ None => (
+ fallback_texture.d2.texture_view.deref(),
+ fallback_texture.d2.sampler.deref(),
+ ),
+ })
+ .unzip();
+ if textures.is_empty() {
+ textures.push(fallback_texture.d2.texture_view.deref());
+ samplers.push(fallback_texture.d2.sampler.deref());
+ }
+
+ let light_sources = BufferBinding {
+ buffer: self.lights.sources.buffer().unwrap(),
+ offset: 0,
+ size: BufferSize::new(
+ self.lights.index.len() as u64 * size_of::<GpuLightSource>() as u64,
+ ),
+ };
+
+ let materials = self
+ .assets
+ .materials
+ .buffer()
+ .unwrap()
+ .as_entire_buffer_binding();
+ let transforms = self
+ .instances
+ .transforms
+ .buffer()
+ .unwrap()
+ .as_entire_buffer_binding();
+ let previous_frame_transforms = self
+ .instances
+ .previous_frame_transforms
+ .buffer()
+ .unwrap()
+ .as_entire_buffer_binding();
+ let geometry_ids = self
+ .instances
+ .geometry_ids
+ .buffer()
+ .unwrap()
+ .as_entire_buffer_binding();
+ let material_ids = self
+ .instances
+ .material_ids
+ .buffer()
+ .unwrap()
+ .as_entire_buffer_binding();
+ let directional_lights = self
+ .lights
+ .directional_lights
+ .buffer()
+ .unwrap()
+ .as_entire_buffer_binding();
+ let translations = self
+ .lights
+ .previous_frame_id_translations
+ .buffer()
+ .unwrap()
+ .as_entire_buffer_binding();
+
+ let current = self.tlas.structures[current_index].as_ref().unwrap();
+ let previous = self.tlas.structures[current_index ^ 1]
+ .as_ref()
+ .filter(|_| self.tlas.built[current_index ^ 1])
+ .unwrap_or(current);
+
+ render_device.create_bind_group(
+ "raytracing_scene_bind_group",
+ layout,
+ &BindGroupEntries::sequential((
+ vertex_buffers.as_slice(),
+ index_buffers.as_slice(),
+ textures.as_slice(),
+ samplers.as_slice(),
+ materials,
+ current.as_binding(),
+ previous.as_binding(),
+ transforms,
+ previous_frame_transforms,
+ geometry_ids,
+ material_ids,
+ light_sources,
+ directional_lights,
+ translations,
+ dfg_view,
+ dfg_sampler,
+ environment_map_light,
+ &self.environment_map_light_sampler,
+ &self.environment_map_light_buffer,
+ )),
+ )
+ }
+
+ fn cache_bind_group(
+ &mut self,
+ current_index: usize,
+ render_device: &RenderDevice,
+ pipeline_cache: &PipelineCache,
+ fallback_texture: &FallbackImage,
+ dfg_view: &TextureView,
+ dfg_sampler: &Sampler,
+ environment_map_light: &TextureView,
+ ) -> BindGroup {
+ if let Some(bind_group) = &self.bind_groups.cached[current_index] {
+ return bind_group.clone();
+ }
+
+ // Only resolve the layout on a miss, as it locks and hashes the whole descriptor
+ let layout = pipeline_cache.get_bind_group_layout(&self.bind_group_layout);
+ let bind_group = self.create_bind_group(
+ current_index,
+ render_device,
+ &layout,
+ fallback_texture,
+ dfg_view,
+ dfg_sampler,
+ environment_map_light,
+ );
+ if self.tlas.previous_binding_is_stable() {
+ self.bind_groups.cached[current_index] = Some(bind_group.clone());
+ }
+ bind_group
+ }
+}
+
+/// Finalizes sparse uploads and selects the cached bind group for this frame's TLAS.
+pub fn prepare_raytracing_scene_bind_group(
+ texture_assets: Res<RenderAssets<GpuImage>>,
+ fallback_texture: Res<FallbackImage>,
+ dfg_lut: Res<DfgLut>,
+ extracted_environment_map_light: Res<ExtractedEnvironmentMapLight>,
+ render_device: Res<RenderDevice>,
+ render_queue: Res<RenderQueue>,
+ pipeline_cache: Res<PipelineCache>,
+ sparse_buffer_update_pipelines: Res<SparseBufferUpdatePipelines>,
+ instance_setup_pipeline: Res<TlasInstanceSetupPipeline>,
+ mut sparse_buffer_update_jobs: ResMut<SparseBufferUpdateJobs>,
+ mut sparse_buffer_update_bind_groups: ResMut<SparseBufferUpdateBindGroups>,
+ mut bindings: ResMut<RaytracingSceneBindings>,
+) {
+ let bindings = &mut *bindings;
+
+ prepare_sparse_uploads(
+ bindings,
+ &render_device,
+ &pipeline_cache,
+ &mut sparse_buffer_update_jobs,
+ &mut sparse_buffer_update_bind_groups,
+ &sparse_buffer_update_pipelines,
+ );
+
+ bindings.tlas.update_instance_setup_bind_group(
+ &bindings.instances,
+ &render_device,
+ &pipeline_cache,
+ &instance_setup_pipeline,
+ );
+ bindings.bind_group = None;
+
+ if bindings.instances.live_count == 0 || bindings.lights.index.is_empty() {
+ return;
+ }
+ if bindings.tlas.structures[bindings.tlas.current_index].is_none() {
+ return;
+ }
+
+ let (dfg_view, dfg_sampler) = texture_assets
+ .get(&dfg_lut.texture)
+ .map(|image| (&image.texture_view, &image.sampler))
+ .unwrap_or((
+ &fallback_texture.d2.texture_view,
+ &fallback_texture.d2.sampler,
+ ));
+
+ let environment_map_light = prepare_environment_map_light(
+ &extracted_environment_map_light,
+ &texture_assets,
+ &fallback_texture,
+ &mut bindings.environment_map_light_buffer,
+ &render_device,
+ &render_queue,
+ );
+
+ if bindings.take_bind_group_invalidation(dfg_view, dfg_sampler, environment_map_light) {
+ bindings.bind_groups.cached = [None, None];
+ }
+
+ let current_index = bindings.tlas.current_index;
+ bindings.bind_group = Some(bindings.cache_bind_group(
+ current_index,
+ &render_device,
+ &pipeline_cache,
+ &fallback_texture,
+ dfg_view,
+ dfg_sampler,
+ environment_map_light,
+ ));
+}
+
+#[derive(ShaderType, Default)]
+pub struct GpuEnvironmentMapLight {
+ pub light_from_world: Mat3,
+ pub intensity: f32,
+ // raea: the sun disk (EnvironmentSun) in the map's own space, the cosine of its radius (above 1: no sun) and the sky
+ // radiance shown inside it
+ pub sun_direction: Vec3,
+ pub sun_cos: f32,
+ pub sky: Vec3,
+}
+
+fn prepare_environment_map_light<'a>(
+ extracted_environment_map_light: &ExtractedEnvironmentMapLight,
+ texture_assets: &'a RenderAssets<GpuImage>,
+ fallback_texture: &'a FallbackImage,
+ buffer: &mut StorageBuffer<GpuEnvironmentMapLight>,
+ render_device: &RenderDevice,
+ render_queue: &RenderQueue,
+) -> &'a TextureView {
+ let cubemap = extracted_environment_map_light
+ .cubemap
+ .as_ref()
+ .and_then(|cubemap| texture_assets.get(cubemap));
+
+ let (texture, uniform) = match cubemap {
+ Some(cubemap) => (
+ &cubemap.texture_view,
+ GpuEnvironmentMapLight {
+ light_from_world: Mat3::from_quat(
+ extracted_environment_map_light.rotation.inverse(),
+ ),
+ intensity: extracted_environment_map_light.intensity,
+ sun_direction: extracted_environment_map_light.sun.map_or(Vec3::Y, |s| s.direction.normalize()),
+ sun_cos: extracted_environment_map_light.sun.map_or(2.0, |s| bevy_math::ops::cos(s.angular_size / 2.0)),
+ sky: extracted_environment_map_light.sun.map_or(Vec3::ZERO, |s| s.sky),
+ },
+ ),
+ None => (
+ &fallback_texture.cube.texture_view,
+ GpuEnvironmentMapLight::default(),
+ ),
+ };
+
+ buffer.set(uniform);
+ buffer.write_buffer(render_device, render_queue);
+ texture
+}
+
+/// Queues the compute jobs that scatter each buffer's staged elements into its GPU buffer.
+fn prepare_sparse_uploads(
+ bindings: &mut RaytracingSceneBindings,
+ device: &RenderDevice,
+ cache: &PipelineCache,
+ jobs: &mut SparseBufferUpdateJobs,
+ groups: &mut SparseBufferUpdateBindGroups,
+ pipelines: &SparseBufferUpdatePipelines,
+) {
+ let _span = info_span!("prepare_sparse_uploads").entered();
+
+ bindings
+ .assets
+ .materials
+ .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
+
+ let instances = &mut bindings.instances;
+ instances
+ .transforms
+ .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
+ instances
+ .previous_frame_transforms
+ .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
+ instances
+ .geometry_ids
+ .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
+ instances
+ .material_ids
+ .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
+ if bindings.tlas.uses_raw_build() {
+ instances
+ .blas_refs
+ .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
+ instances
+ .masks
+ .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
+ }
+
+ let lights = &mut bindings.lights;
+ lights
+ .sources
+ .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
+ lights
+ .directional_lights
+ .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
+ lights
+ .previous_frame_id_translations
+ .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
+}
diff --git a/vendor/bevy_solari/src/scene/binder/instances.rs b/vendor/bevy_solari/src/scene/binder/instances.rs
new file mode 100644
index 00000000..3c165f64
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/binder/instances.rs
@@ -0,0 +1,447 @@
+use super::{
+ allocator::{IndexAllocator, RetainedBindingArray},
+ assets::AssetState,
+ lights::{GpuLightSource, LightSourceId, LightState},
+ BlasManager, RaytracingMesh3d, RaytracingSceneBindings,
+};
+use bevy_asset::AssetId;
+use bevy_ecs::{
+ entity::{Entity, EntityHashMap, EntityHashSet},
+ query::{Changed, Or, With},
+ system::Query,
+};
+use bevy_math::{Affine3, Affine3Ext, Vec4};
+use bevy_mesh::Mesh;
+use bevy_pbr::{MeshMaterial3d, PreviousGlobalTransform, StandardMaterial};
+use bevy_platform::collections::HashMap;
+use bevy_render::{
+ impl_atomic_pod,
+ mesh::allocator::MeshAllocator,
+ render_resource::{AtomicPod, AtomicSparseBufferVec, Buffer, BufferId, BufferUsages},
+};
+use bevy_transform::components::GlobalTransform;
+use bevy_utils::once;
+use bytemuck::{Pod, Zeroable};
+use core::{hash::Hash, num::NonZeroU32};
+use tracing::{info_span, warn};
+
+pub const MAX_MESH_SLAB_COUNT: NonZeroU32 = NonZeroU32::new(500).unwrap();
+
+#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
+#[repr(C)]
+pub struct GpuInstanceGeometryIds {
+ vertex_buffer_id: u32,
+ vertex_buffer_offset: u32,
+ index_buffer_id: u32,
+ index_buffer_offset: u32,
+ triangle_count: u32,
+}
+
+/// A world-from-local affine transform, stored transposed as three rows.
+#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
+#[repr(C)]
+pub struct GpuTransform([Vec4; 3]);
+
+impl GpuTransform {
+ /// The three rows as the flat row-major 3x4 a [`TlasInstance`] wants.
+ ///
+ /// [`TlasInstance`]: bevy_render::render_resource::TlasInstance
+ fn rows(self) -> [f32; 12] {
+ bytemuck::cast(self)
+ }
+}
+
+/// The device address of a slot's acceleration structure. Zero marks an inactive slot.
+#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
+#[repr(transparent)]
+pub struct GpuBlasRef(u64);
+
+impl GpuBlasRef {
+ const NONE: Self = Self(0);
+}
+
+impl_atomic_pod!(GpuInstanceGeometryIds, GpuInstanceGeometryIdsBlob);
+impl_atomic_pod!(GpuTransform, GpuTransformBlob);
+impl_atomic_pod!(GpuBlasRef, GpuBlasRefBlob);
+
+fn storage_buffer<T: AtomicPod>(label: &str) -> AtomicSparseBufferVec<T> {
+ AtomicSparseBufferVec::new(BufferUsages::STORAGE, label.into())
+}
+
+/// raea: the TLAS instance masks. Opaque instances are traced as they always were; an instance whose material a ray may
+/// pass through is left out of that query and found by a second one that tests each of its triangles' alpha
+/// (bindings.wesl's trace_ray). Kept in step with bindings.wesl's RAY_MASK_*.
+pub const MASK_OPAQUE: u32 = 0x01;
+pub const MASK_ALPHA: u32 = 0x02;
+
+/// Everything tracked per raytracing instance.
+#[derive(Clone, Copy)]
+struct Instance {
+ slot: u32,
+ mesh: AssetId<Mesh>,
+ material: AssetId<StandardMaterial>,
+ buffers: Option<(BufferId, BufferId)>,
+}
+
+/// Stable slots, reverse dependency indices and GPU data owned by raytracing instances.
+pub struct InstanceState {
+ pub vertex_buffers: RetainedBindingArray<BufferId, Buffer>,
+ pub index_buffers: RetainedBindingArray<BufferId, Buffer>,
+ pub transforms: AtomicSparseBufferVec<GpuTransform>,
+ pub previous_frame_transforms: AtomicSparseBufferVec<GpuTransform>,
+ pub geometry_ids: AtomicSparseBufferVec<GpuInstanceGeometryIds>,
+ pub material_ids: AtomicSparseBufferVec<u32>,
+ /// raea: each slot's TLAS instance mask (MASK_OPAQUE, or MASK_ALPHA for a material a ray may pass through)
+ pub masks: AtomicSparseBufferVec<u32>,
+ pub blas_refs: AtomicSparseBufferVec<GpuBlasRef>,
+ pub slots: IndexAllocator,
+ records: EntityHashMap<Instance>,
+ pub live_count: u32,
+ pub pending_refresh: EntityHashSet,
+ mesh_instances: HashMap<AssetId<Mesh>, EntityHashSet>,
+ pub material_instances: HashMap<AssetId<StandardMaterial>, EntityHashSet>,
+}
+
+impl InstanceState {
+ pub fn new() -> Self {
+ Self {
+ vertex_buffers: RetainedBindingArray::new(),
+ index_buffers: RetainedBindingArray::new(),
+ transforms: storage_buffer("solari_transforms"),
+ previous_frame_transforms: storage_buffer("solari_previous_frame_transforms"),
+ geometry_ids: storage_buffer("solari_geometry_ids"),
+ material_ids: storage_buffer("solari_material_ids"),
+ masks: storage_buffer("solari_instance_masks"),
+ blas_refs: storage_buffer("solari_blas_refs"),
+ slots: IndexAllocator::new(),
+ records: EntityHashMap::default(),
+ live_count: 0,
+ pending_refresh: EntityHashSet::default(),
+ mesh_instances: HashMap::default(),
+ material_instances: HashMap::default(),
+ }
+ }
+
+ /// Every drawable instance's slot, mesh and world-from-local transform.
+ ///
+ /// Only the `wgpu-core` TLAS build path needs this, to fill in the instance descriptors that
+ /// the raw path sets up on the GPU. Slots with a null acceleration structure reference are not
+ /// currently drawable, and are left out.
+ pub fn drawable(&self) -> impl Iterator<Item = (u32, AssetId<Mesh>, [f32; 12], u8)> + '_ {
+ self.records.values().filter_map(|instance| {
+ let slot = instance.slot;
+ (self.blas_refs.get(slot) != GpuBlasRef::NONE)
+ .then(|| (slot, instance.mesh, self.transforms.get(slot).rows(), self.masks.get(slot) as u8))
+ })
+ }
+
+ /// Queues every instance using `material_id` to be re-resolved.
+ pub fn invalidate_material(&mut self, material_id: AssetId<StandardMaterial>) {
+ if let Some(instances) = self.material_instances.get(&material_id) {
+ self.pending_refresh.extend(instances.iter().copied());
+ }
+ }
+}
+
+pub type InstanceQueryData<'w> = (
+ &'w RaytracingMesh3d,
+ &'w MeshMaterial3d<StandardMaterial>,
+ &'w GlobalTransform,
+ &'w PreviousGlobalTransform,
+);
+
+pub type ChangedInstanceFilter = (
+ With<RaytracingMesh3d>,
+ Or<(
+ Changed<RaytracingMesh3d>,
+ Changed<MeshMaterial3d<StandardMaterial>>,
+ )>,
+);
+
+/// The scene state an instance resolves its GPU data against.
+pub struct InstanceInputs<'a> {
+ pub assets: &'a AssetState,
+ pub blas_manager: &'a BlasManager,
+ pub mesh_allocator: &'a MeshAllocator,
+}
+
+fn unlink<K: Eq + Hash>(map: &mut HashMap<K, EntityHashSet>, key: &K, entity: Entity) {
+ let now_empty = map.get_mut(key).is_some_and(|instances| {
+ instances.remove(&entity);
+ instances.is_empty()
+ });
+ if now_empty {
+ map.remove(key);
+ }
+}
+
+fn relink<K: Copy + Eq + Hash>(
+ map: &mut HashMap<K, EntityHashSet>,
+ entity: Entity,
+ previous: Option<K>,
+ key: K,
+) {
+ if previous == Some(key) {
+ return;
+ }
+ if let Some(previous) = previous {
+ unlink(map, &previous, entity);
+ }
+ map.entry(key).or_default().insert(entity);
+}
+
+impl InstanceState {
+ pub fn remove_instances(
+ &mut self,
+ lights: &mut LightState,
+ removed: impl IntoIterator<Item = Entity>,
+ ) {
+ let _span = info_span!("remove_instances").entered();
+ for entity in removed {
+ self.remove_instance(lights, entity);
+ }
+ }
+
+ pub fn refresh_instances(
+ &mut self,
+ inputs: &InstanceInputs,
+ lights: &mut LightState,
+ instances: &Query<InstanceQueryData>,
+ changed_instances: &Query<Entity, ChangedInstanceFilter>,
+ ) {
+ let _span = info_span!("refresh_instances").entered();
+
+ let mut refresh = core::mem::take(&mut self.pending_refresh);
+ refresh.extend(changed_instances.iter());
+
+ let moved_meshes = inputs.mesh_allocator.meshes_displaced_by_slab_growth();
+ for mesh_id in inputs
+ .blas_manager
+ .changed_meshes()
+ .iter()
+ .copied()
+ .chain(moved_meshes)
+ {
+ if let Some(mesh_instances) = self.mesh_instances.get(&mesh_id) {
+ refresh.extend(mesh_instances.iter().copied());
+ }
+ }
+
+ for entity in refresh {
+ match instances.get(entity) {
+ Ok(data) => self.refresh_instance(inputs, lights, entity, data),
+ Err(_) => self.remove_instance(lights, entity),
+ }
+ }
+ }
+
+ fn reserve_slot(&mut self, slot: u32) {
+ let len = slot + 1;
+ self.transforms.grow(len);
+ self.previous_frame_transforms.grow(len);
+ self.blas_refs.grow(len);
+ self.masks.grow(len);
+ }
+
+ fn refresh_instance(
+ &mut self,
+ inputs: &InstanceInputs,
+ lights: &mut LightState,
+ entity: Entity,
+ (mesh, material, transform, previous_frame_transform): InstanceQueryData,
+ ) {
+ let mesh_id = mesh.id();
+ let material_id = material.id();
+ let previous = self.records.get(&entity).copied();
+
+ relink(
+ &mut self.mesh_instances,
+ entity,
+ previous.map(|instance| instance.mesh),
+ mesh_id,
+ );
+ relink(
+ &mut self.material_instances,
+ entity,
+ previous.map(|instance| instance.material),
+ material_id,
+ );
+
+ let slot = match previous {
+ Some(previous) => previous.slot,
+ None => self.slots.allocate(),
+ };
+ self.reserve_slot(slot);
+
+ // Seed only once. Later refreshes must not overwrite transforms written by extraction.
+ if previous.is_none() {
+ self.write_transforms(slot, transform, previous_frame_transform);
+ }
+
+ let mut instance = Instance {
+ slot,
+ mesh: mesh_id,
+ material: material_id,
+ buffers: previous.and_then(|instance| instance.buffers),
+ };
+ let resolved = self.resolve_instance(inputs, lights, entity, &mut instance);
+
+ self.records.insert(entity, instance);
+ if !resolved {
+ self.pending_refresh.insert(entity);
+ }
+ }
+
+ fn resolve_instance(
+ &mut self,
+ inputs: &InstanceInputs,
+ lights: &mut LightState,
+ entity: Entity,
+ instance: &mut Instance,
+ ) -> bool {
+ let slot = instance.slot;
+ let (Some(vertex_slice), Some(index_slice), Some(material_slot), Some(blas_address)) = (
+ inputs.mesh_allocator.mesh_vertex_slice(&instance.mesh),
+ inputs.mesh_allocator.mesh_index_slice(&instance.mesh),
+ inputs.assets.material_slots.get(&instance.material),
+ inputs.blas_manager.device_address(&instance.mesh),
+ ) else {
+ self.deactivate_instance(lights, entity, instance);
+ return false;
+ };
+
+ let vertex_buffer_key = vertex_slice.buffer.id();
+ let index_buffer_key = index_slice.buffer.id();
+ let capacity = MAX_MESH_SLAB_COUNT.get();
+ if !self.vertex_buffers.has_room(&vertex_buffer_key, capacity)
+ || !self.index_buffers.has_room(&index_buffer_key, capacity)
+ {
+ once!(warn!(
+ "Solari scene needs more than {} mesh slabs. Instances past that limit will \
+ not be rendered.",
+ MAX_MESH_SLAB_COUNT.get()
+ ));
+ self.deactivate_instance(lights, entity, instance);
+ return false;
+ }
+
+ let previous_buffers = instance.buffers.take();
+ let vertex_buffer_id = self
+ .vertex_buffers
+ .acquire(vertex_buffer_key, capacity, || vertex_slice.buffer.clone())
+ .expect("vertex slab binding array had room but handed out no slot");
+ let index_buffer_id = self
+ .index_buffers
+ .acquire(index_buffer_key, capacity, || index_slice.buffer.clone())
+ .expect("index slab binding array had room but handed out no slot");
+ instance.buffers = Some((vertex_buffer_key, index_buffer_key));
+ self.release_buffers(previous_buffers);
+
+ let triangle_count = (index_slice.range.len() / 3) as u32;
+ self.geometry_ids.grow_and_set(
+ slot,
+ GpuInstanceGeometryIds {
+ vertex_buffer_id,
+ vertex_buffer_offset: vertex_slice.range.start,
+ index_buffer_id,
+ index_buffer_offset: index_slice.range.start,
+ triangle_count,
+ },
+ );
+ self.material_ids.grow_and_set(slot, material_slot);
+ let alpha = inputs.assets.alpha_materials.contains(&instance.material);
+ self.masks.grow_and_set(slot, if alpha { MASK_ALPHA } else { MASK_OPAQUE });
+ self.set_blas_ref(slot, GpuBlasRef(blas_address));
+
+ let is_emissive = inputs
+ .assets
+ .emissive_materials
+ .contains(&instance.material);
+ if is_emissive {
+ lights.add_light(
+ LightSourceId::EmissiveMesh(entity),
+ GpuLightSource::new_emissive_mesh_light(slot, triangle_count),
+ );
+ } else {
+ lights.remove_light(LightSourceId::EmissiveMesh(entity));
+ }
+ true
+ }
+
+ fn write_transforms(
+ &self,
+ slot: u32,
+ transform: &GlobalTransform,
+ previous_frame_transform: &PreviousGlobalTransform,
+ ) {
+ self.transforms.set_if_changed(
+ slot,
+ GpuTransform(Affine3::from(transform.affine()).to_transpose()),
+ );
+ self.previous_frame_transforms.set_if_changed(
+ slot,
+ GpuTransform(Affine3::from(previous_frame_transform.0).to_transpose()),
+ );
+ }
+
+ /// Points a slot at an acceleration structure, or at nothing, keeping `live_count` in step.
+ fn set_blas_ref(&mut self, slot: u32, reference: GpuBlasRef) {
+ self.blas_refs.grow(slot + 1);
+ let previous = self.blas_refs.get(slot);
+ if previous == reference {
+ return;
+ }
+ self.blas_refs.set(slot, reference);
+
+ if previous == GpuBlasRef::NONE {
+ self.live_count += 1;
+ } else if reference == GpuBlasRef::NONE {
+ self.live_count -= 1;
+ }
+ }
+
+ fn deactivate_instance(
+ &mut self,
+ lights: &mut LightState,
+ entity: Entity,
+ instance: &mut Instance,
+ ) {
+ self.set_blas_ref(instance.slot, GpuBlasRef::NONE);
+ lights.remove_light(LightSourceId::EmissiveMesh(entity));
+ self.release_buffers(instance.buffers.take());
+ }
+
+ fn release_buffers(&mut self, buffers: Option<(BufferId, BufferId)>) {
+ if let Some((vertex_key, index_key)) = buffers {
+ self.vertex_buffers.release(&vertex_key);
+ self.index_buffers.release(&index_key);
+ }
+ }
+
+ fn remove_instance(&mut self, lights: &mut LightState, entity: Entity) {
+ let Some(mut instance) = self.records.remove(&entity) else {
+ return;
+ };
+
+ self.deactivate_instance(lights, entity, &mut instance);
+ self.slots.release(instance.slot);
+ self.pending_refresh.remove(&entity);
+ unlink(&mut self.mesh_instances, &instance.mesh, entity);
+ unlink(&mut self.material_instances, &instance.material, entity);
+ }
+}
+
+impl RaytracingSceneBindings {
+ /// Parallel hot path: one entity lookup, then two allocation-free sparse writes.
+ pub fn move_instance(
+ &self,
+ entity: Entity,
+ transform: &GlobalTransform,
+ previous_frame_transform: &PreviousGlobalTransform,
+ ) {
+ if let Some(instance) = self.instances.records.get(&entity) {
+ self.instances
+ .write_transforms(instance.slot, transform, previous_frame_transform);
+ }
+ }
+}
diff --git a/vendor/bevy_solari/src/scene/binder/lights.rs b/vendor/bevy_solari/src/scene/binder/lights.rs
new file mode 100644
index 00000000..368d7f06
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/binder/lights.rs
@@ -0,0 +1,340 @@
+use super::allocator::SlotAllocator;
+use bevy_color::ColorToComponents;
+use bevy_ecs::{
+ entity::{Entity, EntityHashSet},
+ system::Query,
+};
+use bevy_math::{ops::cos, Vec3};
+use bevy_pbr::ExtractedDirectionalLight;
+use crate::scene::extract::ExtractedEnvironmentMapLight;
+use crate::scene::EnvironmentSun;
+use bevy_platform::collections::{HashMap, HashSet};
+use bevy_render::render_resource::{AtomicSparseBufferVec, BufferUsages};
+use bevy_render::{impl_atomic_pod, render_resource::AtomicPod};
+use bytemuck::{Pod, Zeroable};
+use core::sync::atomic::{AtomicBool, Ordering};
+use core::{f32::consts::TAU, hash::Hash};
+use tracing::info_span;
+
+const LIGHT_NOT_PRESENT_THIS_FRAME: u32 = u32::MAX;
+
+#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
+#[repr(C)]
+pub struct GpuLightSource {
+ kind: u32,
+ id: u32,
+}
+
+/// Stable identity for one source in the light array.
+///
+/// An entity can contribute both kinds at once, so the entity alone is not enough to identify a
+/// source.
+#[derive(Clone, Copy, Eq, Hash, PartialEq)]
+pub enum LightSourceId {
+ EmissiveMesh(Entity),
+ Directional(Entity),
+}
+
+#[derive(Default)]
+pub struct LightIndex {
+ indices: HashMap<LightSourceId, u32>,
+ ids: Vec<LightSourceId>,
+ changed: HashSet<LightSourceId>,
+}
+
+impl LightIndex {
+ pub fn len(&self) -> usize {
+ self.ids.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.ids.is_empty()
+ }
+
+ fn get(&self, id: &LightSourceId) -> Option<u32> {
+ self.indices.get(id).copied()
+ }
+
+ fn insert(&mut self, id: LightSourceId) -> u32 {
+ if let Some(&index) = self.indices.get(&id) {
+ return index;
+ }
+
+ let index = self.ids.len() as u32;
+ self.ids.push(id);
+ self.indices.insert(id, index);
+ self.changed.insert(id);
+ index
+ }
+
+ /// Removes `id` and reports both its old index and the old final index.
+ ///
+ /// Only the ids tracked here are swapped down. When the two indices differ, the caller has to
+ /// mirror that swap in `sources`, copying the element at the old final index into the hole.
+ fn remove(&mut self, id: LightSourceId) -> Option<(u32, u32)> {
+ let index = self.indices.remove(&id)?;
+ self.changed.insert(id);
+
+ let last = self.ids.len() as u32 - 1;
+ self.ids.swap_remove(index as usize);
+
+ if index != last {
+ let moved = self.ids[index as usize];
+ self.indices.insert(moved, index);
+ self.changed.insert(moved);
+ }
+
+ Some((index, last))
+ }
+}
+
+impl GpuLightSource {
+ pub fn new_emissive_mesh_light(instance_id: u32, triangle_count: u32) -> GpuLightSource {
+ if triangle_count > u16::MAX as u32 {
+ panic!("Too many triangles ({triangle_count}) in an emissive mesh, maximum is 65535.");
+ }
+
+ Self {
+ kind: triangle_count << 1,
+ id: instance_id,
+ }
+ }
+
+ fn new_directional_light(directional_light_id: u32) -> GpuLightSource {
+ Self {
+ kind: 1,
+ id: directional_light_id,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
+#[repr(C)]
+pub struct GpuDirectionalLight {
+ direction_to_light: Vec3,
+ cos_theta_max: f32,
+ luminance: Vec3,
+ inverse_pdf: f32,
+}
+
+impl_atomic_pod!(GpuLightSource, GpuLightSourceBlob);
+impl_atomic_pod!(GpuDirectionalLight, GpuDirectionalLightBlob);
+
+impl GpuDirectionalLight {
+ /// raea: an environment map's sun (EnvironmentSun), turned with the map and scaled by its intensity.
+ fn environment_sun(sun: &EnvironmentSun, environment: &ExtractedEnvironmentMapLight) -> Self {
+ let cos_theta_max = cos(sun.angular_size / 2.0);
+ let solid_angle = TAU * (1.0 - cos_theta_max);
+ Self {
+ direction_to_light: (environment.rotation * sun.direction).normalize(),
+ cos_theta_max,
+ luminance: sun.illuminance * environment.intensity / solid_angle,
+ inverse_pdf: solid_angle,
+ }
+ }
+
+ fn new(directional_light: &ExtractedDirectionalLight) -> Self {
+ let cos_theta_max = cos(directional_light.sun_disk_angular_size / 2.0);
+ let solid_angle = TAU * (1.0 - cos_theta_max);
+ let luminance =
+ (directional_light.color.to_vec3() * directional_light.illuminance) / solid_angle;
+
+ Self {
+ direction_to_light: directional_light.transform.back().into(),
+ cos_theta_max,
+ luminance,
+ inverse_pdf: solid_angle,
+ }
+ }
+}
+
+/// Light slots and the incremental previous-frame id translation state.
+pub struct LightState {
+ /// Kept gap-free because shaders derive the light count with `arrayLength`.
+ pub sources: AtomicSparseBufferVec<GpuLightSource>,
+ pub directional_lights: AtomicSparseBufferVec<GpuDirectionalLight>,
+ pub previous_frame_id_translations: AtomicSparseBufferVec<u32>,
+ pub index: LightIndex,
+ /// Light ids as of the last frame whose translation table the lighting shader actually read.
+ previous_index: HashMap<LightSourceId, u32>,
+ nonidentity_translations: Vec<u32>,
+ directional_slots: SlotAllocator<Entity>,
+ /// Set by the lighting node once it has recorded work reading the translation table.
+ translations_consumed: AtomicBool,
+}
+
+impl LightState {
+ pub fn new() -> Self {
+ Self {
+ sources: AtomicSparseBufferVec::new(
+ BufferUsages::STORAGE,
+ "solari_light_sources".into(),
+ ),
+ directional_lights: AtomicSparseBufferVec::new(
+ BufferUsages::STORAGE,
+ "solari_directional_lights".into(),
+ ),
+ previous_frame_id_translations: AtomicSparseBufferVec::new(
+ BufferUsages::STORAGE,
+ "solari_previous_frame_light_id_translations".into(),
+ ),
+ index: LightIndex::default(),
+ previous_index: HashMap::default(),
+ nonidentity_translations: Vec::new(),
+ directional_slots: SlotAllocator::new(),
+ translations_consumed: AtomicBool::new(false),
+ }
+ }
+
+ pub fn update(
+ &mut self,
+ directional_lights: &Query<(Entity, &ExtractedDirectionalLight)>,
+ environment: &ExtractedEnvironmentMapLight,
+ ) {
+ // There are few enough directional lights to just walk them every frame
+ let _span = info_span!("update_lights").entered();
+
+ let mut live_directional_lights = EntityHashSet::default();
+ for (entity, directional_light) in directional_lights {
+ live_directional_lights.insert(entity);
+
+ let slot = self.directional_slots.get_or_allocate(entity);
+ self.directional_lights
+ .grow_and_set(slot, GpuDirectionalLight::new(directional_light));
+ self.add_light(
+ LightSourceId::Directional(entity),
+ GpuLightSource::new_directional_light(slot),
+ );
+ }
+
+ // raea: the environment map's sun, as one more directional light, keyed by a placeholder entity no light has
+ if let (Some(sun), true) = (environment.sun, environment.cubemap.is_some() && environment.intensity > 0.0) {
+ live_directional_lights.insert(Entity::PLACEHOLDER);
+ let slot = self.directional_slots.get_or_allocate(Entity::PLACEHOLDER);
+ self.directional_lights
+ .grow_and_set(slot, GpuDirectionalLight::environment_sun(&sun, environment));
+ self.add_light(
+ LightSourceId::Directional(Entity::PLACEHOLDER),
+ GpuLightSource::new_directional_light(slot),
+ );
+ }
+
+ let stale: Vec<Entity> = self
+ .directional_slots
+ .keys()
+ .copied()
+ .filter(|entity| !live_directional_lights.contains(entity))
+ .collect();
+ for entity in stale {
+ self.directional_slots.remove(&entity);
+ self.remove_light(LightSourceId::Directional(entity));
+ }
+
+ self.write_light_id_translations();
+
+ if self.index.len() > u16::MAX as usize {
+ panic!("Too many light sources in the scene, maximum is 65535.");
+ }
+ }
+
+ pub fn add_light(&mut self, id: LightSourceId, source: GpuLightSource) {
+ let index = self.index.insert(id);
+ self.sources.grow_and_set(index, source);
+ }
+
+ /// Removes a light, moving the last one down into the hole so the array stays gap-free.
+ pub fn remove_light(&mut self, id: LightSourceId) {
+ let Some((index, last)) = self.index.remove(id) else {
+ return;
+ };
+
+ if index != last {
+ let source = self.sources.get(last);
+ self.sources.grow_and_set(index, source);
+ }
+ }
+
+ /// Rolls the translation table over for a new frame.
+ ///
+ /// `previous_index` and `changed` only advance once the shader has read the table. The
+ /// lighting node bails out while its pipelines compile, and the reservoirs keep the older ids
+ /// across such a gap, so the next table has to translate from those instead. `has_consumers`
+ /// is false when no view runs Solari lighting, where deferring forever would grow both
+ /// without bound.
+ pub fn begin_frame(&mut self, has_consumers: bool) {
+ for index in core::mem::take(&mut self.nonidentity_translations) {
+ self.previous_frame_id_translations
+ .grow_and_set(index, index);
+ }
+
+ if !has_consumers || self.translations_consumed.swap(false, Ordering::Relaxed) {
+ for id in core::mem::take(&mut self.index.changed) {
+ match self.index.get(&id) {
+ Some(index) => self.previous_index.insert(id, index),
+ None => self.previous_index.remove(&id),
+ };
+ }
+ }
+ }
+
+ /// Records that the lighting shader read this frame's translation table.
+ pub fn note_translations_consumed(&self) {
+ self.translations_consumed.store(true, Ordering::Relaxed);
+ }
+
+ /// Records where each light that moved or disappeared this frame ended up, so that reservoirs
+ /// still carrying last frame's light ids can be remapped.
+ fn write_light_id_translations(&mut self) {
+ for id in &self.index.changed {
+ // Lights that first appeared since the last read table have no previous id
+ let Some(&previous) = self.previous_index.get(id) else {
+ continue;
+ };
+ let current = self.index.get(id).unwrap_or(LIGHT_NOT_PRESENT_THIS_FRAME);
+
+ if current != previous {
+ self.previous_frame_id_translations
+ .grow_and_set(previous, current);
+ self.nonidentity_translations.push(previous);
+ }
+ }
+
+ // Every index the shader might read has to be backed by a real element
+ let light_count = self.index.len() as u32;
+ let translations = &mut self.previous_frame_id_translations;
+ if translations.len() < light_count {
+ let start = translations.len();
+ translations.grow(light_count);
+ for index in start..light_count {
+ translations.set(index, index);
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{LightIndex, LightSourceId};
+ use bevy_ecs::entity::Entity;
+
+ #[test]
+ fn light_index_keeps_sources_on_the_same_entity_independent() {
+ let entity = Entity::PLACEHOLDER;
+ let emissive = LightSourceId::EmissiveMesh(entity);
+ let directional = LightSourceId::Directional(entity);
+ let mut lights = LightIndex::default();
+
+ assert_eq!(lights.insert(emissive), 0);
+ assert_eq!(lights.insert(directional), 1);
+ assert_eq!(lights.insert(emissive), 0);
+ assert_eq!(lights.len(), 2);
+
+ assert_eq!(lights.remove(emissive), Some((0, 1)));
+ assert_eq!(lights.get(&emissive), None);
+ assert_eq!(lights.get(&directional), Some(0));
+ assert_eq!(lights.len(), 1);
+
+ assert_eq!(lights.remove(directional), Some((0, 0)));
+ assert!(lights.is_empty());
+ }
+}
diff --git a/vendor/bevy_solari/src/scene/binder/mod.rs b/vendor/bevy_solari/src/scene/binder/mod.rs
new file mode 100644
index 00000000..d269cc54
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/binder/mod.rs
@@ -0,0 +1,241 @@
+mod allocator;
+mod assets;
+mod bind_group;
+mod instances;
+mod lights;
+mod tlas;
+mod tlas_build;
+
+use self::assets::{AssetState, MAX_TEXTURE_COUNT};
+pub use self::bind_group::prepare_raytracing_scene_bind_group;
+use self::bind_group::{BindGroupCacheState, GpuEnvironmentMapLight};
+use self::instances::{
+ ChangedInstanceFilter, InstanceInputs, InstanceQueryData, InstanceState, MAX_MESH_SLAB_COUNT,
+};
+use self::lights::LightState;
+use self::tlas::TlasState;
+pub use self::tlas::{build_raytracing_tlas, TlasInstanceSetupPipeline};
+use super::{blas::BlasManager, extract::StandardMaterialAssets, RaytracingMesh3d};
+use bevy_ecs::{
+ entity::Entity,
+ lifecycle::RemovedComponents,
+ resource::Resource,
+ system::{Query, Res, ResMut},
+ world::{FromWorld, World},
+};
+use bevy_pbr::ExtractedDirectionalLight;
+use bevy_render::{
+ mesh::allocator::MeshAllocator,
+ render_asset::{ExtractedAssets, RenderAssets},
+ render_resource::{binding_types::*, *},
+ renderer::{RenderDevice, RenderQueue},
+ texture::GpuImage,
+};
+use tracing::info_span;
+
+/// Insert this resource into the render world to make the raytracing scene retain the previous
+/// frame's TLAS and the light id translation table that maps into it.
+///
+/// This is useful for temporal techniques that need last frame's data. Retaining it costs a second
+/// TLAS allocation and rebuild, so the scene only does so while something asks for it.
+#[derive(Resource, Default)]
+pub struct RaytracingSceneNeedsPreviousFrameData;
+
+#[derive(Resource)]
+pub struct RaytracingSceneBindings {
+ pub bind_group: Option<BindGroup>,
+ pub bind_group_layout: BindGroupLayoutDescriptor,
+ assets: AssetState,
+ instances: InstanceState,
+ lights: LightState,
+ tlas: TlasState,
+ bind_groups: BindGroupCacheState,
+ environment_map_light_sampler: Sampler,
+ environment_map_light_buffer: StorageBuffer<GpuEnvironmentMapLight>,
+}
+
+impl RaytracingSceneBindings {
+ /// Records that a lighting pass read `previous_frame_light_id_translations`, so the next
+ /// frame's table translates from this frame's light ids rather than older ones.
+ pub fn note_light_translations_consumed(&self) {
+ self.lights.note_translations_consumed();
+ }
+}
+
+impl FromWorld for RaytracingSceneBindings {
+ fn from_world(world: &mut World) -> Self {
+ let render_device = world.resource::<RenderDevice>();
+
+ let bind_group_layout = BindGroupLayoutDescriptor::new(
+ "raytracing_scene_bind_group_layout",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ storage_buffer_read_only_sized(false, None).count(MAX_MESH_SLAB_COUNT),
+ storage_buffer_read_only_sized(false, None).count(MAX_MESH_SLAB_COUNT),
+ texture_2d(TextureSampleType::Float { filterable: true })
+ .count(MAX_TEXTURE_COUNT),
+ sampler(SamplerBindingType::Filtering).count(MAX_TEXTURE_COUNT),
+ storage_buffer_read_only_sized(false, None),
+ acceleration_structure(),
+ acceleration_structure(),
+ storage_buffer_read_only_sized(false, None),
+ storage_buffer_read_only_sized(false, None),
+ storage_buffer_read_only_sized(false, None),
+ storage_buffer_read_only_sized(false, None),
+ storage_buffer_read_only_sized(false, None),
+ storage_buffer_read_only_sized(false, None),
+ storage_buffer_read_only_sized(false, None),
+ texture_2d(TextureSampleType::Float { filterable: true }),
+ sampler(SamplerBindingType::Filtering),
+ texture_cube(TextureSampleType::Float { filterable: true }),
+ sampler(SamplerBindingType::Filtering),
+ storage_buffer_read_only_sized(false, None),
+ ),
+ ),
+ );
+
+ let environment_map_light_sampler = render_device.create_sampler(&SamplerDescriptor {
+ label: Some("solari_environment_map_light_sampler"),
+ address_mode_u: AddressMode::ClampToEdge,
+ address_mode_v: AddressMode::ClampToEdge,
+ address_mode_w: AddressMode::ClampToEdge,
+ mag_filter: FilterMode::Linear,
+ min_filter: FilterMode::Linear,
+ mipmap_filter: MipmapFilterMode::Linear,
+ ..Default::default()
+ });
+
+ let mut environment_map_light_buffer = StorageBuffer::<GpuEnvironmentMapLight>::default();
+ environment_map_light_buffer.set_label(Some("solari_environment_map_light"));
+
+ Self {
+ bind_group: None,
+ bind_group_layout,
+ assets: AssetState::new(),
+ instances: InstanceState::new(),
+ lights: LightState::new(),
+ tlas: TlasState::new(render_device),
+ bind_groups: BindGroupCacheState::new(render_device),
+ environment_map_light_sampler,
+ environment_map_light_buffer,
+ }
+ }
+}
+
+/// Applies this frame's scene changes to the retained buffers, binding arrays and TLAS.
+pub fn prepare_raytracing_scene_resources(
+ instances: Query<InstanceQueryData>,
+ changed_instances: Query<Entity, ChangedInstanceFilter>,
+ mut removed_instances: RemovedComponents<RaytracingMesh3d>,
+ directional_lights: Query<(Entity, &ExtractedDirectionalLight)>,
+ // raea: for its EnvironmentSun, one more directional light
+ environment_map_light: Res<crate::scene::extract::ExtractedEnvironmentMapLight>,
+ needs_previous_frame_data: Option<Res<RaytracingSceneNeedsPreviousFrameData>>,
+ mesh_allocator: Res<MeshAllocator>,
+ blas_manager: Res<BlasManager>,
+ material_assets: Res<StandardMaterialAssets>,
+ texture_assets: Res<RenderAssets<GpuImage>>,
+ extracted_images: Res<ExtractedAssets<GpuImage>>,
+ render_device: Res<RenderDevice>,
+ render_queue: Res<RenderQueue>,
+ pipeline_cache: Res<PipelineCache>,
+ instance_setup_pipeline: Res<TlasInstanceSetupPipeline>,
+ mut bindings: ResMut<RaytracingSceneBindings>,
+) {
+ let bindings = &mut *bindings;
+ let needs_previous_frame_data = needs_previous_frame_data.is_some();
+
+ // Roll light ids over before any removal or compaction writes this frame's translations
+ bindings.lights.begin_frame(needs_previous_frame_data);
+
+ // Update material and texture assets
+ bindings
+ .assets
+ .update_materials(&mut bindings.instances, &material_assets, &texture_assets);
+ bindings.assets.update_textures(
+ &mut bindings.instances,
+ &extracted_images,
+ &texture_assets,
+ &material_assets,
+ );
+
+ // Apply structural instance changes, now that asset slots are current
+ bindings
+ .instances
+ .remove_instances(&mut bindings.lights, removed_instances.read());
+ let inputs = InstanceInputs {
+ assets: &bindings.assets,
+ blas_manager: &blas_manager,
+ mesh_allocator: &mesh_allocator,
+ };
+ bindings.instances.refresh_instances(
+ &inputs,
+ &mut bindings.lights,
+ &instances,
+ &changed_instances,
+ );
+
+ // Update the light set, now that emissive instances are resolved
+ bindings.lights.update(&directional_lights, &environment_map_light);
+
+ // Upload the above writes
+ write_sparse_buffers(bindings, &render_device, &render_queue);
+
+ // Prepare the next TLAS
+ let build_ready = !bindings.tlas.uses_raw_build()
+ || instance_setup_pipeline
+ .id
+ .and_then(|id| pipeline_cache.get_compute_pipeline(id))
+ .is_some();
+ bindings.tlas.advance(
+ &bindings.instances,
+ &mut bindings.bind_groups,
+ &render_device,
+ build_ready,
+ needs_previous_frame_data,
+ );
+}
+
+/// Grows every sparse buffer to hold at least one element, then snapshots its dirty set into
+/// either a staged sparse update or a full reupload.
+fn write_sparse_buffers(
+ bindings: &mut RaytracingSceneBindings,
+ device: &RenderDevice,
+ queue: &RenderQueue,
+) {
+ let _span = info_span!("write_buffers").entered();
+
+ let assets = &mut bindings.assets;
+ assets.materials.grow(1);
+ assets.materials.write_buffers(device, queue);
+
+ let instances = &mut bindings.instances;
+ instances.transforms.grow(1);
+ instances.transforms.write_buffers(device, queue);
+ instances.previous_frame_transforms.grow(1);
+ instances
+ .previous_frame_transforms
+ .write_buffers(device, queue);
+ instances.geometry_ids.grow(1);
+ instances.geometry_ids.write_buffers(device, queue);
+ instances.material_ids.grow(1);
+ instances.material_ids.write_buffers(device, queue);
+ if bindings.tlas.uses_raw_build() {
+ instances.blas_refs.grow(1);
+ instances.blas_refs.write_buffers(device, queue);
+ // raea: the instance masks, which the raw build's setup shader reads
+ instances.masks.grow(1);
+ instances.masks.write_buffers(device, queue);
+ }
+
+ let lights = &mut bindings.lights;
+ lights.sources.grow(1);
+ lights.sources.write_buffers(device, queue);
+ lights.directional_lights.grow(1);
+ lights.directional_lights.write_buffers(device, queue);
+ lights.previous_frame_id_translations.grow(1);
+ lights
+ .previous_frame_id_translations
+ .write_buffers(device, queue);
+}
diff --git a/vendor/bevy_solari/src/scene/binder/setup_tlas_instances.wesl b/vendor/bevy_solari/src/scene/binder/setup_tlas_instances.wesl
new file mode 100644
index 00000000..3707177c
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/binder/setup_tlas_instances.wesl
@@ -0,0 +1,27 @@
+@group(0) @binding(0) var<storage, read> transforms: array<array<vec4<f32>, 3>>;
+@group(0) @binding(1) var<storage, read> blas_refs: array<vec2<u32>>;
+@group(0) @binding(2) var<storage, read_write> instances: array<TlasInstance>;
+// raea: each slot's instance mask (instances.rs MASK_OPAQUE / MASK_ALPHA)
+@group(0) @binding(3) var<storage, read> masks: array<u32>;
+
+struct TlasInstance {
+ transform: array<vec4<f32>, 3>,
+ custom_data_and_mask: u32,
+ sbt_offset_and_flags: u32,
+ blas_ref: vec2<u32>,
+}
+
+@compute @workgroup_size(64, 1, 1)
+fn setup_tlas_instances(@builtin(global_invocation_id) global_id: vec3<u32>) {
+ let slot = global_id.x;
+ if slot >= arrayLength(&instances) || slot >= arrayLength(&blas_refs) || slot >= arrayLength(&transforms) || slot >= arrayLength(&masks) {
+ return;
+ }
+
+ instances[slot] = TlasInstance(
+ transforms[slot],
+ (slot & 0xFFFFFFu) | ((masks[slot] & 0xFFu) << 24u),
+ 0u,
+ blas_refs[slot],
+ );
+}
diff --git a/vendor/bevy_solari/src/scene/binder/tlas.rs b/vendor/bevy_solari/src/scene/binder/tlas.rs
new file mode 100644
index 00000000..829712d9
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/binder/tlas.rs
@@ -0,0 +1,540 @@
+use super::{
+ bind_group::BindGroupCacheState, instances::InstanceState, tlas_build, BlasManager,
+ RaytracingSceneBindings,
+};
+use bevy_asset::load_embedded_asset;
+use bevy_ecs::{
+ resource::Resource,
+ system::{Res, ResMut},
+ world::{FromWorld, World},
+};
+use bevy_render::{
+ diagnostic::RecordDiagnostics,
+ render_resource::{
+ binding_types::{storage_buffer_read_only_sized, storage_buffer_sized},
+ AccelerationStructureFlags, AccelerationStructureUpdateMode, BindGroup, BindGroupEntries,
+ BindGroupLayoutDescriptor, BindGroupLayoutEntries, Buffer, BufferDescriptor, BufferId,
+ BufferUsages, CachedComputePipelineId, CommandEncoderDescriptor, ComputePassDescriptor,
+ ComputePipelineDescriptor, CreateTlasDescriptor, PipelineCache, ShaderStages, Tlas,
+ TlasInstance,
+ },
+ renderer::{RenderContext, RenderDevice},
+};
+use bevy_utils::{default, once};
+use tracing::{info_span, warn};
+use wgpu::{BufferTransition, BufferUses};
+
+/// Compute pipeline that writes per-slot transforms and BLAS addresses into TLAS descriptors.
+#[derive(Resource)]
+pub struct TlasInstanceSetupPipeline {
+ pub layout: BindGroupLayoutDescriptor,
+ pub id: Option<CachedComputePipelineId>,
+}
+
+impl FromWorld for TlasInstanceSetupPipeline {
+ fn from_world(world: &mut World) -> Self {
+ let layout = BindGroupLayoutDescriptor::new(
+ "tlas_instance_setup_bind_group_layout",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ storage_buffer_read_only_sized(false, None),
+ storage_buffer_read_only_sized(false, None),
+ storage_buffer_sized(false, None),
+ // raea: each slot's instance mask (instances.rs MASK_*)
+ storage_buffer_read_only_sized(false, None),
+ ),
+ ),
+ );
+
+ if tlas_build::resolve(world.resource::<RenderDevice>()).is_none() {
+ return Self { layout, id: None };
+ }
+
+ let shader = load_embedded_asset!(world, "setup_tlas_instances.wesl");
+ let id =
+ world
+ .resource::<PipelineCache>()
+ .queue_compute_pipeline(ComputePipelineDescriptor {
+ label: Some("tlas_instance_setup_pipeline".into()),
+ layout: vec![layout.clone()],
+ shader,
+ entry_point: Some("setup_tlas_instances".into()),
+ ..default()
+ });
+
+ Self {
+ layout,
+ id: Some(id),
+ }
+ }
+}
+
+/// Smallest TLAS instance capacity handed out, and the floor [`tlas_capacity_for`] grows from.
+const TLAS_MIN_CAPACITY: u32 = 128;
+
+/// Width of a TLAS instance's custom data in both Vulkan (`instanceCustomIndex`) and DXR
+/// (`InstanceID`). `setup_tlas_instances.wgsl` writes instance slots into that field, so they have
+/// to fit.
+const TLAS_CUSTOM_DATA_BITS: u32 = 24;
+
+/// Instance capacity to allocate to hold `instance_count` slots.
+///
+/// Grows geometrically rather than by a fixed step, so reallocations over a scene's lifetime are
+/// logarithmic in its size. Being a pure function of the count keeps the descriptor buffer and both
+/// TLASes on the same capacity curve without having to coordinate their previous sizes.
+fn tlas_capacity_for(instance_count: u32) -> u32 {
+ let mut capacity = TLAS_MIN_CAPACITY;
+ while capacity < instance_count {
+ capacity = capacity.saturating_add(capacity.div_ceil(2));
+ }
+ capacity
+}
+
+/// The TLAS and its capacity state, double buffered only while something traces last frame's.
+///
+/// An acceleration structure is only bindable once it has been built. Nothing here owns a BLAS:
+/// keeping the ones a built structure points at alive is [`BlasManager`]'s job, which defers every
+/// retirement until [`BlasManager::note_tlas_build`] has seen both structures rebuilt.
+pub struct TlasState {
+ /// The backend to build through, or `None` to go through `wgpu-core`.
+ raw: Option<&'static dyn tlas_build::RawTlasBackend>,
+ /// Whether last frame's structure is being retained alongside this frame's.
+ double_buffered: bool,
+ /// Alternating current/previous acceleration structures. The second is `None` while single
+ /// buffered.
+ pub structures: [Option<Tlas>; 2],
+ capacity: [u32; 2],
+ /// Whether each structure has had a build recorded since its latest allocation.
+ pub built: [bool; 2],
+ /// Which of [`Self::structures`] this frame builds into. The other holds last frame's.
+ pub current_index: usize,
+ pub instance_descriptors: Option<Buffer>,
+ instance_descriptor_capacity: u32,
+ pub scratch: Option<Buffer>,
+ scratch_capacity: u64,
+ scratch_sized_for: u32,
+ pub instance_setup_bind_group: Option<BindGroup>,
+ instance_setup_buffer_ids: Option<[BufferId; 4]>,
+}
+
+impl TlasState {
+ pub fn new(render_device: &RenderDevice) -> Self {
+ Self {
+ raw: tlas_build::resolve(render_device),
+ double_buffered: false,
+ structures: [None, None],
+ capacity: [0, 0],
+ built: [false, false],
+ current_index: 0,
+ instance_descriptors: None,
+ instance_descriptor_capacity: 0,
+ scratch: None,
+ scratch_capacity: 0,
+ scratch_sized_for: 0,
+ instance_setup_bind_group: None,
+ instance_setup_buffer_ids: None,
+ }
+ }
+
+ /// Whether builds go through [`tlas_build`]'s raw path rather than `wgpu-core`.
+ pub fn uses_raw_build(&self) -> bool {
+ self.raw.is_some()
+ }
+
+ /// Brings the acceleration structure up to date with this frame's changes.
+ ///
+ /// While `double_buffered`, the two structures alternate: this frame's is rebuilt, and last
+ /// frame's stays intact so the shaders can trace against it. Otherwise the single structure is
+ /// rebuilt in place, which is safe because the build is recorded before any pass that traces
+ /// it and nothing reads last frame's contents.
+ ///
+ /// `build_ready` reports whether this frame will be able to record a build. When false nothing
+ /// is allocated or swapped, though an unused structure is still released.
+ pub fn advance(
+ &mut self,
+ instances: &InstanceState,
+ bind_groups: &mut BindGroupCacheState,
+ render_device: &RenderDevice,
+ build_ready: bool,
+ double_buffered: bool,
+ ) {
+ let _span = info_span!("advance_tlas").entered();
+
+ // Free the retained structure as soon as nothing wants it
+ self.set_double_buffered(double_buffered, bind_groups);
+
+ // An empty scene must not allocate an unbuilt TLAS that could resurface as a later
+ // previous-frame entry
+ if !build_ready || instances.slots.high_water_mark() == 0 {
+ return;
+ }
+
+ debug_assert!(
+ instances.slots.high_water_mark() < 1 << TLAS_CUSTOM_DATA_BITS,
+ "instance slot count {} does not fit in a TLAS instance's custom data",
+ instances.slots.high_water_mark()
+ );
+
+ // Secure every build input before committing the swap. Neither buffer exists on the
+ // wgpu-core path, which builds from instances written into the TLAS itself.
+ let instance_count = instances.slots.high_water_mark();
+ if self.raw.is_some() {
+ self.reserve_instance_descriptors(instance_count, render_device);
+ self.reserve_tlas_scratch(render_device);
+ if self.instance_descriptors.is_none() || self.scratch.is_none() {
+ return;
+ }
+ }
+
+ if self.double_buffered {
+ self.current_index ^= 1;
+ }
+ let current_index = self.current_index;
+ self.reserve_tlas(current_index, instance_count, render_device, bind_groups);
+ }
+
+ /// Switches between retaining last frame's structure and rebuilding a single one in place,
+ /// dropping the structure that is no longer traced.
+ fn set_double_buffered(
+ &mut self,
+ double_buffered: bool,
+ bind_groups: &mut BindGroupCacheState,
+ ) {
+ if self.double_buffered != double_buffered {
+ self.double_buffered = double_buffered;
+ bind_groups.invalid = true;
+ }
+ if double_buffered {
+ return;
+ }
+
+ // Keep building into whichever structure is already current, so the frame this turns off
+ // does not have to allocate
+ let previous_index = self.current_index ^ 1;
+ if self.structures[previous_index].take().is_some() {
+ self.capacity[previous_index] = 0;
+ self.built[previous_index] = false;
+ bind_groups.invalid = true;
+ }
+ }
+
+ /// Whether the previous-frame slot's binding will still be correct next frame, and so whether
+ /// a bind group using it can be cached.
+ pub fn previous_binding_is_stable(&self) -> bool {
+ !self.double_buffered || self.built[self.current_index ^ 1]
+ }
+
+ /// Rebuilds the setup shader's bind group only when one of its four buffers moves.
+ pub fn update_instance_setup_bind_group(
+ &mut self,
+ instances: &InstanceState,
+ render_device: &RenderDevice,
+ pipeline_cache: &PipelineCache,
+ pipeline: &TlasInstanceSetupPipeline,
+ ) {
+ let (Some(transforms), Some(blas_refs), Some(instances), Some(masks)) = (
+ instances.transforms.buffer(),
+ instances.blas_refs.buffer(),
+ self.instance_descriptors.as_ref(),
+ instances.masks.buffer(),
+ ) else {
+ self.instance_setup_bind_group = None;
+ return;
+ };
+
+ let ids = [transforms.id(), blas_refs.id(), instances.id(), masks.id()];
+ if self.instance_setup_bind_group.is_some() && self.instance_setup_buffer_ids == Some(ids) {
+ return;
+ }
+
+ let layout = pipeline_cache.get_bind_group_layout(&pipeline.layout);
+ self.instance_setup_bind_group = Some(render_device.create_bind_group(
+ "tlas_instance_setup_bind_group",
+ &layout,
+ &BindGroupEntries::sequential((
+ transforms.as_entire_binding(),
+ blas_refs.as_entire_binding(),
+ instances.as_entire_binding(),
+ masks.as_entire_binding(),
+ )),
+ ));
+ self.instance_setup_buffer_ids = Some(ids);
+ }
+
+ /// Makes sure the instance descriptor buffer covers every stable slot.
+ fn reserve_instance_descriptors(&mut self, needed: u32, render_device: &RenderDevice) {
+ if self.instance_descriptors.is_some() && needed <= self.instance_descriptor_capacity {
+ return;
+ }
+
+ let capacity = tlas_capacity_for(needed);
+ self.instance_descriptors = Some(render_device.create_buffer(&BufferDescriptor {
+ label: Some("solari_tlas_instance_descriptors"),
+ size: u64::from(capacity) * tlas_build::INSTANCE_DESCRIPTOR_SIZE,
+ usage: BufferUsages::STORAGE | BufferUsages::TLAS_INPUT,
+ mapped_at_creation: false,
+ }));
+ self.instance_descriptor_capacity = capacity;
+ self.instance_setup_bind_group = None;
+ }
+
+ /// Makes sure the build scratch buffer is big enough for this frame's descriptor capacity.
+ fn reserve_tlas_scratch(&mut self, render_device: &RenderDevice) {
+ let capacity = self.instance_descriptor_capacity;
+ if self.scratch.is_some() && capacity <= self.scratch_sized_for {
+ return;
+ }
+
+ let (Some(backend), Some(instances)) = (self.raw, self.instance_descriptors.as_ref())
+ else {
+ return;
+ };
+ let Some(needed) = backend.scratch_size(render_device, instances, capacity) else {
+ return;
+ };
+ self.scratch_sized_for = capacity;
+
+ if self.scratch.is_some() && needed <= self.scratch_capacity {
+ return;
+ }
+
+ // The setup transition lets wgpu retain an outgrown scratch buffer until in-flight work
+ // releases it
+ self.scratch = backend.create_scratch_buffer(render_device, needed);
+ self.scratch_capacity = if self.scratch.is_some() { needed } else { 0 };
+ }
+
+ /// Makes sure one of the two structures can hold every instance slot, leaving the other alone.
+ fn reserve_tlas(
+ &mut self,
+ current_index: usize,
+ needed: u32,
+ render_device: &RenderDevice,
+ bind_groups: &mut BindGroupCacheState,
+ ) {
+ if self.structures[current_index].is_some() && needed <= self.capacity[current_index] {
+ return;
+ }
+
+ let capacity = tlas_capacity_for(needed);
+ self.structures[current_index] = Some(render_device.wgpu_device().create_tlas(
+ &CreateTlasDescriptor {
+ label: Some("tlas"),
+ flags: AccelerationStructureFlags::PREFER_FAST_TRACE,
+ update_mode: AccelerationStructureUpdateMode::Build,
+ max_instances: capacity,
+ },
+ ));
+ self.capacity[current_index] = capacity;
+ self.built[current_index] = false;
+ bind_groups.invalid = true;
+ }
+}
+
+/// Records this frame's TLAS build into the render graph's command encoder.
+pub fn build_raytracing_tlas(
+ mut bindings: ResMut<RaytracingSceneBindings>,
+ mut blas_manager: ResMut<BlasManager>,
+ pipeline_cache: Res<PipelineCache>,
+ pipeline: Res<TlasInstanceSetupPipeline>,
+ mut render_context: RenderContext,
+) {
+ let bindings = &mut *bindings;
+ let current_index = bindings.tlas.current_index;
+
+ let built = match bindings.tlas.raw {
+ Some(backend) => {
+ setup_tlas_instances(bindings, &pipeline_cache, &pipeline, &mut render_context)
+ && build_tlas_raw(bindings, backend, &mut render_context)
+ }
+ None => build_tlas_through_wgpu_core(bindings, &blas_manager, &mut render_context),
+ };
+
+ if built {
+ bindings.tlas.built[current_index] = true;
+ // This structure no longer points at whatever was retired before it, which is what lets the
+ // oldest retirements go
+ blas_manager.note_tlas_build();
+ }
+}
+
+/// Writes this frame's TLAS instance descriptors on the GPU, ready for [`build_tlas_raw`].
+///
+/// Returns whether the pass was recorded. The build has nothing to read when it wasn't.
+fn setup_tlas_instances(
+ bindings: &mut RaytracingSceneBindings,
+ pipeline_cache: &PipelineCache,
+ pipeline: &TlasInstanceSetupPipeline,
+ render_context: &mut RenderContext,
+) -> bool {
+ if bindings.tlas.structures[bindings.tlas.current_index].is_none() {
+ return false;
+ }
+
+ let (Some(bind_group), Some(compute_pipeline), Some(instances), Some(scratch)) = (
+ bindings.tlas.instance_setup_bind_group.as_ref(),
+ pipeline
+ .id
+ .and_then(|id| pipeline_cache.get_compute_pipeline(id)),
+ bindings.tlas.instance_descriptors.as_ref(),
+ bindings.tlas.scratch.as_ref(),
+ ) else {
+ // `advance` secures all of these before it allocates the TLAS this is setting up for
+ once!(warn!(
+ "TLAS allocated but its instance setup pass could not be recorded: bind group={}, \
+ descriptors={}, scratch={}",
+ bindings.tlas.instance_setup_bind_group.is_some(),
+ bindings.tlas.instance_descriptors.is_some(),
+ bindings.tlas.scratch.is_some(),
+ ));
+ return false;
+ };
+
+ let slot_count = bindings.instances.slots.high_water_mark();
+ if slot_count == 0 {
+ return false;
+ }
+
+ let diagnostics = render_context.diagnostic_recorder();
+ let diagnostics = diagnostics.as_deref();
+ let command_encoder = render_context.command_encoder();
+ let time_span = diagnostics.time_span(command_encoder, "setup_tlas_instances");
+ {
+ let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
+ label: Some("setup_tlas_instances"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(compute_pipeline);
+ pass.set_bind_group(0, bind_group, &[]);
+ pass.dispatch_workgroups(slot_count.div_ceil(64), 1, 1);
+ }
+ time_span.end(command_encoder);
+
+ command_encoder.transition_resources(
+ [
+ BufferTransition {
+ buffer: &**instances,
+ state: BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT,
+ },
+ BufferTransition {
+ buffer: &**scratch,
+ state: BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
+ },
+ ]
+ .into_iter(),
+ core::iter::empty(),
+ );
+
+ true
+}
+
+/// Builds from the descriptors [`setup_tlas_instances`] wrote, straight through `wgpu_hal`.
+fn build_tlas_raw(
+ bindings: &mut RaytracingSceneBindings,
+ backend: &dyn tlas_build::RawTlasBackend,
+ render_context: &mut RenderContext,
+) -> bool {
+ let current_index = bindings.tlas.current_index;
+ let (Some(tlas), Some(instances), Some(scratch)) = (
+ bindings.tlas.structures[current_index].as_mut(),
+ bindings.tlas.instance_descriptors.as_ref(),
+ bindings.tlas.scratch.as_ref(),
+ ) else {
+ once!(warn!(
+ "TLAS instances were set up but not built: structure={}, descriptors={}, scratch={}",
+ bindings.tlas.structures[current_index].is_some(),
+ bindings.tlas.instance_descriptors.is_some(),
+ bindings.tlas.scratch.is_some(),
+ ));
+ return false;
+ };
+
+ let render_device = render_context.render_device().clone();
+ let diagnostics = render_context.diagnostic_recorder();
+ let diagnostics = diagnostics.as_deref();
+ let time_span = diagnostics.time_span(render_context.command_encoder(), "tlas_build");
+
+ let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor {
+ label: Some("tlas_build_command_encoder"),
+ });
+ let built = backend.build_tlas(
+ &mut command_encoder,
+ tlas,
+ instances,
+ bindings.instances.slots.high_water_mark(),
+ scratch,
+ );
+ render_context.add_command_buffer(command_encoder.finish());
+
+ time_span.end(render_context.command_encoder());
+ if !built {
+ once!(warn!(
+ "TLAS build recorded nothing; the resolved backend does not own the build resources."
+ ));
+ }
+ built
+}
+
+/// Builds from instance descriptors filled in on the CPU, through `wgpu-core`.
+///
+/// The portable path, and the only one Metal can use. It costs work per instance every frame rather
+/// than only for the ones that moved, and `wgpu-core` then re-derives the whole build from what it
+/// is handed here, which is the cost [`tlas_build`] exists to avoid.
+fn build_tlas_through_wgpu_core(
+ bindings: &mut RaytracingSceneBindings,
+ blas_manager: &BlasManager,
+ render_context: &mut RenderContext,
+) -> bool {
+ // An empty scene leaves the index unswapped, so whatever is here belongs to an earlier frame
+ // and is still being traced as the previous one
+ if bindings.instances.slots.high_water_mark() == 0 {
+ return false;
+ }
+ let current_index = bindings.tlas.current_index;
+ let Some(tlas) = bindings.tlas.structures[current_index].as_mut() else {
+ return false;
+ };
+
+ {
+ let _span = info_span!("fill_tlas_instances").entered();
+
+ // The TLAS outlives the frame, so a slot freed or deactivated since its last build still
+ // holds that build's instance and has to be cleared before this frame's are written
+ let capacity = tlas.get().len();
+ tlas[0..capacity].iter_mut().for_each(|entry| *entry = None);
+
+ for (slot, mesh, transform, mask) in bindings.instances.drawable() {
+ // A mesh can lose its acceleration structure after the instance resolved against it,
+ // which leaves the slot with nothing to point at for a frame
+ let Some(blas) = blas_manager.get(&mesh) else {
+ continue;
+ };
+ // raea: the slot's mask (opaque or see-through) where every instance had 0xFF
+ tlas[slot as usize] = Some(TlasInstance::new(blas, transform, slot, mask));
+ }
+ }
+
+ let diagnostics = render_context.diagnostic_recorder();
+ let diagnostics = diagnostics.as_deref();
+ let command_encoder = render_context.command_encoder();
+ let time_span = diagnostics.time_span(command_encoder, "tlas_build");
+ command_encoder.build_acceleration_structures(&[], [&*tlas]);
+ time_span.end(command_encoder);
+
+ true
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{tlas_capacity_for, TLAS_MIN_CAPACITY};
+
+ #[test]
+ fn tlas_capacity_grows_geometrically_at_boundaries() {
+ assert_eq!(tlas_capacity_for(0), TLAS_MIN_CAPACITY);
+ assert_eq!(tlas_capacity_for(TLAS_MIN_CAPACITY), TLAS_MIN_CAPACITY);
+ assert_eq!(tlas_capacity_for(TLAS_MIN_CAPACITY + 1), 192);
+ assert_eq!(tlas_capacity_for(192), 192);
+ assert_eq!(tlas_capacity_for(193), 288);
+ }
+}
diff --git a/vendor/bevy_solari/src/scene/binder/tlas_build.rs b/vendor/bevy_solari/src/scene/binder/tlas_build.rs
new file mode 100644
index 00000000..0cb6d3f0
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/binder/tlas_build.rs
@@ -0,0 +1,299 @@
+//! Building the binder's TLAS through `wgpu_hal` directly, bypassing `wgpu-core` and using
+//! an indirect acceleration structure build.
+//!
+//! Vulkan and DX12 only, as their instance descriptors are byte-identical. Metal cannot work this
+//! way: `wgpu-core` makes a TLAS's BLASes resident from its dependency list, and
+//! `mark_acceleration_structures_built` clears that list, so traversal would read memory Metal is
+//! free to have evicted. Every other backend falls back to the `wgpu-core` build in [`super::tlas`].
+//!
+//! Every operation has to be instantiated per backend, as `as_hal` is generic over the hal type and
+//! wgpu exposes no dynamic equivalent. [`resolve`] does that once, by trying each compiled-in
+//! backend and relying on `as_hal` returning `None` for a device that isn't its own, which can't
+//! disagree with the adapter actually in use.
+
+#![expect(
+ unsafe_code,
+ reason = "Building the TLAS without wgpu-core's per-instance cost requires wgpu_hal."
+)]
+// With neither backend compiled in every arm is cfg'd away, so nothing here is instantiated. It
+// still has to exist, because Solari compiles everywhere and only declines to load at runtime.
+#![cfg_attr(
+ not(any(
+ windows,
+ target_os = "linux",
+ target_os = "android",
+ target_os = "freebsd"
+ )),
+ expect(
+ dead_code,
+ unused_variables,
+ reason = "no backend with a raw TLAS build path is compiled in for this target"
+ )
+)]
+
+use bevy_render::{
+ render_resource::{Blas, Buffer, BufferDescriptor, BufferUsages, CommandEncoder, Tlas},
+ renderer::RenderDevice,
+};
+use core::marker::PhantomData;
+use wgpu::{hal, BufferUses};
+
+/// Size of one TLAS instance descriptor, on both Vulkan and DXR.
+pub const INSTANCE_DESCRIPTOR_SIZE: u64 = 64;
+
+/// Flags the TLAS is created with, which its build has to be given again.
+const TLAS_BUILD_FLAGS: wgpu::AccelerationStructureFlags =
+ wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE;
+
+/// The `wgpu_hal` operations a raw TLAS build needs, bound to one backend by [`resolve`].
+pub trait RawTlasBackend: Send + Sync {
+ /// Scratch space a TLAS build over `instance_count` instances of `instances` needs.
+ fn scratch_size(
+ &self,
+ render_device: &RenderDevice,
+ instances: &Buffer,
+ instance_count: u32,
+ ) -> Option<u64>;
+
+ /// Allocates a buffer usable as acceleration structure build scratch.
+ ///
+ /// There is no [`BufferUsages`] for scratch and `STORAGE` won't do, as Vulkan only adds
+ /// `SHADER_DEVICE_ADDRESS` for acceleration structure usages. So it is created through hal and
+ /// handed to `wgpu-core` to own. `wgpu-core` only defers freeing what a submission's tracker
+ /// references, so the caller transitioning it each frame is what makes replacing it safe.
+ fn create_scratch_buffer(&self, render_device: &RenderDevice, size: u64) -> Option<Buffer>;
+
+ /// Records a TLAS build reading instance descriptors straight out of `instances`.
+ ///
+ /// The caller must already have transitioned `instances` to
+ /// `BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT` and `scratch` to
+ /// `BufferUses::ACCELERATION_STRUCTURE_SCRATCH`, on an earlier command buffer in the same
+ /// submission. The scratch transition is not optional even when its state is unchanged: scratch
+ /// is an exclusive usage, so the redundant-looking transition is what keeps consecutive frames'
+ /// builds from overlapping in it.
+ ///
+ /// `encoder` must have no wgpu command recorded into it, including timestamp writes, as
+ /// `wgpu-core` panics if an encoder mixes the wgpu and raw encoding APIs.
+ ///
+ /// Marking the build clears the TLAS's dependency list, which is what otherwise keeps the
+ /// BLASes it points at alive. The caller has to retain them past every submission that might
+ /// still trace it.
+ fn build_tlas(
+ &self,
+ encoder: &mut CommandEncoder,
+ tlas: &mut Tlas,
+ instances: &Buffer,
+ instance_count: u32,
+ scratch: &Buffer,
+ ) -> bool;
+}
+
+/// The backend to build through, or `None` where this device has no raw path.
+pub fn resolve(render_device: &RenderDevice) -> Option<&'static dyn RawTlasBackend> {
+ let device = render_device.wgpu_device();
+
+ #[cfg(any(
+ windows,
+ target_os = "linux",
+ target_os = "android",
+ target_os = "freebsd"
+ ))]
+ // SAFETY: the handle is only read, and is dropped with the guard
+ if unsafe { device.as_hal::<hal::api::Vulkan>() }.is_some() {
+ return Some(&Hal::<hal::api::Vulkan>::NEW);
+ }
+
+ #[cfg(windows)]
+ // SAFETY: the handle is only read, and is dropped with the guard
+ if unsafe { device.as_hal::<hal::api::Dx12>() }.is_some() {
+ return Some(&Hal::<hal::api::Dx12>::NEW);
+ }
+
+ None
+}
+
+/// [`RawTlasBackend`] for one hal backend.
+///
+/// `fn() -> A` rather than `A`, so the marker is [`Send`] and [`Sync`] whatever `A` is.
+struct Hal<A>(PhantomData<fn() -> A>);
+
+impl<A: hal::Api> Hal<A> {
+ const NEW: Self = Self(PhantomData);
+
+ /// Records the build itself, leaving [`RawTlasBackend::build_tlas`] to mark it.
+ fn record_build(
+ &self,
+ encoder: &mut CommandEncoder,
+ tlas: &mut Tlas,
+ instances: &Buffer,
+ instance_count: u32,
+ scratch: &Buffer,
+ ) -> Option<()> {
+ use hal::CommandEncoder as _;
+
+ // Workaround for https://github.com/gfx-rs/wgpu/issues/10191
+ let buffer_address = |buffer: &Buffer| {
+ // SAFETY: the handle is only read, and the buffer is not destroyed here
+ let guard = unsafe { buffer.as_hal::<A>() }?;
+ Some(core::ptr::from_ref::<A::Buffer>(&*guard))
+ };
+ let hal_instances = buffer_address(instances)?;
+ let hal_scratch = buffer_address(scratch)?;
+ // SAFETY: the handle is only read, and the TLAS is not destroyed here
+ let hal_tlas = unsafe { tlas.as_hal::<A>() }?;
+
+ // SAFETY: both buffers outlive this call through the caller's borrows, and neither is
+ // destroyed between reading its address and the build recording
+ let (hal_instances, hal_scratch) = unsafe { (&*hal_instances, &*hal_scratch) };
+
+ let entries =
+ hal::AccelerationStructureEntries::Instances(hal::AccelerationStructureInstances {
+ buffer: Some(hal_instances),
+ offset: 0,
+ count: instance_count,
+ });
+
+ let descriptor = hal::BuildAccelerationStructureDescriptor {
+ entries: &entries,
+ mode: hal::AccelerationStructureBuildMode::Build,
+ flags: TLAS_BUILD_FLAGS,
+ source_acceleration_structure: None,
+ destination_acceleration_structure: &*hal_tlas,
+ scratch_buffer: hal_scratch,
+ scratch_buffer_offset: 0,
+ };
+
+ // The caller transitioned both buffers, so the only barriers left are the acceleration
+ // structure's own, which have no public spelling.
+ //
+ // SAFETY: every resource in `descriptor` belongs to backend `A` and to this device, the
+ // scratch buffer is sized by `scratch_size` and used by no other build in this submission,
+ // and the encoder is neither ended nor its raw handle destroyed here
+ unsafe {
+ encoder.as_hal_mut::<A, _, _>(|encoder| {
+ let encoder = encoder?;
+
+ // Write-after-read against submissions still tracing this TLAS as their previous
+ // frame, and against a BLAS compaction copy submitted ahead of this build. A
+ // barrier's first scope covers everything already submitted, which covers both.
+ encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
+ usage: hal::StateTransition {
+ from: hal::AccelerationStructureUses::SHADER_INPUT
+ | hal::AccelerationStructureUses::COPY_DST,
+ to: hal::AccelerationStructureUses::BUILD_OUTPUT
+ | hal::AccelerationStructureUses::BUILD_INPUT,
+ },
+ });
+
+ encoder.build_acceleration_structures(1, [descriptor]);
+
+ // And read-after-write, for the passes later this frame that trace the result
+ encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
+ usage: hal::StateTransition {
+ from: hal::AccelerationStructureUses::BUILD_OUTPUT,
+ to: hal::AccelerationStructureUses::SHADER_INPUT,
+ },
+ });
+
+ Some(())
+ })
+ }
+ }
+}
+
+impl<A: hal::Api> RawTlasBackend for Hal<A> {
+ fn scratch_size(
+ &self,
+ render_device: &RenderDevice,
+ instances: &Buffer,
+ instance_count: u32,
+ ) -> Option<u64> {
+ use hal::Device as _;
+
+ // SAFETY: the handle is only read, and is dropped with the guard
+ let hal_device = unsafe { render_device.wgpu_device().as_hal::<A>() }?;
+ // SAFETY: the handle is only read, and is dropped with the guard
+ let hal_instances = unsafe { instances.as_hal::<A>() }?;
+
+ // Sizing ignores the buffer itself, but `wgpu_hal`'s Metal path unwraps it unconditionally,
+ // so a real one has to be handed over
+ let entries =
+ hal::AccelerationStructureEntries::Instances(hal::AccelerationStructureInstances {
+ buffer: Some(&*hal_instances),
+ offset: 0,
+ count: instance_count,
+ });
+
+ // SAFETY: `entries` describes a buffer belonging to backend `A`, and the query records
+ // nothing and reads no memory through it
+ let sizes = unsafe {
+ hal_device.get_acceleration_structure_build_sizes(
+ &hal::GetAccelerationStructureBuildSizesDescriptor {
+ entries: &entries,
+ flags: TLAS_BUILD_FLAGS,
+ },
+ )
+ };
+
+ Some(sizes.build_scratch_size)
+ }
+
+ fn create_scratch_buffer(&self, render_device: &RenderDevice, size: u64) -> Option<Buffer> {
+ use hal::Device as _;
+
+ let device = render_device.wgpu_device();
+ let hal_buffer = {
+ // SAFETY: the handle is only read, and is dropped with the guard
+ let hal_device = unsafe { device.as_hal::<A>() }?;
+ // SAFETY: the descriptor is valid and the buffer is handed to `wgpu-core` below, which
+ // takes over destroying it
+ unsafe {
+ hal_device.create_buffer(&hal::BufferDescriptor {
+ label: Some("solari_tlas_scratch"),
+ size,
+ usage: BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
+ memory_flags: hal::MemoryFlags::empty(),
+ })
+ }
+ .ok()?
+ };
+
+ // `usage` is only consulted for wgpu-level validation, which this buffer never sees
+ let descriptor = BufferDescriptor {
+ label: Some("solari_tlas_scratch"),
+ size,
+ usage: BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ };
+
+ // SAFETY: `hal_buffer` was created from this device, matches `descriptor`, and has nonzero
+ // size
+ Some(unsafe { device.create_buffer_from_hal::<A>(hal_buffer, &descriptor) }.into())
+ }
+
+ fn build_tlas(
+ &self,
+ encoder: &mut CommandEncoder,
+ tlas: &mut Tlas,
+ instances: &Buffer,
+ instance_count: u32,
+ scratch: &Buffer,
+ ) -> bool {
+ if self
+ .record_build(encoder, tlas, instances, instance_count, scratch)
+ .is_none()
+ {
+ return false;
+ }
+
+ // Without this the build is invisible to `wgpu-core` and it rejects the TLAS when bound
+ //
+ // SAFETY: the TLAS was just built into this encoder, and every BLAS its instances point at
+ // was built and submitted earlier in the frame by `prepare_raytracing_blas`
+ unsafe {
+ encoder.mark_acceleration_structures_built(core::iter::empty::<&Blas>(), [&*tlas]);
+ }
+
+ true
+ }
+}
diff --git a/vendor/bevy_solari/src/scene/bindings.wesl b/vendor/bevy_solari/src/scene/bindings.wesl
new file mode 100644
index 00000000..82646266
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/bindings.wesl
@@ -0,0 +1,371 @@
+import bevy_pbr::render::pbr_functions::calculate_tbn_mikktspace;
+import bevy_render::maths::affine3_to_square;
+
+enable wgpu_ray_query;
+enable wgpu_binding_array;
+
+struct InstanceGeometryIds {
+ vertex_buffer_id: u32,
+ vertex_buffer_offset: u32,
+ index_buffer_id: u32,
+ index_buffer_offset: u32,
+ triangle_count: u32,
+}
+
+struct VertexBuffer { vertices: array<PackedVertex> }
+
+struct IndexBuffer { indices: array<u32> }
+
+struct PackedVertex {
+ a: vec4<f32>,
+ b: vec4<f32>,
+ tangent: vec4<f32>,
+}
+
+struct Vertex {
+ position: vec3<f32>,
+ normal: vec3<f32>,
+ uv: vec2<f32>,
+ tangent: vec4<f32>,
+}
+
+fn unpack_vertex(packed: PackedVertex) -> Vertex {
+ var vertex: Vertex;
+ vertex.position = packed.a.xyz;
+ vertex.normal = vec3(packed.a.w, packed.b.xy);
+ vertex.uv = packed.b.zw;
+ vertex.tangent = packed.tangent;
+ return vertex;
+}
+
+struct Material {
+ normal_map_texture_id: u32,
+ base_color_texture_id: u32,
+ emissive_texture_id: u32,
+ metallic_roughness_texture_id: u32,
+
+ base_color: vec3<f32>,
+ perceptual_roughness: f32,
+ emissive: vec3<f32>,
+ metallic: f32,
+ // raea: assets.rs GpuMaterial's alpha, its mode (ALPHA_* below) and Mask's cutoff
+ alpha: f32,
+ alpha_mode: u32,
+ alpha_cutoff: f32,
+ reflectance: f32,
+ // raea: StandardMaterial's uv_transform: columns x (xy) and y (zw), then the translation (xy)
+ uv_transform_xy: vec4<f32>,
+ uv_transform_t: vec4<f32>,
+}
+
+const TEXTURE_MAP_NONE = 0xFFFFFFFFu;
+
+// raea: kept in step with assets.rs ALPHA_*
+const ALPHA_OPAQUE = 0u;
+const ALPHA_MASK = 1u;
+const ALPHA_BLEND = 2u;
+const ALPHA_PREMULTIPLIED = 3u;
+const ALPHA_ADD = 4u;
+
+// raea: a mesh's UVs as its material's textures read them (the raster passes' uv_transform)
+fn material_uv(material: Material, uv: vec2<f32>) -> vec2<f32> {
+ return mat2x2(material.uv_transform_xy.xy, material.uv_transform_xy.zw) * uv + material.uv_transform_t.xy;
+}
+
+// raea: a material's alpha at a point: its base colour's times its base colour texture's
+fn material_alpha(material: Material, uv: vec2<f32>) -> f32 {
+ if material.base_color_texture_id == TEXTURE_MAP_NONE { return material.alpha; }
+ return material.alpha * textureSampleLevel(textures[material.base_color_texture_id], samplers[material.base_color_texture_id], uv, 0.0).a;
+}
+
+// raea: a normal-mapped normal that faces away from the ray that sees it (a grazing view of a bumpy plane) bent back
+// just far enough to face it, so the surface isn't shaded from behind (black streaks toward the horizon)
+fn facing_normal(world_normal: vec3<f32>, geometric_world_normal: vec3<f32>, wo: vec3<f32>) -> vec3<f32> {
+ let min_cos = 0.1;
+ let cos_theta = dot(world_normal, wo);
+ if cos_theta >= min_cos || dot(geometric_world_normal, wo) <= 0.0 { return world_normal; }
+ // the normal plus enough of wo that, once normalized, its cosine to wo is min_cos
+ let away = world_normal - cos_theta * wo;
+ if dot(away, away) < 1e-8 { return geometric_world_normal; }
+ let tangent = normalize(away);
+ return normalize(min_cos * wo + sqrt(1.0 - min_cos * min_cos) * tangent);
+}
+
+// raea: the share of light a premultiplied surface's clear coat reflects at an angle (Schlick, F0 from its reflectance)
+fn coat_albedo(reflectance: f32, cos_theta: f32) -> f32 {
+ let f0 = 0.16 * reflectance * reflectance;
+ return f0 + (1.0 - f0) * pow(1.0 - saturate(cos_theta), 5.0);
+}
+
+const MIRROR_ROUGHNESS_THRESHOLD = 0.001f;
+
+struct LightSource {
+ kind: u32, // 1 bit for kind, 31 bits for extra data
+ id: u32,
+}
+
+const LIGHT_SOURCE_KIND_EMISSIVE_MESH = 0u;
+const LIGHT_SOURCE_KIND_DIRECTIONAL = 1u;
+
+struct DirectionalLight {
+ direction_to_light: vec3<f32>,
+ cos_theta_max: f32,
+ luminance: vec3<f32>,
+ inverse_pdf: f32,
+}
+
+struct EnvironmentMapLight {
+ light_from_world: mat3x3<f32>,
+ intensity: f32,
+ // raea: bind_group.rs GpuEnvironmentMapLight's sun disk and the sky inside it
+ sun_direction: vec3<f32>,
+ sun_cos: f32,
+ sky: vec3<f32>,
+}
+
+const LIGHT_NOT_PRESENT_THIS_FRAME = 0xFFFFFFFFu;
+
+@group(0) @binding(0) var<storage> vertex_buffers: binding_array<VertexBuffer>;
+@group(0) @binding(1) var<storage> index_buffers: binding_array<IndexBuffer>;
+@group(0) @binding(2) var textures: binding_array<texture_2d<f32>>;
+@group(0) @binding(3) var samplers: binding_array<sampler>;
+@group(0) @binding(4) var<storage> materials: array<Material>;
+@group(0) @binding(5) var tlas: acceleration_structure;
+@group(0) @binding(6) var previous_frame_tlas: acceleration_structure;
+@group(0) @binding(7) var<storage> transforms: array<mat3x4<f32>>;
+@group(0) @binding(8) var<storage> previous_frame_transforms: array<mat3x4<f32>>;
+@group(0) @binding(9) var<storage> geometry_ids: array<InstanceGeometryIds>;
+@group(0) @binding(10) var<storage> material_ids: array<u32>;
+@group(0) @binding(11) var<storage> light_sources: array<LightSource>;
+@group(0) @binding(12) var<storage> directional_lights: array<DirectionalLight>;
+@group(0) @binding(13) var<storage> previous_frame_light_id_translations: array<u32>;
+@group(0) @binding(14) var brdf_dfg_lut: texture_2d<f32>;
+@group(0) @binding(15) var brdf_dfg_lut_sampler: sampler;
+@group(0) @binding(16) var environment_map: texture_cube<f32>;
+@group(0) @binding(17) var environment_map_sampler: sampler;
+@group(0) @binding(18) var<storage> environment_map_light: EnvironmentMapLight;
+
+const RAY_T_MIN = 0.001f;
+const RAY_T_MAX = 100000.0f;
+
+const RAY_NO_CULL = 0xFFu;
+
+// raea: the TLAS instance masks (instances.rs MASK_*). A ray first finds the nearest opaque instance as Solari always
+// did, then walks the instances whose material it may pass through, up to that hit, keeping the first one alpha_accepts.
+const RAY_MASK_OPAQUE = 0x01u;
+const RAY_MASK_ALPHA = 0x02u;
+
+fn trace_ray(ray_origin: vec3<f32>, ray_direction: vec3<f32>, ray_t_min: f32, ray_t_max: f32, ray_flag: u32) -> RayIntersection {
+ var rq: ray_query;
+ rayQueryInitialize(&rq, tlas, RayDesc(ray_flag, RAY_MASK_OPAQUE, ray_t_min, ray_t_max, ray_origin, ray_direction));
+ rayQueryProceed(&rq);
+ let opaque = rayQueryGetCommittedIntersection(&rq);
+ var t_max = ray_t_max;
+ if opaque.kind != RAY_QUERY_INTERSECTION_NONE { t_max = opaque.t; }
+
+ var aq: ray_query;
+ rayQueryInitialize(&aq, tlas, RayDesc(ray_flag | RAY_FLAG_FORCE_NO_OPAQUE, RAY_MASK_ALPHA, ray_t_min, t_max, ray_origin, ray_direction));
+ while rayQueryProceed(&aq) {
+ if alpha_accepts(rayQueryGetCandidateIntersection(&aq), ray_origin, ray_direction) {
+ rayQueryConfirmIntersection(&aq);
+ }
+ }
+ let through = rayQueryGetCommittedIntersection(&aq);
+ if through.kind != RAY_QUERY_INTERSECTION_NONE { return through; }
+ return opaque;
+}
+
+fn trace_ray_previous_frame(ray_origin: vec3<f32>, ray_direction: vec3<f32>, ray_t_min: f32, ray_t_max: f32, ray_flag: u32) -> RayIntersection {
+ var rq: ray_query;
+ rayQueryInitialize(&rq, previous_frame_tlas, RayDesc(ray_flag, RAY_MASK_OPAQUE, ray_t_min, ray_t_max, ray_origin, ray_direction));
+ rayQueryProceed(&rq);
+ let opaque = rayQueryGetCommittedIntersection(&rq);
+ var t_max = ray_t_max;
+ if opaque.kind != RAY_QUERY_INTERSECTION_NONE { t_max = opaque.t; }
+
+ var aq: ray_query;
+ rayQueryInitialize(&aq, previous_frame_tlas, RayDesc(ray_flag | RAY_FLAG_FORCE_NO_OPAQUE, RAY_MASK_ALPHA, ray_t_min, t_max, ray_origin, ray_direction));
+ while rayQueryProceed(&aq) {
+ // the previous frame's instances keep their slots, so this frame's materials stand in for theirs
+ if alpha_accepts(rayQueryGetCandidateIntersection(&aq), ray_origin, ray_direction) {
+ rayQueryConfirmIntersection(&aq);
+ }
+ }
+ let through = rayQueryGetCommittedIntersection(&aq);
+ if through.kind != RAY_QUERY_INTERSECTION_NONE { return through; }
+ return opaque;
+}
+
+// raea: whether a ray stops at a candidate hit on a see-through material: Mask by its cutoff, Blend with the
+// probability of its alpha (so many rays average to the blend), Premultiplied also for its clear coat's reflection
+// (coat_albedo), Add never (it only adds light)
+fn alpha_accepts(hit: RayIntersection, ray_origin: vec3<f32>, ray_direction: vec3<f32>) -> bool {
+ let instance_id = hit.instance_custom_data;
+ let material = materials[material_ids[instance_id]];
+ if material.alpha_mode == ALPHA_OPAQUE { return true; }
+ if material.alpha_mode == ALPHA_ADD { return false; }
+
+ let vertices = load_vertices(geometry_ids[instance_id], hit.primitive_index);
+ let barycentrics = vec3(1.0 - hit.barycentrics.x - hit.barycentrics.y, hit.barycentrics);
+ let alpha = material_alpha(material, material_uv(material, mat3x2(vertices[0].uv, vertices[1].uv, vertices[2].uv) * barycentrics));
+ if material.alpha_mode == ALPHA_MASK { return alpha >= material.alpha_cutoff; }
+ var p = alpha;
+ if material.alpha_mode == ALPHA_PREMULTIPLIED {
+ let world = transform_positions(affine3_to_square(transforms[instance_id]), vertices);
+ let normal = normalize(cross(world[1] - world[0], world[2] - world[0]));
+ p = alpha + (1.0 - alpha) * coat_albedo(material.reflectance, abs(dot(normal, ray_direction)));
+ }
+ return alpha_hash(hit, ray_origin, ray_direction) < p;
+}
+
+// raea: a number in [0, 1) that changes with the ray and the hit, for alpha_accepts' coin
+fn alpha_hash(hit: RayIntersection, ray_origin: vec3<f32>, ray_direction: vec3<f32>) -> f32 {
+ var h = hit.primitive_index * 747796405u + hit.instance_custom_data;
+ let parts = array<u32, 6>(bitcast<u32>(hit.t), bitcast<u32>(ray_direction.x), bitcast<u32>(ray_direction.y), bitcast<u32>(ray_direction.z), bitcast<u32>(ray_origin.x), bitcast<u32>(ray_origin.z));
+ for (var i = 0u; i < 6u; i++) {
+ h = (h ^ parts[i]) * 747796405u + 2891336453u;
+ h = ((h >> ((h >> 28u) + 4u)) ^ h) * 277803737u;
+ h = (h >> 22u) ^ h;
+ }
+ return f32(h >> 8u) / 16777216.0;
+}
+
+fn sample_texture(id: u32, uv: vec2<f32>) -> vec3<f32> {
+ return textureSampleLevel(textures[id], samplers[id], uv, 0.0).rgb; // TODO: Mipmap
+}
+
+struct ResolvedMaterial {
+ base_color: vec3<f32>,
+ emissive: vec3<f32>,
+ reflectance: f32,
+ perceptual_roughness: f32,
+ roughness: f32,
+ metallic: f32,
+}
+
+struct ResolvedRayHitFull {
+ world_position: vec3<f32>,
+ previous_frame_world_position: vec3<f32>,
+ world_normal: vec3<f32>,
+ geometric_world_normal: vec3<f32>,
+ world_tangent: vec4<f32>,
+ uv: vec2<f32>,
+ triangle_area: f32,
+ triangle_count: u32,
+ material: ResolvedMaterial,
+}
+
+fn resolve_material(material: Material, uv: vec2<f32>) -> ResolvedMaterial {
+ var m: ResolvedMaterial;
+
+ m.base_color = material.base_color.rgb;
+ if material.base_color_texture_id != TEXTURE_MAP_NONE {
+ m.base_color *= sample_texture(material.base_color_texture_id, uv);
+ }
+
+ m.emissive = material.emissive.rgb;
+ if material.emissive_texture_id != TEXTURE_MAP_NONE {
+ m.emissive *= sample_texture(material.emissive_texture_id, uv);
+ }
+
+ m.reflectance = material.reflectance;
+
+ m.perceptual_roughness = material.perceptual_roughness;
+ m.metallic = material.metallic;
+ if material.metallic_roughness_texture_id != TEXTURE_MAP_NONE {
+ let metallic_roughness = sample_texture(material.metallic_roughness_texture_id, uv);
+ m.perceptual_roughness *= metallic_roughness.g;
+ m.metallic *= metallic_roughness.b;
+ }
+
+ m.roughness = m.perceptual_roughness * m.perceptual_roughness;
+
+ return m;
+}
+
+fn resolve_ray_hit_full(ray_hit: RayIntersection) -> ResolvedRayHitFull {
+ let barycentrics = vec3(1.0 - ray_hit.barycentrics.x - ray_hit.barycentrics.y, ray_hit.barycentrics);
+ return resolve_triangle_data_full(ray_hit.instance_custom_data, ray_hit.primitive_index, barycentrics);
+}
+
+fn load_vertices(instance_geometry_ids: InstanceGeometryIds, triangle_id: u32) -> array<Vertex, 3> {
+ let index_buffer = &index_buffers[instance_geometry_ids.index_buffer_id].indices;
+ let vertex_buffer = &vertex_buffers[instance_geometry_ids.vertex_buffer_id].vertices;
+
+ let indices_i = (triangle_id * 3u) + vec3(0u, 1u, 2u) + instance_geometry_ids.index_buffer_offset;
+ let indices = vec3((*index_buffer)[indices_i.x], (*index_buffer)[indices_i.y], (*index_buffer)[indices_i.z]) + instance_geometry_ids.vertex_buffer_offset;
+
+ return array<Vertex, 3>(
+ unpack_vertex((*vertex_buffer)[indices.x]),
+ unpack_vertex((*vertex_buffer)[indices.y]),
+ unpack_vertex((*vertex_buffer)[indices.z])
+ );
+}
+
+fn transform_positions(transform: mat4x4<f32>, vertices: array<Vertex, 3>) -> array<vec3<f32>, 3> {
+ return array<vec3<f32>, 3>(
+ (transform * vec4(vertices[0].position, 1.0)).xyz,
+ (transform * vec4(vertices[1].position, 1.0)).xyz,
+ (transform * vec4(vertices[2].position, 1.0)).xyz
+ );
+}
+
+fn resolve_triangle_data_full(instance_id: u32, triangle_id: u32, barycentrics: vec3<f32>) -> ResolvedRayHitFull {
+ let material_id = material_ids[instance_id];
+ let material = materials[material_id];
+
+ let transform = affine3_to_square(transforms[instance_id]);
+ let previous_frame_transform = affine3_to_square(previous_frame_transforms[instance_id]);
+
+ let instance_geometry_ids = geometry_ids[instance_id];
+ let vertices = load_vertices(instance_geometry_ids, triangle_id);
+
+ let world_vertices = transform_positions(transform, vertices);
+ let world_position = mat3x3(world_vertices[0], world_vertices[1], world_vertices[2]) * barycentrics;
+
+ let previous_frame_world_vertices = transform_positions(previous_frame_transform, vertices);
+ let previous_frame_world_position = mat3x3(previous_frame_world_vertices[0], previous_frame_world_vertices[1], previous_frame_world_vertices[2]) * barycentrics;
+
+ let uv = material_uv(material, mat3x2(vertices[0].uv, vertices[1].uv, vertices[2].uv) * barycentrics);
+
+ let transform_3x3 = mat3x3(transform[0].xyz, transform[1].xyz, transform[2].xyz);
+
+ let cofactor = mat3x3(cross(transform_3x3[1], transform_3x3[2]), cross(transform_3x3[2], transform_3x3[0]), cross(transform_3x3[0], transform_3x3[1]));
+ let determinant = dot(transform_3x3[0], cofactor[0]);
+ let determinant_sign = select(sign(determinant), 1.0, determinant == 0.0);
+
+ let local_tangent = mat3x3(vertices[0].tangent.xyz, vertices[1].tangent.xyz, vertices[2].tangent.xyz) * barycentrics;
+ let world_tangent = vec4(normalize(transform_3x3 * local_tangent), vertices[0].tangent.w * determinant_sign);
+
+ let local_normal = mat3x3(vertices[0].normal, vertices[1].normal, vertices[2].normal) * barycentrics; // TODO: Use barycentric lerp, ray_hit.object_to_world, cross product geo normal
+ var world_normal = normalize(determinant_sign * (cofactor * local_normal));
+
+ let geometric_world_normal = world_normal;
+ if material.normal_map_texture_id != TEXTURE_MAP_NONE {
+ let TBN = calculate_tbn_mikktspace(world_normal, world_tangent);
+ let T = TBN[0];
+ let B = TBN[1];
+ let N = TBN[2];
+ var Nt = sample_texture(material.normal_map_texture_id, uv) * 2.0 - 1.0;
+ Nt.z = sqrt(max(1.0 - dot(Nt.xy, Nt.xy), 0.0)); // Reconstruct Z to support two-channel normal maps
+ world_normal = normalize(Nt.x * T + Nt.y * B + Nt.z * N);
+ }
+
+ let triangle_edge0 = world_vertices[0] - world_vertices[1];
+ let triangle_edge1 = world_vertices[0] - world_vertices[2];
+ let triangle_area = length(cross(triangle_edge0, triangle_edge1)) / 2.0;
+
+ let resolved_material = resolve_material(material, uv);
+
+ return ResolvedRayHitFull(
+ world_position,
+ previous_frame_world_position,
+ world_normal,
+ geometric_world_normal,
+ world_tangent,
+ uv,
+ triangle_area,
+ instance_geometry_ids.triangle_count,
+ resolved_material,
+ );
+}
diff --git a/vendor/bevy_solari/src/scene/blas.rs b/vendor/bevy_solari/src/scene/blas.rs
new file mode 100644
index 00000000..0bf5fcc9
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/blas.rs
@@ -0,0 +1,262 @@
+use alloc::collections::VecDeque;
+use bevy_asset::AssetId;
+use bevy_ecs::{
+ resource::Resource,
+ system::{Res, ResMut},
+};
+use bevy_mesh::{Indices, Mesh};
+use bevy_platform::collections::HashMap;
+use bevy_render::{
+ diagnostic::{DiagnosticsRecorder, RecordDiagnostics},
+ mesh::{
+ allocator::{MeshAllocator, MeshBufferSlice},
+ RenderMesh,
+ },
+ render_asset::ExtractedAssets,
+ render_resource::*,
+ renderer::{RenderDevice, RenderQueue},
+};
+
+/// After compacting this many vertices worth of meshes per frame, no further BLAS will be compacted.
+/// Lower this number to distribute the work across more frames.
+const MAX_COMPACTION_VERTICES_PER_FRAME: u32 = 400_000;
+
+/// Under the `wgpu_hal` build path, we need to manage BLAS lifetimes ourselves.
+/// Since solari keeps both current and previous frame TLAS's around, only after
+/// two TLAS builds since we marked it for deletion is it safe to delete a BLAS.
+const TLAS_BUILDS_BEFORE_DELETION_ALLOWED: usize = 2;
+
+#[derive(Resource, Default)]
+pub struct BlasManager {
+ blas: HashMap<AssetId<Mesh>, Blas>,
+ compaction_queue: VecDeque<(AssetId<Mesh>, u32, bool)>,
+ changed: Vec<AssetId<Mesh>>,
+ /// BLAS that are pending deletion, one batch per TLAS build. The back batch collects
+ /// retirements since the last build, and every batch ahead of it has one more build to wait
+ /// out.
+ pending_deletions: VecDeque<Vec<Blas>>,
+}
+
+impl BlasManager {
+ pub fn get(&self, mesh: &AssetId<Mesh>) -> Option<&Blas> {
+ self.blas.get(mesh)
+ }
+
+ pub fn device_address(&self, mesh: &AssetId<Mesh>) -> Option<u64> {
+ self.blas.get(mesh)?.handle()
+ }
+
+ pub fn changed_meshes(&self) -> &[AssetId<Mesh>] {
+ &self.changed
+ }
+
+ pub fn note_tlas_build(&mut self) {
+ if !self.pending_deletions.is_empty() {
+ self.pending_deletions.push_back(Vec::new());
+ }
+ }
+
+ fn insert(&mut self, mesh: AssetId<Mesh>, blas: Blas) {
+ if let Some(old) = self.blas.insert(mesh, blas) {
+ self.retire(old);
+ }
+
+ self.changed.push(mesh);
+ }
+
+ fn remove(&mut self, mesh: AssetId<Mesh>) {
+ self.changed.push(mesh);
+
+ if let Some(removed) = self.blas.remove(&mesh) {
+ self.retire(removed);
+ }
+ }
+
+ fn retire(&mut self, blas: Blas) {
+ match self.pending_deletions.back_mut() {
+ Some(batch) => batch.push(blas),
+ None => self.pending_deletions.push_back(vec![blas]),
+ }
+ }
+}
+
+pub fn prepare_raytracing_blas(
+ mut blas_manager: ResMut<BlasManager>,
+ extracted_meshes: Res<ExtractedAssets<RenderMesh>>,
+ mesh_allocator: Res<MeshAllocator>,
+ render_device: Res<RenderDevice>,
+ render_queue: Res<RenderQueue>,
+ mut diagnostics: Option<ResMut<DiagnosticsRecorder>>,
+) {
+ blas_manager.changed.clear();
+
+ // Delete BLAS for deleted or modified meshes
+ for asset_id in extracted_meshes
+ .removed
+ .iter()
+ .chain(extracted_meshes.modified.iter())
+ {
+ blas_manager.remove(*asset_id);
+ }
+
+ if extracted_meshes.extracted.is_empty() {
+ return;
+ }
+
+ // Create new BLAS for added or changed meshes
+ let blas_resources = extracted_meshes
+ .extracted
+ .iter()
+ .filter(|(_, mesh)| is_mesh_raytracing_compatible(mesh))
+ .map(|(asset_id, _)| {
+ let vertex_slice = mesh_allocator.mesh_vertex_slice(asset_id).unwrap();
+ let index_slice = mesh_allocator.mesh_index_slice(asset_id).unwrap();
+
+ let (blas, blas_size) =
+ allocate_blas(&vertex_slice, &index_slice, asset_id, &render_device);
+
+ blas_manager.insert(*asset_id, blas);
+ blas_manager
+ .compaction_queue
+ .push_back((*asset_id, blas_size.vertex_count, false));
+
+ (*asset_id, vertex_slice, index_slice, blas_size)
+ })
+ .collect::<Vec<_>>();
+
+ // Build geometry into each BLAS
+ let build_entries = blas_resources
+ .iter()
+ .map(|(asset_id, vertex_slice, index_slice, blas_size)| {
+ let geometry = BlasTriangleGeometry {
+ size: blas_size,
+ vertex_buffer: vertex_slice.buffer,
+ first_vertex: vertex_slice.range.start,
+ vertex_stride: 48,
+ index_buffer: Some(index_slice.buffer),
+ first_index: Some(index_slice.range.start),
+ transform_buffer: None,
+ transform_buffer_offset: None,
+ };
+ BlasBuildEntry {
+ blas: &blas_manager.blas[asset_id],
+ geometry: BlasGeometries::TriangleGeometries(vec![geometry]),
+ }
+ })
+ .collect::<Vec<_>>();
+
+ let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor {
+ label: Some("blas_build_command_encoder"),
+ });
+ let time_span = diagnostics
+ .as_mut()
+ .map(|diagnostics| diagnostics.time_span(&mut command_encoder, "blas_build"));
+ command_encoder.build_acceleration_structures(&build_entries, &[]);
+ if let Some(time_span) = time_span {
+ time_span.end(&mut command_encoder);
+ }
+ render_queue.submit([command_encoder.finish()]);
+}
+
+pub fn compact_raytracing_blas(
+ mut blas_manager: ResMut<BlasManager>,
+ render_queue: Res<RenderQueue>,
+) {
+ let queue_size = blas_manager.compaction_queue.len();
+ let mut meshes_processed = 0;
+ let mut vertices_compacted = 0;
+
+ while !blas_manager.compaction_queue.is_empty()
+ && vertices_compacted < MAX_COMPACTION_VERTICES_PER_FRAME
+ && meshes_processed < queue_size
+ {
+ meshes_processed += 1;
+
+ let (mesh, vertex_count, compaction_started) =
+ blas_manager.compaction_queue.pop_front().unwrap();
+
+ let Some(blas) = blas_manager.get(&mesh) else {
+ continue;
+ };
+
+ if !compaction_started {
+ blas.prepare_compaction_async(|_| {});
+ }
+
+ if blas.ready_for_compaction() {
+ let compacted_blas = render_queue.compact_blas(blas);
+ blas_manager.insert(mesh, compacted_blas);
+
+ vertices_compacted += vertex_count;
+ continue;
+ }
+
+ // BLAS not ready for compaction, put back in queue
+ blas_manager
+ .compaction_queue
+ .push_back((mesh, vertex_count, true));
+ }
+}
+
+pub fn delete_raytracing_blas(
+ mut blas_manager: ResMut<BlasManager>,
+ render_queue: Res<RenderQueue>,
+) {
+ if blas_manager.pending_deletions.len() <= TLAS_BUILDS_BEFORE_DELETION_ALLOWED {
+ return;
+ }
+
+ if let Some(deletable) = blas_manager
+ .pending_deletions
+ .pop_front()
+ .filter(|b| !b.is_empty())
+ {
+ render_queue.on_submitted_work_done(move || drop(deletable));
+ }
+}
+
+fn allocate_blas(
+ vertex_slice: &MeshBufferSlice,
+ index_slice: &MeshBufferSlice,
+ asset_id: &AssetId<Mesh>,
+ render_device: &RenderDevice,
+) -> (Blas, BlasTriangleGeometrySizeDescriptor) {
+ let blas_size = BlasTriangleGeometrySizeDescriptor {
+ vertex_format: Mesh::ATTRIBUTE_POSITION.format,
+ vertex_count: vertex_slice.range.len() as u32,
+ index_format: Some(IndexFormat::Uint32),
+ index_count: Some(index_slice.range.len() as u32),
+ flags: AccelerationStructureGeometryFlags::OPAQUE,
+ };
+
+ // TODO: If we ever introduce BLAS refits, we need to be aware of the TLAS double-buffer
+ // to avoid invalidating the previous frame TLAS
+ let blas = render_device.wgpu_device().create_blas(
+ &CreateBlasDescriptor {
+ label: Some(&asset_id.to_string()),
+ flags: AccelerationStructureFlags::PREFER_FAST_TRACE
+ | AccelerationStructureFlags::ALLOW_COMPACTION,
+ update_mode: AccelerationStructureUpdateMode::Build,
+ },
+ BlasGeometrySizeDescriptors::Triangles {
+ descriptors: vec![blas_size.clone()],
+ },
+ );
+
+ (blas, blas_size)
+}
+
+fn is_mesh_raytracing_compatible(mesh: &Mesh) -> bool {
+ let triangle_list = mesh.primitive_topology() == PrimitiveTopology::TriangleList;
+ let vertex_attributes = mesh
+ .attributes()
+ .map(|(attribute, _)| (attribute.id, attribute.format))
+ .eq([
+ (Mesh::ATTRIBUTE_POSITION.id, Mesh::ATTRIBUTE_POSITION.format),
+ (Mesh::ATTRIBUTE_NORMAL.id, Mesh::ATTRIBUTE_NORMAL.format),
+ (Mesh::ATTRIBUTE_UV_0.id, Mesh::ATTRIBUTE_UV_0.format),
+ (Mesh::ATTRIBUTE_TANGENT.id, Mesh::ATTRIBUTE_TANGENT.format),
+ ]);
+ let indexed_32 = matches!(mesh.indices(), Some(Indices::U32(..)));
+ mesh.enable_raytracing && triangle_list && vertex_attributes && indexed_32
+}
diff --git a/vendor/bevy_solari/src/scene/brdf.wesl b/vendor/bevy_solari/src/scene/brdf.wesl
new file mode 100644
index 00000000..e4fe4fac
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/brdf.wesl
@@ -0,0 +1,176 @@
+import bevy_core_pipeline::tonemapping::tonemapping_luminance as luminance;
+import bevy_pbr::render::pbr_lighting::{D_GGX, V_SmithGGXCorrelated, specular_multiscatter};
+import bevy_pbr::render::pbr_functions::calculate_F0_dielectric;
+import bevy_pbr::render::utils::{rand_f, sample_cosine_hemisphere};
+import bevy_render::maths::{PI, orthonormalize};
+import package::scene::sampling::{sample_ggx_vndf, ggx_vndf_pdf, ggx_vndf_sample_invalid};
+import package::scene::bindings::{ResolvedMaterial, MIRROR_ROUGHNESS_THRESHOLD, brdf_dfg_lut, brdf_dfg_lut_sampler};
+
+enable wgpu_ray_query;
+
+struct EvaluateAndSampleBrdfResult {
+ wi: vec3<f32>,
+ throughput: vec3<f32>,
+ pdf: f32,
+ diffuse_selected: bool,
+}
+
+struct LobeReflectances {
+ specular: vec3<f32>,
+ diffuse: vec3<f32>,
+}
+
+/// Hemispherical reflectance of each lobe
+fn lobe_reflectances(F0_metal: vec3<f32>, F0_dielectric: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>) -> LobeReflectances {
+ let multiscattering_factor = 1.0 / (F_ab.x + F_ab.y) - 1.0;
+ let rho_specular_metallic = (F0_metal * F_ab.x + F_ab.y) * (1.0 + F0_metal * multiscattering_factor);
+ let rho_specular_dielectric = (F0_dielectric * F_ab.x + F_ab.y) * (1.0 + F0_dielectric * multiscattering_factor);
+ return LobeReflectances(
+ mix(rho_specular_dielectric, rho_specular_metallic, material.metallic),
+ (1.0 - material.metallic) * (1.0 - rho_specular_dielectric) * material.base_color,
+ );
+}
+
+fn specular_lobe_sampling_probability(rho: LobeReflectances, perceptual_roughness: f32) -> f32 {
+ let specular_luminance = luminance(rho.specular);
+ let total_luminance = specular_luminance + luminance(rho.diffuse);
+ let energy_probability = specular_luminance / max(total_luminance, 0.0001);
+
+ // Give smooth dielectric reflections more specular samples to prevent undersampling
+ let roughness_biased_probability = mix(0.5, energy_probability, perceptual_roughness);
+ return max(energy_probability, roughness_biased_probability);
+}
+
+fn evaluate_and_sample_brdf(
+ wo: vec3<f32>,
+ world_normal: vec3<f32>,
+ material: ResolvedMaterial,
+ F_ab: vec2<f32>,
+ rng: ptr<function, u32>,
+) -> EvaluateAndSampleBrdfResult {
+ let NdotV = dot(world_normal, wo);
+ if NdotV < 0.0001 { return EvaluateAndSampleBrdfResult(vec3(0.0), vec3(0.0), 0.0, false); }
+ let F0_metal = material.base_color;
+ let F0_dielectric = calculate_F0_dielectric(vec3(material.reflectance));
+ let rho = lobe_reflectances(F0_metal, F0_dielectric, material, F_ab);
+ let specular_weight = specular_lobe_sampling_probability(rho, material.perceptual_roughness);
+ let diffuse_weight = 1.0 - specular_weight;
+
+ let TBN = orthonormalize(world_normal);
+ let T = TBN[0];
+ let B = TBN[1];
+ let N = TBN[2];
+
+ let wo_tangent = vec3(dot(wo, T), dot(wo, B), dot(wo, N));
+
+ var wi: vec3<f32>;
+ var wi_tangent: vec3<f32>;
+ let diffuse_selected = rand_f(rng) < diffuse_weight;
+ if diffuse_selected {
+ wi = sample_cosine_hemisphere(world_normal, rng);
+ wi_tangent = vec3(dot(wi, T), dot(wi, B), dot(wi, N));
+ } else {
+ wi_tangent = sample_ggx_vndf(wo_tangent, material.roughness, rng);
+ if ggx_vndf_sample_invalid(wi_tangent) {
+ return EvaluateAndSampleBrdfResult(vec3(0.0), vec3(0.0), 0.0, false);
+ }
+ wi = wi_tangent.x * T + wi_tangent.y * B + wi_tangent.z * N;
+
+ // Mirror specular is a delta function
+ if material.roughness <= MIRROR_ROUGHNESS_THRESHOLD {
+ return EvaluateAndSampleBrdfResult(
+ wi,
+ evaluate_specular_brdf(wo, wi, world_normal, material, F_ab) / specular_weight,
+ bitcast<f32>(0x7F800000u), // INF
+ false,
+ );
+ }
+ }
+
+ let diffuse_pdf = wi_tangent.z / PI;
+ let specular_pdf = ggx_vndf_pdf(wo_tangent, wi_tangent, material.roughness);
+ let pdf = (diffuse_weight * diffuse_pdf) + (specular_weight * specular_pdf);
+ let throughput = evaluate_brdf(wo, wi, world_normal, material, F_ab) / pdf;
+ return EvaluateAndSampleBrdfResult(wi, throughput, pdf, diffuse_selected);
+}
+
+fn evaluate_brdf(
+ wo: vec3<f32>,
+ wi: vec3<f32>,
+ world_normal: vec3<f32>,
+ material: ResolvedMaterial,
+ F_ab: vec2<f32>,
+) -> vec3<f32> {
+ return evaluate_diffuse_brdf(wo, wi, world_normal, material, F_ab) + evaluate_specular_brdf(wo, wi, world_normal, material, F_ab);
+}
+
+fn evaluate_diffuse_brdf(wo: vec3<f32>, wi: vec3<f32>, world_normal: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>) -> vec3<f32> {
+ let NdotL = dot(world_normal, wi);
+ let NdotV = dot(world_normal, wo);
+ if NdotL < 0.0001 || NdotV < 0.0001 { return vec3(0.0); }
+ let F0_metal = material.base_color;
+ let F0_dielectric = calculate_F0_dielectric(vec3(material.reflectance));
+ let rho = lobe_reflectances(F0_metal, F0_dielectric, material, F_ab);
+ return rho.diffuse / PI * NdotL;
+}
+
+fn evaluate_specular_brdf(wo: vec3<f32>, wi: vec3<f32>, world_normal: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>) -> vec3<f32> {
+ let H = normalize(wi + wo);
+ let NdotL = dot(world_normal, wi);
+ let NdotH = min(dot(world_normal, H), 1.0);
+ let LdotH = dot(wi, H);
+ let NdotV = dot(world_normal, wo);
+ if NdotL < 0.0001 || NdotH < 0.0001 || LdotH < 0.0001 || NdotV < 0.0001 { return vec3(0.0); }
+
+ let F0_metal = material.base_color;
+ let F0_dielectric = calculate_F0_dielectric(vec3(material.reflectance));
+
+ if material.roughness <= MIRROR_ROUGHNESS_THRESHOLD {
+ let mirror_wi = 2.0 * NdotV * world_normal - wo;
+ if distance(mirror_wi, wi) < 0.0001 {
+ let F_metal = fresnel(F0_metal, LdotH);
+ let F_dielectric = fresnel(F0_dielectric, LdotH);
+ return mix(F_dielectric, F_metal, material.metallic);
+ } else {
+ return vec3(0.0);
+ }
+ }
+
+ let D = D_GGX(material.roughness, NdotH);
+ let Vs = V_SmithGGXCorrelated(material.roughness, NdotV, NdotL);
+ let F_metal = fresnel(F0_metal, LdotH);
+ let F_dielectric = fresnel(F0_dielectric, LdotH);
+ return mix(specular_multiscatter(D, Vs, F_dielectric, F0_dielectric, F_ab, 1.0),
+ specular_multiscatter(D, Vs, F_metal, F0_metal, F_ab, 1.0),
+ material.metallic) * NdotL;
+}
+
+fn brdf_pdf(wo: vec3<f32>, wi: vec3<f32>, world_normal: vec3<f32>, material: ResolvedMaterial, F_ab: vec2<f32>) -> f32 {
+ let NdotV = max(dot(world_normal, wo), 0.0001);
+ let F0_metal = material.base_color;
+ let F0_dielectric = calculate_F0_dielectric(vec3(material.reflectance));
+ let rho = lobe_reflectances(F0_metal, F0_dielectric, material, F_ab);
+ let specular_weight = specular_lobe_sampling_probability(rho, material.perceptual_roughness);
+ let diffuse_weight = 1.0 - specular_weight;
+
+ let TBN = orthonormalize(world_normal);
+ let T = TBN[0];
+ let B = TBN[1];
+ let N = TBN[2];
+
+ let wo_tangent = vec3(dot(wo, T), dot(wo, B), dot(wo, N));
+ let wi_tangent = vec3(dot(wi, T), dot(wi, B), dot(wi, N));
+
+ let diffuse_pdf = wi_tangent.z / PI;
+ let specular_pdf = ggx_vndf_pdf(wo_tangent, wi_tangent, material.roughness);
+ return (diffuse_weight * diffuse_pdf) + (specular_weight * specular_pdf);
+}
+
+fn fresnel(f0: vec3<f32>, LdotH: f32) -> vec3<f32> {
+ return f0 + (1.0 - f0) * pow(saturate(1.0 - LdotH), 5.0);
+}
+
+/// Scale/bias approximation
+fn F_AB(perceptual_roughness: f32, NdotV: f32) -> vec2<f32> {
+ return textureSampleLevel(brdf_dfg_lut, brdf_dfg_lut_sampler, vec2<f32>(NdotV, perceptual_roughness), 0.0).rg;
+}
diff --git a/vendor/bevy_solari/src/scene/extract.rs b/vendor/bevy_solari/src/scene/extract.rs
new file mode 100644
index 00000000..8b88046d
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/extract.rs
@@ -0,0 +1,211 @@
+use super::{EnvironmentSun, RaytracingMesh3d, RaytracingSceneBindings};
+use bevy_asset::{AssetEvent, AssetId, Assets, Handle};
+use bevy_camera::Camera;
+use bevy_ecs::{
+ lifecycle::RemovedComponents,
+ message::MessageReader,
+ query::{Added, Changed, Or, With},
+ resource::Resource,
+ system::{Commands, Query, Res, ResMut},
+};
+use bevy_image::Image;
+use bevy_light::{EnvironmentMapLight, GeneratedEnvironmentMapLight};
+use bevy_math::Quat;
+use bevy_pbr::{MeshMaterial3d, PreviousGlobalTransform, StandardMaterial};
+use bevy_platform::collections::HashMap;
+use bevy_render::{sync_world::RenderEntity, Extract};
+use bevy_transform::components::GlobalTransform;
+use bevy_utils::once;
+use tracing::warn;
+
+/// Creates or removes components in the render world related to raytracing instances.
+pub fn extract_raytracing_scene_structural(
+ new_instances: Extract<
+ Query<
+ (
+ RenderEntity,
+ &RaytracingMesh3d,
+ &MeshMaterial3d<StandardMaterial>,
+ &GlobalTransform,
+ Option<&PreviousGlobalTransform>,
+ ),
+ Added<RaytracingMesh3d>,
+ >,
+ >,
+ mut removed_raytracing_meshes: Extract<RemovedComponents<RaytracingMesh3d>>,
+ render_entities: Extract<Query<RenderEntity>>,
+ mut commands: Commands,
+) {
+ // Process removed components before additions, that way it properly handles same-frame removal->insertion
+ for main_entity in removed_raytracing_meshes.read() {
+ if let Ok(render_entity) = render_entities.get(main_entity) {
+ commands.entity(render_entity).remove::<RaytracingMesh3d>();
+ }
+ }
+
+ for (render_entity, mesh, material, transform, previous_frame_transform) in &new_instances {
+ commands.entity(render_entity).insert((
+ mesh.clone(),
+ material.clone(),
+ *transform,
+ previous_frame_transform
+ .cloned()
+ .unwrap_or(PreviousGlobalTransform(transform.affine())),
+ ));
+ }
+}
+
+/// Copies the transforms of moved raytracing instances from the main world
+/// straight into their GPU buffers.
+pub fn extract_raytracing_scene_transforms(
+ main_instances: Extract<
+ Query<
+ (
+ RenderEntity,
+ &GlobalTransform,
+ Option<&PreviousGlobalTransform>,
+ ),
+ (
+ Or<(Changed<GlobalTransform>, Changed<PreviousGlobalTransform>)>,
+ With<RaytracingMesh3d>,
+ ),
+ >,
+ >,
+ bindings: Res<RaytracingSceneBindings>,
+) {
+ main_instances
+ .par_iter()
+ .for_each(|(render_entity, transform, previous_frame_transform)| {
+ let previous_frame_transform = previous_frame_transform
+ .cloned()
+ .unwrap_or(PreviousGlobalTransform(transform.affine()));
+
+ bindings.move_instance(render_entity, transform, &previous_frame_transform);
+ });
+}
+
+/// Updates the mesh and material of existing raytracing instances in the render world.
+pub fn extract_raytracing_scene_meshes_and_materials(
+ main_instances: Extract<
+ Query<
+ (
+ RenderEntity,
+ &RaytracingMesh3d,
+ &MeshMaterial3d<StandardMaterial>,
+ ),
+ Or<(
+ Changed<RaytracingMesh3d>,
+ Changed<MeshMaterial3d<StandardMaterial>>,
+ )>,
+ >,
+ >,
+ mut render_instances: Query<(&mut RaytracingMesh3d, &mut MeshMaterial3d<StandardMaterial>)>,
+) {
+ for (render_entity, new_mesh, new_material) in &main_instances {
+ if let Ok((mut mesh, mut material)) = render_instances.get_mut(render_entity) {
+ *mesh = new_mesh.clone();
+ *material = new_material.clone();
+ }
+ }
+}
+
+/// The set of [`StandardMaterial`] in the scene, mirrored into the render world.
+#[derive(Resource, Default)]
+pub struct StandardMaterialAssets {
+ materials: HashMap<AssetId<StandardMaterial>, StandardMaterial>,
+ /// Materials added or modified this frame.
+ pub changed: Vec<AssetId<StandardMaterial>>,
+ /// Materials removed this frame.
+ pub removed: Vec<AssetId<StandardMaterial>>,
+}
+
+impl StandardMaterialAssets {
+ pub fn get(&self, id: &AssetId<StandardMaterial>) -> Option<&StandardMaterial> {
+ self.materials.get(id)
+ }
+}
+
+/// Keeps [`StandardMaterialAssets`] up to date in the render world.
+pub fn extract_raytracing_material_assets(
+ main_materials: Extract<Res<Assets<StandardMaterial>>>,
+ mut render_materials: ResMut<StandardMaterialAssets>,
+ mut events: Extract<MessageReader<AssetEvent<StandardMaterial>>>,
+) {
+ let render_materials = &mut *render_materials;
+
+ render_materials.changed.clear();
+ render_materials.removed.clear();
+
+ for event in events.read() {
+ match event {
+ AssetEvent::Added { id } | AssetEvent::Modified { id } => {
+ if let Some(material) = main_materials.get(*id) {
+ render_materials.materials.insert(*id, material.clone());
+ render_materials.changed.push(*id);
+ }
+ }
+ AssetEvent::Removed { id } => {
+ render_materials.materials.remove(id);
+ render_materials.removed.push(*id);
+ }
+ AssetEvent::Unused { .. } | AssetEvent::LoadedWithDependencies { .. } => {}
+ }
+ }
+}
+
+#[derive(Resource, Default, Clone, PartialEq)]
+pub struct ExtractedEnvironmentMapLight {
+ pub cubemap: Option<Handle<Image>>,
+ pub intensity: f32,
+ pub rotation: Quat,
+ // raea: the camera's EnvironmentSun
+ pub sun: Option<EnvironmentSun>,
+}
+
+/// Finds the environment map light to use for the raytraced scene, if any.
+pub fn extract_raytracing_environment_map_light(
+ cameras: Extract<
+ Query<(
+ &Camera,
+ Option<&GeneratedEnvironmentMapLight>,
+ Option<&EnvironmentMapLight>,
+ Option<&EnvironmentSun>,
+ )>,
+ >,
+ mut environment_map_light: ResMut<ExtractedEnvironmentMapLight>,
+) {
+ let mut extracted_env_map_light = ExtractedEnvironmentMapLight::default();
+
+ for (camera, generated, pregenerated, sun) in &cameras {
+ if !camera.is_active {
+ continue;
+ }
+
+ let env_map_light = match (generated, pregenerated) {
+ (Some(generated), _) => ExtractedEnvironmentMapLight {
+ cubemap: Some(generated.environment_map.clone()),
+ intensity: generated.intensity,
+ rotation: generated.rotation,
+ sun: sun.copied(),
+ },
+ (None, Some(pregenerated)) => ExtractedEnvironmentMapLight {
+ cubemap: Some(pregenerated.specular_map.clone()),
+ intensity: pregenerated.intensity,
+ rotation: pregenerated.rotation,
+ sun: sun.copied(),
+ },
+ (None, None) => continue,
+ };
+
+ if extracted_env_map_light.cubemap.is_none() {
+ extracted_env_map_light = env_map_light;
+ } else if extracted_env_map_light != env_map_light {
+ once!(warn!(
+ "bevy_solari only supports a single environment light for the whole scene, but \
+ multiple cameras have differing environment lights. Using the first one found."
+ ));
+ }
+ }
+
+ *environment_map_light = extracted_env_map_light;
+}
diff --git a/vendor/bevy_solari/src/scene/mod.rs b/vendor/bevy_solari/src/scene/mod.rs
new file mode 100644
index 00000000..b092329c
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/mod.rs
@@ -0,0 +1,106 @@
+mod binder;
+mod blas;
+mod extract;
+mod types;
+
+use bevy_asset::embedded_asset;
+use bevy_shader::load_shader_library;
+pub use binder::prepare_raytracing_scene_resources;
+pub use binder::{RaytracingSceneBindings, RaytracingSceneNeedsPreviousFrameData};
+// raea: EnvironmentSun, a panorama's sun sampled as a light
+pub use types::{EnvironmentSun, RaytracingMesh3d};
+
+use crate::SolariPlugins;
+use bevy_app::{App, Plugin};
+use bevy_ecs::schedule::IntoScheduleConfigs;
+use bevy_render::{
+ mesh::{
+ allocator::{allocate_and_free_meshes, MeshAllocatorSettings},
+ RenderMesh,
+ },
+ render_asset::prepare_assets,
+ render_resource::{update_sparse_buffers, BufferUsages},
+ renderer::{RenderDevice, RenderGraph, RenderGraphSystems},
+ ExtractSchedule, GpuResourceAppExt, Render, RenderApp, RenderSystems,
+};
+use binder::{
+ build_raytracing_tlas, prepare_raytracing_scene_bind_group, TlasInstanceSetupPipeline,
+};
+use blas::{compact_raytracing_blas, delete_raytracing_blas, prepare_raytracing_blas, BlasManager};
+use extract::{
+ extract_raytracing_environment_map_light, extract_raytracing_material_assets,
+ extract_raytracing_scene_meshes_and_materials, extract_raytracing_scene_structural,
+ extract_raytracing_scene_transforms, ExtractedEnvironmentMapLight, StandardMaterialAssets,
+};
+use tracing::warn;
+
+/// Creates acceleration structures and binding arrays of resources for raytracing.
+pub struct RaytracingScenePlugin;
+
+impl Plugin for RaytracingScenePlugin {
+ fn build(&self, app: &mut App) {
+ load_shader_library!(app, "brdf.wesl");
+ load_shader_library!(app, "bindings.wesl");
+ load_shader_library!(app, "sampling.wesl");
+ embedded_asset!(app, "binder/setup_tlas_instances.wesl");
+ }
+
+ fn finish(&self, app: &mut App) {
+ let render_app = app.sub_app_mut(RenderApp);
+
+ let render_device = render_app.world().resource::<RenderDevice>();
+ let features = render_device.features();
+ if !features.contains(SolariPlugins::required_wgpu_features()) {
+ warn!(
+ "RaytracingScenePlugin not loaded. GPU lacks support for required features: {:?}.",
+ SolariPlugins::required_wgpu_features().difference(features)
+ );
+ return;
+ }
+
+ render_app
+ .world_mut()
+ .resource_mut::<MeshAllocatorSettings>()
+ .extra_buffer_usages |= BufferUsages::BLAS_INPUT | BufferUsages::STORAGE;
+
+ render_app
+ .init_resource::<ExtractedEnvironmentMapLight>()
+ .init_gpu_resource::<BlasManager>()
+ .init_gpu_resource::<StandardMaterialAssets>()
+ .init_gpu_resource::<RaytracingSceneBindings>()
+ .init_gpu_resource::<TlasInstanceSetupPipeline>()
+ .add_systems(
+ ExtractSchedule,
+ (
+ extract_raytracing_scene_structural,
+ extract_raytracing_scene_transforms,
+ extract_raytracing_scene_meshes_and_materials,
+ extract_raytracing_material_assets,
+ extract_raytracing_environment_map_light,
+ ),
+ )
+ .add_systems(
+ Render,
+ (
+ prepare_raytracing_blas
+ .in_set(RenderSystems::PrepareAssets)
+ .before(prepare_assets::<RenderMesh>)
+ .after(allocate_and_free_meshes),
+ compact_raytracing_blas
+ .in_set(RenderSystems::PrepareAssets)
+ .after(prepare_raytracing_blas),
+ prepare_raytracing_scene_resources.in_set(RenderSystems::PrepareResources),
+ prepare_raytracing_scene_bind_group.in_set(RenderSystems::PrepareBindGroups),
+ ),
+ )
+ .add_systems(
+ RenderGraph,
+ (
+ build_raytracing_tlas
+ .after(update_sparse_buffers)
+ .in_set(RenderGraphSystems::Begin),
+ delete_raytracing_blas.in_set(RenderGraphSystems::Finish),
+ ),
+ );
+ }
+}
diff --git a/vendor/bevy_solari/src/scene/sampling.wesl b/vendor/bevy_solari/src/scene/sampling.wesl
new file mode 100644
index 00000000..51c459b6
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/sampling.wesl
@@ -0,0 +1,278 @@
+import bevy_pbr::render::pbr_lighting::D_GGX;
+import bevy_pbr::render::utils::{rand_vec2f, rand_u, rand_range_u};
+import bevy_render::maths::{PI_2, orthonormalize};
+import package::scene::bindings::{trace_ray, trace_ray_previous_frame, RAY_T_MIN, RAY_T_MAX, light_sources, directional_lights, environment_map, environment_map_sampler, environment_map_light, LightSource, LIGHT_SOURCE_KIND_DIRECTIONAL, resolve_triangle_data_full, ResolvedRayHitFull, MIRROR_ROUGHNESS_THRESHOLD};
+
+enable wgpu_ray_query;
+
+fn power_heuristic(f: f32, g: f32) -> f32 {
+ return balance_heuristic(f * f, g * g);
+}
+
+fn balance_heuristic(f: f32, g: f32) -> f32 {
+ // Need to guard against NaNs since ReSTIR reservoirs can have UCW=0
+ if f == 0.0 {
+ return 0.0;
+ }
+ // When NaN, fall back to even weights of 0.5 : 0.5
+ let weight = 1.0 / (1.0 + (g / f));
+ return select(weight, 0.5, isnan(weight));
+}
+
+/// https://gpuopen.com/download/Bounded_VNDF_Sampling_for_Smith-GGX_Reflections.pdf (Listing 1)
+/// Result is invalid when output.z <= 0.0, and must be discarded
+fn sample_ggx_vndf(wi_tangent: vec3<f32>, roughness: f32, rng: ptr<function, u32>) -> vec3<f32> {
+ // Mirror BRDF case
+ if roughness <= MIRROR_ROUGHNESS_THRESHOLD {
+ return vec3(-wi_tangent.xy, wi_tangent.z);
+ }
+
+ let i = wi_tangent;
+ let rand = rand_vec2f(rng);
+ let i_std = normalize(vec3(i.xy * roughness, i.z));
+ let phi = PI_2 * rand.x;
+ let a = roughness;
+ let s = 1.0 + length(vec2(i.xy));
+ let a2 = a * a;
+ let s2 = s * s;
+ let k = (1.0 - a2) * s2 / (s2 + a2 * i.z * i.z);
+ let b = select(i_std.z, k * i_std.z, i.z > 0.0);
+ let z = fma(1.0 - rand.y, 1.0 + b, -b);
+ let sin_theta = sqrt(saturate(1.0 - z * z));
+ let o_std = vec3(sin_theta * cos(phi), sin_theta * sin(phi), z);
+ let m_std = i_std + o_std;
+ let m = normalize(vec3(m_std.xy * roughness, m_std.z));
+ return 2.0 * dot(i, m) * m - i;
+}
+
+fn ggx_vndf_sample_invalid(ray_tangent: vec3<f32>) -> bool {
+ return !(ray_tangent.z > 0.0);
+}
+
+/// https://gpuopen.com/download/Bounded_VNDF_Sampling_for_Smith-GGX_Reflections.pdf (Listing 2)
+fn ggx_vndf_pdf(wi_tangent: vec3<f32>, wo_tangent: vec3<f32>, roughness: f32) -> f32 {
+ // Mirror BRDF case
+ if roughness <= MIRROR_ROUGHNESS_THRESHOLD {
+ let mirror_wo = vec3(-wi_tangent.xy, wi_tangent.z);
+ if distance(mirror_wo, wo_tangent) < 0.0001 {
+ return bitcast<f32>(0x7F800000u); // INF
+ } else {
+ return 0.0;
+ }
+ }
+
+ let i = wi_tangent;
+ let o = wo_tangent;
+ let m = normalize(i + o);
+ let ndf = D_GGX(roughness, saturate(m.z));
+ let ai = roughness * i.xy;
+ let len2 = dot(ai, ai);
+ let t = sqrt(len2 + i.z * i.z);
+ var pdf: f32;
+ if i.z >= 0.0 {
+ let a = roughness;
+ let s = 1.0 + length(i.xy);
+ let a2 = a * a;
+ let s2 = s * s;
+ let k = (1.0 - a2) * s2 / (s2 + a2 * i.z * i.z);
+ pdf = ndf / (2.0 * (k * i.z + t));
+ } else {
+ pdf = ndf * (t - i.z) / (2.0 * len2);
+ }
+
+ return select(pdf, 0.0, isnan(pdf));
+}
+
+fn isinf(x: f32) -> bool {
+ return (bitcast<u32>(x) & 0x7fffffffu) == 0x7f800000u;
+}
+
+fn isnan(x: f32) -> bool {
+ return (bitcast<u32>(x) & 0x7fffffffu) > 0x7f800000u;
+}
+
+const NULL_LIGHT_ID = 0xFFFFFFFFu;
+
+struct LightSample {
+ light_id: u32,
+ seed: u32,
+}
+
+struct ResolvedLightSample {
+ world_position: vec4<f32>,
+ world_normal: vec3<f32>,
+ radiance: vec3<f32>,
+ inverse_pdf: f32,
+}
+
+struct LightContribution {
+ radiance: vec3<f32>,
+ inverse_pdf: f32,
+ /// inverse_pdf may not be in solid angle measure (e.g. area measure)
+ /// but inverse_solid_angle_pdf is always in solid angle measure
+ /// for cases where it's required, e.g. MIS between light sampling techniques
+ inverse_solid_angle_pdf: f32,
+ wi: vec3<f32>,
+ brdf_rays_can_hit: bool,
+}
+
+struct GenerateRandomLightSampleResult {
+ light_sample: LightSample,
+ resolved_light_sample: ResolvedLightSample,
+}
+
+fn sample_random_light(ray_origin: vec3<f32>, origin_world_normal: vec3<f32>, rng: ptr<function, u32>) -> LightContribution {
+ let sample = generate_random_light_sample(rng);
+ var light_contribution = calculate_resolved_light_contribution(sample.resolved_light_sample, ray_origin, origin_world_normal);
+ light_contribution.radiance *= trace_visibility(ray_origin, sample.resolved_light_sample.world_position);
+ return light_contribution;
+}
+
+fn random_emissive_light_pdf(hit: ResolvedRayHitFull, ray_distance: f32, NdotV: f32) -> f32 {
+ let light_count = arrayLength(&light_sources);
+ let area_pdf = 1.0 / (f32(light_count) * f32(hit.triangle_count) * hit.triangle_area);
+ return area_pdf * (ray_distance * ray_distance) / NdotV;
+}
+
+// raea: the environment map's light along a direction, its sun disk (EnvironmentSun) showing the sky around it: the
+// sun is a directional light that light sampling finds
+fn sample_environment_map_light(world_direction: vec3<f32>) -> vec3<f32> {
+ return sample_environment_map_light_and_sun(world_direction, false);
+}
+
+// raea: the environment map's light along a direction, with its sun where `sun` (a ray that samples no lights: a
+// camera ray, or one off a mirror)
+fn sample_environment_map_light_and_sun(world_direction: vec3<f32>, sun: bool) -> vec3<f32> {
+ if environment_map_light.intensity == 0.0 { return vec3(0.0); }
+
+ var sample_direction = environment_map_light.light_from_world * world_direction;
+ if !sun && dot(sample_direction, environment_map_light.sun_direction) > environment_map_light.sun_cos {
+ return environment_map_light.sky * environment_map_light.intensity;
+ }
+ sample_direction.z = -sample_direction.z;
+
+ // Hardcoded to sample mip 0 (unfiltered radiance)
+ return textureSampleLevel(environment_map, environment_map_sampler, sample_direction, 0.0).rgb * environment_map_light.intensity;
+}
+
+fn generate_random_light_sample(rng: ptr<function, u32>) -> GenerateRandomLightSampleResult {
+ let light_count = arrayLength(&light_sources);
+ let light_id = rand_range_u(light_count, rng);
+
+ let light_source = light_sources[light_id];
+
+ var triangle_id = 0u;
+ if light_source.kind != LIGHT_SOURCE_KIND_DIRECTIONAL {
+ let triangle_count = light_source.kind >> 1u;
+ triangle_id = rand_range_u(triangle_count, rng);
+ }
+
+ let seed = rand_u(rng);
+ let light_sample = LightSample((light_id << 16u) | triangle_id, seed);
+
+ var resolved_light_sample = resolve_light_sample(light_sample, light_source);
+ resolved_light_sample.inverse_pdf *= f32(light_count);
+
+ return GenerateRandomLightSampleResult(light_sample, resolved_light_sample);
+}
+
+fn resolve_light_sample(light_sample: LightSample, light_source: LightSource) -> ResolvedLightSample {
+ if light_source.kind == LIGHT_SOURCE_KIND_DIRECTIONAL {
+ let directional_light = directional_lights[light_source.id];
+
+ var direction_to_light: vec3<f32>;
+@if(!NO_DIRECTIONAL_LIGHT_SOFT_SHADOWS) {
+ // Sample a random direction within a cone whose base is the sun approximated as a disk
+ // https://www.realtimerendering.com/raytracinggems/unofficial_RayTracingGems_v1.9.pdf#0004286901.INDD%3ASec30%3A305
+ var rng = light_sample.seed;
+ let random = rand_vec2f(&rng);
+ let cos_theta = (1.0 - random.x) + random.x * directional_light.cos_theta_max;
+ let sin_theta = sqrt(1.0 - cos_theta * cos_theta);
+ let phi = random.y * PI_2;
+ let x = cos(phi) * sin_theta;
+ let y = sin(phi) * sin_theta;
+ direction_to_light = vec3(x, y, cos_theta);
+
+ // Rotate the ray so that the cone it was sampled from is aligned with the light direction
+ direction_to_light = orthonormalize(directional_light.direction_to_light) * direction_to_light;
+} @else {
+ direction_to_light = directional_light.direction_to_light;
+}
+
+ return ResolvedLightSample(
+ vec4(direction_to_light, 0.0),
+ -direction_to_light,
+ directional_light.luminance,
+ directional_light.inverse_pdf,
+ );
+} else {
+ let triangle_count = light_source.kind >> 1u;
+ let triangle_id = light_sample.light_id & 0xFFFFu;
+ let barycentrics = triangle_barycentrics(light_sample.seed);
+ let triangle_data = resolve_triangle_data_full(light_source.id, triangle_id, barycentrics);
+
+ return ResolvedLightSample(
+ vec4(triangle_data.world_position, 1.0),
+ triangle_data.world_normal,
+ triangle_data.material.emissive.rgb,
+ f32(triangle_count) * triangle_data.triangle_area,
+ );
+ }
+}
+
+fn calculate_resolved_light_contribution(resolved_light_sample: ResolvedLightSample, ray_origin: vec3<f32>, origin_world_normal: vec3<f32>) -> LightContribution {
+ let ray = resolved_light_sample.world_position.xyz - (resolved_light_sample.world_position.w * ray_origin);
+ let light_distance = length(ray);
+ let wi = ray / light_distance;
+
+ let cos_theta_light = saturate(dot(-wi, resolved_light_sample.world_normal));
+ let light_distance_squared = light_distance * light_distance;
+ let denominator = cos_theta_light / light_distance_squared;
+
+ let radiance = resolved_light_sample.radiance * denominator;
+ let inverse_solid_angle_pdf = resolved_light_sample.inverse_pdf * denominator;
+
+ return LightContribution(radiance, resolved_light_sample.inverse_pdf, inverse_solid_angle_pdf, wi, resolved_light_sample.world_position.w == 1.0);
+}
+
+fn trace_visibility(ray_origin: vec3<f32>, point: vec4<f32>) -> f32 {
+ var ray_direction = point.xyz;
+ var ray_t_max = RAY_T_MAX;
+
+ if point.w == 1.0 {
+ let ray = ray_direction - ray_origin;
+ let dist = length(ray);
+ ray_direction = ray / dist;
+ ray_t_max = dist - RAY_T_MIN;
+ }
+
+ if ray_t_max < RAY_T_MIN { return 0.0; }
+
+ let ray_hit = trace_ray(ray_origin, ray_direction, RAY_T_MIN, ray_t_max, RAY_FLAG_TERMINATE_ON_FIRST_HIT);
+ return f32(ray_hit.kind == RAY_QUERY_INTERSECTION_NONE);
+}
+
+fn trace_visibility_previous_frame(ray_origin: vec3<f32>, point: vec4<f32>) -> f32 {
+ var ray_direction = point.xyz;
+ var ray_t_max = RAY_T_MAX;
+
+ if point.w == 1.0 {
+ let ray = ray_direction - ray_origin;
+ let dist = length(ray);
+ ray_direction = ray / dist;
+ ray_t_max = dist - RAY_T_MIN;
+ }
+
+ if ray_t_max < RAY_T_MIN { return 0.0; }
+
+ let ray_hit = trace_ray_previous_frame(ray_origin, ray_direction, RAY_T_MIN, ray_t_max, RAY_FLAG_TERMINATE_ON_FIRST_HIT);
+ return f32(ray_hit.kind == RAY_QUERY_INTERSECTION_NONE);
+}
+
+/// https://www.realtimerendering.com/raytracinggems/unofficial_RayTracingGems_v1.9.pdf#0004286901.INDD%3ASec22%3A297
+fn triangle_barycentrics(seed: u32) -> vec3<f32> {
+ var rng = seed;
+ var barycentrics = rand_vec2f(&rng);
+ if barycentrics.x + barycentrics.y > 1.0 { barycentrics = 1.0 - barycentrics; }
+ return vec3(1.0 - barycentrics.x - barycentrics.y, barycentrics);
+}
diff --git a/vendor/bevy_solari/src/scene/types.rs b/vendor/bevy_solari/src/scene/types.rs
new file mode 100644
index 00000000..f1d3aba8
--- /dev/null
+++ b/vendor/bevy_solari/src/scene/types.rs
@@ -0,0 +1,40 @@
+use bevy_asset::Handle;
+use bevy_derive::{Deref, DerefMut};
+use bevy_ecs::{component::Component, prelude::ReflectComponent, template::FromTemplate};
+use bevy_mesh::Mesh;
+use bevy_pbr::{MeshMaterial3d, StandardMaterial};
+use bevy_reflect::{prelude::ReflectDefault, Reflect};
+use bevy_render::sync_world::SyncToRenderWorld;
+use bevy_transform::components::Transform;
+use derive_more::derive::From;
+
+/// A mesh component used for raytracing.
+///
+/// The mesh used in this component must have [`Mesh::enable_raytracing`] set to true,
+/// use the following set of vertex attributes: `{POSITION, NORMAL, UV_0, TANGENT}`, use [`bevy_mesh::PrimitiveTopology::TriangleList`],
+/// and use [`bevy_mesh::Indices::U32`].
+///
+/// The material used for this entity must be [`MeshMaterial3d<StandardMaterial>`].
+#[derive(
+ Component, FromTemplate, Clone, Debug, Default, Deref, DerefMut, Reflect, PartialEq, Eq, From,
+)]
+#[reflect(Component, Default, Clone, PartialEq)]
+#[require(MeshMaterial3d<StandardMaterial>, Transform, SyncToRenderWorld)]
+pub struct RaytracingMesh3d(pub Handle<Mesh>);
+
+/// raea: the sun in a camera's environment map, found in its panorama (a small disk far brighter than the sky). Solari
+/// samples it as a directional light, so glossy and diffuse surfaces get its highlights and shadows, which reflection
+/// rays alone find too rarely for the denoiser to keep; inside its disk the environment map then shows `sky`, so its
+/// light isn't counted twice. Rays that don't sample lights (the path tracer's camera rays and mirror bounces) still see
+/// the panorama's own sun.
+#[derive(Component, Clone, Copy, Debug, Default, PartialEq)]
+pub struct EnvironmentSun {
+ /// Toward the sun, in the panorama's own space: the world's before the environment map light's rotation.
+ pub direction: bevy_math::Vec3,
+ /// The sun disk's angular diameter, in radians.
+ pub angular_size: f32,
+ /// The illuminance it adds, linear RGB, before the environment map light's intensity.
+ pub illuminance: bevy_math::Vec3,
+ /// The sky's radiance around it, linear RGB, before the intensity: what the environment map shows inside the disk.
+ pub sky: bevy_math::Vec3,
+}
diff --git a/vendor/vendor.toml b/vendor/vendor.toml
index 0782c735..ac84fa75 100644
--- a/vendor/vendor.toml
+++ b/vendor/vendor.toml
@@ -44,6 +44,13 @@ kind = "patch"
reason = "on Taffy 0.15 (Blitz's), so one Taffy builds"
exit = "a Bevy release on Taffy 0.15"
+[bevy_solari]
+path = "vendor/bevy_solari"
+upstream = "crates.io:0.20.0"
+kind = "patch"
+reason = "materials traced by their alpha (mask, blend, a premultiplied coat), uv_transform, and a panorama sun sampled as a directional light"
+exit = "a Bevy release whose Solari traces alpha and importance-samples the environment map"
+
# checked 2026-10-26: crates.io bevy_ui_widgets 0.20.0 (latest) is still on parley ^0.11; a Bevy git revision with 0.12 is Bevy main, not 0.20
[bevy_ui_widgets]
path = "vendor/bevy_ui_widgets"