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.

LT12: raea's own temporal filter, the levels' dither moving under it, and the light check pre-rolled

shinyobjectz4946bf9c0028
diff --git a/docs/manual/reference/sdk/3d.md b/docs/manual/reference/sdk/3d.md
index 73e8df14..2ad463fa 100644
--- a/docs/manual/reference/sdk/3d.md
+++ b/docs/manual/reference/sdk/3d.md
@@ -1317,7 +1317,7 @@ type AnimGraphNode = | { clip: string | number; time?: number; weight?: number;
| Field | Type | What it is |
| --- | --- | --- |
-| `mode` (required) | `"msaa" \| "smaa" \| "fxaa" \| "none"` | "msaa" (4x multisampling, the default), "smaa" (morphological, high preset: the default with AmbientOcclusion, which can't multisample), "fxaa" (cheapest, softest) or "none". Each draws a frame from that frame alone, so a render equals its play (temporal anti-aliasing isn't offered: it needs the frames before) |
+| `mode` (required) | `"msaa" \| "smaa" \| "fxaa" \| "none" \| "steady"` | "msaa" (4x multisampling, the default), "smaa" (morphological, high preset: the default with AmbientOcclusion, which can't multisample), "fxaa" (cheapest, softest), "none", or "steady": raea's temporal filter, each frame drawn from a slightly different place inside its pixels and blended with the frames before it, so what one frame can only draw as a pattern of pixels (levels cross-fading by distance, far detail a pixel wide, noisy light) settles to its true share; single-sampled, with depth and motion prepasses (on Berlin's fly, faster than msaa). The others draw a frame from that frame alone, so a render equals its play; "steady" needs the frames before, so a render that starts partway through differs from its play for its first few frames |
### `AtmosphereProps`
diff --git a/docs/manual/reference/sdk/post_process.md b/docs/manual/reference/sdk/post_process.md
index 1405e1be..8da7d5f6 100644
--- a/docs/manual/reference/sdk/post_process.md
+++ b/docs/manual/reference/sdk/post_process.md
@@ -140,7 +140,7 @@ Takes [`ToneMappingProps`](3d.md#tonemappingprops)'s props.
| Field | Type | What it is |
| --- | --- | --- |
-| `mode` (required) | `"msaa" \| "smaa" \| "fxaa" \| "none"` | "msaa" (4x multisampling, the default), "smaa" (morphological, high preset: the default with AmbientOcclusion, which can't multisample), "fxaa" (cheapest, softest) or "none". Each draws a frame from that frame alone, so a render equals its play (temporal anti-aliasing isn't offered: it needs the frames before) |
+| `mode` (required) | `"msaa" \| "smaa" \| "fxaa" \| "none" \| "steady"` | "msaa" (4x multisampling, the default), "smaa" (morphological, high preset: the default with AmbientOcclusion, which can't multisample), "fxaa" (cheapest, softest), "none", or "steady": raea's temporal filter, each frame drawn from a slightly different place inside its pixels and blended with the frames before it, so what one frame can only draw as a pattern of pixels (levels cross-fading by distance, far detail a pixel wide, noisy light) settles to its true share; single-sampled, with depth and motion prepasses (on Berlin's fly, faster than msaa). The others draw a frame from that frame alone, so a render equals its play; "steady" needs the frames before, so a render that starts partway through differs from its play for its first few frames |
### `BloomProps`
diff --git a/docs/realism.feature b/docs/realism.feature
index 9958b09d..7cb2ad09 100644
--- a/docs/realism.feature
+++ b/docs/realism.feature
@@ -481,6 +481,21 @@ Feature: raea Light: raea's own real-time realism renderer, measured against rae
And quality tiers scale it for smaller GPUs, each tier's numbers in LT1's table, down to a tier for GPUs with
no ray-tracing hardware: screen traces and probes, the world cache filled by a compute traversal of the
coarse ray scene, leaf translucency and the finish (LT19) intact, so the image degrades and never drops
+ And the temporal filter is raea's own (11-18; raea-sys-post steady.rs, <AntiAliasing mode="steady">, or
+ RAEA_STEADY on every 3D camera): 16 jitter places, one for each of the levels' cross-fade dither's 16, which
+ now moves each frame under a jittered view (raea's bevy_pbr pbr_functions.wesl, its prepass alike); the past
+ fetched by the depth and motion prepasses at the nearest neighbour's motion, clipped to the 3x3 YCoCg spread
+ (1.5 sigma still, 1 at 4 px a frame), blended in linear light at 1/n down to 1/32 still and 1/8 moving. MSAA
+ goes off under it. On Berlin's 1440p fly the dither's dot bands are gone at full size and the walk's heroes
+ leave no trail; the far city's roof slopes, a pixel wide, alias more without MSAA (prefiltered far levels,
+ LT21). Live 2560x1440 work p50, median of 3, MSAA 4x against steady: walk 53.0/55.0 ms, fly 47.3/42.5 (Bevy's
+ TAA: 52.9/53.5, 53.4/42.1). Off by default; a render's first frames have no past
+ And `raea light check` draws 16 frames before each still or shot that doesn't follow the frame before, unmeasured,
+ so what keeps a past has its own, and never steadies its reference (RAEA_STEADY's jitter moved the path-traced
+ shot by part of a pixel a frame: 0.478 stops of its own on FLOOR3, read as the paths' flicker). LT1 raster,
+ without and with the filter: FLOOR3 mean 1.379/1.392 stops, bias -0.801/-0.816, worst 3.370/3.392, flicker
+ 0.101/0.111, live 12.6/14.5 ms (the prepasses cost more than MSAA saves on a small room); glade 1.758/1.750,
+ 1.542/1.532, 3.000/2.953, flicker 0.817/0.788; gambit-walk live 49.0/44.1 ms; kitchen live 53.8/55.6 ms
Scenario: LT19. The camera and the finish
Given much of a photo's look is its camera's, not its light's (Shane's notes, 11-17: a good denoiser, AgX,
diff --git a/engine/light/src/lib.rs b/engine/light/src/lib.rs
index c98f0cec..50e10e2c 100644
--- a/engine/light/src/lib.rs
+++ b/engine/light/src/lib.rs
@@ -1,7 +1,8 @@
//! `raea light check SCENES.json -o DIR` (docs/realism.feature LT1): the bar raea Light is measured by. Each scene
//! is rendered on each light path (RAEA_LIGHT, engine/render/raytrace force.rs) and against its reference, the path
//! tracer held RAEA_LIGHT_SPP draws a frame: how far each path's stills are from it in stops (mean, bias, worst tile),
-//! how much its moving shot flickers against the shot path-traced, and what a frame costs. The numbers go to
+//! how much its moving shot flickers against the shot path-traced (each path drawing the 16 frames before a still
+//! or the shot first, unmeasured, so what keeps a past has its own), and what a frame costs. The numbers go to
//! DIR/report.json and a table.
//!
//! A scene in SCENES.json: { "name", "dir" (its project, where its renders run; ~ is the home folder), "file" (in dir),
@@ -82,10 +83,14 @@ fn render(scene: &Scene, path: &str, spp: u32, at: &[i64], out: &Path) -> R<f64>
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let at: Vec<String> = at.iter().map(i64::to_string).collect();
let t = Instant::now();
- let run = std::process::Command::new(exe)
- .current_dir(&scene.dir)
- .envs(switches(path))
- .env("RAEA_LIGHT_SPP", spp.to_string())
+ let mut cmd = std::process::Command::new(exe);
+ cmd.current_dir(&scene.dir).envs(switches(path)).env("RAEA_LIGHT_SPP", spp.to_string());
+ // the truth is never steadied: RAEA_STEADY's jitter moved the path-traced shot's frames by part of a pixel each,
+ // and that read as the paths' flicker (FLOOR3's reference 0.478 stops of its own against 0.101)
+ if path == "pathtracer" {
+ cmd.env_remove("RAEA_STEADY");
+ }
+ let run = cmd
.args(["render", &scene.file, "--composition", &scene.composition, "--at", &at.join(","), "-o"])
.arg(format!("{}/", out.display()))
.output()
@@ -130,8 +135,28 @@ fn live(scene: &Scene, path: &str, size: (i64, i64), out: &Path) -> R<Value> {
}))
}
-fn frames(dir: &Path, n: usize) -> R<Vec<metric::Luma>> {
- (0..n).map(|k| metric::load(&dir.join(format!("frame-{k:05}.png")))).collect()
+/// The frames written to `dir` at these places in its render
+fn frames(dir: &Path, at: impl IntoIterator<Item = usize>) -> R<Vec<metric::Luma>> {
+ at.into_iter().map(|k| metric::load(&dir.join(format!("frame-{k:05}.png")))).collect()
+}
+
+/// frames drawn before each measured frame that doesn't follow the one before it, and not measured, so whatever
+/// keeps a past (raea's temporal filter, the GI's caches) has its own, as it does in play: from a cold start a
+/// filter's first frames average one, two, three frames
+const BEFORE: i64 = 16;
+
+/// `at` with BEFORE frames drawn before each of its frames that doesn't follow the one before, and where each of
+/// `at`'s frames lands in that render
+fn with_before(at: &[i64]) -> (Vec<i64>, Vec<usize>) {
+ let (mut all, mut place) = (Vec::new(), Vec::new());
+ for &f in at {
+ if all.last() != Some(&(f - 1)) {
+ all.extend((f - BEFORE).max(0)..f);
+ }
+ place.push(all.len());
+ all.push(f);
+ }
+ (all, place)
}
fn round(x: f32, k: f32) -> f64 {
@@ -150,7 +175,7 @@ fn reference(scene: &Scene, spp: u32, at: &[i64], dir: &Path, fresh: bool) -> R<
std::fs::write(dir.join("made.json"), made.to_string()).map_err(|e| e.to_string())?;
json!({ "spp": spp, "seconds_a_frame": round(s as f32 / at.len().max(1) as f32, 10.0) })
};
- Ok((frames(dir, at.len())?, how))
+ Ok((frames(dir, 0..at.len())?, how))
}
/// One scene: its reference stills and shot (kept as `reference` says), then each path's stills and shot against them,
@@ -181,10 +206,11 @@ fn check(scene: &Scene, paths: &[String], spp: u32, out: &Path, fresh: bool) ->
};
for path in paths {
let dir = root.join(path);
- let secs = render(scene, path, 1, &scene.stills, &dir)?;
- let mut r = json!({ "seconds_a_still": round(secs as f32 / scene.stills.len().max(1) as f32, 100.0) });
+ let (all, place) = with_before(&scene.stills);
+ let secs = render(scene, path, 1, &all, &dir)?;
+ let mut r = json!({ "seconds_a_still": round(secs as f32 / all.len().max(1) as f32, 100.0) });
if let Some(refs) = &reference {
- let got = frames(&dir, scene.stills.len())?;
+ let got = frames(&dir, place)?;
let d: Vec<metric::Distance> = got.iter().zip(refs).map(|(a, b)| metric::distance(a, b)).collect::<R<_>>()?;
let n = d.len().max(1) as f32;
r["mean_stops"] = json!(round(d.iter().map(|x| x.mean).sum::<f32>() / n, 1000.0));
@@ -194,15 +220,16 @@ fn check(scene: &Scene, paths: &[String], spp: u32, out: &Path, fresh: bool) ->
}
if let Some(at) = &shot {
let dir = root.join(format!("{path}-shot"));
- let secs = render(scene, path, 1, at, &dir)?;
- let got = frames(&dir, at.len())?;
+ let (all, place) = with_before(at);
+ let secs = render(scene, path, 1, &all, &dir)?;
+ let got = frames(&dir, place)?;
// in stops, against the shot path-traced; and the frames' own second difference, in 8-bit steps, which
// counts the shot's motion as well
if let Some(refs) = &ref_shot {
r["flicker_stops"] = json!(metric::error_flicker(&got, refs)?.map(|f| round(f, 1000.0)));
}
r["flicker_raw"] = json!(metric::flicker(&got).map(|f| round(f, 100.0)));
- r["seconds_a_shot_frame"] = json!(round(secs as f32 / at.len() as f32, 100.0));
+ r["seconds_a_shot_frame"] = json!(round(secs as f32 / all.len() as f32, 100.0));
}
r["live"] = match &scene.live {
// at the scene's size only: the live 3D draws at its composition's size whatever the stage's
@@ -260,3 +287,18 @@ pub fn light(args: &[String]) -> R<String> {
std::fs::write(out.join("report.json"), serde_json::to_string_pretty(&report).unwrap_or_default()).map_err(|e| e.to_string())?;
Ok(format!("{}{}", table(&reports), format_args!("raea light: wrote {}", out.join("report.json").display())))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_frame_that_doesnt_follow_the_one_before_gets_16_drawn_before_it() {
+ let (all, place) = with_before(&[20, 21, 22, 100]);
+ assert_eq!(all.len(), 16 + 3 + 16 + 1);
+ assert_eq!(place, vec![16, 17, 18, 35]);
+ assert_eq!(place.iter().map(|&k| all[k]).collect::<Vec<_>>(), vec![20, 21, 22, 100]);
+ // none before the composition's first frame
+ assert_eq!(with_before(&[3]).0, vec![0, 1, 2, 3]);
+ }
+}
diff --git a/engine/render/src/engine/raea_plugins.rs b/engine/render/src/engine/raea_plugins.rs
index a7b5082b..b3a0dbbb 100644
--- a/engine/render/src/engine/raea_plugins.rs
+++ b/engine/render/src/engine/raea_plugins.rs
@@ -47,6 +47,7 @@ raea_plugin! {
FroxelGlassPlugin: super::froxel_glass::install, "Glass seen through froxel fog (froxel_glass.rs).";
LookPlugin: super::look::install, "Models drawn as pixel art or the site's grain (look.rs).";
OutlinePlugin: super::outline::install, "Ink outlines (outline.rs).";
+ SteadyPlugin: raea_sys_post::steady::install, "raea's temporal filter: each frame jittered and blended with those before it (raea-sys-post steady.rs, docs/realism.feature LT12).";
ComposePlugin: super::compose::install, "Composition passes: each object's pass mask, read by Look, Outline, Bloom and Grade (compose.rs).";
Text3dPlugin: super::text3d::install, "Text in the 3D world: bevy_rich_text3d and its faces (raea-sys-text3d).";
FirePlugin: super::fire::install, "Flames drawn as volumes (fire.rs).";
diff --git a/sdk/render/src/3d/effects.tsx b/sdk/render/src/3d/effects.tsx
index 564b8e19..ddef1d66 100644
--- a/sdk/render/src/3d/effects.tsx
+++ b/sdk/render/src/3d/effects.tsx
@@ -363,16 +363,20 @@ export function AmbientOcclusion(props: AmbientOcclusionProps) {
export interface AntiAliasingProps {
/** "msaa" (4x multisampling, the default), "smaa" (morphological, high preset: the default with AmbientOcclusion,
- * which can't multisample), "fxaa" (cheapest, softest) or "none". Each draws a frame from that frame alone, so a
- * render equals its play (temporal anti-aliasing isn't offered: it needs the frames before) */
- mode: "msaa" | "smaa" | "fxaa" | "none";
+ * which can't multisample), "fxaa" (cheapest, softest), "none", or "steady": raea's temporal filter, each frame
+ * drawn from a slightly different place inside its pixels and blended with the frames before it, so what one frame
+ * can only draw as a pattern of pixels (levels cross-fading by distance, far detail a pixel wide, noisy light)
+ * settles to its true share; single-sampled, with depth and motion prepasses (on Berlin's fly, faster than msaa).
+ * The others draw a frame from that frame alone, so a render equals its play; "steady" needs the frames before, so a
+ * render that starts partway through differs from its play for its first few frames */
+ mode: "msaa" | "smaa" | "fxaa" | "none" | "steady";
}
/** How the 3D's edges are smoothed. Put it inside the Canvas3D, once; each frame's is its own.
* @bevy bevy_anti_alias::smaa::Smaa
* @bevy bevy_anti_alias::fxaa::Fxaa */
export function AntiAliasing(props: AntiAliasingProps) {
- if (!["msaa", "smaa", "fxaa", "none"].includes(props.mode)) throw new RangeError(`AntiAliasing: mode must be "msaa", "smaa", "fxaa" or "none", got ${JSON.stringify(props.mode)}`);
+ if (!["msaa", "smaa", "fxaa", "none", "steady"].includes(props.mode)) throw new RangeError(`AntiAliasing: mode must be "msaa", "smaa", "fxaa", "none" or "steady", got ${JSON.stringify(props.mode)}`);
return node3d("AntiAliasing", props as unknown as Record<string, unknown>);
}
diff --git a/systems/post/src/camera.rs b/systems/post/src/camera.rs
index feab49a3..752f8273 100644
--- a/systems/post/src/camera.rs
+++ b/systems/post/src/camera.rs
@@ -24,7 +24,8 @@ const GROUPS: [Group; 11] = [
Group { keys: |k| k == "exposure", on: on::exposure, off: |w, e| { w.entity_mut(e).insert(bevy::camera::Exposure::default()); } },
Group { keys: |k| k.starts_with("grade_"), on: on::grading, off: |w, e| { w.entity_mut(e).insert(bevy::render::view::ColorGrading::default()); } },
Group { keys: |k| k.starts_with("vignette"), on: on::vignette, off: remove::<bevy::post_process::effect_stack::Vignette> },
- Group { keys: |k| k.starts_with("ssao") || k == "aa", on: on::aa, off: remove::<(bevy::pbr::ScreenSpaceAmbientOcclusion, bevy::anti_alias::smaa::Smaa, bevy::anti_alias::fxaa::Fxaa)> },
+ // the temporal filter goes with its jitter, which would otherwise keep moving the levels' dither with no filter
+ Group { keys: |k| k.starts_with("ssao") || k == "aa", on: on::aa, off: remove::<(bevy::pbr::ScreenSpaceAmbientOcclusion, bevy::anti_alias::smaa::Smaa, bevy::anti_alias::fxaa::Fxaa, crate::steady::Steady, bevy::render::camera::TemporalJitter)> },
// depth of field: on with the frames that have one (their post set has dof_max), its aperture and focus following
// the frame in sync_camera (RR1: it went on once, with the camera, so a play opening on a shot without it had none)
Group { keys: |k| k == "dof_max" || k == "dof_mode", on: on::dof, off: remove::<bevy::post_process::dof::DepthOfField> },
diff --git a/systems/post/src/camera/on.rs b/systems/post/src/camera/on.rs
index fac75766..d06a6250 100644
--- a/systems/post/src/camera/on.rs
+++ b/systems/post/src/camera/on.rs
@@ -161,6 +161,12 @@ pub fn aa(world: &mut World, e: Entity, vals: &Vals) {
..default()
});
}
+ // raea's temporal filter (steady.rs): <AntiAliasing mode="steady">, or on every 3D camera with RAEA_STEADY (LT1's
+ // scenes measured with it). Its depth and motion prepasses are read single-sampled (PrepassRead keeps MSAA off).
+ let steady = matches!(vals.get("aa"), Some(V::S(m)) if m == "steady") || std::env::var_os("RAEA_STEADY").is_some();
+ if steady && !preview() && world.get::<Camera3d>(e).is_some() {
+ world.entity_mut(e).insert((crate::steady::Steady, raea_sys_compose::passes::PrepassRead, Msaa::Off));
+ }
match vals.get("aa") {
Some(V::S(m)) if m == "smaa" && !preview() => {
world.entity_mut(e).insert(bevy::anti_alias::smaa::Smaa { preset: bevy::anti_alias::smaa::SmaaPreset::High });
diff --git a/systems/post/src/lib.rs b/systems/post/src/lib.rs
index a062a247..1a47a364 100644
--- a/systems/post/src/lib.rs
+++ b/systems/post/src/lib.rs
@@ -16,6 +16,8 @@ pub mod motion_blur;
pub mod dof;
pub mod effect_stack;
pub mod outline;
+// raea's temporal filter (docs/realism.feature LT12)
+pub mod steady;
/// A live scene's camera made before its first 3D part (MSAA off, as a 2D scene's is) multisamples once a frame brings
/// one, as a render's camera does from its load, which sees every frame's rows (#38: kept-mount's cube mounts at frame
diff --git a/systems/post/src/steady.rs b/systems/post/src/steady.rs
new file mode 100644
index 00000000..c17fc8ba
--- /dev/null
+++ b/systems/post/src/steady.rs
@@ -0,0 +1,212 @@
+//! raea's temporal filter (docs/realism.feature LT12). Each frame is drawn from a slightly different place inside its
+//! pixels and blended with the frames before it, moved by the depth and motion prepasses, so what one frame can only
+//! draw as a pattern of whole pixels averages over frames to its true share: the levels' cross-fade dither (which moves
+//! to another of its 16 places each frame under it: raea's bevy_pbr pbr_functions.wesl), the far city's roof slopes a
+//! pixel wide, the far sun map's shimmer. A camera with `Steady` draws with MSAA off and its depth and motion prepasses
+//! (on Berlin's fly that was faster than MSAA 4x: 42 ms against 53).
+//!
+//! The past frame is fetched where the pixel's surface was (the motion of its nearest neighbour, so an edge moves with
+//! what's in front of it), kept inside the spread of the pixel's 3x3 neighbourhood this frame (in YCoCg, so a surface
+//! that moved away or came into view leaves no trail), and blended by how long the pixel has been in view and how fast
+//! it moves: in view for n frames it takes 1/n of this frame, down to 1/RAEA_STEADY_STILL (32) when still and to
+//! 1/RAEA_STEADY_MOVING (8) at RAEA_STEADY_PX (4) pixels a frame or more. Bevy's TAA takes 1/10 whenever anything moves
+//! at all, so on the fly its far roofs and the dither bands kept a pattern.
+
+use std::collections::HashMap;
+
+use bevy::{
+ core_pipeline::{
+ prepass::{DepthPrepass, MotionVectorPrepass, ViewPrepassTextures},
+ schedule::Core3d,
+ Core3dSystems, FullscreenShader,
+ },
+ diagnostic::FrameCount,
+ prelude::*,
+ render::{
+ camera::{ExtractedCamera, TemporalJitter},
+ extract_component::{ExtractComponent, ExtractComponentPlugin},
+ render_resource::{
+ binding_types::{sampler, texture_2d, texture_depth_2d, uniform_buffer_sized},
+ *,
+ },
+ renderer::{RenderContext, RenderDevice, ViewQuery},
+ texture::{CachedTexture, TextureCache},
+ view::ViewTarget,
+ Render, RenderApp, RenderStartup, RenderSystems,
+ },
+};
+
+/// A camera whose frames are steadied over time (RAEA_STEADY). Brings the jitter and the prepasses it reads.
+#[derive(Component, Clone, Copy, Default, ExtractComponent)]
+#[extract_app(bevy::render::RenderApp)]
+#[require(TemporalJitter, DepthPrepass, MotionVectorPrepass)]
+pub struct Steady;
+
+/// the history's format: this frame blended with those before (rgb, linear), and how many frames the pixel
+/// has been in view (a)
+const PAST: TextureFormat = TextureFormat::Rgba16Float;
+
+pub fn install(app: &mut App) {
+ bevy::asset::embedded_asset!(app, "steady.wesl");
+ app.add_plugins(ExtractComponentPlugin::<Steady>::default());
+ let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return };
+ render_app.add_systems(RenderStartup, init_pipeline);
+ render_app.add_systems(Render, (jitter.in_set(RenderSystems::PrepareViews), textures.in_set(RenderSystems::PrepareResources)));
+ render_app.add_systems(Core3d, draw.in_set(Core3dSystems::EarlyPostProcess));
+}
+
+/// the i-th of the Halton sequence in base b, in 0-1
+fn halton(mut i: u32, b: u32) -> f32 {
+ let (mut f, mut r) = (1.0, 0.0);
+ while i > 0 {
+ f /= b as f32;
+ r += f * (i % b) as f32;
+ i /= b;
+ }
+ r
+}
+
+/// Each frame's place inside the pixel: 16 of the Halton (2, 3) sequence, one for each of the dither's 16 places
+fn jitter(frame: Res<FrameCount>, mut q: Query<&mut TemporalJitter, With<Steady>>) {
+ let i = frame.0 % 16 + 1;
+ for mut j in &mut q {
+ j.offset = Vec2::new(halton(i, 2), halton(i, 3)) - 0.5;
+ }
+}
+
+/// a view's two histories (read last frame's, write this one's) and its parameters
+#[derive(Component)]
+struct SteadyFrame {
+ read: CachedTexture,
+ write: CachedTexture,
+ params: Buffer,
+}
+
+fn env(name: &str, default: f32) -> f32 {
+ std::env::var(name).ok().and_then(|v| v.parse().ok()).filter(|v: &f32| *v > 0.0).unwrap_or(default)
+}
+
+/// Each steadied view's histories, swapped each frame, and its parameters: the slowest and fastest rates a frame, the
+/// motion in pixels where the fastest is reached, and whether the history starts again (a view's first frame, or a
+/// new size).
+fn textures(
+ mut commands: Commands,
+ mut cache: ResMut<TextureCache>,
+ device: Res<RenderDevice>,
+ frame: Res<FrameCount>,
+ views: Query<(Entity, &ExtractedCamera), With<Steady>>,
+ mut seen: Local<HashMap<Entity, UVec2>>,
+) {
+ let (still, moving, px) = (1.0 / env("RAEA_STEADY_STILL", 32.0), 1.0 / env("RAEA_STEADY_MOVING", 8.0), env("RAEA_STEADY_PX", 4.0));
+ for (e, camera) in &views {
+ let Some(size) = camera.physical_target_size else { continue };
+ let desc = |label: &'static str| TextureDescriptor {
+ label: Some(label),
+ size: Extent3d { width: size.x, height: size.y, depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: TextureDimension::D2,
+ format: PAST,
+ usage: TextureUsages::TEXTURE_BINDING | TextureUsages::RENDER_ATTACHMENT,
+ view_formats: &[],
+ };
+ let (a, b) = (cache.get(&device, desc("steady_a")), cache.get(&device, desc("steady_b")));
+ let (read, write) = if frame.0 % 2 == 0 { (b, a) } else { (a, b) };
+ let reset = seen.insert(e, size) != Some(size);
+ let words: Vec<u8> = [still.to_bits(), moving.to_bits(), px.to_bits(), reset as u32].iter().flat_map(|w| w.to_le_bytes()).collect();
+ let params = device.create_buffer_with_data(&BufferInitDescriptor { label: Some("steady_params"), contents: &words, usage: BufferUsages::UNIFORM });
+ commands.entity(e).insert(SteadyFrame { read, write, params });
+ }
+}
+
+#[derive(Resource)]
+struct SteadyPipeline {
+ layout: BindGroupLayoutDescriptor,
+ linear: Sampler,
+ /// one pipeline a view target format: an HDR camera's (Rgba16Float) and an LDR one's
+ hdr: CachedRenderPipelineId,
+ ldr: CachedRenderPipelineId,
+}
+
+fn init_pipeline(mut commands: Commands, device: Res<RenderDevice>, assets: Res<AssetServer>, fullscreen: Res<FullscreenShader>, cache: Res<PipelineCache>) {
+ let layout = BindGroupLayoutDescriptor::new(
+ "steady_layout",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::FRAGMENT,
+ (
+ // this frame, the history, the motion prepass, the depth prepass
+ texture_2d(TextureSampleType::Float { filterable: true }),
+ texture_2d(TextureSampleType::Float { filterable: true }),
+ texture_2d(TextureSampleType::Float { filterable: true }),
+ texture_depth_2d(),
+ sampler(SamplerBindingType::Filtering),
+ uniform_buffer_sized(false, core::num::NonZero::new(16)),
+ ),
+ ),
+ );
+ let shader = assets.load("embedded://raea_sys_post/steady.wesl");
+ let pipeline = |format: TextureFormat| {
+ let target = |format| Some(ColorTargetState { format, blend: None, write_mask: ColorWrites::ALL });
+ cache.queue_render_pipeline(RenderPipelineDescriptor {
+ label: Some("steady".into()),
+ layout: vec![layout.clone()],
+ vertex: fullscreen.to_vertex_state(),
+ fragment: Some(FragmentState { shader: shader.clone(), targets: vec![target(format), target(PAST)], ..default() }),
+ ..default()
+ })
+ };
+ let (hdr, ldr) = (pipeline(super::bevy_api::HDR_FORMAT), pipeline(TextureFormat::Rgba8UnormSrgb));
+ let linear = device.create_sampler(&SamplerDescriptor { mag_filter: FilterMode::Linear, min_filter: FilterMode::Linear, ..default() });
+ commands.insert_resource(SteadyPipeline { layout, linear, hdr, ldr });
+}
+
+fn draw(
+ view: ViewQuery<(&ExtractedCamera, &ViewTarget, &ViewPrepassTextures, &SteadyFrame)>,
+ pipeline: Option<Res<SteadyPipeline>>,
+ cache: Res<PipelineCache>,
+ mut ctx: RenderContext,
+) {
+ let Some(p) = pipeline else { return };
+ let (camera, target, prepass, f) = view.into_inner();
+ let id = if target.main_texture_format() == super::bevy_api::HDR_FORMAT { p.hdr } else { p.ldr };
+ let (Some(rp), Some(motion), Some(depth)) = (cache.get_render_pipeline(id), prepass.motion_vectors_view(), prepass.depth_only_view()) else {
+ return;
+ };
+ let post = target.post_process_write();
+ let group = ctx.render_device().create_bind_group(
+ "steady_group",
+ &cache.get_bind_group_layout(&p.layout),
+ &BindGroupEntries::sequential((post.source, &f.read.default_view, motion, depth, &p.linear, f.params.as_entire_binding())),
+ );
+ let attach = |view| Some(RenderPassColorAttachment { view, depth_slice: None, resolve_target: None, ops: Operations::default() });
+ let mut pass = ctx.command_encoder().begin_render_pass(&RenderPassDescriptor {
+ label: Some("steady"),
+ color_attachments: &[attach(post.destination), attach(&f.write.default_view)],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ pass.set_pipeline(rp);
+ pass.set_bind_group(0, &group, &[]);
+ if let Some(v) = camera.viewport.as_ref() {
+ pass.set_viewport(v.physical_position.x as f32, v.physical_position.y as f32, v.physical_size.x as f32, v.physical_size.y as f32, v.depth.start, v.depth.end);
+ }
+ pass.draw(0..3, 0..1);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_jitter_takes_16_places_spread_over_the_pixel() {
+ let places: Vec<Vec2> = (1..=16).map(|i| Vec2::new(halton(i, 2), halton(i, 3)) - 0.5).collect();
+ assert!(places.iter().all(|p| p.x.abs() < 0.5 && p.y.abs() < 0.5));
+ // every quarter of the pixel gets 4 of them
+ for q in 0..4 {
+ let n = places.iter().filter(|p| (p.x >= 0.0) == (q & 1 == 1) && (p.y >= 0.0) == (q & 2 == 2)).count();
+ assert!((3..=5).contains(&n), "quarter {q}: {n}");
+ }
+ }
+}
diff --git a/systems/post/src/steady.wesl b/systems/post/src/steady.wesl
new file mode 100644
index 00000000..6614fbd8
--- /dev/null
+++ b/systems/post/src/steady.wesl
@@ -0,0 +1,114 @@
+// raea's temporal filter (steady.rs; docs/realism.feature LT12): this frame blended with the frames before it, the
+// past fetched where each pixel's surface was and kept inside the spread of its neighbourhood now.
+import bevy_core_pipeline::fullscreen_vertex_shader::FullscreenVertexOutput;
+
+@group(0) @binding(0) var now_tex: texture_2d<f32>;
+@group(0) @binding(1) var past_tex: texture_2d<f32>;
+@group(0) @binding(2) var motion_tex: texture_2d<f32>;
+@group(0) @binding(3) var depth_tex: texture_depth_2d;
+@group(0) @binding(4) var lin: sampler;
+
+struct Params {
+ /// the smallest share of this frame a still pixel takes, and a moving one's at `px` pixels a frame or more
+ still: f32,
+ moving: f32,
+ px: f32,
+ /// 1: no history yet (the view's first frame, or a new size)
+ reset: u32,
+}
+@group(0) @binding(5) var<uniform> p: Params;
+
+struct Out {
+ @location(0) colour: vec4<f32>,
+ /// this frame blended with the past (rgb, linear) and how many frames the pixel has been in view (a)
+ @location(1) past: vec4<f32>,
+}
+
+fn peak(c: vec3<f32>) -> f32 { return max(c.r, max(c.g, c.b)); }
+// HDR into 0-1 and back, for the neighbourhood's box, so one bright pixel doesn't stretch it (the blend itself is
+// linear, as MSAA's resolve is: blended squashed, a bright roof slope and its shaded one averaged a quarter too dark)
+fn squash(c: vec3<f32>) -> vec3<f32> { return c / (1.0 + peak(c)); }
+fn unsquash(c: vec3<f32>) -> vec3<f32> { return c / max(1.0 - peak(c), 1e-4); }
+fn to_ycocg(c: vec3<f32>) -> vec3<f32> {
+ return vec3(0.25 * c.r + 0.5 * c.g + 0.25 * c.b, 0.5 * c.r - 0.5 * c.b, -0.25 * c.r + 0.5 * c.g - 0.25 * c.b);
+}
+fn to_rgb(c: vec3<f32>) -> vec3<f32> { return vec3(c.x + c.y - c.z, c.x + c.z, c.x - c.y - c.z); }
+
+// the history at uv through a Catmull-Rom filter, from five bilinear fetches (its four corner weights are small and
+// left out), so it doesn't blur a little more every frame
+fn past_at(uv: vec2<f32>, size: vec2<f32>) -> vec3<f32> {
+ let pos = uv * size;
+ let c = floor(pos - 0.5) + 0.5;
+ let f = pos - c;
+ let w0 = f * (-0.5 + f * (1.0 - 0.5 * f));
+ let w1 = 1.0 + f * f * (-2.5 + 1.5 * f);
+ let w2 = f * (0.5 + f * (2.0 - 1.5 * f));
+ let w3 = f * f * (-0.5 + 0.5 * f);
+ let w12 = w1 + w2;
+ let t0 = (c - 1.0) / size;
+ let t3 = (c + 2.0) / size;
+ let t12 = (c + w2 / w12) / size;
+ var s = textureSampleLevel(past_tex, lin, vec2(t12.x, t0.y), 0.0).rgb * (w12.x * w0.y);
+ s += textureSampleLevel(past_tex, lin, vec2(t0.x, t12.y), 0.0).rgb * (w0.x * w12.y);
+ s += textureSampleLevel(past_tex, lin, t12, 0.0).rgb * (w12.x * w12.y);
+ s += textureSampleLevel(past_tex, lin, vec2(t3.x, t12.y), 0.0).rgb * (w3.x * w12.y);
+ s += textureSampleLevel(past_tex, lin, vec2(t12.x, t3.y), 0.0).rgb * (w12.x * w3.y);
+ let w = w12.x * w0.y + w0.x * w12.y + w12.x * w12.y + w3.x * w12.y + w12.x * w3.y;
+ return max(s / w, vec3(0.0));
+}
+
+@fragment
+fn fragment(in: FullscreenVertexOutput) -> Out {
+ let dims = vec2<i32>(textureDimensions(now_tex));
+ let size = vec2<f32>(dims);
+ let px = vec2<i32>(in.uv * size);
+ let here = textureLoad(now_tex, px, 0);
+ var out: Out;
+ out.colour = here;
+ out.past = vec4(here.rgb, 1.0);
+ if (p.reset != 0u) {
+ return out;
+ }
+ // the 3x3 neighbourhood now: its mean and spread, and the nearest surface among the pixel and its four diagonal
+ // neighbours (reverse z: larger is nearer), whose motion moves an edge with what's in front of it
+ var best = px;
+ var near = textureLoad(depth_tex, px, 0);
+ var m1 = vec3(0.0);
+ var m2 = vec3(0.0);
+ for (var y = -1; y <= 1; y++) {
+ for (var x = -1; x <= 1; x++) {
+ let q = clamp(px + vec2(x, y), vec2(0), dims - 1);
+ let c = to_ycocg(squash(textureLoad(now_tex, q, 0).rgb));
+ m1 += c;
+ m2 += c * c;
+ if (x != 0 && y != 0) {
+ let d = textureLoad(depth_tex, q, 0);
+ if (d > near) {
+ near = d;
+ best = q;
+ }
+ }
+ }
+ }
+ let motion = textureLoad(motion_tex, best, 0).xy;
+ let then = in.uv - motion;
+ if (any(then != saturate(then))) {
+ return out;
+ }
+ let fast = saturate(length(motion * size) / p.px);
+ let mean = m1 / 9.0;
+ // a slow pixel keeps more of its past (a looser box), a fast one less
+ let box = sqrt(max(m2 / 9.0 - mean * mean, vec3(0.0))) * mix(1.5, 1.0, fast);
+ // the past clipped toward the box's centre along one line, not per channel, so its colour isn't shifted
+ let v = to_ycocg(squash(past_at(then, size))) - mean;
+ let worst = max(max(abs(v.x) / max(box.x, 1e-5), abs(v.y) / max(box.y, 1e-5)), abs(v.z) / max(box.z, 1e-5));
+ let past = unsquash(clamp(to_rgb(mean + v / max(worst, 1.0)), vec3(0.0), vec3(0.999)));
+ // frames in view: one more than the pixel had, capped where its rate floors, and fewer the further its past was
+ // outside the box (a surface just come into view starts its average again)
+ let age = textureLoad(past_tex, clamp(vec2<i32>(then * size), vec2(0), dims - 1), 0).a;
+ let n = max(min(age + 1.0, 1.0 / mix(p.still, p.moving, fast)) / max(worst, 1.0), 1.0);
+ let blended = mix(past, here.rgb, 1.0 / n);
+ out.colour = vec4(blended, here.a);
+ out.past = vec4(blended, n);
+ return out;
+}
diff --git a/vendor/bevy_pbr/src/prepass/mod.rs b/vendor/bevy_pbr/src/prepass/mod.rs
index 0840e6dd..3aaa7772 100644
--- a/vendor/bevy_pbr/src/prepass/mod.rs
+++ b/vendor/bevy_pbr/src/prepass/mod.rs
@@ -458,6 +458,10 @@ impl PrepassPipeline {
if mesh_key.contains(MeshPipelineKey::DEPTH_PREPASS) {
shader_defs.push("DEPTH_PREPASS".into());
}
+ // raea: see check_prepass_views_need_specialization
+ if mesh_key.contains(MeshPipelineKey::TEMPORAL_JITTER) {
+ shader_defs.push("TEMPORAL_JITTER".into());
+ }
if mesh_key.contains(MeshPipelineKey::MAY_DISCARD) {
shader_defs.push("MAY_DISCARD".into());
}
@@ -922,9 +926,10 @@ pub fn check_prepass_views_need_specialization(
Option<&DepthPrepass>,
Option<&NormalPrepass>,
Option<&MotionVectorPrepass>,
+ bevy_ecs::query::Has<TemporalJitter>,
)>,
) {
- for (view, msaa, depth_prepass, normal_prepass, motion_vector_prepass) in views.iter_mut() {
+ for (view, msaa, depth_prepass, normal_prepass, motion_vector_prepass, jitter) in views.iter_mut() {
let mut view_key = MeshPipelineKey::from_msaa_samples(msaa.samples());
if depth_prepass.is_some() {
view_key |= MeshPipelineKey::DEPTH_PREPASS;
@@ -935,6 +940,11 @@ pub fn check_prepass_views_need_specialization(
if motion_vector_prepass.is_some() {
view_key |= MeshPipelineKey::MOTION_VECTOR_PREPASS;
}
+ // raea: a jittered view's prepass moves the levels' dither each frame as its main pass does
+ // (pbr_functions.wesl visibility_range_dither)
+ if jitter {
+ view_key |= MeshPipelineKey::TEMPORAL_JITTER;
+ }
if let Some(current_key) = view_key_cache.get_mut(&view.retained_view_entity) {
if *current_key != view_key {
diff --git a/vendor/bevy_pbr/src/render/pbr_functions.wesl b/vendor/bevy_pbr/src/render/pbr_functions.wesl
index 5065e109..eda2b98b 100644
--- a/vendor/bevy_pbr/src/render/pbr_functions.wesl
+++ b/vendor/bevy_pbr/src/render/pbr_functions.wesl
@@ -88,7 +88,15 @@ fn visibility_range_dither(frag_coord: vec4<f32>, dither: i32) {
}
// Otherwise, check the dither pattern.
- let coords = vec2<u32>(floor(frag_coord.xy)) % 4u;
+ var cell = vec2<u32>(floor(frag_coord.xy));
+ // raea: under a temporal filter (a jittered view) the pattern moves to another of its 16 places each frame, so the
+ // filter's history sees every threshold at every pixel and a cross-fade averages to its share, not a fixed pattern
+ // of dots (docs/realism.feature LT12). The prepass moves it the same way, so its depth keeps the same fragments.
+@if(TEMPORAL_JITTER) {
+ let k = (view_bindings::view.frame_count * 11u) % 16u;
+ cell += vec2(k % 4u, k / 4u);
+}
+ let coords = cell % 4u;
let threshold = i32((DITHER_THRESHOLD_MAP[coords.y] >> (coords.x * 8)) & 0xff);
if ((dither >= 0 && dither + threshold >= 16) || (dither < 0 && 1 + dither + threshold <= 0)) {
discard;