Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
<SolariLighting>'s denoiser, guides, emission and jitter are props: an A/B is two compositions, not a build
shinyobjectz82f1fb40520f
diff --git a/Cargo.lock b/Cargo.lockindex 71b78ed5..1cb6caa6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14964,6 +14964,8 @@ dependencies = ["objc2-metal 0.3.2","objc2-metal-fx","raea-io-home",+ "raea-io-trace",+ "serde_json","wgpu",]diff --git a/engine/render/raytrace/Cargo.toml b/engine/render/raytrace/Cargo.tomlindex 57950696..c7775d3a 100644--- a/engine/render/raytrace/Cargo.toml+++ b/engine/render/raytrace/Cargo.toml@@ -9,6 +9,9 @@ description = "raea-render's ray tracing: Bevy's Solari for a scene whose camera[dependencies]# RAEA_SOLARI_DYNAMIC=1 read as raea's other switches areraea-io-home = { path = "../../../io/home" }+# each view's effective SolariSettings, once, into the run's trace (settings.rs)+raea-io-trace = { path = "../../../io/trace" }+serde_json = "1"bevy = { version = "=0.20.0", default-features = false, features = ["std", "3d_bevy_render", "bevy_solari"] }# the same wgpu Bevy uses (the guide pass records on its device; MetalFX runs on its Metal objects)wgpu = "=30.0.1"diff --git a/engine/render/raytrace/src/emit_taa.rs b/engine/render/raytrace/src/emit_taa.rsindex 0aa7e1b7..d6bd0c4e 100644--- a/engine/render/raytrace/src/emit_taa.rs+++ b/engine/render/raytrace/src/emit_taa.rs@@ -28,12 +28,6 @@ use bevy::prelude::*;pub(crate) const WGSL: &str = include_str!("emit_taa.wgsl");-/// On unless RAEA_SOLARI_EMISSIVE is mask or split.-pub(crate) fn on() -> bool {- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();- *ON.get_or_init(|| !matches!(std::env::var("RAEA_SOLARI_EMISSIVE").as_deref(), Ok("mask") | Ok("split")))-}-/// RAEA_EMIT_TAA_DEBUG=1: the pass paints its weights instead; 2 never takes the history, 3 always does; 4 paints which/// of RT32's rules held it (emit_taa.wgsl)pub(crate) fn debug() -> f32 {@@ -41,14 +35,6 @@ pub(crate) fn debug() -> f32 {*ON.get_or_init(|| std::env::var("RAEA_EMIT_TAA_DEBUG").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0))}-/// RAEA_EMIT_TAA_SHARP: how fast a sample's weight falls with its distance from a pixel's centre, exp(-k d^2) in output-/// pixels, 6 by default: at Blackman-Harris's 2.29 the forest's canopy came out 1.28 times the tracer's as seen (tone-/// mapped), its sky through the twigs spread wider than a pixel, and a screen's detail 0.38 of the tracer's-pub(crate) fn sharp() -> f32 {- static ON: std::sync::OnceLock<f32> = std::sync::OnceLock::new();- *ON.get_or_init(|| std::env::var("RAEA_EMIT_TAA_SHARP").ok().and_then(|v| v.parse().ok()).unwrap_or(6.0))-}-/// A view's emission history at the output's size: the gathered emission and its weight, and the depths it was gathered/// over with the evidence for its nearest surface, two of each, one read as the other is written.pub(crate) struct History {diff --git a/engine/render/raytrace/src/lib.rs b/engine/render/raytrace/src/lib.rsindex 47bd127f..eece6810 100644--- a/engine/render/raytrace/src/lib.rs+++ b/engine/render/raytrace/src/lib.rs@@ -15,6 +15,8 @@ mod emit_taa;mod upscale;// RAEA_LIGHT: one light path for every camera (docs/realism.feature LT1)pub mod force;+// SolariSettings' environment overrides (docs/nobuild.feature NB1a)+mod settings;/// RT9: the fraction of the view's size a side this camera's main pass draws at (a third to 1), which MetalFX's/// temporal scaler brings up to the whole view after it (upscale.rs); 1 draws at the full size. <SolariLighting scale>@@ -31,9 +33,63 @@ impl Default for RenderScale {}}+/// A Solari camera's settings for the denoiser, its guides, the emission's history and the jitter (docs/nobuild.feature+/// NB1a): what <SolariLighting>'s props set in TypeScript, through <BevyComponent> by this type's path, so a value is+/// tried in a composition, never a build. Each field's environment variable overrides it for every camera, as a+/// developer's A/B (settings.rs); a camera without it has the defaults. Read on the view, each frame.+#[derive(Component, Reflect, Clone, Debug, PartialEq, bevy::render::extract_component::ExtractComponent)]+#[extract_app(bevy::render::RenderApp)]+#[reflect(Component, Default)]+pub struct SolariSettings {+ /// MetalFX's denoiser on the lighting (RT4); off shows Solari's noise (RAEA_SOLARI_DENOISE=0)+ pub denoise: bool,+ /// the denoiser guided by Solari's own guides, a mirror's pixel taking what it reflects (RT17); off, by the G-buffer+ /// (RAEA_SOLARI_PSR=0)+ pub guides: bool,+ /// a glossy pixel as far off as what it reflects in the denoiser's depth, so its reflection doesn't trail (RT34;+ /// RAEA_SOLARI_PSR_DEPTH=0)+ pub reflection_depth: bool,+ /// an emissive surface's own light: "taa", taken out before the denoiser and gathered over frames (RT11, RT32);+ /// "split", each frame's alone; "mask", left in for the denoiser (RAEA_SOLARI_EMISSIVE)+ pub emissive: String,+ /// a view drawn small: denoised and brought up in "one" pass, or denoised small and scaled in a second, "two"+ /// (RAEA_SOLARI_UPSCALE)+ pub upscale: String,+ /// what MetalFX divides the colour by before it denoises and multiplies it by after: bright light kept, at the cost+ /// of fireflies past 16 (metalfx.rs pre_exposure; RAEA_METALFX_PREEXPOSURE)+ pub preexposure: f32,+ /// a full-size view jittered too, so the denoiser anti-aliases its edges as it gathers frames (RAEA_SOLARI_AA=0)+ pub aa: bool,+ /// which of MetalFX's passes is told the jitter: "" the denoiser, "scaler", "both", "flip", "0" none (and none is+ /// made) (RAEA_SOLARI_JITTER)+ pub jitter: String,+ /// how fast a sample's weight falls with its distance from a pixel's centre in the emission's history, exp(-k d^2)+ /// in output pixels (RAEA_EMIT_TAA_SHARP): at Blackman-Harris's 2.29 the forest's canopy came out 1.28 times the+ /// tracer's as seen (tone mapped), its sky through the twigs spread wider than a pixel, and a screen's detail 0.38+ /// of the tracer's+ pub emissive_sharpness: f32,+}++impl Default for SolariSettings {+ fn default() -> Self {+ SolariSettings {+ denoise: true,+ guides: true,+ reflection_depth: true,+ emissive: "taa".into(),+ upscale: "one".into(),+ preexposure: 16.0,+ aa: true,+ jitter: String::new(),+ emissive_sharpness: 6.0,+ }+ }+}+/// Solari's plugins, and RAEA_LIGHT's camera override when it names a path.pub fn add(app: &mut App) {- app.register_type::<RenderScale>();+ app.register_type::<RenderScale>().register_type::<SolariSettings>();+ app.add_plugins(bevy::render::extract_component::ExtractComponentPlugin::<SolariSettings>::default());solari::add(app);force::add(app);}diff --git a/engine/render/raytrace/src/metalfx.rs b/engine/render/raytrace/src/metalfx.rsindex b3d06624..4140a88a 100644--- a/engine/render/raytrace/src/metalfx.rs+++ b/engine/render/raytrace/src/metalfx.rs@@ -16,7 +16,8 @@//! frame on the small grid, so the scaler gained nothing from the jitter (0.7 of the full size's fine detail at 0.67).//!//! Where there's no MetalFX denoiser (not macOS 26, not Metal, a device it doesn't support) the lighting draws as it-//! is and raea says so once. RAEA_SOLARI_DENOISE=0 turns it off, to see the noise.+//! is and raea says so once. A view's SolariSettings choose how it runs (lib.rs; docs/nobuild.feature NB1a): `denoise`+//! false (RAEA_SOLARI_DENOISE=0) leaves its lighting un-denoised, to see the noise.use super::*;use bevy::camera::MainPassResolutionOverride;@@ -42,9 +43,6 @@ use wgpu::hal::api::Metal;/// nothing in the G-buffer, and denoising them would smear them. Bevy doesn't export Solari's system, so it's found by/// name and ordered against by its system type set.pub(crate) fn add(app: &mut App) {- if std::env::var("RAEA_SOLARI_DENOISE").is_ok_and(|v| v == "0") {- return;- }let Some(r) = app.get_sub_app_mut(bevy::render::RenderApp) else { return };let mut schedules = r.world_mut().resource_mut::<Schedules>();let Some(core) = schedules.get_mut(Core3d) else { return };@@ -61,37 +59,10 @@ pub(crate) fn add(app: &mut App) {};core.add_systems(denoise.after(solari).before(main_opaque_pass_3d).in_set(Core3dSystems::MainPass));core.add_systems(denoise_up.before(super::upscale::upscale).in_set(Core3dSystems::EarlyPostProcess));- // Solari's own guides (primary surface replacement: a mirror's pixel takes what it reflects), unless- // RAEA_SOLARI_PSR=0, which guides from the G-buffer as before- if std::env::var("RAEA_SOLARI_PSR").as_deref() != Ok("0") {- r.world_mut().insert_resource(bevy::solari::realtime::SolariGuideBuffers { reflection_depth: psr_depth() });- }-}--/// The emission taken out before the denoiser and put back after (see DECODE_WGSL): gathered over frames by default-/// (emit_taa.rs), each frame's alone with RAEA_SOLARI_EMISSIVE=split; =mask leaves it in, for the denoiser.-fn split() -> bool {- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();- *ON.get_or_init(|| std::env::var("RAEA_SOLARI_EMISSIVE").as_deref() == Ok("split") || super::emit_taa::on())-}--/// A view drawn small is denoised and brought up in one pass (unless RAEA_SOLARI_UPSCALE=two).-fn one_pass() -> bool {- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();- *ON.get_or_init(|| std::env::var("RAEA_SOLARI_UPSCALE").as_deref() != Ok("two"))-}--/// What MetalFX divides the colour by before it denoises, and multiplies its output by after (RAEA_METALFX_PREEXPOSURE,-/// 16 by default). It denoises bright light compressed, so a rare bright sample (the sky in a glossy reflection, a-/// lamp's light found by one path in many) counts for less than its share, and Solari's one path a pixel is made of-/// rare bright samples: at 1, the desk kept 0.74 of the path tracer's light, the forest's haze 0.72 and its far trunks-/// 0.87, and Russian roulette's doubled samples lost more (photo 5's windows: q 0.5 kept 0.60 of q 1's light; 3.4-/// stops darker, 0.97). At 16: the desk 0.86, the haze 1.03, the trunks 1.01, the hall's whole frame 0.935 -> 0.971-/// and q 0.5 keeping 0.98 of q 1's; flicker 0.85 -> 0.88% of pixels. Higher keeps more and lets fireflies through:-/// at 64 the desk 0.91 and the hall's dark corners 1.2; at 256 the desk's wall 1.59-fn pre_exposure() -> f32 {- static ON: std::sync::OnceLock<f32> = std::sync::OnceLock::new();- *ON.get_or_init(|| std::env::var("RAEA_METALFX_PREEXPOSURE").ok().and_then(|v| v.parse().ok()).filter(|v: &f32| *v > 0.0).unwrap_or(16.0))+ // Solari's own guides (primary surface replacement: a mirror's pixel takes what it reflects, and a glossy one is as+ // far off as what it reflects, RT34), written for every view; a view's `guides` and `reflection_depth` choose whether+ // its denoiser reads them+ r.world_mut().insert_resource(bevy::solari::realtime::SolariGuideBuffers { reflection_depth: true });}// the guides' shader: what it writes and why (the emission's split) is in its file@@ -150,7 +121,7 @@ fn mtl(t: &wgpu::Texture) -> Option<Retained<ProtocolObject<dyn MTLTexture>>> {}impl View {- fn new(dev: &wgpu::Device, size: UVec2, out_size: UVec2, guide_depth: bool) -> Result<View, String> {+ fn new(dev: &wgpu::Device, size: UVec2, out_size: UVec2, guide_depth: bool, taa: bool) -> Result<View, String> {let hal = unsafe { dev.as_hal::<Metal>() }.ok_or("the GPU isn't on Metal")?;let device = hal.raw_device();unsafe {@@ -189,7 +160,7 @@ impl View {emit: texture(dev, size, wgpu::TextureFormat::Rgba16Float, guide, "metalfx split emission"),mask: texture(dev, size, wgpu::TextureFormat::R32Float, guide, "metalfx denoise strength"),out: texture(dev, out_size, wgpu::TextureFormat::Rgba16Float, guide | U::RENDER_ATTACHMENT | U::COPY_SRC, "metalfx output"),- taa: super::emit_taa::on().then(|| super::emit_taa::History::new(dev, out_size)),+ taa: taa.then(|| super::emit_taa::History::new(dev, out_size)),fresh: true,})}@@ -197,8 +168,16 @@ impl View {/// The denoiser on `cb`, then its output copied over the colour's corner of its size. `jitter` is the/// camera's this frame, in the main pass's pixels, as MetalFX takes it (Bevy's TemporalJitter negated, as its DLSS- /// gives it).- fn encode(&mut self, cb: &ProtocolObject<dyn MTLCommandBuffer>, color: &wgpu::Texture, depth: &wgpu::Texture, motion: &wgpu::Texture, view: &ExtractedView, jitter: Vec2, reset: bool) -> Result<(), &'static str> {+ /// gives it). `pre_exposure`: what MetalFX divides the colour by before it denoises, and multiplies its output by+ /// after (SolariSettings.preexposure, 16 by default). It denoises bright light compressed, so a rare bright sample (the+ /// sky in a glossy reflection, a lamp's light found by one path in many) counts for less than its share, and Solari's+ /// one path a pixel is made of rare bright samples: at 1, the desk kept 0.74 of the path tracer's light, the forest's+ /// haze 0.72 and its far trunks 0.87, and Russian roulette's doubled samples lost more (photo 5's windows: q 0.5 kept+ /// 0.60 of q 1's light; 3.4 stops darker, 0.97). At 16: the desk 0.86, the haze 1.03, the trunks 1.01, the hall's+ /// whole frame 0.935 -> 0.971 and q 0.5 keeping 0.98 of q 1's; flicker 0.85 -> 0.88% of pixels. Higher keeps more+ /// and lets fireflies through: at 64 the desk 0.91 and the hall's dark corners 1.2; at 256 the desk's wall 1.59+ #[allow(clippy::too_many_arguments)]+ fn encode(&mut self, cb: &ProtocolObject<dyn MTLCommandBuffer>, color: &wgpu::Texture, depth: &wgpu::Texture, motion: &wgpu::Texture, view: &ExtractedView, jitter: Vec2, reset: bool, pre_exposure: f32) -> Result<(), &'static str> {let get = |t: &wgpu::Texture| mtl(t).ok_or("a texture isn't a Metal one");let (color, depth, motion) = (get(color)?, get(depth)?, get(motion)?);let (diffuse, specular, normal, rough, out) = (get(&self.diffuse)?, get(&self.specular)?, get(&self.normal)?, get(&self.rough)?, get(&self.out)?);@@ -221,7 +200,7 @@ impl View {s.setJitterOffsetX(jitter.x);s.setJitterOffsetY(jitter.y);s.setDepthReversed(true);- s.setPreExposure(pre_exposure());+ s.setPreExposure(pre_exposure);s.setShouldResetHistory(reset || self.fresh);matrices(s, view.world_from_view.to_matrix().inverse(), view.clip_from_view);s.encodeToCommandBuffer(cb);@@ -261,46 +240,44 @@ fn matrices(s: &ProtocolObject<dyn MTLFXTemporalDenoisedScaler>, world_to_view:}}-type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static ExtractedView, &'static ExtractedCamera, &'static SolariLighting, Option<&'static MainPassResolutionOverride>, Option<&'static TemporalJitter>, Has<super::upscale::Upscaled>, Option<&'static SolariGuideTextures>);+type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static ExtractedView, &'static ExtractedCamera, &'static SolariLighting, Option<&'static MainPassResolutionOverride>, Option<&'static TemporalJitter>, Has<super::upscale::Upscaled>, Option<&'static SolariGuideTextures>, Option<&'static super::SolariSettings>);-/// Before the forward meshes: a view at its full size, or one drawn small when RAEA_SOLARI_UPSCALE=two (its corner).-fn denoise(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {+/// Before the forward meshes: a view at its full size, or one drawn small whose settings upscale in "two" (its corner).+/// Each view's settings go into the run's trace here, once and on a change.+fn denoise(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext, mut seen: Local<HashMap<Entity, super::SolariSettings>>) {let entity = view.entity();let item = view.into_inner();- if item.7 && one_pass() {+ let st = super::settings::of(item.9);+ let scale = item.5.map_or(1.0, |p| p.0.x as f32 / item.0.main_texture().width() as f32);+ super::settings::record(entity, &st, scale, &mut seen);+ if !st.denoise || (item.7 && st.one_pass()) {return;}- run(entity, item, &device, &mut kit, &mut ctx, false);+ run(entity, item, &st, &device, &mut kit, &mut ctx, false);}/// After the main pass: a view drawn small, denoised from its corner out to its whole size.fn denoise_up(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {let entity = view.entity();let item = view.into_inner();- if !item.7 || !one_pass() {+ let st = super::settings::of(item.9);+ if !st.denoise || !item.7 || !st.one_pass() {return;}- run(entity, item, &device, &mut kit, &mut ctx, true);-}--/// The denoiser's depth is Solari's guide depth, where a glossy pixel is as far off as what it reflects (docs/raytracing.feature-/// RT34): an orb's reflection in a monitor's glass no longer trails it (+0.71 -> +0.08 stops). RAEA_SOLARI_PSR_DEPTH=0-/// gives it the prepass's depth, as before. A glossy pixel whose reflection leaves the scene must have its depth too: left-/// unwritten (0, the sky's) MetalFX darkened window.tsx's shelves, far from those pixels, by 8%-fn psr_depth() -> bool {- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();- *ON.get_or_init(|| std::env::var("RAEA_SOLARI_PSR_DEPTH").as_deref() != Ok("0"))+ run(entity, item, &st, &device, &mut kit, &mut ctx, true);}-type Item<'a> = (&'a ViewTarget, &'a ViewPrepassTextures, &'a ExtractedView, &'a ExtractedCamera, &'a SolariLighting, Option<&'a MainPassResolutionOverride>, Option<&'a TemporalJitter>, bool, Option<&'a SolariGuideTextures>);+type Item<'a> = (&'a ViewTarget, &'a ViewPrepassTextures, &'a ExtractedView, &'a ExtractedCamera, &'a SolariLighting, Option<&'a MainPassResolutionOverride>, Option<&'a TemporalJitter>, bool, Option<&'a SolariGuideTextures>, Option<&'a super::SolariSettings>);/// The guides from the G-buffer and the emissive out, at the main pass's size; MetalFX's denoiser, out to the whole/// view when `up`; its output over the colour and the emissive back in.-fn run(entity: Entity, item: Item, device: &RenderDevice, kit: &mut Kit, ctx: &mut RenderContext, up: bool) {+fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDevice, kit: &mut Kit, ctx: &mut RenderContext, up: bool) {if kit.off {return;}- let (target, pre, ext, cam, solari, part, jitter, _, guides) = item;+ let (target, pre, ext, cam, solari, part, jitter, _, guides, _) = item;+ // Solari wrote its guides for every view; this one reads them unless its settings say the G-buffer's+ let guides = guides.filter(|_| st.guides);let (Some(depth), Some(motion), Some(gbuf)) = (pre.depth.as_ref(), pre.motion_vectors.as_ref(), pre.deferred.as_ref()) else { return };if target.main_texture_format() != TextureFormat::Rgba16Float {return;@@ -309,13 +286,14 @@ fn run(entity: Entity, item: Item, device: &RenderDevice, kit: &mut Kit, ctx: &mlet full = UVec2::new(color.width(), color.height());let size = part.map_or(full, |p| p.0);let out_size = if up { full } else { size };- let jitter = jitter.map_or(Vec2::ZERO, |j| -j.offset * super::upscale::jitter_gain(true, true));+ let jitter = jitter.map_or(Vec2::ZERO, |j| -j.offset * super::upscale::jitter_gain(&st.jitter, true, true));let dev = device.wgpu_device().clone();// with Solari's guides, the denoiser's depth is theirs: a mirror's pixel as far off as what it reflects, so when what// it reflects moves off (an orb in a monitor's glass) the wall now there is a disocclusion and its history goes- let guide_depth = guides.is_some() && psr_depth();- if kit.views.get(&entity).map(|v| (v.size, v.out_size, v.guide_depth)) != Some((size, out_size, guide_depth)) {- match View::new(&dev, size, out_size, guide_depth) {+ let guide_depth = guides.is_some() && st.reflection_depth;+ let taa = st.taa();+ if kit.views.get(&entity).map(|v| (v.size, v.out_size, v.guide_depth, v.taa.is_some())) != Some((size, out_size, guide_depth, taa)) {+ match View::new(&dev, size, out_size, guide_depth, taa) {Ok(v) => {kit.views.insert(entity, v);}@@ -340,7 +318,7 @@ fn run(entity: Entity, item: Item, device: &RenderDevice, kit: &mut Kit, ctx: &mlet reset = solari.reset || kit.views.get(&entity).is_none_or(|v| v.fresh);// the jitter's cycle at this render scale, how long a twig glimpsed through it can stay away (emit_taa.wgsl)let cycle = super::upscale::cycle(size.x as f32 / full.x as f32) as f32;- let words: [f32; 16] = [cam.exposure, if split() { 1.0 } else { 0.0 }, if reset { 1.0 } else { 0.0 }, super::emit_taa::debug(), out_size.x as f32, out_size.y as f32, size.x as f32, size.y as f32, back.x, back.y, back.z, super::emit_taa::sharp(), jitter.x, jitter.y, cycle, 0.0];+ let words: [f32; 16] = [cam.exposure, if st.split() { 1.0 } else { 0.0 }, if reset { 1.0 } else { 0.0 }, super::emit_taa::debug(), out_size.x as f32, out_size.y as f32, size.x as f32, size.y as f32, back.x, back.y, back.z, st.emissive_sharpness, jitter.x, jitter.y, cycle, 0.0];let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_ne_bytes()).collect();let params = wgpu::util::DeviceExt::create_buffer_init(&dev, &wgpu::util::BufferInitDescriptor { label: Some("metalfx params"), contents: &bytes, usage: wgpu::BufferUsages::UNIFORM });let v = kit.views.get_mut(&entity).unwrap();@@ -379,13 +357,13 @@ fn run(entity: Entity, item: Item, device: &RenderDevice, kit: &mut Kit, ctx: &mlet mut raw = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("metalfx denoise") });let done = unsafe {raw.as_hal_mut::<Metal, _, _>(|e| match e.and_then(|e| e.raw_command_buffer()) {- Some(cb) => v.encode(cb, color, match guides { Some(g) if v.guide_depth => &g.depth.texture, _ => &depth.texture.texture }, guide_motion, ext, jitter, solari.reset),+ Some(cb) => v.encode(cb, color, match guides { Some(g) if v.guide_depth => &g.depth.texture, _ => &depth.texture.texture }, guide_motion, ext, jitter, solari.reset, st.preexposure),None => Err("wgpu gave no Metal command buffer"),})};ctx.add_command_buffer(raw.finish());// the emissive back in, after the denoiser's command buffer (add_command_buffer flushed the encoder before it)- if split() {+ if st.split() {let mut entries = vec![wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&color_view) },wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() },diff --git a/engine/render/raytrace/src/settings.rs b/engine/render/raytrace/src/settings.rsnew file mode 100644index 00000000..fdb30edc--- /dev/null+++ b/engine/render/raytrace/src/settings.rs@@ -0,0 +1,119 @@+//! SolariSettings' environment overrides (docs/nobuild.feature NB1a): each field's variable, read once, over every+//! camera's value, so an A/B on any scene needs neither a build nor an edit. A camera without SolariSettings has the+//! defaults, under the same overrides.+use super::SolariSettings;+use bevy::prelude::Entity;+use std::collections::HashMap;++#[derive(Default)]+struct Overrides {+ denoise: Option<bool>,+ guides: Option<bool>,+ reflection_depth: Option<bool>,+ emissive: Option<String>,+ upscale: Option<String>,+ preexposure: Option<f32>,+ aa: Option<bool>,+ jitter: Option<String>,+ emissive_sharpness: Option<f32>,+}++fn overrides() -> &'static Overrides {+ static O: std::sync::OnceLock<Overrides> = std::sync::OnceLock::new();+ O.get_or_init(|| {+ let var = |n: &str| std::env::var(n).ok();+ // "0" turns a switch off and anything else on, as each variable did on its own+ let switch = |n: &str| var(n).map(|v| v != "0");+ let num = |n: &str| var(n).and_then(|v| v.parse::<f32>().ok()).filter(|v| v.is_finite() && *v > 0.0);+ Overrides {+ denoise: switch("RAEA_SOLARI_DENOISE"),+ guides: switch("RAEA_SOLARI_PSR"),+ reflection_depth: switch("RAEA_SOLARI_PSR_DEPTH"),+ emissive: var("RAEA_SOLARI_EMISSIVE").filter(|v| matches!(v.as_str(), "taa" | "split" | "mask")),+ upscale: var("RAEA_SOLARI_UPSCALE").filter(|v| matches!(v.as_str(), "one" | "two")),+ preexposure: num("RAEA_METALFX_PREEXPOSURE"),+ aa: switch("RAEA_SOLARI_AA"),+ jitter: var("RAEA_SOLARI_JITTER"),+ emissive_sharpness: num("RAEA_EMIT_TAA_SHARP"),+ }+ })+}++/// A view's settings as they apply: its own (or the defaults), each overridden by its variable when that is set.+pub(crate) fn of(s: Option<&SolariSettings>) -> SolariSettings {+ let o = overrides();+ let mut s = s.cloned().unwrap_or_default();+ if let Some(v) = o.denoise { s.denoise = v; }+ if let Some(v) = o.guides { s.guides = v; }+ if let Some(v) = o.reflection_depth { s.reflection_depth = v; }+ if let Some(v) = &o.emissive { s.emissive = v.clone(); }+ if let Some(v) = &o.upscale { s.upscale = v.clone(); }+ if let Some(v) = o.preexposure { s.preexposure = v; }+ if let Some(v) = o.aa { s.aa = v; }+ if let Some(v) = &o.jitter { s.jitter = v.clone(); }+ if let Some(v) = o.emissive_sharpness { s.emissive_sharpness = v; }+ s+}++/// The variables set, each with its value and the prop it overrides.+fn set() -> Vec<(&'static str, String, &'static str)> {+ [+ ("RAEA_SOLARI_DENOISE", "denoise"),+ ("RAEA_SOLARI_PSR", "guides"),+ ("RAEA_SOLARI_PSR_DEPTH", "reflectionDepth"),+ ("RAEA_SOLARI_EMISSIVE", "emissive"),+ ("RAEA_SOLARI_UPSCALE", "upscale"),+ ("RAEA_METALFX_PREEXPOSURE", "preexposure"),+ ("RAEA_SOLARI_AA", "aa"),+ ("RAEA_SOLARI_JITTER", "jitter"),+ ("RAEA_EMIT_TAA_SHARP", "emissiveSharpness"),+ ("RAEA_SOLARI_SCALE", "scale"),+ ]+ .into_iter()+ .filter_map(|(n, prop)| std::env::var(n).ok().map(|v| (n, v, prop)))+ .collect()+}++/// A view's settings as they apply, into the run's trace (`solari_settings`: the view, each field, and the variables+/// that overrode a prop) the first frame and whenever they change, so a render says what it drew with; and once a run,+/// on stderr, which variables override <SolariLighting>'s props.+/// `scale`: the fraction of the view's width its main pass draws (RenderScale, or RAEA_SOLARI_SCALE's).+pub(crate) fn record(view: Entity, s: &SolariSettings, scale: f32, seen: &mut HashMap<Entity, SolariSettings>) {+ if seen.get(&view) == Some(s) {+ return;+ }+ seen.insert(view, s.clone());+ let env = set();+ static SAID: std::sync::Once = std::sync::Once::new();+ if !env.is_empty() {+ SAID.call_once(|| {+ let list: Vec<String> = env.iter().map(|(n, v, prop)| format!("{n}={v} over {prop}")).collect();+ eprintln!("raea: <SolariLighting> on every camera: {} (docs/nobuild.feature NB1a)", list.join(", "));+ });+ }+ raea_io_trace::event(+ "solari_settings",+ serde_json::json!({+ "view": view.to_bits(),+ "denoise": s.denoise, "guides": s.guides, "reflection_depth": s.reflection_depth, "emissive": s.emissive,+ "upscale": s.upscale, "preexposure": s.preexposure, "aa": s.aa, "jitter": s.jitter,+ "emissive_sharpness": s.emissive_sharpness, "scale": (f64::from(scale) * 1000.0).round() / 1000.0,+ "env": env.iter().map(|(n, v, _)| format!("{n}={v}")).collect::<Vec<_>>(),+ }),+ );+}++impl SolariSettings {+ /// the emission is taken out before the denoiser and put back after ("taa" or "split")+ pub(crate) fn split(&self) -> bool {+ self.emissive != "mask"+ }+ /// the emission's history is gathered over frames (emit_taa.rs)+ pub(crate) fn taa(&self) -> bool {+ self.emissive == "taa"+ }+ /// a view drawn small is denoised and brought up in one pass+ pub(crate) fn one_pass(&self) -> bool {+ self.upscale != "two"+ }+}diff --git a/engine/render/raytrace/src/upscale.rs b/engine/render/raytrace/src/upscale.rsindex ca4225f9..5434edfb 100644--- a/engine/render/raytrace/src/upscale.rs+++ b/engine/render/raytrace/src/upscale.rs@@ -63,15 +63,10 @@ pub(crate) static BROUGHT_UP: AtomicBool = AtomicBool::new(false);/// then, as the raw frame would shimmer half a pixel.pub(crate) static DENOISING: AtomicBool = AtomicBool::new(false);-fn jitter_mode() -> &'static str {- static MODE: std::sync::OnceLock<String> = std::sync::OnceLock::new();- MODE.get_or_init(|| std::env::var("RAEA_SOLARI_JITTER").unwrap_or_default())-}-/// What MetalFX's denoiser (`denoiser`) or scaler is told of the jitter, times Bevy's offset negated (as its DLSS gives-/// it): 1, 0 or -1, by RAEA_SOLARI_JITTER. With no denoiser before it, the scaler is told it.-pub(crate) fn jitter_gain(denoiser: bool, denoised: bool) -> f32 {- match (jitter_mode(), denoiser) {+/// it): 1, 0 or -1, by the view's SolariSettings.jitter (`mode`). With no denoiser before it, the scaler is told it.+pub(crate) fn jitter_gain(mode: &str, denoiser: bool, denoised: bool) -> f32 {+ match (mode, denoiser) {("0", _) => 0.0,("both", _) => 1.0,("scaler", true) => 0.0,@@ -97,28 +92,25 @@ fn halton(mut i: u32, base: u32) -> f32 {#[derive(Component)]struct Jittered;-/// A Solari camera at its full size is jittered too, so MetalFX's denoiser anti-aliases its edges as it gathers frames:-/// photo 2's frame 95 had stepped edges held still, and jittered it came 15.9 -> 15.6 off the path tracer.-/// RAEA_SOLARI_AA=0 holds it still.-fn aa() -> bool {- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();- *ON.get_or_init(|| std::env::var("RAEA_SOLARI_AA").as_deref() != Ok("0"))-}-/// How many frames the jitter takes to come round at render scale `s`: 8 / s², as DLSS asks.pub(crate) fn cycle(s: f32) -> u32 {(8.0 / (s * s)).ceil() as u32}/// Each drawn-small camera's sub-pixel offset this frame (a Halton (2, 3) cycle, longer the smaller it draws, as-/// DLSS asks: 8 / s² frames), its mip bias, and the prepasses the scaler reads (depth, motion).-fn jitter(mut cmd: Commands, frame: Res<FrameCount>, mut cams: Query<(Entity, Option<&RenderScale>, Has<SolariLighting>, Option<&mut TemporalJitter>, Has<Jittered>), With<Camera3d>>) {- for (e, rs, solari, j, mine) in &mut cams {+/// DLSS asks: 8 / s² frames), its mip bias, and the prepasses the scaler reads (depth, motion). A Solari camera at its+/// full size is jittered too unless its settings' `aa` is off, so MetalFX's denoiser anti-aliases its edges as it+/// gathers frames: photo 2's frame 95 had stepped edges held still, and jittered it came 15.9 -> 15.6 off the path+/// tracer.+#[allow(clippy::type_complexity)]+fn jitter(mut cmd: Commands, frame: Res<FrameCount>, mut cams: Query<(Entity, Option<&RenderScale>, Has<SolariLighting>, Option<&mut TemporalJitter>, Has<Jittered>, Option<&super::SolariSettings>), With<Camera3d>>) {+ for (e, rs, solari, j, mine, st) in &mut cams {let s = scale(rs, solari);- if s < 1.0 || (solari && aa() && DENOISING.load(Ordering::Relaxed)) {+ let st = super::settings::of(st);+ if s < 1.0 || (solari && st.aa && st.denoise && DENOISING.load(Ordering::Relaxed)) {let n = cycle(s);let i = frame.0 % n + 1;- let offset = if jitter_mode() == "0" { Vec2::ZERO } else { Vec2::new(halton(i, 2), halton(i, 3)) - 0.5 };+ let offset = if st.jitter == "0" { Vec2::ZERO } else { Vec2::new(halton(i, 2), halton(i, 3)) - 0.5 };match j {Some(mut j) if mine => j.offset = offset,Some(_) => {}@@ -242,7 +234,7 @@ impl View {}}-pub(crate) type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static MainPassResolutionOverride, Option<&'static TemporalJitter>, Option<&'static SolariLighting>);+pub(crate) type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static MainPassResolutionOverride, Option<&'static TemporalJitter>, Option<&'static SolariLighting>, Option<&'static super::SolariSettings>);pub(crate) fn upscale(view: ViewQuery<Viewed, With<Upscaled>>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {// the denoiser brought it up already, in the same pass (metalfx.rs)@@ -250,7 +242,7 @@ pub(crate) fn upscale(view: ViewQuery<Viewed, With<Upscaled>>, device: Res<Rendereturn;}let entity = view.entity();- let (target, pre, part, jitter, solari) = view.into_inner();+ let (target, pre, part, jitter, solari, st) = view.into_inner();let (Some(depth), Some(motion)) = (pre.depth.as_ref(), pre.motion_vectors.as_ref()) else { return };let color: &wgpu::Texture = target.main_texture();if target.main_texture_format() != bevy::render::render_resource::TextureFormat::Rgba16Float {@@ -272,7 +264,7 @@ pub(crate) fn upscale(view: ViewQuery<Viewed, With<Upscaled>>, device: Res<Rende}let v = kit.views.get_mut(&entity).unwrap();let denoised = DENOISED.swap(false, Ordering::Relaxed);- let jitter = jitter.map_or(Vec2::ZERO, |j| -j.offset * jitter_gain(false, denoised));+ let jitter = jitter.map_or(Vec2::ZERO, |j| -j.offset * jitter_gain(&super::settings::of(st).jitter, false, denoised));let mut raw = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("metalfx upscale") });let done = unsafe {raw.as_hal_mut::<Metal, _, _>(|e| match e.and_then(|e| e.raw_command_buffer()) {diff --git a/sdk/guides/craft/bevy/solari.md b/sdk/guides/craft/bevy/solari.mdindex 55dace37..4711b113 100644--- a/sdk/guides/craft/bevy/solari.md+++ b/sdk/guides/craft/bevy/solari.md@@ -5,8 +5,8 @@- Put `<SolariLighting />` (`raea/light`) inside the `<Camera3d>` it lights. raea sets up what Bevy asks for around it(HDR, no MSAA, the deferred and depth prepasses). It needs a GPU with ray queries: Apple silicon on Metal, an RTXcard on Vulkan. Elsewhere the scene draws raster-lit and raea says so. On the Mac, MetalFX's denoiser cleans the- result (`RAEA_SOLARI_DENOISE=0` shows the raw noise).-- Its three props:+ result (`denoise={false}` shows the raw noise).+- Its main props:- `bounces`: how many times light bounces. Bevy's default is 3 when it's left out; 2 is enough for most rooms andcosts less.- `restir`: reuse light samples between pixels and frames. It's off by default, as Bevy has it. Turn it on when@@ -15,6 +15,19 @@the old shot's light smears into the new one for a few frames. A cut between cameras (`<Camera3d is_active>`,the first active one draws) needs none: the engine resets Solari's and the path tracer's history on the framethe shot changes.+ - `scale`: draw the view at this fraction of its size a side and let MetalFX bring it up. A game at 0.67 traces 45%+ of the pixels.+ - `primarySamples` and `secondarySamples`: light samples at the first hit and at each bounce (Bevy's 8 and 4). After+ the denoiser, 4 and 2 look the same in most rooms and save time.+- Every other choice the engine makes for the traced light is a prop too, so an A/B is two compositions, never a+ build: `denoise`, `guides`, `reflectionDepth`, `emissive` ("taa", "split", "mask"), `upscale` ("one", "two"),+ `preexposure`, `aa`, `jitter`, `emissiveSharpness`, `firstBounce`, `confidenceCap` and `cache` (the world cache's+ `frames`, `lightSamples`, `reach`, `updates`, `cellSize`, `lodScale`). Each prop's TSDoc says what it changes. The+ defaults are the measured best, so leave them unless a test scene shows otherwise. A developer's environment+ variable of the same setting (`RAEA_SOLARI_DENOISE=0`, `RAEA_METALFX_PREEXPOSURE=4`) overrides the prop on every+ camera, for an A/B across many scenes at once.+- Keep a look's settings as a TypeScript object and spread it: `const LIVE = { primarySamples: 4, scale: 0.67 }`,+ then `<SolariLighting {...LIVE} />` or `<SolariLighting {...LIVE} preexposure={32} />`.- For a still to judge the look against, use `<Pathtracer />` in its place: exact and slow, accumulating while theview holds still. It isn't for motion.- Light the scene with what Solari sees:@@ -66,8 +79,8 @@ from a world-space cache that rays keep updating (the world cache), read whereveagainst acceleration structures built from the meshes. That's why it needs its own mesh layout (raea makes a copy permesh, once), why only the `StandardMaterial` fields it knows are traced (base colour, emissive, metallic and roughness,normal maps, alpha masks, `uv_transform`), and why it's noisy until a denoiser runs. Reflections went in with 0.18-(specular) and 0.19 (a mirror BRDF). Their motion vectors aren't there yet, so a polished floor's reflections smear-when the camera moves.+(specular) and 0.19 (a mirror BRDF). raea's patches give a mirror's and a glossy surface's pixels the motion and depth+of what they reflect, so the denoiser follows a reflection instead of smearing it.Bevy changes Solari every release. It arrived in 0.17, gained specular in 0.18 and mirrors in 0.19, and 0.20 turnedReSTIR off by default, added the atmosphere and environment lighting, and ran on Metal (with no denoiser of its own:diff --git a/sdk/render/src/bevy3d/raytracing.tsx b/sdk/render/src/bevy3d/raytracing.tsxindex 458def0e..2b3b32b4 100644--- a/sdk/render/src/bevy3d/raytracing.tsx+++ b/sdk/render/src/bevy3d/raytracing.tsx@@ -9,17 +9,101 @@ export interface SolariLightingProps {bounces?: number;/** start the lighting's history again (a cut) */reset?: boolean;+ /** with ReSTIR, the most frames a pixel's reused samples may count for: higher is steadier and slower to follow a+ * change in the light (Bevy's 8) */+ confidenceCap?: number;+ /** direct light samples at the camera's first hit, a pixel a frame (Bevy's 8). After MetalFX's denoiser 4 bought+ * the window scene nothing over 8 and saved 1.5 ms at 1080p's pixels */+ primarySamples?: number;+ /** direct light samples at each bounce (Bevy's 4) */+ secondarySamples?: number;+ /** the chance a pixel traces its first bounce this frame, its light divided by it (Russian roulette): 0.5 halves the+ * bounce's tracing, most of a dense forest's (1, every pixel every frame) */+ firstBounce?: number;+ /** Solari's world cache, the bounce light it keeps in cells across the scene */+ cache?: {+ /** frames a cell's light is gathered over: steadier and slower to follow a change (Bevy's 32) */+ frames?: number;+ /** direct light samples a cell takes a frame (32) */+ lightSamples?: number;+ /** the farthest a ray between cells is traced, metres; past it the sky counts only if the ray reaches it (1000) */+ reach?: number;+ /** about how many cells are updated a frame (40000) */+ updates?: number;+ /** a nearest cell's size, metres (0.15) */+ cellSize?: number;+ /** how fast cells grow with distance from the camera (15) */+ lodScale?: number;+ };/** draw the view at this fraction of its size a side (a third to 1) and let MetalFX's temporal scaler bring it up to* the full size, so a game traces fewer pixels: 0.67 traces 45% of them (RT9). On the Mac; elsewhere it draws at the- * full size and raea says so. 1 (or left out): the full size */+ * full size and raea says so. 1 (or left out): the full size; RAEA_SOLARI_SCALE overrides it */scale?: number;+ /** MetalFX's temporal denoiser on the lighting (RT4). false shows Solari's raw noise. Default true;+ * RAEA_SOLARI_DENOISE=0 overrides it */+ denoise?: boolean;+ /** the denoiser guided by Solari's own guides, where a mirror's pixel takes what it reflects (RT17); false guides it+ * by the G-buffer. Default true; RAEA_SOLARI_PSR=0 overrides it */+ guides?: boolean;+ /** a glossy surface's pixel as far off as what it reflects in the denoiser's depth, so a reflection doesn't trail+ * what it shows (RT34). Default true; RAEA_SOLARI_PSR_DEPTH=0 overrides it */+ reflectionDepth?: boolean;+ /** an emissive surface's own light: "taa" taken out before the denoiser and gathered over frames (RT11, RT32),+ * "split" each frame's alone, "mask" left in for the denoiser. Default "taa"; RAEA_SOLARI_EMISSIVE overrides it */+ emissive?: "taa" | "split" | "mask";+ /** a view drawn small (scale below 1): denoised and brought up in "one" pass, or denoised small and scaled in "two".+ * Default "one"; RAEA_SOLARI_UPSCALE overrides it */+ upscale?: "one" | "two";+ /** what MetalFX divides the light by before it denoises and multiplies it by after. Higher keeps more of a rare+ * bright sample (a lamp found by one path in many) and lets more fireflies through: 1 kept 0.74 of the desk's+ * light, 16 0.86, 64 0.91. Default 16; RAEA_METALFX_PREEXPOSURE overrides it */+ preexposure?: number;+ /** jitter a full-size view too, so the denoiser anti-aliases its edges as it gathers frames. Default true;+ * RAEA_SOLARI_AA=0 overrides it */+ aa?: boolean;+ /** which of MetalFX's passes is told the camera's jitter: "denoiser", "scaler", "both", "flip" (the denoiser,+ * negated), "none" (and the view isn't jittered). For A/Bs of RT9; default "denoiser"; RAEA_SOLARI_JITTER ("" the+ * denoiser, "0" none) overrides it */+ jitter?: "denoiser" | "scaler" | "both" | "flip" | "none";+ /** how fast a sample's weight falls with its distance from a pixel's centre in the emission's history, exp(-k d²) in+ * output pixels: lower is softer. Default 6; RAEA_EMIT_TAA_SHARP overrides it */+ emissiveSharpness?: number;+}++/** <SolariLighting>'s denoiser, guide, emission and jitter props as raea_render_raytrace::SolariSettings' fields (only+ * those given; the rest keep the engine's defaults). An environment variable of the same setting overrides it, for an+ * A/B across scenes (RAEA_SOLARI_DENOISE, RAEA_METALFX_PREEXPOSURE, ...; docs/nobuild.feature NB1a). */+export function solariSettings(p: SolariLightingProps): Record<string, unknown> | undefined {+ const pos = (n: string, v: number | undefined) => {+ if (v !== undefined && !(Number.isFinite(v) && v > 0)) throw new RangeError(`SolariLighting: ${n} is a number above 0, got ${v}`);+ };+ pos("preexposure", p.preexposure);+ pos("emissiveSharpness", p.emissiveSharpness);+ const one = <T extends string>(n: string, v: T | undefined, of: readonly T[]) => {+ if (v !== undefined && !of.includes(v)) throw new RangeError(`SolariLighting: ${n} is one of ${of.join(", ")}, got ${v}`);+ };+ one("emissive", p.emissive, ["taa", "split", "mask"] as const);+ one("upscale", p.upscale, ["one", "two"] as const);+ one("jitter", p.jitter, ["denoiser", "scaler", "both", "flip", "none"] as const);+ const v: Record<string, unknown> = {};+ if (p.denoise !== undefined) v.denoise = p.denoise;+ if (p.guides !== undefined) v.guides = p.guides;+ if (p.reflectionDepth !== undefined) v.reflection_depth = p.reflectionDepth;+ if (p.emissive !== undefined) v.emissive = p.emissive;+ if (p.upscale !== undefined) v.upscale = p.upscale;+ if (p.preexposure !== undefined) v.preexposure = p.preexposure;+ if (p.aa !== undefined) v.aa = p.aa;+ // the engine's names for the passes (upscale.rs jitter_gain): "" the denoiser, "0" none+ if (p.jitter !== undefined) v.jitter = p.jitter === "denoiser" ? "" : p.jitter === "none" ? "0" : p.jitter;+ if (p.emissiveSharpness !== undefined) v.emissive_sharpness = p.emissiveSharpness;+ return Object.keys(v).length ? v : undefined;}/** Ray-traced direct and indirect light for the <Camera3d> it's inside (Bevy's SolariLighting): shadows, bounce* light and reflections traced against the scene, in place of shadow maps. Needs a GPU with ray queries (Apple* silicon on Metal, RTX on Vulkan); elsewhere the scene draws raster-lit and raea says so. On the Mac MetalFX's- * temporal denoiser cleans it up (RT4; RAEA_SOLARI_DENOISE=0 shows the raw noise). A <Character> (skinned, morphed) stays raster-lit: Bevy 0.20's- * Solari can't trace it (RT5). */+ * temporal denoiser cleans it up (RT4; denoise={false} shows the raw noise). A <Character> (skinned, morphed) stays+ * raster-lit: Bevy 0.20's Solari can't trace it (RT5). */export function SolariLighting(p: SolariLightingProps = {}) {if (p.bounces !== undefined && !(Number.isInteger(p.bounces) && p.bounces >= 0)) throw new RangeError(`SolariLighting: bounces is a whole number, got ${p.bounces}`);if (p.scale !== undefined && !(p.scale >= 1 / 3 && p.scale <= 1)) throw new RangeError(`SolariLighting: scale is a third to 1 (of the view's size a side), got ${p.scale}`);@@ -27,12 +111,32 @@ export function SolariLighting(p: SolariLightingProps = {}) {if (p.restir !== undefined) value.restir = p.restir;if (p.bounces !== undefined) value.max_bounces = p.bounces;if (p.reset !== undefined) value.reset = p.reset;+ const field = (prop: string, name: string, v: number | undefined, whole = false) => {+ if (v === undefined) return;+ if (!(Number.isFinite(v) && v >= 0) || (whole && !Number.isInteger(v))) throw new RangeError(`SolariLighting: ${prop} is ${whole ? "a whole number" : "a number"} of 0 or more, got ${v}`);+ value[name] = v;+ };+ field("confidenceCap", "confidence_weight_cap", p.confidenceCap);+ field("primarySamples", "primary_di_samples", p.primarySamples, true);+ field("secondarySamples", "secondary_di_samples", p.secondarySamples, true);+ if (p.firstBounce !== undefined && !(p.firstBounce > 0 && p.firstBounce <= 1)) throw new RangeError(`SolariLighting: firstBounce is a chance above 0, up to 1, got ${p.firstBounce}`);+ field("firstBounce", "first_bounce_probability", p.firstBounce);+ const c = p.cache ?? {};+ field("cache.frames", "world_cache_max_temporal_samples", c.frames);+ field("cache.lightSamples", "world_cache_direct_light_sample_count", c.lightSamples, true);+ field("cache.reach", "world_cache_max_gi_ray_distance", c.reach);+ field("cache.updates", "world_cache_cell_updates_soft_target", c.updates, true);+ field("cache.cellSize", "world_cache_position_base_cell_size", c.cellSize);+ field("cache.lodScale", "world_cache_position_lod_scale", c.lodScale);+ const settings = solariSettings(p);const lighting = <BevyComponent type="bevy_solari::realtime::SolariLighting" value={value} />;- if (p.scale === undefined || p.scale === 1) return lighting;+ const scaled = p.scale !== undefined && p.scale !== 1;+ if (!scaled && !settings) return lighting;return (<>{lighting}- <BevyComponent type="raea_render_raytrace::RenderScale" value={{ scale: p.scale }} />+ {scaled && <BevyComponent type="raea_render_raytrace::RenderScale" value={{ scale: p.scale }} />}+ {settings && <BevyComponent type="raea_render_raytrace::SolariSettings" value={settings} />}</>);}