Skip to main content

concinnity_core/components/
environment_map.rs

1// Baked image-based lighting environment schema.
2
3use crate::ecs::PayloadLocator;
4use crate::ecs::asset_id::AssetId;
5use alloc::string::String;
6
7/// A baked lighting environment built from an equirectangular source (or a
8/// built-in generator). It provides the scene's ambient image-based lighting
9/// (soft diffuse fill plus glossy reflections that follow surface roughness)
10/// and the on-screen sky.
11///
12/// **Source formats:** a Radiance `.hdr`, or a panorama-sphere `.glb` /
13/// `.gltf` -- the packaging where an environment image is painted on the
14/// emissive channel of a sphere you stand inside. `cn add` recognises the
15/// latter and produces an EnvironmentMap instead of scene geometry.
16///
17/// **Dynamic range:** a `.hdr` carries real radiance, so its sun can be
18/// thousands of times brighter than the sky and bakes into a bright key light
19/// with a hot specular highlight. A panorama inside a `.glb` is a display
20/// image whose brightest value is white; it is read literally, with the sRGB
21/// curve inverted and white landing at 1.0 radiance. That makes it an exact
22/// backdrop and a soft, low-contrast fill light, never a key light. Raise
23/// [PostProcessConfig](#postprocessconfig)'s `ambient_intensity` to lift the
24/// level rather than expecting the bake to invent range the file lacks.
25///
26/// **`prefilter_face_size` note:** this controls both the reflection detail and
27/// the on-screen sky sharpness. 512 is the default balance: 256 visibly
28/// pixelates a 4K-source sky, 1024 sharpens it further at 4× the size.
29///
30/// **Built-in generators:** `sky` produces a procedural blue sky with a soft
31/// sun, useful when no source file is available.
32///
33/// The sky mesh that displays the map (a skybox
34/// [ProceduralMesh](#proceduralmesh) plus its [Material](#material) and
35/// [Prop](#prop)) is injected at build time when the world declares no skybox
36/// mesh of its own. Declare an [EngineDefaults](#enginedefaults) with
37/// `"sky": false` to use the map for image-based lighting only, with the
38/// background left to `clear_color` or your own geometry.
39///
40/// ```rust
41/// # use concinnity_core::components::EnvironmentMap;
42/// EnvironmentMap {
43///     source: "assets/hdri/studio.hdr".into(),
44///     ..Default::default()
45/// };
46/// ```
47#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
48#[serde(default)]
49pub struct EnvironmentMap {
50    /// Asset identity; injected via `inject_name`. Not part of `args`.
51    #[serde(skip)]
52    pub asset_id: AssetId,
53    /// Path to the source equirectangular panorama -- a Radiance `.hdr`, or a
54    /// panorama-sphere `.glb` / `.gltf` -- relative to the project root.
55    /// Mutually exclusive with `generator`.
56    pub source: String,
57    /// Built-in source name (e.g. "sky"). Mutually exclusive with `source`.
58    pub generator: String,
59    /// Face size of the reflection/sky cubemap, in pixels. Higher is sharper
60    /// but larger.
61    pub prefilter_face_size: u32,
62    /// Face size of the diffuse ambient cubemap, in pixels.
63    pub irradiance_face_size: u32,
64    /// Number of samples used to filter each reflection texel. Higher reduces
65    /// noise at the cost of build time.
66    pub prefilter_samples: u32,
67    /// Upper bound on how bright a single source texel may count while building
68    /// the glossy reflection mips. A clear-sky HDR holds a few sun or sky
69    /// texels thousands of times brighter than their surroundings; left
70    /// unbounded they survive into the small (coarse) reflection mips as lone
71    /// hot texels and smear across glossy floors as hard bright squares. This
72    /// caps each sampled texel so that energy spreads smoothly across the
73    /// reflection instead. It affects reflections only, never the on-screen
74    /// sky. Set to `0` to disable (no cap); lower values clamp harder.
75    pub prefilter_clamp: f32,
76    /// Injected at load time from the compiled blob payload.
77    #[serde(skip)]
78    pub locator: Option<PayloadLocator>,
79}
80
81// The face-size / sample-count defaults below are the single source of truth:
82// the build pipeline deserialises args through this struct, so a field absent
83// from a JSONL entry inherits these values rather than a constant duplicated in
84// the build crate. They are chosen for ~32 MB payloads and a few seconds of
85// build cost on the dev box. `prefilter_face_size` does double duty: mips 1..N
86// feed the GGX specular IBL lookup (fine at low resolution) while mip 0 is
87// sampled directly by the skybox sentinel branch in the fragment shaders, so it
88// has to be large enough that the displayed sky doesn't look blocky. 512 is the
89// balance point; 256 visibly pixelates a 4K HDR sky, 1024 quadruples the payload
90// for sharpness only the skybox (not the IBL math) actually uses.
91//
92// `prefilter_clamp` defaults to a moderate cap rather than off: an unbounded
93// clear-sky HDR aliases its sun and bright sky into hard squares on glossy
94// floors (the coarse reflection mips hold only a handful of texels, so one hot
95// texel paints a whole region). The cap spreads that energy without touching
96// the on-screen sky, and a uniform sky below the cap is unchanged.
97impl Default for EnvironmentMap {
98    fn default() -> Self {
99        Self {
100            asset_id: AssetId::default(),
101            source: String::new(),
102            generator: String::new(),
103            prefilter_face_size: 512,
104            irradiance_face_size: 8,
105            prefilter_samples: 1024,
106            prefilter_clamp: 12.0,
107            locator: None,
108        }
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn defaults_size_the_prefilter_for_a_sharp_skybox() {
118        // Mip 0 is sampled directly by the skybox branch, so the prefilter face
119        // has to be far larger than the irradiance one, which only ever feeds
120        // the diffuse convolution.
121        let e = EnvironmentMap::default();
122        assert_eq!(e.prefilter_face_size, 512);
123        assert_eq!(e.irradiance_face_size, 8);
124        assert!(e.prefilter_face_size > e.irradiance_face_size);
125        assert_eq!(e.prefilter_samples, 1024);
126        // The clamp defaults on: an unbounded HDR sun aliases into hard squares
127        // in the coarse reflection mips.
128        assert_eq!(e.prefilter_clamp, 12.0);
129        assert!(e.source.is_empty());
130        assert!(e.generator.is_empty());
131        assert!(e.locator.is_none());
132    }
133
134    #[test]
135    fn an_authored_bake_parses_and_round_trips_through_postcard() {
136        let e: EnvironmentMap = serde_json::from_str(
137            r#"{"source":"sky.hdr","prefilter_face_size":1024,"irradiance_face_size":16,
138                "prefilter_samples":512,"prefilter_clamp":0}"#,
139        )
140        .unwrap();
141        assert_eq!(e.source, "sky.hdr");
142        assert_eq!(e.prefilter_face_size, 1024);
143        // A zero clamp turns the cap off rather than blacking out the sky.
144        assert_eq!(e.prefilter_clamp, 0.0);
145
146        let bytes = postcard::to_allocvec(&e).unwrap();
147        let back: EnvironmentMap = postcard::from_bytes(&bytes).unwrap();
148        assert_eq!(back.irradiance_face_size, 16);
149        assert_eq!(back.prefilter_samples, 512);
150        assert_eq!(back.asset_id, AssetId::default());
151        assert!(back.locator.is_none());
152    }
153
154    #[test]
155    fn a_generated_environment_names_its_generator_instead_of_a_source() {
156        let e: EnvironmentMap = serde_json::from_str(r#"{"generator":"gradient_sky"}"#).unwrap();
157        assert_eq!(e.generator, "gradient_sky");
158        assert!(e.source.is_empty());
159    }
160}