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.

Solari for 0.1.10: raea light steady tells a held frame's movement by kind (settling, boiling, jitter, flicker; engine/light/src/kinds.rs, steady-kinds.png) and raea check reports the newest hold of a composition lit by Solari; SolariLighting gains knee, late (the denoiser after the sky and forward meshes) and firefly (a sample over N times its 8x8 mean cut back); reflected ReSTIR neighbours and a pixel permute at the frame's border; the eased emitter clamp is opt-in (emissiveClamp.stillHold, thin histories only), so the default is 0.1.9's (lightbench window-still-off-def +0.17 stops, inside RT32's 0.19). MALL RAT: 22 of 24 holds STEADY; t3-1320's border needs overscan (RT40, not built), t2-3686 passes on rerun. Work of the Solari session, committed at its stable point

shinyobjectz3a1cff770b44
diff --git a/Cargo.lock b/Cargo.lock
index 0dc9e259..287a6e78 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14807,7 +14807,9 @@ name = "raea-light"
version = "0.1.0"
dependencies = [
"image",
+ "raea-core-facts",
"raea-io-home",
+ "raea-io-trace",
"raea-runtime-bundle",
"serde_json",
]
diff --git a/apps/direction/src/check.rs b/apps/direction/src/check.rs
index 0b1ab601..67acd128 100644
--- a/apps/direction/src/check.rs
+++ b/apps/direction/src/check.rs
@@ -240,6 +240,16 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh
None => hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render && n.name != "text-read")).for_each(|(r, _)| needs(&mut waits, r)),
}
}
+ // traced light held still (raea light steady): with the floor, a composition lit by Solari carries what its newest
+ // hold of each frame found, kept in the project's record; with none yet, it waits for one
+ if floor && traced(tsx) {
+ let held = light_held(tsx, id.as_deref());
+ if held.is_empty() {
+ let c = id.as_ref().map(|i| format!(" --composition {i}")).unwrap_or_default();
+ waits.push(("light-steady".into(), format!("a held frame of its traced light (raea light steady {}{c} --frame N -o DIR)", tsx.display())));
+ }
+ found.extend(held.into_iter().filter(|f| f.level != Level::Note));
+ }
// the project's own checks, in one run
let mut files: Vec<PathBuf> = Vec::new();
let mut plan = Vec::new();
@@ -269,6 +279,31 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh
Ok(Checked { file: tsx.to_path_buf(), id, found: finding::ranked(found), waits, render, shots, fps })
}
+/// Whether a composition is lit by traced light: its file, or a .tsx beside it or a folder down, names SolariLighting.
+fn traced(tsx: &Path) -> bool {
+ let names = |p: &Path| std::fs::read_to_string(p).is_ok_and(|s| s.contains("SolariLighting"));
+ if names(tsx) {
+ return true;
+ }
+ let Some(dir) = tsx.parent() else { return false };
+ let tsxs = |d: &Path| -> Vec<PathBuf> { std::fs::read_dir(d).into_iter().flatten().flatten().map(|e| e.path()).collect() };
+ tsxs(dir).into_iter().flat_map(|p| if p.is_dir() { tsxs(&p) } else { vec![p] }).filter(|p| p.extension().is_some_and(|x| x == "tsx")).any(|p| names(&p))
+}
+
+/// The findings of the newest hold of each frame of a composition (`raea light steady`), from its project's record.
+fn light_held(tsx: &Path, id: Option<&str>) -> Vec<Finding> {
+ let Some(project) = tsx.canonicalize().ok().and_then(|t| record::up(t.parent()?, ".raea/project")) else { return Vec::new() };
+ let of = record::rel(&project, tsx);
+ let mut newest: std::collections::BTreeMap<i64, Vec<Finding>> = std::collections::BTreeMap::new();
+ for e in record::read(&project).into_iter().filter(|e| e.by == "raea light steady" && e.of == of) {
+ let mine: Vec<Finding> = e.findings.into_iter().filter(|f| id.is_none_or(|i| f.about.iter().any(|a| a.name == i))).collect();
+ if let Some(frame) = mine.first().and_then(|f| f.frames).map(|f| f[0]) {
+ newest.insert(frame, mine);
+ }
+ }
+ newest.into_values().flatten().collect()
+}
+
/// Where `f` is in `files`, added at the end when it isn't yet: the one run's checks, each file once.
fn file_index(files: &mut Vec<PathBuf>, f: &Path) -> usize {
if let Some(at) = files.iter().position(|x| x == f) {
diff --git a/docs/solari-efficiency.md b/docs/solari-efficiency.md
index 191f0bc5..4ec1367a 100644
--- a/docs/solari-efficiency.md
+++ b/docs/solari-efficiency.md
@@ -95,7 +95,7 @@ The same t2 frame (1188), median scene luminance: a cold single frame at 1440 x
long-run level depends on how many pixels feed it, and the camcorder's auto-exposure, metered at 160 x 240, set the
final 14-40x too bright: Shane's overexposed daylight. The path tracer at t2's hold frame (t2-pt) says which is right.
-## What fixes the patches, measured (11-25, with raea-be)
+## What fixes the patches, measured (11-25)
The patches are **boiling**, the industry's word for denoised traced light's soft patches crawling over still surfaces
(NRD, RTXDI, GI-1.0, the ReSTIR papers, Lumen). raea now uses it (docs/skills.glossary.md, the Solari guide's "Boiling");
@@ -147,3 +147,116 @@ Built in the fork, all off unless asked: `paths` (SolariLighting::paths_per_pixe
and `cache.iterations`, the still-camera query (with `cache.steady`, RAEA_SOLARI_STEADY=1), `cache.bake`/`cache.load`
(experimental: a whole take overflows 2^20 cells), light selection by a fixed sky share (RAEA_SOLARI_SKY_SHARE, 0 =
upstream), ReSTIR's spatial radius (RAEA_SOLARI_SPATIAL_RADIUS, 30).
+
+## Telling the movement apart, and what each kind was (11-25, afternoon)
+
+`raea light steady` now tells the kinds of movement in a held frame apart (engine/light/src/kinds.rs). It
+reads each 32 px square over the last 75 held frames and splits its light four ways:
+- **settling**: the square's straight-line trend over the window. The light is still building, which a real render's
+ lead-in covers. It's reported as "unsettled" over p95 5%, not failed;
+- **boiling**: what's left once the trend is removed, where it's slow (lag-1 correlation 0.5 or more);
+- **jitter**: what repeats on a 2-16 frame cycle, the camera's sub-pixel jitter showing through;
+- **flicker**: what is fast with no cycle, such as a firefly, a sparkle in a reflection, or two faces at one depth.
+
+Each kind has its own limit: boiling rms 1.5% with its worst square under three times that, jitter and flicker worst
+5%, and drift 0.05 stops. steady-kinds.png maps them: red is jitter or flicker, green is boiling, blue is settling.
+Before, a single number mixed them, and the fixes differ.
+
+What each turned out to be on MALL RAT:
+
+| hold | before | change | after |
+|---|---|---|---|
+| t1 1699 (silhouettes against the sky) | jitter worst 73%, all 3.73 | the denoiser after the sky and forward meshes (`late`) | jitter worst 3.8%, all 0.76: STEADY |
+| t2 1188 (the court, 4 paths) | jitter worst 10% on the shop signs | `late` + emissive "taa" | jitter 0.09%, worst 2.8% |
+| t2 1188 | boiling 1.27%, worst 5-7% at the frame's right edge | ReSTIR's spatial neighbours reflected back into the frame, not clamped to its border (restir.wesl) | boiling 1.21%, worst 4.25%: STEADY (t1 425: 0.58) |
+| kitchen | 0.63 all, grain 1.38 | `late` | 0.40 all, grain 0.55 |
+
+- **The edges stepping with the jitter: the sky and forward meshes were drawn after the denoiser.** MetalFX ran
+ before Bevy's main opaque pass (metalfx.rs `denoise`). That pass then drew the Environment's background and every
+ forward mesh with the jittered camera, and nothing resolved them. Each silhouette against the sky stepped a pixel
+ a frame on the 8-frame Halton cycle. `SolariSettings.late` (TSX `late`, RAEA_SOLARI_DENOISE_LATE) runs it after
+ the main pass instead. The guides pass already marks a pixel with no G-buffer (sky, forward meshes) undenoised
+ (mask 1) but still gathered.
+- **The shop signs' edges: MALL RAT's `emissive="split"`** puts each emitter's light back after the denoiser frame by
+ frame, so emissive edges keep the jitter. The default "taa" mode gathers them over frames.
+- **A soft knee around MetalFX** (`knee`, RAEA_METALFX_KNEE; logarithmic above the white at preexposure/16) was
+ tried first, on the theory that the resolve averaged bright edges in linear light. It changed nothing at t1 1699
+ (73% either way), because the sky wasn't going through the resolve at all. It keeps the kitchen's mean within
+ 0.004 stops. It's kept for now, default 1.
+- **Not the cache's update rate or cell life.** Every cell updated every frame (`cache.updates` 2,000,000) read 1.98
+ and 1.88 against 1.89. Cells kept for 600 frames unqueried (`cache.life`, RAEA_SOLARI_CELL_LIFE) read 1.34 against
+ 1.27. A 600-frame hold settles by about frame 300-450, but over a longer window the boiling reads higher, so the
+ detector now fixes its window at 75 frames.
+- **Offline, a 64-frame average of a frozen cache's frames reads 0.50**, the kitchen's level. Of a live cache's, it
+ reads no better than as rendered. So what boils is slow: the light wanders over tens of frames, longer than
+ MetalFX's history.
+
+## Fireflies that linger, the frame's border, and dark squares (11-25, evening)
+
+A baseline of every MALL RAT take at three frames (27 holds) had the frame-wide boiling under 1.5% on all but one,
+and still failed most of them on a single worst square of 5 to 25%. Three different things were in that number.
+
+- **A firefly that lingers.** A hot square's level is flat for 40 frames, jumps 30% in one frame, and takes about 30
+ frames to fall back. One very bright sample (a bounce landing beside a small lamp) gets a large weight, temporal
+ reuse keeps it, and spatial reuse spreads it to its neighbours. Whether a hold passed depended on whether one
+ landed in its 75 frames: t7 187 read 0.88% (worst 10.1%) and, minutes later with nothing changed, 0.39% (worst
+ 2.0%). The party room (t5 1440), lit by small bulbs, has them all the time. This is the case RTXDI's boiling filter
+ is for, and ReSTIR PT Enhanced (2026) describes the cause. raea's version is `SolariLighting.firefly_cap` (TSX
+ `firefly`, RAEA_SOLARI_FIREFLY): after temporal reuse, a reservoir whose contribution is over N times the mean of
+ its 8x8 block has its weight cut to that (restir.wesl, a `var<workgroup>` array and a barrier). On t5 1440:
+
+ | firefly | boiling | worst square | frame's mean |
+ |---|---|---|---|
+ | off | 1.63% | 7.4% | 0 stops |
+ | 32 | 1.42% | 4.9% | -0.003 |
+ | 12 | 1.06% | 6.3% | -0.15 |
+ | 6 | 0.73% | 3.0% | -0.29: STEADY |
+ | 3 | 0.69% | 3.9% | -0.38 |
+
+ It costs the light those samples carried, so it is off by default and a composition asks for it. Cutting the
+ sample's confidence, not its weight (ReSTIR PT Enhanced's adaptive cap), lost nearly as much light (-0.22 at 6) and
+ held less still (0.89%).
+- **The frame's border boils more, in a band as wide as the spatial reuse radius.** By distance from the border, in
+ 8 px steps: 0.94, 0.79, 0.67, 0.62, 0.57, then 0.5 from 48 px in (t7 187). A border pixel has half a disc of
+ neighbours to reuse from. Reflecting the neighbours into the frame helped the first few pixels (above); permuting
+ the 3 px border strip that `permute_pixel` leaves unpermuted changed nothing (kept, it is harmless). What production
+ renderers do is overscan: render a margin and crop it. raea has no overscan yet.
+- **Dark squares read high as a plain ratio.** The detector divided each square's deviation by its level, so the
+ darkest corners led (12% of nearly nothing). The eye's contrast threshold is constant in bright light (Weber) and
+ rises as the square root of falling luminance in dim light (de Vries-Rose; Barten's model has both). kinds.rs now
+ divides by sqrt(level x 0.05) below a level of 0.05 (linear; about 5 cd/m2 on a 100 cd/m2 display). t5 1440 read
+ 2.03% before and 1.59% after on the same frames.
+
+What was looked up and already there: the world cache's lookups are jittered in the tangent plane (GI-1.0 and
+world-space ReSTIR name hash-cell blotches and this cure), and its blend is the adaptive one (Boissé's, in Bevy 0.18).
+
+For moving shots, ReVQ (No-Reference Rendered Video Quality Assessment, arXiv 2510.13349) is the design to follow:
+windows of 5 frames warped onto their last with motion vectors, pixels without a correspondence masked, differences
+over spans of 1 to 4 frames. A first try that chained 32 frames of motion vectors read 10% on a clean shot from the
+warp's own error.
+
+With the firefly filter at 6 on every take, 19 of 24 holds read STEADY (8 of 22 before). What was left, by cause:
+
+- **Emitters thinner than a pixel flickered: the emitter history's clamp.** MALL RAT's ceiling tubes seen edge-on are
+ 1 to 3 px tall and changed shape every frame (t6 211 and t8 204: jitter 7.7% and 7.0% in their squares). With the
+ history always taken (RAEA_EMIT_TAA_DEBUG=3) the jitter read 0.01%. emit_taa.wgsl held a still pixel's history
+ inside the range of this frame's samples about it, so a lamp switched off goes dark at once; a tube that some of the
+ jitter's positions miss altogether was cut to black on those frames. Eased (a quarter of the way to those bounds a
+ frame) both holds read STEADY (jitter 2.2% and 1.2%), but lightbench's orb switched off then left +2.52 stops on its
+ tile where it left +0.17 (RT32). Eased only where the history is thin (dark two pixels to both sides, across or
+ down) the tubes read 3.6% and 2.1% and the orb +0.30, its rim. Two stricter tests of "thin" kept the rim out and
+ lost the tubes (5.2 to 6.5%). So the engine's default is as it was (STILL_HOLD 1) and MALL RAT asks for it
+ (`constants={{ emissiveClamp: { stillHold: 0.25 } }}`); the fix for every scene is a count, kept with the history,
+ of the frames a pixel was missed. A softer gather kernel made it worse (11 to 13% at emissiveSharpness 3 and 1.5).
+- **The border** (above): t3 1320's wall at the frame's right edge is lit in 8 px blocks that change each frame, and
+ the corner squares of t5 900 and the court boil past the worst-square limit on some runs. Overscan is
+ docs/raytracing.feature RT40, designed and not built.
+- A hold near the limit passes on one run and fails on the next (t2 922 and t2 2304 failed in the baseline and read
+ STEADY minutes later): what's left there is chance, a firefly landing in the 75 frames or not.
+
+The moving detector (scratch moving3.py, ReVQ's design on raea's own motion vectors and depth) reads 0.5% a frame on
+the court's door swing where the 32-frame chain read 10%, and tells one path a pixel from four (worst square 9.3%
+against 5.8% over 4 frames). It did not tell `late` and emissive "taa" from the settings before them on that shot,
+which has no sky edge or sign in it and whose light changes as the doors open. It needs a moving shot under steady
+light to be judged on before it gates anything.
+
diff --git a/engine/light/Cargo.toml b/engine/light/Cargo.toml
index db197d68..59e62717 100644
--- a/engine/light/Cargo.toml
+++ b/engine/light/Cargo.toml
@@ -13,3 +13,7 @@ serde_json = "1"
raea-runtime-bundle = { path = "../../runtime/bundle" }
# the home folder on every OS (HOME, then USERPROFILE)
raea-io-home = { path = "../../io/home" }
+# a held frame's findings kept in its project's record, where raea check and raea findings read them
+raea-core-facts = { path = "../../core/facts" }
+# the record's UTC stamp, as raea render's
+raea-io-trace = { path = "../../io/trace" }
diff --git a/engine/light/src/kinds.rs b/engine/light/src/kinds.rs
new file mode 100644
index 00000000..05be409c
--- /dev/null
+++ b/engine/light/src/kinds.rs
@@ -0,0 +1,170 @@
+//! What moves in a held frame, told apart (steady.rs measures how much). One number hid four things that have
+//! different causes and different fixes (MALL RAT, 11-25: take 1 failed on edges, take 2 on patches):
+//!
+//! - **settling**: a square whose level climbs or falls steadily through the window. The light is still building (a
+//! world cache lit a ray a cell a frame takes hundreds of frames in a closed court): hold longer before measuring,
+//! and give a render the same lead-in.
+//! - **boiling**: a square that wanders slowly about its level (each frame close to the last: lag-1 correlation over
+//! SLOW). Traced light's patches: too few rays behind a denoiser. More paths, a cache that converges.
+//! - **jitter**: a square that repeats on a short cycle (the camera's sub-pixel jitter is 8 frames long). An edge the
+//! temporal resolve isn't holding: a silhouette against the sky or a clipped-bright doorway steps a pixel a frame.
+//! Doors, walls and beams look as if they shake.
+//! - **flicker**: fast and without a cycle. A firefly, a sparkle in a reflection, two faces fighting for one depth.
+//!
+//! Each is each LARGE square's deviation in time over its mean, with its straight-line trend taken out first, counted
+//! to the kind the square's own series shows, and reported as the rms over every lit square (the others counting as
+//! zero, so the four add in squares to the whole), with the worst square and where it is.
+
+use crate::metric::Luma;
+use serde_json::{json, Value};
+
+/// A square whose deviation is under this (a fraction of its level) isn't moving: no kind.
+const QUIET: f64 = 0.0015;
+/// Lag-1 correlation from which a square's movement is slow.
+const SLOW: f64 = 0.5;
+/// The correlation with itself a cycle later from which a square repeats.
+const REPEATS: f64 = 0.6;
+/// The longest cycle looked for, frames (the jitter's is 8; a 16-frame sequence is the longest raea uses).
+const CYCLE: usize = 16;
+
+/// Below this level (linear, a twentieth of white: about 5 cd/m2 on a 100 cd/m2 display) a change shows less than its
+/// ratio to the level says. The eye's contrast threshold is constant in bright light (Weber) and rises as the square
+/// root of falling luminance in dim light (de Vries-Rose; Barten's contrast sensitivity model has both). Measured as a
+/// plain ratio, MALL RAT's worst squares were its darkest corners (t5 1440, t8 510: 12% and 6% of nearly nothing).
+const DIM: f64 = 0.05;
+
+/// The level a square's deviation is a fraction of: its mean in bright light, and sqrt(mean x DIM) below DIM, so a
+/// dark square's movement counts by how much of it shows.
+pub fn shown_level(mean: f64, lit: f64) -> f64 {
+ let m = mean.max(lit);
+ if m >= DIM { m } else { (m * DIM).sqrt() }
+}
+
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub enum Kind {
+ Still,
+ Boiling,
+ Jitter,
+ Flicker,
+}
+
+/// One square's series read: its kind, its deviation over its level (trend out), its trend across the window over its
+/// level, and the cycle it repeats on (0: none).
+pub fn read(series: &[f64], lit: f64) -> (Kind, f64, f64, usize) {
+ let n = series.len();
+ let mean = series.iter().sum::<f64>() / n as f64;
+ let mid = (n as f64 - 1.0) / 2.0;
+ let slope = series.iter().enumerate().map(|(t, v)| (t as f64 - mid) * v).sum::<f64>() / (0..n).map(|t| (t as f64 - mid).powi(2)).sum::<f64>().max(1e-12);
+ let r: Vec<f64> = series.iter().enumerate().map(|(t, v)| v - mean - slope * (t as f64 - mid)).collect();
+ let var = r.iter().map(|v| v * v).sum::<f64>() / n as f64;
+ let level = shown_level(mean, lit);
+ let (dev, trend) = (var.sqrt() / level, slope.abs() * (n as f64 - 1.0) / level);
+ if dev < QUIET {
+ return (Kind::Still, dev, trend, 0);
+ }
+ // the series against itself p frames later, as a correlation
+ let corr = |p: usize| r[p..].iter().zip(&r).map(|(a, b)| a * b).sum::<f64>() / (n - p) as f64 / var.max(1e-18);
+ let slow = corr(1) >= SLOW;
+ let (cycle, best) = (2..=CYCLE.min(n / 3)).map(|p| (p, corr(p))).fold((0, 0.0), |a, b| if b.1 > a.1 { b } else { a });
+ if !slow && best >= REPEATS {
+ (Kind::Jitter, dev, trend, cycle)
+ } else if slow {
+ (Kind::Boiling, dev, trend, 0)
+ } else {
+ (Kind::Flicker, dev, trend, 0)
+ }
+}
+
+/// The kinds of a window of held frames: the report's fields, and a picture at the frame's size (red: jitter and
+/// flicker, green: boiling, blue: settling; each white at `shown` percent).
+pub fn kinds(frames: &[Luma], k: usize, lit: f64, shown: f64) -> (Value, image::RgbImage) {
+ let blocks: Vec<Luma> = frames.iter().map(|f| f.blocks(k)).collect();
+ let (w, h) = (blocks[0].w, blocks[0].h);
+ let pct = |v: f64| (v * 1e4).round() / 100.0;
+ let mut sums = [0.0f64; 4];
+ let mut counts = [0usize; 4];
+ let mut worst = [(0.0f64, 0usize); 4];
+ let mut cycles = vec![0usize; CYCLE + 1];
+ let (mut trends, mut lit_n) = (Vec::new(), 0usize);
+ let mut px = vec![[0u8; 3]; w * h];
+ let level = |v: f64| (v * 100.0 / shown * 255.0).min(255.0) as u8;
+ for i in 0..w * h {
+ let series: Vec<f64> = blocks.iter().map(|b| b.y[i] as f64).collect();
+ if series.iter().sum::<f64>() / series.len() as f64 <= lit {
+ continue;
+ }
+ lit_n += 1;
+ let (kind, dev, trend, cycle) = read(&series, lit);
+ trends.push(trend);
+ let j = kind as usize;
+ sums[j] += dev * dev;
+ counts[j] += 1;
+ if dev > worst[j].0 {
+ worst[j] = (dev, i);
+ }
+ cycles[cycle] += usize::from(kind == Kind::Jitter);
+ px[i] = match kind {
+ Kind::Still => [0, 0, level(trend)],
+ Kind::Boiling => [0, level(dev), level(trend)],
+ Kind::Jitter | Kind::Flicker => [level(dev), 0, level(trend)],
+ };
+ }
+ trends.sort_by(|a, b| a.total_cmp(b));
+ let at = |q: f64| trends.get(((trends.len() as f64 - 1.0) * q).round() as usize).copied().unwrap_or(0.0);
+ let one = |j: usize| json!({ "rms": pct((sums[j] / lit_n.max(1) as f64).sqrt()), "squares": counts[j], "worst": pct(worst[j].0), "worst_at": [worst[j].1 % w * k, worst[j].1 / w * k] });
+ let cycle = cycles.iter().enumerate().max_by_key(|c| *c.1).filter(|c| *c.1 > 0).map_or(0, |c| c.0);
+ let report = json!({
+ "boiling": one(Kind::Boiling as usize), "jitter": one(Kind::Jitter as usize), "flicker": one(Kind::Flicker as usize),
+ "cycle": cycle, "settling": { "median": pct(at(0.5)), "p95": pct(at(0.95)) },
+ });
+ let picture = image::RgbImage::from_fn((w * k) as u32, (h * k) as u32, |x, y| image::Rgb(px[y as usize / k * w + x as usize / k]));
+ (report, picture)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn rnd(seed: &mut u32) -> f64 {
+ *seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
+ (*seed >> 8) as f64 / (1u32 << 24) as f64 * 2.0 - 1.0
+ }
+
+ #[test]
+ fn each_kind_of_movement_is_told_from_the_others() {
+ let mut s = 3u32;
+ // a level that climbs 10% and nothing else: still, with its trend
+ let climb: Vec<f64> = (0..75).map(|t| 0.3 * (1.0 + 0.1 * t as f64 / 74.0)).collect();
+ let (kind, dev, trend, _) = read(&climb, 0.004);
+ assert_eq!(kind, Kind::Still);
+ assert!(dev < 1e-6 && (trend - 0.0952).abs() < 0.01, "{dev} {trend}");
+ // a slow wander: each frame a small step from the last
+ let mut v = 0.0;
+ let wander: Vec<f64> = (0..75).map(|_| { v = 0.92 * v + 0.01 * rnd(&mut s); 0.3 * (1.0 + v) }).collect();
+ assert_eq!(read(&wander, 0.004).0, Kind::Boiling);
+ // the jitter's cycle: eight levels, again and again, with a little grain on top
+ let phase = [7.5, 1.7, 2.6, 10.4, 1.7, 5.6, 11.3, 1.7];
+ let cycle: Vec<f64> = (0..75).map(|t| 0.02 * phase[t % 8] * (1.0 + 0.02 * rnd(&mut s))).collect();
+ let (kind, dev, _, p) = read(&cycle, 0.004);
+ assert_eq!((kind, p), (Kind::Jitter, 8));
+ assert!(dev > 0.5, "{dev}");
+ // new every frame: flicker
+ let fast: Vec<f64> = (0..75).map(|_| 0.3 * (1.0 + 0.05 * rnd(&mut s))).collect();
+ assert_eq!(read(&fast, 0.004).0, Kind::Flicker);
+ // and a climb under a wander is still boiling, its trend kept apart
+ let both: Vec<f64> = wander.iter().enumerate().map(|(t, v)| v + 0.03 * t as f64 / 74.0).collect();
+ let (kind, _, trend, _) = read(&both, 0.004);
+ assert_eq!(kind, Kind::Boiling);
+ assert!(trend > 0.05, "{trend}");
+ }
+
+ #[test]
+ fn a_dark_squares_movement_counts_for_less_than_its_ratio() {
+ let mut s = 5u32;
+ let series = |level: f64, s: &mut u32| -> Vec<f64> { (0..75).map(|_| level * (1.0 + 0.05 * rnd(s))).collect() };
+ let (lit, dark) = (read(&series(0.3, &mut s), 0.004).1, read(&series(0.005, &mut s), 0.004).1);
+ // the same 5% ratio: counted whole at a lit level, and by sqrt(0.005 / 0.05) at a dark one
+ assert!((dark / lit - (0.005f64 / 0.05).sqrt()).abs() < 0.05, "{dark} {lit}");
+ assert_eq!(shown_level(0.05, 0.004), 0.05);
+ }
+}
diff --git a/engine/light/src/lib.rs b/engine/light/src/lib.rs
index 2f12507a..a5b0bb85 100644
--- a/engine/light/src/lib.rs
+++ b/engine/light/src/lib.rs
@@ -13,6 +13,7 @@
//! live stage, 1920x1080 by default) }.
pub mod metric;
+mod kinds;
pub mod steady;
use raea_runtime_bundle::{flag, R};
diff --git a/engine/light/src/steady.rs b/engine/light/src/steady.rs
index 49e2471d..63ff92df 100644
--- a/engine/light/src/steady.rs
+++ b/engine/light/src/steady.rs
@@ -35,6 +35,15 @@ const MAX: f64 = 1.5;
const MAX_ENERGY: f64 = 0.25;
/// How far the held frame's level may move between the first and the last quarter of the measured frames, in stops.
const MAX_DRIFT: f64 = 0.05;
+/// The frames measured: the last WINDOW of a hold (or its second half, if that's shorter). Fixed, because a slow
+/// wander reads larger over a longer window, so two holds of different lengths wouldn't compare.
+const WINDOW: usize = 75;
+/// What the worst square that moves with the jitter, or flickers, may show, percent: an edge stepping a pixel a frame
+/// reads 20 to 70; a resolved one under 2.
+const MAX_FAST: f64 = 5.0;
+/// The trend across the window a hold's squares may still have (the 95th percentile), percent: over it the light was
+/// still building when it was measured, and what reads as boiling is partly that.
+const MAX_SETTLING: f64 = 5.0;
/// Each square's mean and deviation in time over `frames`, side `k`: (w, h, [(mean, deviation / mean)]).
fn squares(frames: &[Luma], k: usize) -> (usize, usize, Vec<(f64, f64)>) {
@@ -57,7 +66,7 @@ fn rms(v: impl Iterator<Item = f64>) -> f64 {
}
/// The measure of held frames (the module's doc), and steady.png's picture: the large squares' deviation.
-pub fn measure(frames: &[Luma]) -> R<(Value, image::GrayImage)> {
+pub fn measure(frames: &[Luma]) -> R<(Value, image::GrayImage, image::RgbImage)> {
if frames.len() < 8 {
return Err(format!("{} held frames: 8 at least say whether the light holds still", frames.len()));
}
@@ -85,12 +94,14 @@ pub fn measure(frames: &[Luma]) -> R<(Value, image::GrayImage)> {
let level = |f: &[Luma]| f.iter().map(|f| f.y.iter().map(|&v| v as f64).sum::<f64>() / f.y.len().max(1) as f64).sum::<f64>() / f.len() as f64;
let q = (frames.len() / 4).max(1);
let drift = (level(&frames[frames.len() - q..]).max(1e-6) / level(&frames[..q]).max(1e-6)).log2();
+ let (kinds, kinds_map) = crate::kinds::kinds(frames, LARGE, LIT, MAX_SHOWN);
let report = json!({
+ "kinds": kinds,
"drift": (drift * 1e3).round() / 1e3,
"frames": frames.len(), "blotch": pct(blotch), "grain": pct(grain), "spread": ((blotch / grain.max(1e-9)) * 100.0).round() / 100.0,
"worst": pct(worst.0), "worst_at": [worst.1, worst.2], "lit": ((large.iter().filter(lit).count() as f64 / large.len().max(1) as f64) * 100.0).round() / 100.0,
});
- Ok((report, map))
+ Ok((report, map, kinds_map))
}
/// The PNG frames of a folder, in order.
@@ -141,12 +152,26 @@ pub fn report(dir: &Path, max: Option<f64>) -> R<Value> {
let max = max.unwrap_or(MAX);
// the second half: the first is the light building from nothing, which a render's lead-in covers
let files = held(dir)?;
- let frames: Vec<Luma> = files[files.len() / 2..].iter().map(|p| metric::load(p)).collect::<R<_>>()?;
- let (mut report, map) = measure(&frames)?;
+ let frames: Vec<Luma> = files[files.len() - WINDOW.min(files.len() - files.len() / 2)..].iter().map(|p| metric::load(p)).collect::<R<_>>()?;
+ let (mut report, map, kinds_map) = measure(&frames)?;
let png = dir.join("steady.png");
map.save(&png).map_err(|e| format!("{}: {e}", png.display()))?;
+ let kinds_png = dir.join("steady-kinds.png");
+ kinds_map.save(&kinds_png).map_err(|e| format!("{}: {e}", kinds_png.display()))?;
let get = |k: &str| report[k].as_f64().unwrap_or(0.0);
- let ok = get("blotch") <= max && get("worst") <= max * 3.0 && get("drift").abs() <= MAX_DRIFT;
+ let kind = |k: &str, f: &str| report["kinds"][k][f].as_f64().unwrap_or(0.0);
+ // each kind against its own limit, and what failed named: the fixes differ
+ let mut failed: Vec<&str> = Vec::new();
+ if kind("boiling", "rms") > max || kind("boiling", "worst") > max * 3.0 { failed.push("boiling"); }
+ if kind("jitter", "worst") > MAX_FAST { failed.push("jitter"); }
+ if kind("flicker", "worst") > MAX_FAST { failed.push("flicker"); }
+ if get("drift").abs() > MAX_DRIFT { failed.push("drift"); }
+ let ok = failed.is_empty();
+ let unsettled = kind("settling", "p95") > MAX_SETTLING;
+ let failed: Vec<String> = failed.into_iter().map(String::from).collect();
+ report["failed"] = json!(failed);
+ report["unsettled"] = json!(unsettled);
+ report["kinds_picture"] = json!(kinds_png);
report["max"] = json!(max);
report["max_drift"] = json!(MAX_DRIFT);
report["steady"] = json!(ok);
@@ -157,15 +182,75 @@ pub fn report(dir: &Path, max: Option<f64>) -> R<Value> {
/// A report as one line.
pub fn line(r: &Value) -> String {
+ let k = &r["kinds"];
+ let one = |name: &str| format!("{name} {}% (worst {}% at {},{})", k[name]["rms"], k[name]["worst"], k[name]["worst_at"][0], k[name]["worst_at"][1]);
format!(
- "drift {} stops (max {}), blotch {}% (max {}), worst {}% at {},{}, grain {}%, spread {} over {} held frames; {}",
- r["drift"], r["max_drift"], r["blotch"], r["max"], r["worst"], r["worst_at"][0], r["worst_at"][1], r["grain"], r["spread"], r["frames"], r["picture"].as_str().unwrap_or("")
+ "{}{}, {}{}, {}, settling {}% (p95 {}%){}, drift {} stops (max {}); all movement {}% (blotch), grain {}%, spread {} over {} held frames; {}",
+ one("boiling"), format_args!(" (max {})", r["max"]), one("jitter"), if k["cycle"].as_u64().unwrap_or(0) > 0 { format!(" on a {}-frame cycle", k["cycle"]) } else { String::new() }, one("flicker"),
+ k["settling"]["median"], k["settling"]["p95"], if r["unsettled"] == json!(true) { " STILL SETTLING: hold longer (--frames) before reading the rest" } else { "" },
+ r["drift"], r["max_drift"], r["blotch"], r["grain"], r["spread"], r["frames"], r["kinds_picture"].as_str().unwrap_or("")
)
}
+/// What a held frame that moves is told, by what moved.
+pub fn why(r: &Value) -> String {
+ let failed: Vec<&str> = r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
+ let mut says: Vec<String> = Vec::new();
+ if failed.contains(&"boiling") || failed.contains(&"drift") { says.push(WHY.to_string()); }
+ if failed.contains(&"jitter") { says.push("Jitter: squares that repeat on a short cycle are edges stepping with the camera's sub-pixel jitter, which the temporal resolve should have held: a silhouette against the sky or a clipped-bright opening. Hold it with RAEA_SOLARI_AA=0 to confirm (it goes), then keep the bright side under the resolve's range (exposure, the sky's level) or report it".to_string()); }
+ if failed.contains(&"flicker") { says.push("Flicker: fast and without a cycle is a firefly, a sparkle in a reflection or two faces at one depth: look at the worst square in steady-kinds.png (red), and run raea scene lint for faces in one plane".to_string()); }
+ says.join(" ")
+}
+
/// What a light that boils is told (boiling: the trade's word for low-frequency patches that crawl on a held frame).
pub const WHY: &str = "Boiling: patches this size are light built over frames that hasn't settled. On Solari, paths (SolariLighting paths={4}) first, then the world cache, ReSTIR's reuse or the denoiser. Hold the frame with each switched off in turn (cache.steady or a baked cache, RAEA_SOLARI_DENOISE=0, RAEA_SOLARI_PSR=0) to see which; DIR/render.log holds what each render said";
+/// The check a held frame's findings carry in the project's record, which `raea check` reads for a traced composition.
+pub const CHECK: &str = "light-steady";
+
+/// A held frame's report as findings, one a kind that failed: about the composition, on the frame held.
+pub fn findings(r: &Value, composition: Option<&str>, frame: i64) -> Vec<raea_core_facts::Finding> {
+ use raea_core_facts::{Finding, Level};
+ let k = &r["kinds"];
+ let num = |v: &Value| v.as_f64().unwrap_or(0.0);
+ let at = |name: &str| format!("{},{}", k[name]["worst_at"][0], k[name]["worst_at"][1]);
+ let mut out = Vec::new();
+ let mut push = |kind: &str, level: Level, says: String, value: f64, limit: f64, fix: &str| {
+ let mut f = Finding::new(CHECK, level, says, "raea light steady").frames(frame, frame + 1).measure(kind, value, "%", Some(limit)).fix(fix);
+ if let Some(c) = composition {
+ f = f.about(c, None);
+ }
+ out.push(f);
+ };
+ let failed: Vec<&str> = r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
+ let max = num(&r["max"]);
+ if failed.contains(&"boiling") {
+ push("boiling", Level::Error, format!("the light boils on frame {frame} held: {}% (worst square {}% at {}; max {max}, worst {})", k["boiling"]["rms"], k["boiling"]["worst"], at("boiling"), max * 3.0), num(&k["boiling"]["worst"]), max * 3.0, WHY);
+ }
+ if failed.contains(&"jitter") {
+ push("jitter", Level::Error, format!("edges step with the camera's jitter on frame {frame} held: worst square {}% at {} on a {}-frame cycle (max {MAX_FAST})", k["jitter"]["worst"], at("jitter"), k["cycle"]), num(&k["jitter"]["worst"]), MAX_FAST, "an edge against the sky, a forward mesh or an emitter left out of the denoiser's history: SolariLighting late and emissive=\"taa\" (the Solari guide)");
+ }
+ if failed.contains(&"flicker") {
+ push("flicker", Level::Error, format!("a square flickers on frame {frame} held: {}% at {} (max {MAX_FAST})", k["flicker"]["worst"], at("flicker")), num(&k["flicker"]["worst"]), MAX_FAST, "a firefly, a sparkle in a reflection or two faces in one plane: look at the square in steady-kinds.png, and run raea scene lint for faces in one plane");
+ }
+ if failed.contains(&"drift") {
+ push("drift", Level::Error, format!("the held frame's light drifts {} stops (max {MAX_DRIFT})", r["drift"]), num(&r["drift"]).abs(), MAX_DRIFT, WHY);
+ }
+ if failed.is_empty() {
+ push("steady", Level::Note, format!("the light holds still on frame {frame} held: {}", line(r)), num(&r["blotch"]), max, "");
+ }
+ if r["unsettled"] == json!(true) {
+ push("settling", Level::Note, format!("the light was still building on frame {frame} held (settling p95 {}%): hold longer, or give the shot a lead-in", k["settling"]["p95"]), num(&k["settling"]["p95"]), MAX_SETTLING, "a still lead-in before the shot, as long as the hold took to settle");
+ }
+ out
+}
+
+/// A held frame's findings kept in `file`'s project's record (nothing outside a project).
+fn keep(file: &str, out: &Path, r: &Value, composition: Option<&str>, frame: i64) {
+ let stamp = raea_io_trace::utc(std::time::SystemTime::now()).1;
+ raea_core_facts::record::keep("raea light steady", Path::new(file), Some(out), &findings(r, composition, frame), Vec::new(), &stamp);
+}
+
pub fn steady(args: &[String]) -> R<String> {
let first = args.first().ok_or(format!("usage: {USAGE}"))?;
let max = flag(args, "--max").map(|m| m.parse::<f64>().map_err(|_| format!("--max takes a percent, not {m}"))).transpose()?;
@@ -179,6 +264,10 @@ pub fn steady(args: &[String]) -> R<String> {
out
};
let mut r = report(&dir, max)?;
+ let held_frame = flag(args, "--frame").and_then(|f| f.parse::<i64>().ok());
+ if let (false, Some(f)) = (Path::new(first).is_dir(), held_frame) {
+ keep(first, dir.parent().unwrap_or(&dir), &r, flag(args, "--composition").as_deref(), f);
+ }
// --run M: the frame cold against the same frame at the end of M frames played up to it. A cache that gains or
// loses energy over minutes (MALL RAT's court, 11-24: 7 times brighter inside the long render) shows here and not
// in a hold
@@ -201,9 +290,9 @@ pub fn steady(args: &[String]) -> R<String> {
}
std::fs::write(dir.join("steady.json"), serde_json::to_string_pretty(&r).unwrap_or_default()).map_err(|e| e.to_string())?;
let said = format!("energy {} stops after {m} frames against the frame cold (max {MAX_ENERGY}), {}", r["energy"], line(&r));
- return if r["steady"] == json!(true) { Ok(format!("STEADY {said}")) } else { Err(format!("the light boils: {said}. {WHY}")) };
+ return if r["steady"] == json!(true) { Ok(format!("STEADY {said}")) } else { Err(format!("the held frame moves ({}): {said}. {}", r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default(), why(&r))) };
}
- if r["steady"] == json!(true) { Ok(format!("STEADY {}", line(&r))) } else { Err(format!("the light boils: {}. {WHY}", line(&r))) }
+ if r["steady"] == json!(true) { Ok(format!("STEADY {}", line(&r))) } else { Err(format!("the held frame moves ({}): {}. {}", r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default(), line(&r), why(&r))) }
}
#[cfg(test)]
@@ -231,6 +320,7 @@ mod tests {
#[test]
fn grain_is_steady_and_blotches_are_not() {
let still = measure(&frames(0.0, 0.0)).unwrap().0;
+ assert_eq!(still["kinds"]["boiling"]["rms"], 0.0);
assert_eq!(still["blotch"], 0.0);
assert_eq!(still["drift"], 0.0);
// a light that doubles over the held frames: about 0.8 of a stop between the first and the last quarter
diff --git a/engine/render/raytrace/src/emit_taa.wgsl b/engine/render/raytrace/src/emit_taa.wgsl
index 5a5156d9..0f5d95fc 100644
--- a/engine/render/raytrace/src/emit_taa.wgsl
+++ b/engine/render/raytrace/src/emit_taa.wgsl
@@ -18,6 +18,16 @@ const HISTORY_CAP: f32 = 16.0;
// a still pixel's history held within what's about it now, its darkest and brightest times these
const STILL_LOW: f32 = 0.95;
const STILL_HIGH: f32 = 1.05;
+// how far a still pixel's history goes toward those bounds a frame where it's thin (THIN). At 1, the default, it's held
+// to them at once, and an emitter under a pixel tall, which some of the jitter's positions miss altogether, is cut to
+// black on those frames and built again on the others: MALL RAT's ceiling tubes seen edge-on changed shape every frame
+// (raea light steady: jitter 7% and 8% in their squares, 0.01% with the history always taken). At a quarter
+// (<SolariLighting constants={{ emissiveClamp: { stillHold: 0.25 } }} />) they read 2.1% and 3.6%, and a 30000-nit
+// orb switched off leaves its rim behind: +0.30 stops on its tile against +0.17, +0.26 eight frames on (lightbench
+// window-still-off-q against -one). So it's a scene's choice until a pixel can count the frames it was missed
+const STILL_HOLD: f32 = 1.0;
+// a history counts as thin where the brighter of its two sides, two pixels off, is under this much of it
+const THIN: f32 = 0.25;
// a moving pixel's history held under this many times the brightest about it, plus this
const MOVING_GAIN: f32 = 4.0;
const MOVING_FLOOR: f32 = 0.02;
@@ -190,7 +200,23 @@ fn restore_taa(@builtin(global_invocation_id) id: vec3<u32>) {
// them (a lamp switched off goes dark at once, rim and all, not over a second)
let reach = select(1.5, 1.05, still);
if (hd.b * reach >= zlo && hd.a <= zhi * reach && params[0].w != 3.0) {
- hrgb = clamped;
+ // eased only where the history is a thin line or a point: an emitter under a pixel wide is all the jitter can miss outright. A lamp's or an orb's
+ // face and rim have light to one side, and go dark at once (RT32: eased everywhere, a 30000-nit orb
+ // switched off left +2.5 stops on its tile for 8 frames and +0.8 at 16; eased on thin histories, +0.30
+ // against +0.17 clamped at once, the orb's rim where it's dark to both sides)
+ var hold = 1.0;
+ if (still) {
+ let px = 2.0 / out_size;
+ let lw = vec3<f32>(0.2126, 0.7152, 0.0722);
+ let l0 = dot(hrgb, lw) * THIN;
+ let lx = max(dot(textureSampleLevel(hist_in, hist_sampler, was + vec2<f32>(px.x, 0.0), 0.0).rgb, lw), dot(textureSampleLevel(hist_in, hist_sampler, was - vec2<f32>(px.x, 0.0), 0.0).rgb, lw));
+ let ly = max(dot(textureSampleLevel(hist_in, hist_sampler, was + vec2<f32>(0.0, px.y), 0.0).rgb, lw), dot(textureSampleLevel(hist_in, hist_sampler, was - vec2<f32>(0.0, px.y), 0.0).rgb, lw));
+ // stricter tests of "thin" kept the orb's rim out (+0.18 by the second frame) and lost the tubes:
+ // a line alike along itself, 5.2 and 5.8%; a ring of eight with each lit place lit across, 6.2 and
+ // 6.5% (the tubes hang in rows, so a tube's neighbours light one side of it)
+ if (min(lx, ly) < l0) { hold = STILL_HOLD; }
+ }
+ hrgb = mix(hrgb, clamped, hold);
dbg_f += 8.0;
}
}
@@ -232,5 +258,5 @@ fn restore_taa(@builtin(global_invocation_id) id: vec3<u32>) {
textureStore(color, p, vec4<f32>(weight, hist.a / HISTORY_CAP, f32(hist.a > 0.0), c.a));
return;
}
- textureStore(color, p, vec4<f32>(c.rgb + e, c.a));
+ textureStore(color, p, vec4<f32>(uncompress(c.rgb) + e, c.a));
}
diff --git a/engine/render/raytrace/src/lib.rs b/engine/render/raytrace/src/lib.rs
index a4fdb9fe..8bb789ec 100644
--- a/engine/render/raytrace/src/lib.rs
+++ b/engine/render/raytrace/src/lib.rs
@@ -58,6 +58,16 @@ pub struct SolariSettings {
/// 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,
+ /// where the denoiser's soft knee starts, in its white (the colour at `preexposure / 16`); 0 turns it off
+ /// (RAEA_METALFX_KNEE). Above it a pixel's light goes in as its log: W (1 + ln(m / W)), its colour scaled to match,
+ /// and comes out undone after the denoiser. MetalFX averages a silhouette against bright sky or a lit doorway in
+ /// linear light, so its jittered edge pixel swung with the sky's share, 8 frames a cycle (MALL RAT t1 frame 1699:
+ /// steady 3.72, 0.81 with the jitter off). Light under the knee is untouched, so it isn't biased
+ pub knee: f32,
+ /// a full-size view denoised after the main pass instead of before it, so the sky and the forward meshes (drawn
+ /// there, with the jittered camera) are gathered over frames too and their edges stop stepping with the jitter
+ /// (metalfx.rs denoise_late; RAEA_SOLARI_DENOISE_LATE)
+ pub late: bool,
/// 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
@@ -85,6 +95,8 @@ impl Default for SolariSettings {
emissive: "taa".into(),
upscale: "one".into(),
preexposure: 16.0,
+ knee: 1.0,
+ late: false,
aa: true,
jitter: String::new(),
emissive_sharpness: 6.0,
diff --git a/engine/render/raytrace/src/metalfx.rs b/engine/render/raytrace/src/metalfx.rs
index 7db6f848..f6e9bb79 100644
--- a/engine/render/raytrace/src/metalfx.rs
+++ b/engine/render/raytrace/src/metalfx.rs
@@ -59,6 +59,7 @@ 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));
+ core.add_systems(denoise_late.before(super::upscale::upscale).in_set(Core3dSystems::EarlyPostProcess));
// 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
@@ -94,7 +95,7 @@ struct View {
struct Kit {
/// the guides (and the emissive out), the emissive back in, from this frame or gathered over frames (emit_taa.rs),
/// and the sampler that reads the gathered emission's history
- pipeline: Option<(wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::Sampler, wgpu::ComputePipeline)>,
+ pipeline: Option<(wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::Sampler, wgpu::ComputePipeline, wgpu::ComputePipeline)>,
views: HashMap<Entity, View>,
off: bool,
}
@@ -250,8 +251,23 @@ fn denoise(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Ki
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);
- // a view drawn small is denoised and brought up in one pass, unless its upscale is "two"
- if !st.denoise || (item.7 && st.upscale != "two") {
+ // a view drawn small is denoised and brought up in one pass, unless its upscale is "two"; one whose settings say
+ // `late` after the forward meshes and the sky (denoise_late)
+ if !st.denoise || (item.7 && st.upscale != "two") || (st.late && !item.7) {
+ return;
+ }
+ run(entity, item, &st, &device, &mut kit, &mut ctx, false);
+}
+
+/// After the main pass: a view at its full size whose settings say `late`, so the sky and the forward meshes, drawn with
+/// the jittered camera after Solari, are gathered over frames with the rest. Drawn after the denoiser, they kept the
+/// jitter: a silhouette against the sky stepped a pixel a frame on its 8-frame cycle (MALL RAT t1 frame 1699, steady's
+/// jitter worst square 73%)
+fn denoise_late(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {
+ let entity = view.entity();
+ let item = view.into_inner();
+ let st = super::settings::of(item.9);
+ if !st.denoise || item.7 || !st.late {
return;
}
run(entity, item, &st, &device, &mut kit, &mut ctx, false);
@@ -307,7 +323,7 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
}
}
}
- let (pipeline, restore, restore_taa, hist_sampler, pipeline_psr) = kit
+ let (pipeline, restore, restore_taa, hist_sampler, pipeline_psr, expand) = kit
.pipeline
.get_or_insert_with(|| {
// read from a project's engine-shaders/ or the checkout when one has them (docs/nobuild.feature NB5b)
@@ -316,7 +332,7 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
let source = format!("{guides}{taa}");
let module = dev.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("metalfx guides"), source: wgpu::ShaderSource::Wgsl(source.into()) });
let make = |entry: &str| dev.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("metalfx guides"), layout: None, module: &module, entry_point: Some(entry), compilation_options: Default::default(), cache: None });
- (make("main"), make("restore"), make("restore_taa"), super::emit_taa::sampler(&dev), make("main_psr"))
+ (make("main"), make("restore"), make("restore_taa"), super::emit_taa::sampler(&dev), make("main_psr"), make("expand"))
})
.clone();
let color_view = color.create_view(&Default::default());
@@ -324,7 +340,7 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
let 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, st.jitter_frames) 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, st.emissive_sharpness, jitter.x, jitter.y, cycle, 0.0];
+ 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, st.emissive_sharpness, jitter.x, jitter.y, cycle, st.knee.max(0.0) * st.preexposure / 16.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();
@@ -391,6 +407,18 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
pass.dispatch_workgroups(out_size.x.div_ceil(8), out_size.y.div_ceil(8), 1);
}
}
+ // the knee undone where no `restore` ran (emissive "mask")
+ if !split && st.knee > 0.0 {
+ let entries = [
+ wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&color_view) },
+ wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() },
+ ];
+ let bind = dev.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("metalfx knee undone"), layout: &expand.get_bind_group_layout(0), entries: &entries });
+ let mut pass = ctx.command_encoder().begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("metalfx knee undone"), timestamp_writes: None });
+ pass.set_pipeline(&expand);
+ pass.set_bind_group(0, &bind, &[]);
+ pass.dispatch_workgroups(out_size.x.div_ceil(8), out_size.y.div_ceil(8), 1);
+ }
use std::sync::atomic::Ordering::Relaxed;
super::upscale::DENOISED.store(done.is_ok(), Relaxed);
super::upscale::DENOISING.store(done.is_ok(), Relaxed);
diff --git a/engine/render/raytrace/src/metalfx_guides.wgsl b/engine/render/raytrace/src/metalfx_guides.wgsl
index a0c7e0c6..70910d0d 100644
--- a/engine/render/raytrace/src/metalfx_guides.wgsl
+++ b/engine/render/raytrace/src/metalfx_guides.wgsl
@@ -22,12 +22,28 @@
@group(0) @binding(5) var color: texture_storage_2d<rgba16float, read_write>;
// [0].x: the camera's exposure, .y: 1 to split all emission out (RAEA_SOLARI_EMISSIVE=split); [1]: the output's size
// and the input's (the corner of the colour the main pass drew); [2].xyz: the camera's back, world-space; [3].xy: the
-// jitter MetalFX is told, in input pixels
+// jitter MetalFX is told, in input pixels, .w: where the soft knee starts in the colour (0: none; SolariSettings.knee)
@group(0) @binding(6) var<uniform> params: array<vec4<f32>, 4>;
// the emission `main` took out of the colour, at the input's size, for `restore` to put back
@group(0) @binding(7) var emit: texture_storage_2d<rgba16float, read_write>;
// MetalFX's denoise strength mask: 1 leaves a pixel undenoised
@group(0) @binding(8) var mask: texture_storage_2d<r32float, write>;
+// The soft knee (SolariSettings.knee): above W a pixel's light m (its largest channel) goes in as W (1 + ln(m / W)),
+// which meets the line at W with the same slope, and its colour is scaled to match; `expand` undoes it after the
+// denoiser. Logarithmic rather than Reinhard's m / (1 + m): its half floats keep a bright pixel's light to about 0.5%,
+// where Reinhard's curve crowds every highlight just under its ceiling and loses them
+fn compress(c: vec3<f32>) -> vec3<f32> {
+ let w = params[3].w;
+ let m = max(c.r, max(c.g, c.b));
+ if (w <= 0.0 || m <= w) { return c; }
+ return c * (w * (1.0 + log(m / w)) / m);
+}
+fn uncompress(c: vec3<f32>) -> vec3<f32> {
+ let w = params[3].w;
+ let m = max(c.r, max(c.g, c.b));
+ if (w <= 0.0 || m <= w) { return c; }
+ return c * (w * exp(min(m / w - 1.0, 80.0)) / m);
+}
fn rgb9e5(v: u32) -> vec3<f32> {
let scale = exp2(f32(i32(extractBits(v, 27u, 5u)) - 15 - 9));
return vec3<f32>(f32(extractBits(v, 0u, 9u)), f32(extractBits(v, 9u, 9u)), f32(extractBits(v, 18u, 9u))) * scale;
@@ -84,6 +100,7 @@ fn sky(p: vec2<i32>) {
textureStore(rough, p, vec4<f32>(1.0, 0.0, 0.0, 0.0));
textureStore(emit, p, vec4<f32>(0.0));
textureStore(mask, p, vec4<f32>(1.0, 0.0, 0.0, 0.0));
+ textureStore(color, p, vec4<f32>(compress(c), textureLoad(color, p).a));
}
fn store(p: vec2<i32>, g: vec4<u32>, s: Surface) {
textureStore(normal, p, vec4<f32>(s.normal, 0.0));
@@ -95,7 +112,7 @@ fn store(p: vec2<i32>, g: vec4<u32>, s: Surface) {
if (params[0].y > 0.5) {
let taken = min(e, c.rgb);
textureStore(diffuse, p, vec4<f32>(s.diffuse, 1.0));
- textureStore(color, p, vec4<f32>(c.rgb - taken, c.a));
+ textureStore(color, p, vec4<f32>(compress(c.rgb - taken), c.a));
textureStore(emit, p, vec4<f32>(taken, 0.0));
textureStore(mask, p, vec4<f32>(0.0));
return;
@@ -104,6 +121,7 @@ fn store(p: vec2<i32>, g: vec4<u32>, s: Surface) {
let share = dot(e, luma) / max(dot(c.rgb, luma), 1e-4);
textureStore(diffuse, p, vec4<f32>(min(s.diffuse + e / (vec3<f32>(1.0) + e), vec3<f32>(1.0)), 1.0));
textureStore(mask, p, vec4<f32>(smoothstep(0.3, 0.7, share), 0.0, 0.0, 0.0));
+ textureStore(color, p, vec4<f32>(compress(c.rgb), c.a));
}
@compute @workgroup_size(8, 8, 1)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
@@ -142,5 +160,14 @@ fn restore(@builtin(global_invocation_id) id: vec3<u32>) {
let t = q - floor(q);
let e = mix(mix(emitted(i), emitted(i + vec2<i32>(1, 0)), t.x), mix(emitted(i + vec2<i32>(0, 1)), emitted(i + vec2<i32>(1, 1)), t.x), t.y);
let c = textureLoad(color, p);
- textureStore(color, p, vec4<f32>(c.rgb + e, c.a));
+ textureStore(color, p, vec4<f32>(uncompress(c.rgb) + e, c.a));
+}
+// the knee undone, with no emission to put back (emissive "mask"): run after the denoiser whenever `restore` isn't
+@compute @workgroup_size(8, 8, 1)
+fn expand(@builtin(global_invocation_id) id: vec3<u32>) {
+ let size = vec2<u32>(params[1].xy);
+ if (id.x >= size.x || id.y >= size.y) { return; }
+ let p = vec2<i32>(id.xy);
+ let c = textureLoad(color, p);
+ textureStore(color, p, vec4<f32>(uncompress(c.rgb), c.a));
}
diff --git a/engine/render/raytrace/src/settings.rs b/engine/render/raytrace/src/settings.rs
index 71e24c54..3f55107b 100644
--- a/engine/render/raytrace/src/settings.rs
+++ b/engine/render/raytrace/src/settings.rs
@@ -13,6 +13,8 @@ struct Overrides {
emissive: Option<String>,
upscale: Option<String>,
preexposure: Option<f32>,
+ knee: Option<f32>,
+ late: Option<bool>,
aa: Option<bool>,
jitter: Option<String>,
emissive_sharpness: Option<f32>,
@@ -33,6 +35,8 @@ fn overrides() -> &'static Overrides {
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"),
+ late: switch("RAEA_SOLARI_DENOISE_LATE"),
+ knee: var("RAEA_METALFX_KNEE").and_then(|v| v.parse::<f32>().ok()).filter(|v| v.is_finite() && *v >= 0.0),
aa: switch("RAEA_SOLARI_AA"),
jitter: var("RAEA_SOLARI_JITTER"),
emissive_sharpness: num("RAEA_EMIT_TAA_SHARP"),
@@ -51,6 +55,8 @@ pub(crate) fn of(s: Option<&SolariSettings>) -> SolariSettings {
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.knee { s.knee = v; }
+ if let Some(v) = o.late { s.late = 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; }
@@ -66,6 +72,8 @@ const VARS: &[(&str, &str)] = &[
("RAEA_SOLARI_EMISSIVE", "emissive"),
("RAEA_SOLARI_UPSCALE", "upscale"),
("RAEA_METALFX_PREEXPOSURE", "preexposure"),
+ ("RAEA_METALFX_KNEE", "knee"),
+ ("RAEA_SOLARI_DENOISE_LATE", "late"),
("RAEA_SOLARI_AA", "aa"),
("RAEA_SOLARI_JITTER", "jitter"),
("RAEA_SOLARI_DYNAMIC", "dynamic"),
diff --git a/sdk/guides/craft/bevy/solari.md b/sdk/guides/craft/bevy/solari.md
index 47358614..49432427 100644
--- a/sdk/guides/craft/bevy/solari.md
+++ b/sdk/guides/craft/bevy/solari.md
@@ -21,7 +21,7 @@
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`, `jitterFrames`, `emissiveSharpness`, `dynamic`, `firstBounce`, `confidenceCap` and `cache` (the world cache's
+ `preexposure`, `knee`, `late`, `firefly`, `aa`, `jitter`, `jitterFrames`, `emissiveSharpness`, `dynamic`, `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
@@ -118,9 +118,17 @@ Tell it from its neighbours:
- **grain**: pixel-sized noise, which a denoiser removes and boiling is what it leaves;
- **sparkle**: thin edges and fine texture aliasing under the camera's jitter.
-Measure it: `raea light steady FILE --composition ID --frame N --frames 150` holds frame N and measures its second
-half. blotch is boiling's size (the 32 px patches' movement, limit 1.5%), grain the pixel-sized part, and spread their
-ratio (near 0.25 is pure grain; 0.5 and up is boiling).
+Measure it: `raea light steady FILE --composition ID --frame N --frames 150 -o DIR` holds frame N and reads its last
+75 frames square by square (32 px), each square's movement told by kind, since each has its own fix:
+- **settling**: the square's straight-line trend, the light still building. It's a note, not a fault: hold longer, or
+ give the shot a lead-in as long as it took;
+- **boiling**: what's slow once the trend is out. Limit 1.5% over the frame, and three times that in its worst square;
+- **jitter**: what repeats on a short cycle (8 frames at full size). Edges step with the camera's sub-pixel jitter
+ because something was drawn outside the denoiser's history. Limit 5% in the worst square;
+- **flicker**: fast with no cycle, such as a firefly, a sparkle in a reflection, or two faces in one plane. Limit 5%.
+`DIR/steady-kinds.png` maps them (red jitter and flicker, green boiling, blue settling). Each hold is kept in the
+project's record, so `raea check` reports what the newest hold of each frame found for a composition lit by Solari, and
+waits for one when there is none. raea check names the command.
What it comes from, measured on MALL RAT's sunlit mall court (blotch 3.0 at one path a pixel), largest first:
1. **Too few paths.** One path's bounce light at a pixel is as noisy as its mean, and ReSTIR's reuse and the denoiser
@@ -130,8 +138,26 @@ What it comes from, measured on MALL RAT's sunlit mall court (blotch 3.0 at one
papers' "correlation artifacts"). Its radius and confidence cap don't fix it.
3. **The world cache's young cells.** A frozen, converged cache reads 0.1-0.3 lower than any live one; `cache.steady`
doesn't close the gap yet.
+4. **A firefly that lingers.** A patch jumps brighter in one frame and takes a second to fall back: one very bright
+ sample (a bounce landing beside a small lamp) kept by temporal reuse and spread by spatial reuse. Rooms lit by
+ small bulbs have them constantly. `<SolariLighting firefly={6} />` cuts a sample over 6 times the mean of its 8x8
+ pixels back to that. It costs the light those samples carried (0.3 stops in such a room at 6, half that at 12),
+ so set the exposure after it.
Not the cause there: the denoiser (it passes the patches through), the number of small lights, the direct light's
-samples, the camera's jitter.
+samples, the world cache's update rate or how long its cells live.
+
+Jitter has its own causes, measured on MALL RAT (t1 against its sky: worst square 73%, then 3.8%):
+1. **The sky and forward meshes drawn after the denoiser.** By default the denoiser runs before the main pass, which
+ then draws the Environment's background and every forward mesh with the jittered camera, unresolved. Every
+ silhouette against the sky steps a pixel a frame. `<SolariLighting late />` denoises after them.
+2. **Emitters put back frame by frame.** `emissive="split"` returns each emitter's light after the denoiser without a
+ history, so a sign's letters step. Keep the default "taa".
+3. **An emitter thinner than a pixel.** A ceiling tube seen edge-on is missed by some of the jitter's positions, and
+ its history is cut to black on those frames. `constants={{ emissiveClamp: { stillHold: 0.25 } }}` eases that for
+ thin lights (7% to 2%). It isn't the default: a bright lamp switched off in shot then leaves its rim for a few frames.
+4. **The frame's border.** The last 32 px boil about twice as much as the middle, and a wall there can show 8 px
+ blocks. There's no setting for it yet; frame a held shot so a flat lit wall doesn't end at the frame's edge.
+The first two, and paths, belong on any shot that has sky or signs in it.
## Why
diff --git a/sdk/render/src/bevy3d/raytracing.tsx b/sdk/render/src/bevy3d/raytracing.tsx
index 7e818ddf..91949011 100644
--- a/sdk/render/src/bevy3d/raytracing.tsx
+++ b/sdk/render/src/bevy3d/raytracing.tsx
@@ -24,6 +24,11 @@ export interface SolariLightingProps {
/** initial paths a pixel a frame (1 to 16, 1 by default): N cut the noise of one path N times, at N times its rays.
* A sunlit room seen through bounces (MALL RAT's court) needs 4 or more to hold still */
paths?: number;
+ /** the firefly filter: a sample over this many times the mean of its 8x8 pixels is cut back to that after temporal
+ * reuse (off by default; 2 and up). One very bright sample otherwise lingers and spreads: a patch jumps brighter and
+ * takes a second to fall back. Lower holds stiller and loses more light (a room lit by small bulbs: 6 holds still
+ * and reads 0.3 stops darker, 12 half of both; 32 loses nothing and gains little) */
+ firefly?: 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) */
@@ -39,6 +44,9 @@ export interface SolariLightingProps {
steady?: boolean;
/** cache updates a frame (1): more converge faster */
iterations?: number;
+ /** frames a cell lives unqueried (10): a camera that leaves a place and comes back finds its light still built
+ * instead of starting cold; longer lives keep more cells, which the cache's 2^20 slots must hold */
+ life?: number;
cellSize?: number;
/** how fast cells grow with distance from the camera (15) */
lodScale?: number;
@@ -74,6 +82,13 @@ export interface SolariLightingProps {
* 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;
+ /** where the denoiser's soft knee starts, in its white (1 by default; 0 off). Light above it is denoised as its log
+ * and restored after, so a silhouette against bright sky or a lit doorway doesn't step with the camera's jitter.
+ * RAEA_METALFX_KNEE overrides it */
+ knee?: number;
+ /** denoise after the forward meshes and the sky, so their edges are gathered over frames too instead of stepping
+ * with the camera's jitter. RAEA_SOLARI_DENOISE_LATE overrides it */
+ late?: boolean;
/** 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;
@@ -136,8 +151,10 @@ export interface SolariLightingProps {
emissiveHistory?: number;
/** how an emissive surface's history is held to the light about it now: a still pixel within the darkest times
* stillLow (0.95) and the brightest times stillHigh (1.05); a moving one under the brightest times movingGain (4)
- * plus movingFloor (0.02) */
- emissiveClamp?: { stillLow?: number; stillHigh?: number; movingGain?: number; movingFloor?: number };
+ * plus movingFloor (0.02). stillHold (1) is how far a still pixel whose history is a thin line or a
+ * point goes toward its bounds a frame: 0.25 stops an emitter thinner than a pixel flickering (a ceiling tube seen
+ * edge-on), and a bright lamp switched off then leaves its rim for a few frames */
+ emissiveClamp?: { stillLow?: number; stillHigh?: number; stillHold?: number; movingGain?: number; movingFloor?: number };
};
}
@@ -174,6 +191,7 @@ export function solariConstants(c: SolariLightingProps["constants"]) {
[taa, "HISTORY_CAP", at(c.emissiveHistory, "emissiveHistory")],
[taa, "STILL_LOW", at(e.stillLow, "emissiveClamp.stillLow")],
[taa, "STILL_HIGH", at(e.stillHigh, "emissiveClamp.stillHigh")],
+ [taa, "STILL_HOLD", at(e.stillHold, "emissiveClamp.stillHold")],
[taa, "MOVING_GAIN", at(e.movingGain, "emissiveClamp.movingGain")],
[taa, "MOVING_FLOOR", at(e.movingFloor, "emissiveClamp.movingFloor")],
]);
@@ -202,6 +220,11 @@ export function solariSettings(p: SolariLightingProps): Record<string, unknown>
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.late !== undefined) v.late = p.late;
+ if (p.knee !== undefined) {
+ if (!(Number.isFinite(p.knee) && p.knee >= 0)) throw new RangeError(`SolariLighting: knee is a number from 0, got ${p.knee}`);
+ v.knee = p.knee;
+ }
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;
@@ -235,6 +258,8 @@ export function SolariLighting(p: SolariLightingProps = {}) {
field("firstBounce", "first_bounce_probability", p.firstBounce);
if (p.paths !== undefined && !(Number.isInteger(p.paths) && p.paths >= 1 && p.paths <= 16)) throw new RangeError(`SolariLighting: paths is a whole number from 1 to 16, got ${p.paths}`);
field("paths", "paths_per_pixel", p.paths, true);
+ if (p.firefly !== undefined && !(p.firefly === 0 || p.firefly >= 2)) throw new RangeError(`SolariLighting: firefly is 0 (off) or a multiplier from 2 up, got ${p.firefly}`);
+ field("firefly", "firefly_cap", p.firefly);
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);
@@ -247,6 +272,8 @@ export function SolariLighting(p: SolariLightingProps = {}) {
// (11-25, MALL RAT's splotches); light that moves (a power cut) lags by the history, so set frames to what it can bear
if (c.steady) value.world_cache_steady = true;
field("cache.iterations", "world_cache_update_iterations", c.iterations, true);
+ if (c.life !== undefined && !(Number.isInteger(c.life) && c.life >= 1 && c.life <= 65535)) throw new RangeError(`SolariLighting: cache.life is a whole number of frames from 1 to 65535, got ${c.life}`);
+ field("cache.life", "world_cache_cell_lifetime", c.life, true);
if (c.bake) {
value.world_cache_keep = true;
value.world_cache_steady = true;
diff --git a/systems/contact/src/lint.rs b/systems/contact/src/lint.rs
index e3cc185b..8dff9d4b 100644
--- a/systems/contact/src/lint.rs
+++ b/systems/contact/src/lint.rs
@@ -320,7 +320,8 @@ fn moving(now: &[Item], other: &[Item]) -> Vec<bool> {
/// `now` is the frame's parts, `next` the next frame's (or the one before, at the end) to see what moves.
pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {
let moving = moving(now, next);
- let (parts, items, skipped) = parts_of(now, &moving);
+ let (parts, items, mut skipped) = parts_of(now, &moving);
+ let (parts, items) = unparked(parts, items, &mut skipped);
let grid = Grid::new(&parts);
let insets = insets(&parts);
let mut out = Vec::new();
@@ -451,6 +452,34 @@ pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {
(out, errors)
}
+/// How far from the scene a part is parked: a piece swaps a flipbook's frames (MALL RAT's fountain, 88 water models) by
+/// moving the ones not shown hundreds of metres away, where they lie in one another and read as faces fighting.
+const PARKED: f32 = 500.0;
+
+/// The parts in the scene, without those parked far from it (further than PARKED from the median of every part's
+/// centre), each of those said once as not checked.
+fn unparked<T>(parts: Vec<Part>, items: Vec<T>, skipped: &mut Vec<String>) -> (Vec<Part>, Vec<T>) {
+ if parts.len() < 3 {
+ return (parts, items);
+ }
+ let mid = |k: usize| {
+ let mut v: Vec<f32> = parts.iter().map(|p| ((p.lo + p.hi) * 0.5)[k]).collect();
+ v.sort_by(f32::total_cmp);
+ v[v.len() / 2]
+ };
+ let centre = Vec3::new(mid(0), mid(1), mid(2));
+ let mut parked = 0;
+ let kept: (Vec<Part>, Vec<T>) = parts.into_iter().zip(items).filter(|(p, _)| {
+ let far = ((p.lo + p.hi) * 0.5).distance(centre) > PARKED;
+ parked += far as usize;
+ !far
+ }).unzip();
+ if parked > 0 {
+ skipped.push(format!("{parked} part{} parked over {PARKED} m from the scene (a flipbook's frames not shown)", if parked == 1 { "" } else { "s" }));
+ }
+ kept
+}
+
/// The surface a part would land on and how far it is (negative: sunk): what it rests on, or the nearest surface
/// under it when it's in the air.
fn landing(r: &Rest) -> Option<(usize, u32, f32)> {
diff --git a/systems/contact/src/lint/tests.rs b/systems/contact/src/lint/tests.rs
index 91e7e468..6696cd09 100644
--- a/systems/contact/src/lint/tests.rs
+++ b/systems/contact/src/lint/tests.rs
@@ -140,3 +140,15 @@ fn a_part_moved_sideways_is_settled_where_it_lands() {
// moved along the top it stays on it
assert!(matches!(rest_after(&parts, &ins, 2, Vec3::new(-0.3, 0.0, 0.0)), Rest::On { under: 1, .. }));
}
+
+#[test]
+fn a_flipbooks_frames_parked_far_away_are_left_out() {
+ let mut parts = vec![part("floor", Vec3::ZERO, Vec3::new(20.0, 0.1, 20.0)), part("bench", Vec3::new(1.0, 0.3, 0.0), Vec3::new(1.5, 0.5, 0.4)), part("water0", Vec3::new(0.0, 0.5, 3.0), Vec3::ONE)];
+ for i in 1..4 {
+ parts.push(part(&format!("water{i}"), Vec3::new(0.0, -900.0, 3.0), Vec3::ONE));
+ }
+ let mut skipped = Vec::new();
+ let (kept, _) = unparked(parts, vec![(); 6], &mut skipped);
+ assert_eq!(kept.iter().map(|p| p.label.as_str()).collect::<Vec<_>>(), ["floor", "bench", "water0"]);
+ assert!(skipped[0].starts_with("3 parts parked"), "{skipped:?}");
+}
diff --git a/vendor/bevy_solari/src/realtime/bindings.wesl b/vendor/bevy_solari/src/realtime/bindings.wesl
index 540f1a48..98cd8fda 100644
--- a/vendor/bevy_solari/src/realtime/bindings.wesl
+++ b/vendor/bevy_solari/src/realtime/bindings.wesl
@@ -57,12 +57,15 @@ struct SolariLightingSettings {
reset: u32,
// raea: SolariLighting::first_bounce_probability (prepare.rs), and padding
first_bounce_probability: f32,
- // raea: bit 0 SolariLighting::world_cache_steady, bit 1 that and the camera where it was last frame (prepare.rs)
+ // raea: bit 0 SolariLighting::world_cache_steady, bit 1 that and the camera where it was last frame, bits 16-31 a
+ // cell's life in frames (0: the caller's, Solari's 10) (prepare.rs)
world_cache_steady: u32,
// raea (11-25): ReSTIR's spatial reuse radius in pixels (prepare.rs, RAEA_SOLARI_SPATIAL_RADIUS; Bevy's 30)
spatial_reuse_radius: f32,
// raea (11-25): SolariLighting::paths_per_pixel, initial paths traced a pixel a frame (initial_path.wesl)
paths_per_pixel: u32,
+ // raea (11-25): the firefly filter's multiplier (restir.wesl; SolariLighting::firefly_cap, RAEA_SOLARI_FIREFLY), 0 off
+ firefly_cap: f32,
}
/// Don't adjust the size of this struct without also adjusting `prepare::RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE`.
diff --git a/vendor/bevy_solari/src/realtime/gbuffer_utils.wesl b/vendor/bevy_solari/src/realtime/gbuffer_utils.wesl
index ee08af0e..6222ccd9 100644
--- a/vendor/bevy_solari/src/realtime/gbuffer_utils.wesl
+++ b/vendor/bevy_solari/src/realtime/gbuffer_utils.wesl
@@ -63,7 +63,15 @@ fn permute_pixel(pixel_id: vec2<u32>, frame_index: u32, view_size: vec2<f32>) ->
shifted_pixel_id ^= vec2<i32>(3);
shifted_pixel_id -= offset;
if any(shifted_pixel_id < vec2<i32>(0)) || any(shifted_pixel_id >= vec2<i32>(view_size)) {
- return pixel_id;
+ // raea (11-25): a pixel whose shifted 4x4 block runs off the frame was left unpermuted, so the frame's 3 px
+ // border reused its own history every frame and boiled more than the rest (MALL RAT's holds: border squares
+ // 27% more on average, twice on t7, t8). It takes the block's swap unshifted instead, which stays in the frame
+ // when the frame's a multiple of 4, and is left as it was only when that's off it too.
+ let unshifted = vec2<i32>(pixel_id) ^ vec2<i32>(3);
+ if any(unshifted >= vec2<i32>(view_size)) {
+ return pixel_id;
+ }
+ return vec2<u32>(unshifted);
}
return vec2<u32>(shifted_pixel_id);
}
diff --git a/vendor/bevy_solari/src/realtime/mod.rs b/vendor/bevy_solari/src/realtime/mod.rs
index e7acc106..4fde23aa 100644
--- a/vendor/bevy_solari/src/realtime/mod.rs
+++ b/vendor/bevy_solari/src/realtime/mod.rs
@@ -175,6 +175,15 @@ pub struct SolariLighting {
///
/// Defaults to `1`.
pub paths_per_pixel: u32,
+ /// raea (11-25): the firefly filter (RTXDI's boiling filter). After temporal reuse, a reservoir whose contribution
+ /// is over this many times the mean of its 8x8 block has its weight cut to that. One very bright sample (a bounce
+ /// landing beside a small lamp) is otherwise reused for many frames and spread to its neighbours: a patch jumps
+ /// 30% in a frame and takes 30 frames to fall back. It costs the light those samples carried, so it's a trade:
+ /// MALL RAT's party room, lit by bulbs, held still at 6 (boiling 1.63% to 0.73%) and read 0.29 stops darker; at 32
+ /// nothing is lost and little is gained. RTXDI's usual strengths are 31 to 41.
+ ///
+ /// Defaults to `0.0` (off).
+ pub firefly_cap: f32,
/// How responsive the world cache is to changes in lighting.
///
@@ -252,6 +261,11 @@ pub struct SolariLighting {
/// raea: the cache's update (each cell's bounce sample, blended) run this many times a frame, each with its own
/// random numbers while `world_cache_steady`. A bake converges in fewer frames. Defaults to 1.
pub world_cache_update_iterations: u32,
+ /// raea (11-25): how many frames a world cache cell lives without being queried, up to 65535; 0 is Solari's 10. A
+ /// moving camera that leaves a place and comes back finds its cells dead after 10 frames and its light starting
+ /// cold again: MALL RAT's court kept settling as the camera crossed it (raea light steady). Longer lives keep more
+ /// cells, which the cache's 2^20 slots must hold.
+ pub world_cache_cell_lifetime: u32,
/// raea: write the whole cache to this file at the end of this frame (a bake, a few frames before its last). Empty:
/// no write.
pub world_cache_save: String,
@@ -271,6 +285,7 @@ impl Default for SolariLighting {
max_bounces: 3,
first_bounce_probability: 1.0,
paths_per_pixel: 1,
+ firefly_cap: 0.0,
world_cache_max_temporal_samples: 32.0,
world_cache_direct_light_sample_count: 32,
world_cache_max_gi_ray_distance: 1000.0,
@@ -281,6 +296,7 @@ impl Default for SolariLighting {
world_cache_keep: false,
world_cache_steady: false,
world_cache_update_iterations: 1,
+ world_cache_cell_lifetime: 0,
world_cache_save: String::new(),
world_cache_load: String::new(),
}
diff --git a/vendor/bevy_solari/src/realtime/prepare.rs b/vendor/bevy_solari/src/realtime/prepare.rs
index fbc33c4b..2c3ca540 100644
--- a/vendor/bevy_solari/src/realtime/prepare.rs
+++ b/vendor/bevy_solari/src/realtime/prepare.rs
@@ -85,6 +85,9 @@ struct SolariLightingUniforms {
spatial_reuse_radius: f32,
// raea (11-25): SolariLighting::paths_per_pixel (RAEA_SOLARI_PATHS overrides it)
paths_per_pixel: u32,
+ // raea (11-25): the firefly filter (restir.wesl): a reservoir whose contribution is over this many times its 8x8
+ // block's mean is cut back to that, 0 off (RAEA_SOLARI_FIREFLY)
+ firefly_cap: f32,
}
impl SolariLightingUniforms {
@@ -104,8 +107,10 @@ impl SolariLightingUniforms {
reset: (settings.reset || force_reset) as u32,
first_bounce_probability: settings.first_bounce_probability.clamp(0.05, 1.0),
// bit 1: a steady cache with the camera held (world_cache_query.wesl world_cache_still)
- world_cache_steady: (settings.world_cache_steady || steady_override()) as u32 | ((((settings.world_cache_steady || steady_override()) && still) as u32) << 1),
+ // bits 16-31: a cell's life in frames unqueried (world_cache_query.wesl cell_life), 0 for Solari's
+ world_cache_steady: (settings.world_cache_steady || steady_override()) as u32 | ((((settings.world_cache_steady || steady_override()) && still) as u32) << 1) | (life_override().unwrap_or(settings.world_cache_cell_lifetime).min(65535) << 16),
spatial_reuse_radius: spatial_reuse_radius(),
+ firefly_cap: firefly_override().unwrap_or(settings.firefly_cap).max(0.0),
paths_per_pixel: paths_override().unwrap_or(settings.paths_per_pixel).clamp(1, 16),
}
}
@@ -412,6 +417,12 @@ fn spatial_reuse_radius() -> f32 {
*R.get_or_init(|| std::env::var("RAEA_SOLARI_SPATIAL_RADIUS").ok().and_then(|v| v.parse::<f32>().ok()).filter(|v| *v >= 1.0).unwrap_or(30.0))
}
+/// raea: RAEA_SOLARI_FIREFLY, the firefly filter's multiplier for every camera whatever the composition asks (0 off)
+fn firefly_override() -> Option<f32> {
+ static F: std::sync::OnceLock<Option<f32>> = std::sync::OnceLock::new();
+ *F.get_or_init(|| std::env::var("RAEA_SOLARI_FIREFLY").ok().and_then(|v| v.parse::<f32>().ok()).filter(|v| *v >= 0.0))
+}
+
/// raea: RAEA_SOLARI_PATHS, paths a pixel for every camera whatever the composition asks (a sweep)
fn paths_override() -> Option<u32> {
static P: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
@@ -424,3 +435,9 @@ fn steady_override() -> bool {
static S: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*S.get_or_init(|| std::env::var("RAEA_SOLARI_STEADY").as_deref() == Ok("1"))
}
+
+/// raea: RAEA_SOLARI_CELL_LIFE, a world cache cell's life in frames for every camera whatever the composition asks
+fn life_override() -> Option<u32> {
+ static L: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
+ *L.get_or_init(|| std::env::var("RAEA_SOLARI_CELL_LIFE").ok().and_then(|v| v.parse::<u32>().ok()))
+}
diff --git a/vendor/bevy_solari/src/realtime/restir.wesl b/vendor/bevy_solari/src/realtime/restir.wesl
index fe535575..48ef8d43 100644
--- a/vendor/bevy_solari/src/realtime/restir.wesl
+++ b/vendor/bevy_solari/src/realtime/restir.wesl
@@ -15,17 +15,57 @@ enable wgpu_ray_query;
const SPATIAL_REUSE_RADIUS_PIXELS = 30.0;
+// raea (11-25): the firefly filter, after RTXDI's boiling filter (RTXDI_BoilingFilter; ReSTIR PT Enhanced names the
+// cause: a high-energy sample weighted up by temporal reuse spreads through spatial reuse and stays). Each pixel of
+// an 8x8 block puts its merged reservoir's contribution (the target function times its weight) here; one that is over
+// constants.firefly_cap times the block's mean has its weight cut to that before it is kept, so it can't be reused at
+// full strength next frame. RTXDI drops such a reservoir; cutting it keeps the light it would have given on average.
+// On MALL RAT's held frames a square jumped 30% in a frame and took 30 to fall back (raea light steady, boiling 10%).
+var<workgroup> block_contribution: array<f32, 64>;
+
+struct TemporalPixel {
+ reservoir: Reservoir,
+ contribution: f32,
+ pixel_index: u32,
+ keep: bool,
+}
+
@compute @workgroup_size(8, 8, 1)
-fn initial_and_temporal(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) global_id: vec3<u32>) {
- if any(global_id.xy >= vec2u(view.main_pass_viewport.zw)) { return; }
+fn initial_and_temporal(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) global_id: vec3<u32>, @builtin(local_invocation_index) local_index: u32) {
+ var pixel = initial_and_temporal_pixel(workgroup_id, global_id);
+ var own = pixel.contribution;
+ if !(own > 0.0) || isinf(own) { own = 0.0; }
+ block_contribution[local_index] = own;
+ workgroupBarrier();
+ if !pixel.keep { return; }
+ if constants.firefly_cap > 0.0 && own > 0.0 {
+ var sum = 0.0;
+ var lit = 0.0;
+ for (var i = 0u; i < 64u; i++) {
+ let c = block_contribution[i];
+ sum += c;
+ lit += f32(c > 0.0);
+ }
+ let most = sum / max(lit, 1.0) * constants.firefly_cap;
+ if own > most {
+ // the weight is cut, so the frame is darker by what the outliers carried (a room lit by small bulbs: 0.15
+ // stops at 12, 0.29 at 6). Cutting the confidence instead (ReSTIR PT Enhanced's adaptive cap) lost as
+ // much there and held less still (0.89 against 0.73 at 6)
+ pixel.reservoir.unbiased_contribution_weight *= most / own;
+ }
+ }
+ reservoirs_b[pixel.pixel_index] = pixel.reservoir;
+}
+
+fn initial_and_temporal_pixel(workgroup_id: vec3<u32>, global_id: vec3<u32>) -> TemporalPixel {
+ if any(global_id.xy >= vec2u(view.main_pass_viewport.zw)) { return TemporalPixel(empty_reservoir(), 0.0, 0u, false); }
let pixel_index = global_id.x + global_id.y * u32(view.main_pass_viewport.z);
var rng = pixel_index + constants.frame_rng;
let depth = textureLoad(depth_buffer, global_id.xy, 0);
if depth == 0.0 {
- reservoirs_b[pixel_index] = empty_reservoir();
- return;
+ return TemporalPixel(empty_reservoir(), 0.0, pixel_index, true);
}
let surface = gpixel_resolve(textureLoad(gbuffer, global_id.xy, 0), depth, global_id.xy, view.main_pass_viewport.zw, view.world_from_clip);
@@ -38,7 +78,8 @@ fn initial_and_temporal(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin
let merge_result = merge_reservoirs(initial.reservoir, surface.world_position, surface.world_normal, surface.material,
temporal.reservoir, temporal.world_position, temporal.world_normal, temporal.material, previous_camera_world_position, &rng);
- reservoirs_b[pixel_index] = merge_result.merged_reservoir;
+ let contribution = luminance(merge_result.selected_sample_brdf_radiance) * merge_result.merged_reservoir.unbiased_contribution_weight;
+ return TemporalPixel(merge_result.merged_reservoir, contribution, pixel_index, true);
}
@compute @workgroup_size(8, 8, 1)
@@ -140,7 +181,13 @@ fn load_spatial_reservoir(pixel_id: vec2<u32>, depth: f32, world_position: vec3<
fn get_neighbor_pixel_id(center_pixel_id: vec2<u32>, search_radius: f32, rng: ptr<function, u32>) -> vec2<u32> {
var spatial_id = vec2<f32>(center_pixel_id) + sample_disk(search_radius, rng);
- spatial_id = clamp(spatial_id, vec2(0.0), view.main_pass_viewport.zw - 1.0);
+ // raea (11-25): a neighbour off the frame reflected back in, not clamped to its border: clamped, about half a border
+ // pixel's neighbours were the same border column, so the pixels along it reused the same few reservoirs and their
+ // light wandered together (MALL RAT t2's worst boiling square, 6.8%, was on the frame's edge in every hold)
+ let hi = view.main_pass_viewport.zw - 1.0;
+ spatial_id = abs(spatial_id);
+ spatial_id = hi - abs(hi - spatial_id);
+ spatial_id = clamp(spatial_id, vec2(0.0), hi);
return vec2<u32>(spatial_id);
}
diff --git a/vendor/bevy_solari/src/realtime/world_cache_query.wesl b/vendor/bevy_solari/src/realtime/world_cache_query.wesl
index ad61ac9c..a244b6a9 100644
--- a/vendor/bevy_solari/src/realtime/world_cache_query.wesl
+++ b/vendor/bevy_solari/src/realtime/world_cache_query.wesl
@@ -66,9 +66,9 @@ fn query_world_cache_found(world_position_in: vec3<f32>, world_normal: vec3<f32>
// Cell already exists or is empty - reset lifetime
if existing_checksum == checksum || existing_checksum == WORLD_CACHE_EMPTY_CELL {
@if(!WORLD_CACHE_QUERY_ATOMIC_MAX_LIFETIME)
- atomicStore(&world_cache.life[key], cell_lifetime);
+ atomicStore(&world_cache.life[key], cell_life(cell_lifetime));
@else
- atomicMax(&world_cache.life[key], cell_lifetime);
+ atomicMax(&world_cache.life[key], cell_life(cell_lifetime));
}
if existing_checksum == checksum {
@@ -100,6 +100,10 @@ fn get_cell_size(world_position: vec3<f32>, view_position: vec3<f32>, ray_t: f32
}
// raea (11-25): bit 1 of constants.world_cache_steady (prepare.rs): a steady cache with the camera where it was last frame
+// raea (11-25): a queried cell's life, SolariLighting::world_cache_cell_lifetime where set (bits 16-31 of
+// constants.world_cache_steady), else the caller's (Solari's 10)
+fn cell_life(caller: u32) -> u32 { let own = constants.world_cache_steady >> 16u; return select(caller, own, own != 0u); }
+
fn world_cache_still() -> bool { return (constants.world_cache_steady & 2u) != 0u; }
fn quantize_position(world_position: vec3<f32>, quantization_factor: f32) -> vec3<f32> {