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.

SolariLighting paths: N initial paths a pixel, merged by RIS, cut the boiling in held sun-lit interiors (MALL RAT's court 3.0 to 1.6-1.9 on raea light steady, at 1.6-2.2x the frame; unbiased on the kitchen); a steady world cache whose query holds still with the camera, and a baked one, when a composition asks. All off by default: paths 1, sky share 0, spatial radius 30. It doesn't yet pass the 1.5 gate there: the world cache's own noise is what's left (docs/solari-efficiency.md). raea light steady says the light boils (the trade's word; the Solari guide says what it is and what to try first)

shinyobjectz09d87cfa1c93
diff --git a/docs/solari-efficiency.md b/docs/solari-efficiency.md
new file mode 100644
index 00000000..191f0bc5
--- /dev/null
+++ b/docs/solari-efficiency.md
@@ -0,0 +1,149 @@
+# Solari, forked: where MALL RAT's frame time goes (11-25)
+
+Measured on MALL RAT's own takes (Raea/anchor-tenant, `tools/solari-sweep.sh`, scored by `out/lab/pf/score.sh`): each
+lever moved alone from the take's settings, 240 frames, wall time a frame, scored SSIM/PSNR against the take as it
+renders (pf0) on the finished VHS look at 1440 x 1080. pfR is pf0 drawn again: its numbers are the noise floor (and wall
+time itself moves about 10% run to run). The sweep stopped partway: t8 has four levers.
+
+| lever | t2 ms (pf0 204) | t2 ssim / psnr | t4 ms (pf0 82) | t4 ssim / psnr |
+|---|---|---|---|---|
+| pfR, the floor | 185 | 0.991 / 37.2 | 80 | 0.989 / 42.6 |
+| pfB, 1 bounce | 186 | 0.990 / 36.2 | **64** | 0.988 / 41.0 |
+| pfS, half the samples (8/4) | 194 | 0.988 / 32.6 | 75 | 0.987 / 40.5 |
+| pfF, firstBounce 0.5 | 161 | 0.989 / 35.8 | 61 | 0.984 / 38.8 |
+| pfC, Solari at 0.67 scale | 149 | 0.986 / 35.8 | 52 | 0.964 / 34.3 |
+| pfH, Solari at 0.5 | 154 | 0.984 / 35.1 | 33 | 0.959 / 35.0 |
+| pfT, Solari at 0.35 | 153 | 0.980 / 33.8 | 25 | 0.950 / 33.1 |
+| pfD, whole frame 720 x 540 | 180 | 0.983 / 33.4 | 25 | 0.967 / 34.2 |
+| pfE, whole frame 960 x 720 | 165 | **0.987 / 36.6** | **37** | **0.978 / 38.6** |
+
+Solari's own GPU time (RAEA_SOLARI_TIMES) on t2: 18.5 ms at 0.5 scale (initial path 14.6, spatial and shade 2.7, world
+cache 1.1, light tiles 0.1), 31.7 ms at 960 x 720; by pixel count about 70 ms at full size.
+
+## What it says
+
+1. **t2 is not Solari's.** At 0.35 scale Solari takes 11 ms and the frame still takes 153. About 140 ms a frame in the
+ mall court goes to the rest: the composition's scene each frame (hundreds of LOD pieces, 88 baked water frames, the
+ arcade), raster, the look's FramePass chain and the encode. That is the biggest saving left, and it needs a CPU
+ and GPU profile of one t2 frame (xctrace), not a Solari change.
+2. **Render the tape at 960 x 720.** The VHS look keeps about 320 x 240 a field, so the whole frame at 960 x 720 (pfE)
+ is the best lever measured: t4 55% faster at SSIM 0.978, t2 about 15% faster, nearly at the floor. It beats scaling
+ Solari alone (pfC) on both time and picture, because raster and the look shrink with it.
+3. **One bounce is free in picture.** pfB sits at the floor on all three takes and saves 20% on t4: the world cache
+ already carries the light past the first bounce.
+4. **Fewer samples are not.** Halving spp saves little time (the cost is per pixel, not per sample, at these counts)
+ and costs PSNR (t2 37.2 to 32.6). The other way round, the noise notes on v3 (21, 22) are answered with more samples
+ on t5 and t8 only.
+5. t8's pfS and pfF score PSNR 19.8. Frame by frame it isn't a timing slip: pfS starts at 10 dB and climbs steadily to
+ 39 over the 240 frames (pfR holds 35-42 throughout). With fewer samples t8's light starts far off and takes about
+ 4 s to settle, most likely through its short world-cache life (`cache: { frames: 6 }`, set so the power cut drops
+ the light at once). In a take with a short cache, cutting samples costs seconds of wrong light, not noise.
+
+## The quality fix: light selection by power, not by count
+
+`generate_random_light_sample` (scene/sampling.wesl) picks a light source uniformly: `light_id = rand_range_u(light_count)`,
+and every pdf divides by `light_count` (sampling.wesl 131-175, realtime/restir.wesl 330, realtime/initial_path.wesl 370).
+Each emissive mesh, each directional light and each sky portal is one source. So:
+- a dim exit sign gets as many samples as the sun, and a scene with 300 emissive pieces gives the sun 1/300 of them:
+ noise where the sun matters (v3 notes 7, 21, 22);
+- a LOD swap or a set mounted mid-shot changes the count, so the sun's share jumps and the denoiser shows a one-frame
+ 2-5x brightness step (t2 v3: frames 1042, 2263, 3960, 4315, each a LOD swap). The composition now holds LOD levels a
+ take and mounts sets for the whole take, which works round it, not through it.
+
+Two ways to fix it in the fork, smallest first:
+- **A fixed share for the sky.** Directional lights and portals get a fixed probability q (0.5) split among them,
+ emissive meshes share 1 - q. The count of emissive pieces then never moves the sun's share. Needs the two counts in
+ a uniform and the sources kept in two runs (LightIndex's swap_remove keeps no order today), and the five pdf sites
+ changed to read the share by kind.
+- **Power-weighted (an alias table).** Each source weighted by its power (emissive luminance x area; a directional
+ light's illuminance; a portal's sky radiance x area), sampled in O(1) through an alias table rebuilt when the light
+ set changes. GpuLightSource grows from {kind, id} to {kind, id, pmf, threshold, alias}. The emissive-hit pdf (MIS in
+ the path tracer and initial_path) needs the hit's source pmf, so the instance needs its light index. ReSTIR DI's
+ light tiles inherit it for free, since they draw from generate_random_light_sample.
+
+Either needs a release build and a check on t2's four swap frames and t8; neither was built while MALL RAT v4 held the
+GPU.
+
+## The splotches: the world cache's history, and a bake (11-25)
+
+Shane on v4: "noisy splotchy thing in the lights and reflections ... it's definitely the world cache, can we bake it?"
+Each cell takes one bounce ray an update and blends it over a history capped at 32, but the adaptive cut
+(`alpha = |lum delta| / lum`, world_cache_update.wesl blend_new_samples) reads a cell's own noise as the light changing
+and holds the history near 10. Ten one-ray samples is the blotch: cell-sized patches that crawl.
+
+Built in the fork (vendor/bevy_solari, uncommitted, lane solari-bake to come):
+- `world_cache_steady`: the blend keeps the whole history up to `cache.frames`, with no adaptive cut, and each update's
+ ray seeded by the cell's sample count, so one cell's rays don't repeat. `cache.steady` in the SDK.
+- `world_cache_update_iterations`: N cache updates a frame. `cache.iterations` in the SDK.
+- `world_cache_keep`: no decay, so cells never die. `world_cache_save` / `world_cache_load`: the cache buffer
+ written to a file (bake.rs: a copy to a MAP_READ buffer, mapped and written before the next frame's pipelines) or
+ read into it and held (the whole world-cache stage skipped). `cache.bake: { iterations, save }` and
+ `cache.load` in the SDK.
+
+The bake doesn't fit. A cell's key holds its LOD band (stochastic between bands), its quantised position after a
+±half-cell jitter and a plane slice along the normal, so one surface seen from a moving camera makes many keys. With
+nothing decaying, t2's whole take filled all 2^20 slots, and so did each 6 s window of it (13 windows, each 100%).
+A cache that is full loses cells, and a loaded cache missing cells has holes. A bake would need larger cells, no
+jitter, or a cache sized to the take. So the live steady history is tried first: it gives the same convergence on
+the cells the camera sees (they are read each frame, so never die) with no file and no capacity limit. It costs a lag
+on light that moves, as long as the history: t8's power cut needs a short `frames`, as it has today.
+
+## The cache's level drifts with time and resolution (11-25)
+
+The same t2 frame (1188), median scene luminance: a cold single frame at 1440 x 1080 reads 0.0189 and at 160 x 240
+(the meter) 0.0177. Inside the long renders, the view reads 0.130 (7x) and the meter 0.0034 (0.2x). So the cache's
+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)
+
+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");
+`raea light steady`'s blotch is its size in one held frame.
+
+What others do about it that raea hasn't tried yet:
+- a longer denoiser history: NRD says history "can be bumped up to 60 frames relatively safely" to suppress residual
+ boiling, and Lumen's guides raise `MaxFramesAccumulated` (10 -> 16) before adding rays. MetalFX's history is the
+ next lever here;
+- blue-noise sampling (NRD: "reduced residual boiling in areas with acceptable sampling quality"), against Solari's white
+ hash noise;
+- a larger ReSTIR temporal cap with decorrelating mutations (Sawhney et al. 2024: boiling from hard indirect light is
+ resolved by a greater M cap, and mutations remove the blotches a larger cap brings), or RTXDI's boiling filter
+ (which loses energy);
+- for an offline render, a noise pattern held still across frames (Octane's "static noise"): a held shot can't boil,
+ though its grain stops moving.
+
+Measured with `raea light steady` (frame held, its light's movement over time; limit 1.5% blotch, worst tile 4.5%) on
+MALL RAT t2 frame 1188 (150 held, 75 measured), and the bench kitchen (STEADY 0.63 today). t2's runs of one setup spread
+by 0.1-0.4, so each setup that matters was run twice.
+
+| setup on t2 | blotch | verdict |
+|---|---|---|
+| today (1 path, ReSTIR, live cache) | 2.84-3.09 | fails |
+| the controls: raster, and the look's passes off | 0.0, 3.04 | the patches are Solari's |
+| world cache baked and frozen | 2.55 | the cache is not the main cause |
+| denoiser off / its guides off | grain 17.6, 2.9 | MetalFX passes the patches, doesn't make them |
+| ReSTIR off; its confidence cap 32; spatial radius 8 | 2.13; 3.03; 2.98 | ReSTIR adds, its settings don't fix |
+| 2x/4x direct-light samples; 64 small emissives removed; light selection by a sky share | no change | not the direct light |
+| denoiser and ReSTIR off, cache frozen: the raw light | 98% per-pixel grain, white in space and time | one path's bounce has a sd as large as its mean |
+| **paths 4 / 8** (new: N initial paths a pixel, RIS-merged) | **1.89 / 2.10** | halves it |
+| paths 8 + frozen cache | 1.45, 1.53 | on the line |
+| paths 8 + steady cache (1024 history, 8 updates) | 1.65, 1.69 | |
+| paths 4-8 + steady + still-camera query (no jitter, one LOD) | 1.66-1.88 | no better |
+| paths 8, ReSTIR off, steady / frozen | 1.60, 1.69 / 1.54 | |
+| paths 8 + frozen, camera jitter off | 1.31 (the one pass) | jitter isn't the floor |
+
+Bias: the kitchen's mean at 4 paths against 1 is +0.0015 stops (per-pixel median 0); with the steady cache and still
+query +0.0013. Glade's moving shot (the still query off while it moves): flicker 0.708 against 0.702. Cost on t2: a
+150-frame hold 50 s at 1 path, 82-94 s at 4, 112 s at 8; glade 1.72 -> 2.47 s a still at 4.
+
+So: `paths` is the lever that ships (default 1; MALL RAT's takes set it). It takes t2 from about 3.0 to 1.6-1.9, which
+still fails the gate. The rest is the world cache: a frozen one reads 0.1-0.3 lower than any live one at the same paths,
+and the live cache made to converge (steady history, more updates, the still-camera query) doesn't close the gap. Left
+for the next release: a cache that converges like the frozen one (cells kept for a held shot without the 2^20 overflow:
+a bigger or per-take cache, or ReSTIR GI's reservoirs carrying the cache's light), then t2 again.
+
+Built in the fork, all off unless asked: `paths` (SolariLighting::paths_per_pixel, RAEA_SOLARI_PATHS), `cache.steady`
+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).
diff --git a/engine/light/src/lib.rs b/engine/light/src/lib.rs
index 2e7c037c..2f12507a 100644
--- a/engine/light/src/lib.rs
+++ b/engine/light/src/lib.rs
@@ -351,7 +351,7 @@ pub fn light(args: &[String]) -> R<String> {
// won't be the same the next time
let moved: Vec<String> = reports.iter().flat_map(|r| r["paths"].as_object().into_iter().flatten().filter(|(_, p)| p["steady"]["steady"] == json!(false)).map(|(path, p)| format!("{} on {path}: {}", r["name"].as_str().unwrap_or(""), steady::line(&p["steady"])))).collect();
if !moved.is_empty() {
- return Err(format!("{said}\nthe light doesn't hold still ({}). {}", moved.join("; "), steady::WHY));
+ return Err(format!("{said}\nthe light boils ({}). {}", moved.join("; "), steady::WHY));
}
Ok(said)
}
diff --git a/engine/light/src/steady.rs b/engine/light/src/steady.rs
index 10c3eedf..49e2471d 100644
--- a/engine/light/src/steady.rs
+++ b/engine/light/src/steady.rs
@@ -163,8 +163,8 @@ pub fn line(r: &Value) -> String {
)
}
-/// What a light that doesn't hold still is told.
-pub const WHY: &str = "Patches this size are light built over frames that hasn't settled: on Solari 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";
+/// 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";
pub fn steady(args: &[String]) -> R<String> {
let first = args.first().ok_or(format!("usage: {USAGE}"))?;
@@ -201,9 +201,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 doesn't hold still: {said}. {WHY}")) };
+ return if r["steady"] == json!(true) { Ok(format!("STEADY {said}")) } else { Err(format!("the light boils: {said}. {WHY}")) };
}
- if r["steady"] == json!(true) { Ok(format!("STEADY {}", line(&r))) } else { Err(format!("the light doesn't hold still: {}. {WHY}", line(&r))) }
+ if r["steady"] == json!(true) { Ok(format!("STEADY {}", line(&r))) } else { Err(format!("the light boils: {}. {WHY}", line(&r))) }
}
#[cfg(test)]
diff --git a/sdk/guides/craft/bevy/solari.md b/sdk/guides/craft/bevy/solari.md
index 31f74883..47358614 100644
--- a/sdk/guides/craft/bevy/solari.md
+++ b/sdk/guides/craft/bevy/solari.md
@@ -104,6 +104,35 @@ frames path-traced (FLIP, bias, flicker, blotches, lag after a doorway opens or
looks wrong as a case. A take's own passes after the denoiser (a lens, a grade) aren't evidence about it: bench the
view without them.
+## Boiling: soft patches that crawl
+
+Boiling is what real-time path tracing's leftover noise looks like once a denoiser has smoothed it: soft patches tens of
+pixels across that crawl over floors, walls and reflections in a shot that should hold still, each frame a little
+different. A still frame can look clean while the shot boils, so judge it held, never from one frame. It's the industry's
+word (NVIDIA's NRD and RTXDI, AMD's GI-1.0, the ReSTIR papers, Lumen's guides), and raea uses it for this alone. A toon
+look's line boil (`boil`, a drawn line wobbling on twos) is a different thing; say "light boiling" when both are about.
+
+Tell it from its neighbours:
+- **flicker**: a region's brightness jumps (a light count changing, exposure hunting), rather than patches crawling;
+- **fireflies**: lone bright pixels, from a tiny, very bright emitter;
+- **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).
+
+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
+ turn that into patches. `<SolariLighting paths={4} />` traces 4 paths a pixel and halves it, at about 1.7x the
+ frame (8 paths: a little more, at 2.2x). This is the fix to reach for first, on any sunlit interior.
+2. **ReSTIR's reuse.** Neighbouring pixels and frames share a few good samples, so their errors move together (the
+ 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.
+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.
+
## Why
Solari is real-time path tracing in three parts. Direct light picks among the emissive triangles and the sun with
@@ -129,6 +158,8 @@ WESL), not a post written for an older one.
- Walls of `Plane3d`: light leaks along their edges. Use boxes.
- No `reset` at a cut made by moving the one camera: the new shot's first frames carry the old shot's light.
- A tiny, very bright emitter (a 1 cm LED at 100,000): fireflies. Make it bigger and dimmer, or turn on `restir`.
+- A sunlit interior at one path a pixel: it boils (Boiling, above). Set `paths={4}` and hold a frame with
+ `raea light steady` before the whole render.
- Judging reflections from one still. Check a moving shot for smearing.
- A glow pitched for raster (`emissive` 2) in a traced scene: it's black. Pitch it in the traced light's units.
- Following a 0.17 or 0.18 example: the API and the defaults have changed since.
diff --git a/sdk/render/src/bevy3d/raytracing.tsx b/sdk/render/src/bevy3d/raytracing.tsx
index 5d0c5cf4..7e818ddf 100644
--- a/sdk/render/src/bevy3d/raytracing.tsx
+++ b/sdk/render/src/bevy3d/raytracing.tsx
@@ -21,6 +21,9 @@ export interface SolariLightingProps {
/** the chance a pixel traces its first bounce this frame, its light divided by it (Russian roulette): 0.5 halves the
* bounce's tracing, most of a dense forest's (1, every pixel every frame) */
firstBounce?: number;
+ /** 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;
/** 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) */
@@ -32,9 +35,21 @@ export interface SolariLightingProps {
/** about how many cells are updated a frame (40000) */
updates?: number;
/** a nearest cell's size, metres (0.15) */
+ /** keep each cell's whole history (up to frames), not cut short when its own noise reads as the light changing */
+ steady?: boolean;
+ /** cache updates a frame (1): more converge faster */
+ iterations?: number;
cellSize?: number;
/** how fast cells grow with distance from the camera (15) */
lodScale?: number;
+ /** bake the cache (docs/solari-efficiency.md): render the take's own camera path with it and every cell it meets
+ * stays, keeps its whole history (set `frames` long, 4096 or more) and updates `iterations` times a frame (1).
+ * `save` names the file to write this frame: give it a few frames before the bake's last */
+ bake?: { iterations?: number; save?: string };
+ /** a baked cache's file (`bake.save`), read and held while the shot renders: no updates, nothing ages out, a cut
+ * doesn't empty it. Another name later in the shot reads that one (a take whose lights change at a cut). Its sets
+ * and lights must be the bake's: what moved since is lit as the bake saw it */
+ load?: string;
};
/** draw the view at this fraction of its size a side (a third to 1) and let MetalFX's temporal scaler bring it up to
* the full size, so a game traces fewer pixels: 0.67 traces 45% of them (RT9). On the Mac; elsewhere it draws at the
@@ -218,6 +233,8 @@ export function SolariLighting(p: SolariLightingProps = {}) {
field("secondarySamples", "secondary_di_samples", p.secondarySamples, true);
if (p.firstBounce !== undefined && !(p.firstBounce > 0 && p.firstBounce <= 1)) throw new RangeError(`SolariLighting: firstBounce is a chance above 0, up to 1, got ${p.firstBounce}`);
field("firstBounce", "first_bounce_probability", p.firstBounce);
+ 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);
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);
@@ -225,6 +242,19 @@ export function SolariLighting(p: SolariLightingProps = {}) {
field("cache.updates", "world_cache_cell_updates_soft_target", c.updates, true);
field("cache.cellSize", "world_cache_position_base_cell_size", c.cellSize);
field("cache.lodScale", "world_cache_position_lod_scale", c.lodScale);
+ // steady: the cache's light kept over its whole history (up to cache.frames), never cut short when a cell's own noise
+ // reads as change; iterations: that many cache updates a frame. Light that holds still converges instead of crawling
+ // (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.bake) {
+ value.world_cache_keep = true;
+ value.world_cache_steady = true;
+ field("cache.bake.iterations", "world_cache_update_iterations", c.bake.iterations ?? 1, true);
+ }
+ if (c.bake && c.load) throw new RangeError("SolariLighting: cache.bake and cache.load together: a bake gathers the cache, a load holds one already baked");
+ // both always written: a value left out may keep the last frame's, and a save that stuck would write every frame
+ if (c.bake || c.load) { value.world_cache_save = c.bake?.save ?? ""; value.world_cache_load = c.load ?? ""; }
const settings = solariSettings(p);
const constants = solariConstants(p.constants);
const lighting = <BevyComponent type="bevy_solari::realtime::SolariLighting" value={value} />;
diff --git a/vendor/bevy_solari/src/realtime/bake.rs b/vendor/bevy_solari/src/realtime/bake.rs
new file mode 100644
index 00000000..1fb0e842
--- /dev/null
+++ b/vendor/bevy_solari/src/realtime/bake.rs
@@ -0,0 +1,43 @@
+//! raea: a baked world cache written out (SolariLighting::world_cache_save). The node copies the cache into a buffer
+//! it can map at the end of the frame's update; a later frame, once that copy has run, maps it and writes the file.
+//! A bake asks a few frames before its last, so the final frame's node finds the write still to finish.
+use super::prepare::{WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET, WORLD_CACHE_BUFFER_SIZE};
+use std::sync::Mutex;
+
+static PENDING: Mutex<Vec<(wgpu::Buffer, String)>> = Mutex::new(Vec::new());
+
+pub fn save(device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, cache: &wgpu::Buffer, path: &str) {
+ let read = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("solari_world_cache_bake"),
+ size: WORLD_CACHE_BUFFER_SIZE,
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ encoder.copy_buffer_to_buffer(cache, 0, &read, 0, WORLD_CACHE_BUFFER_SIZE);
+ PENDING.lock().unwrap().push((read, path.to_string()));
+}
+
+pub fn finish(device: &wgpu::Device) {
+ let pending: Vec<_> = std::mem::take(&mut *PENDING.lock().unwrap());
+ for (read, path) in pending {
+ let slice = read.slice(..);
+ slice.map_async(wgpu::MapMode::Read, |_| {});
+ if let Err(e) = device.poll(wgpu::PollType::wait_indefinitely()) {
+ eprintln!("raea: REFUSED the world cache bake {path}: the device: {e}");
+ continue;
+ }
+ let bytes = match slice.get_mapped_range() {
+ Ok(view) => view.to_vec(),
+ Err(e) => { eprintln!("raea: REFUSED the world cache bake {path}: its copy: {e}"); continue; }
+ };
+ read.unmap();
+ let at = WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET as usize;
+ let cells = u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]);
+ if let Some(dir) = std::path::Path::new(&path).parent() { let _ = std::fs::create_dir_all(dir); }
+ match std::fs::write(&path, &bytes) {
+ // a cache over about half full has started losing cells to collisions (3 probes): say so
+ Ok(()) => eprintln!("raea: the world cache baked to {path} ({cells} cells, {:.0}% of its {} slots{})", 100.0 * cells as f64 / (super::prepare::WORLD_CACHE_SIZE as f64), super::prepare::WORLD_CACHE_SIZE, if cells as u64 > super::prepare::WORLD_CACHE_SIZE / 2 { "; over half full, cells are being lost: bake with larger cells (cache.cellSize)" } else { "" }),
+ Err(e) => eprintln!("raea: REFUSED the world cache bake {path}: {e}"),
+ }
+ }
+}
diff --git a/vendor/bevy_solari/src/realtime/bindings.wesl b/vendor/bevy_solari/src/realtime/bindings.wesl
index 97ad5b96..540f1a48 100644
--- a/vendor/bevy_solari/src/realtime/bindings.wesl
+++ b/vendor/bevy_solari/src/realtime/bindings.wesl
@@ -57,9 +57,12 @@ struct SolariLightingSettings {
reset: u32,
// raea: SolariLighting::first_bounce_probability (prepare.rs), and padding
first_bounce_probability: f32,
- pad0: u32,
- pad1: u32,
- pad2: u32,
+ // raea: bit 0 SolariLighting::world_cache_steady, bit 1 that and the camera where it was last frame (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,
}
/// 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/initial_path.wesl b/vendor/bevy_solari/src/realtime/initial_path.wesl
index babba612..d6feda93 100644
--- a/vendor/bevy_solari/src/realtime/initial_path.wesl
+++ b/vendor/bevy_solari/src/realtime/initial_path.wesl
@@ -5,7 +5,7 @@ import bevy_render::utils::octahedral_encode;
import package::scene::brdf::{brdf_pdf, evaluate_and_sample_brdf, evaluate_brdf, EvaluateAndSampleBrdfResult, F_AB};
import package::realtime::presample_light_tiles::unpack_resolved_light_sample;
import package::realtime::bindings::{empty_reservoir, light_tile_resolved_samples, light_tile_samples, Reservoir, constants, view};
-import package::scene::sampling::{calculate_resolved_light_contribution, isinf, LightSample, NULL_LIGHT_ID, power_heuristic, trace_visibility, sample_environment_map_light_and_sun, sky_portal_mis_weight};
+import package::scene::sampling::{calculate_resolved_light_contribution, emissive_light_pmf, isinf, LightSample, NULL_LIGHT_ID, power_heuristic, trace_visibility, sample_environment_map_light_and_sun, sky_portal_mis_weight};
import package::scene::bindings::{face_hit, light_sources, MIRROR_ROUGHNESS_THRESHOLD, RAY_T_MAX, RAY_T_MIN, resolve_ray_hit_full, ResolvedMaterial, ResolvedRayHitFull, trace_ray};
import package::realtime::world_cache_query::{get_cell_size, query_world_cache, query_world_cache_found, WORLD_CACHE_CELL_LIFETIME};
@@ -30,6 +30,44 @@ const GLOSSY_NEE_FLOOR = 0.25;
struct InitialSamplingResult {
@if(RESTIR) reservoir: Reservoir,
radiance: vec3<f32>,
+ // raea: the target function of the reservoir's chosen candidate (its weight is the contribution weight times it)
+ @if(RESTIR) chosen_target: f32,
+}
+
+// raea (11-25): constants.paths_per_pixel paths from the same G-buffer surface. Their directly shaded light is
+// averaged; their reservoirs are resampled into one, path i chosen in proportion to its weight w_i (its contribution
+// weight times its candidate's target), the result's contribution weight (sum w_i / N) / target. One path is upstream's
+fn generate_initial_paths(world_position: vec3<f32>, world_normal: vec3<f32>, material: ResolvedMaterial, workgroup_id: vec2<u32>, pixel_id: vec2<u32>, rng: ptr<function, u32>) -> InitialSamplingResult {
+ let n = max(constants.paths_per_pixel, 1u);
+ if n == 1u { return generate_initial_path(world_position, world_normal, material, workgroup_id, pixel_id, rng); }
+ var out: InitialSamplingResult;
+ out.radiance = vec3(0.0);
+ @if(RESTIR) {
+ out.reservoir = empty_reservoir();
+ out.reservoir.confidence_weight = 1.0;
+ out.chosen_target = 0.0;
+ }
+ var weight_sum = 0.0;
+ for (var i = 0u; i < n; i++) {
+ let path = generate_initial_path(world_position, world_normal, material, workgroup_id, pixel_id, rng);
+ out.radiance += path.radiance;
+ @if(RESTIR) {
+ let w = path.reservoir.unbiased_contribution_weight * path.chosen_target;
+ if w > 0.0 {
+ weight_sum += w;
+ if rand_f(rng) < w / weight_sum {
+ out.reservoir = path.reservoir;
+ out.chosen_target = path.chosen_target;
+ }
+ }
+ }
+ }
+ out.radiance /= f32(n);
+ @if(RESTIR) {
+ out.reservoir.confidence_weight = 1.0;
+ out.reservoir.unbiased_contribution_weight = select(0.0, (weight_sum / f32(n)) / out.chosen_target, out.chosen_target > 0.0);
+ }
+ return out;
}
/// Path vertices use the following convention: x0 = camera, x1 = primary ray hit (the G-buffer
@@ -227,8 +265,10 @@ fn generate_initial_path(world_position: vec3<f32>, world_normal: vec3<f32>, mat
var result: InitialSamplingResult;
result.radiance = path.radiance;
@if(RESTIR) {
+ result.chosen_target = 0.0;
if path.selected_target_function > 0.0 {
path.reservoir.unbiased_contribution_weight = path.weight_sum / path.selected_target_function;
+ result.chosen_target = path.selected_target_function;
}
result.reservoir = path.reservoir;
}
@@ -367,8 +407,7 @@ fn generate_emissive_candidate(
rng: ptr<function, u32>,
) {
let NdotV_hit = max(dot(ray_hit.world_normal, -wi), 0.0001);
- let light_count = arrayLength(&light_sources);
- let area_pdf = 1.0 / (f32(light_count) * f32(ray_hit.triangle_count) * ray_hit.triangle_area);
+ let area_pdf = emissive_light_pmf() / (f32(ray_hit.triangle_count) * ray_hit.triangle_area);
let p_light = area_pdf * ray_t * ray_t / NdotV_hit;
let emissive_mis_weight = power_heuristic(p_brdf, p_light * p_nee * f32(di_samples));
diff --git a/vendor/bevy_solari/src/realtime/mod.rs b/vendor/bevy_solari/src/realtime/mod.rs
index f9cac0f7..e7acc106 100644
--- a/vendor/bevy_solari/src/realtime/mod.rs
+++ b/vendor/bevy_solari/src/realtime/mod.rs
@@ -1,3 +1,4 @@
+mod bake;
mod extract;
// raea: the denoiser guides (primary surface replacement) without DLSS
mod guides;
@@ -167,6 +168,14 @@ pub struct SolariLighting {
/// Defaults to `1.0` (every pixel, every frame).
pub first_bounce_probability: f32,
+ /// raea (11-25): initial paths traced a pixel a frame, 1 to 16. One path a pixel on MALL RAT's sunlit court has a
+ /// standard deviation as large as its mean (raea light steady, denoiser and ReSTIR off: white noise), which ReSTIR's
+ /// reuse and the denoiser turn into patches that crawl. N paths cut that variance N times: their directly shaded
+ /// light averaged, their reservoirs resampled into one (RIS over the N). Costs N times the initial path's rays.
+ ///
+ /// Defaults to `1`.
+ pub paths_per_pixel: u32,
+
/// How responsive the world cache is to changes in lighting.
///
/// Higher values accumulate more temporal history, giving more stable but
@@ -230,6 +239,26 @@ pub struct SolariLighting {
/// After setting this to true, it will automatically be toggled
/// back to false at the end of the frame.
pub reset: bool,
+
+ /// raea: the world cache baked (docs/solari-efficiency.md). A take's lights and sets hold still, so its cache can be
+ /// gathered once, converged, and read back while it renders: a live cell takes one bounce ray a frame and keeps a
+ /// short history, and each cell's own error is a blotch the denoiser spreads over floors, walls and reflections.
+ ///
+ /// Cells never age out while set: a bake keeps every cell its camera path meets. A reset still empties the cache.
+ pub world_cache_keep: bool,
+ /// raea: each cell keeps its whole history (up to `world_cache_max_temporal_samples`) instead of shortening it when
+ /// its light changes, which a cell's own noise reads as. For a bake, with a long history.
+ pub world_cache_steady: bool,
+ /// 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: 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,
+ /// raea: read the cache from this file (a bake's `world_cache_save`) and hold it: no decay, no updates, and a reset
+ /// doesn't empty it. Read again when the name changes (a take whose lights change at a cut: one bake each side).
+ /// A cell the bake never met stays empty and a path that finds it carries on tracing. Empty: the live cache.
+ pub world_cache_load: String,
}
impl Default for SolariLighting {
@@ -241,6 +270,7 @@ impl Default for SolariLighting {
secondary_di_samples: 4,
max_bounces: 3,
first_bounce_probability: 1.0,
+ paths_per_pixel: 1,
world_cache_max_temporal_samples: 32.0,
world_cache_direct_light_sample_count: 32,
world_cache_max_gi_ray_distance: 1000.0,
@@ -248,6 +278,11 @@ impl Default for SolariLighting {
world_cache_position_base_cell_size: 0.15,
world_cache_position_lod_scale: 15.0,
reset: true, // No temporal history on the first frame
+ world_cache_keep: false,
+ world_cache_steady: false,
+ world_cache_update_iterations: 1,
+ world_cache_save: String::new(),
+ world_cache_load: String::new(),
}
}
}
diff --git a/vendor/bevy_solari/src/realtime/no_restir.wesl b/vendor/bevy_solari/src/realtime/no_restir.wesl
index f15fcd02..32ca31db 100644
--- a/vendor/bevy_solari/src/realtime/no_restir.wesl
+++ b/vendor/bevy_solari/src/realtime/no_restir.wesl
@@ -1,5 +1,5 @@
import package::realtime::gbuffer_utils::gpixel_resolve;
-import package::realtime::initial_path::generate_initial_path;
+import package::realtime::initial_path::generate_initial_paths;
import package::realtime::bindings::{constants, depth_buffer, gbuffer, view, view_output};
import package::scene::bindings::RAY_T_MAX;
import package::realtime::world_cache_query::{query_world_cache, WORLD_CACHE_CELL_LIFETIME};
@@ -18,7 +18,8 @@ fn initial_and_shade(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(gl
let surface = gpixel_resolve(textureLoad(gbuffer, global_id.xy, 0), depth, global_id.xy, view.main_pass_viewport.zw, view.world_from_clip);
- let path = generate_initial_path(surface.world_position, surface.world_normal, surface.material, workgroup_id.xy, global_id.xy, &rng);
+ // raea: SolariLighting::paths_per_pixel paths, merged (initial_path.wesl generate_initial_paths)
+ let path = generate_initial_paths(surface.world_position, surface.world_normal, surface.material, workgroup_id.xy, global_id.xy, &rng);
var pixel_color = path.radiance;
pixel_color += surface.material.emissive;
diff --git a/vendor/bevy_solari/src/realtime/node.rs b/vendor/bevy_solari/src/realtime/node.rs
index 3715cca5..8ef79e21 100644
--- a/vendor/bevy_solari/src/realtime/node.rs
+++ b/vendor/bevy_solari/src/realtime/node.rs
@@ -69,6 +69,7 @@ type SolariLightingViewQuery = (
&'static ViewUniformOffset,
&'static PreviousViewUniformOffset,
Option<&'static super::guides::SolariGuideTextures>,
+ &'static super::SolariLighting,
);
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
@@ -80,6 +81,7 @@ type SolariLightingViewQuery = (
&'static PreviousViewUniformOffset,
Option<&'static ViewDlssRayReconstructionTextures>,
Option<&'static super::guides::SolariGuideTextures>,
+ &'static super::SolariLighting,
);
pub fn solari_lighting(
@@ -101,6 +103,7 @@ pub fn solari_lighting(
view_uniform_offset,
previous_view_uniform_offset,
view_guides,
+ settings,
) = view.into_inner();
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
@@ -112,6 +115,7 @@ pub fn solari_lighting(
previous_view_uniform_offset,
view_dlss_rr_textures,
view_guides,
+ settings,
) = view.into_inner();
// raea: DLSS-RR's guides, else guides.rs's, both written by the same passes
@@ -126,6 +130,9 @@ pub fn solari_lighting(
[&d.diffuse_albedo, &d.specular_albedo, &d.normal_roughness, &d.depth, &d.specular_motion_vectors]
}));
+ // raea: a bake's earlier writes, submitted since, finished to their files
+ super::bake::finish(render_device.wgpu_device());
+
let Some(pipelines) = solari_pipelines else {
return;
};
@@ -335,13 +342,19 @@ pub fn solari_lighting(
d.end(&mut pass);
drop(pass);
+ // raea: a baked cache (SolariLighting::world_cache_load) is held: no decay, no compaction, no update, so neither
+ // time nor a reset changes it. A bake (world_cache_keep) skips the decay but on a reset, so every cell its camera
+ // path meets stays, and runs the update world_cache_update_iterations times
+ let frozen = !settings.world_cache_load.is_empty();
let mut pass = stage!("solari_lighting/world_cache", 1);
let d = diagnostics.time_span(&mut pass, "solari_lighting/world_cache");
-
+ if !frozen {
pass.set_bind_group(2, &bind_group_world_cache_active_cells_dispatch, &[]);
- pass.set_pipeline(decay_world_cache_pipeline);
- pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1);
+ if !settings.world_cache_keep || settings.reset {
+ pass.set_pipeline(decay_world_cache_pipeline);
+ pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1);
+ }
pass.set_pipeline(compact_world_cache_single_block_pipeline);
pass.dispatch_workgroups((WORLD_CACHE_SIZE / 1024) as u32, 1, 1);
@@ -354,27 +367,36 @@ pub fn solari_lighting(
pass.set_bind_group(2, None, &[]);
- pass.set_pipeline(sample_di_for_world_cache_pipeline);
- pass.dispatch_workgroups_indirect(
- &solari_lighting_resources.world_cache_active_cells_dispatch,
- 0,
- );
+ for _ in 0..settings.world_cache_update_iterations.max(1) {
+ pass.set_pipeline(sample_di_for_world_cache_pipeline);
+ pass.dispatch_workgroups_indirect(
+ &solari_lighting_resources.world_cache_active_cells_dispatch,
+ 0,
+ );
- pass.set_pipeline(sample_gi_for_world_cache_pipeline);
- pass.dispatch_workgroups_indirect(
- &solari_lighting_resources.world_cache_active_cells_dispatch,
- 0,
- );
+ pass.set_pipeline(sample_gi_for_world_cache_pipeline);
+ pass.dispatch_workgroups_indirect(
+ &solari_lighting_resources.world_cache_active_cells_dispatch,
+ 0,
+ );
- pass.set_pipeline(blend_new_world_cache_samples_pipeline);
- pass.dispatch_workgroups_indirect(
- &solari_lighting_resources.world_cache_active_cells_dispatch,
- 0,
- );
+ pass.set_pipeline(blend_new_world_cache_samples_pipeline);
+ pass.dispatch_workgroups_indirect(
+ &solari_lighting_resources.world_cache_active_cells_dispatch,
+ 0,
+ );
+ }
+ }
d.end(&mut pass);
drop(pass);
+ // raea: a bake's write (SolariLighting::world_cache_save): the cache copied out at the end of this frame's update
+ // and written to the file by a later frame, once this one has been submitted (bake::finish)
+ if !settings.world_cache_save.is_empty() {
+ super::bake::save(render_device.wgpu_device(), command_encoder, &solari_lighting_resources.world_cache, &settings.world_cache_save);
+ }
+
let mut pass = stage!("solari_lighting/initial", 2);
let d = diagnostics.time_span(&mut pass, "solari_lighting/lighting");
diff --git a/vendor/bevy_solari/src/realtime/prepare.rs b/vendor/bevy_solari/src/realtime/prepare.rs
index 6e80c326..fbc33c4b 100644
--- a/vendor/bevy_solari/src/realtime/prepare.rs
+++ b/vendor/bevy_solari/src/realtime/prepare.rs
@@ -11,7 +11,7 @@ use bevy_ecs::query::Has;
use bevy_ecs::{
component::Component,
entity::Entity,
- system::{Commands, Query, Res},
+ system::{Commands, Local, Query, Res},
};
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
use bevy_image::ToExtents;
@@ -77,11 +77,18 @@ struct SolariLightingUniforms {
reset: u32,
// raea: SolariLighting::first_bounce_probability, padded to keep the uniform a multiple of 16 bytes
first_bounce_probability: f32,
- pad: [u32; 3],
+ // raea: SolariLighting::world_cache_steady (a bake's cells keep their whole history and draw new random numbers
+ // each update in a frame)
+ world_cache_steady: u32,
+ // raea (11-25): ReSTIR's spatial reuse radius in pixels, Bevy's 30 unless RAEA_SOLARI_SPATIAL_RADIUS says; a 30 px
+ // disc is the size of the patches MALL RAT's held frames show (raea light steady)
+ spatial_reuse_radius: f32,
+ // raea (11-25): SolariLighting::paths_per_pixel (RAEA_SOLARI_PATHS overrides it)
+ paths_per_pixel: u32,
}
impl SolariLightingUniforms {
- fn new(settings: &SolariLighting, frame_count: u32, force_reset: bool) -> Self {
+ fn new(settings: &SolariLighting, frame_count: u32, force_reset: bool, still: bool) -> Self {
Self {
confidence_weight_cap: settings.confidence_weight_cap,
primary_di_samples: settings.primary_di_samples,
@@ -96,7 +103,10 @@ impl SolariLightingUniforms {
frame_rng: frame_count.wrapping_mul(5782582),
reset: (settings.reset || force_reset) as u32,
first_bounce_probability: settings.first_bounce_probability.clamp(0.05, 1.0),
- pad: [0; 3],
+ // 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),
+ spatial_reuse_radius: spatial_reuse_radius(),
+ paths_per_pixel: paths_override().unwrap_or(settings.paths_per_pixel).clamp(1, 16),
}
}
}
@@ -125,6 +135,30 @@ pub struct SolariLightingResources {
pub world_cache: Buffer,
pub world_cache_active_cells_dispatch: Buffer,
pub view_size: UVec2,
+ /// raea: the baked cache file this view's world cache holds (SolariLighting::world_cache_load), "" for none
+ pub world_cache_loaded: std::sync::Arc<std::sync::Mutex<String>>,
+}
+
+/// raea: read a baked world cache (SolariLighting::world_cache_save) into a view's cache buffer. A file of another size
+/// (another build's cache layout) is refused, said once, and the view keeps its live cache.
+fn load_world_cache(render_queue: &RenderQueue, buffer: &Buffer, path: &str) -> bool {
+ match std::fs::read(path) {
+ Ok(bytes) if bytes.len() as u64 == WORLD_CACHE_BUFFER_SIZE => {
+ render_queue.write_buffer(buffer, 0, &bytes);
+ let at = WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET as usize;
+ let cells = u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]);
+ eprintln!("raea: the world cache baked in {path} read ({cells} cells); held while it renders");
+ true
+ }
+ Ok(bytes) => {
+ eprintln!("raea: REFUSED the baked world cache {path}: {} bytes, this build's cache is {WORLD_CACHE_BUFFER_SIZE} (bake it again with this raea); the live cache is used", bytes.len());
+ false
+ }
+ Err(e) => {
+ eprintln!("raea: REFUSED the baked world cache {path}: {e}; the live cache is used");
+ false
+ }
+ }
}
pub struct SolariReservoirBuffers {
@@ -151,6 +185,9 @@ pub fn prepare_solari_lighting_resources(
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
frame_count: Res<FrameCount>,
+ // raea (11-25): each view's camera last frame, so the cache knows when it holds still (world_cache_still)
+ views: Query<&bevy_render::view::ExtractedView>,
+ mut last_camera: Local<std::collections::HashMap<Entity, bevy_math::Mat4>>,
// raea: the guides for a denoiser other than DLSS-RR (guides.rs)
guides: Option<Res<super::guides::SolariGuideBuffers>>,
mut commands: Commands,
@@ -179,8 +216,13 @@ pub fn prepare_solari_lighting_resources(
let reusable = solari_lighting_resources.filter(|r| {
r.view_size == view_size && r.reservoirs.is_some() == solari_lighting.restir
});
+ let camera_now = views.get(entity).map(|v| v.world_from_view.to_matrix()).ok();
+ let still = camera_now.is_some() && last_camera.get(&entity).copied() == camera_now;
+ if let Some(m) = camera_now {
+ last_camera.insert(entity, m);
+ }
let uniforms =
- SolariLightingUniforms::new(solari_lighting, frame_count.0, reusable.is_none());
+ SolariLightingUniforms::new(solari_lighting, frame_count.0, reusable.is_none(), still);
if let Some(solari_lighting_resources) = reusable {
// The constants uniform can change every frame, so always upload it.
@@ -189,6 +231,12 @@ pub fn prepare_solari_lighting_resources(
0,
bytemuck::bytes_of(&uniforms),
);
+ // raea: a baked cache named for the first time, or another one (a cut between two bakes)
+ let mut loaded = solari_lighting_resources.world_cache_loaded.lock().unwrap();
+ if !solari_lighting.world_cache_load.is_empty() && *loaded != solari_lighting.world_cache_load {
+ load_world_cache(&render_queue, &solari_lighting_resources.world_cache, &solari_lighting.world_cache_load);
+ *loaded = solari_lighting.world_cache_load.clone();
+ }
continue;
}
@@ -232,9 +280,15 @@ pub fn prepare_solari_lighting_resources(
let world_cache = render_device.create_buffer(&BufferDescriptor {
label: Some("solari_lighting_world_cache"),
size: WORLD_CACHE_BUFFER_SIZE,
- usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
+ usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC | BufferUsages::COPY_DST,
mapped_at_creation: false,
});
+ // raea: a baked cache, read in place of the live one's empty start
+ let mut world_cache_loaded = String::new();
+ if !solari_lighting.world_cache_load.is_empty() {
+ load_world_cache(&render_queue, &world_cache, &solari_lighting.world_cache_load);
+ world_cache_loaded = solari_lighting.world_cache_load.clone();
+ }
let world_cache_active_cells_dispatch = render_device.create_buffer(&BufferDescriptor {
label: Some("solari_lighting_world_cache_active_cells_dispatch"),
@@ -251,6 +305,7 @@ pub fn prepare_solari_lighting_resources(
world_cache,
world_cache_active_cells_dispatch,
view_size,
+ world_cache_loaded: std::sync::Arc::new(std::sync::Mutex::new(world_cache_loaded)),
});
if guides.is_some() {
commands
@@ -350,3 +405,22 @@ pub fn prepare_solari_lighting_resources(
}
}
}
+
+/// raea: ReSTIR's spatial reuse radius in pixels (restir.wesl), 30 as Bevy has it unless RAEA_SOLARI_SPATIAL_RADIUS says
+fn spatial_reuse_radius() -> f32 {
+ static R: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
+ *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_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();
+ *P.get_or_init(|| std::env::var("RAEA_SOLARI_PATHS").ok().and_then(|v| v.parse::<u32>().ok()).filter(|v| *v >= 1))
+}
+
+/// raea: RAEA_SOLARI_STEADY=1, the steady cache for every camera whatever the composition asks (a check on a scene that
+/// doesn't set cache.steady)
+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"))
+}
diff --git a/vendor/bevy_solari/src/realtime/restir.wesl b/vendor/bevy_solari/src/realtime/restir.wesl
index 9d70028e..fe535575 100644
--- a/vendor/bevy_solari/src/realtime/restir.wesl
+++ b/vendor/bevy_solari/src/realtime/restir.wesl
@@ -5,9 +5,9 @@ import bevy_pbr::render::utils::{rand_f, rand_u, sample_disk};
import bevy_render::utils::octahedral_decode;
import package::scene::brdf::{brdf_pdf, evaluate_brdf, F_AB};
import package::realtime::gbuffer_utils::{gpixel_resolve, permute_pixel, pixel_dissimilar};
-import package::realtime::initial_path::{generate_initial_path, InitialSamplingResult};
+import package::realtime::initial_path::{generate_initial_paths, InitialSamplingResult};
import package::realtime::bindings::{depth_buffer, empty_reservoir, gbuffer, load_motion_vector, previous_depth_buffer, previous_gbuffer, previous_view, reservoirs_a, reservoirs_b, Reservoir, constants, view, view_output};
-import package::scene::sampling::{balance_heuristic, calculate_resolved_light_contribution, isinf, isnan, LightSample, NULL_LIGHT_ID, power_heuristic, resolve_light_sample, ResolvedLightSample, trace_visibility, trace_visibility_previous_frame, ray_origin_toward_sample};
+import package::scene::sampling::{balance_heuristic, light_pmf, calculate_resolved_light_contribution, isinf, isnan, LightSample, NULL_LIGHT_ID, power_heuristic, resolve_light_sample, ResolvedLightSample, trace_visibility, trace_visibility_previous_frame, ray_origin_toward_sample};
import package::scene::bindings::{light_sources, LIGHT_NOT_PRESENT_THIS_FRAME, previous_frame_light_id_translations, RAY_T_MAX, RAY_T_MIN, ResolvedMaterial};
import package::realtime::world_cache_query::{query_world_cache, WORLD_CACHE_CELL_LIFETIME};
@@ -29,7 +29,7 @@ fn initial_and_temporal(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin
}
let surface = gpixel_resolve(textureLoad(gbuffer, global_id.xy, 0), depth, global_id.xy, view.main_pass_viewport.zw, view.world_from_clip);
- let initial = generate_initial_path(surface.world_position, surface.world_normal, surface.material, workgroup_id.xy, global_id.xy, &rng);
+ let initial = generate_initial_paths(surface.world_position, surface.world_normal, surface.material, workgroup_id.xy, global_id.xy, &rng);
textureStore(view_output, global_id.xy, vec4(initial.radiance, 0.0));
let temporal = load_temporal_reservoir(global_id.xy, depth, surface.world_position, surface.world_normal);
@@ -119,7 +119,7 @@ fn load_temporal_reservoir(pixel_id: vec2<u32>, depth: f32, world_position: vec3
fn load_spatial_reservoir(pixel_id: vec2<u32>, depth: f32, world_position: vec3<f32>, world_normal: vec3<f32>, rng: ptr<function, u32>) -> NeighborInfo {
for (var i = 0u; i < 5u; i++) {
- let spatial_pixel_id = get_neighbor_pixel_id(pixel_id, SPATIAL_REUSE_RADIUS_PIXELS, rng);
+ let spatial_pixel_id = get_neighbor_pixel_id(pixel_id, constants.spatial_reuse_radius, rng);
if all(spatial_pixel_id == pixel_id) {
continue;
@@ -327,8 +327,7 @@ fn reservoir_contribution(reservoir: Reservoir, resolved: ResolvedLightSample, w
// nee_mis_weight in generate_nee_candidate and generate_emissive_candidate, which puts the same factor in the target.
var nee_mis_weight = 1.0;
if light_contribution.brdf_rays_can_hit && light_contribution.inverse_solid_angle_pdf > 0.0 {
- let light_count = arrayLength(&light_sources);
- let inverse_solid_angle_pdf = light_contribution.inverse_solid_angle_pdf * f32(light_count);
+ let inverse_solid_angle_pdf = light_contribution.inverse_solid_angle_pdf / light_pmf(reservoir.light_sample.light_id >> 16u);
let p_nee = mix(1.0, material.perceptual_roughness, material.metallic);
let p_nee_strategy = f32(constants.primary_di_samples) * (1.0 / inverse_solid_angle_pdf) * p_nee;
let p_brdf_at_nee = brdf_pdf(wo, light_contribution.wi, world_normal, material, F_ab);
diff --git a/vendor/bevy_solari/src/realtime/world_cache_query.wesl b/vendor/bevy_solari/src/realtime/world_cache_query.wesl
index 7a6644d7..ad61ac9c 100644
--- a/vendor/bevy_solari/src/realtime/world_cache_query.wesl
+++ b/vendor/bevy_solari/src/realtime/world_cache_query.wesl
@@ -30,12 +30,18 @@ fn query_world_cache_found(world_position_in: vec3<f32>, world_normal: vec3<f32>
var cell_size = get_cell_size(world_position, view_position, ray_t, rng);
@if(!NO_JITTER_WORLD_CACHE) {
+ // raea (11-25): while the camera holds still with a steady cache (world_cache_still), no jitter and one LOD band
+ // (get_cell_size), so a surface has one key a cell and each cell converges. With them, a held frame kept making
+ // keys (a jittered point, a band picked by chance), and the young cells' few samples kept MALL RAT's held court
+ // patchy where a frozen cache wasn't (raea light steady). A moving camera keeps both, which hide the cells' edges
+ if !world_cache_still() {
// Jitter query point, which essentially blurs the cache a bit so it's not so grid-like
// https://tomclabault.github.io/blog/2025/regir, jitter_world_position_tangent_plane
let TBN = orthonormalize(world_normal);
let offset = (rand_vec2f(rng) * 2.0 - 1.0) * cell_size * 0.5;
world_position += offset.x * TBN[0] + offset.y * TBN[1];
cell_size = get_cell_size(world_position, view_position, ray_t, rng);
+ }
}
let world_position_quantized = bitcast<vec3<u32>>(quantize_position(world_position, cell_size));
@@ -87,10 +93,15 @@ fn get_cell_size(world_position: vec3<f32>, view_position: vec3<f32>, ray_t: f32
let camera_distance = distance(view_position, world_position) / constants.world_cache_position_lod_scale;
let lod_f = log2(1.0 + camera_distance);
let lod_fract = fract(lod_f);
- let lod = floor(lod_f) + select(0.0, 1.0, rand_f(rng) < lod_fract * lod_fract * lod_fract);
+ let coin = rand_f(rng);
+ // raea: one band while the camera holds (world_cache_still); the random pick between two bands otherwise
+ let lod = floor(lod_f) + select(select(0.0, 1.0, coin < lod_fract * lod_fract * lod_fract), select(0.0, 1.0, lod_fract > 0.5), world_cache_still());
return constants.world_cache_position_base_cell_size * exp2(lod);
}
+// raea (11-25): bit 1 of constants.world_cache_steady (prepare.rs): a steady cache with the camera where it was last frame
+fn world_cache_still() -> bool { return (constants.world_cache_steady & 2u) != 0u; }
+
fn quantize_position(world_position: vec3<f32>, quantization_factor: f32) -> vec3<f32> {
return floor(world_position / quantization_factor + 0.0001);
}
diff --git a/vendor/bevy_solari/src/realtime/world_cache_update.wesl b/vendor/bevy_solari/src/realtime/world_cache_update.wesl
index 23b1c08d..db195e86 100644
--- a/vendor/bevy_solari/src/realtime/world_cache_update.wesl
+++ b/vendor/bevy_solari/src/realtime/world_cache_update.wesl
@@ -14,13 +14,22 @@ import package::realtime::bindings::{
enable wgpu_ray_query;
+// raea: a cell's random numbers this frame. A bake (world_cache_steady) runs the update several times a frame
+// (SolariLighting::world_cache_update_iterations), so each run takes the cell's sample count too, which its blend raises
+// by one: the same numbers each run would add the same sample again. sample_di, sample_gi and blend_new_samples read the
+// count before blend_new_samples writes it, so the three agree on whether the cell updates
+fn cell_seed(cell_index: u32) -> u32 {
+ let n = select(0u, u32(world_cache.radiance[cell_index].a) * 2654435761u, ((constants.world_cache_steady & 1u) != 0u));
+ return cell_index + constants.frame_rng + n;
+}
+
@compute @workgroup_size(64, 1, 1)
fn sample_di(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_invocation_id) active_cell_id: vec3<u32>) {
if active_cell_id.x >= world_cache.active_cells_count { return; }
let cell_index = world_cache.active_cell_indices[active_cell_id.x];
let geometry_data = world_cache.geometry_data[cell_index];
- var rng = cell_index + constants.frame_rng;
+ var rng = cell_seed(cell_index);
if rand_f(&rng) >= f32(constants.world_cache_cell_updates_soft_target) / f32(world_cache.active_cells_count) { return; }
@@ -37,7 +46,7 @@ fn sample_gi(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(global_inv
let cell_index = world_cache.active_cell_indices[active_cell_id.x];
let geometry_data = world_cache.geometry_data[cell_index];
- var rng = cell_index + constants.frame_rng;
+ var rng = cell_seed(cell_index);
if rand_f(&rng) >= f32(constants.world_cache_cell_updates_soft_target) / f32(world_cache.active_cells_count) { return; }
@@ -87,7 +96,7 @@ fn blend_new_samples(@builtin(global_invocation_id) active_cell_id: vec3<u32>) {
if active_cell_id.x >= world_cache.active_cells_count { return; }
let cell_index = world_cache.active_cell_indices[active_cell_id.x];
- var rng = cell_index + constants.frame_rng;
+ var rng = cell_seed(cell_index);
if rand_f(&rng) >= f32(constants.world_cache_cell_updates_soft_target) / f32(world_cache.active_cells_count) { return; }
@@ -100,7 +109,9 @@ fn blend_new_samples(@builtin(global_invocation_id) active_cell_id: vec3<u32>) {
let sample_count = min(old_radiance.a + 1.0, constants.world_cache_max_temporal_samples);
let alpha = abs(luminance_delta) / max(luminance(old_radiance.rgb), 0.001);
let max_sample_count = mix(constants.world_cache_max_temporal_samples, 1.0, pow(saturate(alpha), 1.0 / 8.0));
- var blend_amount = 1.0 / min(sample_count, max_sample_count);
+ // raea: a bake (world_cache_steady) keeps the whole history: a cell's own noise moves its luminance, which the
+ // line above reads as the light changing, and at one ray a frame it cut a 32-frame history to about 10
+ var blend_amount = 1.0 / select(min(sample_count, max_sample_count), sample_count, ((constants.world_cache_steady & 1u) != 0u));
if bool(constants.reset) {
blend_amount = 1.0;
}
diff --git a/vendor/bevy_solari/src/scene/binder/bind_group.rs b/vendor/bevy_solari/src/scene/binder/bind_group.rs
index 0843b892..043b16f7 100644
--- a/vendor/bevy_solari/src/scene/binder/bind_group.rs
+++ b/vendor/bevy_solari/src/scene/binder/bind_group.rs
@@ -4,7 +4,7 @@ use super::{
};
use crate::scene::extract::ExtractedEnvironmentMapLight;
use bevy_ecs::system::{Res, ResMut};
-use bevy_math::{Mat3, Vec3, Vec4};
+use bevy_math::{Mat3, UVec4, Vec3, Vec4};
use bevy_pbr::DfgLut;
use bevy_render::{
render_asset::RenderAssets,
@@ -328,9 +328,11 @@ pub fn prepare_raytracing_scene_bind_group(
));
let any_alpha = !bindings.assets.alpha_materials.is_empty() || alpha_pass_always();
+ let sky_ids = bindings.lights.index.sky_ids();
let environment_map_light = prepare_environment_map_light(
&extracted_environment_map_light,
any_alpha,
+ &sky_ids,
&texture_assets,
&fallback_texture,
&mut bindings.environment_map_light_buffer,
@@ -369,6 +371,35 @@ pub struct GpuEnvironmentMapLight {
// raea: the sky portals (SkyPortals), three rows each: the corner and the area, then the two edges
pub portal_count: u32,
pub portals: [Vec4; 3 * crate::scene::MAX_SKY_PORTALS],
+ // raea (11-25): light selection's fixed share for the sky's sources and their indices (sampling.wesl pick_light)
+ pub sky_share: f32,
+ pub sky_count: u32,
+ pub sky_ids: [UVec4; MAX_SKY_IDS / 4],
+}
+
+/// raea: the most sky sources (directional lights and sky portals) light selection gives a share; past it, every
+/// source alike as upstream
+pub const MAX_SKY_IDS: usize = 16;
+
+/// raea (11-25): the part of light selection's samples the sky's sources share (sampling.wesl pick_light), 0 unless
+/// RAEA_SOLARI_SKY_SHARE says (0: every source alike, by count, as upstream)
+fn sky_share() -> f32 {
+ static SHARE: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
+ *SHARE.get_or_init(|| {
+ std::env::var("RAEA_SOLARI_SKY_SHARE").ok().and_then(|v| v.parse::<f32>().ok()).filter(|v| (0.0..1.0).contains(v)).unwrap_or(0.0)
+ })
+}
+
+/// raea: the sky's sources as the uniform holds them: none (every source alike) when there are more than MAX_SKY_IDS
+pub fn pack_sky_ids(ids: &[u32]) -> (f32, u32, [UVec4; MAX_SKY_IDS / 4]) {
+ let mut out = [UVec4::ZERO; MAX_SKY_IDS / 4];
+ if ids.is_empty() || ids.len() > MAX_SKY_IDS {
+ return (0.0, 0, out);
+ }
+ for (i, id) in ids.iter().enumerate() {
+ out[i / 4][i % 4] = *id;
+ }
+ (sky_share(), ids.len() as u32, out)
}
impl Default for GpuEnvironmentMapLight {
@@ -382,6 +413,9 @@ impl Default for GpuEnvironmentMapLight {
any_alpha: 0,
portal_count: 0,
portals: [Vec4::ZERO; 3 * crate::scene::MAX_SKY_PORTALS],
+ sky_share: 0.0,
+ sky_count: 0,
+ sky_ids: [UVec4::ZERO; MAX_SKY_IDS / 4],
}
}
}
@@ -415,6 +449,7 @@ fn alpha_pass_always() -> bool {
fn prepare_environment_map_light<'a>(
extracted_environment_map_light: &ExtractedEnvironmentMapLight,
any_alpha: bool,
+ sky_ids: &[u32],
texture_assets: &'a RenderAssets<GpuImage>,
fallback_texture: &'a FallbackImage,
buffer: &mut StorageBuffer<GpuEnvironmentMapLight>,
@@ -440,6 +475,9 @@ fn prepare_environment_map_light<'a>(
any_alpha: 0,
portal_count: 0,
portals: [Vec4::ZERO; 3 * crate::scene::MAX_SKY_PORTALS],
+ sky_share: 0.0,
+ sky_count: 0,
+ sky_ids: [UVec4::ZERO; MAX_SKY_IDS / 4],
},
),
None => (
@@ -449,6 +487,7 @@ fn prepare_environment_map_light<'a>(
};
uniform.any_alpha = any_alpha as u32;
+ (uniform.sky_share, uniform.sky_count, uniform.sky_ids) = pack_sky_ids(sky_ids);
if cubemap.is_some() {
(uniform.portal_count, uniform.portals) = pack_sky_portals(&extracted_environment_map_light.portals);
}
diff --git a/vendor/bevy_solari/src/scene/binder/lights.rs b/vendor/bevy_solari/src/scene/binder/lights.rs
index 58b5893c..12e4cac7 100644
--- a/vendor/bevy_solari/src/scene/binder/lights.rs
+++ b/vendor/bevy_solari/src/scene/binder/lights.rs
@@ -45,6 +45,17 @@ pub struct LightIndex {
}
impl LightIndex {
+ /// raea (11-25): the indices of the sky's sources (directional lights and sky portals), ascending, for light
+ /// selection's fixed sky share (sampling.wesl pick_light)
+ pub fn sky_ids(&self) -> Vec<u32> {
+ self.ids
+ .iter()
+ .enumerate()
+ .filter(|(_, id)| !matches!(id, LightSourceId::EmissiveMesh(_)))
+ .map(|(i, _)| i as u32)
+ .collect()
+ }
+
pub fn len(&self) -> usize {
self.ids.len()
}
diff --git a/vendor/bevy_solari/src/scene/bindings.wesl b/vendor/bevy_solari/src/scene/bindings.wesl
index 10b33895..8e00ca9f 100644
--- a/vendor/bevy_solari/src/scene/bindings.wesl
+++ b/vendor/bevy_solari/src/scene/bindings.wesl
@@ -163,6 +163,11 @@ struct EnvironmentMapLight {
// raea: the sky portals (bind_group.rs pack_sky_portals): three rows each, the corner and the area, then the edges
portal_count: u32,
portals: array<vec4<f32>, 24>,
+ // raea (11-25): light selection's fixed share for the sky (directional lights and sky portals), and those sources'
+ // indices in light_sources, ascending (bind_group.rs sky_light_ids); a share of 0 picks every source alike, by count
+ sky_share: f32,
+ sky_count: u32,
+ sky_ids: array<vec4<u32>, 4>,
}
// raea: a sky portal, the parallelogram corner + a u + b v for a and b from 0 to 1; normal: cross(u, v), unit length
diff --git a/vendor/bevy_solari/src/scene/sampling.wesl b/vendor/bevy_solari/src/scene/sampling.wesl
index 51c5e2a6..1f5909b9 100644
--- a/vendor/bevy_solari/src/scene/sampling.wesl
+++ b/vendor/bevy_solari/src/scene/sampling.wesl
@@ -1,5 +1,5 @@
import bevy_pbr::render::pbr_lighting::D_GGX;
-import bevy_pbr::render::utils::{rand_vec2f, rand_u, rand_range_u};
+import bevy_pbr::render::utils::{rand_f, rand_vec2f, rand_u, rand_range_u};
import bevy_render::maths::{PI_2, orthonormalize};
import package::scene::bindings::{trace_ray, trace_ray_previous_frame, RAY_T_MIN, RAY_T_MAX, light_sources, directional_lights, environment_map, environment_map_sampler, environment_map_light, LightSource, LIGHT_SOURCE_KIND_DIRECTIONAL, LIGHT_SOURCE_KIND_SKY_PORTAL, sky_portal, resolve_triangle_data_full, ResolvedRayHitFull, MIRROR_ROUGHNESS_THRESHOLD, offset_ray_origin};
@@ -128,9 +128,45 @@ fn sample_random_light(ray_origin: vec3<f32>, origin_world_normal: vec3<f32>, rn
return light_contribution;
}
+// raea (11-25): light selection. Upstream picks a source uniformly by count, so in MALL RAT's court (93 emissive meshes,
+// the sun and its sky portals) the sun, which lights most of it, got one sample in about 95, and a LOD swap that changed
+// the count moved its share from one frame to the next. Now the sky's sources (directional lights and sky portals) share
+// a fixed part of the samples, environment_map_light.sky_share, and the emissive meshes the rest; within each group
+// every source alike. A share of 0 (or a scene with only one group) is upstream's: every source alike
+fn sky_sources() -> u32 { return environment_map_light.sky_count; }
+fn light_share_on() -> bool {
+ let n = arrayLength(&light_sources);
+ return environment_map_light.sky_share > 0.0 && sky_sources() > 0u && sky_sources() < n;
+}
+// the chance light selection picks one given sky source (a directional light or a sky portal)
+fn sky_light_pmf() -> f32 {
+ if !light_share_on() { return 1.0 / f32(arrayLength(&light_sources)); }
+ return environment_map_light.sky_share / f32(sky_sources());
+}
+// the chance light selection picks one given emissive mesh
+fn emissive_light_pmf() -> f32 {
+ if !light_share_on() { return 1.0 / f32(arrayLength(&light_sources)); }
+ return (1.0 - environment_map_light.sky_share) / f32(arrayLength(&light_sources) - sky_sources());
+}
+// the chance light selection picks source `light_index`
+fn light_pmf(light_index: u32) -> f32 {
+ if (light_sources[light_index].kind & 1u) == 1u { return sky_light_pmf(); }
+ return emissive_light_pmf();
+}
+fn sky_light_id(i: u32) -> u32 { return environment_map_light.sky_ids[i >> 2u][i & 3u]; }
+fn pick_light(rng: ptr<function, u32>) -> u32 {
+ let n = arrayLength(&light_sources);
+ if !light_share_on() { return rand_range_u(n, rng); }
+ let s = sky_sources();
+ if rand_f(rng) < environment_map_light.sky_share { return sky_light_id(rand_range_u(s, rng)); }
+ // the r-th emissive source: r counted past each sky source at or below it (the sky's indices ascend)
+ var r = rand_range_u(n - s, rng);
+ for (var i = 0u; i < s; i++) { if sky_light_id(i) <= r { r += 1u; } }
+ return r;
+}
+
fn random_emissive_light_pdf(hit: ResolvedRayHitFull, ray_distance: f32, NdotV: f32) -> f32 {
- let light_count = arrayLength(&light_sources);
- let area_pdf = 1.0 / (f32(light_count) * f32(hit.triangle_count) * hit.triangle_area);
+ let area_pdf = emissive_light_pmf() / (f32(hit.triangle_count) * hit.triangle_area);
return area_pdf * (ray_distance * ray_distance) / NdotV;
}
@@ -156,8 +192,7 @@ fn sample_environment_map_light_and_sun(world_direction: vec3<f32>, sun: bool) -
}
fn generate_random_light_sample(rng: ptr<function, u32>) -> GenerateRandomLightSampleResult {
- let light_count = arrayLength(&light_sources);
- let light_id = rand_range_u(light_count, rng);
+ let light_id = pick_light(rng);
let light_source = light_sources[light_id];
@@ -172,7 +207,7 @@ fn generate_random_light_sample(rng: ptr<function, u32>) -> GenerateRandomLightS
let light_sample = LightSample((light_id << 16u) | triangle_id, seed);
var resolved_light_sample = resolve_light_sample(light_sample, light_source);
- resolved_light_sample.inverse_pdf *= f32(light_count);
+ resolved_light_sample.inverse_pdf /= light_pmf(light_id);
return GenerateRandomLightSampleResult(light_sample, resolved_light_sample);
}
@@ -274,7 +309,7 @@ fn sky_portal_light_pdf(origin: vec3<f32>, wi: vec3<f32>) -> f32 {
let a = (dot(h, portal.u) * vv - dot(h, portal.v) * uv) / det;
let b = (dot(h, portal.v) * uu - dot(h, portal.u) * uv) / det;
if a < 0.0 || a > 1.0 || b < 0.0 || b > 1.0 { continue; }
- return t * t / (f32(arrayLength(&light_sources)) * portal.area * abs(cos_portal));
+ return t * t * sky_light_pmf() / (portal.area * abs(cos_portal));
}
return 0.0;
}