diff --git a/astraweave-render/src/bin/gpu_frame_budget.rs b/astraweave-render/src/bin/gpu_frame_budget.rs index 41cf29a0f4..6378e05947 100644 --- a/astraweave-render/src/bin/gpu_frame_budget.rs +++ b/astraweave-render/src/bin/gpu_frame_budget.rs @@ -5,6 +5,10 @@ //! //! ```text //! cargo run -p astraweave-render --release --features gpu-frame-budget --bin gpu_frame_budget -- --scene heavy --debug-timestamps --glb "assets/The Complete KayKit Collection v4/KayKit Adventurers 2.0/Characters/gltf/Rogue.glb" +//! +//! An enabled gated flag is rejected, including `--atmosphere`. +//! `--flag=false` and `--flag false` are off and do not bail. The printed +//! `median_gpu_frame_ms` is the baseline frame. No gated cell is filled here. //! ``` use anyhow::Context; @@ -31,6 +35,8 @@ const SAMPLES: usize = 120; fn main() -> anyhow::Result<()> { env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init(); + let args: Vec = std::env::args().skip(1).collect(); + astraweave_render::budget_gate::reject_gated_flags(&args)?; let glb = glb_path(); let heavy = scene_is_heavy(); let debug_timestamps = debug_timestamps(); @@ -141,11 +147,14 @@ fn main() -> anyhow::Result<()> { renderer.set_shadows_enabled(true); add_heavy_terrain(&mut renderer)?; renderer.set_particle_emitter(Some(emitter()))?; - // Cloud shadows stay at the renderer default (on): a 512² compute march - // between the sky pass and the main pass. Volumetric fog and god rays - // are not called. GPU indirect culling is not the draw path on any - // adapter: each model still binds its own group 3, so one indirect - // buffer cannot select those groups. The CPU frustum remains the filter. + // Cloud shadows stay at the renderer default (on). That is + // `CloudShadowPass`, not `VolumetricCloudsPass`. Volumetric fog, god + // rays, and every gated presentation pass stay off. GPU indirect culling + // is not the draw path on any adapter: each model still binds its own + // group 3, so one indirect buffer cannot select those groups. The CPU + // frustum remains the filter. + println!("gated_atmosphere=off"); + println!("gated_measure=baseline"); let gpu_cull = "cpu_fallback"; let device = renderer.device().clone(); diff --git a/astraweave-render/src/budget_gate.rs b/astraweave-render/src/budget_gate.rs new file mode 100644 index 0000000000..b10697463a --- /dev/null +++ b/astraweave-render/src/budget_gate.rs @@ -0,0 +1,139 @@ +//! Command-line gate for `gpu_frame_budget`. +//! +//! An enabled gated flag is rejected before the scene is built. +//! `--name=false` and `--name false` are off and do not bail. + +/// True when `name` is enabled on this command line. +/// +/// Bare `--name` is on, including when the next token is another flag. +/// `--name=true` is on. The third clause is the `--name ` pair: +/// `true` is on and `false` is off. +pub fn flag_on(args: &[String], name: &str) -> bool { + let equals_true = format!("{name}=true"); + args.iter().enumerate().any(|(index, arg)| { + let next = args.get(index + 1).map(String::as_str); + (arg == name && bare_flag(next)) + || arg == &equals_true + || (arg == name && next == Some("true")) + }) +} + +fn bare_flag(next: Option<&str>) -> bool { + match next { + None => true, + Some(token) if token.starts_with('-') => true, + Some(_) => false, + } +} + +/// Scaffolding only. No enabled gated flag draws a frame, so no cell can be filled. +pub fn reject_gated_flags(args: &[String]) -> anyhow::Result<()> { + const BLOCKED: &[(&str, &str)] = &[ + ( + "--atmosphere", + "enabling it skips the HDR and depth clear, so the heavy scene does not land", + ), + ( + "--ssgi", + "normal and velocity targets are allocated and never written, and ssgi_history is sampled before copy_to_history; the pass writes denoised_view, and record_gated_presentation never copies it onto hdr_tex, so the post pass samples a frame that does not show it", + ), + ( + "--taa", + "normal and velocity targets are allocated and never written, and taa_history is sampled before copy_to_history; the pass writes resolved_view and sharpened_view, and record_gated_presentation never copies them onto hdr_tex, so the post pass samples a frame that does not show them", + ), + ( + "--upscale", + "normal and velocity targets are allocated and never written, and upscale_history is sampled before copy_to_history; the pass writes sharpened_view, and record_gated_presentation never copies it onto hdr_tex, so the post pass samples a frame that does not show it", + ), + ( + "--dof", + "the depth-of-field history target is uncleared and the result is not copied onto HDR", + ), + ( + "--clouds", + "the raymarch samples cloud_history before writing it, and the composite is not copied onto HDR", + ), + ]; + let hits: Vec = BLOCKED + .iter() + .filter(|(flag, _)| flag_on(args, flag)) + .map(|(flag, why)| format!("{flag} ({why})")) + .collect(); + if hits.is_empty() { + return Ok(()); + } + anyhow::bail!( + "gated flags cannot fill a measurement cell: {}", + hits.join("; ") + ) +} + +#[cfg(test)] +mod tests { + use super::{flag_on, reject_gated_flags}; + + fn args(parts: &[&str]) -> Vec { + parts.iter().map(|part| (*part).to_string()).collect() + } + + fn rejected(parts: &[&str]) -> String { + reject_gated_flags(&args(parts)) + .expect_err("gated flag must fail before a frame") + .to_string() + } + + #[test] + fn reject_gated_flags_covers_each_form() { + assert!(reject_gated_flags(&args(&["--scene", "heavy"])).is_ok()); + for flag in [ + "--atmosphere", + "--ssgi", + "--taa", + "--upscale", + "--dof", + "--clouds", + ] { + let message = rejected(&[flag]); + assert!(message.contains(flag), "{message}"); + assert!(flag_on(&args(&[flag]), flag)); + assert!(flag_on(&args(&[&format!("{flag}=true")]), flag)); + assert!(flag_on(&args(&[flag, "true"]), flag)); + assert!(!flag_on(&args(&[&format!("{flag}=false")]), flag)); + assert!(!flag_on(&args(&[flag, "false"]), flag)); + assert!(reject_gated_flags(&args(&[&format!("{flag}=false")])).is_ok()); + assert!(reject_gated_flags(&args(&[flag, "false"])).is_ok()); + } + let equals = rejected(&["--atmosphere=true"]); + assert!(equals.contains("--atmosphere"), "{equals}"); + let two_token = rejected(&["--atmosphere", "true"]); + assert!(two_token.contains("--atmosphere"), "{two_token}"); + let pair = rejected(&["--atmosphere", "--ssgi"]); + assert!(pair.contains("--atmosphere"), "{pair}"); + assert!(pair.contains("--ssgi"), "{pair}"); + assert!(pair.contains("ssgi_history"), "{pair}"); + let ssgi = rejected(&["--ssgi"]); + assert!(ssgi.contains("copy_to_history"), "{ssgi}"); + assert!(ssgi.contains("denoised_view"), "{ssgi}"); + assert!(ssgi.contains("hdr_tex"), "{ssgi}"); + assert!(ssgi.contains("record_gated_presentation"), "{ssgi}"); + let taa = rejected(&["--taa"]); + assert!(taa.contains("taa_history"), "{taa}"); + assert!(taa.contains("resolved_view"), "{taa}"); + assert!(taa.contains("sharpened_view"), "{taa}"); + assert!(taa.contains("hdr_tex"), "{taa}"); + let upscale = rejected(&["--upscale"]); + assert!(upscale.contains("upscale_history"), "{upscale}"); + assert!(upscale.contains("sharpened_view"), "{upscale}"); + assert!(upscale.contains("hdr_tex"), "{upscale}"); + let false_then_ssgi = rejected(&["--atmosphere", "false", "--ssgi"]); + assert!( + !false_then_ssgi.contains("--atmosphere"), + "{false_then_ssgi}" + ); + assert!( + false_then_ssgi.contains("ssgi_history"), + "{false_then_ssgi}" + ); + assert!(rejected(&["--atmosphere", "false", "--atmosphere"]).contains("--atmosphere")); + } +} diff --git a/astraweave-render/src/lib.rs b/astraweave-render/src/lib.rs index 08aff449fa..f6b0887a73 100644 --- a/astraweave-render/src/lib.rs +++ b/astraweave-render/src/lib.rs @@ -62,6 +62,7 @@ pub mod biome_detector; pub mod biome_material; pub mod biome_transition; pub mod bloom; // Physically-based bloom with 13-tap downsample and tent upsample +pub mod budget_gate; // gpu_frame_budget gated-flag parser pub mod culling; // GPU-driven frustum culling (Phase 2 Task 3) pub mod culling_node; // Culling node for render graph pub mod disney_material; // Disney principled BRDF evaluation + WGSL source (Phase 9) diff --git a/docs/architecture/render_pipeline_material_system_shader_infrastructure.md b/docs/architecture/render_pipeline_material_system_shader_infrastructure.md index 298ca0e9b1..a39815cfcc 100644 --- a/docs/architecture/render_pipeline_material_system_shader_infrastructure.md +++ b/docs/architecture/render_pipeline_material_system_shader_infrastructure.md @@ -8,8 +8,8 @@ domain: rendering lifecycle_status: active integration_status: wired owns: [astraweave-materials, astraweave-render] -doc_version: "1.48" -last_verified_commit: 36757dad +doc_version: "1.50" +last_verified_commit: f72defda --- # Architecture Trace: Render Pipeline + Material System + Shader Infrastructure @@ -20,12 +20,16 @@ last_verified_commit: 36757dad |---|---| | **System name** | Render Pipeline + Material System + Shader Infrastructure | | **Primary crates** | `astraweave-render` (123 Rust files / ~78K LoC + 71 WGSL files), `astraweave-materials` (single-file material-graph crate), `tools/aw_editor/src/viewport/` (editor-side renderer + engine adapter) | -| **Document version** | 1.48 | -| **Last verified against commit** | `36757dad` (parent of this notice; verified at the PR head; stamp updated on merge). Prior `2ce0da5d` (v1.46 behavior: `decode_texture` caps the read and `shutdown_timeout` is 500 ms; the extra byte past a full fifo is still there). Prior `596eed69` (v1.45 parent: Hi-Z contracts, lavapipe `stream_fallback`, decode runtime polls). Prior `f56b2fa4` (v1.45: the forward `HizPyramid` is gated on `sample_hiz`; `NaniteCullingPipeline` keeps a separate pyramid). Prior `09d49dfe` (v1.41: flat sample on the shard 13 and 14 targets that hit 600s). Prior `0758171bf` (lifecycle RSS); prior `154d723aa` (v1.19, 2026-08-02: L.3.C-resolution — 4-cascade CSM + `FarCascadePolicy` + fit-derived bias cap; trace updated in the same commit as the code, so this names its parent); prior `d4c4479d4` (v1.12, 2026-07-25: T.2d.F tier retirement — see revision notice); prior `8232b150b` (v1.10, 2026-07-21: E3 terrain render-path additions verified first-hand — see revision notice); prior `7c29b8182` (v1.8 verification pass: §2.6 Water surface render path re-verified end-to-end against `water.rs` / `water.wgsl` / `renderer.rs` — every file:line citation confirmed, zero corrections, no markers needed; v1.7 added the subsection + cross-link to `docs/architecture/water.md`); prior: `67c9de7e1` (full trace); water rows W.2a + W.2b.2 + W.2c.2 weave-deformation + W.2c.3 weave producer (2026-06-22) + F.4.2 weave-impact accent machinery + F.4.3 live HDR-overlay composite & combined-frame measurement (2026-06-24) | +| **Document version** | 1.50 | +| **Last verified against commit** | `f72defda` (parent of the flag-parser notice; not lower than main `8b4caa27`). Prior `83798b48` (v1.49 parent: the timestamp row's reject sentence). Prior `36757dad` (v1.48 parent; verified at that PR head; stamp updated on merge). Prior `2ce0da5d` (v1.46 behavior: `decode_texture` caps the read and `shutdown_timeout` is 500 ms; the extra byte past a full fifo is still there). Prior `596eed69` (v1.45 parent: Hi-Z contracts, lavapipe `stream_fallback`, decode runtime polls). Prior `f56b2fa4` (v1.45: the forward `HizPyramid` is gated on `sample_hiz`; `NaniteCullingPipeline` keeps a separate pyramid). Prior `09d49dfe` (v1.41: flat sample on the shard 13 and 14 targets that hit 600s). Prior `0758171bf` (lifecycle RSS); prior `154d723aa` (v1.19, 2026-08-02: L.3.C-resolution — 4-cascade CSM + `FarCascadePolicy` + fit-derived bias cap; trace updated in the same commit as the code, so this names its parent); prior `d4c4479d4` (v1.12, 2026-07-25: T.2d.F tier retirement — see revision notice); prior `8232b150b` (v1.10, 2026-07-21: E3 terrain render-path additions verified first-hand — see revision notice); prior `7c29b8182` (v1.8 verification pass: §2.6 Water surface render path re-verified end-to-end against `water.rs` / `water.wgsl` / `renderer.rs` — every file:line citation confirmed, zero corrections, no markers needed; v1.7 added the subsection + cross-link to `docs/architecture/water.md`); prior: `67c9de7e1` (full trace); water rows W.2a + W.2b.2 + W.2c.2 weave-deformation + W.2c.3 weave producer (2026-06-22) + F.4.2 weave-impact accent machinery + F.4.3 live HDR-overlay composite & combined-frame measurement (2026-06-24) | | **Last verified date** | 2026-08-02 (L.3.C-resolution: 4-cascade CSM, far-cascade refresh policy, fit-derived receiver-bias cap, invariant 20 (e)-(i)); 2026-07-21 (E3 terrain render-path, T.0 trace-sync); 2026-06-25 (§2.6 water render-path verification pass); 2026-06-24 (water render-path subsection authored); 2026-05-10 (full trace) | | **Status** | **ACTIVE WORKZONE** — Editor Multi-Tool Architecture Campaign Sub-phase 3 (Mediator Brush) is in flight as of campaign-doc commit `e3d07f366` (2026-05-08, Round-8-Closure). Fix 27 Unified Pipeline Campaign is structurally complete (per CLAUDE.md) but deeper editor↔runtime unification continues. Treat this trace as a **navigational map**; per-subsystem detailed traces are follow-up work. | | **Owner notes** | This trace covers an unusually large system (~78K LoC source + 71 WGSL files + editor viewport). Per the template's "One last thing" rule on scale, this doc is intentionally structured as a **subsystem map + load-bearing-aggregator detail**, not an exhaustive per-file trace. Sub-systems like Lumen GI, MegaLights, Nanite, Atmosphere, GPU Particles, Volumetric Fog, IBL, and TAA each warrant their own dedicated trace if and when they enter focused work. The doc covers terrain materials by reference to `docs/architecture/terrain_materials.md`. | +> **Revision notice — 2026-10-21 (v1.50).** `flag_on` lives in `budget_gate.rs` and is covered by lib tests. Bare `--name`, `--name=true`, and `--name true` are on. `--name=false` and `--name false` are off and do not bail. The timestamp row keeps the Hi-Z sentence and the reject sentence. `last_verified_commit` is `f72defda`, the parent of this notice. +> +> **Revision notice — 2026-10-21 (v1.49).** The timestamp row records that `gpu_frame_budget` rejects every gated flag, including `--atmosphere`, before it builds the scene. `last_verified_commit` is `83798b48`, the parent of this notice. Main's v1.48 wording stays. +> > **Revision notice — 2026-10-21 (v1.48).** `astraweave-render` enables tokio `io-util` on its own dependency line. Verified at the PR head. `last_verified_commit` names the parent `36757dad`: the trace convention is that the edit lands in the child, so the stamp cannot be this commit, and it does not claim `36757dad` contains this notice. The stamp is updated on merge. > > **Revision notice — 2026-10-21 (v1.47).** Corrected in v1.48. The shared `read_capped_image`, the stop at the cap with no further read, and the unix fifo cleanup are `36757dad`. They are not in `2ce0da5d`. The 1660 Ti `hiz` 0.275 ms figure is that capture; the default frame does not record Hi-Z unless `sample_hiz` is set. @@ -533,6 +537,7 @@ This map enumerates the load-bearing files. Per-file traces of every subsystem a | `astraweave-render/src/staging_ring.rs` | Per-frame transient GPU allocator | Active | `Renderer.staging_ring` field | | `astraweave-render/src/gpu_memory.rs` | Memory budget tracker | Active | `GpuMemoryBudget`, `MemoryCategory` | | `astraweave-render/src/gpu_profiler.rs` | Per-pass GPU timestamp profiler | Active (optional — None when `TIMESTAMP_QUERY` is unsupported or the period is not positive) | Resolve is on the write encoder. The staging copy is a later submission. The log prints encoder ids and `encoder_count`. `prove_readback` must read a non-zero tick. `tests/gpu_timestamp.rs` | +| `astraweave-render/src/budget_gate.rs` | Gated-flag parser for `gpu_frame_budget` | Active | `flag_on` treats `--name=false` and `--name false` as off. Lib tests cover the forms. The bin calls `reject_gated_flags` before the scene. | ### Material system @@ -833,7 +838,7 @@ This map enumerates the load-bearing files. Per-file traces of every subsystem a | 18 | The weave-impact **accent** layer reuses `astraweave-fluids`' secondary-billboard machinery and stays **crate-independent**, and (F.4.3) is now **LIVE in-frame**: accents are produced by a binary-glue `WaterAccentProducer` and drawn by `FluidRenderer::render_accents` (additive-billboard-only — the SSFR surface chain is **never** invoked for accents), composited over the `WaterRenderer` surface **after the water pass, before tonemap, into the HDR target** via the renderer's stored `hdr_overlay` callback fired inside `run_water_pass` on every exit path. The callback type is pure `wgpu` `(encoder, hdr_view, scene_depth, device, queue)`, so `astraweave-render` gains **no** `astraweave-fluids` dependency — the binary registers a closure whose body calls `render_accents`. Both `render()` (demo) and `draw_into()` (editor) fire it because both call `run_water_pass`, so editor parity is automatic for the **pass mechanism** (the editor *producer feed* is a logged follow-on). **Zero-accent identity:** `render_accents` early-returns at count 0 and a `None` overlay records zero GPU work → byte-identical frame. **Measured (1660 Ti Max-Q, Vulkan, 1080p, 512 accents):** accent composite **0.006–0.013 ms** (median); water surface 0.18–0.24 ms; **combined 0.18–0.26 ms** — accents ~40–80× under the 0.5 ms target, total ~8× under the 2.0 ms water budget. | Yes (live composite; editor producer-feed deferred) | `astraweave-render/src/renderer.rs` `hdr_overlay` field + `set_hdr_overlay` + `fire_hdr_overlay` (called in `run_water_pass` all 3 exits, after `water_renderer` restore); `render_accents` (no depth/smooth/shade); `set_secondary_particles` + live-count `secondary_particle_count`; `examples/weaving_playground/src/{main.rs (per-frame upload + Rc-closure overlay), weave_accent_producer.rs}`; neither crate's `Cargo.toml` references the other; combined measurement `examples/weaving_playground/examples/accent_budget_probe.rs`; `gpu_render_accents_smoke`; F.4.3 (`docs/campaigns/water-successor/F4_3_EXECUTION_REPORT.md`) | | 19 | **One BRDF for every fragment — no stepped shading tier.** T.2d.F (2026-07-25, director-ratified) deleted the material-LOD tiers: the LOD1\|2 threshold (pixel footprint 2.0) was the T.2d-convicted camera-anchored detail boundary (matched to 4 px in two frames), and because `fwidth(world_pos)` includes the height derivative the per-pixel tier selection dithered over rough ground (40-55% of far-field high-frequency energy was tier flicker; measured removed: -48.6%/-51.7% at the boundary stations). `evaluate_brdf` (GGX + height-correlated Smith + Burley + Kulla-Conty multiscatter) is the single shading path in SHADER_SRC, SKINNED_SHADER_SRC and `pbr_terrain_forward.wgsl`; the static shader's former LOD2 IBL approximation died with the shared threshold (full IBL everywhere). Close range measured unchanged (1 px/786,432 at the 20 m station); far field brightens up to +9.5% (accepted consequence — T.2a/T.2c far-field frames rot); min-spec frame cost -1.0% (27.055 -> 26.773 ms median, 1660 Ti Max-Q, 1080p, n=300). A stepped tier may NOT return under any perf outcome — the ratified fallback is a falloff CONTINUOUS in footprint. | Yes | `renderer.rs::material_lod_tiers_are_retired` (asserts symbol ABSENCE across all four shader surfaces; proven to fail on pre-fix code); tombstone comment in `brdf_common.wgsl`; `docs/audits/T2DF_OUTCOME.md` | | 21 | **One forward Hi-Z pyramid, presentation particles, and streamed albedo.** (a) The forward renderer has one `HizPyramid`. `draw_into` builds it from that frame's depth view into R32Float only when `sample_hiz` is set. `set_sample_hiz(true)` drops any pyramid so the next frame copies the current depth view, including when the size is unchanged. The default is false. SSGI samples scene depth, and no pass calls `HizPyramid::view`. `NaniteCullingPipeline` (feature `nanite`) builds a separate pyramid in `build_hiz_pyramid` from `src/shaders/nanite_hiz_pyramid.wgsl`. Its copy from the previous depth is a placeholder (`_src_depth` is unused), and `draw_into` does not record it. The forward pyramid is not read back into the simulation. (b) CPU `FrustumPlanes::test_aabb` remains the model draw filter. (c) `GpuParticleSystem` runs only when an emitter is set, uses the caller seed and `dt`, and does not write ECS, nav, or physics. (d) A streamed albedo stays on the 1×1 fallback bind until `TextureStreamingManager` admits the decoded image. The worker reads at most 64 MiB and decodes with `decode_limited_image` (4096-pixel edge). `Drop` waits at most 500 ms, so a blocked read does not hold the caller. A failed load is stored; it is not dropped with `.ok()`. The last resident image, or that fallback, stays bound. `TextureStreamingManager::new` returns `Result` when the decode runtime cannot start. | Yes | `hiz_pyramid.rs` + `tests/hiz_depth_copy.rs` + `tests/hiz_rebind.rs`; `tests/frustum_agree.rs`; `tests/particle_present.rs`; `texture_streaming.rs` `tick` / `admit`; `tests/stream_fallback.rs` | -| 22 | **A GPU timestamp slot exists only for a pass that is recorded, and `resolve_query_set` is on that write encoder.** `draw_into` does not reserve a skipped pass, does not create a command encoder, and does not call `queue.submit`. Sky, water, atmosphere, and particles record into the caller's encoder. Hi-Z records only when `sample_hiz` is set, and that build copies the depth view passed to that `draw_into`. `submit_timestamped` rejects a resolve that is missing or recorded on a different encoder, submits that one buffer, polls without blocking for at most 5s, then copies. The copy is a later submission (wgpu#6406). A resolve in a later submission deadlocks NVIDIA. Equal non-zero ticks are an empty pass and stay out of the sum. Soft particles sample scene depth through a read-only attachment. `gpu_frame_budget` prints per-frame validation and out-of-memory scopes, and reads back `0xA1B2C3D4` copied in that same encoder. The lavapipe heavy-scene test fails if that scope is an error or the word is not `0xA1B2C3D4`. The heavy scene is one model per instance. `budget_11ms` is `pass` when `median_gpu_frame_ms` is ≤ 11 and `fail` when it is over. The min-spec record is the GTX 1660 Ti Max-Q heavy scene at `939a21bb`: 3.688 ms, pass. | Yes | `gpu_profiler.rs` `resolve_queries`, `submit_frame`, `wait_for_gpu`; `tests/gpu_timestamp.rs`; `gpu_frame_budget --scene heavy` | +| 22 | **A GPU timestamp slot exists only for a pass that is recorded, and `resolve_query_set` is on that write encoder.** `draw_into` does not reserve a skipped pass, does not create a command encoder, and does not call `queue.submit`. Sky, water, atmosphere, and particles record into the caller's encoder. Hi-Z records only when `sample_hiz` is set, and that build copies the depth view passed to that `draw_into`. `submit_timestamped` rejects a resolve that is missing or recorded on a different encoder, submits that one buffer, polls without blocking for at most 5s, then copies. The copy is a later submission (wgpu#6406). A resolve in a later submission deadlocks NVIDIA. Equal non-zero ticks are an empty pass and stay out of the sum. Soft particles sample scene depth through a read-only attachment. `gpu_frame_budget` prints per-frame validation and out-of-memory scopes, and reads back `0xA1B2C3D4` copied in that same encoder. The lavapipe heavy-scene test fails if that scope is an error or the word is not `0xA1B2C3D4`. The heavy scene is one model per instance. `budget_11ms` is `pass` when `median_gpu_frame_ms` is ≤ 11 and `fail` when it is over. The min-spec record is the GTX 1660 Ti Max-Q heavy scene at `939a21bb`: 3.688 ms, pass. `gpu_frame_budget` rejects an enabled gated flag, including `--atmosphere`, before it builds the scene. `--flag=false` and `--flag false` are off and do not bail. The printed median is the baseline frame. | Yes | `gpu_profiler.rs` `resolve_queries`, `submit_frame`, `wait_for_gpu`; `tests/gpu_timestamp.rs`; `budget_gate.rs` `flag_on`, `reject_gated_flags`; `gpu_frame_budget --scene heavy` | | 20 | **Terrain is a CSM caster AND receiver, through the live machinery only, with one owner per resource (L.3).** (a) One CSM sampling implementation: `shaders/shadow_common.wgsl`'s `csm_shadow_factor` is the ONLY cascade-select+PCF code; SHADER_SRC (group 2) and `pbr_terrain_forward.wgsl` (group 4) both call it — adding a third sampling implementation (or resurrecting the dormant `shadow_csm.rs` path alongside it) violates this. (b) The terrain receiver binds the renderer's EXISTING `light_bg` at group(4) — layout from the shared `TerrainMaterialManager::create_shadow_bgl` used by `Renderer::new` and the pipeline tests; no second shadow bind group of the same logical role may exist (§7.7). (c) The `extras.x < 0` sentinel disables shadow work in BOTH shaders and skips the caster passes; the off-state is byte-identical to pre-L.3 (proven: 0 differing pixels at the toggle stations). (d) The shadow term multiplies the DIRECT sun only — never the IBL/ambient terms (shadowed ground stays skylit; same term discipline as L.2's AO-on-indirect-only). (e) Terrain casts into ALL cascade layers (**4 since L.3.C**: 0.5→86.1, →500, →1400, →3000 m; `CASCADE_COUNT` is the single source of truth and every per-cascade array is `array::from_fn` over it) with per-cascade AABB culling (`TerrainChunkGpu.aabb_*`, computed at upload — the single source of chunk bounds). (f — L.3.A) Coverage must not end inside plainly-visible range at ANY supported camera regime, its fade must be WIDE (the last 30% of coverage, not a fixed narrow band). (g — L.3.A/L.3.C) Cascades `>= FIRST_CACHED_CASCADE` run under `FarCascadePolicy` (shipped: `LiveC2` — c2 re-fits every frame, c3 stays cached). A frozen window is safe to sample ONLY through the **two-phase commit**: `c_far_pending` is set when the matrix changes and cleared ONLY by a pass that actually rendered that layer — never treat a cached GPU resource as filled because its CPU parameters were updated. That one write is also what makes both pass gates policy-aware; bypassing it for a live cascade yields right-matrix/stale-map. A cascade carries the drift pad **iff** its window can freeze — the pad is not free (padded c2 renders 1.880 m texels against 1.491 m live). (h — L.3.C resolution) The receiver-bias cap is DERIVED from the fits the renderer just computed (`min(1, c1_depth / this_depth)`, delivered in `MainLightUbo.bias_scales`), never a constant: constants derived from a *model* of the fits shipped 8.5% wrong. (i — verification, L.3.A→L.3.C, director-ratified) Camera-fitted or temporally-cached shadow work is verified by **continuous per-frame legs** (no settle, no toggling), with **refresh telemetry per far cascade** wherever any cache survives, and measured by **twin deterministic flights differenced** (`off[i] − on[i]`) so view-dependent shading cancels; static stations alone are never sufficient, and no metric is trusted until it has been shown to RESPOND to a change whose sign is already known. | Yes | `shadow_common.wgsl` (single implementation + `bias_scales`); `create_shadow_bgl` (shared constructor); the sentinel contract tests (`test_shadow_override_sentinel_logic`, `test_shader_has_conditional_shadow_not_hardcoded`); `renderer.rs` `FarCascadePolicy` / `CascadeFit` / `shadow_cascade_fits` / `shadow_far_telemetry`; `docs/audits/L3_OUTCOME.md`, `L3A_OUTCOME.md`, `L3B_OUTCOME.md`, `L3C_OUTCOME.md`, `L3C_RESOLUTION_OUTCOME.md` | | 21 | Same-named `#[repr(C)]` Rust structs and WGSL `var` / `var` structs share size and field offsets. `vec3` is 16-byte aligned in WGSL. `FogDensityParams` is 160 bytes (`froxel_dims` at 96, `wind_dir` at 144). `ScatterParams` is 176 bytes. `CascadeData` storage stride is 96. | Yes | `tests/wgsl_struct_layout.rs` walks `shaders/` and `src/`. | | 22 | **Fate-scars do not add a volumetric pass.** A 32³ world-space texture is sampled by `fog_density.wgsl` at the froxel's world position and written into the existing density volume (R density, G forward weight, B tint). `scatter.wgsl` consumes those channels. The froxel dimensions stay the quality preset. WGSL does not read `i64`, and the scar is not addressed by `froxel_idx % 64`. Fog-off (`enabled == false`, or no pass) uploads nothing. | Yes | `scar_shader_samples_world_space_and_has_no_i64`; `Renderer::upload_veil_scar_volume` returns before work when fog is absent | diff --git a/docs/current/WIRING_CAMPAIGN.md b/docs/current/WIRING_CAMPAIGN.md new file mode 100644 index 0000000000..3bc7750c38 --- /dev/null +++ b/docs/current/WIRING_CAMPAIGN.md @@ -0,0 +1,87 @@ +# Wiring campaign + +Inventory of systems that compile and are not on the default runtime path. Base is `main` at `8b4caa27`. One pull request per system. + +A wiring pull request may add a runtime caller and a quality setting. The default stays off until `gpu_frame_budget --scene heavy` with that pass's flag prints `median_gpu_frame_ms` at or under 11 on a GTX 1660 Ti. The user runs those captures. An RTX 4060 Ti debug run is not that column. Lavapipe time is not that column. No pass is turned on from an estimate. + +The published heavy-scene GPU frame is 3.688 ms (`939a21bb`, GTX 1660 Ti Max-Q, Vulkan, 1920×1080, 30 warmup + 120 samples). That number is the baseline row. It is not a sum we can add estimates to. + +Presentation passes must not write simulation state and must not read a wall clock or an unseeded RNG. + +#371 (heavy-scene water) and #372 (GPU culling CPU fallback) belong to the render workstream. This campaign does not edit them. + +## What 7.397 ms is + +The same heavy scene was 11.085 ms before the cloud-shadow amortization and 3.688 ms after it. The difference, 7.397 ms, is that `CloudShadowPass` change. `gpu_frame_budget` does not call `set_cloud_raymarch_enabled`, so 7.397 ms is not a `VolumetricCloudsPass` measurement. The raymarch cost is unmeasured. + +## Measured column + +A cell is filled only by a GTX 1660 Ti heavy-scene run whose validation scope is clean and whose command line enables exactly one gated pass. This binary rejects an enabled gated flag before it builds the scene, including bare `--atmosphere`, `--atmosphere=true`, and `--atmosphere true`. `--atmosphere=false` and `--atmosphere false` are off and do not bail. Every gated cell on this binary stays blank. Every gated default stays off. #395 is the atmosphere measurement. It prints `atmosphere_with_aravath_fog` only when both fog and shafts build. Otherwise it bails and prints no median. + +| System | Flag | `median_gpu_frame_ms` on GTX 1660 Ti heavy | Default | +|---|---|---|---| +| Baseline (HDRI sky, no gated pass) | none | 3.688 | The captured scene | +| Atmosphere, replacing `SkyRenderer` | `--atmosphere` | #395 prints `atmosphere_with_aravath_fog` only when both fog and shafts build. Otherwise it bails and there is no median. | Off. This binary rejects an enabled `--atmosphere`. | +| SSGI, TAA, temporal upscale | `--ssgi`, `--taa`, `--upscale` | No median counts. Each pass writes its own texture. `record_gated_presentation` never copies that texture onto `hdr_tex`. The presented frame samples HDR. A history fix alone can still print a median of a frame that does not show the pass. | Off. | + +Fog and god rays remain callers in `light_the_world` when volumetrics are on. #395 does not remove those setters. #395 owns the clear, the sky sample, and the sun. `parse_volumetrics_cfg` strips spaces and a `#` comment, then matches the remainder to `volumetrics=off` or `volumetrics=on`. The last matching key wins. A later line that is not one of those two keys leaves the value alone. A missing file stays on. A read or parse error stops startup. `launch_options` applies the file first. `--no-volumetrics` and `--safe` force off. `--volumetrics` forces on, including over a cfg-off file. They are not in the 3.688 ms capture. Their heavy-scene medians are blank. Do not add them into an unmeasured sum. + +## Already on a runtime caller + +| System | State | Owner | Default | +|---|---|---|---| +| Volumetric fog (`VolumetricFogPass`) | `light_the_world` calls `set_volumetric_fog_config` with `gameplay_config` unless the last matching `aravath.cfg` key is `volumetrics=off`, or the process is started with `--no-volumetrics` or `--safe`. `--volumetrics` forces the pass on. That call remains. #395 does not remove it. | `astraweave-render`, `aravath_runtime` | On in the game. Issue #227. Heavy-scene median is unmeasured. | +| God rays (`GodRayPass`) | `light_the_world` calls `set_god_ray_config` (half resolution, 32 samples) on that same path. That call remains. #395 does not remove it. | `astraweave-render`, `aravath_runtime` | On in the game. Issue #228. Heavy-scene median is unmeasured. | +| Cloud shadows | `CloudShadowPass` is built in `Renderer::new`. The 3.688 ms capture includes it at 0.323 ms. | `astraweave-render` | On. This is not `VolumetricCloudsPass`. | + +## Prerequisite before SSGI and TAA + +`record_gated_presentation` allocates `gated_normal` and `gated_velocity` when SSGI, TAA, or temporal upscale is on. Nothing writes those textures. SSGI and TAA sample them. Wiring either pass waits on a pass that writes both targets from the scene. That prerequisite is its own pull request, and it stays off the default until its own heavy-scene median is filled in. + +| Order | System | Current state | Wiring plan | Owner crate | Exit test | +|---|---|---|---|---|---| +| 0 | Scene normal and velocity | Uninitialized `Rgba16Float` and `Rg16Float` targets. Nothing clears them. No draw call stores a normal or a motion vector. | A presentation pass clears both, draws them, and only then may SSGI or TAA sample them. Quality default off. | `astraweave-render` | With the pass enabled, a headless frame's normal and velocity textures hold the drawn values. With it disabled, SSGI and TAA stay off. Replay hashes unchanged. | + +## Wire next, one PR each + +Defaults stay off. A later pull flips a default only after the measured cell above is ≤ 11 on a GTX 1660 Ti. + +| Order | System | Issue | Current state | Wiring plan | Owner crate | Exit test | +|---|---|---|---|---|---|---| +| 1 | Atmosphere (`AtmospherePass`) | #226 | Flag defaults false. This binary rejects an enabled `--atmosphere`. #395 prints `atmosphere_with_aravath_fog` only when both fog and shafts build; otherwise it bails and prints no median. `record_gated_presentation` on this head calls `prepare_frame` with sun `Vec3::Y`, moon `Vec3::NEG_Y`, near `0.1`, and far `200.0`. | #395 is the one caller. It owns the clear, the sky sample, and the sun. The zenith sun on this head is that pull's gap. #226 tracks the pull. Fog and god rays stay on `light_the_world`. #395 does not remove those setters. Default stays off. | `astraweave-render` | This inventory does not enable the flag. Replay hashes unchanged. | +| 2 | Depth of field | #232 | `set_dof_enabled` defaults false. Live shader is `advanced_post.rs` `DOF_SHADER`: `texture_depth_2d`, center sample plus 8 offsets (9 taps). `apply_dof` writes `AdvancedPostFx`'s texture labeled `"TAA History"` (`history_view`) with `LoadOp::Load`. `AdvancedPostFx::new` never clears it. That texture is not `TaaPass`'s `taa_history`. The post pass still reads HDR. `shaders/dof.wgsl` is a different 16-tap `texture_2d` shader and is not this pass. | The shared history name is a conflict. DoF and TAA stay at their defaults until those histories are separate, the DoF target is cleared, and the post pass reads the 9-tap output. No `--dof` before that. | `astraweave-render` | Default stays off. No measured cell until the histories are separate. | +| 3 | Cloud raymarch (`VolumetricCloudsPass`) | #229 | `execute` samples `cloud_history` and writes `composited_texture`. `copy_cloud_to_history` runs after the sample. `record_gated_presentation` does not copy the composite onto HDR. | Write history before the sample, and copy the composite onto HDR. Then add `--clouds`. Not the 7.397 ms shadow delta. | `astraweave-render` | A clean scope and a median of a frame that shows the composite. Default stays off until that cell is ≤ 11. | +| 4 | SSGI | #230 | `set_ssgi_enabled` defaults false. Depth is `texture_depth_2d`. The pass writes its own texture. Normal, velocity, and `ssgi_history` are not written. `record_gated_presentation` does not call `copy_to_history` and does not copy the pass onto `hdr_tex`. | After the normal and velocity row, and after the pass is copied onto `hdr_tex` so the presented frame contains it. | `astraweave-render` | No `--ssgi` median until the presented frame contains the pass. | +| 5 | TAA | #231 | `set_taa_enabled` defaults false. `next_frame` and `apply_jitter_to_projection` have no caller. `TaaPass` writes its own texture and samples `taa_history`. `record_gated_presentation` does not copy that texture onto `hdr_tex`. DoF writes a different texture labeled `"TAA History"`. | After the normal and velocity row, with jitter applied, history written first, and the pass copied onto `hdr_tex`. The DoF texture is not that history. The name collision blocks a TAA default. | `astraweave-render` | Default stays off. No `--taa` median until the presented frame contains the pass and the histories are separate. | +| 6 | Temporal upscale | #233 | `upscale_on` defaults false. The pass writes its own texture and reads the unwritten velocity target. `record_gated_presentation` does not copy that texture onto `hdr_tex`. | After the normal and velocity row, and after the pass is copied onto `hdr_tex`. | `astraweave-render` | Default stays false. No `--upscale` median until the presented frame contains the pass. | + +## Do not add a second pipeline + +| System | Issue | What is in the tree | Why it is not a wiring target | +|---|---|---|---| +| `SkyPassNode` | #234 | `frame_graph.rs`. `run` returns `Ok(())`. | Live sky is `SkyRenderer`. `AtmospherePass` is not a second sky on screen. | +| `weather_system.rs` | #236 | Still compiled. Tests construct `WeatherTransition`. | Live weather is `effects::WeatherFx` and `SceneEnvironment`. A second weather model is not a feature. | +| `shadow_csm.rs` | #238 | Still compiled. This is a second cascade map. | Live cascades are `renderer.rs` and `shaders/shadow_common.wgsl`. | +| `shadow_quality.rs`, `shadow_sampling.wgsl` | #238 | Still compiled. This is the PCSS / Poisson filter and `ShadowParamsGpu`. It is not another cascade atlas. | The live cascade path does not sample this filter. | + +`VolumetricFogNode`, `BrdfLutPass`, and `weather_gpu.rs` are not in the tree. They are not rows. + +## Owned elsewhere + +| System | Issue | State | This campaign | +|---|---|---|---| +| Heavy-scene water | #371 | The heavy scene does not draw water. The capture's water pass is 0.003 ms. | Skip. Render workstream. | +| GPU culling CPU fallback | #372 | `gpu_cull=cpu_fallback` on every adapter. | Skip. Render workstream. | +| `AIArbiter`, advanced GOAP, `GoapPlanner` | #334, #383 | Feature-gated. Off `sys_ai_planning` and `sys_spatial_tick`. | Do not flip the features into the tick. `shadow_mode` and GOAP telemetry read `Instant`. The port is #383. Exit: replay hashes unchanged. | +| `recorded_line` | none new | Pure helper in `astraweave-dialogue`. Callers are its tests. | Later dialogue pull. Exit: one non-test caller that does not draw. | + +## Order + +1. This inventory. `gpu_frame_budget` rejects an enabled gated flag, including `--atmosphere`. `--flag false` is off. Every gated cell on this binary stays blank. #395 prints `atmosphere_with_aravath_fog` only when both fog and shafts build; otherwise it bails and there is no median. Defaults stay off. +2. No second atmosphere caller. #395 is that caller, and #226 tracks it. +3. Normal and velocity targets, default off. +4. Depth of field, cloud raymarch, SSGI, TAA, temporal upscale. SSGI, TAA, and upscale write their own textures, and `record_gated_presentation` never copies them onto `hdr_tex`, so no median counts until the presented frame contains the pass. Each default stays off until its measured cell is ≤ 11 on a GTX 1660 Ti. +5. Fog and god rays remain callers in `light_the_world`. #395 does not remove them. +6. #234, #236, and #238 are not second implementations. +7. #371 and #372 are not this campaign. +8. #334 and #383 stay off the tick until the port in #383.