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
Solari drawn below the view's size and brought up by MetalFX; no unread shadow maps
shinyobjectz1c7b3afeb83b
diff --git a/engine/render/raytrace/Cargo.toml b/engine/render/raytrace/Cargo.tomlindex a2a0eea5..57950696 100644--- a/engine/render/raytrace/Cargo.toml+++ b/engine/render/raytrace/Cargo.toml@@ -16,5 +16,5 @@ wgpu = "=30.0.1"# MetalFX's temporal denoiser (wgpu 30 is on objc2-metal 0.3)[target.'cfg(target_os = "macos")'.dependencies]objc2 = "0.6"-objc2-metal = { version = "0.3.2", default-features = false, features = ["std", "MTLTexture", "MTLCommandBuffer", "MTLCommandEncoder", "MTLBlitCommandEncoder", "MTLDevice", "MTLPixelFormat", "MTLResource"] }+objc2-metal = { version = "0.3.2", default-features = false, features = ["std", "MTLTexture", "MTLCommandBuffer", "MTLCommandEncoder", "MTLBlitCommandEncoder", "MTLDevice", "MTLPixelFormat", "MTLResource", "MTLTypes"] }objc2-metal-fx = "=0.3.2"diff --git a/engine/render/raytrace/src/lib.rs b/engine/render/raytrace/src/lib.rsindex 86f2494a..b6da5869 100644--- a/engine/render/raytrace/src/lib.rs+++ b/engine/render/raytrace/src/lib.rs@@ -1,5 +1,6 @@//! raea-render's ray tracing (docs/raytracing.feature): Bevy's Solari for a scene whose camera asks for it (RT3,-//! solari.rs), and MetalFX's temporal denoiser on its lighting on the Mac (RT4, metalfx.rs). raea-render brings this+//! solari.rs), MetalFX's temporal denoiser on its lighting on the Mac (RT4, metalfx.rs), and its temporal scaler for a+//! view drawn below its size (RT9, upscale.rs). raea-render brings this//! crate in under its `raytracing` feature and adds it to an engine only when the program asks.use bevy::prelude::*;@@ -8,11 +9,29 @@ use std::collections::HashMap;mod solari;#[cfg(target_os = "macos")]mod metalfx;+#[cfg(target_os = "macos")]+mod upscale;// RAEA_LIGHT: one light path for every camera (docs/realism.feature LT1)pub mod force;+/// 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>+/// sets it. On the Mac only: elsewhere the view draws at its full size and raea says so once.+#[derive(Component, Reflect, Clone, Copy, Debug, PartialEq)]+#[reflect(Component, Default)]+pub struct RenderScale {+ pub scale: f32,+}++impl Default for RenderScale {+ fn default() -> Self {+ RenderScale { scale: 1.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>();solari::add(app);force::add(app);}@@ -23,12 +42,21 @@ pub fn wanted(prog: &impl std::fmt::Debug) -> bool {force::needs_solari() || format!("{prog:?}").contains("bevy_solari::")}-/// After app.finish(): MetalFX's denoiser after Solari's lighting, on the Mac; nothing elsewhere.+/// After app.finish(): MetalFX's denoiser after Solari's lighting and its scaler after the main pass, on the Mac;+/// elsewhere a RenderScale below 1 is said once to be ignored.pub fn add_denoiser(app: &mut App) {#[cfg(target_os = "macos")]- metalfx::add(app);+ {+ metalfx::add(app);+ upscale::add(app);+ }#[cfg(not(target_os = "macos"))]- let _ = app;+ app.add_systems(PostUpdate, |q: Query<&RenderScale>, mut said: Local<bool>| {+ if !*said && q.iter().any(|r| r.scale < 0.999) {+ *said = true;+ eprintln!("raea: <SolariLighting scale>: no scaler off the Mac; the view draws at its full size (docs/raytracing.feature RT9)");+ }+ });}/// The path tracer starts its accumulation again on the next draw (a reference frame of its own, RAEA_LIGHT_SPP,diff --git a/engine/render/raytrace/src/metalfx.rs b/engine/render/raytrace/src/metalfx.rsindex bfbf5db5..1af60244 100644--- a/engine/render/raytrace/src/metalfx.rs+++ b/engine/render/raytrace/src/metalfx.rs@@ -7,23 +7,28 @@//! denoiser on the view's colour, depth and motion and copies its output back over the colour, before the forward//! meshes and the tonemapping. The two command buffers go to wgpu's queue in that order, after Solari's.//!+//! Drawn below its size (RT9, upscale.rs), the view's main pass holds only the top-left corner of its textures: the+//! denoiser works on that corner, at the main pass's size and with its jitter, and MetalFX's temporal scaler brings it+//! up after the forward meshes.+//!//! 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.use super::*;+use bevy::camera::MainPassResolutionOverride;use bevy::core_pipeline::core_3d::main_opaque_pass_3d;use bevy::ecs::schedule::Schedules;use bevy::core_pipeline::prepass::ViewPrepassTextures;use bevy::core_pipeline::schedule::{Core3d, Core3dSystems};use bevy::render::render_resource::TextureFormat;use bevy::render::renderer::{RenderContext, RenderDevice, ViewQuery};-use bevy::render::camera::ExtractedCamera;+use bevy::render::camera::{ExtractedCamera, TemporalJitter};use bevy::render::view::{ExtractedView, ViewTarget};use bevy::solari::prelude::SolariLighting;use objc2::rc::Retained;use objc2::runtime::ProtocolObject;use objc2::Message;-use objc2_metal::{MTLBlitCommandEncoder, MTLCommandBuffer, MTLCommandEncoder, MTLPixelFormat, MTLTexture};+use objc2_metal::{MTLBlitCommandEncoder, MTLCommandBuffer, MTLCommandEncoder, MTLOrigin, MTLPixelFormat, MTLSize, MTLTexture};use objc2_metal_fx::{MTLFXTemporalDenoisedScaler, MTLFXTemporalDenoisedScalerBase, MTLFXTemporalDenoisedScalerDescriptor};use wgpu::hal::api::Metal;@@ -67,7 +72,7 @@ const DECODE_WGSL: &str = r#"@group(0) @binding(3) var normal: texture_storage_2d<rgba16float, write>;@group(0) @binding(4) var rough: texture_storage_2d<r32float, write>;@group(0) @binding(5) var color: texture_storage_2d<rgba16float, read_write>;-// x: the camera's exposure+// x: the camera's exposure; y, z: the main pass's size (the corner of the colour it drew)@group(0) @binding(6) var<uniform> params: vec4<f32>;fn rgb9e5(v: u32) -> vec3<f32> {let scale = exp2(f32(i32(extractBits(v, 27u, 5u)) - 15 - 9));@@ -105,7 +110,7 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {}@compute @workgroup_size(8, 8, 1)fn restore(@builtin(global_invocation_id) id: vec3<u32>) {- let size = textureDimensions(color);+ let size = vec2<u32>(params.yz);if (id.x >= size.x || id.y >= size.y) { return; }let p = vec2<i32>(id.xy);let c = textureLoad(color, p);@@ -193,8 +198,10 @@ impl View {}}- /// The denoiser on `cb`, then its output copied over the colour.- fn encode(&mut self, cb: &ProtocolObject<dyn MTLCommandBuffer>, color: &wgpu::Texture, depth: &wgpu::Texture, motion: &wgpu::Texture, view: &ExtractedView, reset: bool) -> Result<(), &'static str> {+ /// The denoiser on `cb`, then its output copied over the colour's corner the main pass drew. `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> {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)?);@@ -212,14 +219,16 @@ impl View {// pixelss.setMotionVectorScaleX(-(self.size.x as f32));s.setMotionVectorScaleY(-(self.size.y as f32));- s.setJitterOffsetX(0.0);- s.setJitterOffsetY(0.0);+ s.setJitterOffsetX(jitter.x);+ s.setJitterOffsetY(jitter.y);s.setDepthReversed(true);s.setShouldResetHistory(reset || self.fresh);matrices(s, view.world_from_view.to_matrix().inverse(), view.clip_from_view);s.encodeToCommandBuffer(cb);let blit = cb.blitCommandEncoder().ok_or("no blit encoder")?;- blit.copyFromTexture_toTexture(&out, &color);+ let o = MTLOrigin { x: 0, y: 0, z: 0 };+ let size = MTLSize { width: self.size.x as _, height: self.size.y as _, depth: 1 };+ blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(&out, 0, 0, o, size, &color, 0, 0, o);blit.endEncoding();}self.fresh = false;@@ -252,18 +261,21 @@ fn matrices(s: &ProtocolObject<dyn MTLFXTemporalDenoisedScaler>, world_to_view:}}-fn denoise(view: ViewQuery<(&ViewTarget, &ViewPrepassTextures, &ExtractedView, &ExtractedCamera, &SolariLighting)>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {+type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static ExtractedView, &'static ExtractedCamera, &'static SolariLighting, Option<&'static MainPassResolutionOverride>, Option<&'static TemporalJitter>);++fn denoise(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {if kit.off {return;}let entity = view.entity();- let (target, pre, ext, cam, solari) = view.into_inner();+ let (target, pre, ext, cam, solari, part, jitter) = view.into_inner();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;}let color: &wgpu::Texture = target.main_texture();- let size = UVec2::new(color.width(), color.height());+ let size = part.map_or(UVec2::new(color.width(), color.height()), |p| p.0);+ let jitter = jitter.map_or(Vec2::ZERO, |j| -j.offset * super::upscale::jitter_gain(true, true));let dev = device.wgpu_device().clone();if kit.views.get(&entity).map(|v| v.size) != Some(size) {match View::new(&dev, size) {@@ -287,7 +299,9 @@ fn denoise(view: ViewQuery<(&ViewTarget, &ViewPrepassTextures, &ExtractedView, &.clone();let color_view = color.create_view(&Default::default());let mut exposure = [0u8; 16];- exposure[..4].copy_from_slice(&cam.exposure.to_ne_bytes());+ for (i, v) in [cam.exposure, size.x as f32, size.y as f32].into_iter().enumerate() {+ exposure[4 * i..4 * i + 4].copy_from_slice(&v.to_ne_bytes());+ }let params = wgpu::util::DeviceExt::create_buffer_init(&dev, &wgpu::util::BufferInitDescriptor { label: Some("metalfx exposure"), contents: &exposure, usage: wgpu::BufferUsages::UNIFORM });let v = kit.views.get_mut(&entity).unwrap();let views = [&v.diffuse, &v.specular, &v.normal, &v.rough].map(|t| t.create_view(&Default::default()));@@ -308,7 +322,7 @@ fn denoise(view: ViewQuery<(&ViewTarget, &ViewPrepassTextures, &ExtractedView, &let 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, &depth.texture.texture, &motion.texture.texture, ext, solari.reset),+ Some(cb) => v.encode(cb, color, &depth.texture.texture, &motion.texture.texture, ext, jitter, solari.reset),None => Err("wgpu gave no Metal command buffer"),})};@@ -329,6 +343,8 @@ fn denoise(view: ViewQuery<(&ViewTarget, &ViewPrepassTextures, &ExtractedView, &pass.set_bind_group(0, &back, &[]);pass.dispatch_workgroups(size.x.div_ceil(8), size.y.div_ceil(8), 1);}+ super::upscale::DENOISED.store(done.is_ok(), std::sync::atomic::Ordering::Relaxed);+ super::upscale::DENOISING.store(done.is_ok(), std::sync::atomic::Ordering::Relaxed);if let Err(e) = done {kit.off = true;eprintln!("raea: <SolariLighting>: the MetalFX denoiser stopped ({e}); the lighting draws un-denoised");diff --git a/engine/render/raytrace/src/solari.rs b/engine/render/raytrace/src/solari.rsindex 12926c4f..d08dd9ef 100644--- a/engine/render/raytrace/src/solari.rs+++ b/engine/render/raytrace/src/solari.rs@@ -16,7 +16,7 @@ use bevy::solari::pathtracer::{Pathtracer, PathtracingPlugin};use bevy::solari::prelude::{RaytracingMesh3d, SolariLighting, SolariPlugins};pub fn add(app: &mut App) {- app.add_plugins((SolariPlugins, PathtracingPlugin)).add_systems(PostUpdate, (cameras, meshes, deferred).before(bevy::camera::CameraUpdateSystems));+ app.add_plugins((SolariPlugins, PathtracingPlugin)).add_systems(PostUpdate, (cameras, meshes, deferred, shadow_maps).before(bevy::camera::CameraUpdateSystems));if dynamic() {// a twin posed after its joints are placed and before this frame's asset events go out, so the traced scene// gets the pose with the frame that draws it; a part's visibility read once it is propagated@@ -242,6 +242,48 @@ fn meshes(}}+/// A light whose shadow maps this module turned off, to turn them back on.+#[derive(Component)]+struct MapsOff;++/// RT10: Solari and the path tracer trace their shadows and never read a light's shadow maps, yet Bevy still draws+/// them each frame (photo 2's sun's cascades: 1.5 ms of a 22 ms live frame). So while every active 3D camera traces its+/// light and nothing is drawn raster-lit by them (a skinned or morphed mesh, a <Character>: RT5), the lights draw none;+/// each one this turned off gets its maps back when that stops.+fn shadow_maps(+ mut cmd: Commands,+ cams: Query<(&Camera, Has<SolariLighting>, Has<Pathtracer>), With<Camera3d>>,+ raster: Query<(), Or<(With<bevy::mesh::skinning::SkinnedMesh>, With<bevy::mesh::morph::MeshMorphWeights>)>>,+ mut dir: Query<(Entity, &mut DirectionalLight, Has<MapsOff>)>,+ mut point: Query<(Entity, &mut PointLight, Has<MapsOff>)>,+ mut spot: Query<(Entity, &mut SpotLight, Has<MapsOff>)>,+) {+ let (mut any, mut all) = (false, true);+ for (c, solari, path) in &cams {+ if c.is_active {+ any = true;+ all &= solari || path;+ }+ }+ let off = any && all && raster.is_empty();+ macro_rules! each {+ ($q:expr) => {+ for (e, mut l, mine) in &mut $q {+ if off && l.shadow_maps_enabled {+ l.shadow_maps_enabled = false;+ cmd.entity(e).insert(MapsOff);+ } else if !off && mine {+ l.shadow_maps_enabled = true;+ cmd.entity(e).remove::<MapsOff>();+ }+ }+ };+ }+ each!(dir);+ each!(point);+ each!(spot);+}+/// Under Solari, a material that lets light through (`diffuse_transmission`: a leaf, a sheer curtain, a lampshade)/// is pinned to the deferred path. Left on Auto, Bevy draws it forward, as the G-buffer has no room for transmission,/// so it skipped Solari's lighting and drew raster-lit over the traced frame, its emissive shown raw: photo 2's lampdiff --git a/engine/render/raytrace/src/upscale.rs b/engine/render/raytrace/src/upscale.rsnew file mode 100644index 00000000..b4c22b2d--- /dev/null+++ b/engine/render/raytrace/src/upscale.rs@@ -0,0 +1,279 @@+//! RT9 (docs/raytracing.feature): a view drawn below its size and brought up to it, so a real-time frame traces fewer+//! pixels (photo 2's tracing costs 2.6 ms at 368x490, 8 ms at 736x981, 12 ms at 1104x1472; RT8). <SolariLighting+//! scale={s}> (RenderScale on the camera; RAEA_SOLARI_SCALE=s for every Solari camera) draws the main pass (the+//! G-buffer, Solari's tracing, MetalFX's denoiser, the forward meshes) at s of the view's size a side, in the top-left+//! corner of its textures: Bevy's MainPassResolutionOverride, as its DLSS uses. Then, where Bevy's DLSS upscales+//! (EarlyPostProcess, before the post-processing, which runs at the full size), MetalFX's temporal scaler takes that+//! corner's colour, depth and motion up to the whole view.+//!+//! The camera's projection is jittered by a Halton (2, 3) sequence of sub-pixel offsets, so the frames the scaler+//! gathers sample between the smaller pixels, and textures take a finer mip to match (MipBias, log2 s).+//! MetalFX's denoiser, at the main pass's size, is told the jitter and gives back a frame without it, so the scaler+//! after it is told none (told it again, the frame blurred: 0.68 of the full size's fine detail against 0.77 still).+//! RAEA_SOLARI_JITTER picks which pass is told it, to compare: denoiser (unset), scaler, both, flip (the denoiser, with+//! the offset unnegated), 0 (the projection held still).+//!+//! On the Mac, where MetalFX has a temporal scaler for the GPU. Elsewhere, or where it has none, the view draws at its+//! full size and raea says so once.++use super::*;+use bevy::camera::MainPassResolutionOverride;+use bevy::core_pipeline::prepass::{DepthPrepass, MotionVectorPrepass, ViewPrepassTextures};+use bevy::core_pipeline::schedule::{Core3d, Core3dSystems};+use bevy::diagnostic::FrameCount;+use bevy::render::camera::{MipBias, TemporalJitter};+use bevy::render::renderer::{RenderContext, RenderDevice, ViewQuery};+use bevy::render::sync_world::RenderEntity;+use bevy::render::view::ViewTarget;+use bevy::render::{Extract, ExtractSchedule, RenderApp};+use bevy::solari::prelude::SolariLighting;+use objc2::rc::Retained;+use objc2::runtime::ProtocolObject;+use objc2::Message;+use objc2_metal::{MTLBlitCommandEncoder, MTLCommandBuffer, MTLCommandEncoder, MTLPixelFormat};+use objc2_metal_fx::{MTLFXTemporalScaler, MTLFXTemporalScalerBase, MTLFXTemporalScalerDescriptor};+use std::sync::atomic::{AtomicBool, Ordering};+use wgpu::hal::api::Metal;++/// No temporal scaler on this GPU: every view draws at its full size.+static NONE: AtomicBool = AtomicBool::new(false);++/// After app.finish(): the jitter and the main pass's size in the main world, the scaler after the main pass.+pub(crate) fn add(app: &mut App) {+ app.add_systems(PostUpdate, jitter);+ let Some(r) = app.get_sub_app_mut(RenderApp) else { return };+ r.add_systems(ExtractSchedule, extract).add_systems(Core3d, upscale.in_set(Core3dSystems::EarlyPostProcess));+}++/// The fraction of the view's size a side its main pass draws at, 1/3 to 1: RAEA_SOLARI_SCALE on a Solari camera, else+/// its RenderScale; 1 where there's no scaler.+fn scale(rs: Option<&RenderScale>, solari: bool) -> f32 {+ static FORCED: std::sync::OnceLock<Option<f32>> = std::sync::OnceLock::new();+ let forced = *FORCED.get_or_init(|| std::env::var("RAEA_SOLARI_SCALE").ok().and_then(|v| v.parse::<f32>().ok()));+ let s = if solari && let Some(f) = forced { f } else { rs.map_or(1.0, |r| r.scale) };+ if NONE.load(Ordering::Relaxed) || !s.is_finite() || s >= 0.999 { 1.0 } else { s.clamp(1.0 / 3.0, 1.0) }+}++/// The denoiser ran on the view this frame (metalfx.rs sets it; the scaler, after it, reads and clears it).+pub(crate) static DENOISED: AtomicBool = AtomicBool::new(false);+/// The denoiser is running (metalfx.rs sets it as it encodes, clears it if it stops): a full-size view is jittered only+/// 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) {+ ("0", _) => 0.0,+ ("both", _) => 1.0,+ ("scaler", true) => 0.0,+ ("scaler", false) => 1.0,+ ("flip", true) => -1.0,+ ("flip", false) => if denoised { 0.0 } else { -1.0 },+ (_, true) => 1.0,+ (_, false) => if denoised { 0.0 } else { 1.0 },+ }+}++fn halton(mut i: u32, base: u32) -> f32 {+ let (mut f, mut r) = (1.0, 0.0);+ while i > 0 {+ f /= base as f32;+ r += f * (i % base) as f32;+ i /= base;+ }+ r+}++/// A camera this module jittered, so only its own jitter is taken off when the scale goes back to 1.+#[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"))+}++/// 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 {+ let s = scale(rs, solari);+ if s < 1.0 || (solari && aa() && DENOISING.load(Ordering::Relaxed)) {+ let n = (8.0 / (s * s)).ceil() as u32;+ 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 };+ match j {+ Some(mut j) if mine => j.offset = offset,+ Some(_) => {}+ None => {+ cmd.entity(e).insert((TemporalJitter { offset }, MipBias(s.log2()), Jittered)).insert_if_new((DepthPrepass, MotionVectorPrepass));+ }+ }+ } else if mine {+ cmd.entity(e).remove::<(TemporalJitter, MipBias, Jittered)>();+ }+ }+}++/// A view the scaler brings up (it has the main pass's size in MainPassResolutionOverride).+#[derive(Component)]+struct Upscaled;++/// Each drawn-small camera's main pass size onto its view; taken off when its scale goes back to 1.+fn extract(mut cmd: Commands, cams: Extract<Query<(RenderEntity, &Camera, Option<&RenderScale>, Has<SolariLighting>), With<Camera3d>>>, upscaled: Query<(), With<Upscaled>>) {+ for (re, cam, rs, solari) in &cams {+ let s = scale(rs, solari);+ match cam.physical_viewport_size() {+ Some(size) if s < 1.0 && cam.is_active => {+ let part = (size.as_vec2() * s).round().as_uvec2().max(UVec2::ONE);+ cmd.entity(re).insert((MainPassResolutionOverride(part), Upscaled));+ }+ _ if upscaled.contains(re) => {+ cmd.entity(re).remove::<(MainPassResolutionOverride, Upscaled)>();+ }+ _ => {}+ }+ }+}++/// A view's scaler and its output, made again when the view's or the main pass's size changes.+struct View {+ full: UVec2,+ part: UVec2,+ scaler: Retained<ProtocolObject<dyn MTLFXTemporalScaler>>,+ out: wgpu::Texture,+ fresh: bool,+}++#[derive(Default)]+struct Kit {+ views: HashMap<Entity, View>,+}+// the Metal objects are only touched on the render thread, in this system+unsafe impl Send for Kit {}+unsafe impl Sync for Kit {}++impl View {+ /// A scaler from any corner of a `full` texture whose side is a third of it or more (MetalFX's dynamic resolution:+ /// the content's size is set each frame), out to `full`.+ fn new(dev: &wgpu::Device, full: UVec2, part: UVec2) -> Result<View, String> {+ let hal = unsafe { dev.as_hal::<Metal>() }.ok_or("the GPU isn't on Metal")?;+ let device = hal.raw_device();+ unsafe {+ if !MTLFXTemporalScalerDescriptor::supportsDevice(device) {+ return Err("MetalFX has no temporal scaler for this GPU".into());+ }+ let d = MTLFXTemporalScalerDescriptor::new();+ d.setColorTextureFormat(MTLPixelFormat::RGBA16Float);+ d.setDepthTextureFormat(MTLPixelFormat::Depth32Float);+ d.setMotionTextureFormat(MTLPixelFormat::RG16Float);+ d.setOutputTextureFormat(MTLPixelFormat::RGBA16Float);+ d.setInputWidth(full.x as _);+ d.setInputHeight(full.y as _);+ d.setOutputWidth(full.x as _);+ d.setOutputHeight(full.y as _);+ d.setInputContentPropertiesEnabled(true);+ d.setInputContentMinScale(1.0);+ d.setInputContentMaxScale(3.0);+ // the colour is linear and unbounded (the exposure is applied, the tone mapping isn't yet)+ d.setAutoExposureEnabled(true);+ d.setRequiresSynchronousInitialization(true);+ let scaler = d.newTemporalScalerWithDevice(device).ok_or("MetalFX made no temporal scaler")?;+ drop(hal);+ use wgpu::TextureUsages as U;+ let out = dev.create_texture(&wgpu::TextureDescriptor {+ label: Some("metalfx upscaled"),+ size: wgpu::Extent3d { width: full.x, height: full.y, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Rgba16Float,+ usage: U::STORAGE_BINDING | U::TEXTURE_BINDING | U::RENDER_ATTACHMENT | U::COPY_SRC,+ view_formats: &[],+ });+ Ok(View { full, part, scaler, out, fresh: true })+ }+ }++ /// The scaler on `cb`, from the main pass's corner of the colour, depth and motion, then its output over the colour.+ fn encode(&mut self, cb: &ProtocolObject<dyn MTLCommandBuffer>, color: &wgpu::Texture, depth: &wgpu::Texture, motion: &wgpu::Texture, jitter: Vec2, reset: bool) -> Result<(), &'static str> {+ let get = |t: &wgpu::Texture| unsafe { t.as_hal::<Metal>() }.map(|t| t.raw_handle().retain()).ok_or("a texture isn't a Metal one");+ let (color, depth, motion, out) = (get(color)?, get(depth)?, get(motion)?, get(&self.out)?);+ let s = &*self.scaler;+ unsafe {+ s.setInputContentWidth(self.part.x as _);+ s.setInputContentHeight(self.part.y as _);+ s.setColorTexture(Some(&color));+ s.setDepthTexture(Some(&depth));+ s.setMotionTexture(Some(&motion));+ s.setOutputTexture(Some(&out));+ // Bevy's motion is this frame's UV minus the last's, over the main pass's viewport; MetalFX's points from+ // this pixel to where it was, in the input's pixels+ s.setMotionVectorScaleX(-(self.part.x as f32));+ s.setMotionVectorScaleY(-(self.part.y as f32));+ s.setJitterOffsetX(jitter.x);+ s.setJitterOffsetY(jitter.y);+ s.setDepthReversed(true);+ s.setReset(reset || self.fresh);+ s.encodeToCommandBuffer(cb);+ let blit = cb.blitCommandEncoder().ok_or("no blit encoder")?;+ blit.copyFromTexture_toTexture(&out, &color);+ blit.endEncoding();+ }+ self.fresh = false;+ Ok(())+ }+}++type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static MainPassResolutionOverride, Option<&'static TemporalJitter>, Option<&'static SolariLighting>);++fn upscale(view: ViewQuery<Viewed, With<Upscaled>>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {+ if NONE.load(Ordering::Relaxed) {+ return;+ }+ let entity = view.entity();+ let (target, pre, part, jitter, solari) = 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 {+ return;+ }+ let full = UVec2::new(color.width(), color.height());+ let dev = device.wgpu_device().clone();+ if kit.views.get(&entity).map(|v| (v.full, v.part)) != Some((full, part.0)) {+ match View::new(&dev, full, part.0) {+ Ok(v) => {+ kit.views.insert(entity, v);+ }+ Err(e) => {+ NONE.store(true, Ordering::Relaxed);+ eprintln!("raea: <SolariLighting scale>: no MetalFX scaler ({e}); the view draws at its full size (docs/raytracing.feature RT9)");+ return;+ }+ }+ }+ 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 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()) {+ Some(cb) => v.encode(cb, color, &depth.texture.texture, &motion.texture.texture, jitter, solari.is_some_and(|s| s.reset)),+ None => Err("wgpu gave no Metal command buffer"),+ })+ };+ ctx.add_command_buffer(raw.finish());+ if let Err(e) = done {+ NONE.store(true, Ordering::Relaxed);+ eprintln!("raea: <SolariLighting scale>: the MetalFX scaler stopped ({e}); the view draws at its full size");+ }+}diff --git a/sdk/render/src/bevy3d/raytracing.tsx b/sdk/render/src/bevy3d/raytracing.tsxindex 02da58c8..458def0e 100644--- a/sdk/render/src/bevy3d/raytracing.tsx+++ b/sdk/render/src/bevy3d/raytracing.tsx@@ -9,6 +9,10 @@ export interface SolariLightingProps {bounces?: number;/** start the lighting's history again (a cut) */reset?: boolean;+ /** 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 */+ scale?: number;}/** Ray-traced direct and indirect light for the <Camera3d> it's inside (Bevy's SolariLighting): shadows, bounce@@ -18,11 +22,19 @@ export interface SolariLightingProps {* 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}`);const value: Record<string, unknown> = {};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;- return <BevyComponent type="bevy_solari::realtime::SolariLighting" value={value} />;+ const lighting = <BevyComponent type="bevy_solari::realtime::SolariLighting" value={value} />;+ if (p.scale === undefined || p.scale === 1) return lighting;+ return (+ <>+ {lighting}+ <BevyComponent type="raea_render_raytrace::RenderScale" value={{ scale: p.scale }} />+ </>+ );}export interface PathtracerProps {