From e3b5b2ab91fb160885813fda8f9e0a505e602de5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:53:36 +0100 Subject: [PATCH 1/7] Shadow budget in views: graphics.shadow_views, a point light 6 and a spot 1 graphics.shadow_views (0 to 384, default 0) counts the shadow budget in shadow views instead of lights: the lights that ask go nearest first, each taking its views while they fit, and a farther light that fits may still cast one. Above 0 it replaces shadow_lights; at 0 nothing changes, tool texts included. The lights query and ai/status say the budget in views, how many are taken, and what a light that missed out takes. Co-Authored-By: Claude Opus 5.5 --- crates/shards_light/src/budget.rs | 79 +++++++++++++++++---- crates/shards_light/src/lib.rs | 61 ++++++++++++---- crates/shards_light/src/tools.rs | 50 ++++++++++--- crates/shards_light/tests/light/headless.rs | 30 ++++++++ crates/shards_settings/src/groups.rs | 50 +++++++++++++ crates/shards_settings/src/lib.rs | 2 +- 6 files changed, 236 insertions(+), 36 deletions(-) diff --git a/crates/shards_light/src/budget.rs b/crates/shards_light/src/budget.rs index d88426f3..564c41bd 100644 --- a/crates/shards_light/src/budget.rs +++ b/crates/shards_light/src/budget.rs @@ -1,4 +1,6 @@ -//! The shadow budget: of the lights that want shadows, only the nearest `budget` to the viewer get them. +//! The shadow budget: of the lights that want shadows, only the nearest to the viewer get them, as many as the +//! budget holds: so many lights (`graphics.shadow_lights`), or so many shadow views (`graphics.shadow_views`: a +//! point light's cube is 6, a spot is 1). //! //! A pure function of the lights and the viewer, so a picture and a headless `lights` query agree and a //! shot taken twice from one place shows the same shadows. There is no hysteresis: a light that is @@ -6,6 +8,13 @@ use std::cmp::Ordering; +pub use shards_settings::ShadowBudget; + +/// The shadow views a point light takes: its shadow is a cube map, six passes. +pub const POINT_VIEWS: usize = 6; +/// The shadow views a spot light takes: one pass. +pub const SPOT_VIEWS: usize = 1; + /// One light that is a candidate for a shadow. #[derive(Clone, Debug, PartialEq)] pub struct Candidate<'a> { @@ -15,6 +24,8 @@ pub struct Candidate<'a> { pub key: &'a str, /// Whether its content asks for shadows. pub wants: bool, + /// The shadow views its shadow takes ([`POINT_VIEWS`], [`SPOT_VIEWS`]); only a budget in views reads it. + pub views: usize, } /// Distances are compared to the centimetre, so a viewer that stands still on a boundary does not flip a @@ -24,42 +35,84 @@ fn rank(a: &Candidate, b: &Candidate) -> Ordering { cm(a).cmp(&cm(b)).then_with(|| a.key.cmp(b.key)) } -/// Which of `lights` cast a shadow, in the same order: the first `budget` of those that want one, nearest -/// first. A light that does not want shadows never has one. -pub fn casters(lights: &[Candidate], budget: usize) -> Vec { +/// Which of `lights` cast a shadow, in the same order, nearest first: under [`ShadowBudget::Lights`] the first +/// that many of those that want one; under [`ShadowBudget::Views`] each in turn while its views fit in what is +/// left (a near point light that does not fit has none, and a farther spot that does fit has one). A light that +/// does not want shadows never has one. +pub fn casters(lights: &[Candidate], budget: ShadowBudget) -> Vec { let mut wanting: Vec = (0..lights.len()).filter(|i| lights[*i].wants && lights[*i].distance.is_finite()).collect(); wanting.sort_by(|a, b| rank(&lights[*a], &lights[*b]).then(a.cmp(b))); let mut out = vec![false; lights.len()]; - for i in wanting.into_iter().take(budget) { - out[i] = true; + match budget { + ShadowBudget::Lights(n) => { + for i in wanting.into_iter().take(n) { + out[i] = true; + } + } + ShadowBudget::Views(mut left) => { + for i in wanting { + let cost = lights[i].views.max(1); + if cost <= left { + left -= cost; + out[i] = true; + } + } + } } out } +/// The shadow views the casters take, by [`casters`]' answer. +pub fn views_used(lights: &[Candidate], casts: &[bool]) -> usize { + lights.iter().zip(casts).filter(|(_, c)| **c).map(|(l, _)| l.views.max(1)).sum() +} + #[cfg(test)] mod tests { use super::*; fn lights<'a>(list: &[(f32, &'a str, bool)]) -> Vec> { - list.iter().map(|(distance, key, wants)| Candidate { distance: *distance, key, wants: *wants }).collect() + list.iter().map(|(distance, key, wants)| Candidate { distance: *distance, key, wants: *wants, views: POINT_VIEWS }).collect() + } + + const fn n(lights: usize) -> ShadowBudget { + ShadowBudget::Lights(lights) } #[test] fn the_nearest_that_want_a_shadow_get_one() { let all = lights(&[(9.0, "c", true), (2.0, "a", true), (5.0, "b", true), (1.0, "n", false), (30.0, "z", true)]); - assert_eq!(casters(&all, 2), [false, true, true, false, false]); - assert_eq!(casters(&all, 0), [false; 5], "a budget of 0 is no shadows"); - assert_eq!(casters(&all, 99), [true, true, true, false, true], "a light that does not want one never has one"); + assert_eq!(casters(&all, n(2)), [false, true, true, false, false]); + assert_eq!(casters(&all, n(0)), [false; 5], "a budget of 0 is no shadows"); + assert_eq!(casters(&all, n(99)), [true, true, true, false, true], "a light that does not want one never has one"); + } + + #[test] + fn a_budget_in_views_lets_many_spots_shadow_where_one_point_would() { + let mut all = lights(&[(1.0, "point", true), (2.0, "s1", true), (3.0, "s2", true), (4.0, "s3", true), (5.0, "far point", true)]); + for spot in &mut all[1..4] { + spot.views = SPOT_VIEWS; + } + let casts = casters(&all, ShadowBudget::Views(6)); + assert_eq!(casts, [true, false, false, false, false], "the nearest point takes the whole cube"); + let casts = casters(&all, ShadowBudget::Views(8)); + assert_eq!(casts, [true, true, true, false, false], "then two spots in the two views left"); + assert_eq!(views_used(&all, &casts), 8); + let casts = casters(&all, ShadowBudget::Views(5)); + assert_eq!(casts, [false, true, true, true, false], "a point that does not fit has none; the spots behind it that fit do"); + assert_eq!(views_used(&all, &casts), 3); + assert_eq!(casters(&all, ShadowBudget::Views(0)), [false; 5]); + assert_eq!(casters(&all, ShadowBudget::Views(15)), [true, true, true, true, true]); } #[test] fn ties_go_by_key_and_the_order_of_the_list_does_not_matter() { let a = lights(&[(4.0, "lamp.b", true), (4.001, "lamp.a", true), (4.0, "lamp.c", true)]); // To the centimetre all three are 4 m: the key decides. - assert_eq!(casters(&a, 1), [false, true, false]); + assert_eq!(casters(&a, n(1)), [false, true, false]); let b = lights(&[(4.0, "lamp.c", true), (4.0, "lamp.a", true), (4.0, "lamp.b", true)]); - assert_eq!(casters(&b, 2), [false, true, true]); + assert_eq!(casters(&b, n(2)), [false, true, true]); let nan = lights(&[(f32::NAN, "x", true), (1.0, "y", true)]); - assert_eq!(casters(&nan, 2), [false, true], "a light with no distance has no shadow"); + assert_eq!(casters(&nan, n(2)), [false, true], "a light with no distance has no shadow"); } } diff --git a/crates/shards_light/src/lib.rs b/crates/shards_light/src/lib.rs index 701f908a..3e82a956 100644 --- a/crates/shards_light/src/lib.rs +++ b/crates/shards_light/src/lib.rs @@ -16,7 +16,8 @@ //! noise of a depth. //! - **Shadow budget.** `graphics.shadow_lights` (default 4, none under `graphics.shadows = "off"`): of the lights //! whose content says `shadows: true`, the nearest that many to the viewer (the active camera, else the local player) -//! cast shadows, ties by a stable key ([`budget::casters`]). +//! cast shadows, ties by a stable key ([`budget::casters`]). `graphics.shadow_views` above 0 counts the budget in +//! shadow views instead (a point light 6, a spot 1), nearest first, and replaces `shadow_lights`. //! - **For the AI:** the `lights` query (counts by kind, who casts a shadow now, who flickers and how bright, the //! picture's grading and its blend) and `light` in `ai/status`. //! @@ -43,6 +44,7 @@ use shards_core::{EngineAppExt, LocalPlayer}; use shards_motion::camera::{picture_clock, FirstPersonCamera, ThirdPersonCamera}; use shards_settings::{AccessibilitySettings, FlashLevel, GraphicsSettings}; +pub use budget::ShadowBudget; pub use def::{kelvin_srgb, Flicker, LightDef, LightKind, MAX_RANGE}; pub use tools::LightsArgs; @@ -137,9 +139,20 @@ pub struct LightInfo { pub distance: Option, } +impl LightInfo { + /// The shadow views its shadow takes: 6 for a point light (a cube), 1 for a spot, 0 with no definition. + pub fn shadow_views(&self) -> usize { + match self.def.as_ref().map(|d| d.kind) { + Some(LightKind::Point) => budget::POINT_VIEWS, + Some(LightKind::Spot { .. }) => budget::SPOT_VIEWS, + None => 0, + } + } +} + /// Where the picture's lights stand now: refreshed every frame, and by the `lights` query. The picture's, never /// the simulation's (no `AiId`, not in a snapshot or a replay). -#[derive(Resource, Clone, Debug, Default, PartialEq)] +#[derive(Resource, Clone, Debug, PartialEq)] pub struct LightState { /// Every content light, in key order. pub lights: Vec, @@ -147,12 +160,27 @@ pub struct LightState { pub clock: f64, /// The viewer the shadow budget measures from, and what it is (`camera`, `player`). pub viewer: Option<(Vec3, &'static str)>, - /// How many lights may cast a shadow. - pub budget: usize, + /// How many lights, or shadow views, may cast a shadow. + pub budget: ShadowBudget, + /// The shadow views the lights that cast one take now (a point light 6, a spot 1), whatever the budget counts. + pub views_used: usize, /// The player's `accessibility.flashes`: what flickers is slower and shallower (`Reduced`) or steady (`Off`). pub flashes: FlashLevel, } +impl Default for LightState { + fn default() -> Self { + Self { + lights: Vec::new(), + clock: 0.0, + viewer: None, + budget: ShadowBudget::Lights(DEFAULT_SHADOW_LIGHTS), + views_used: 0, + flashes: FlashLevel::default(), + } + } +} + impl LightState { /// The lights that cast a shadow now. pub fn casting(&self) -> impl Iterator { @@ -219,7 +247,7 @@ fn update_state( mut seeds: ResMut, ) { let clock = picture_clock(&fixed); - let budget = settings.as_ref().map_or(DEFAULT_SHADOW_LIGHTS, |s| s.shadow_light_budget()); + let budget = settings.as_ref().map_or(ShadowBudget::Lights(DEFAULT_SHADOW_LIGHTS), |s| s.shadow_budget()); let flashes = accessibility.as_ref().map_or(FlashLevel::Full, |a| a.flash_level()); let viewer = cameras .iter() @@ -259,25 +287,34 @@ fn update_state( seeds.forget_unplaced(&placed); // Key order, then place: never the order of a query. lights.sort_by(|a, b| a.key.cmp(&b.key).then_with(|| a.position.to_array().map(f32::to_bits).cmp(&b.position.to_array().map(f32::to_bits)))); - let candidates: Vec = - lights.iter().map(|l| budget::Candidate { distance: l.distance.unwrap_or(0.0), key: &l.key, wants: l.wants_shadow }).collect(); + let candidates: Vec = lights + .iter() + .map(|l| budget::Candidate { distance: l.distance.unwrap_or(0.0), key: &l.key, wants: l.wants_shadow, views: l.shadow_views() }) + .collect(); let casts = budget::casters(&candidates, budget); + let views_used = budget::views_used(&candidates, &casts); for (light, casts) in lights.iter_mut().zip(casts) { light.casts = casts; } - let next = LightState { lights, clock, viewer, budget, flashes }; + let next = LightState { lights, clock, viewer, budget, views_used, flashes }; if *state != next { *state = next; } } -/// `ai/status` → `light: {lights, casting, flickering, budget}`. +/// `ai/status` → `light: {lights, casting, flickering, budget}`, and `budget_views` (the budget counts views, a point +/// light 6, a spot 1) with `views_used` while `graphics.shadow_views` is set. fn status(world: &World) -> Value { let Some(state) = world.get_resource::() else { return json!({}) }; - json!({ + let mut out = json!({ "lights": state.lights.len(), "casting": state.casting().count(), "flickering": state.flickering().count(), - "budget": state.budget, - }) + "budget": state.budget.amount(), + }); + if let ShadowBudget::Views(_) = state.budget { + out["budget_views"] = json!(true); + out["views_used"] = json!(state.views_used); + } + out } diff --git a/crates/shards_light/src/tools.rs b/crates/shards_light/src/tools.rs index 5014b354..3c50bd7c 100644 --- a/crates/shards_light/src/tools.rs +++ b/crates/shards_light/src/tools.rs @@ -10,14 +10,15 @@ use shards_content::ContentDb; use shards_motion::camera::{picture_clock, CameraTuning, Grading, GradingBlend, GradingDef}; use shards_settings::FlashLevel; -use crate::{update_state, Flicker, LightDef, LightInfo, LightState}; +use crate::{update_state, Flicker, LightDef, LightInfo, LightState, ShadowBudget}; pub(crate) fn register(world: &mut World) { register_tool(world, "lights", Scope::Player, ToolKind::Query, lights); } /// What the picture's lights and colour grade are doing now: the content lights by kind, who flickers and how bright -/// each is at this moment, who casts a shadow and why the others do not, and the grade the camera shows with the +/// each is at this moment, who casts a shadow and why the others do not (against `graphics.shadow_lights`, or against +/// `graphics.shadow_views` when it is set: a point light takes 6 views, a spot 1), and the grade the camera shows with the /// progress of its blend toward or away from a grading volume. Pictures only: it is the same headless, from the /// simulation's clock. #[derive(Deserialize, JsonSchema, Default)] @@ -45,12 +46,41 @@ fn flicker_text(light: &LightInfo, def: &LightDef) -> String { } } -fn shadow_text(light: &LightInfo, state: &LightState) -> &'static str { - match (light.wants_shadow, light.casts) { - (true, true) => "shadow: yes", - (true, false) if state.budget == 0 => "shadow: no (budget 0)", - (true, false) => "shadow: no (over the budget)", - (false, _) => "shadow: not asked", +fn shadow_text(light: &LightInfo, state: &LightState) -> String { + match (light.wants_shadow, light.casts, state.budget) { + (true, true, ShadowBudget::Lights(_)) => "shadow: yes".to_owned(), + (true, true, ShadowBudget::Views(_)) => format!("shadow: yes ({} {})", light.shadow_views(), views_word(light.shadow_views())), + (true, false, budget) if budget.amount() == 0 => "shadow: no (budget 0)".to_owned(), + (true, false, ShadowBudget::Lights(_)) => "shadow: no (over the budget)".to_owned(), + // Nearer lights took the views; this one did not fit in what they left (a farther spot may have). + (true, false, ShadowBudget::Views(n)) => format!( + "shadow: no (over the budget: it takes {} {}, {} of {n} left after the nearer lights)", + light.shadow_views(), + views_word(light.shadow_views()), + left_before(light, state, n), + ), + (false, ..) => "shadow: not asked".to_owned(), + } +} + +fn views_word(n: usize) -> &'static str { + if n == 1 { "view" } else { "views" } +} + +/// The views the casters nearer than `light` left of `budget`: what it did not fit in. +fn left_before(light: &LightInfo, state: &LightState, budget: usize) -> usize { + let me = light.distance.unwrap_or(0.0); + let nearer: usize = state.casting().filter(|l| l.distance.unwrap_or(0.0) <= me).map(LightInfo::shadow_views).sum(); + budget.saturating_sub(nearer) +} + +/// The budget on the head line: as it always read for a budget of lights, with the views taken for one of views. +fn budget_text(state: &LightState) -> String { + match state.budget { + ShadowBudget::Lights(n) => format!("budget {n}: graphics.shadow_lights"), + ShadowBudget::Views(n) => { + format!("budget {n} views, {} taken: graphics.shadow_views, a point light takes 6 and a spot 1", state.views_used) + } } } @@ -124,11 +154,11 @@ fn lights(In(call): In>, world: &mut World) -> ToolResult { kinds.push_str(&format!(", without a definition {undefined}")); } let mut out = vec![format!( - "lights: {} ({kinds}) · {} flicker · {wanting} want a shadow, {} cast one (budget {}: graphics.shadow_lights) · clock {:.3} s", + "lights: {} ({kinds}) · {} flicker · {wanting} want a shadow, {} cast one ({}) · clock {:.3} s", state.lights.len(), state.flickering().count(), state.casting().count(), - state.budget, + budget_text(state), state.clock, )]; out.push(match state.viewer { diff --git a/crates/shards_light/tests/light/headless.rs b/crates/shards_light/tests/light/headless.rs index c1bea39e..af825146 100644 --- a/crates/shards_light/tests/light/headless.rs +++ b/crates/shards_light/tests/light/headless.rs @@ -128,6 +128,36 @@ fn the_nearest_lights_that_ask_for_a_shadow_get_one() { assert_eq!(casting(&mut twins), ["Lamp.Y"], "the key decides a tie"); } +#[test] +fn a_budget_in_views_counts_a_point_light_as_six_and_a_spot_as_one() { + // `Lamp.A` (a point, 1 m) and `Lamp.D` (the spot, 3 m) ask for a shadow. + let (_assets, mut app) = room("views"); + app.world_mut().resource_mut::().shadow_views = 6; + assert_eq!(casting(&mut app), ["Lamp.A"], "the nearer point takes all six views"); + let said = ok(&mut app, "lights", json!({})); + assert!(said.contains("2 want a shadow, 1 cast one (budget 6 views, 6 taken: graphics.shadow_views"), "{said}"); + assert!(line(&said, "Lamp.A").contains("shadow: yes (6 views)"), "{said}"); + assert!(line(&said, "Lamp.D").contains("shadow: no (over the budget: it takes 1 view, 0 of 6 left after the nearer lights)"), "{said}"); + assert_eq!((status(&app)["budget"].clone(), status(&app)["budget_views"].clone(), status(&app)["views_used"].clone()), (json!(6), json!(true), json!(6))); + + // Five views: the point does not fit, the spot behind it does. `shadow_lights` is not read while views are set. + let mut graphics = app.world_mut().resource_mut::(); + (graphics.shadow_views, graphics.shadow_lights) = (5, 0); + assert_eq!(casting(&mut app), ["Lamp.D"]); + let said = ok(&mut app, "lights", json!({})); + assert!(line(&said, "Lamp.A").contains("it takes 6 views, 5 of 5 left"), "{said}"); + assert!(said.contains("budget 5 views, 1 taken"), "{said}"); + app.world_mut().resource_mut::().shadow_views = 7; + assert_eq!(casting(&mut app), ["Lamp.A", "Lamp.D"]); + + // Back to 0: lights are counted again, and the line reads as it always did. + *app.world_mut().resource_mut::() = GraphicsSettings { shadow_lights: 1, ..default() }; + assert_eq!(casting(&mut app), ["Lamp.A"]); + let said = ok(&mut app, "lights", json!({})); + assert!(said.contains("(budget 1: graphics.shadow_lights)") && line(&said, "Lamp.A").ends_with("shadow: yes"), "{said}"); + assert!(status(&app).get("budget_views").is_none()); +} + #[test] fn a_light_without_a_definition_is_named_and_draws_nothing() { let (_assets, mut app) = room("ghost"); diff --git a/crates/shards_settings/src/groups.rs b/crates/shards_settings/src/groups.rs index 88ce15c8..63155efb 100644 --- a/crates/shards_settings/src/groups.rs +++ b/crates/shards_settings/src/groups.rs @@ -78,6 +78,27 @@ impl ShadowQuality { /// The most lights from content that may cast shadows at once ([`GraphicsSettings::shadow_lights`]). pub const MAX_SHADOW_LIGHTS: u32 = 64; +/// The most shadow views the content lights may take at once ([`GraphicsSettings::shadow_views`]): 64 cube maps. +pub const MAX_SHADOW_VIEWS: u32 = 384; + +/// What the shadow budget of the content lights counts ([`GraphicsSettings::shadow_budget`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ShadowBudget { + /// So many lights, whatever they cost (`graphics.shadow_lights`). + Lights(usize), + /// So many shadow views (`graphics.shadow_views`): a point light takes 6 (a cube), a spot 1. + Views(usize), +} + +impl ShadowBudget { + /// The number, whatever it counts. + pub fn amount(self) -> usize { + match self { + ShadowBudget::Lights(n) | ShadowBudget::Views(n) => n, + } + } +} + /// Window and rendering. Applied to the primary window by [`apply_graphics`](crate::apply_graphics) /// while there is one; a headless game only keeps the values. #[derive(Resource, Reflect, SettingsGroup, Clone, Debug, PartialEq)] @@ -102,6 +123,12 @@ pub struct GraphicsSettings { /// [`GraphicsSettings::shadow_light_budget`]): a light that wants shadows and is farther than that many has none. /// Under `shadows = "off"` none does. A cube shadow map is six passes, so this is the knob for a weak GPU. pub shadow_lights: u32, + /// The same budget counted in shadow views instead of lights (1 to 384; 0, the default, counts lights by + /// `shadow_lights`): a point light's shadow is a cube of 6 views, a spot's is 1, and each view is a pass the render + /// thread prepares, so twelve views shadow twelve spots or two points. The nearest lights that ask take theirs first; + /// one that does not fit in what is left has none, and a farther one that fits does. When it is above 0, + /// `shadow_lights` is not read; `shadows = "off"` is still none ([`GraphicsSettings::shadow_budget`]). + pub shadow_views: u32, /// How much of the foliage and small props the scatter module strews (0 none to 1 all of it, /// [`GraphicsSettings::foliage_density`]): fewer instances of the same scatter, never others. pub foliage: f64, @@ -120,6 +147,7 @@ impl Default for GraphicsSettings { render_scale: 1.0, shadows: "high".into(), shadow_lights: 4, + shadow_views: 0, foliage: 1.0, interpolation: true, } @@ -155,6 +183,16 @@ impl GraphicsSettings { if self.shadow_quality() == ShadowQuality::Off { 0 } else { self.shadow_lights.min(MAX_SHADOW_LIGHTS) as usize } } + /// The shadow budget of the content lights now: `shadow_views` views when it is above 0 (at most 384), else + /// `shadow_lights` lights ([`Self::shadow_light_budget`]); nothing under `shadows = "off"`. + pub fn shadow_budget(&self) -> ShadowBudget { + if self.shadow_views == 0 { + return ShadowBudget::Lights(self.shadow_light_budget()); + } + let views = if self.shadow_quality() == ShadowQuality::Off { 0 } else { self.shadow_views.min(MAX_SHADOW_VIEWS) as usize }; + ShadowBudget::Views(views) + } + /// Why these values are not allowed, if they are not (what `settings_set` refuses). pub fn check(&self) -> Result<(), String> { if self.resolution.trim() != "auto" && self.window_size().is_none() { @@ -168,6 +206,12 @@ impl GraphicsSettings { if self.shadow_lights > MAX_SHADOW_LIGHTS { return Err(format!("graphics.shadow_lights {} is out of range: use a whole number from 0 to {MAX_SHADOW_LIGHTS}", self.shadow_lights)); } + if self.shadow_views > MAX_SHADOW_VIEWS { + return Err(format!( + "graphics.shadow_views {} is out of range: use a whole number from 0 (count lights by shadow_lights) to {MAX_SHADOW_VIEWS}", + self.shadow_views + )); + } if ShadowQuality::parse(&self.shadows).is_none() { return Err(format!("graphics.shadows `{}` is not one of {}", self.shadows, ShadowQuality::NAMES.join(", "))); } @@ -407,6 +451,10 @@ mod tests { assert_eq!(GraphicsSettings::default().shadow_light_budget(), 4, "four shadow lights by default"); assert_eq!(GraphicsSettings { shadow_lights: 1000, ..default() }.shadow_light_budget(), 64, "a hand-edited 1000 is the most"); assert_eq!(GraphicsSettings { shadows: "off".into(), ..default() }.shadow_light_budget(), 0, "no shadows is no shadow lights"); + assert_eq!(GraphicsSettings::default().shadow_budget(), ShadowBudget::Lights(4), "lights are counted until views are set"); + assert_eq!(GraphicsSettings { shadow_views: 12, shadow_lights: 1, ..default() }.shadow_budget(), ShadowBudget::Views(12), "views replace lights"); + assert_eq!(GraphicsSettings { shadow_views: 5000, ..default() }.shadow_budget(), ShadowBudget::Views(384)); + assert_eq!(GraphicsSettings { shadow_views: 12, shadows: "off".into(), ..default() }.shadow_budget(), ShadowBudget::Views(0)); let a = AccessibilitySettings { camera_shake: f64::NAN, fov_deg: 400.0, flashes: "strobe".into(), ..default() }; assert_eq!((a.shake(), a.fov(), a.flash_level()), (1.0, 120.0, FlashLevel::Full)); let audio = AudioSettings { master: 0.5, music: 0.5, ..default() }; @@ -424,6 +472,8 @@ mod tests { assert!(bad.contains("1920x1080"), "{bad}"); let bad = GraphicsSettings { shadow_lights: 65, ..default() }.check().unwrap_err(); assert!(bad.contains("graphics.shadow_lights 65") && bad.contains("0 to 64"), "{bad}"); + let bad = GraphicsSettings { shadow_views: 385, ..default() }.check().unwrap_err(); + assert!(bad.contains("graphics.shadow_views 385") && bad.contains("to 384"), "{bad}"); let mut controls = ControlSettings::default(); controls.hold_or_toggle.insert("gameplay.sprint".into(), "tap".into()); assert!(controls.check().unwrap_err().contains("press, hold, toggle")); diff --git a/crates/shards_settings/src/lib.rs b/crates/shards_settings/src/lib.rs index 472483cb..7092f525 100644 --- a/crates/shards_settings/src/lib.rs +++ b/crates/shards_settings/src/lib.rs @@ -56,7 +56,7 @@ use serde_json::{json, Value}; use shards_core::EngineAppExt; pub use bevy::settings::SettingsGroup; -pub use groups::{AccessibilitySettings, AudioSettings, ControlSettings, FlashLevel, GraphicsSettings, ShadowQuality}; +pub use groups::{AccessibilitySettings, AudioSettings, ControlSettings, FlashLevel, GraphicsSettings, ShadowBudget, ShadowQuality}; pub use registry::{watch_settings, SettingsAppExt, SettingsChanged, SettingsRegistry}; pub use file::{stored_entries, watch_store}; pub use store::{flush, flush_checked, install, save_soon, save_soon_in, Installed, SettingsAppId, SettingsStorage}; From 8330348c15e116e4575b55b227df42a13c39ff4c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:53:36 +0100 Subject: [PATCH 2/7] Camera picture: SSAO from content, with its prepasses and MSAA off picture.ssao: Some((quality, radius, thickness)) in the camera content gives the world cameras Bevy's ScreenSpaceAmbientOcclusion, the depth and normal prepasses they lack and Msaa::Off (Bevy draws no SSAO under MSAA), put back when another module takes a prepass away. Taking it out gives the camera back its own SSAO, MSAA and prepasses. The view model's camera follows the world camera's MSAA and has no SSAO. Off by default. Co-Authored-By: Claude Opus 5.5 --- .../shards/tests/action_render/view_model.rs | 30 +++ crates/shards_motion/Cargo.toml | 2 +- crates/shards_motion/src/camera/mod.rs | 2 +- crates/shards_motion/src/camera/picture.rs | 215 +++++++++++++++++- 4 files changed, 239 insertions(+), 10 deletions(-) diff --git a/crates/shards/tests/action_render/view_model.rs b/crates/shards/tests/action_render/view_model.rs index 63e2511d..6c5098cc 100644 --- a/crates/shards/tests/action_render/view_model.rs +++ b/crates/shards/tests/action_render/view_model.rs @@ -246,3 +246,33 @@ fn a_world_camera_that_grades_in_its_shaders_hands_its_grade_to_the_view_model_c app.update(); assert_eq!(grade_of(&app, vm), ColorGrading::default(), "under HDR the view model is drawn over the graded picture, ungraded"); } + +#[test] +fn ssao_on_the_world_camera_turns_its_msaa_off_and_the_view_model_camera_follows_without_ssao_of_its_own() { + use shards::bevy::pbr::ScreenSpaceAmbientOcclusion; + use shards::bevy::render::view::Msaa; + use shards::motion::camera::{PictureTuning, SsaoTuning}; + + let World3 { mut app, camera, .. } = scene("action_render_view_model_ssao"); + // A window's camera has MSAA (the render plugin's required component); the bare test app's does not, so give it one. + app.world_mut().entity_mut(camera).insert(Msaa::Sample4); + app.update(); + app.update(); + let vm = view_cameras(&mut app)[0]; + let msaa = |app: &App, e: Entity| app.world().get::(e).copied(); + assert_eq!(msaa(&app, vm), Some(Msaa::Sample4), "the two cameras share one main texture, so one sample count"); + + app.world_mut().resource_mut::().picture = PictureTuning { ssao: Some(SsaoTuning::default()), ..default() }; + app.update(); + app.update(); + assert!(app.world().get::(camera).is_some()); + assert_eq!(msaa(&app, camera), Some(Msaa::Off), "Bevy draws no SSAO under MSAA"); + assert_eq!(msaa(&app, vm), Some(Msaa::Off), "the view model's camera follows the world camera"); + assert!(app.world().get::(vm).is_none(), "the arms are drawn over the occluded world, with none of their own"); + + app.world_mut().resource_mut::().picture = PictureTuning::default(); + app.update(); + app.update(); + assert!(app.world().get::(camera).is_none()); + assert_eq!((msaa(&app, camera), msaa(&app, vm)), (Some(Msaa::Sample4), Some(Msaa::Sample4)), "both get their MSAA back"); +} diff --git a/crates/shards_motion/Cargo.toml b/crates/shards_motion/Cargo.toml index e81b5351..902a2a24 100644 --- a/crates/shards_motion/Cargo.toml +++ b/crates/shards_motion/Cargo.toml @@ -10,7 +10,7 @@ license.workspace = true [features] # The third-person camera systems and the collider overlay (they need a window to be seen; # the pure camera math and the data types are always built). -render = ["ai_core/render", "bevy/bevy_post_process", "bevy/bevy_light"] +render = ["ai_core/render", "bevy/bevy_post_process", "bevy/bevy_light", "bevy/bevy_pbr", "bevy/bevy_core_pipeline"] # Real gamepads through gilrs (needs libudev). Without it `Gamepad` entities still work, # a game or a test just has to spawn them. gamepad = ["bevy/bevy_gilrs"] diff --git a/crates/shards_motion/src/camera/mod.rs b/crates/shards_motion/src/camera/mod.rs index 0173974a..ad662a7c 100644 --- a/crates/shards_motion/src/camera/mod.rs +++ b/crates/shards_motion/src/camera/mod.rs @@ -53,7 +53,7 @@ pub use first_person::{ pub use grading::{picture_clock, Grading, GradingBlend, GradingDef, GradingVolume}; #[cfg(feature = "render")] pub use grading::GradingSet; -pub use picture::{BloomComposite, BloomTuning, PictureTuning, ToneMapping}; +pub use picture::{BloomComposite, BloomTuning, PictureTuning, SsaoQuality, SsaoTuning, ToneMapping}; pub use tuning::{ArmTuning, AutoCentreTuning, CameraOffsets, CameraTuning, FitTuning, FlickTuning, FramingTuning, TraumaTuning}; pub use shot::{ShotDef, ShotEnded, ShotKey, ShotPoint, ShotStarted, Shots}; diff --git a/crates/shards_motion/src/camera/picture.rs b/crates/shards_motion/src/camera/picture.rs index 18251699..c5ae08c5 100644 --- a/crates/shards_motion/src/camera/picture.rs +++ b/crates/shards_motion/src/camera/picture.rs @@ -1,6 +1,6 @@ //! The picture a camera draws ([`PictureTuning`], the `picture` of the `camera` content): its tone -//! mapping and its bloom. Both are left out by default, and then a camera keeps what the game -//! spawned it with: a game without a `picture` sees no change. +//! mapping, its bloom and its screen-space ambient occlusion. All are left out by default, and then a +//! camera keeps what the game spawned it with: a game without a `picture` sees no change. //! //! Bloom needs the camera to draw in HDR (Bevy's `Hdr`), which moves the tone mapping from each //! material's shader to a pass over the whole picture: the colours the materials compute are the @@ -8,6 +8,16 @@ //! mapping and the bloom instead of stopping at full. While the content gives a camera a bloom it //! draws in HDR; taking the bloom out of the content gives the camera back what it had. //! +//! SSAO ([`SsaoTuning`], Bevy's `ScreenSpaceAmbientOcclusion`) darkens the light that comes from no one +//! direction (an ambient light, an irradiance volume, an environment map) in creases and where things +//! meet, from the depth and normals of what is on screen; it never darkens a point, spot or directional +//! light, nor a lightmap's light (which has its occlusion baked in). It needs a depth and a normal prepass +//! and a camera without MSAA: while the content gives a camera SSAO, the camera gets the prepasses it +//! lacks (again, if another module takes one away) and `Msaa::Off`, and taking SSAO out of the content +//! gives it back its own MSAA and drops the prepasses it did not have. The view model's camera +//! (`shards_action`) copies the world camera's MSAA, so the two still share one main texture; it gets no +//! SSAO of its own (the arms are drawn over the occluded world). +//! //! Only the picture changes: the `camera` kind is not simulation content, and nothing here is in a //! snapshot or a replay. @@ -84,6 +94,44 @@ impl Default for BloomTuning { } } +/// How many samples SSAO takes for a pixel (Bevy's quality levels): more is smoother and dearer. +#[derive(Reflect, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SsaoQuality { + /// 4 samples a pixel. + Low, + /// 8. + Medium, + /// 18 (Bevy's default). + #[default] + High, + /// 54. + Ultra, +} + +/// Screen-space ambient occlusion (Bevy's `ScreenSpaceAmbientOcclusion`, whose defaults these are). +/// +/// ```ron +/// (quality: Medium, radius: 0.5, thickness: 0.25) +/// ``` +#[derive(Reflect, Serialize, Deserialize, Clone, Debug, PartialEq)] +#[reflect(Default)] +#[serde(default, deny_unknown_fields)] +pub struct SsaoTuning { + pub quality: SsaoQuality, + /// How far around a pixel the occluders are looked for (m, above 0): wider darkens broader corners, with more + /// haloes and noise. + pub radius: f32, + /// How thick everything on screen is taken to be (m, above 0): a ray that passes behind something closer than + /// this is occluded by it. + pub thickness: f32, +} + +impl Default for SsaoTuning { + fn default() -> Self { + Self { quality: SsaoQuality::High, radius: 0.5 * 1.457, thickness: 0.25 } + } +} + /// The picture a camera draws: each part left out leaves the camera as the game made it. /// /// ```ron @@ -104,6 +152,11 @@ pub struct PictureTuning { /// camera whose `tone_mapping` is `None` shows none of it. #[serde(skip_serializing_if = "Option::is_none")] pub grading: Option, + /// Screen-space ambient occlusion ([`SsaoTuning`]); `None` keeps the camera's own (none, unless the game gave it + /// one). It turns the camera's MSAA off while it is on (Bevy's SSAO needs that) and adds a depth and a normal + /// prepass. + #[serde(skip_serializing_if = "Option::is_none")] + pub ssao: Option, } impl PictureTuning { @@ -117,6 +170,13 @@ impl PictureTuning { if let Some(grading) = &self.grading { out.extend(grading.problems("picture.grading")); } + if let Some(ssao) = &self.ssao { + for (name, v) in [("radius", ssao.radius), ("thickness", ssao.thickness)] { + if !(v > 0.0 && v.is_finite()) { + out.push(format!("picture.ssao.{name}: above 0, not {v}")); + } + } + } let Some(bloom) = &self.bloom else { return out }; let at_least_zero = [ ("intensity", bloom.intensity), @@ -145,11 +205,13 @@ pub(super) use render::apply_picture; #[cfg(feature = "render")] mod render { use bevy::camera::Hdr; + use bevy::core_pipeline::prepass::{DepthPrepass, NormalPrepass}; + use bevy::pbr::{ScreenSpaceAmbientOcclusion, ScreenSpaceAmbientOcclusionQualityLevel}; use bevy::post_process::bloom::{Bloom, BloomCompositeMode, BloomPrefilter}; use bevy::prelude::*; - use bevy::render::view::Tonemapping; + use bevy::render::view::{Msaa, Tonemapping}; - use super::{BloomComposite, BloomTuning, ToneMapping}; + use super::{BloomComposite, BloomTuning, SsaoQuality, SsaoTuning, ToneMapping}; use crate::camera::{CameraTuning, FirstPersonCamera, ThirdPersonCamera}; impl ToneMapping { @@ -186,6 +248,21 @@ mod render { } } + impl SsaoTuning { + pub fn bevy(&self) -> ScreenSpaceAmbientOcclusion { + ScreenSpaceAmbientOcclusion { + quality_level: match self.quality { + SsaoQuality::Low => ScreenSpaceAmbientOcclusionQualityLevel::Low, + SsaoQuality::Medium => ScreenSpaceAmbientOcclusionQualityLevel::Medium, + SsaoQuality::High => ScreenSpaceAmbientOcclusionQualityLevel::High, + SsaoQuality::Ultra => ScreenSpaceAmbientOcclusionQualityLevel::Ultra, + }, + radius: self.radius, + constant_object_thickness: self.thickness, + } + } + } + /// What the content changed on a camera, kept so that taking it out of the content gives the /// camera back what it had. #[derive(Component, Clone, Default)] @@ -196,32 +273,61 @@ mod render { bloom: Option>, /// Whether the content's bloom made the camera draw in HDR (it did not before). hdr_added: bool, + /// The camera's own SSAO (or none) and MSAA (or none) while the content's SSAO is in force. + ssao: Option, + } + + /// What a camera had before the content gave it SSAO. + #[derive(Clone, Default)] + struct SsaoOwn { + ssao: Option, + msaa: Option, + /// The prepasses the content's SSAO added (the camera did not have them). + depth_added: bool, + normal_added: bool, } /// The cameras that appeared since the last frame. type NewCameras<'w, 's> = Query<'w, 's, (), Or<(Added, Added)>>; + /// What a camera's SSAO needs: its prepasses and no MSAA. + type SsaoNeeds = (Option<&'static ScreenSpaceAmbientOcclusion>, Option<&'static Msaa>, Has, Has); + /// The cameras a picture applies to, with what they have now. type Cameras<'w, 's> = Query< 'w, 's, - (Entity, Option<&'static Tonemapping>, Option<&'static Bloom>, Has, Option<&'static PictureSet>), + (Entity, Option<&'static Tonemapping>, Option<&'static Bloom>, Has, Option<&'static PictureSet>, SsaoNeeds), (With, Or<(With, With)>), >; + /// The cameras the content gave SSAO that lost what it needs since (another module took a prepass away, or + /// something turned MSAA back on). + type SsaoBroken<'w, 's> = Query< + 'w, + 's, + (Option<&'static Msaa>, Has, Has, &'static PictureSet), + (With, Or<(With, With)>), + >; + + fn ssao_broken(cameras: &SsaoBroken) -> bool { + cameras.iter().any(|(msaa, depth, normal, set)| set.ssao.is_some() && (!depth || !normal || msaa.is_some_and(|m| *m != Msaa::Off))) + } + /// `Update`: the `picture` of the camera tuning onto every 3D camera with a /// [`ThirdPersonCamera`] or [`FirstPersonCamera`], when the tuning changes and when such a camera appears. pub fn apply_picture( tuning: Res, added: NewCameras, cameras: Cameras, + broken: SsaoBroken, mut commands: Commands, ) { - if !tuning.is_changed() && added.is_empty() { + if !tuning.is_changed() && added.is_empty() && !ssao_broken(&broken) { return; } let picture = &tuning.picture; - for (entity, tone_mapping, bloom, hdr, set) in &cameras { + for (entity, tone_mapping, bloom, hdr, set, (ssao, msaa, depth, normal)) in &cameras { let mut set = set.cloned().unwrap_or_default(); let mut camera = commands.entity(entity); match (picture.tone_mapping, set.tone_mapping) { @@ -261,7 +367,54 @@ mod render { } (None, None) => {} } - if set.tone_mapping.is_none() && set.bloom.is_none() { + match (&picture.ssao, set.ssao.take()) { + (Some(want), own) => { + let mut own = own.unwrap_or_else(|| SsaoOwn { ssao: ssao.cloned(), msaa: msaa.copied(), ..default() }); + // The prepasses go in before the SSAO, whose own required ones would hide what the camera lacked. + if !depth { + camera.insert(DepthPrepass); + own.depth_added = true; + } + if !normal { + camera.insert(NormalPrepass); + own.normal_added = true; + } + if msaa != Some(&Msaa::Off) { + camera.insert(Msaa::Off); + } + let want = want.bevy(); + if ssao != Some(&want) { + camera.insert(want); + } + set.ssao = Some(own); + } + (None, Some(own)) => { + match own.ssao { + Some(theirs) => { + camera.insert(theirs); + } + None => { + camera.remove::(); + } + } + if own.depth_added { + camera.remove::(); + } + if own.normal_added { + camera.remove::(); + } + match own.msaa { + Some(msaa) => { + camera.insert(msaa); + } + None => { + camera.remove::(); + } + } + } + (None, None) => {} + } + if set.tone_mapping.is_none() && set.bloom.is_none() && set.ssao.is_none() { camera.remove::(); } else { camera.insert(set); @@ -331,6 +484,48 @@ mod render { assert_eq!(world.get::(camera), Some(&Tonemapping::Reinhard)); } + #[test] + fn the_contents_ssao_turns_msaa_off_adds_prepasses_and_gives_them_back() { + let (mut app, camera) = app(); + app.world_mut().entity_mut(camera).insert(Msaa::Sample4); + app.update(); + let ssao = SsaoTuning { quality: SsaoQuality::Medium, radius: 0.4, thickness: 0.1 }; + set(&mut app, PictureTuning { ssao: Some(ssao.clone()), ..default() }); + let world = app.world(); + let drawn = world.get::(camera).expect("SSAO"); + assert_eq!((drawn.quality_level, drawn.radius, drawn.constant_object_thickness), (ScreenSpaceAmbientOcclusionQualityLevel::Medium, 0.4, 0.1)); + assert_eq!(world.get::(camera), Some(&Msaa::Off), "Bevy's SSAO needs MSAA off"); + assert!(world.get::(camera).is_some() && world.get::(camera).is_some()); + + // Another module (the decals' depth prepass) takes a prepass away: it comes back the next frame. + app.world_mut().entity_mut(camera).remove::(); + app.world_mut().entity_mut(camera).insert(Msaa::Sample8); + app.update(); + assert!(app.world().get::(camera).is_some(), "SSAO without its prepass would draw nothing"); + assert_eq!(app.world().get::(camera), Some(&Msaa::Off)); + + set(&mut app, PictureTuning::default()); + let world = app.world(); + assert!(world.get::(camera).is_none()); + assert_eq!(world.get::(camera), Some(&Msaa::Sample4), "its own MSAA back"); + assert!(world.get::(camera).is_none() && world.get::(camera).is_none(), "no prepass it did not have"); + assert!(world.get::(camera).is_none()); + } + + #[test] + fn a_camera_with_prepasses_and_no_msaa_of_its_own_keeps_them_after_ssao() { + let (mut app, camera) = app(); + app.world_mut().entity_mut(camera).insert(DepthPrepass); + app.update(); + set(&mut app, PictureTuning { ssao: Some(SsaoTuning::default()), ..default() }); + assert_eq!(app.world().get::(camera), Some(&Msaa::Off)); + set(&mut app, PictureTuning::default()); + let world = app.world(); + assert!(world.get::(camera).is_some(), "the camera's own prepass stays"); + assert!(world.get::(camera).is_none(), "the one SSAO added goes"); + assert!(world.get::(camera).is_none(), "no MSAA component before, none after"); + } + #[test] fn a_camera_that_appears_later_gets_the_picture_too() { let (mut app, _) = app(); @@ -353,6 +548,10 @@ mod tests { let read: PictureTuning = ron::from_str("(bloom: Some((threshold: 1.15, composite: Additive)))").unwrap(); assert_eq!(read.bloom.as_ref().map(|b| (b.intensity, b.threshold, b.composite)), Some((0.15, 1.15, BloomComposite::Additive))); assert!(read.problems().is_empty()); + let read: PictureTuning = ron::from_str("(ssao: Some((quality: Low)))").unwrap(); + assert_eq!(read.ssao, Some(SsaoTuning { quality: SsaoQuality::Low, ..default() })); + let bad = PictureTuning { ssao: Some(SsaoTuning { radius: 0.0, thickness: f32::INFINITY, ..default() }), ..default() }; + assert_eq!(bad.problems(), ["picture.ssao.radius: above 0, not 0", "picture.ssao.thickness: above 0, not inf"]); let bad = PictureTuning { bloom: Some(BloomTuning { intensity: -1.0, high_pass_frequency: 0.0, threshold_softness: 2.0, threshold: f32::NAN, ..default() }), ..default() From d32caf0aa1031591e477ab6254a7edcee664c799 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:53:36 +0100 Subject: [PATCH 3/7] Baked light for levels: lightmaps and light probes, sets switched at run time Level nodes name their baked files (lightmap, lightmap_rect, irradiance_volume, reflection_probe, probe_falloff); the picture-only content kind baked_light names the folders of a level's sets and their exposure. A drawn level puts Bevy's Lightmap on the meshes (by their second UV map) and LightProbe with IrradianceVolume / EnvironmentMapLight on the probe boxes. select_baked_set switches a level's set (BakedLight, a resource of the picture); tools baked_light and baked_light_set. A content light with baked: true lights no lightmapped mesh's diffuse. Two Bevy 0.20 limits are worked around: a changed Lightmap on a mesh that has one is ignored (a switch takes the old one off for a frame once the new image is loaded), and a Lightmap that comes or goes does not pick the mesh's pipeline again (the mesh is marked changed with every one, or wgpu fails validation and Bevy stops drawing). Offscreen tests: a lightmapped mesh draws its lightmap, switches sets and still takes dynamic lights; and an ignored measurement of what SSAO costs on the GPU. Co-Authored-By: Claude Opus 5.5 --- crates/sandbox/tests/sandbox/state_audit.rs | 1 + crates/shards/tests/level_render.rs | 434 ++++++++++++ crates/shards_level/Cargo.toml | 2 +- crates/shards_level/src/asset.rs | 9 +- crates/shards_level/src/baked.rs | 723 ++++++++++++++++++++ crates/shards_level/src/lib.rs | 10 + crates/shards_level/src/props.rs | 83 ++- crates/shards_light/src/def.rs | 8 +- crates/shards_light/src/render.rs | 6 +- 9 files changed, 1267 insertions(+), 9 deletions(-) create mode 100644 crates/shards_level/src/baked.rs diff --git a/crates/sandbox/tests/sandbox/state_audit.rs b/crates/sandbox/tests/sandbox/state_audit.rs index 873ec4d2..2bf0ec91 100644 --- a/crates/sandbox/tests/sandbox/state_audit.rs +++ b/crates/sandbox/tests/sandbox/state_audit.rs @@ -151,6 +151,7 @@ const OUTSIDE: &[(&str, &str)] = &[ // shards_hitstop ("shards_hitstop::", "the hit stop log: what was held and why, never changing the world; the holds themselves are ai_core::hold's"), // shards_level + ("shards_level::baked::BakedLight", "the baked set each level draws: the picture's, which a game sets from its own saved state"), ("shards_level::library::LevelLibrary", "loaded level files: what the world is built around, which a snapshot check guards"), ("shards_level::spawn::LevelInstances", "the levels spawned, made again by the snapshot prepares `levels` and `placed levels`"), // shards_light diff --git a/crates/shards/tests/level_render.rs b/crates/shards/tests/level_render.rs index 76a318c5..0162562b 100644 --- a/crates/shards/tests/level_render.rs +++ b/crates/shards/tests/level_render.rs @@ -150,3 +150,437 @@ fn shows_its_scene(level: &str) { } assert!(!names.iter().any(|n| n == "Kit"), "{names:?}"); } + + +// --- baked light ------------------------------------------------------------------------------------------------ + +/// A folder of its own for one test's assets, removed afterwards. +struct BakedAssets(std::path::PathBuf); + +impl BakedAssets { + fn put(&self, file: &str, bytes: &[u8]) { + let path = self.0.join(file); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + + fn dir(&self) -> String { + self.0.to_string_lossy().into_owned() + } +} + +impl Drop for BakedAssets { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn base64(bytes: &[u8]) -> String { + const ABC: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + for chunk in bytes.chunks(3) { + let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)]; + let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + for i in 0..4 { + if i <= chunk.len() { + out.push(ABC[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + +/// A PNG of `width` x `height` (8-bit RGB, deflate's stored blocks, no compression), each pixel one of the colours +/// with channels 0 or 255. +fn png(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + fn crc(bytes: &[u8]) -> u32 { + let mut c = 0xffff_ffffu32; + for b in bytes { + c ^= u32::from(*b); + for _ in 0..8 { + c = if c & 1 == 1 { 0xedb8_8320 ^ (c >> 1) } else { c >> 1 }; + } + } + !c + } + fn chunk(out: &mut Vec, kind: &[u8], data: &[u8]) { + out.extend((data.len() as u32).to_be_bytes()); + let mut body = kind.to_vec(); + body.extend(data); + out.extend(&body); + out.extend(crc(&body).to_be_bytes()); + } + let mut raw = Vec::new(); + for y in 0..height { + raw.push(0); + for x in 0..width { + raw.extend(pixel(x, y).map(|on| if on > 0 { 255 } else { 0 })); + } + } + let (mut a, mut b) = (1u32, 0u32); + for byte in &raw { + a = (a + u32::from(*byte)) % 65521; + b = (b + a) % 65521; + } + let len = raw.len() as u16; + let mut zlib = vec![0x78, 0x01, 0x01]; + zlib.extend(len.to_le_bytes()); + zlib.extend((!len).to_le_bytes()); + zlib.extend(&raw); + zlib.extend(((b << 16) | a).to_be_bytes()); + let mut out = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; + let mut header = Vec::new(); + header.extend((width as u32).to_be_bytes()); + header.extend((height as u32).to_be_bytes()); + header.extend([8, 2, 0, 0, 0]); + chunk(&mut out, b"IHDR", &header); + chunk(&mut out, b"IDAT", &zlib); + chunk(&mut out, b"IEND", &[]); + out +} + +/// A level of two quads facing +Z, `Left` (x -2.1 to -0.1) and `Right` (0.1 to 2.1), 2 m high, each with a second +/// UV map over the whole quad (v 0 at the top) and a `lightmap` of `atlas.png` over the top (`Left`) or bottom +/// (`Right`) half of the image; and `Room`, an empty with an irradiance volume and a reflection probe. +fn baked_level() -> String { + let mut bytes: Vec = Vec::new(); + let mut f32s = |values: &[f32]| values.iter().for_each(|v| bytes.extend(v.to_le_bytes())); + // Positions of both quads, then normals, then the UVs (one set, used for both maps). + let quad = |x0: f32| [x0, -1.0, 0.0, x0 + 2.0, -1.0, 0.0, x0 + 2.0, 1.0, 0.0, x0, 1.0, 0.0]; + f32s(&quad(-2.1)); + f32s(&quad(0.1)); + f32s(&[0.0, 0.0, 1.0].repeat(4)); + f32s(&[0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0]); + for i in [0u16, 1, 2, 0, 2, 3] { + bytes.extend(i.to_le_bytes()); + } + let length = bytes.len(); + let view = |offset: usize, len: usize, target: u32| json!({"buffer": 0, "byteOffset": offset, "byteLength": len, "target": target}); + let mesh = |position: usize| { + json!({"primitives": [{"attributes": {"POSITION": position, "NORMAL": 2, "TEXCOORD_0": 3, "TEXCOORD_1": 3}, "indices": 4, "material": 0}]}) + }; + let gltf = json!({ + "asset": {"version": "2.0"}, + "scene": 0, + "scenes": [{"nodes": [0, 1, 2]}], + "nodes": [ + {"name": "Left", "mesh": 0, "extras": {"lightmap": "atlas.png", "lightmap_rect": [0.0, 0.0, 1.0, 0.5]}}, + {"name": "Right", "mesh": 1, "extras": {"lightmap": "atlas.png", "lightmap_rect": [0.0, 0.5, 1.0, 1.0]}}, + {"name": "Room", "scale": [6.0, 4.0, 6.0], "extras": {"irradiance_volume": "room.ktx2", "reflection_probe": "room", "probe_falloff": 0.2}}, + ], + "meshes": [mesh(0), mesh(1)], + "materials": [{"pbrMetallicRoughness": {"baseColorFactor": [1.0, 1.0, 1.0, 1.0], "metallicFactor": 0.0, "roughnessFactor": 1.0}}], + "buffers": [{"byteLength": length, "uri": format!("data:application/octet-stream;base64,{}", base64(&bytes))}], + "bufferViews": [view(0, 48, 34962), view(48, 48, 34962), view(96, 48, 34962), view(144, 32, 34962), view(176, 12, 34963)], + "accessors": [ + {"bufferView": 0, "componentType": 5126, "count": 4, "type": "VEC3", "min": [-2.1, -1.0, 0.0], "max": [-0.1, 1.0, 0.0]}, + {"bufferView": 1, "componentType": 5126, "count": 4, "type": "VEC3", "min": [0.1, -1.0, 0.0], "max": [2.1, 1.0, 0.0]}, + {"bufferView": 2, "componentType": 5126, "count": 4, "type": "VEC3"}, + {"bufferView": 3, "componentType": 5126, "count": 4, "type": "VEC2"}, + {"bufferView": 4, "componentType": 5123, "count": 6, "type": "SCALAR"}, + ], + }); + gltf.to_string() +} + +/// The assets of the baked level: two sets, `on` (an atlas red over green) and `off` (all blue); the probe files are +/// placeholders (a probe is checked for its components, not drawn). +fn baked_assets(tag: &str) -> BakedAssets { + let assets = BakedAssets(std::env::temp_dir().join(format!("shards_baked_{tag}_{}", std::process::id()))); + assets.put("levels/lit.gltf", baked_level().as_bytes()); + assets.put("content/levels/lit.level.ron", br#"{ "lit": (file: "levels/lit.gltf") }"#); + assets.put( + "content/levels/lit.baked_light.ron", + br#"{ "lit": (sets: { "on": "baked/on", "off": "baked/off" }, set: "on", lightmap_exposure: 2000.0, irradiance_intensity: 300.0) }"#, + ); + assets.put("content/light/lamps.light.ron", br#"{ "bulb": (intensity: 16000.0, range: 20.0), "baked_bulb": (intensity: 16000.0, range: 20.0, baked: true) }"#); + // Top two rows red, bottom two green: a mesh that reads the wrong half, or the image upside down, shows the other colour. + assets.put("baked/on/atlas.png", &png(4, 4, |_, y| if y < 2 { [1, 0, 0] } else { [0, 1, 0] })); + assets.put("baked/off/atlas.png", &png(4, 4, |_, _| [0, 0, 1])); + for set in ["on", "off"] { + for file in ["room.ktx2", "room_diffuse.ktx2", "room_specular.ktx2"] { + assets.put(&format!("baked/{set}/{file}"), b"not read by the test"); + } + } + assets +} + +/// The lightmap of each lightmapped mesh by its node's name: the image's path and the rect. +fn lightmaps(app: &mut App) -> Vec<(String, String, Rect)> { + use shards::bevy::pbr::Lightmap; + let world = app.world_mut(); + let mut out: Vec<(String, String, Rect)> = world + .query::<(&Lightmap, &ChildOf)>() + .iter(world) + .map(|(lightmap, parent)| { + let node = world.get::(parent.parent()).map(|n| n.as_str().to_owned()).unwrap_or_default(); + let path = lightmap.image.path().map(|p| p.path().to_string_lossy().replace('\\', "/")).unwrap_or_default(); + (node, path, lightmap.uv_rect) + }) + .collect(); + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +#[test] +fn a_levels_baked_light_puts_lightmaps_and_probes_on_its_picture_and_switches_sets() { + use shards::bevy::light::{EnvironmentMapLight, IrradianceVolume, LightProbe}; + use shards::level::BakedLight; + + let assets = baked_assets("wiring"); + let mut app = shards::testing::test_app(|config| config.asset_dir = assets.dir(), |_| {}); + let errors: Vec = app.world().resource::().errors().map(ToString::to_string).collect(); + assert!(errors.is_empty(), "{errors:#?}"); + ok(&mut app, "spawn_level", json!({"id": "lit"})); + // Nothing for gameplay: the baked nodes spawn no entity. + let gameplay = { + let world = app.world_mut(); + world.query::<&FromLevel>().iter(world).count() + }; + assert_eq!(gameplay, 0, "baked light is the picture's alone"); + update_until(&mut app, "both quads are lightmapped", |app| lightmaps(app).len() == 2); + let top = Rect::new(0.0, 0.0, 1.0, 0.5); + let bottom = Rect::new(0.0, 0.5, 1.0, 1.0); + assert_eq!( + lightmaps(&mut app), + [("Left".to_owned(), "baked/on/atlas.png".to_owned(), top), ("Right".to_owned(), "baked/on/atlas.png".to_owned(), bottom)] + ); + // The material takes the set's exposure. + let exposures: Vec = { + let world = app.world_mut(); + let handles: Vec<_> = world.query_filtered::<&MeshMaterial3d, With>().iter(world).map(|m| m.0.clone()).collect(); + let materials = world.resource::>(); + handles.iter().map(|h| materials.get(h).unwrap().lightmap_exposure).collect() + }; + assert_eq!(exposures, [2000.0, 2000.0]); + // The probe box: a light probe with both kinds of baked light, from the same set. + let (falloff, voxels, intensity, specular) = { + let world = app.world_mut(); + let (probe, volume, reflection) = world.query::<(&LightProbe, &IrradianceVolume, &EnvironmentMapLight)>().single(world).expect("one probe"); + let path = |h: &Handle| h.path().map(|p| p.path().to_string_lossy().replace('\\', "/")).unwrap_or_default(); + (probe.falloff, path(&volume.voxels), volume.intensity, path(&reflection.specular_map)) + }; + assert_eq!((falloff, voxels.as_str(), intensity, specular.as_str()), (Vec3::splat(0.2), "baked/on/room.ktx2", 300.0, "baked/on/room_specular.ktx2")); + + // The story turns the lamps off: the game (here the tool) picks the other set, and every image follows. + let said = ok(&mut app, "baked_light_set", json!({"level": "lit", "set": "off"})).result; + assert_eq!(said, "level `lit` draws its baked set `off`"); + // The new image loads while the old one is drawn; then the old one is off for a frame (Bevy takes a new lightmap only + // on a mesh with none) and the new one on. + let started = Instant::now(); + loop { + app.update(); + let paths: Vec = lightmaps(&mut app).into_iter().map(|(_, path, _)| path).collect(); + if paths == ["baked/off/atlas.png", "baked/off/atlas.png"] { + break; + } + assert!(paths.is_empty() || paths.iter().all(|p| p == "baked/on/atlas.png"), "a switch shows the old set or none, never a mix: {paths:?}"); + assert!(started.elapsed() < Duration::from_secs(30), "the `off` set was not put on: {paths:?}"); + std::thread::sleep(Duration::from_millis(1)); + } + let said = ok(&mut app, "baked_light", json!({})).result.as_str().unwrap_or_default().to_owned(); + assert!(said.contains("lit: set `off` (chosen by the game) of off, on"), "{said}"); + assert!(said.contains("nodes: 2 with a lightmap, 1 irradiance volumes, 1 reflection probes"), "{said}"); + assert!(said.contains("drawn: 2 meshes lightmapped, 1 probes"), "{said}"); + // A wrong set is named, with the ones there are; back to the definition's own without `set`. + let refused = shards::testing::call(&mut app, "baked_light_set", json!({"level": "lit", "set": "of"})); + assert!(format!("{refused:?}").contains("no baked set `of` (did you mean `off`?)"), "{refused:?}"); + ok(&mut app, "baked_light_set", json!({"level": "lit"})); + assert_eq!(app.world().resource::().chosen("lit"), None); + let started = Instant::now(); + while lightmaps(&mut app).iter().map(|(_, path, _)| path.as_str()).collect::>() != ["baked/on/atlas.png", "baked/on/atlas.png"] { + assert!(started.elapsed() < Duration::from_secs(30), "the definition's set was not put back"); + app.update(); + } +} + +#[test] +#[ignore = "needs a GPU, or a software one (WGPU_FORCE_FALLBACK_ADAPTER=1): cargo test -p shards --test level_render -- --ignored offscreen"] +fn offscreen_a_lightmapped_mesh_draws_its_lightmap_and_still_takes_dynamic_lights() { + use std::sync::{Arc, Mutex}; + + use shards::ai_core::display::Offscreen; + use shards::bevy::light::GlobalAmbientLight; + use shards::bevy::render::view::screenshot::{Screenshot, ScreenshotCaptured}; + use shards::bevy::render::view::{DebandDither, Msaa, Tonemapping}; + use shards::light::ContentLight; + + fn capture(app: &mut App) -> Image { + let image = app.world().resource::().image.clone(); + let slot: Arc>> = Arc::default(); + let into = slot.clone(); + app.world_mut().spawn(Screenshot::image(image)).observe(move |captured: On| { + *into.lock().unwrap() = Some(captured.image.clone()); + }); + let started = Instant::now(); + loop { + app.update(); + if let Some(image) = slot.lock().unwrap().take() { + return image; + } + if started.elapsed() > Duration::from_secs(60) { + let journal = app.world().resource::(); + let errors: Vec = journal.after(0).0.filter(|e| matches!(e.kind, shards::ai_core::JournalKind::Warn | shards::ai_core::JournalKind::Error)).map(|e| e.to_string()).collect(); + panic!("no screenshot within a minute: {errors:#?}"); + } + } + } + /// The mean colour (0 to 255) of a 20 x 20 block around (x, y). + fn mean(image: &Image, x: u32, y: u32) -> [f32; 3] { + let mut sum = [0.0f32; 3]; + for dy in 0..20 { + for dx in 0..20 { + let [r, g, b, _] = image.get_color_at(x - 10 + dx, y - 10 + dy).unwrap().to_srgba().to_u8_array(); + for (s, c) in sum.iter_mut().zip([r, g, b]) { + *s += f32::from(c) / 400.0; + } + } + } + sum + } + + const SIZE: (u32, u32) = (320, 160); + let assets = baked_assets("offscreen"); + let dir = assets.dir(); + let mut app = shards::testing::test_app( + move |config| { + (config.headless, config.offscreen, config.window) = (false, true, SIZE); + config.asset_dir = dir; + }, + |app| { + app.insert_resource(ClearColor(Color::BLACK)).insert_resource(GlobalAmbientLight { brightness: 0.0, ..default() }); + }, + ); + ok(&mut app, "spawn_level", json!({"id": "lit"})); + // Straight at the quads, which fill the picture's middle: no anti-aliasing, tone curve or dither. + let camera = (Camera3d::default(), Msaa::Off, Tonemapping::None, DebandDither::Disabled); + app.world_mut().spawn((camera, Transform::from_xyz(0.0, 0.0, 4.0).looking_at(Vec3::ZERO, Vec3::Y))); + let (left, right) = ((SIZE.0 / 4, SIZE.1 / 2), (SIZE.0 * 3 / 4, SIZE.1 / 2)); + + // The pipelines compile and the atlas loads a few frames in: wait for a lit picture. + let started = Instant::now(); + let picture = loop { + let picture = capture(&mut app); + let (l, r) = (mean(&picture, left.0, left.1), mean(&picture, right.0, right.1)); + if l[0] > 40.0 && r[1] > 40.0 { + break picture; + } + assert!(started.elapsed() < Duration::from_secs(120), "the lightmaps were not drawn within two minutes: left {l:?}, right {r:?}"); + }; + let (l, r) = (mean(&picture, left.0, left.1), mean(&picture, right.0, right.1)); + eprintln!("lightmapped: left {l:?}, right {r:?}"); + assert!(l[0] > 4.0 * (l[1] + l[2]).max(1.0), "the left quad covers the red top half of the atlas: {l:?}"); + assert!(r[1] > 4.0 * (r[0] + r[2]).max(1.0), "the right quad covers the green bottom half: {r:?}"); + + // The other set: blue over both. + ok(&mut app, "baked_light_set", json!({"level": "lit", "set": "off"})); + let started = Instant::now(); + loop { + let picture = capture(&mut app); + let (l, r) = (mean(&picture, left.0, left.1), mean(&picture, right.0, right.1)); + if l[2] > 40.0 && r[2] > 40.0 && l[0] < 10.0 && r[1] < 10.0 { + break; + } + assert!(started.elapsed() < Duration::from_secs(60), "the `off` set was not drawn: left {l:?}, right {r:?}"); + } + let base = mean(&capture(&mut app), left.0, left.1); + + // A dynamic light in front of the quads adds its light to a lightmapped mesh; a light whose content says it is + // baked adds no diffuse light to it (it is in the lightmap already). + let lamp = app.world_mut().spawn((ContentLight::new("baked_bulb"), Transform::from_xyz(-1.1, 0.0, 1.0))).id(); + for _ in 0..5 { + capture(&mut app); + } + let with_baked = mean(&capture(&mut app), left.0, left.1); + app.world_mut().entity_mut(lamp).insert(ContentLight::new("bulb")); + for _ in 0..5 { + capture(&mut app); + } + let with_bulb = mean(&capture(&mut app), left.0, left.1); + eprintln!("blue set {base:?}, a baked lamp {with_baked:?}, a dynamic lamp {with_bulb:?}"); + // The blue lightmap has no red: the red that comes is the lamp's (white light on a white surface). + assert!(with_bulb[0] > base[0] + 60.0, "a dynamic light still lights the lightmapped quad: {base:?} -> {with_bulb:?}"); + // Only the baked lamp's faint shine (specular, which the bake does not hold) is left of it. + assert!(with_baked[0] - base[0] < 0.35 * (with_bulb[0] - base[0]), "a baked lamp adds no diffuse to it: {base:?} -> {with_baked:?}"); +} + +/// What Bevy's SSAO costs the GPU at 1920x1080, at each quality, over a floor with a grid of blocks that fills the +/// picture: the GPU time of each render pass (Bevy's `RenderDiagnosticsPlugin`, timestamp queries) with no SSAO and +/// with it. A measurement, not a check: it prints the numbers for the manual ("What it costs"). +#[test] +#[ignore = "a measurement on a GPU: cargo test -p shards --test level_render -- --ignored --nocapture offscreen_measure"] +fn offscreen_measure_what_ssao_costs_on_the_gpu() { + use shards::bevy::diagnostic::DiagnosticsStore; + use shards::bevy::pbr::{ScreenSpaceAmbientOcclusion, ScreenSpaceAmbientOcclusionQualityLevel as Quality}; + use shards::bevy::render::diagnostic::RenderDiagnosticsPlugin; + use shards::bevy::render::view::Msaa; + + const SIZE: (u32, u32) = (1920, 1080); + let mut app = shards::testing::test_app( + |config| (config.headless, config.offscreen, config.window) = (false, true, SIZE), + |app| { + if !app.is_plugin_added::() { + app.add_plugins(RenderDiagnosticsPlugin); + } + }, + ); + let world = app.world_mut(); + let cube = world.resource_mut::>().add(Cuboid::new(1.0, 2.0, 1.0)); + let floor = world.resource_mut::>().add(Plane3d::default().mesh().size(60.0, 60.0)); + let grey = world.resource_mut::>().add(StandardMaterial { base_color: Color::srgb(0.7, 0.7, 0.7), ..default() }); + world.spawn((Mesh3d(floor), MeshMaterial3d(grey.clone()))); + for x in -6..=6 { + for z in -12..=0 { + world.spawn((Mesh3d(cube.clone()), MeshMaterial3d(grey.clone()), Transform::from_xyz(x as f32 * 2.0, 1.0, z as f32 * 2.0))); + } + } + world.spawn((PointLight { intensity: 2_000_000.0, range: 40.0, ..default() }, Transform::from_xyz(0.0, 6.0, 2.0))); + let camera = world.spawn((Camera3d::default(), Msaa::Off, Transform::from_xyz(0.0, 3.0, 8.0).looking_at(Vec3::new(0.0, 0.0, -6.0), Vec3::Y))).id(); + + // The GPU time of each pass over `frames` frames, after a warm-up (pipelines compile, timings arrive a frame late). + let measure = |app: &mut App, frames: usize| -> Vec<(String, f64)> { + for _ in 0..60 { + app.update(); + } + let mut store = app.world_mut().resource_mut::(); + let paths: Vec<_> = store.iter().map(|d| d.path().clone()).filter(|p| p.as_str().starts_with("render/")).collect(); + for path in &paths { + if let Some(d) = store.get_mut(path) { + d.clear_history(); + } + } + for _ in 0..frames { + app.update(); + } + let store = app.world().resource::(); + let mut out: Vec<(String, f64)> = store + .iter() + .filter(|d| d.path().as_str().starts_with("render/") && d.path().as_str().ends_with("elapsed_gpu")) + .filter_map(|d| d.average().map(|a| (d.path().as_str().to_owned(), a))) + .collect(); + out.sort_by(|a, b| a.0.cmp(&b.0)); + out + }; + let total = |passes: &[(String, f64)]| -> f64 { + // Only the top-level spans: a nested one is inside its parent's time. + passes.iter().filter(|(p, _)| p.matches('/').count() == 2).map(|(_, t)| t).sum() + }; + let without = measure(&mut app, 240); + eprintln!("no SSAO: {:.3} ms on the GPU", total(&without)); + for (path, ms) in &without { + eprintln!(" {path}: {ms:.3} ms"); + } + assert!(!without.is_empty(), "no GPU timings: the adapter has no timestamp queries"); + for quality in [Quality::Low, Quality::Medium, Quality::High, Quality::Ultra] { + app.world_mut().entity_mut(camera).insert(ScreenSpaceAmbientOcclusion { quality_level: quality, ..default() }); + let with = measure(&mut app, 240); + let ssao: f64 = with.iter().filter(|(p, _)| p.contains("ssao")).map(|(_, t)| t).sum(); + let prepass: f64 = with.iter().filter(|(p, _)| p.contains("prepass")).map(|(_, t)| t).sum(); + eprintln!("SSAO {quality:?}: {:.3} ms on the GPU (+{:.3}); the ssao pass {ssao:.3} ms, the prepasses {prepass:.3} ms", total(&with), total(&with) - total(&without)); + for (path, ms) in &with { + eprintln!(" {path}: {ms:.3} ms"); + } + } +} diff --git a/crates/shards_level/Cargo.toml b/crates/shards_level/Cargo.toml index a258343e..d4646a87 100644 --- a/crates/shards_level/Cargo.toml +++ b/crates/shards_level/Cargo.toml @@ -10,7 +10,7 @@ license.workspace = true [features] # The level's visual scene: the same file through Bevy's glTF loader, under one root entity. # Gameplay entities are the same with or without it. -render = ["ai_core/render", "shards_motion/render", "bevy/bevy_gltf", "bevy/bevy_light", "bevy/bevy_world_serialization"] +render = ["ai_core/render", "shards_motion/render", "bevy/bevy_gltf", "bevy/bevy_light", "bevy/bevy_pbr", "bevy/bevy_world_serialization"] [dependencies] ai_core.workspace = true diff --git a/crates/shards_level/src/asset.rs b/crates/shards_level/src/asset.rs index 6f0d61ec..dc28fe44 100644 --- a/crates/shards_level/src/asset.rs +++ b/crates/shards_level/src/asset.rs @@ -73,6 +73,8 @@ pub struct LevelNode { /// The bounds of the mesh's `POSITION` data in the node's own space (all primitives). /// `None` without a mesh, or for a mesh with no vertex positions. pub bounds: Option, + /// Whether every primitive of the mesh has a second UV map (`TEXCOORD_1`), which a lightmap is drawn by. + pub uv1: bool, } /// A marker as the file declares it, for listings and for `required_markers`. @@ -142,19 +144,20 @@ impl LevelAsset { let path = if parent_path.is_empty() { name.clone() } else { format!("{parent_path}/{name}") }; let world = parent_world * local_matrix(node.transform()); let (extras, extras_problem) = parse_extras(node.extras()); - let (mesh, bounds, mesh_extras) = match node.mesh() { + let (mesh, bounds, mesh_extras, uv1) = match node.mesh() { Some(mesh) => ( Some(mesh.name().map_or_else(|| format!("mesh{}", mesh.index()), str::to_owned)), mesh_bounds(&mesh), parse_extras(mesh.extras()).0, + mesh.primitives().len() > 0 && mesh.primitives().all(|p| p.get(&gltf::Semantic::TexCoords(1)).is_some()), ), - None => (None, None, Map::new()), + None => (None, None, Map::new(), false), }; let index = node.index(); for child in node.children().collect::>().into_iter().rev() { stack.push((child, Some(index), world, path.clone())); } - found.insert(index, LevelNode { index, name, path, parent, world, extras, extras_problem, mesh, mesh_extras, bounds }); + found.insert(index, LevelNode { index, name, path, parent, world, extras, extras_problem, mesh, mesh_extras, bounds, uv1 }); } Ok(LevelAsset { diff --git a/crates/shards_level/src/baked.rs b/crates/shards_level/src/baked.rs new file mode 100644 index 00000000..053084fd --- /dev/null +++ b/crates/shards_level/src/baked.rs @@ -0,0 +1,723 @@ +//! Baked light for a level's picture: lightmaps on its meshes, and irradiance volumes and reflection probes in +//! its rooms, from images a bake (Blender's, by the game's own dressing script) wrote. Picture only: nothing here +//! is simulation state, a snapshot or a replay. +//! +//! **Where it is said.** The level's nodes say *which* image each mesh or probe takes, by a file name, as +//! custom properties a bake script writes onto the objects (`lightmap`, `lightmap_rect`, `irradiance_volume`, +//! `reflection_probe`, `probe_falloff`, see [`BakedNode`]); the content kind `baked_light` (one definition per +//! level, under the level's id, [`BakedLightDef`]) says *where* those files are, as named **sets** (a folder +//! each: the lamps on, the lamps off after a breach), which set a level starts with and how bright the images +//! are. The glTF file is the same for every set, so a set is switched without loading the level again. +//! +//! **Switching.** [`BakedLight`] holds the set each level draws when it is not the definition's `set`: a game +//! switches with [`select_baked_set`] (or `ResMut`) from its own state, which it keeps and saves; the +//! resource is the picture's and not in a snapshot, so a game sets it again from its state after a load. Agents +//! use `baked_light` (what is baked and drawn) and `baked_light_set`. +//! +//! **Drawing** (the `render` feature): a mesh primitive under a `lightmap` node gets Bevy's `Lightmap` (the image, +//! the node's `lightmap_rect`, the mesh's second UV map `TEXCOORD_1`), and its `StandardMaterial` the set's +//! `lightmap_exposure`; a probe node gets a `LightProbe` with an `IrradianceVolume` and/or an +//! `EnvironmentMapLight`. A lightmapped mesh still takes every dynamic light (a flashlight, a muzzle flash, a +//! flicker); a content light whose `baked: true` says its light is in the lightmaps lights no lightmapped mesh's +//! diffuse (`shards_light`), so it is not counted twice, and still lights moving bodies. + +use std::collections::BTreeMap; + +use ai_core::prelude::*; +use ai_core::tools::{register_tool, ToolKind}; +use bevy::prelude::*; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use shards_content::db::closest; +use shards_content::{ContentDb, ContentDef, Refs}; + +use crate::asset::{check_relative, LevelAsset}; +use crate::def::LevelDef; +use crate::library::level_asset; +use crate::props::baked_of; +use crate::spawn::LevelInstances; + +fn one() -> f32 { + 1.0 +} + +fn is_one(v: &f32) -> bool { + *v == 1.0 +} + +/// The baked light of a level (`content/**/*.baked_light.ron`, kind `baked_light`), under the level's id. +/// +/// ```ron +/// { +/// "tunnels1": ( +/// sets: { "lamps_on": "baked/tunnels1/on", "breach": "baked/tunnels1/breach" }, +/// set: "lamps_on", +/// lightmap_exposure: 2000.0, +/// irradiance_intensity: 2000.0, +/// ), +/// } +/// ``` +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct BakedLightDef { + /// The sets of baked images, by name: a folder each (relative to the asset folder) that holds every file the + /// level's nodes name (`lightmap`, `irradiance_volume`, and `_diffuse.ktx2` with + /// `_specular.ktx2`). + pub sets: BTreeMap, + /// The set drawn while the game has chosen none ([`BakedLight`]). + pub set: String, + /// What a lightmap texel of 1 is worth (Bevy's `StandardMaterial::lightmap_exposure`, in cd/m²), on every + /// material of the level's lightmapped meshes. A bake writes radiance in its own units; this brings them to the + /// units of the game's lights and camera exposure. + #[serde(default = "one", skip_serializing_if = "is_one")] + pub lightmap_exposure: f32, + /// The same for the irradiance volumes (Bevy's `IrradianceVolume::intensity`). + #[serde(default = "one", skip_serializing_if = "is_one")] + pub irradiance_intensity: f32, + /// The same for the reflection probes (Bevy's `EnvironmentMapLight::intensity`). + #[serde(default = "one", skip_serializing_if = "is_one")] + pub reflection_intensity: f32, + /// Bicubic sampling of the lightmaps: smoother, dearer, and it may leak light at the edges of a chart. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub bicubic: bool, +} + +impl BakedLightDef { + /// The folder of the set `name`. + pub fn folder(&self, name: &str) -> Option<&str> { + self.sets.get(name).map(String::as_str) + } + + /// What is wrong with it without the level, one line each. + pub fn problems(&self) -> Vec { + let mut out = Vec::new(); + if self.sets.is_empty() { + out.push("`sets` is empty: name at least one folder of baked images, like { \"lamps_on\": \"baked/level/on\" }".to_owned()); + } else if !self.sets.contains_key(&self.set) { + let hint = closest(&self.set, self.sets.keys().map(String::as_str)).map(|c| format!(" (did you mean `{c}`?)")).unwrap_or_default(); + out.push(format!("`set`: no set `{}` in `sets`{hint}; the sets: {}", self.set, self.set_names())); + } + for (name, folder) in &self.sets { + if let Err(why) = check_relative(folder) { + out.push(format!("set `{name}`: {why}")); + } + } + for (name, v) in [("lightmap_exposure", self.lightmap_exposure), ("irradiance_intensity", self.irradiance_intensity), ("reflection_intensity", self.reflection_intensity)] { + if !(v >= 0.0 && v.is_finite()) { + out.push(format!("`{name}`: 0 or more, not {v}")); + } + } + out + } + + fn set_names(&self) -> String { + self.sets.keys().map(String::as_str).collect::>().join(", ") + } +} + +impl ContentDef for BakedLightDef { + const KIND: &'static str = "baked_light"; + // Only the picture reads it: editing it never makes a replay diverge or a co-op handshake fail. + const SIMULATION: bool = false; + + fn validate(&self, id: &str, refs: &mut Refs) { + for problem in self.problems() { + refs.error(problem); + } + if !refs.require::(id, "the definition's id (a `baked_light` is named after its level)") { + return; + } + // The level's file, its baked nodes and every set's files: only with an asset folder (a bare database checks + // the shape alone). + let Some(root) = refs.asset_root() else { return }; + let Some(level) = refs.db().peek::(id) else { return }; + let Ok(asset) = LevelAsset::read(root, &level.file) else { return }; // the level's own check names it + let nodes = baked_nodes(&asset); + if nodes.is_empty() { + refs.error(format!( + "`{}` has no node with `lightmap`, `irradiance_volume` or `reflection_probe`: the bake script writes those custom \ + properties on the objects it baked", + level.file + )); + } + for (path, node) in &nodes { + if let Some(file) = &node.lightmap { + let mesh = asset.nodes.iter().find(|n| &n.path == path); + match mesh { + Some(n) if n.mesh.is_none() => refs.error(format!("node `{path}`: `lightmap` `{file}` on a node without a mesh")), + Some(n) if !n.uv1 => refs.error(format!( + "node `{path}`: mesh `{}` has no second UV map (glTF TEXCOORD_1), which a lightmap is drawn by: bake into a \ + second UV map in Blender and export it (Bevy draws a lightmap without it as nothing)", + n.mesh.as_deref().unwrap_or_default() + )), + _ => {} + } + } + for (set, folder) in &self.sets { + for file in node.files() { + let at = format!("{folder}/{file}"); + if !root.join(&at).is_file() { + refs.error(format!("node `{path}`: set `{set}` has no `{at}`")); + } + } + } + } + } +} + +/// What one level node says about baked light: its custom properties, which a bake script writes. +/// +/// | property | value | what it does | +/// |---|---|---| +/// | `lightmap` | a file name (`walls_0.ktx2`) | the node's mesh draws this lightmap of the set by its second UV map: a `.ktx2` of linear half floats (`Rgba16Float`) or `Rgb9e5` is the format for a bake; a `.png` is read as sRGB (8 bits, low range); a `.hdr` is 32-bit float, which only a GPU that filters such textures draws | +/// | `lightmap_rect` | `[x0, y0, x1, y1]` | the part of the image its UVs cover (0 to 1, the top left first; the whole image when left out): many meshes share one atlas | +/// | `irradiance_volume` | a file name (`hall.ktx2`) | the node is a light probe box with this irradiance volume (a 3D KTX2 texture in Bevy's layout) of the set: moving bodies inside take its light | +/// | `reflection_probe` | a name (`hall`) | the node is a light probe box with the reflection cube maps `hall_diffuse.ktx2` and `hall_specular.ktx2` of the set | +/// | `probe_falloff` | `[x, y, z]` or one number, 0 to 1 | how far in from the box's sides the probe fades (Bevy's `LightProbe::falloff`; 0, a hard edge, when left out) | +/// +/// A probe's box is the unit cube (-0.5 to 0.5) scaled, turned and placed by the node's transform (Bevy's light +/// probe): in Blender an empty of display type *Cube* and size 0.5, scaled to the room. +#[derive(Clone, Debug, PartialEq)] +pub struct BakedNode { + pub lightmap: Option, + pub lightmap_rect: Rect, + pub irradiance_volume: Option, + pub reflection_probe: Option, + pub probe_falloff: Vec3, +} + +impl Default for BakedNode { + fn default() -> Self { + Self { lightmap: None, lightmap_rect: Rect::new(0.0, 0.0, 1.0, 1.0), irradiance_volume: None, reflection_probe: None, probe_falloff: Vec3::ZERO } + } +} + +impl BakedNode { + /// Whether the node is a light probe box. + pub fn is_probe(&self) -> bool { + self.irradiance_volume.is_some() || self.reflection_probe.is_some() + } + + /// The files it names, relative to a set's folder. + pub fn files(&self) -> Vec { + let mut out: Vec = self.lightmap.iter().chain(&self.irradiance_volume).cloned().collect(); + if let Some(name) = &self.reflection_probe { + out.extend(reflection_files(name)); + } + out + } +} + +/// The two cube maps of the reflection probe `name`: diffuse, then specular. +pub fn reflection_files(name: &str) -> [String; 2] { + [format!("{name}_diffuse.ktx2"), format!("{name}_specular.ktx2")] +} + +/// The level's nodes that carry baked light, by path, in file order (those whose properties have a problem are +/// left out: the level's own check names it). +pub fn baked_nodes(level: &LevelAsset) -> Vec<(String, BakedNode)> { + level.nodes.iter().filter_map(|n| baked_of(&n.extras).ok().flatten().map(|b| (n.path.clone(), b))).collect() +} + +/// The baked set each level draws, when the game chose one: picture only, in no snapshot or replay. A game derives it +/// from its own state (and sets it again after a load); a level the map does not name draws its definition's `set`. +#[derive(Resource, Default, Clone, Debug, PartialEq)] +pub struct BakedLight { + chosen: BTreeMap, +} + +impl BakedLight { + /// Level `level` (its content id) draws the set `set` from now on. Writes only when it changes. + pub fn select(&mut self, level: &str, set: &str) { + if self.chosen(level) != Some(set) { + self.chosen.insert(level.to_owned(), set.to_owned()); + } + } + + /// Level `level` draws its definition's `set` again. + pub fn reset(&mut self, level: &str) { + self.chosen.remove(level); + } + + /// The set the game chose for `level`, if it chose one. + pub fn chosen(&self, level: &str) -> Option<&str> { + self.chosen.get(level).map(String::as_str) + } + + /// The set `level` draws under `def`: the chosen one when the definition has it, else the definition's. + pub fn set_of<'a>(&'a self, level: &str, def: &'a BakedLightDef) -> &'a str { + self.chosen(level).filter(|s| def.sets.contains_key(*s)).unwrap_or(&def.set) + } +} + +/// Switches level `level` to its baked set `set` (`None`: back to its definition's), checking both against the +/// content. Idempotent: calling it every frame with the same set changes nothing. +pub fn select_baked_set(world: &mut World, level: &str, set: Option<&str>) -> Result<(), String> { + let db = world.get_resource::().ok_or("no content database")?; + let Some(def) = db.peek::(level) else { + let ids: Vec<&str> = db.peek_ids::().collect(); + let hint = closest(level, ids.iter().copied()).map(|c| format!(" (did you mean `{c}`?)")).unwrap_or_default(); + let known = if ids.is_empty() { "no level has one".to_owned() } else { format!("the levels with one: {}", ids.join(", ")) }; + return Err(format!("no `baked_light` definition for the level `{level}`{hint}; {known}")); + }; + if let Some(set) = set + && !def.sets.contains_key(set) + { + let hint = closest(set, def.sets.keys().map(String::as_str)).map(|c| format!(" (did you mean `{c}`?)")).unwrap_or_default(); + return Err(format!("the level `{level}` has no baked set `{set}`{hint}; its sets: {}", def.set_names())); + } + let mut light = world.get_resource_or_insert_with(BakedLight::default); + match set { + Some(set) => light.select(level, set), + None if light.chosen(level).is_some() => light.reset(level), + None => {} + } + Ok(()) +} + +pub(crate) fn register(world: &mut World) { + register_tool(world, "baked_light", Scope::Player, ToolKind::Query, baked_light); + // Picture only, like `look_outlines`: not journaled or recorded (the game's own state chooses the set). + register_tool(world, "baked_light_set", Scope::Dev, ToolKind::Query, baked_light_set); +} + +/// The levels' baked light: for each level with a `baked_light` definition, its sets and the one drawn now (and +/// who chose it), how many of the level's nodes carry a lightmap or a probe, and, in a drawn game, how many meshes +/// draw a lightmap now and which images are still loading or failed. +#[derive(Deserialize, JsonSchema, Default)] +pub struct BakedLightArgs { + /// Only this level (its content id). + pub level: Option, +} + +/// Switches a level's baked light to another set of its `baked_light` definition (the lamps off after a breach); +/// without `set`, back to the definition's own. Picture only: a game switches from its own state. +#[derive(Deserialize, JsonSchema, Default)] +pub struct BakedLightSetArgs { + /// The level (its content id). + pub level: String, + /// The set (a key of the definition's `sets`); left out, the definition's `set`. + pub set: Option, +} + +fn baked_light(In(call): In>, world: &World) -> ToolResult { + let db = world.get_resource::().ok_or("no content database")?; + let light = world.get_resource::().cloned().unwrap_or_default(); + let ids: Vec<&str> = db.peek_ids::().filter(|id| call.args.level.as_deref().is_none_or(|l| l == *id)).collect(); + if let Some(level) = &call.args.level + && ids.is_empty() + { + let all: Vec<&str> = db.peek_ids::().collect(); + let hint = closest(level, all.iter().copied()).map(|c| format!(" (did you mean `{c}`?)")).unwrap_or_default(); + return Err(format!("no `baked_light` definition for the level `{level}`{hint}")); + } + let mut out = vec![format!("baked light: {} levels", ids.len())]; + let drawn = drawn_counts(world); + for id in ids { + let Some(def) = db.peek::(id) else { continue }; + let set = light.set_of(id, def); + let by = if light.chosen(id) == Some(set) { "chosen by the game" } else { "the definition's" }; + let placed = world.get_resource::().map_or(0, |i| i.iter().filter(|i| i.label == id).count()); + out.push(format!(" {id}: set `{set}` ({by}) of {} · placed {placed} times", def.set_names())); + let file = db.peek::(id).map(|l| l.file.clone()); + match file.as_deref().map(|f| level_asset(world, f)) { + Some(Ok(level)) => { + let nodes = baked_nodes(level); + let lightmaps = nodes.iter().filter(|(_, n)| n.lightmap.is_some()).count(); + let volumes = nodes.iter().filter(|(_, n)| n.irradiance_volume.is_some()).count(); + let reflections = nodes.iter().filter(|(_, n)| n.reflection_probe.is_some()).count(); + out.push(format!(" nodes: {lightmaps} with a lightmap, {volumes} irradiance volumes, {reflections} reflection probes")); + } + Some(Err(why)) => out.push(format!(" the level's file: {why}")), + None => out.push(format!(" no `level` definition `{id}`")), + } + match drawn.as_ref().and_then(|d| d.get(id)) { + Some(d) => out.push(format!( + " drawn: {} meshes lightmapped, {} probes · images: {} loading, {} failed{}", + d.meshes, + d.probes, + d.loading, + d.failed.len(), + if d.failed.is_empty() { String::new() } else { format!(" ({})", d.failed.join(", ")) } + )), + None if drawn.is_some() => out.push(" drawn: nothing yet (the level is not placed, or its picture is loading)".to_owned()), + None => out.push(" drawn: nothing (no picture in this game)".to_owned()), + } + } + Ok(out.join("\n")) +} + +fn baked_light_set(In(call): In>, world: &mut World) -> ToolResult { + let BakedLightSetArgs { level, set } = call.args; + select_baked_set(world, &level, set.as_deref())?; + let db = world.resource::(); + let def = db.peek::(&level).ok_or("the definition is gone")?; + let now = world.get_resource::().map_or(def.set.as_str(), |l| l.set_of(&level, def)).to_owned(); + Ok(format!("level `{level}` draws its baked set `{now}`")) +} + +/// What the picture draws now, per level id: `None` in a game without a picture. +#[derive(Default)] +#[cfg_attr(not(feature = "render"), allow(dead_code, reason = "only a picture fills it"))] +struct Drawn { + meshes: usize, + probes: usize, + loading: usize, + failed: Vec, +} + +#[cfg(feature = "render")] +fn drawn_counts(world: &World) -> Option> { + render::drawn_counts(world) +} + +#[cfg(not(feature = "render"))] +fn drawn_counts(_: &World) -> Option> { + None +} + +#[cfg(feature = "render")] +pub(crate) use render::plugin as render_plugin; + +#[cfg(feature = "render")] +mod render { + use std::collections::BTreeMap; + + use bevy::asset::LoadState; + use bevy::gltf::GltfExtras; + use bevy::image::{ImageLoaderSettings, ImageSampler}; + use bevy::light::{EnvironmentMapLight, IrradianceVolume, LightProbe}; + use bevy::pbr::Lightmap; + use bevy::prelude::*; + use shards_content::ContentDb; + + use super::{reflection_files, BakedLight, BakedLightDef, BakedNode, Drawn}; + use crate::props::baked_of; + use crate::render::LevelVisual; + use crate::spawn::LevelInstances; + + /// A node of a level's picture that carries baked light: what its properties say, and what is drawn on it now. + #[derive(Component, Clone, Debug)] + pub struct BakedPicture { + /// The level instance. + pub instance: u32, + pub node: BakedNode, + /// What was put on it: the folder and the numbers, so a switch or an edit puts it again. + applied: Option, + /// The images it draws now, for the query. + images: Vec<(String, Handle)>, + /// The meshes it lightmapped. + meshes: usize, + /// A switch's new lightmap, loading while the old one is still drawn. + staged: Option<(String, Handle)>, + /// Whether the old lightmap was taken off for the switch (Bevy takes a new one only on a mesh that has none). + lifted: bool, + } + + #[derive(Clone, Debug, PartialEq)] + struct Applied { + folder: String, + lightmap_exposure: f32, + irradiance_intensity: f32, + reflection_intensity: f32, + bicubic: bool, + } + + pub(crate) fn plugin(app: &mut App) { + // Known before any level is placed, so the query tells "nothing placed" from "no picture". + app.world_mut().register_component::(); + // After the glTF scene is spawned (`replace_lamps` reads its extras in `PostUpdate` too), before extraction. + app.add_systems(PostUpdate, (find_baked_nodes, draw_baked, keep_exposure).chain()); + } + + /// `PostUpdate`: a node under a level's picture whose extras carry baked light is marked with what they say. + fn find_baked_nodes( + mut commands: Commands, + new: Query<(Entity, &GltfExtras), Added>, + visuals: Query<&LevelVisual>, + parents: Query<&ChildOf>, + ) { + for (entity, extras) in &new { + let Ok(serde_json::Value::Object(props)) = serde_json::from_str::(&extras.value) else { continue }; + let Ok(Some(node)) = baked_of(&props) else { continue }; + let Some(instance) = parents.iter_ancestors(entity).find_map(|a| visuals.get(a).ok()).map(|v| v.instance) else { continue }; + commands.entity(entity).insert(BakedPicture { instance, node, applied: None, images: Vec::new(), meshes: 0, staged: None, lifted: false }); + } + } + + /// Baked light is sampled linearly between texels and clamped at the edges, whatever sampler the game made the + /// default (a pixel-art game's nearest). A `.hdr` has a loader of its own, which takes the default sampler. + fn load(server: &AssetServer, path: String) -> Handle { + if path.ends_with(".hdr") { + return server.load(path); + } + server.load_builder().with_settings(|s: &mut ImageLoaderSettings| s.sampler = ImageSampler::linear()).load(path) + } + + /// `PostUpdate`: each baked node draws the set its level draws now (the game's choice, else the definition's), + /// put again when the set or the definition's numbers change; a node whose level lost its definition loses it. + #[allow(clippy::too_many_arguments, reason = "a Bevy system: one parameter per thing it reads")] + fn draw_baked( + mut commands: Commands, + server: Option>, + db: Option>, + light: Option>, + instances: Option>, + mut pictures: Query<(Entity, &mut BakedPicture, Option<&Children>)>, + mut meshes: Query<&mut Mesh3d>, + ) { + let (Some(server), Some(db), Some(instances)) = (server, db, instances) else { return }; + let none = BakedLight::default(); + let light = light.as_deref().unwrap_or(&none); + for (entity, mut picture, children) in &mut pictures { + let Some(level) = instances.get(picture.instance).map(|i| i.label.clone()) else { continue }; + let def: Option<&BakedLightDef> = db.peek::(&level); + let want = def.and_then(|def| { + let folder = def.folder(light.set_of(&level, def))?.to_owned(); + Some(Applied { + folder, + lightmap_exposure: def.lightmap_exposure, + irradiance_intensity: def.irradiance_intensity, + reflection_intensity: def.reflection_intensity, + bicubic: def.bicubic, + }) + }); + // (A lightmap taken off for a switch goes back on even when the switch was undone meanwhile.) + if picture.applied == want && !picture.lifted { + continue; + } + // The meshes of the node: its own, and its primitives (Bevy's glTF loader puts each on a child). + let targets: Vec = + std::iter::once(entity).chain(children.into_iter().flat_map(|c| c.iter())).filter(|e| meshes.contains(*e)).collect(); + // Bevy 0.20 picks a mesh's pipeline again only when its `Mesh3d` or material changes, not when a `Lightmap` + // comes or goes, while its bind group follows the lightmap at once: a lightmap put on or taken off without a + // touch of the mesh draws with a pipeline and a bind group that disagree (a wgpu validation error, and Bevy + // stops drawing). So every change of a `Lightmap` marks the mesh changed in the same frame. + let Some(want) = want else { + // The definition is gone: the node draws no baked light. + for target in &targets { + commands.entity(*target).remove::<(Lightmap, BakedExposure)>(); + } + if picture.node.lightmap.is_some() { + touch(&mut meshes, &targets); + } + commands.entity(entity).remove::<(LightProbe, IrradianceVolume, EnvironmentMapLight)>(); + (picture.applied, picture.images, picture.meshes, picture.staged, picture.lifted) = (None, Vec::new(), 0, None, false); + continue; + }; + if picture.node.lightmap.is_some() && targets.is_empty() { + // The scene's primitives are not in yet: next frame. + continue; + } + let mut images = Vec::new(); + if let Some(file) = &picture.node.lightmap { + let path = format!("{}/{file}", want.folder); + let image = match &picture.staged { + Some((staged, image)) if *staged == path => image.clone(), + _ => load(&server, path.clone()), + }; + // Bevy 0.20 takes no new `Lightmap` on a mesh that has one (`extract_lightmaps` skips a mesh it knows), so a + // switch waits for the new image to load while the old one is drawn, takes the old one off for a frame, + // then puts the new one on: one frame without a lightmap, and no frame of a blank image (the new one is on + // the GPU by then). + let switch = picture.applied.as_ref().is_some_and(|a| a.folder != want.folder || a.bicubic != want.bicubic); + if switch && !picture.lifted { + let ready = matches!(server.load_state(image.id()), LoadState::Loaded | LoadState::Failed(_)); + if ready { + for target in &targets { + commands.entity(*target).remove::(); + } + touch(&mut meshes, &targets); + picture.lifted = true; + } + picture.staged = Some((path, image)); + continue; + } + let put = picture.applied.as_ref().is_none_or(|a| a.folder != want.folder || a.bicubic != want.bicubic) || picture.lifted; + for target in &targets { + let lightmap = Lightmap { image: image.clone(), uv_rect: picture.node.lightmap_rect, bicubic_sampling: want.bicubic }; + if put { + commands.entity(*target).insert((lightmap, BakedExposure(want.lightmap_exposure))); + } else { + // Only the exposure changed: the lightmap stays as it is. + commands.entity(*target).insert(BakedExposure(want.lightmap_exposure)); + } + } + if put { + touch(&mut meshes, &targets); + } + images.push((path, image)); + } + if picture.node.is_probe() { + let mut probe = commands.entity(entity); + probe.insert(LightProbe { falloff: picture.node.probe_falloff }); + match &picture.node.irradiance_volume { + Some(file) => { + let path = format!("{}/{file}", want.folder); + let voxels = load(&server, path.clone()); + probe.insert(IrradianceVolume { voxels: voxels.clone(), intensity: want.irradiance_intensity, affects_lightmapped_meshes: false }); + images.push((path, voxels)); + } + None => { + probe.remove::(); + } + } + match &picture.node.reflection_probe { + Some(name) => { + let [diffuse, specular] = reflection_files(name).map(|f| format!("{}/{f}", want.folder)); + let (d, s) = (load(&server, diffuse.clone()), load(&server, specular.clone())); + probe.insert(EnvironmentMapLight { + diffuse_map: d.clone(), + specular_map: s.clone(), + intensity: want.reflection_intensity, + affects_lightmapped_mesh_diffuse: false, + ..default() + }); + images.extend([(diffuse, d), (specular, s)]); + } + None => { + probe.remove::(); + } + } + } + picture.meshes = if picture.node.lightmap.is_some() { targets.len() } else { 0 }; + picture.images = images; + picture.applied = Some(want); + (picture.staged, picture.lifted) = (None, false); + } + } + + /// Marks the meshes changed, so Bevy picks their pipeline again (see `draw_baked`). + fn touch(meshes: &mut Query<&mut Mesh3d>, targets: &[Entity]) { + for target in targets { + if let Ok(mut mesh) = meshes.get_mut(*target) { + mesh.set_changed(); + } + } + } + + /// The lightmap exposure of a lightmapped mesh's level, kept on whatever `StandardMaterial` the mesh draws with (the + /// glTF's, or one a `Lit` look made later). + #[derive(Component, Clone, Copy, Debug, PartialEq)] + pub struct BakedExposure(pub f32); + + /// The lightmapped meshes whose exposure or material changed. + type ExposureChanged<'w, 's> = Query< + 'w, + 's, + (&'static BakedExposure, &'static MeshMaterial3d), + Or<(Changed, Changed>)>, + >; + + /// `PostUpdate`, after the baked nodes are drawn: the material of a mesh whose exposure or material changed takes the + /// exposure, written only where it differs (a write prepares the material again). + fn keep_exposure(meshes: ExposureChanged, materials: Option>>) { + // A game without the PBR renderer has no materials, and draws no lightmap. + let Some(mut materials) = materials else { return }; + for (exposure, material) in &meshes { + if materials.get(&material.0).is_some_and(|m| m.lightmap_exposure != exposure.0) + && let Some(mut m) = materials.get_mut(&material.0) + { + m.lightmap_exposure = exposure.0; + } + } + } + + /// What the baked pictures draw now, per level id. + pub(super) fn drawn_counts(world: &World) -> Option> { + let server = world.get_resource::()?; + let instances = world.get_resource::()?; + // A game without scenes draws nothing: no picture. + world.get_resource::>()?; + let mut out: BTreeMap = BTreeMap::new(); + let mut query = world.try_query::<&BakedPicture>()?; + for picture in query.iter(world) { + let Some(level) = instances.get(picture.instance).map(|i| i.label.clone()) else { continue }; + let entry = out.entry(level).or_default(); + entry.meshes += picture.meshes; + entry.probes += usize::from(picture.applied.is_some() && picture.node.is_probe()); + for (path, image) in &picture.images { + match server.load_state(image.id()) { + LoadState::Loaded => {} + LoadState::Failed(_) => { + if !entry.failed.contains(path) { + entry.failed.push(path.clone()); + } + } + _ => entry.loading += 1, + } + } + } + Some(out) + } +} + +#[cfg(test)] +mod tests { + use serde_json::{json, Map, Value}; + + use super::*; + + fn props(value: Value) -> Map { + value.as_object().cloned().unwrap() + } + + #[test] + fn a_nodes_baked_properties_are_read_and_their_mistakes_named() { + let mesh = baked_of(&props(json!({"lightmap": "walls_0.ktx2", "lightmap_rect": [0.0, 0.5, 0.5, 1.0]}))).unwrap().unwrap(); + assert_eq!((mesh.lightmap.as_deref(), mesh.lightmap_rect, mesh.is_probe()), (Some("walls_0.ktx2"), Rect::new(0.0, 0.5, 0.5, 1.0), false)); + let probe = baked_of(&props(json!({"irradiance_volume": "hall.ktx2", "reflection_probe": "hall", "probe_falloff": 0.2}))).unwrap().unwrap(); + assert_eq!((probe.probe_falloff, probe.is_probe()), (Vec3::splat(0.2), true)); + assert_eq!(probe.files(), ["hall.ktx2", "hall_diffuse.ktx2", "hall_specular.ktx2"]); + assert_eq!(baked_of(&props(json!({"collider": "auto"}))), Ok(None), "a node without baked light"); + + let wrong = baked_of(&props(json!({"lightmap": "../up.ktx2", "lightmap_rect": [0.5, 0.0, 0.2, 1.0], "probe_falloff": [0.1, 2.0, 0.1]}))); + let text = wrong.unwrap_err().join("\n"); + for want in [ + "`lightmap` `../up.ktx2` must be a file name inside a baked set's folder", + "`lightmap_rect` must be [x0, y0, x1, y1] within 0 to 1 with x0 < x1", + "`probe_falloff` must be [x, y, z] or one number, each 0 to 1", + "`probe_falloff` does nothing without `irradiance_volume` or `reflection_probe`", + ] { + assert!(text.contains(want), "{want}\n---\n{text}"); + } + let orphan = baked_of(&props(json!({"lightmap_rect": [0.0, 0.0, 1.0, 1.0]}))).unwrap_err(); + assert!(orphan.join("\n").contains("`lightmap_rect` does nothing without `lightmap`"), "{orphan:?}"); + } + + #[test] + fn a_baked_light_definition_reads_with_its_defaults_and_names_its_mistakes() { + let read: BakedLightDef = ron::from_str(r#"(sets: {"on": "baked/on", "off": "baked/off"}, set: "on")"#).unwrap(); + assert_eq!((read.lightmap_exposure, read.irradiance_intensity, read.reflection_intensity, read.bicubic), (1.0, 1.0, 1.0, false)); + assert!(read.problems().is_empty(), "{:?}", read.problems()); + assert_eq!(read.folder("off"), Some("baked/off")); + + let bad = BakedLightDef { + sets: BTreeMap::from([("off".to_owned(), "baked/off".to_owned()), ("up".to_owned(), "../baked".to_owned())]), + set: "offf".into(), + lightmap_exposure: -1.0, + reflection_intensity: f32::NAN, + ..read + }; + let text = bad.problems().join("\n"); + for want in ["`set`: no set `offf` in `sets` (did you mean `off`?)", "set `up`: `../baked` must be a path inside the asset folder", "`lightmap_exposure`: 0 or more, not -1", "`reflection_intensity`: 0 or more, not NaN"] { + assert!(text.contains(want), "{want}\n---\n{text}"); + } + let empty = BakedLightDef { sets: BTreeMap::new(), set: "on".into(), ..bad }; + assert!(empty.problems()[0].starts_with("`sets` is empty"), "{:?}", empty.problems()); + } + + #[test] + fn the_game_chooses_a_set_and_an_unknown_one_falls_back_to_the_definitions() { + let def: BakedLightDef = ron::from_str(r#"(sets: {"on": "baked/on", "off": "baked/off"}, set: "on")"#).unwrap(); + let mut light = BakedLight::default(); + assert_eq!((light.set_of("hall", &def), light.chosen("hall")), ("on", None)); + light.select("hall", "off"); + assert_eq!((light.set_of("hall", &def), light.chosen("hall")), ("off", Some("off"))); + // A set the definition lost (a content edit): the definition's own is drawn, the choice kept for when it is back. + light.select("hall", "breach"); + assert_eq!((light.set_of("hall", &def), light.chosen("hall")), ("on", Some("breach"))); + light.reset("hall"); + assert_eq!(light, BakedLight::default()); + } +} diff --git a/crates/shards_level/src/lib.rs b/crates/shards_level/src/lib.rs index 2a664029..e3eae533 100644 --- a/crates/shards_level/src/lib.rs +++ b/crates/shards_level/src/lib.rs @@ -63,6 +63,8 @@ //! | `mover` | text | the node becomes a [`Mover`](shards_motion::Mover) going through the keys of that `mover` definition (F6); the nodes below it move with it as its [`MoverPart`](shards_motion::MoverPart)s, and its picture follows it; movers do not nest | //! | `light` | text | the node shines by that `light` definition ([`ContentLight`](shards_light::ContentLight), F13): a Blender lamp, whose own glTF light the picture drops for it, or an empty; a spot points along the node's -Z | //! | `grading` | text | on a `marker` = `trigger` node: the picture blends toward that `grading` definition ([`GradingVolume`](shards_motion::camera::GradingVolume)) while the local player is inside | +//! | `lightmap`, `lightmap_rect` | a file name; `[x0, y0, x1, y1]` | baked light (the picture's, [`BakedNode`]): the mesh draws that lightmap of the level's baked set (a `baked_light` definition, [`BakedLightDef`]) by its second UV map, over that part of the image | +//! | `irradiance_volume`, `reflection_probe`, `probe_falloff` | a file name; a name; `[x, y, z]` or a number | baked light: the node is a light probe box (the unit cube under its transform) with that irradiance volume and/or reflection cube maps, fading that far in from its sides | //! //! Every other key is a **component**: its short name (`Health`) or full type path //! (`my_game::combat::Health`), and its value as JSON in the shape `inspect` and the `get` @@ -156,6 +158,7 @@ //! gameplay entities are the same with and without it. mod asset; +mod baked; mod def; mod library; mod marker; @@ -171,6 +174,7 @@ use shards_content::{ContentAppExt, ContentPlugin}; use shards_core::EngineAppExt; pub use asset::{Bounds, LevelAsset, LevelLoadError, LevelLoader, LevelNode, MarkerInfo}; +pub use baked::{baked_nodes, reflection_files, select_baked_set, BakedLight, BakedLightArgs, BakedLightDef, BakedLightSetArgs, BakedNode}; pub use def::LevelDef; pub use library::{held_change, level_asset, request_level, LevelLibrary}; pub use marker::{LevelMarker, MarkerKind, RequiredMarker}; @@ -212,6 +216,9 @@ impl Plugin for LevelPlugin { .register_type::() .register_type::() .add_content::() + // Baked light (lightmaps, light probes) of a level's picture: a kind the simulation never reads. + .add_content::() + .init_resource::() .init_resource::() .init_resource::() // The levels placed by id are (`PlacedLevels`): the snapshot's go back where it @@ -245,6 +252,9 @@ impl Plugin for LevelPlugin { ); #[cfg(feature = "render")] render::plugin(app); + #[cfg(feature = "render")] + baked::render_plugin(app); tools::register(app.world_mut()); + baked::register(app.world_mut()); } } diff --git a/crates/shards_level/src/props.rs b/crates/shards_level/src/props.rs index 15bb9b1a..0e9b06ff 100644 --- a/crates/shards_level/src/props.rs +++ b/crates/shards_level/src/props.rs @@ -27,11 +27,12 @@ use shards_light::LightDef; use shards_motion::camera::GradingDef; use shards_motion::{CollisionLayers, LayerMask, MoverDef, VolumeKind, PROBE_RANGE}; -use crate::asset::{json_kind, LevelAsset, LevelNode}; +use crate::asset::{check_relative, json_kind, LevelAsset, LevelNode}; +use crate::baked::BakedNode; use crate::marker::{MarkerKind, RequiredMarker}; /// The level properties, in documentation order. -pub const PROPERTIES: [&str; 22] = [ +pub const PROPERTIES: [&str; 27] = [ "marker", "name", "socket", @@ -54,8 +55,16 @@ pub const PROPERTIES: [&str; 22] = [ "hold_s", "use_range", "prompt", + "lightmap", + "lightmap_rect", + "irradiance_volume", + "reflection_probe", + "probe_falloff", ]; +/// The level properties of baked light (the picture's, [`BakedNode`]): nothing spawns for them. +pub(crate) const BAKED_PROPERTIES: [&str; 5] = ["lightmap", "lightmap_rect", "irradiance_volume", "reflection_probe", "probe_falloff"]; + /// Components the file cannot set: the engine owns them. const ENGINE_OWNED: [(&str, &str); 3] = [ ("ai_core::id::AiId", "AiId is assigned by the engine"), @@ -520,6 +529,12 @@ pub(crate) fn plan_node(node: &LevelNode, position: usize, registry: &TypeRegist Err(e) => problems.push(e), } + // Baked light: the picture's (a `baked_light` definition says where its files are); the node spawns nothing for it. + if let Err(found) = baked_of(props) { + problems.extend(found); + } + used.extend(BAKED_PROPERTIES); + for key in PROPERTIES { if props.contains_key(key) && !used.contains(&key) { problems.push(format!("`{key}` does nothing on this node: {}", why_unused(key))); @@ -534,6 +549,70 @@ pub(crate) fn plan_node(node: &LevelNode, position: usize, registry: &TypeRegist (plan, problems) } +/// What a node's properties say about baked light: `None` when it names none, the problems when they are wrong. +pub(crate) fn baked_of(props: &Map) -> Result, Vec> { + if !BAKED_PROPERTIES.iter().any(|k| props.contains_key(*k)) { + return Ok(None); + } + let mut node = BakedNode::default(); + let mut problems = Vec::new(); + let mut file = |key: &str| -> Option { + match text(props, key) { + Ok(Some("")) => { + problems.push(format!("`{key}` is empty; name a file in the folders of the level's baked sets (a `baked_light` definition)")); + None + } + Ok(Some(name)) => match check_relative(name) { + Ok(()) => Some(name.to_owned()), + Err(_) => { + problems.push(format!("`{key}` `{name}` must be a file name inside a baked set's folder (relative, no `..`)")); + None + } + }, + Ok(None) => None, + Err(e) => { + problems.push(e); + None + } + } + }; + node.lightmap = file("lightmap"); + node.irradiance_volume = file("irradiance_volume"); + node.reflection_probe = file("reflection_probe"); + if let Some(value) = props.get("lightmap_rect") { + let parts: Option> = value.as_array().filter(|a| a.len() == 4).and_then(|a| a.iter().map(|v| v.as_f64().map(|f| f as f32)).collect()); + match parts.as_deref() { + Some(&[x0, y0, x1, y1]) if [x0, y0, x1, y1].iter().all(|v| (0.0..=1.0).contains(v)) && x0 < x1 && y0 < y1 => { + node.lightmap_rect = Rect::new(x0, y0, x1, y1); + } + _ => problems.push(format!( + "`lightmap_rect` must be [x0, y0, x1, y1] within 0 to 1 with x0 < x1 and y0 < y1 (the top left first), found {value}" + )), + } + if !props.contains_key("lightmap") { + problems.push("`lightmap_rect` does nothing without `lightmap`: it is the part of that image the mesh covers".to_owned()); + } + } + if let Some(value) = props.get("probe_falloff") { + let as_f32 = |v: &Value| v.as_f64().map(|f| f as f32); + let read = match value { + Value::Array(items) if items.len() == 3 => { + let v: Option> = items.iter().map(as_f32).collect(); + v.map(|v| Vec3::new(v[0], v[1], v[2])) + } + other => as_f32(other).map(Vec3::splat), + }; + match read { + Some(v) if v.to_array().iter().all(|c| (0.0..=1.0).contains(c)) => node.probe_falloff = v, + _ => problems.push(format!("`probe_falloff` must be [x, y, z] or one number, each 0 to 1, found {value}")), + } + if !props.contains_key("irradiance_volume") && !props.contains_key("reflection_probe") { + problems.push("`probe_falloff` does nothing without `irradiance_volume` or `reflection_probe`: it is how a probe's box fades".to_owned()); + } + } + if problems.is_empty() { Ok(Some(node)) } else { Err(problems) } +} + fn why_unused(key: &str) -> &'static str { match key { "name" => "it names a marker, and the node has no `marker`", diff --git a/crates/shards_light/src/def.rs b/crates/shards_light/src/def.rs index 444a6839..511030b9 100644 --- a/crates/shards_light/src/def.rs +++ b/crates/shards_light/src/def.rs @@ -93,6 +93,12 @@ pub struct LightDef { /// How the brightness moves. #[serde(skip_serializing_if = "is_steady")] pub flicker: Flicker, + /// Whether its light is baked into the level's lightmaps (`baked_light`, `shards_level`): it then lights no + /// lightmapped mesh's diffuse (Bevy's `affects_lightmapped_mesh_diffuse`), which has it already, and still lights + /// what moves (bodies, props) and the shine of every surface. A flashlight, a muzzle flash and a light that + /// changes from the bake (a flicker the bake did not see) leave it `false`. + #[serde(skip_serializing_if = "is_false")] + pub baked: bool, } fn is_zero(v: &f32) -> bool { @@ -109,7 +115,7 @@ fn is_steady(f: &Flicker) -> bool { impl Default for LightDef { fn default() -> Self { - Self { kind: LightKind::Point, color: String::new(), kelvin: 0.0, intensity: 100_000.0, range: 15.0, radius: 0.0, shadows: false, flicker: Flicker::None } + Self { kind: LightKind::Point, color: String::new(), kelvin: 0.0, intensity: 100_000.0, range: 15.0, radius: 0.0, shadows: false, flicker: Flicker::None, baked: false } } } diff --git a/crates/shards_light/src/render.rs b/crates/shards_light/src/render.rs index d35e0457..5b488dda 100644 --- a/crates/shards_light/src/render.rs +++ b/crates/shards_light/src/render.rs @@ -43,6 +43,7 @@ fn point_of(light: &LightInfo) -> Option { range: def.range, radius: def.radius, shadow_maps_enabled: light.casts, + affects_lightmapped_mesh_diffuse: !def.baked, ..default() }) } @@ -58,6 +59,7 @@ fn spot_of(light: &LightInfo) -> Option { shadow_maps_enabled: light.casts, inner_angle: half(inner_deg), outer_angle: half(outer_deg), + affects_lightmapped_mesh_diffuse: !def.baked, ..default() }) } @@ -76,11 +78,11 @@ macro_rules! sync_fields { } fn set_point(light: &mut Mut, want: &PointLight) { - sync_fields!(light, want, [color, intensity, range, radius, shadow_maps_enabled]); + sync_fields!(light, want, [color, intensity, range, radius, shadow_maps_enabled, affects_lightmapped_mesh_diffuse]); } fn set_spot(light: &mut Mut, want: &SpotLight) { - sync_fields!(light, want, [color, intensity, range, radius, shadow_maps_enabled, inner_angle, outer_angle]); + sync_fields!(light, want, [color, intensity, range, radius, shadow_maps_enabled, inner_angle, outer_angle, affects_lightmapped_mesh_diffuse]); } /// `Update`, after the state: each content light has the Bevy light its definition and the budget say, and a From 19a8f5ae84a6fa3be4dff7e3a28f88fa420cd1ff Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:53:36 +0100 Subject: [PATCH 4/7] Docs: SSAO, shadow views, baked light, and confining a light to a room The manual's picture, settings, lights and levels sections, the agents' notes, CHANGELOG and engine-progress. Confining a light to a room was researched and not done: Bevy's clustered lights carry no volume, so it needs a patched bevy_pbr; the manual says what that would take. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 20 +++++++ .../ui-audio-look-fx-scatter-animation.md | 4 +- docs/agents/watching-and-driving.md | 2 +- docs/engine-progress.md | 1 + docs/manual.md | 57 +++++++++++++++++-- 5 files changed, 78 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d5bcd54..bac90103 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,26 @@ git push origin v0.1.0 Changes that land in the main branch after phases C–E (`0.4.0`) go here. ### Added +- Ambient occlusion in the camera's picture (the manual's "The picture"): `picture.ssao: Some((quality, radius, thickness))` + in the `camera` content gives the world cameras Bevy's `ScreenSpaceAmbientOcclusion` (`SsaoTuning`, `SsaoQuality::{Low, + Medium, High, Ultra}`), with the depth and normal prepasses it needs and `Msaa::Off` while it is on (Bevy draws no SSAO + under MSAA); taking it out gives the camera back its own SSAO, MSAA and prepasses. The view model's camera follows the + world camera's MSAA and has no SSAO. Off by default. +- A shadow budget in views (the manual's "Lights and colour grading (F13)"): `graphics.shadow_views` (0 to 384, default 0) + counts the shadow budget in shadow views, a point light 6 and a spot 1, the nearest first, and replaces + `graphics.shadow_lights` while above 0. The `lights` query says the budget in views, how many are taken and, for a light + that missed out, what it takes and what was left; `ai/status` adds `light.budget_views` and `light.views_used`. + `GraphicsSettings::shadow_budget` and `ShadowBudget::{Lights, Views}`. At 0 nothing changes. +- Baked light for levels (the manual's "Levels from Blender (E4.2)", "Baked light"): level node properties `lightmap`, + `lightmap_rect`, `irradiance_volume`, `reflection_probe` and `probe_falloff`, and the picture-only content kind + `baked_light` (`BakedLightDef { sets, set, lightmap_exposure, irradiance_intensity, reflection_intensity, bicubic }`, one + per level id) that names the folders of the level's sets of baked images. A drawn level puts Bevy's `Lightmap` on the + meshes (by their second UV map; the check names a mesh without one and every file a set lacks) and a `LightProbe` with an + `IrradianceVolume` and/or an `EnvironmentMapLight` on the probe boxes; lightmapped meshes still take every dynamic light. + A game switches a level's set at run time with `shards::level::select_baked_set` (the resource `BakedLight`, the + picture's, in no snapshot); the tools `baked_light` (player) and `baked_light_set` (dev). A content light's new + `baked: true` lights no lightmapped mesh's diffuse (its light is in the bake). A level without a `baked_light` draws as + before. - The game's own subtitle lines (the manual's "Subtitles"): `shards::audio::subtitles::say(world, Saying { sound, text, speaker, secs, bus })` shows a line that no voice says, for the seconds the game gives, on the clock of the bus it names (the simulation's, so a pause holds it; real time on `Ui`): words the game puts together, such as a tablet's new task as diff --git a/docs/agents/ui-audio-look-fx-scatter-animation.md b/docs/agents/ui-audio-look-fx-scatter-animation.md index fcaf5083..35f09c1e 100644 --- a/docs/agents/ui-audio-look-fx-scatter-animation.md +++ b/docs/agents/ui-audio-look-fx-scatter-animation.md @@ -54,7 +54,9 @@ Read this when you touch screens and menus, sound and music, mesh looks, particl - **Lights are content** (`*.light.ron`, kind `light`, `shards_light`): kind (`Point`, or `Spot(inner_deg, outer_deg)` with the cone's whole opening in degrees, along the node's -Z), `color` (`#rrggbb`) or `kelvin`, `intensity` in Bevy's lumens, `range`, `radius`, `shadows`, `flicker`. A `ContentLight { id }` on an entity places one (a level node's `light=`, a prefab's `"ContentLight": (id: "lamp")`, code). Picture only (`SIMULATION = false`): with `render` the module puts a Bevy `PointLight`/`SpotLight` on a **child** entity (`LightPicture`, no `AiId`; `ContentLight` itself requires `Transform` and, with `render`, `Visibility`, so the entity that carries it has the same components headless and drawn), headless it only keeps `LightState`. Do not put a Bevy light on a gameplay entity for the look, and do not read a light in a tick. A game's own Bevy lights (a sun, a glTF lamp with no `light=`) are the game's: the module never touches them. - **Flicker is a pure function of the simulation's clock** (`Time` elapsed plus overstep, `shards_motion::camera::picture_clock`): a pause freezes it and `step` moves it, a headless game and a drawn one agree, and a test at a known tick knows the letter. A noise flicker is seeded by the light's content id, node name and place as they were when it first appeared (`flicker::seed_of`, kept in `LightSeeds` while the entity is placed, so a carried or moved light keeps its wander and `accessibility.flashes` still caps its rate), never `SimRng`; the position-based `key` is for ordering and ties only. A new per-light random value is taken once per entity the same way. The player's `accessibility.flashes` shapes it (`flicker::shaped`, `level_for`): reduced is no faster than 2 a second and half as far from the light as written, off is steady, and the `lights` query shows the flicker as drawn. New flicker kinds go in `flicker::level` as pure functions of `(clock, seed)`. -- **The shadow budget** (`graphics.shadow_lights`, `GraphicsSettings::shadow_light_budget`) is `budget::casters`, a pure function of the lights' distances to the viewer (the `AiCamera`, else a `ThirdPersonCamera` or `FirstPersonCamera`, else the local player's eye; with none of them there is no viewer: `lights` says so, every distance is unknown and ties go by the key alone), ties by a stable key (definition id, name, place), never by `Entity`. Only content lights that ask (`shadows: true`) take part. +- **The shadow budget** (`graphics.shadow_lights`, `GraphicsSettings::shadow_light_budget`) is `budget::casters`, a pure function of the lights' distances to the viewer (the `AiCamera`, else a `ThirdPersonCamera` or `FirstPersonCamera`, else the local player's eye; with none of them there is no viewer: `lights` says so, every distance is unknown and ties go by the key alone), ties by a stable key (definition id, name, place), never by `Entity`. Only content lights that ask (`shadows: true`) take part. `graphics.shadow_views` above 0 makes it a budget in views (`ShadowBudget::Views`: a point light 6, a spot 1, each light taken while its views fit, a farther one may still fit); at 0 it is the light count, byte for byte the old texts. +- **Ambient occlusion is the camera's picture** (`picture.ssao`, `SsaoTuning`): `apply_picture` adds `DepthPrepass`/`NormalPrepass` the camera lacks, sets `Msaa::Off` (Bevy's SSAO draws nothing under MSAA) and remembers what the camera had in `PictureSet`, so taking it out gives back the camera's own SSAO, MSAA and prepasses; it re-applies when another module takes a prepass away (the fx decals remove theirs). The view model's camera copies the world camera's `Msaa` and never gets SSAO. Bevy does not apply SSAO to a lightmap's light. +- **Baked light is the level's picture** (`shards_level::baked`, kind `baked_light`, `SIMULATION = false`): node properties name the files, the definition (keyed by the level's id) names the folders of the sets; `draw_baked` puts `Lightmap`/`LightProbe`/`IrradianceVolume`/`EnvironmentMapLight` on the drawn level and `keep_exposure` keeps `lightmap_exposure` on whatever `StandardMaterial` the mesh has. `BakedLight` (the chosen set per level) is a resource of the picture, in `state_audit`'s `OUTSIDE`; a game sets it from its own saved state. A `LightDef` with `baked: true` lights no lightmapped mesh's diffuse. A `Toon` look ignores lightmaps and probes. - **Colour grading is the camera's picture** (`picture.grading`, `shards_motion::camera::grading`): a `Grading` (exposure, white balance `temperature`/`tint`, `hue_deg`, `saturation`, `contrast`, `lift`/`gamma`/`gain`) becomes Bevy's `ColorGrading` on the world cameras; Bevy grades before tone mapping, so `tone_mapping: None` shows none of it. A `GradingVolume { id }` on a trigger volume (a level node's `grading=` with `marker = trigger`) blends the picture toward the `grading` definition while the local player's body touches it (`MotionState::volumes`; the last in collider id order wins), over its `blend_s`, and back to the camera's own. `GradingBlend` is a resource of the picture, tracked in `FixedLast` (exact ticks, `step` included) and applied in `Update`; it is in no snapshot or replay. Add a camera kind the picture reaches to `apply_grading` (the same cameras as `apply_picture`) and copy its `ColorGrading` to any second camera that draws the world. - **Check it** with the `lights` query (counts, flicker now, who casts a shadow and why not, the grade and its blend), headless (`lights.scenario`) and offscreen (`sandbox/tests/sandbox/lights.rs`: a flashing lamp at two moments, a grading volume's channel means). diff --git a/docs/agents/watching-and-driving.md b/docs/agents/watching-and-driving.md index 3c51f3eb..1b0c715a 100644 --- a/docs/agents/watching-and-driving.md +++ b/docs/agents/watching-and-driving.md @@ -76,7 +76,7 @@ cargo run -p sandbox --release -- --perf reference --offscreen # performance t `*.look.ron`, how many meshes each one draws; without a window and `--offscreen` nothing is styled, and it says so), `look_outlines on=false` (hide the outlines); **camera** — `camera_mode mode=first|third|content` (look through the first-person camera, or back through the orbit one, for this session: F1b; a window or `--offscreen` shows it; a headless game only stores the choice for the session, and a replay does not restore it); **foliage** — `scatter` (`*.scatter.ron` definitions, how many of each were scattered and what found no room; without a window and `--offscreen` nothing is scattered, and it says so), `scatter_set on=false` - (remove; `on=true` — scatter again), density — `settings_set group=graphics key=foliage value=0.5`; **lights** — `lights` (the lights from `*.light.ron` placed in the world: kind counts, which flicker and how bright each is now, which cast a shadow against `graphics.shadow_lights` and why the others do not, the picture's colour grade and its blend toward a grading volume; `id=`, `limit=`; the same headless and drawn), budget — `settings_set group=graphics key=shadow_lights value=2`; **effects** — + (remove; `on=true` — scatter again), density — `settings_set group=graphics key=foliage value=0.5`; **lights** — `lights` (the lights from `*.light.ron` placed in the world: kind counts, which flicker and how bright each is now, which cast a shadow against `graphics.shadow_lights` and why the others do not, the picture's colour grade and its blend toward a grading volume; `id=`, `limit=`; the same headless and drawn), budget — `settings_set group=graphics key=shadow_lights value=2` (or in views: `key=shadow_views value=12`, a point light 6, a spot 1); **baked light** — `baked_light` (each level's set of lightmaps and probes, who chose it, what is drawn and which images are loading or failed; `level=`), `baked_light_set level= set=` (dev: switch, without `set` back to the definition's); **effects** — `effects` (effects from `*.effect.ron`, their pools, the event table and links, the marks alive per kind, the debris at rest and the rays it cast, and the telegraph decals on the ground), `mark_spawn mark=bullet_hole point=[x,y,z] normal=[x,y,z]` (or `from=[x,y,z] toward=[x,y,z]`: a mark where a ray finds a surface), `fx_clear tag=gore` (or `all=true`), `effect_play effect=hit_spark at=eN` (or `point=[x,y,z]`), `telegraph_decals on=false` (the telegraph fill becomes gizmos again); without a window and `--offscreen` effects do not play, and the tools say so; **hit stop** — `hitstop` (how this machine holds, the settings, the table, what is held now, the totals and the ticks that ran inside a clock hold, which must be 0, the last holds), `hitstop_play event=damaged weight=Break attacker=e5 target=e6` (a hold as a blow would make; `seconds=0.08` skips the table); headless and stepped games never hold, and the tools say why: the hold is for a window or `--offscreen` in real time (not `--paused`); **rules** — `rules` (the rule set in play, its factors by class with the session's, the modes, whether a change is allowed now; `mode=gentle` describes another, and `playing` still names the one in play), `rules_set mode=harsh` or `cycle=1` (the host only, out of combat: `step --until named:rules_changeable`; `force=true` from a dev session), a game without `rules/default` has none and says so; **Steam** (a game with the `steam` feature) — `steam` (who this machine is in Steam, the lobby and diff --git a/docs/engine-progress.md b/docs/engine-progress.md index 78d218a9..698855e1 100644 --- a/docs/engine-progress.md +++ b/docs/engine-progress.md @@ -669,6 +669,7 @@ Gaps found by porting a larger game onto the engine (its port notes), closed one | F5 | use by looking: the physics layer `USE` (a query layer that collides with nothing), the component `Usable { name, prompt, hold_s, use_range }`, the pure ray `use_target` / `use_probe` / `use_point` (from `eye_of` along `look_dir` against `USE` and `WORLD`: a wall or glass nearer blocks, the nearest in its reach wins, a tie goes to the lower `ColliderId`), the `locomotion` field `use_range` (2 m by default, out of the written form); `ActionSystems::Use` (before the machine, bodies in `AiId` order): an `interact` press that finds a target triggers `Used { who, what, name }` (journalled, not a net event), a `hold_s` makes `UseProgress` (reflected state: snapshots, the replay hash) that grows while held and ends in `Used`, letting go, looking away, going out of reach or down cancels it; a revive in reach keeps its press; the tool `interact` (`target=eN` turns the look first, every refusal says why and changes nothing), the `USE` line of `observe`, `use_view`, the UI sources `you.use_target` and `you.use_progress`; a level `interactable` gets `Usable` and a use area from its node, the properties `hold_s`, `use_range`, `prompt` and the layer word `use`, checked with the node named | ✅ | `crates/shards_motion/src/usable.rs`, `physics/mod.rs`, `controller/params.rs`, `crates/shards_action/src/using.rs`, `look.rs`, `tools.rs`, `crates/shards_level/src/{props,spawn,tools}.rs`, `crates/shards/src/ui_wiring.rs`; tests `usable::tests` (11), `shards_action/tests/combat/using.rs` (15: a press, glass, the dead and downed, `AiId` against entity order, a hold and each way to cancel it, the revive that keeps its press, the tool and its refusals), `shards_level/tests/level/markers.rs` (5 more), `spawn.rs` (the bury order), `sandbox/tests/sandbox/using.rs` (the room's file, the scenario, `interact target=` through the room, a game observer that opens the used door and the use area sliding with it, a hold in a snapshot, the replay in heavy mode: `--heavy 10`); the sandbox's room `levels/use.gltf` with `world/use.level.ron`, `use.scenario`, the reference replay `use.json`; recording it left the twenty-five others byte-identical, and all twenty-six verify. Not in F5: a use by an NPC, a sphere cast for small things, `Used` as a net event, a use progress told as events | | F2 | crouch: `locomotion` gains `crouch_height` (none: the body cannot crouch), `crouch_speed` (a cap on the crouched walk, none: no slowdown) and `crouch_time` (0: at once), all left out of the written form at their defaults and checked with the field named; the input `crouch` (`input_names::CROUCH`, held, in the standard map on X; `hold_to_toggle` turns it into a toggle) is read from `Intent::held` by the controller; the stance is the reflected component `Crouch { depth, wanted, blocked }` beside `MotionState` (a new field of `MotionState` or `LocomotionInput` would have changed every body's hash), put on a body when it first crouches, `net_predicted` (a predicting client leaves the collider's shape to the host's state), judged by `motion.finite`; on the ground the feet stay and the head comes down, in the air the head stays and the feet are pulled up (`Crouch` lift added to `Transform`), a stand-up is a shape cast of the standing capsule (up on the ground, down in the air) and waits while it is blocked; `Crouched` and `Stood` events with journal lines; `CharacterParams::{can_crouch, height_at, eye_above_feet_at, at_depth}` give every reader of a body's size the stance (the controller's casts and collider, the separation pass, the movers that carry it, `clearance`/`path_to`, `eye_of`); the hurtbox is the body's own collider, fitted each tick; `PartDef::at_crouched` moves a part with the stance; the tool `crouch` (`hold=true` or `hold=false`; answers say how far and over how long, and when there is no room to stand), the describer (`ground 2.1m/s crouched`, `crouched, no room to stand`), `move_info`, and `stance=` (`standing`, `crouched` or `current`) on `clearance` and `path_to` (a crouched route is planned on the local grid: the navmesh is baked for the standing body) | ✅ | `crates/shards_motion/src/controller/{stance,params,mod,locomotion}.rs`, `eye.rs`, `ai.rs`, `tools.rs`, `invariants.rs`, `input/map.rs`, `perception/mod.rs`, `movers/step.rs`, `crates/shards_action/src/{parts,tools}.rs`, `crates/shards_core/src/intent.rs`; tests `controller::stance` (7), `params` (3), `ai` (1), `shards_motion/tests/motion/crouch.rs` (10: the capsule and the eye over `crouch_time`, a body that cannot crouch, a duct passed crouched, a ceiling that holds a stand-up, the speed cap and no sprint, a crouch jump over a ledge a plain jump misses, the head kept in the air, `clearance` and `path_to` with `stance=`, the refusal), `parts::a_part_with_a_crouched_place_...` (1), `sandbox/tests/sandbox/crouch.rs` (7: the room's file, the duct, the ledge, a crouched dummy's hurtbox, eye and head and a crouched shooter's eye, a crouched body on the movers' lift, a co-op client crouching its own body, the replay in heavy mode), `engine_rules.rs` (the depth control); the sandbox's `crouch_viewer` locomotion, `crouch_dummy` prefab and parts, room `levels/crouch.gltf` with `world/crouch.level.ron`, `crouch.scenario`, the reference replay `crouch.json` (verified with `--heavy 10`); recording it left the twenty-four others byte-identical (`git status tests/replays`). Not in F2: NPC brains do not crouch (no hiding yet, F11), the attack assist's sight line and a leap's landing probe use the standing size, an NPC's own eye is its `perception` content's `eye_height`, a crouched route on the navmesh, and the first-person camera's own easing of the eye (F1b: it follows `eye_of`, so the crouch shows in first person) | | F13 | lights from content, flicker, the shadow budget and colour grading (the FPS spec): the module `shards_light` (`shards::light`, optional: `--without light`; the content kind `light`, `LightDef { kind: Point \| Spot(inner_deg, outer_deg), color \| kelvin, intensity (lumens), range, radius, shadows, flicker: None \| Pattern(pattern, rate) \| Noise(rate, depth) }`, checked with the field named; the reflected component `ContentLight { id }`, placed by a level node's `light=`, a prefab or code, and `replay_ignore`d; `flicker::level`, pure in the simulation's clock and a seed of the light's own, never `SimRng`; `budget::casters`, pure, the nearest lights that ask for a shadow get one; `LightState`, refreshed every frame and by the query; the player query `lights` and `light` in `ai/status`; with `render` a Bevy `PointLight` or `SpotLight` on a child entity without an `AiId`, `LightPicture`); the setting `graphics.shadow_lights` (`u32`, default 4, 0 to 64, none under `shadows = "off"`, `GraphicsSettings::shadow_light_budget`); `shards_level`: the properties `light` and `grading` (checked against the content and the node: an unknown or empty id with a "did you mean", `grading` off a trigger marker) and the glTF loader's own lamp under a `light=` node taken out of the picture (`render.rs`, `lamps`); `shards_motion::camera::grading`: `picture.grading: Option` (`exposure`, `temperature`, `tint`, `hue_deg`, `saturation`, `contrast`, `lift`, `gamma`, `gain`; left out of the written form), the content kind `grading` (`GradingDef { blend_s, grading }`), `GradingVolume { id }` (a level node's `grading=` on a trigger marker), the resource `GradingBlend` (tracked in `FixedLast` from `MotionState::volumes`, or the camera's place with no local player, evaluated on `Time`), `apply_grading` onto the third-person and first-person cameras, the view model's camera taking the grade of a world camera that does not draw in HDR (`shards_action::render::view_model`) | ✅ | `crates/shards_light/src/` (`def.rs`, `flicker.rs`, `budget.rs`, `render.rs`, `tools.rs`), `crates/shards_motion/src/camera/grading.rs`, `crates/shards_level/src/{props,spawn,render}.rs`, `crates/shards_settings/src/groups.rs`; tests `shards_light` 25 (`src/` 8, `tests/light/` 17: the content check, the query and the clock, the flash setting, the budget, the Bevy lights of a drawn game), `grading.rs` 7, `tests/action_render/view_model.rs` +1, `tests/sandbox/lights.rs` (6, and 4 `#[ignore]`d for a GPU), `lights.scenario`; the sandbox's `content/light/`, `levels/lit_room.gltf`, `docs/media/lights.png`; measured on a GPU with `--offscreen`: the flasher on against off moved the brightest block of the room's picture by 91 of 255, and `rust` moved the mean colour from (85, 88, 78) to (98, 59, 56); `cargo run -p sandbox --release -- --perf reference --offscreen` passes every budget, three runs each back to back with the main it was cut from (tick average 0.87-1.14 ms against 0.85-0.98 ms, frame average 3.32-3.94 ms against 3.35-3.59 ms: run to run noise is about 10 percent, and the scene has no lights; the module adds two resources, which Bevy 0.20 keeps as entities (16484 entities against 16482), and a few systems that find nothing to do); no reference replay changed. Not in F13: directional lights as content, an emissive bulb that follows a flicker, hysteresis in the shadow budget, per-channel lift/gamma/gain wheels and a LUT (not in Bevy's built-in path), grading of a view model under an HDR camera | +| F13b | more light for the FPS spec, each off by default: ambient occlusion in the camera's picture (`picture.ssao`, `SsaoTuning { quality, radius, thickness }`: Bevy's SSAO with the depth and normal prepasses it needs and MSAA off while it is on, everything given back when it is taken out; the view model's camera follows the MSAA); a shadow budget in views (`graphics.shadow_views`, a point light 6, a spot 1, the nearest first, `ShadowBudget`; the `lights` query and `ai/status` say it); baked light (node properties `lightmap`, `lightmap_rect`, `irradiance_volume`, `reflection_probe`, `probe_falloff`; the picture-only kind `baked_light` with named sets of images; Bevy's `Lightmap`, `LightProbe`, `IrradianceVolume`, `EnvironmentMapLight` on the drawn level; `select_baked_set`, `BakedLight`; tools `baked_light`, `baked_light_set`; `LightDef::baked`). Confining a light to a room: researched, not done (it needs a patched `bevy_pbr`; the manual says what it would take) | ✅ | `crates/shards_motion/src/camera/picture.rs`, `crates/shards_settings/src/groups.rs`, `crates/shards_light/src/{budget,lib,tools,def,render}.rs`, `crates/shards_level/src/{baked,props,asset}.rs`; tests `picture.rs` (SSAO, unit), `tests/action_render/view_model.rs` (MSAA), `budget.rs`, `tests/light/headless.rs` (views), `tests/level_render.rs` (baked light; offscreen `#[ignore]`: a lightmapped mesh draws its lightmap and takes dynamic lights) | | R4 | the camera next to a big body: measured first (`tests/motion/camera_big.rs`, `measure`, `#[ignore]`: at the defaults the feet sit at y -0.37 of the frame and a point 6 m up at 2 m, 9 m up at 8 m and 12 m up at any distance reach the top edge or pass it), then `FramingTuning::fit` (`FitTuning { margin, tilt_max, rate }`, default `None`: no change): a locked camera's view turns up from the focus (`ThirdPersonCamera::tilt`, `fit_tilt`, measured in the camera's own frame) just far enough to put the target on the top margin and never so far that the feet leave the bottom one (the player is kept when both cannot be; `fit_room` holds the tilt to the feet and `tilt_max` on every frame); a lower camera is the existing `framing.pitch_clamp`; the far plane needed nothing | ✅ | `crates/shards_motion/src/camera/{tuning,math,mod,systems}.rs`; tests `camera::math` (`the_fit_turns_up_to_a_high_target_and_never_loses_the_feet`), `tests/motion/camera_big.rs` (6 and the measurement), `camera_content.rs` (`a_fit_is_read_with_its_defaults_and_bad_numbers_are_errors`); the sandbox's `combat/camera.camera.ron` turns the fit on (content: 214 definitions in 64 files). Not in R4: an arm that grows for a big body (a game sets `ThirdPersonCamera::distance`); framing a threat other than the lock (a swinging hand while locked on a leg); a vertical flick | | K1 | a separate aim sensitivity: `controls.aim_sensitivity` (0.05 to 5) to `CameraSettings::aim_sensitivity`, used by free look while the game sets `CameraOffsets::aiming`; the sandbox's "Aim speed" slider | ✅ | `crates/shards_settings/src/groups.rs`, `crates/shards_motion/src/camera/{mod,tuning,systems}.rs`; tests `tests/motion/camera.rs` (1), `input.rs`, `tests/settings/{persist,tools}.rs` | | K2 | camera auto-centre: `controls.camera_auto_centre` (off by default) to `CameraSettings::auto_centre`; `CameraTuning::auto_centre` (`delay_s`, `rate`, `min_speed`, `max_turn_deg`, `pitch`); free look turns behind a walking body after the look is left alone (`ThirdPersonCamera::look_idle_s`, `camera::math::auto_centre`); the sandbox's toggle | ✅ | `crates/shards_motion/src/camera/{math,tuning,mod,systems}.rs`, `crates/shards_settings/src/groups.rs`; tests `camera::math` (1), `tests/motion/camera.rs` (3), `input.rs`, `tests/settings/{persist,tools}.rs` | diff --git a/docs/manual.md b/docs/manual.md index 96188891..24adb56c 100644 --- a/docs/manual.md +++ b/docs/manual.md @@ -1112,6 +1112,8 @@ For the AI: `observe` shows `slowed x0.60, rooted, capped 3.0m/s, no sprint, spr | `picture.bloom.intensity` / `low_frequency_boost` / `low_frequency_boost_curvature` / `high_pass_frequency` | `0.15` / `0.7` / `0.95` / `1` | Bevy's natural bloom: how strong the glow is, how much more the wide part of it weighs and how that falls off, and how wide it reaches (above 0, at most 1) | | `picture.bloom.threshold` / `threshold_softness` | `0` / `0` | only light brighter than this spreads (linear; 0 lets everything glow a little, as Bevy's natural bloom does); how soft the knee at the threshold is, 0 to 1 | | `picture.bloom.composite` | `EnergyConserving` | `EnergyConserving`: the glow takes its share of the light from the picture (Bevy's natural bloom); `Additive`: it is added on top | +| `picture.ssao` | `None`: the camera's own (none) | screen-space ambient occlusion: the light that comes from no one direction (an ambient light, an irradiance volume, a reflection probe) darkens in creases and where things meet. It turns the camera's MSAA off while it is set and adds a depth and a normal prepass (the picture, below) | +| `picture.ssao.quality` / `radius` / `thickness` | `High` / `0.7285` / `0.25` | Bevy's `ScreenSpaceAmbientOcclusion`: `Low` (4 samples a pixel), `Medium` (8), `High` (18) or `Ultra` (54); how far round a pixel occluders are looked for (m, above 0); how thick everything on screen is taken to be (m, above 0) | | `picture.grading` | `None`: the camera's own | a colour grade of the whole picture: `exposure` (stops), `temperature` and `tint` (white balance, `-1` to `1`), `hue_deg`, `saturation`, `contrast`, `lift`, `gamma` and `gain` (the neutral values: 0, 0, 0, 0, 1, 1, 0, 1, 1); Bevy's `ColorGrading` with the same values for shadows, midtones and highlights. Bevy grades just before tone mapping, so it shows nothing under `tone_mapping: None`. A grading volume blends the picture away from it and back (the picture, below; "Lights and colour grading (F13)") | | `mode` | `ThirdPerson` | the camera the game plays through: `FirstPerson` puts a `FirstPersonCamera` on every `ThirdPersonCamera` entity (F1b, "The first-person camera and the view model") | | `first_person.*` | see the table in "The first-person camera and the view model (F1b)" | the first-person camera's own numbers: the ease on steps, the landing dip, the bob, the lean, the default view model; read by `FirstPersonCamera` only | @@ -1176,7 +1178,13 @@ down the framed arm may go (`(0.0, 0.7)` keeps it level with the head next to a lock pick and the flick read the camera's `Transform`, so with a tilt they measure from what the player sees. The far plane (Bevy's default 1000 m) did not need a number. The sandbox's `combat/camera.camera.ron` turns the fit on for its colossus. -**The picture (`picture`).** The camera content can also say how the picture is drawn: its tone mapping, its bloom and its colour grade (`shards::motion::camera::{PictureTuning, ToneMapping, BloomTuning, BloomComposite, Grading}`). All three are left out by default, and then every camera keeps what the game spawned it with, so a game without a `picture` sees no change. They apply to every 3D camera with `ThirdPersonCamera` or `FirstPersonCamera`, a camera spawned later included. A bloom makes the camera draw in HDR (Bevy's `Bloom` requires `Hdr`): the materials' colours are no longer stopped at full, and tone mapping moves from each material's shader to one pass over the whole picture, so light brighter than white (a lamp, an effect with an `intensity` above 1, see "Effects and decals") keeps its brightness until the tone mapping and the bloom see it. Taking `bloom` out of the content (or the whole definition) gives the camera back its own bloom, or none, and leaves HDR off again if the content turned it on. The same holds for `tone_mapping`. A game that sets its own `Bloom`, `Hdr` or `Tonemapping` on the camera keeps them while the content says nothing. The picture changes nothing else: the `camera` kind is not simulation content, so no replay changes. With HDR on, everything is tone mapped once, in the post pass, particles included (the particles' shader has no tone mapping of its own, so without HDR their colours reach the screen as written). +**The picture (`picture`).** The camera content can also say how the picture is drawn: its tone mapping, its bloom, its colour grade and its ambient occlusion (`shards::motion::camera::{PictureTuning, ToneMapping, BloomTuning, BloomComposite, Grading, SsaoTuning, SsaoQuality}`). All four are left out by default, and then every camera keeps what the game spawned it with, so a game without a `picture` sees no change. They apply to every 3D camera with `ThirdPersonCamera` or `FirstPersonCamera`, a camera spawned later included. A bloom makes the camera draw in HDR (Bevy's `Bloom` requires `Hdr`): the materials' colours are no longer stopped at full, and tone mapping moves from each material's shader to one pass over the whole picture, so light brighter than white (a lamp, an effect with an `intensity` above 1, see "Effects and decals") keeps its brightness until the tone mapping and the bloom see it. Taking `bloom` out of the content (or the whole definition) gives the camera back its own bloom, or none, and leaves HDR off again if the content turned it on. The same holds for `tone_mapping`. A game that sets its own `Bloom`, `Hdr` or `Tonemapping` on the camera keeps them while the content says nothing. The picture changes nothing else: the `camera` kind is not simulation content, so no replay changes. With HDR on, everything is tone mapped once, in the post pass, particles included (the particles' shader has no tone mapping of its own, so without HDR their colours reach the screen as written). + +*Ambient occlusion.* `picture.ssao` gives the camera Bevy's `ScreenSpaceAmbientOcclusion`: from the depth and normals of what is on screen it darkens the indirect light (an ambient light, a camera's own `AmbientLight` fill, an irradiance volume, a reflection probe) in creases, corners and where a body meets the floor. It never darkens a point, spot or directional light, and Bevy does not apply it to a lightmap's light either (a bake has its occlusion in it): on a level with lightmaps it shows on what moves, lit by the probes and the ambient. Bevy's SSAO needs a depth prepass, a normal prepass and a camera without MSAA (with MSAA it logs an error and draws none): while the content gives a camera SSAO, the camera gets the prepasses it lacks and `Msaa::Off`; if another module takes a prepass away (the decals' depth prepass goes when the decals do) it is put back the next frame. Taking `ssao` out of the content gives the camera back its own SSAO (or none) and its own MSAA, and drops the prepasses it did not have. The first-person view model's camera copies the world camera's MSAA (the two share one main texture) and has no SSAO of its own: the arms are drawn over the occluded world. Without MSAA edges alias: a game that turns SSAO on wants an anti-aliasing pass of its own (FXAA, SMAA or TAA on the camera; TAA also smooths SSAO's noise). What it costs, measured on an RTX 5080 at 1920×1080 (`offscreen_measure_what_ssao_costs_on_the_gpu` in `crates/shards/tests/level_render.rs`, `#[ignore]`: Bevy's GPU timestamps of each pass over a floor with a grid of blocks): the SSAO pass takes 0.09 ms at `Low`, 0.13 ms at `Medium`, 0.22 ms at `High` and 0.60 ms at `Ultra`, and the depth and normal prepass 0.01 ms more; the whole frame grows by 0.07, 0.12, 0.20 and 0.58 ms (the prepass lets the main pass skip hidden pixels, which pays a little back). The cost goes with the pixels on screen, not with what is in the world; a weaker GPU pays several times more. + +```ron +{ "default": (picture: (ssao: Some((quality: Medium, radius: 0.5)))) } +``` ```ron // assets/content/combat/camera.camera.ron: the sandbox's bloom; only light 1.5 times past white glows, so nothing @@ -2773,6 +2781,8 @@ Blender (.blend) ── export glTF ──► tiles/ruin.gltf ──► LevelAss | `mover` | text | the node is a mover (F6) that goes through the keys of that `mover` definition, and the nodes below it move with it (see "Movers (F6)") | | `light` | text | the node shines by that `light` definition (F13, `shards_light::ContentLight`) from where it stands: a Blender lamp, whose own glTF light is taken out of the picture and replaced, or an empty; a spot points along the node's -Z (see "Lights and colour grading (F13)") | | `grading` | text | on a `marker` = `trigger` node: the picture blends toward that `grading` definition (F13, `GradingVolume`) while the local player is inside, and back when it leaves | +| `lightmap`, `lightmap_rect` | a file name; `[x0, y0, x1, y1]` (0 to 1, the top left first; the whole image when left out) | baked light (the picture's, "Baked light" below): the node's mesh draws that lightmap of the level's baked set by its second UV map, over that part of the image | +| `irradiance_volume`, `reflection_probe`, `probe_falloff` | a file name; a name; `[x, y, z]` or one number, 0 to 1 | baked light: the node (an empty) is a light probe box, the unit cube under its transform, with that irradiance volume and/or the reflection cube maps `_diffuse.ktx2` and `_specular.ktx2`, fading that far in from its sides | | `hold_s`, `use_range`, `prompt` | seconds (zero or more), metres (above zero, at most 100), text | for an `interactable` (F5, see "Use by looking"): the seconds the button is held for a use (0, the default, is a press), how far from the eye it can be used (without it, the body's own `use_range`), and the text a HUD shows (a Fluent `@id` or plain text; without it, the marker's name) | Any other key is a **component**: a short name (`Health`) or the full type path. The value is JSON in the form that `inspect` and `get` show: @@ -2785,6 +2795,39 @@ Locked = true (component with no fields) A JSON object can be typed in as text (the *String* type): text that holds a JSON object or list is read as one. The *Python* type does the same without quotes: `{"current": 40.0}` becomes a dictionary, and the exporter writes it as a JSON object. A list of names (`["world", "game3"]` for `layers`) works the same way. A component must be registered for reflection (`#[derive(Reflect)]`, `#[reflect(Component)]`), as for prefabs. On a node with `prefab`, component properties merge into the prefab field by field (`Health = {"current": 10}` leaves the prefab's `max`). A node without these properties (a group, or a mesh without `collider`) spawns nothing, and the mesh stays a picture only. Keys with `_` are ignored. +**Baked light (lightmaps and light probes).** A level can carry light a bake worked out (Blender's Cycles, by the game's own dressing script; the engine has no baker): a **lightmap** per mesh, the light that falls on each texel of the walls (the bounce, the soft shadows, the occlusion a live light does not have), and **light probes** in its rooms, so a body that moves through the room takes the room's baked light. It is the picture's alone: nothing spawns for it, no tick reads it, and its content kind is not simulation content. + +- *The file says which image.* The bake script writes custom properties on the objects it baked: `lightmap = "walls_0.ktx2"` and `lightmap_rect = [0.0, 0.5, 0.5, 1.0]` on a mesh (many meshes share one atlas, each in its rect), and on an empty that boxes a room `irradiance_volume = "hall.ktx2"` and/or `reflection_probe = "hall"`, with `probe_falloff = 0.2`. A probe's box is Bevy's: the unit cube (-0.5 to 0.5) under the node's transform (in Blender an empty of display type *Cube* and size 0.5, scaled to the room). The mesh draws its lightmap by its **second UV map** (`TEXCOORD_1`; bake into a second UV map and export it); `content check` names a lightmapped mesh without one, which Bevy would draw unlit by the map. +- *The content says where the files are.* `content/**/*.baked_light.ron`, the kind `baked_light`, one definition per level under the level's id (`BakedLightDef`, `SIMULATION = false`: editing it never moves a replay or a co-op handshake): + +```ron +// content/levels/tunnels1.baked_light.ron +{ + "tunnels1": ( + sets: { "lamps_on": "baked/tunnels1/on", "breach": "baked/tunnels1/breach" }, + set: "lamps_on", + lightmap_exposure: 2000.0, + irradiance_intensity: 2000.0, + reflection_intensity: 2000.0, + ), +} +``` + +| field of a `baked_light` | default | meaning | +|---|---|---| +| `sets` | (required) | the sets of baked images, by name: a folder each, relative to the asset folder, holding every file the level's nodes name. The glTF is the same for every set | +| `set` | (required) | the set drawn while the game has chosen none | +| `lightmap_exposure` | `1` | what a lightmap texel of 1 is worth in cd/m² (Bevy's `StandardMaterial::lightmap_exposure`, put on the material of every lightmapped mesh): a bake writes radiance in its own units, and this brings them to the game's lights and camera exposure (at Bevy's default exposure, about 1000 is full white) | +| `irradiance_intensity` / `reflection_intensity` | `1` / `1` | the same for the irradiance volumes and the reflection probes (Bevy's `intensity` of each) | +| `bicubic` | `false` | bicubic sampling of the lightmaps: smoother, dearer, and it may leak at the edges of a chart | + + The check names each problem: a `set` that is not in `sets`, a folder outside the asset folder, a level without a baked node, a lightmapped mesh without a second UV map, and every file a node names that a set's folder lacks (`node `Hall/Wall.003`: set `breach` has no `baked/tunnels1/breach/walls_0.ktx2``). The node properties themselves are checked with the level (an empty name, a rect outside 0 to 1, a `lightmap_rect` without a `lightmap`). +- *Formats.* A `.ktx2` of linear half floats (`Rgba16Float`) or `Rgb9e5` is the format for a bake (Blender writes EXR; convert it, e.g. with `ktx create --format R16G16B16A16_SFLOAT`). A `.png` is read as sRGB, 8 bits a channel: fine for a test, low range for a real bake. A `.hdr` is 32-bit float, which only a GPU that filters such textures can sample (Bevy asks for the feature where the adapter has it). Irradiance volumes are 3D KTX2 textures in Bevy's layout (`bevy::pbr::irradiance_volume`; Blender's volume bakes export to it with `bevy-baked-gi`); reflection probes are pairs of KTX2 cube maps. Every baked image is sampled linearly and clamped at the edges, whatever sampler the game made the default (except a `.hdr`, whose loader takes the default). +- *Drawing* (with `render`). Each mesh primitive of a `lightmap` node gets Bevy's `Lightmap` (the image, the rect, `bicubic`), and the material it draws with gets the set's `lightmap_exposure` (kept on whatever `StandardMaterial` it has, one a `Lit` look made included). A lightmapped mesh still takes every dynamic light: a flashlight, a muzzle flash, a flickering lamp. A content light with `baked: true` lights no lightmapped mesh's diffuse (it is in the lightmap already) and still lights bodies and the shine of surfaces. A probe node gets a `LightProbe` with an `IrradianceVolume` (which does not light lightmapped meshes: they have their own) and/or an `EnvironmentMapLight`. Bevy ranks the indirect light of a surface lightmap first, then an irradiance volume, then a reflection probe; ambient light is added on top (a camera's `AmbientLight` with `affects_lightmapped_meshes: false` leaves baked walls alone). A `Toon` look draws its own bands and ignores lightmaps and probes; a `Lit` look keeps them. SSAO (`picture.ssao`) does not darken a lightmap's light. +- *Switching sets.* `BakedLight` (a resource, the picture's: in no snapshot or replay) holds the set each level draws when the game chose one. The story turns the lamps off after a breach: the game calls `shards::level::select_baked_set(world, "tunnels1", Some("breach"))` (or `ResMut::select`), from its own state, which it saves; it calls it again after a load, and calling it every frame with the same set changes nothing. `None` goes back to the definition's `set`. The probes follow on the next frame; a lightmap follows once the new set's image has loaded (the old one is drawn meanwhile), with one frame without a lightmap between the two, because Bevy 0.20 puts a new `Lightmap` only on a mesh that has none. The content lights the breach turns off are the game's to turn off. (Bevy also picks a mesh's pipeline again only when its mesh or material changes, not when a lightmap comes or goes: the engine marks the mesh changed with every lightmap it puts on or takes off. A game that puts a `Lightmap` on its own meshes must do the same, or Bevy stops drawing on a wgpu validation error.) +- *For the AI.* `baked_light` (player scope): each level with a `baked_light`, the set drawn and who chose it, how many nodes carry a lightmap or a probe, and in a drawn game how many meshes are lightmapped and which images are loading or failed; `level=` narrows it. `baked_light_set level=tunnels1 set=breach` (dev scope, picture only like `look_outlines`) switches; without `set` it goes back to the definition's. +- *Not here.* The bake itself (that is the game's dressing script), lightmaps on levels placed by file alone (a tile of a region: they have no `baked_light`, which is keyed by a level's id), and a blend between two sets (a switch is a cut). + **Engine markers** (`marker`). The game finds them with an ordinary `Query<(&LevelMarker, &Transform)>`. | `marker` | entity | what the AI sees | @@ -6059,6 +6102,7 @@ resolution = "1920x1080" # "auto" — the game's own choice render_scale = 1.0 # 0.5…2: the 3D world is drawn at this many times the window's pixels (UI stays at native) shadows = "high" # off | low | medium | high shadow_lights = 4 # 0…64: how many lights from content cast shadows, the nearest to the camera first (shards_light); `shadows = "off"` is none +shadow_views = 0 # 0…384: the same budget in shadow views (a point light 6, a spot 1), the nearest first; 0 counts lights by shadow_lights foliage = 1.0 # 0…1: how much foliage and small objects to scatter (scatter) interpolation = true # draw bodies between their last two ticks (smooth at any refresh rate); false: the last tick's pose @@ -6095,7 +6139,7 @@ attack_assist = true # false: attacks do not correct their direction tow | group | who and how | |---|---| -| `graphics` | `shards_settings::apply_graphics`: the main window (fullscreen, vsync, size). `shadow_lights` is read by `shards_light`: of the content lights that ask for a shadow, only that many, the nearest to the camera, cast one (see "Lights and colour grading (F13)"; `shadows = "off"` is none). The window changes when the settings change, not every frame, so the size the player dragged with the mouse is not taken back. Without a window the values are only stored. `render_scale` is applied by `shards::render_scale`: the resolution of the 3D picture, not the window scale (see "3D picture resolution" below). `shadows` is read by the game: `GraphicsSettings::shadow_quality()`; `foliage` is read by `shards_scatter` (`GraphicsSettings::foliage_density()`): at 0.5 half of the same instances stays, with no new ones (see "Foliage and small objects (E10.2)"); `interpolation` is read by `shards_motion` (render interpolation, see "Render interpolation (C8)") | +| `graphics` | `shards_settings::apply_graphics`: the main window (fullscreen, vsync, size). `shadow_lights` is read by `shards_light`: of the content lights that ask for a shadow, only that many, the nearest to the camera, cast one (see "Lights and colour grading (F13)"; `shadows = "off"` is none). `shadow_views` above 0 counts that budget in shadow views instead and replaces `shadow_lights` (a point light takes 6, a spot 1). The window changes when the settings change, not every frame, so the size the player dragged with the mouse is not taken back. Without a window the values are only stored. `render_scale` is applied by `shards::render_scale`: the resolution of the 3D picture, not the window scale (see "3D picture resolution" below). `shadows` is read by the game: `GraphicsSettings::shadow_quality()`; `foliage` is read by `shards_scatter` (`GraphicsSettings::foliage_density()`): at 0.5 half of the same instances stays, with no new ones (see "Foliage and small objects (E10.2)"); `interpolation` is read by `shards_motion` (render interpolation, see "Render interpolation (C8)") | | `audio` | `shards_audio`: the volume of the buses `music`, `sfx`, `voice`, `ui` with `master` taken into account (`AudioSettings::volume("music")`), applied to what is already playing (see "Audio") | | `controls` | `shards_motion`: `ControlSettings` ⇄ `InputMap` (see "Input" in "Movement (E2)"); the two look speeds (`mouse_sensitivity`, and `aim_sensitivity` while the game sets `CameraOffsets::aiming`), the Y-axis inversion and `camera_auto_centre` go to `CameraSettings`; `attack_assist = false` makes the controls hold `assist_off` for the player's body (see "Action timeline (B2a)") | | `accessibility` | `shards_motion`: the field of view and the strength of the camera shake, `MotionBlur` on the cameras that have it (the game adds the component, the setting sets the strength, 0 turns it off), `hold_to_toggle` in the input map; `shards_action`: `flashes` for the blinking of telegraphs and of off-screen markers (`reduced` — half as big and no more than 2 times a second, `off` — a steady light, `draw::pulse_at`) and `shards_ui`: `flashes` for full-screen flashes (`reduced` — at most 0.35 strong, pulses no more than 2 times a second and half as deep, eased fades, `off` — none; see "UI (E9)"); `shards_light`: `flashes` for the flicker of lights (`reduced` — at most 2 steps or changes a second and half as far from the light as written, `off` — steady; see "Lights and colour grading (F13)"); `shards_audio`: `subtitles` for the lines of voices (off: the source `subtitles` is empty; see "Audio") | @@ -7105,6 +7149,7 @@ A light is content, and so is the colour of the picture. The `shards_light` modu | `range` | `15` | how far it reaches (m), above 0 and at most 1000 | | `radius` | `0` | the size of the source (m): bigger softens its highlight | | `shadows` | `false` | whether it asks for a shadow; the shadow budget decides whether it gets one | +| `baked` | `false` | its light is baked into the level's lightmaps (`baked_light`, "Levels from Blender (E4.2)", "Baked light"): it then lights no lightmapped mesh's diffuse (Bevy's `affects_lightmapped_mesh_diffuse`), which has it already, so a lamp is not counted twice and lights nothing on a baked wall through the wall; it still lights what moves (bodies, props) and the shine of every surface. A flashlight, a muzzle flash and a light that changes from the bake leave it `false` | | `flicker` | `None` | `Pattern(pattern, rate)`: one letter `a`-`z` per step, `rate` steps a second, looping; `a` is dark, `m` the light as written, `z` about twice (`(letter - 'a') / 12`), the classic light styles. `Noise(rate, depth)`: smooth noise that wanders between `1 - depth` and 1 times the intensity, `rate` times a second | The content check names the file, the definition and the field: `intensity` 0 or more, `range` above 0, the spot angles as above, a pattern of the letters `a`-`z` only (and not empty), `rate` above 0 (at most 240), `depth` from 0 to 1, a `color` that reads, a `kelvin` from 1000 to 40000, and not a `color` with a `kelvin`. A `grading` definition (`blend_s`, `grading`) is checked the same way: `blend_s` from 0 to 60 seconds, `temperature` and `tint` from -1 to 1, `exposure` from -10 to 10, `hue_deg` from -180 to 180, `saturation` and `contrast` from 0 to 4, `lift` from -1 to 1, `gamma` from 0.05 to 4, `gain` from 0 to 8. Both kinds are not simulation content (`SIMULATION = false`): editing them never makes a replay diverge. @@ -7115,11 +7160,13 @@ The content check names the file, the definition and the field: `intensity` 0 or **The shadow budget.** `graphics.shadow_lights` (default 4, 0 to 64, `settings_set group=graphics key=shadow_lights value=2`; `graphics.shadows = "off"` is none) says how many content lights may cast a shadow at once. Of the lights whose definition says `shadows: true`, the ones nearest the viewer get one; the viewer is the active camera (the AI's `AiCamera`, else a `ThirdPersonCamera` or a `FirstPersonCamera`), and a game with no camera (headless) measures from the local player's eye; with no camera and no local player there is no viewer, the `lights` query says so and every distance is unknown, and ties go by the key alone. Distances are compared to the centimetre and ties go by a key made of the definition's id, the node's name and the place, never by `Entity`, so a shot taken twice from one place shows the same shadows and a headless game agrees with a drawn one standing there. There is no hysteresis: a light that comes nearer than one that has a shadow takes it, once. A cube shadow map is six passes, so this is the knob for a weak GPU. Only content lights that ask are counted: a game's own Bevy lights keep their own `shadow_maps_enabled`. +**A budget in shadow views.** Each shadow view is a pass the render thread prepares and the GPU draws: a point light's cube is six, a spot's one. `graphics.shadow_views` (default 0, 0 to 384, `settings_set group=graphics key=shadow_views value=12`) counts the budget in views instead of lights: above 0 it replaces `shadow_lights`, and `shadows = "off"` is still none. The lights that ask go nearest first, each taking its views while they fit in what is left; one that does not fit has no shadow, and a farther light that does fit has one, so twelve views shadow twelve spots, or two points, or one point and the six nearest spots. The `lights` query then reads `budget 12 views, 8 taken: graphics.shadow_views`, and a light that missed out says why: `shadow: no (over the budget: it takes 6 views, 2 of 12 left after the nearer lights)`; `ai/status` adds `budget_views: true` and `views_used`. A game whose lamps are mostly spots aimed at what they light gets many more shadows for the same cost this way, and every shadowed lamp is one that does not light through a wall. + **Colour grading.** `picture.grading` of the `camera` content is a `Grading`: `exposure` (stops), `temperature` and `tint` (white balance: positive is redder or more magenta), `hue_deg`, `saturation`, `contrast`, `lift`, `gamma`, `gain` (the offset, power and slope of the ASC CDL). It becomes Bevy's `ColorGrading` on every 3D camera with a `ThirdPersonCamera` or a `FirstPersonCamera` (the same cameras as the rest of the picture), the same values for the shadows, the midtones and the highlights; Bevy grades just before tone mapping, so a camera whose `tone_mapping` is `None` shows none of it. Per-channel lift/gamma/gain wheels and a LUT are not in Bevy's built-in path (its sections are scalar, its LUT is the tone mapper's), so they are not here: `temperature` and `tint` are the colour casts. A camera keeps its own `ColorGrading` (a game's) while the content says nothing, and gets it back when the content stops saying anything. A **grading volume** changes it where the player stands. A level node with `marker = "trigger"` (a collider shapes it, `auto` by default) and `grading = "rust"`, or a prefab with `"GradingVolume": (id: "rust")` on an entity with a trigger `Volume`: while the local player's body touches it (`MotionState::volumes`), the picture blends from what it shows toward the `rust` definition over its `blend_s` (eased, smoothstep), holds it, and blends back to the camera's own grade over the same time when the player leaves; a game with no local player uses the volumes the camera stands in. Where volumes overlap, the one placed last (the highest collider id) wins; a blend that changes course starts from what is shown, so nothing jumps. The state is the resource `GradingBlend`, tracked in `FixedLast` on every tick (so a `step` of 100 ticks sees the tick the player crossed the line) and evaluated on the simulation's clock, which is why a headless game can say where the blend is. It is in no snapshot or replay. -**For the AI.** The query `lights` (player scope, the same headless and drawn): the lights by kind, how many flicker, how many want a shadow and cast one against the budget, the viewer the budget measures from, and a line per light: its definition, name, place, distance, lumens now against its definition's, the flicker (pattern step and letter, or noise, with the percentage now) and `shadow: yes`, `no (over the budget)`, `no (budget 0)` or `not asked`; then the grade the picture shows and where its blend is (the line reads "blending toward `rust`, 62 % done", "holding `rust` (blend done)", "blending back to the camera's own, 30 % done" or "the camera's own"). `lights id=sodium` lists one definition, `limit=` the first lights (24). `ai/status` has `light: {lights, casting, flickering, budget}`. The tool refreshes the state first, as a frame does, so a stepped game answers for now. +**For the AI.** The query `lights` (player scope, the same headless and drawn): the lights by kind, how many flicker, how many want a shadow and cast one against the budget, the viewer the budget measures from, and a line per light: its definition, name, place, distance, lumens now against its definition's, the flicker (pattern step and letter, or noise, with the percentage now) and `shadow: yes`, `no (over the budget)`, `no (budget 0)` or `not asked`; then the grade the picture shows and where its blend is (the line reads "blending toward `rust`, 62 % done", "holding `rust` (blend done)", "blending back to the camera's own, 30 % done" or "the camera's own"). `lights id=sodium` lists one definition, `limit=` the first lights (24). `ai/status` has `light: {lights, casting, flickering, budget}` (and `budget_views`, `views_used` under `graphics.shadow_views`). The tool refreshes the state first, as a frame does, so a stepped game answers for now. ```text $ shards act lights @@ -7137,7 +7184,9 @@ grading: the camera's own **In the sandbox.** `content/light/` has the lights (`lamp`, `sodium`, `tube`, `flasher`, `dimmer`, `torch`), the gradings (`rust`, `cold`), the prefabs `lit_lamp` and `lit_flasher`, and the level `lit_room` (`assets/levels/lit_room.gltf`, written by `tests/sandbox/lights.rs`): a floor and three walls with six lights (four on Blender lamps that the content lights replace, two on empties) and a trigger volume over its right half that grades with `rust`. `scenarios/lights.scenario` plays it with queries alone, so it runs headless. Tests: `shards_light` (unit tests for the definitions, the flicker and the budget; `tests/light/` for the content check, the query, the clock and the Bevy lights of a drawn game) and the sandbox's `lights.rs`, whose `#[ignore]`d tests need a GPU (`cargo test -p sandbox --test sandbox -- --ignored lights`): the picture holds exactly the six content lights, a flashing lamp lights the room at one moment and not at the next, and a grading volume changes the channel means of the shot and gives them back. -**What is not here.** Directional lights (a sun) are not content yet. Emissive bulbs do not follow a flicker (the material is the game's). There is no area light or light cookie, no hysteresis in the budget, and a spot's shadow costs one pass where a point light's costs six, which the budget does not tell apart. The view model's camera (F1b) takes the world camera's grade when that camera does not draw in HDR; under an HDR camera (any `picture.bloom`) it draws over the graded picture and stays ungraded, and any other second camera that draws the world is the game's to grade. Checked on a GPU with `--offscreen` (RTX 5080); not checked by eye in a window. +**What is not here.** Directional lights (a sun) are not content yet. Emissive bulbs do not follow a flicker (the material is the game's). There is no area light or light cookie and no hysteresis in the budget. A light cannot be confined to a room: a light without a shadow lights through walls (see "Confining a light to a room" below). The view model's camera (F1b) takes the world camera's grade when that camera does not draw in HDR; under an HDR camera (any `picture.bloom`) it draws over the graded picture and stays ungraded, and any other second camera that draws the world is the game's to grade. Checked on a GPU with `--offscreen` (RTX 5080); not checked by eye in a window. + +**Confining a light to a room.** A light lights everything inside its `range` (and a spot's cone) that faces it; only its shadow map stops it at a wall, so a lamp without a shadow (over the budget, or `shadows: false`) lights the next room through the wall. There is no clean way in Bevy 0.20 to clip a light to a box or a room. Its clustered lights carry no room or volume (the GPU struct `GpuClusteredLight` and its WGSL twin `ClusteredLight` are Bevy's, with `pub(crate)` fields, and the mesh view bind group is fixed), its clustering does not read a light's `RenderLayers`, and `RenderLayers` filter a light per camera, not per surface, so they would not confine a light to a room even where honoured. A clean confinement needs a patched `bevy_pbr`: a component on the light (an axis-aligned box, or a room mask matched against a per-mesh mask) extracted into the clustered light (16 to 32 bytes more per light), and a test in the point and spot light functions of `pbr_lighting.wesl` that returns no light for a fragment outside it (six compares per light per fragment, nothing on the CPU). That is a fork of Bevy's renderer to carry from version to version, so it is not done. What the engine does give: a budget in shadow views (`graphics.shadow_views`, above), which gives many spots a shadow where one point light would; and baked light (`baked_light` with `baked: true` on the lamps the bake holds), whose lightmaps carry the walls' occlusion, so a baked lamp lights no lightmapped surface at all, through a wall or not, and only what moves and the surfaces' shine take its live light. ## Hit stop (C2) From 8c0675522e0ff6a27d96de8b7404518c28e9d057 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:10:22 +0100 Subject: [PATCH 5/7] Offscreen test: the camera content's SSAO through the first-person cameras Drawn for real in the sandbox: SSAO on the first-person camera with the view model's camera following its MSAA, a depth prepass taken away for a frame put back with the frames going on, and SSAO out again giving both cameras their MSAA back. Each picture is taken once the pipelines are compiled. Co-Authored-By: Claude Opus 5.5 --- crates/sandbox/tests/sandbox/first_person.rs | 65 ++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/crates/sandbox/tests/sandbox/first_person.rs b/crates/sandbox/tests/sandbox/first_person.rs index 1e19b22f..fc1522a2 100644 --- a/crates/sandbox/tests/sandbox/first_person.rs +++ b/crates/sandbox/tests/sandbox/first_person.rs @@ -317,3 +317,68 @@ fn a_mouse_move_turns_the_look_and_the_picture_in_its_frame_and_the_body_on_the_ } eprintln!("{table}"); } + +/// The camera content's SSAO drawn for real, through the first-person camera and its view model's camera: the picture +/// darkens where things meet, a prepass another module takes away comes back without a lost frame, and taking SSAO +/// out gives the cameras their MSAA back. Every capture must arrive: a camera whose prepasses, MSAA and SSAO disagree +/// is an error Bevy logs and draws nothing for, or a wgpu validation error that stops the drawing. +#[test] +#[ignore = "needs a GPU, or a software one (WGPU_FORCE_FALLBACK_ADAPTER=1): cargo test -p sandbox --test sandbox -- --ignored first_person"] +fn ssao_from_the_camera_content_draws_through_the_first_person_cameras_and_goes_again() { + use shards::bevy::core_pipeline::prepass::{DepthPrepass, NormalPrepass}; + use shards::bevy::pbr::ScreenSpaceAmbientOcclusion; + use shards::bevy::render::view::Msaa; + use shards::motion::camera::SsaoTuning; + + use crate::offscreen::{block, capture, mean_difference}; + + // A picture once the pipelines are compiled (a `shot` waits for them): a change of the camera's passes compiles new + // ones, and a frame drawn meanwhile leaves out what waits for them (a capture alike twice can still be one of those). + let drawn = |app: &mut App, picture: &Handle| { + shot_to(app, "ssao"); + capture_stable(app, picture) + }; + + let mut app = offscreen_app(); + let picture = app.world().resource::().image.clone(); + step(&mut app, 30); + look_down_through_the_eye(&mut app); + settle(&mut app, 200); + let plain = drawn(&mut app, &picture); + let world = app.world_mut(); + let camera = world.query_filtered::, With)>().single(world).unwrap(); + let view_model = world.query_filtered::>().single(world).unwrap(); + let msaa = |app: &App, e: Entity| app.world().get::(e).copied(); + let own = msaa(&app, camera); + + app.world_mut().resource_mut::().picture.ssao = Some(SsaoTuning::default()); + settle(&mut app, 30); + let occluded = drawn(&mut app, &picture); + let world = app.world(); + assert!(world.get::(camera).is_some() && world.get::(camera).is_some()); + assert_eq!((msaa(&app, camera), msaa(&app, view_model)), (Some(Msaa::Off), Some(Msaa::Off)), "both cameras without MSAA"); + assert!(world.get::(view_model).is_none(), "the arms have no SSAO of their own"); + let luma = |[r, g, b]: [f64; 3]| 0.2126 * r + 0.7152 * g + 0.0722 * b; + let (w, h) = (plain.width(), plain.height()); + let (before, after) = (luma(block(&plain, 0, 0, w, h)), luma(block(&occluded, 0, 0, w, h))); + let differ = mean_difference(&plain, &occluded); + eprintln!("SSAO in the sandbox's first person: luma {before:.2} -> {after:.2}, mean difference {differ:.3}"); + assert!(differ > 0.05 && after < before, "SSAO darkens the picture: luma {before:.2} -> {after:.2}, difference {differ:.3}"); + + // A module takes the depth prepass away (the decals do when they end): it is back the next frame, and the frames go on. + app.world_mut().entity_mut(camera).remove::(); + for _ in 0..5 { + capture(&mut app, picture.clone()); + } + assert!(app.world().get::(camera).is_some(), "the prepass SSAO needs is put back"); + let again = drawn(&mut app, &picture); + assert!(mean_difference(&occluded, &again) < 1.0, "and the picture is the occluded one: {:.3}", mean_difference(&occluded, &again)); + + // Out again: the cameras' own MSAA, no SSAO, the plain picture. + app.world_mut().resource_mut::().picture.ssao = None; + settle(&mut app, 30); + let back = drawn(&mut app, &picture); + assert!(app.world().get::(camera).is_none()); + assert_eq!((msaa(&app, camera), msaa(&app, view_model)), (own, own), "the MSAA the camera had, on both"); + assert!(mean_difference(&plain, &back) < 1.0, "the plain picture again: {:.3}", mean_difference(&plain, &back)); +} From 6d8faadc1e199b5263df1a23bfb160a18f6b0eb4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:58:17 +0100 Subject: [PATCH 6/7] Colour grading: say that only HDR draws more than a grade's exposure Bevy grades a camera that does not draw in HDR in each material's shader, where only the exposure is applied (WHITE_BALANCE, SECTIONAL_COLOR_GRADING and HUE_ROTATE exist only in the tone mapping pass's pipeline). A bloom puts the camera in HDR and draws the rest of a grade for the first time, so a grade tuned without HDR (a game's temperature 0.2, contrast 1.2) turned its picture black and red. Nothing draws differently: the docs now say which fields need HDR, the real scale of temperature and tint (an offset to the CIE white point) and the contrast pivot, and the lights query adds a drawn: line. Grading::hdr_only, grade_drawn_in_full, and an offscreen test that pins Bevy's behaviour. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 +++ crates/sandbox/tests/sandbox/first_person.rs | 57 +++++++++++++ crates/shards_light/src/tools.rs | 23 ++++-- crates/shards_light/tests/light/drawn.rs | 27 ++++++ crates/shards_motion/src/camera/grading.rs | 82 ++++++++++++++++--- crates/shards_motion/src/camera/mod.rs | 2 +- crates/shards_motion/src/camera/picture.rs | 3 +- .../ui-audio-look-fx-scatter-animation.md | 2 +- docs/manual.md | 13 ++- 9 files changed, 195 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bac90103..88e2c834 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -403,6 +403,16 @@ Changes that land in the main branch after phases C–E (`0.4.0`) go here. and the timing `field_timing` (`#[ignore]`) in `physics/world.rs`. ### Fixed +- Colour grading said every field of a grade is drawn; Bevy draws only a grade's `exposure` on a camera that does not draw + in HDR (it grades in each material's shader there), and the rest (`temperature`, `tint`, `hue_deg`, `saturation`, + `contrast`, `lift`, `gamma`, `gain`) only in HDR, in its tone mapping pass. A grade tuned without HDR therefore changed + when a `picture.bloom` put the camera in HDR: a game's tunnels went black with red in them. Nothing is drawn + differently; the docs (`Grading`, `PictureTuning::grading`, the manual's "Colour grading") say so now, give + `temperature` and `tint` their real scale (an offset to the CIE 1931 white point: 0.02 to 0.05 is a clear cast, the old + examples' 0.35 takes the white point off the diagram) and say that `contrast` pivots on 0.5 of the linear picture before + the exposure (a dark scene that the grade's exposure lifts goes black under a contrast above 1). The `lights` query's + grading lines add `drawn: all of it (the camera draws in HDR)` or `drawn: its exposure alone; ...` with the fields left + out; `Grading::hdr_only` and `shards_motion::camera::grade_drawn_in_full`. An offscreen test pins Bevy's behaviour. - A replay with a pause menu in it plays through (the manual's "Replays"). The menu takes effect after its frame's time is counted, so the session may run that frame's tick under it and record the calls made in the menu one tick after the call that opened it; played back, the opening call came inside a tick and paused the clock, which then never reached diff --git a/crates/sandbox/tests/sandbox/first_person.rs b/crates/sandbox/tests/sandbox/first_person.rs index fc1522a2..e89c351c 100644 --- a/crates/sandbox/tests/sandbox/first_person.rs +++ b/crates/sandbox/tests/sandbox/first_person.rs @@ -382,3 +382,60 @@ fn ssao_from_the_camera_content_draws_through_the_first_person_cameras_and_goes_ assert_eq!((msaa(&app, camera), msaa(&app, view_model)), (own, own), "the MSAA the camera had, on both"); assert!(mean_difference(&plain, &back) < 1.0, "the plain picture again: {:.3}", mean_difference(&plain, &back)); } + +/// How much of a grade Bevy draws: a camera in HDR is graded in the tone mapping pass, all of the grade; a camera that is +/// not is graded in each material's shader, where Bevy applies the exposure alone. So a white balance draws nothing until +/// a bloom puts the cameras in HDR, and an exposure draws the same either way; the `lights` query says which it is. (A +/// game tuned its grades without HDR, at a white balance far too strong, and its picture went black and red when it +/// turned a bloom on.) If Bevy starts to grade in full without HDR this fails, and the grading docs and the query's +/// `drawn:` line want changing. +#[test] +#[ignore = "needs a GPU, or a software one (WGPU_FORCE_FALLBACK_ADAPTER=1): cargo test -p sandbox --test sandbox -- --ignored first_person"] +fn a_grade_draws_its_exposure_alone_without_hdr_and_all_of_it_in_hdr() { + use shards::motion::camera::{BloomComposite, BloomTuning, Grading}; + + use crate::offscreen::block; + + let mut app = offscreen_app(); + let picture = app.world().resource::().image.clone(); + step(&mut app, 30); + look_down_through_the_eye(&mut app); + settle(&mut app, 200); + // The mean colour of the world above the arms, with this bloom and this grade (a `shot` first: it waits for the + // pipelines that a change to HDR compiles). + let world_with = |app: &mut App, name: &str, bloom: &Option, grade: Option<&Grading>| { + let mut tuning = app.world_mut().resource_mut::(); + (tuning.picture.bloom, tuning.picture.grading) = (bloom.clone(), grade.cloned()); + settle(app, 30); + shot_to(app, name); + let image = capture_stable(app, &picture); + block(&image, 0, 200, image.width(), 250) + }; + let drawn = |app: &mut App| { + let said = ok(app, "lights", json!({})).result; + said.as_str().unwrap().lines().find(|l| l.starts_with(" drawn:")).map(str::to_owned) + }; + let bloom = Some(BloomTuning { intensity: 0.1, threshold: 1.0, composite: BloomComposite::Additive, ..default() }); + let warm = Grading { temperature: 0.05, ..default() }; + let brighter = Grading { exposure: 1.7, ..default() }; + + let plain = world_with(&mut app, "grade-plain", &None, None); + let warm_ldr = world_with(&mut app, "grade-warm", &None, Some(&warm)); + let said_ldr = drawn(&mut app); + let brighter_ldr = world_with(&mut app, "grade-brighter", &None, Some(&brighter)); + let plain_hdr = world_with(&mut app, "grade-plain-hdr", &bloom, None); + let warm_hdr = world_with(&mut app, "grade-warm-hdr", &bloom, Some(&warm)); + let said_hdr = drawn(&mut app); + let brighter_hdr = world_with(&mut app, "grade-brighter-hdr", &bloom, Some(&brighter)); + eprintln!( + "the world's mean colour: plain {plain:.1?}, warm {warm_ldr:.1?}, brighter {brighter_ldr:.1?}; in HDR plain {plain_hdr:.1?}, warm {warm_hdr:.1?}, brighter {brighter_hdr:.1?}" + ); + let alike = |a: [f64; 3], b: [f64; 3]| (0..3).all(|c| (a[c] - b[c]).abs() < 1.5); + assert!(alike(plain, warm_ldr), "without HDR a white balance draws nothing: {plain:.1?} and {warm_ldr:.1?}"); + assert!(said_ldr.as_deref().is_some_and(|l| l.contains("its exposure alone") && l.contains("leaves out temperature")), "{said_ldr:?}"); + assert!(brighter_ldr[1] > plain[1] + 20.0, "an exposure is drawn without HDR: {plain:.1?} and {brighter_ldr:.1?}"); + assert!(alike(plain, plain_hdr), "this bloom leaves the world above the arms as it was: {plain:.1?} and {plain_hdr:.1?}"); + assert!(warm_hdr[0] > plain_hdr[0] + 8.0 && warm_hdr[2] < plain_hdr[2] - 3.0, "in HDR it warms the picture: {plain_hdr:.1?} and {warm_hdr:.1?}"); + assert_eq!(said_hdr.as_deref(), Some(" drawn: all of it (the camera draws in HDR)")); + assert!(alike(brighter_ldr, brighter_hdr), "and an exposure is drawn alike in both: {brighter_ldr:.1?} and {brighter_hdr:.1?}"); +} diff --git a/crates/shards_light/src/tools.rs b/crates/shards_light/src/tools.rs index 3c50bd7c..b616cf39 100644 --- a/crates/shards_light/src/tools.rs +++ b/crates/shards_light/src/tools.rs @@ -7,7 +7,7 @@ use schemars::JsonSchema; use serde::Deserialize; use shards_content::db::closest; use shards_content::ContentDb; -use shards_motion::camera::{picture_clock, CameraTuning, Grading, GradingBlend, GradingDef}; +use shards_motion::camera::{grade_drawn_in_full, picture_clock, CameraTuning, Grading, GradingBlend, GradingDef}; use shards_settings::FlashLevel; use crate::{update_state, Flicker, LightDef, LightInfo, LightState, ShadowBudget}; @@ -20,7 +20,8 @@ pub(crate) fn register(world: &mut World) { /// each is at this moment, who casts a shadow and why the others do not (against `graphics.shadow_lights`, or against /// `graphics.shadow_views` when it is set: a point light takes 6 views, a spot 1), and the grade the camera shows with the /// progress of its blend toward or away from a grading volume. Pictures only: it is the same headless, from the -/// simulation's clock. +/// simulation's clock, except for one line a drawn game adds when the grade has more than an exposure: how much of it +/// the world cameras draw (all of it in HDR, its exposure alone without). #[derive(Deserialize, JsonSchema, Default)] pub struct LightsArgs { /// Only the lights of this `light` definition (`id=sodium`). @@ -102,8 +103,9 @@ pub fn grade_text(grade: &Grading) -> String { if changed.is_empty() { "neutral".to_owned() } else { changed.join(", ") } } -/// The `grading:` lines: the grade the camera shows and where its blend is. -fn grading_lines(world: &World) -> Vec { +/// The `grading:` lines: the grade the camera shows, how much of it the cameras draw (`in_full`, +/// [`grade_drawn_in_full`]) and where its blend is. +fn grading_lines(world: &World, in_full: Option) -> Vec { let (Some(blend), Some(fixed)) = (world.get_resource::(), world.get_resource::>()) else { return vec!["grading: not in this game".to_owned()]; }; @@ -124,6 +126,16 @@ fn grading_lines(world: &World) -> Vec { None => " shows: no grade of the content (the camera keeps whatever the game gave it)".to_owned(), }; let mut out = vec![head, line]; + let hdr_only = shown.as_ref().map(Grading::hdr_only).unwrap_or_default(); + match in_full { + Some(false) if !hdr_only.is_empty() => out.push(format!( + " drawn: its exposure alone; the camera draws without HDR, where Bevy grades in each material's shader and leaves out {} \ + (a camera in HDR draws them: the picture's `bloom`, or the game's own `Hdr`)", + hdr_only.join(", ") + )), + Some(true) if !hdr_only.is_empty() => out.push(" drawn: all of it (the camera draws in HDR)".to_owned()), + _ => {} + } if base.is_some() { out.push(" the camera content's `picture.grading` is its own grade".to_owned()); } @@ -193,7 +205,8 @@ fn lights(In(call): In>, world: &mut World) -> ToolResult { if shown.len() > limit { out.push(format!(" … and {} more (limit={limit})", shown.len() - limit)); } - out.extend(grading_lines(world)); + let in_full = grade_drawn_in_full(world); + out.extend(grading_lines(world, in_full)); Ok(out.join("\n")) } diff --git a/crates/shards_light/tests/light/drawn.rs b/crates/shards_light/tests/light/drawn.rs index 5337aef8..3df33b8e 100644 --- a/crates/shards_light/tests/light/drawn.rs +++ b/crates/shards_light/tests/light/drawn.rs @@ -1,8 +1,10 @@ //! A game that draws (offscreen, with no GPU behind it): each content light gets a Bevy light on a child entity, driven //! every frame, and the game's own lights are left alone. +use shards::bevy::camera::{Camera3d, Hdr}; use shards::bevy::light::{PointLight, SpotLight}; use shards::light::{ContentLight, LightPicture}; +use shards::motion::camera::{CameraTuning, Grading, ThirdPersonCamera}; use shards::settings::GraphicsSettings; use crate::*; @@ -128,3 +130,28 @@ fn a_light_that_loses_its_content_light_or_its_definition_loses_its_picture_and_ let own_light = app.world().get::(own).unwrap(); assert_eq!((own_light.intensity, own_light.shadow_maps_enabled), (777.0, true), "the game's own light is its own"); } + +/// The `lights` query says how much of the grade the world camera draws: without HDR Bevy grades in each material's +/// shader and draws the exposure alone, in HDR all of it; a grade of nothing but an exposure needs no word. +#[test] +fn the_query_says_how_much_of_the_grade_the_camera_draws() { + let assets = Folder::new("drawn_grade"); + let mut app = drawn(&assets); + let camera = app.world_mut().spawn((Camera3d::default(), ThirdPersonCamera::default())).id(); + app.world_mut().resource_mut::().picture.grading = Some(Grading { exposure: 0.5, temperature: 0.03, contrast: 1.1, ..default() }); + app.update(); + let said = ok(&mut app, "lights", json!({})); + assert!(said.contains("shows: exposure 0.500, temperature 0.030, contrast 1.100"), "{said}"); + assert!( + said.contains(" drawn: its exposure alone; the camera draws without HDR, where Bevy grades in each material's shader and leaves out temperature, contrast"), + "{said}" + ); + app.world_mut().entity_mut(camera).insert(Hdr); + let said = ok(&mut app, "lights", json!({})); + assert!(said.contains(" drawn: all of it (the camera draws in HDR)"), "{said}"); + app.world_mut().resource_mut::().picture.grading = Some(Grading { exposure: 0.5, ..default() }); + app.world_mut().entity_mut(camera).remove::(); + app.update(); + let said = ok(&mut app, "lights", json!({})); + assert!(said.contains("shows: exposure 0.500") && !said.contains("drawn:"), "every camera draws an exposure: {said}"); +} diff --git a/crates/shards_motion/src/camera/grading.rs b/crates/shards_motion/src/camera/grading.rs index 45c66cf0..378b57a4 100644 --- a/crates/shards_motion/src/camera/grading.rs +++ b/crates/shards_motion/src/camera/grading.rs @@ -14,8 +14,20 @@ //! - Picture only: nothing here is in a snapshot or a replay. The volume is read, never written; the //! tracking runs in `FixedLast` so it sees each tick's volumes exactly, whatever the frame rate. //! -//! Bevy applies a grade just before tone mapping, so a camera whose tone mapping is `None` shows -//! none of it (the picture's `tone_mapping` doc says so). A game's own `ColorGrading` on a camera is +//! **How much of a grade is drawn depends on the camera.** A camera that draws in HDR (the picture's `bloom`, or +//! the game's own `Hdr`) is graded by Bevy's tone mapping pass, which draws all of the grade. A camera that does not +//! draw in HDR is graded in each material's shader, and Bevy applies only the `exposure` there: `temperature`, +//! `tint`, `hue_deg`, `saturation`, `contrast`, `lift`, `gamma` and `gain` are left out ([`Grading::hdr_only`] +//! names them). Turning a bloom on therefore draws the rest of a grade for the first time, and a grade tuned without +//! HDR can look nothing like it did. The `lights` query says which it is (`drawn:`). A camera whose tone mapping is +//! `None` shows none of a grade (the picture's `tone_mapping` doc says so). +//! +//! In HDR Bevy grades in this order: the white balance, then saturation and contrast, then lift, gamma and gain, +//! and the `exposure` last. Contrast pivots on 0.5 of the linear picture before the exposure, so a dark scene that the +//! grade's exposure lifts loses its darks below zero: with `contrast` above 1 it goes black. Such a scene keeps +//! `contrast` at 1, or is lit (or exposed by the camera's `Exposure`) instead. +//! +//! A game's own `ColorGrading` on a camera is //! kept while the content says nothing and put back when the content stops saying anything; a blend //! starts from the camera's content grading (or the neutral one), not from the game's own. @@ -28,10 +40,11 @@ use shards_core::LocalPlayer; use super::CameraTuning; use crate::controller::MotionState; -/// A grade of the picture. The neutral grade (the default) changes nothing. +/// A grade of the picture. The neutral grade (the default) changes nothing. Every field but `exposure` is drawn only +/// by a camera in HDR (the module says why). /// /// ```ron -/// (temperature: 0.35, saturation: 0.7, contrast: 1.1) +/// (temperature: 0.03, saturation: 0.8, contrast: 1.1) /// ``` #[derive(Reflect, Serialize, Deserialize, Clone, Debug, PartialEq)] #[reflect(Default)] @@ -39,21 +52,26 @@ use crate::controller::MotionState; pub struct Grading { /// Exposure in stops (EV): 1 is twice the light. `-10` to `10`. pub exposure: f32, - /// White balance toward red (positive) or blue (negative), Bevy's units: `-1` to `1`, no change in brightness. + /// White balance toward red (positive) or blue (negative), no change in brightness. Bevy's units: what is taken + /// from the *x* of the white point in CIE 1931 (D65's is 0.3127), so small numbers are strong: 0.02 to 0.05 is a + /// clear warm or cool cast, and near 0.3 the white point leaves the colour diagram (the picture loses its green and + /// blue). The check allows `-1` to `1`. HDR only. pub temperature: f32, - /// White balance toward magenta (positive) or green (negative): `-1` to `1`. + /// White balance toward magenta (positive) or green (negative): what is added to the *y* of the white point (D65's + /// is 0.3290); 0.01 to 0.03 is a clear cast. The check allows `-1` to `1`. HDR only. pub tint: f32, - /// Turns every hue round the colour wheel, degrees: `-180` to `180`. + /// Turns every hue round the colour wheel, degrees: `-180` to `180`. HDR only. pub hue_deg: f32, - /// 1 as drawn, 0 grey, above 1 stronger colours: `0` to `4`. + /// 1 as drawn, 0 grey, above 1 stronger colours: `0` to `4`. HDR only. pub saturation: f32, - /// 1 as drawn, below 1 toward grey, above 1 away from it: `0` to `4`. + /// 1 as drawn, below 1 toward grey, above 1 away from it: `0` to `4`. It pivots on 0.5 of the linear picture, + /// before the `exposure`: above 1 it blackens a dark scene that the exposure lifts. HDR only. pub contrast: f32, - /// A fixed lift of the dark end (the offset of the ASC CDL): `-1` to `1`, 0 none. + /// A fixed lift of the dark end (the offset of the ASC CDL): `-1` to `1`, 0 none. HDR only. pub lift: f32, - /// The curve of the light (the power of the ASC CDL): `0.05` to `4`, 1 none. + /// The curve of the light (the power of the ASC CDL): `0.05` to `4`, 1 none. HDR only. pub gamma: f32, - /// A multiplier of the light (the slope of the ASC CDL): `0` to `8`, 1 none. + /// A multiplier of the light (the slope of the ASC CDL): `0` to `8`, 1 none. HDR only. pub gain: f32, } @@ -88,6 +106,17 @@ impl Grading { .collect() } + /// The fields of this grade that only a camera drawing in HDR shows (every one but `exposure` that is not + /// neutral), by name. Without HDR, Bevy grades in each material's shader and applies the exposure alone. + pub fn hdr_only(&self) -> Vec<&'static str> { + self.fields() + .into_iter() + .zip(Self::default().fields()) + .filter(|((name, value, ..), (_, neutral, ..))| *name != "exposure" && value != neutral) + .map(|((name, ..), _)| name) + .collect() + } + /// Whether this grade changes nothing. pub fn is_neutral(&self) -> bool { *self == Self::default() @@ -117,7 +146,7 @@ pub const MAX_BLEND_S: f32 = 60.0; /// ids to definitions). /// /// ```ron -/// { "rust": (blend_s: 1.5, grading: (temperature: 0.35, saturation: 0.7)) } +/// { "rust": (blend_s: 1.5, grading: (temperature: 0.03, saturation: 0.7)) } /// ``` #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[serde(default, deny_unknown_fields)] @@ -296,6 +325,25 @@ pub(super) fn plugin(app: &mut App) { app.add_systems(Update, render::apply_grading); } +/// Whether the world cameras (3D, with a [`ThirdPersonCamera`](super::ThirdPersonCamera) or a +/// [`FirstPersonCamera`](super::FirstPersonCamera)) draw a grade in full: `Some(true)` when every one draws in HDR, +/// `Some(false)` when one does not (it draws only the grade's `exposure`, [`Grading::hdr_only`]), `None` without such +/// a camera or without the picture (a headless build). +pub fn grade_drawn_in_full(world: &mut World) -> Option { + #[cfg(feature = "render")] + { + use bevy::camera::{Camera3d, Hdr}; + let mut cameras = + world.query_filtered::, (With, Or<(With, With)>)>(); + cameras.iter(world).fold(None, |all, hdr| Some(all.unwrap_or(true) && hdr)) + } + #[cfg(not(feature = "render"))] + { + let _ = world; + None + } +} + #[cfg(feature = "render")] mod render { use bevy::camera::Camera3d; @@ -513,6 +561,14 @@ mod tests { assert!(ron::from_str::("(blend: 1.0)").is_err(), "an unknown field is an error"); } + #[test] + fn every_field_but_the_exposure_is_drawn_only_in_hdr() { + assert!(Grading::default().hdr_only().is_empty()); + assert!(Grading { exposure: 1.7, ..default() }.hdr_only().is_empty(), "an exposure is drawn by every camera"); + let grade = Grading { exposure: 1.7, temperature: 0.03, contrast: 1.2, gain: 1.1, ..default() }; + assert_eq!(grade.hdr_only(), ["temperature", "contrast", "gain"]); + } + #[test] fn a_blend_eases_between_the_grades_on_the_clock_and_a_cut_is_instant() { let mut blend = GradingBlend::default(); diff --git a/crates/shards_motion/src/camera/mod.rs b/crates/shards_motion/src/camera/mod.rs index ad662a7c..4de451bc 100644 --- a/crates/shards_motion/src/camera/mod.rs +++ b/crates/shards_motion/src/camera/mod.rs @@ -50,7 +50,7 @@ pub use first_person::{ heading_of, look_through, turn_look, view_rotation, BobTuning, CameraMode, EyeFrame, EyeShift, EyeState, FirstPersonCamera, FirstPersonTuning, FromMode, LandingTuning, RollTuning, OWN_BODY_LAYER, VIEW_MODEL_LAYER, }; -pub use grading::{picture_clock, Grading, GradingBlend, GradingDef, GradingVolume}; +pub use grading::{grade_drawn_in_full, picture_clock, Grading, GradingBlend, GradingDef, GradingVolume}; #[cfg(feature = "render")] pub use grading::GradingSet; pub use picture::{BloomComposite, BloomTuning, PictureTuning, SsaoQuality, SsaoTuning, ToneMapping}; diff --git a/crates/shards_motion/src/camera/picture.rs b/crates/shards_motion/src/camera/picture.rs index c5ae08c5..127e163e 100644 --- a/crates/shards_motion/src/camera/picture.rs +++ b/crates/shards_motion/src/camera/picture.rs @@ -149,7 +149,8 @@ pub struct PictureTuning { pub bloom: Option, /// A colour grade of the whole picture (F13, [`Grading`]); `None` keeps the camera's own. A trigger volume with a /// `grading` blends the picture away from it and back (`GradingVolume`). Bevy grades just before tone mapping, so a - /// camera whose `tone_mapping` is `None` shows none of it. + /// camera whose `tone_mapping` is `None` shows none of it, and a camera that does not draw in HDR shows only its + /// `exposure`: the rest of a grade is drawn once a `bloom` (or the game's `Hdr`) puts the camera in HDR. #[serde(skip_serializing_if = "Option::is_none")] pub grading: Option, /// Screen-space ambient occlusion ([`SsaoTuning`]); `None` keeps the camera's own (none, unless the game gave it diff --git a/docs/agents/ui-audio-look-fx-scatter-animation.md b/docs/agents/ui-audio-look-fx-scatter-animation.md index 35f09c1e..8919e011 100644 --- a/docs/agents/ui-audio-look-fx-scatter-animation.md +++ b/docs/agents/ui-audio-look-fx-scatter-animation.md @@ -57,7 +57,7 @@ Read this when you touch screens and menus, sound and music, mesh looks, particl - **The shadow budget** (`graphics.shadow_lights`, `GraphicsSettings::shadow_light_budget`) is `budget::casters`, a pure function of the lights' distances to the viewer (the `AiCamera`, else a `ThirdPersonCamera` or `FirstPersonCamera`, else the local player's eye; with none of them there is no viewer: `lights` says so, every distance is unknown and ties go by the key alone), ties by a stable key (definition id, name, place), never by `Entity`. Only content lights that ask (`shadows: true`) take part. `graphics.shadow_views` above 0 makes it a budget in views (`ShadowBudget::Views`: a point light 6, a spot 1, each light taken while its views fit, a farther one may still fit); at 0 it is the light count, byte for byte the old texts. - **Ambient occlusion is the camera's picture** (`picture.ssao`, `SsaoTuning`): `apply_picture` adds `DepthPrepass`/`NormalPrepass` the camera lacks, sets `Msaa::Off` (Bevy's SSAO draws nothing under MSAA) and remembers what the camera had in `PictureSet`, so taking it out gives back the camera's own SSAO, MSAA and prepasses; it re-applies when another module takes a prepass away (the fx decals remove theirs). The view model's camera copies the world camera's `Msaa` and never gets SSAO. Bevy does not apply SSAO to a lightmap's light. - **Baked light is the level's picture** (`shards_level::baked`, kind `baked_light`, `SIMULATION = false`): node properties name the files, the definition (keyed by the level's id) names the folders of the sets; `draw_baked` puts `Lightmap`/`LightProbe`/`IrradianceVolume`/`EnvironmentMapLight` on the drawn level and `keep_exposure` keeps `lightmap_exposure` on whatever `StandardMaterial` the mesh has. `BakedLight` (the chosen set per level) is a resource of the picture, in `state_audit`'s `OUTSIDE`; a game sets it from its own saved state. A `LightDef` with `baked: true` lights no lightmapped mesh's diffuse. A `Toon` look ignores lightmaps and probes. -- **Colour grading is the camera's picture** (`picture.grading`, `shards_motion::camera::grading`): a `Grading` (exposure, white balance `temperature`/`tint`, `hue_deg`, `saturation`, `contrast`, `lift`/`gamma`/`gain`) becomes Bevy's `ColorGrading` on the world cameras; Bevy grades before tone mapping, so `tone_mapping: None` shows none of it. A `GradingVolume { id }` on a trigger volume (a level node's `grading=` with `marker = trigger`) blends the picture toward the `grading` definition while the local player's body touches it (`MotionState::volumes`; the last in collider id order wins), over its `blend_s`, and back to the camera's own. `GradingBlend` is a resource of the picture, tracked in `FixedLast` (exact ticks, `step` included) and applied in `Update`; it is in no snapshot or replay. Add a camera kind the picture reaches to `apply_grading` (the same cameras as `apply_picture`) and copy its `ColorGrading` to any second camera that draws the world. +- **Colour grading is the camera's picture** (`picture.grading`, `shards_motion::camera::grading`): a `Grading` (exposure, white balance `temperature`/`tint`, `hue_deg`, `saturation`, `contrast`, `lift`/`gamma`/`gain`) becomes Bevy's `ColorGrading` on the world cameras; Bevy grades before tone mapping, so `tone_mapping: None` shows none of it, and a camera that does not draw in HDR shows only the `exposure` (Bevy grades it in each material's shader, without the white balance and the sections): the rest appears when a bloom puts the camera in HDR (`Grading::hdr_only`, `grade_drawn_in_full`, the `lights` query's `drawn:` line). `temperature`/`tint` are offsets to the CIE white point: 0.02 to 0.05 is already a strong cast. A `GradingVolume { id }` on a trigger volume (a level node's `grading=` with `marker = trigger`) blends the picture toward the `grading` definition while the local player's body touches it (`MotionState::volumes`; the last in collider id order wins), over its `blend_s`, and back to the camera's own. `GradingBlend` is a resource of the picture, tracked in `FixedLast` (exact ticks, `step` included) and applied in `Update`; it is in no snapshot or replay. Add a camera kind the picture reaches to `apply_grading` (the same cameras as `apply_picture`) and copy its `ColorGrading` to any second camera that draws the world. - **Check it** with the `lights` query (counts, flicker now, who casts a shadow and why not, the grade and its blend), headless (`lights.scenario`) and offscreen (`sandbox/tests/sandbox/lights.rs`: a flashing lamp at two moments, a grading volume's channel means). ## Animation diff --git a/docs/manual.md b/docs/manual.md index 24adb56c..d3af8516 100644 --- a/docs/manual.md +++ b/docs/manual.md @@ -1114,7 +1114,7 @@ For the AI: `observe` shows `slowed x0.60, rooted, capped 3.0m/s, no sprint, spr | `picture.bloom.composite` | `EnergyConserving` | `EnergyConserving`: the glow takes its share of the light from the picture (Bevy's natural bloom); `Additive`: it is added on top | | `picture.ssao` | `None`: the camera's own (none) | screen-space ambient occlusion: the light that comes from no one direction (an ambient light, an irradiance volume, a reflection probe) darkens in creases and where things meet. It turns the camera's MSAA off while it is set and adds a depth and a normal prepass (the picture, below) | | `picture.ssao.quality` / `radius` / `thickness` | `High` / `0.7285` / `0.25` | Bevy's `ScreenSpaceAmbientOcclusion`: `Low` (4 samples a pixel), `Medium` (8), `High` (18) or `Ultra` (54); how far round a pixel occluders are looked for (m, above 0); how thick everything on screen is taken to be (m, above 0) | -| `picture.grading` | `None`: the camera's own | a colour grade of the whole picture: `exposure` (stops), `temperature` and `tint` (white balance, `-1` to `1`), `hue_deg`, `saturation`, `contrast`, `lift`, `gamma` and `gain` (the neutral values: 0, 0, 0, 0, 1, 1, 0, 1, 1); Bevy's `ColorGrading` with the same values for shadows, midtones and highlights. Bevy grades just before tone mapping, so it shows nothing under `tone_mapping: None`. A grading volume blends the picture away from it and back (the picture, below; "Lights and colour grading (F13)") | +| `picture.grading` | `None`: the camera's own | a colour grade of the whole picture: `exposure` (stops), `temperature` and `tint` (white balance, `-1` to `1`), `hue_deg`, `saturation`, `contrast`, `lift`, `gamma` and `gain` (the neutral values: 0, 0, 0, 0, 1, 1, 0, 1, 1); Bevy's `ColorGrading` with the same values for shadows, midtones and highlights. Bevy grades just before tone mapping, so it shows nothing under `tone_mapping: None`, and **a camera that does not draw in HDR shows only the `exposure`**: the rest is drawn once a `bloom` (or the game's `Hdr`) puts the camera in HDR ("Lights and colour grading (F13)", "Colour grading"). A grading volume blends the picture away from it and back (the picture, below; "Lights and colour grading (F13)") | | `mode` | `ThirdPerson` | the camera the game plays through: `FirstPerson` puts a `FirstPersonCamera` on every `ThirdPersonCamera` entity (F1b, "The first-person camera and the view model") | | `first_person.*` | see the table in "The first-person camera and the view model (F1b)" | the first-person camera's own numbers: the ease on steps, the landing dip, the bob, the lean, the default view model; read by `FirstPersonCamera` only | @@ -7162,11 +7162,18 @@ The content check names the file, the definition and the field: `intensity` 0 or **A budget in shadow views.** Each shadow view is a pass the render thread prepares and the GPU draws: a point light's cube is six, a spot's one. `graphics.shadow_views` (default 0, 0 to 384, `settings_set group=graphics key=shadow_views value=12`) counts the budget in views instead of lights: above 0 it replaces `shadow_lights`, and `shadows = "off"` is still none. The lights that ask go nearest first, each taking its views while they fit in what is left; one that does not fit has no shadow, and a farther light that does fit has one, so twelve views shadow twelve spots, or two points, or one point and the six nearest spots. The `lights` query then reads `budget 12 views, 8 taken: graphics.shadow_views`, and a light that missed out says why: `shadow: no (over the budget: it takes 6 views, 2 of 12 left after the nearer lights)`; `ai/status` adds `budget_views: true` and `views_used`. A game whose lamps are mostly spots aimed at what they light gets many more shadows for the same cost this way, and every shadowed lamp is one that does not light through a wall. -**Colour grading.** `picture.grading` of the `camera` content is a `Grading`: `exposure` (stops), `temperature` and `tint` (white balance: positive is redder or more magenta), `hue_deg`, `saturation`, `contrast`, `lift`, `gamma`, `gain` (the offset, power and slope of the ASC CDL). It becomes Bevy's `ColorGrading` on every 3D camera with a `ThirdPersonCamera` or a `FirstPersonCamera` (the same cameras as the rest of the picture), the same values for the shadows, the midtones and the highlights; Bevy grades just before tone mapping, so a camera whose `tone_mapping` is `None` shows none of it. Per-channel lift/gamma/gain wheels and a LUT are not in Bevy's built-in path (its sections are scalar, its LUT is the tone mapper's), so they are not here: `temperature` and `tint` are the colour casts. A camera keeps its own `ColorGrading` (a game's) while the content says nothing, and gets it back when the content stops saying anything. +**Colour grading.** `picture.grading` of the `camera` content is a `Grading`: `exposure` (stops), `temperature` and `tint` (white balance: positive is redder or more magenta, in Bevy's units, below), `hue_deg`, `saturation`, `contrast`, `lift`, `gamma`, `gain` (the offset, power and slope of the ASC CDL). It becomes Bevy's `ColorGrading` on every 3D camera with a `ThirdPersonCamera` or a `FirstPersonCamera` (the same cameras as the rest of the picture), the same values for the shadows, the midtones and the highlights; Bevy grades just before tone mapping, so a camera whose `tone_mapping` is `None` shows none of it. Per-channel lift/gamma/gain wheels and a LUT are not in Bevy's built-in path (its sections are scalar, its LUT is the tone mapper's), so they are not here: `temperature` and `tint` are the colour casts. A camera keeps its own `ColorGrading` (a game's) while the content says nothing, and gets it back when the content stops saying anything. + +**How much of a grade is drawn depends on the camera.** A camera that draws in HDR (a `picture.bloom`, or the game's own `Hdr`) is graded in Bevy's tone mapping pass, which draws the whole grade. A camera that does not is graded in each material's shader, where Bevy applies the `exposure` alone: `temperature`, `tint`, `hue_deg`, `saturation`, `contrast`, `lift`, `gamma` and `gain` are left out. So turning a bloom on draws the rest of a grade for the first time, and a grade tuned without HDR can look nothing like it did: a game whose grades had a `temperature` of 0.2 and a `contrast` of 1.2 saw its tunnels go black with red in them when it turned a bloom on. The `lights` query says which it is under the grade (`drawn: its exposure alone; ... leaves out temperature, contrast`, or `drawn: all of it`), and a grade of nothing but an exposure draws the same either way. Two things to know when tuning in HDR: + +- `temperature` and `tint` are Bevy's: what is taken from the *x* of the white point and added to its *y* in CIE 1931 (D65 is (0.3127, 0.3290)). Small numbers are strong: a `temperature` of 0.02 to 0.05 is a clear warm or cool cast and a `tint` of 0.01 to 0.03 a clear magenta or green one; near 0.3 the white point leaves the colour diagram and the picture loses its green and blue. The content check allows -1 to 1. +- Bevy grades in this order: the white balance, saturation and contrast, lift, gamma and gain, and the `exposure` last. `contrast` pivots on 0.5 of the linear picture before the exposure, so in a dark scene that the grade's exposure lifts, a `contrast` above 1 sends the darks below zero and the picture goes black. Keep such a grade's `contrast` at 1, or light the scene (or expose the camera, Bevy's `Exposure`) instead of the grade. + +A first-person view model is drawn by a second camera over the world ("The first-person camera and the view model (F1b)"). Without HDR it takes the world camera's grade (its exposure); in HDR it is drawn over the finished picture with no tone mapping and no grade, so a grade's exposure brightens the world and not the arms. A **grading volume** changes it where the player stands. A level node with `marker = "trigger"` (a collider shapes it, `auto` by default) and `grading = "rust"`, or a prefab with `"GradingVolume": (id: "rust")` on an entity with a trigger `Volume`: while the local player's body touches it (`MotionState::volumes`), the picture blends from what it shows toward the `rust` definition over its `blend_s` (eased, smoothstep), holds it, and blends back to the camera's own grade over the same time when the player leaves; a game with no local player uses the volumes the camera stands in. Where volumes overlap, the one placed last (the highest collider id) wins; a blend that changes course starts from what is shown, so nothing jumps. The state is the resource `GradingBlend`, tracked in `FixedLast` on every tick (so a `step` of 100 ticks sees the tick the player crossed the line) and evaluated on the simulation's clock, which is why a headless game can say where the blend is. It is in no snapshot or replay. -**For the AI.** The query `lights` (player scope, the same headless and drawn): the lights by kind, how many flicker, how many want a shadow and cast one against the budget, the viewer the budget measures from, and a line per light: its definition, name, place, distance, lumens now against its definition's, the flicker (pattern step and letter, or noise, with the percentage now) and `shadow: yes`, `no (over the budget)`, `no (budget 0)` or `not asked`; then the grade the picture shows and where its blend is (the line reads "blending toward `rust`, 62 % done", "holding `rust` (blend done)", "blending back to the camera's own, 30 % done" or "the camera's own"). `lights id=sodium` lists one definition, `limit=` the first lights (24). `ai/status` has `light: {lights, casting, flickering, budget}` (and `budget_views`, `views_used` under `graphics.shadow_views`). The tool refreshes the state first, as a frame does, so a stepped game answers for now. +**For the AI.** The query `lights` (player scope, the same headless and drawn): the lights by kind, how many flicker, how many want a shadow and cast one against the budget, the viewer the budget measures from, and a line per light: its definition, name, place, distance, lumens now against its definition's, the flicker (pattern step and letter, or noise, with the percentage now) and `shadow: yes`, `no (over the budget)`, `no (budget 0)` or `not asked`; then the grade the picture shows and where its blend is (the line reads "blending toward `rust`, 62 % done", "holding `rust` (blend done)", "blending back to the camera's own, 30 % done" or "the camera's own"), and, in a drawn game with a grade that has more than an exposure, how much of it the world cameras draw (`drawn: all of it (the camera draws in HDR)`, or `drawn: its exposure alone; ...` with the fields left out). `lights id=sodium` lists one definition, `limit=` the first lights (24). `ai/status` has `light: {lights, casting, flickering, budget}` (and `budget_views`, `views_used` under `graphics.shadow_views`). The tool refreshes the state first, as a frame does, so a stepped game answers for now. ```text $ shards act lights From 73170a9c56b815c00c002889c62693016f02603d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:06:45 +0100 Subject: [PATCH 7/7] Grading: hdr_only at the query's tolerance; docs and test counts Grading::hdr_only takes a field within 0.0005 of neutral as neutral, as the lights query prints it, so the end of a blend never says "leaves out" beside "shows: neutral". The tint's scale is stated as Bevy's formula gives it, not as a measured range. engine-progress counts the shards_light tests (9 and 19) and names the new ones; the agents' cookbook has the drawn: line. Co-Authored-By: Claude Opus 5.5 --- crates/shards_motion/src/camera/grading.rs | 10 ++++++---- docs/agents/watching-and-driving.md | 2 +- docs/engine-progress.md | 2 +- docs/manual.md | 2 +- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/shards_motion/src/camera/grading.rs b/crates/shards_motion/src/camera/grading.rs index 378b57a4..d578f350 100644 --- a/crates/shards_motion/src/camera/grading.rs +++ b/crates/shards_motion/src/camera/grading.rs @@ -58,7 +58,7 @@ pub struct Grading { /// blue). The check allows `-1` to `1`. HDR only. pub temperature: f32, /// White balance toward magenta (positive) or green (negative): what is added to the *y* of the white point (D65's - /// is 0.3290); 0.01 to 0.03 is a clear cast. The check allows `-1` to `1`. HDR only. + /// is 0.3290), so small numbers are strong here too. The check allows `-1` to `1`. HDR only. pub tint: f32, /// Turns every hue round the colour wheel, degrees: `-180` to `180`. HDR only. pub hue_deg: f32, @@ -106,13 +106,14 @@ impl Grading { .collect() } - /// The fields of this grade that only a camera drawing in HDR shows (every one but `exposure` that is not - /// neutral), by name. Without HDR, Bevy grades in each material's shader and applies the exposure alone. + /// The fields of this grade that only a camera drawing in HDR shows (every one but `exposure` that is more than + /// 0.0005 from neutral, as the `lights` query prints them), by name. Without HDR, Bevy grades in each material's + /// shader and applies the exposure alone. pub fn hdr_only(&self) -> Vec<&'static str> { self.fields() .into_iter() .zip(Self::default().fields()) - .filter(|((name, value, ..), (_, neutral, ..))| *name != "exposure" && value != neutral) + .filter(|((name, value, ..), (_, neutral, ..))| *name != "exposure" && (value - neutral).abs() > 0.0005) .map(|((name, ..), _)| name) .collect() } @@ -567,6 +568,7 @@ mod tests { assert!(Grading { exposure: 1.7, ..default() }.hdr_only().is_empty(), "an exposure is drawn by every camera"); let grade = Grading { exposure: 1.7, temperature: 0.03, contrast: 1.2, gain: 1.1, ..default() }; assert_eq!(grade.hdr_only(), ["temperature", "contrast", "gain"]); + assert!(Grading { saturation: 1.0001, ..default() }.hdr_only().is_empty(), "the end of a blend is neutral, as the query prints it"); } #[test] diff --git a/docs/agents/watching-and-driving.md b/docs/agents/watching-and-driving.md index 1b0c715a..70cd4bae 100644 --- a/docs/agents/watching-and-driving.md +++ b/docs/agents/watching-and-driving.md @@ -76,7 +76,7 @@ cargo run -p sandbox --release -- --perf reference --offscreen # performance t `*.look.ron`, how many meshes each one draws; without a window and `--offscreen` nothing is styled, and it says so), `look_outlines on=false` (hide the outlines); **camera** — `camera_mode mode=first|third|content` (look through the first-person camera, or back through the orbit one, for this session: F1b; a window or `--offscreen` shows it; a headless game only stores the choice for the session, and a replay does not restore it); **foliage** — `scatter` (`*.scatter.ron` definitions, how many of each were scattered and what found no room; without a window and `--offscreen` nothing is scattered, and it says so), `scatter_set on=false` - (remove; `on=true` — scatter again), density — `settings_set group=graphics key=foliage value=0.5`; **lights** — `lights` (the lights from `*.light.ron` placed in the world: kind counts, which flicker and how bright each is now, which cast a shadow against `graphics.shadow_lights` and why the others do not, the picture's colour grade and its blend toward a grading volume; `id=`, `limit=`; the same headless and drawn), budget — `settings_set group=graphics key=shadow_lights value=2` (or in views: `key=shadow_views value=12`, a point light 6, a spot 1); **baked light** — `baked_light` (each level's set of lightmaps and probes, who chose it, what is drawn and which images are loading or failed; `level=`), `baked_light_set level= set=` (dev: switch, without `set` back to the definition's); **effects** — + (remove; `on=true` — scatter again), density — `settings_set group=graphics key=foliage value=0.5`; **lights** — `lights` (the lights from `*.light.ron` placed in the world: kind counts, which flicker and how bright each is now, which cast a shadow against `graphics.shadow_lights` and why the others do not, the picture's colour grade and its blend toward a grading volume, and in a drawn game how much of the grade the cameras draw: `drawn: all of it` in HDR, `drawn: its exposure alone` without; `id=`, `limit=`; the same headless and drawn but that line), budget — `settings_set group=graphics key=shadow_lights value=2` (or in views: `key=shadow_views value=12`, a point light 6, a spot 1); **baked light** — `baked_light` (each level's set of lightmaps and probes, who chose it, what is drawn and which images are loading or failed; `level=`), `baked_light_set level= set=` (dev: switch, without `set` back to the definition's); **effects** — `effects` (effects from `*.effect.ron`, their pools, the event table and links, the marks alive per kind, the debris at rest and the rays it cast, and the telegraph decals on the ground), `mark_spawn mark=bullet_hole point=[x,y,z] normal=[x,y,z]` (or `from=[x,y,z] toward=[x,y,z]`: a mark where a ray finds a surface), `fx_clear tag=gore` (or `all=true`), `effect_play effect=hit_spark at=eN` (or `point=[x,y,z]`), `telegraph_decals on=false` (the telegraph fill becomes gizmos again); without a window and `--offscreen` effects do not play, and the tools say so; **hit stop** — `hitstop` (how this machine holds, the settings, the table, what is held now, the totals and the ticks that ran inside a clock hold, which must be 0, the last holds), `hitstop_play event=damaged weight=Break attacker=e5 target=e6` (a hold as a blow would make; `seconds=0.08` skips the table); headless and stepped games never hold, and the tools say why: the hold is for a window or `--offscreen` in real time (not `--paused`); **rules** — `rules` (the rule set in play, its factors by class with the session's, the modes, whether a change is allowed now; `mode=gentle` describes another, and `playing` still names the one in play), `rules_set mode=harsh` or `cycle=1` (the host only, out of combat: `step --until named:rules_changeable`; `force=true` from a dev session), a game without `rules/default` has none and says so; **Steam** (a game with the `steam` feature) — `steam` (who this machine is in Steam, the lobby and diff --git a/docs/engine-progress.md b/docs/engine-progress.md index 698855e1..15fb0277 100644 --- a/docs/engine-progress.md +++ b/docs/engine-progress.md @@ -488,7 +488,7 @@ under `nohup` SIGHUP is ignored, and the test `kill_and_hangup_remove_the_token_ | `shards_scatter` | 26 | `src/` (15: a voxel field near the tile is ground 1, the definition and each of its errors, `spacing` not less than a centimetre, the outline through `extends`, the limit of entities per tile; meshes; the layout — seed, `spacing`, `graphics.foliage`, the ground and the band of heights, free space above a slope and by walls, only static colliders near the tile, the limit for a tiny `spacing`) and `tests/scatter/` (11: without a picture, tiles and repeats, walls and slope, only static colliders, batches and `VisibilityRange`, `foliage`, `scatter_set`, an edit of the content and the tile's tags, a definition that is too dense, a region change; one more `#[ignore]` — the picture on the GPU); a run on 16 October 2026 on Windows | | `shards_fx` | 69 (F9 +30, 39 counted with `-- --list` before it; D1.7 +1) | `src/` (13: the effect's description, typos in numbers, with no overflow and within the limits, flight by a formula versus steps, a cone and a sphere, the hit axis, the pool and evicting the oldest, decal shapes and the growth of the fill, bands from the zone rather than from the world's origin, colour packing, the shard mesh) and `tests/fx/` (16, D1.7 +1: content checks, an effect with an error plays within the check's limits, tools, the menu and the status without a picture, pools from the content, start, the simulation clock, `rate`, event effects on the side of the hit, labels and `PlayEffect`, a cue at a bone and its strength (the point, fewer and smaller particles, what a `rate` emits later), decals of a circle and a sector, the ally's colour, turning decals off and `DepthPrepass`); 1 under `#[ignore]`: the picture on the GPU — a decal in the zone and particles in pixels; a run on 16 October 2026 on Windows, together with foliage; F9: `src/` +14 (`debris.rs` 7: bounces, tunnelling, friction, walls and ceilings, an edge, late frames, the shown pose; `mark.rs` 5; `marks_render.rs` 2) and `tests/fx/` +16 (`gore.rs` 12, `content.rs` +1, `offscreen_gore.rs` 3 under `#[ignore]` for a GPU: marks on a wall, a floor and a ceiling and kept off a pillar, chunks of a mesh with no UVs on the floor, a quad that wears a picture), counted with `-- --list` on 24 October 2026 on Windows | | `shards_hitstop` | 27 | `src/` (7: a rule for the local player's blows only, the rules in order — the first match gives the hold, ceiling and bad numbers, a rule the ones before it cover, typos refused) and `tests/hitstop/` (20: the solo rule — a machine outside co-op takes it and a host or client passes it over, and the play tool names a rule held to solo play; the content check, the ladder for every event, a swing that lands — headless and nothing held, the tools and their errors, no table, the player's scale and local filter; alone in real time — no tick inside a hold, the speed masked, no burst after, 2 s of frames = ticks + held frames, merge by the later end, a speed set during a hold, a pause, a step and the gate, the cooldown; co-op host and client — pictures only, never the clock, the local filter); plus 4 in `ai_core::hold`, 1 in `shards_action` (a held body stands still) and in the sandbox `hitstop.rs` (a replay recorded while the clock was held verifies identical with hit stop off, headless and in a window; a blow between two others holds nothing; a manual hold keeps the table's ceiling; a real tick inside a hold breaks the rule), `hitstop.scenario` and `stand/hitstop.scenario`; live: `--offscreen` in real time (18 holds of 0.06-0.10 s in 8 s, 0 ticks inside, ticks 422 against 421 expected from the wall time less the held time) and a 1-client stand (picture holds only) | -| `shards_light` | 25 | `src/` (8: the definitions read and written, their bad numbers named by field, colours from hex and from a temperature, a pattern stepping through its letters at its rate and looping, noise inside its depth and the same every time, what the player's flash setting makes of a flicker, the budget's nearest-first and its ties by key) and `tests/light/` (17: the content check — clean, every bad field named with the file, a typo, a bad grading; the query and the flicker on the simulation's clock, the same in every run and in two steps as in one, calmed by `accessibility.flashes`, a moving noise light that keeps its wander and its reduced rate; the nearest lights that ask get a shadow, by settings, by moving the camera, by key; a light with no definition named; the status and no Bevy light headless; a game with no lights; and in a drawn game the Bevy light on a child without an `AiId` that follows the flicker and is not rewritten while steady, a spot's half angles and a kind that changes, the budget turning shadows on and off, a lost component or definition taking the picture away and a game's own light left alone) | +| `shards_light` | 28 | `src/` (9: the definitions read and written, their bad numbers named by field, colours from hex and from a temperature, a pattern stepping through its letters at its rate and looping, noise inside its depth and the same every time, what the player's flash setting makes of a flicker, the budget's nearest-first and its ties by key, a budget in views) and `tests/light/` (19: the content check — clean, every bad field named with the file, a typo, a bad grading; the query and the flicker on the simulation's clock, the same in every run and in two steps as in one, calmed by `accessibility.flashes`, a moving noise light that keeps its wander and its reduced rate; the nearest lights that ask get a shadow, by settings, by moving the camera, by key; a light with no definition named; a budget in views, a point light 6 and a spot 1; the status and no Bevy light headless; a game with no lights; and in a drawn game the Bevy light on a child without an `AiId` that follows the flicker and is not rewritten while steady, a spot's half angles and a kind that changes, the budget turning shadows on and off, a lost component or definition taking the picture away and a game's own light left alone, and the query saying how much of the grade the world camera draws: its exposure alone without HDR, all of it in HDR) | | `shards_rules` | 37 | `src/` (24: C3.4a +1, a view needs a set in play and a class; `def.rs` one test per validation message, charges, `min` without a shift, a session row without a column and a prefab `RuleClass` that does not read included; `read.rs` the class of a body, a session row for 0 to 9 players, the session size with a corpse and a filter, `token_limit`, `stamina_factor`, `incoming` and `outgoing`; `tools.rs` the error texts of `rules_set` and `rules`, a change, `cycle` both ways, the answer of `rules`; `guard.rs`; the replay check, the journal line, the session line, the dev entry that says why it does nothing) and `tests/rules/` (13: `state.rs` a new world plays `start` with no event, the main menu removes the rules alone and sets them neutral on a host, a client starts none and drops its copy at the main menu, the route and the tool refuse a client, the dev entry runs the next rule set, a region trip keeps them, refusals record nothing, a same-mode call changes nothing, `cycle` wraps both ways and `cycle=2` is refused, a content edit adds to `generation`, a vanished mode falls back with a warning and one `Content` event, rules content that appears starts them, the session count with a filter that leaves a body out; `snapshot.rs` a snapshot with rules loads back equal with no rescale of a player or a `brute`, a snapshot without them removes them and a refused load puts them back, a host sets them neutral, neutral hashes as none) | | `shards_voxel` | 65 | `src/` (43: the volume — shape and chunk-count limits checked without allocating, edits clipped to the volume, the hash stable across runs and equal for `-0.0`, compaction; the palette and each of its errors; noise golden values; the registry, streams, retries, golden world, palette in the world hash; `column_boxes` and `water_boxes` against a brute-force reference) `tests/voxel.rs` (8: the content kind, errors naming the file, `content_apply`, no hash change from the kind alone, duplicate registration) and `tests/region/` (14: the region kind — a region generated, built and answered for like one of tiles, the worldgen report with its totals and the fallback, a snapshot into a game without the region and a forged volume refused, the cache against a cold build in `ColliderId` order, a save and the refusal of another step version, hot reload, content errors, `--check-content`, the same API types on tiles and on a volume, a co-op client with another volume or none refused at the handoff, a replay with the cache on and off and in heavy mode, a forged manifest grid refused in a save, `region_load` and a snapshot, a mark off the volume, `VoxelPlugin` before `WorldPlugin`); a run on 18 October 2026 on Windows | | `shards_steam` | 70 | `src/` (31: the fake Steam 16 — lobbies and their type, lobby search (filters by data, lobby types, a full lobby, a slow and a refusing Steam), refusal to create a lobby, sessions and their closing, the server, achievements, cloud and quota, invitation, callbacks that fail; stopping of callbacks and the quota text 2; addresses and `+connect_lobby` 3; reconciling the cloud and file names 4; achievements 1; transport 1; lobby search — a filter by build, how lobbies differ, the size 3; the lobby's owner is the same account 1) and `tests/steam/` (39: sessions 15, achievements 6, cloud 6, tools 4, lobby search 7, scenarios 1: a stand over the fake Steam) | diff --git a/docs/manual.md b/docs/manual.md index d3af8516..50ec4c0c 100644 --- a/docs/manual.md +++ b/docs/manual.md @@ -7166,7 +7166,7 @@ The content check names the file, the definition and the field: `intensity` 0 or **How much of a grade is drawn depends on the camera.** A camera that draws in HDR (a `picture.bloom`, or the game's own `Hdr`) is graded in Bevy's tone mapping pass, which draws the whole grade. A camera that does not is graded in each material's shader, where Bevy applies the `exposure` alone: `temperature`, `tint`, `hue_deg`, `saturation`, `contrast`, `lift`, `gamma` and `gain` are left out. So turning a bloom on draws the rest of a grade for the first time, and a grade tuned without HDR can look nothing like it did: a game whose grades had a `temperature` of 0.2 and a `contrast` of 1.2 saw its tunnels go black with red in them when it turned a bloom on. The `lights` query says which it is under the grade (`drawn: its exposure alone; ... leaves out temperature, contrast`, or `drawn: all of it`), and a grade of nothing but an exposure draws the same either way. Two things to know when tuning in HDR: -- `temperature` and `tint` are Bevy's: what is taken from the *x* of the white point and added to its *y* in CIE 1931 (D65 is (0.3127, 0.3290)). Small numbers are strong: a `temperature` of 0.02 to 0.05 is a clear warm or cool cast and a `tint` of 0.01 to 0.03 a clear magenta or green one; near 0.3 the white point leaves the colour diagram and the picture loses its green and blue. The content check allows -1 to 1. +- `temperature` and `tint` are Bevy's: what is taken from the *x* of the white point and added to its *y* in CIE 1931 (D65 is (0.3127, 0.3290)). Small numbers are strong: a `temperature` of 0.02 to 0.05 is a clear warm or cool cast (at 0.05 the sandbox's grey room draws a fifth redder), and `tint` works on the same scale; near 0.3 the white point leaves the colour diagram and the picture loses its green and blue. The content check allows -1 to 1. - Bevy grades in this order: the white balance, saturation and contrast, lift, gamma and gain, and the `exposure` last. `contrast` pivots on 0.5 of the linear picture before the exposure, so in a dark scene that the grade's exposure lifts, a `contrast` above 1 sends the darks below zero and the picture goes black. Keep such a grade's `contrast` at 1, or light the scene (or expose the camera, Bevy's `Exposure`) instead of the grade. A first-person view model is drawn by a second camera over the world ("The first-person camera and the view model (F1b)"). Without HDR it takes the world camera's grade (its exposure); in HDR it is drawn over the finished picture with no tone mapping and no grade, so a grade's exposure brightens the world and not the arms.