Skip to main content

sgl_3d/frame_input/
look.rs

1//! The frame's authored image: exposure, local exposure, bloom, motion blur
2//! and colour grading. Values and defaults are Bevy 9d12036's (`bevy_post_process`
3//! `AutoExposure`, `AutoExposureCompensationCurve`, `Bloom` and `MotionBlur`,
4//! `bevy_render` `ColorGrading`).
5
6/// The frame's one exposure, which the tone map and FSR both take.
7#[derive(Clone, Copy, Debug, Default, PartialEq)]
8pub struct Exposure {
9    /// Stops applied to the scene's linear light before tone mapping: 0
10    /// leaves it, +1 doubles it. With `automatic` it is what metering sees
11    /// and what the correction adds to, as Bevy's camera exposure is.
12    pub stops: f32,
13    /// Automatic exposure; `None` keeps the frame at `stops`.
14    pub automatic: Option<AutoExposure>,
15}
16
17/// Bevy's auto exposure: a 64-bin histogram of the frame's log2 luminance
18/// (after `Exposure::stops`) from -8 to 8 through a metering mask, whose
19/// average without the darkest and brightest 10% of samples sets a target
20/// that makes that average the compensation curve's stops above 1.
21/// Luminance below the range positions the 10-90% window but stays out of
22/// the average (-8 where nothing else is left); above it counts in the
23/// highest bin. The correction moves toward the target at the authored
24/// speeds, linearly while far from it and exponentially within 1.5 stops,
25/// against jitter when the target keeps moving slightly, never stepping past
26/// it however long the frame, and restarts at the target when history does. `frame_time_ms` times it. The range, filter and
27/// 1.5 stops are Bevy's defaults and SGL3D's.
28#[derive(Clone, Copy, Debug, PartialEq)]
29pub struct AutoExposure {
30    /// Stops per second at which the exposure follows a scene that got
31    /// brighter; 0 holds it. A nonfinite or negative speed is the
32    /// default's, 3.
33    pub speed_brighten: f32,
34    /// Stops per second at which the exposure follows a scene that got
35    /// darker; 0 holds it. A nonfinite or negative speed is the default's,
36    /// 1.
37    pub speed_darken: f32,
38    /// The least correction in stops, relative to `Exposure::stops`: the
39    /// limit on darkening. With a nonfinite limit, or one above
40    /// `correction_max`, the correction is unlimited both ways, as in Bevy.
41    pub correction_min: f32,
42    /// The greatest correction in stops: the limit on brightening. With a
43    /// nonfinite limit, or one below `correction_min`, the correction is
44    /// unlimited both ways, as in Bevy.
45    pub correction_max: f32,
46    pub compensation: CompensationCurve,
47    pub metering_mask: MeteringMask,
48}
49
50impl Default for AutoExposure {
51    /// Bevy's: brightening at 3 stops per second and darkening at 1, an
52    /// unlimited correction, no compensation and every pixel metered alike.
53    fn default() -> Self {
54        Self {
55            speed_brighten: 3.,
56            speed_darken: 1.,
57            correction_min: f32::MIN,
58            correction_max: f32::MAX,
59            compensation: CompensationCurve::default(),
60            metering_mask: MeteringMask::UNIFORM,
61        }
62    }
63}
64
65/// Bevy's exposure compensation curve: stops added to the target for the
66/// frame's metered average log2 luminance. Linear between its points and
67/// constant beyond its ends; with none it adds nothing.
68#[derive(Clone, Copy, Debug, Default, PartialEq)]
69pub struct CompensationCurve {
70    points: [[f32; 2]; CompensationCurve::MAX_POINTS],
71    len: usize,
72}
73
74/// Why a compensation curve was refused.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum CompensationCurveError {
77    /// More than `CompensationCurve::MAX_POINTS` points.
78    TooManyPoints,
79    /// A coordinate is not finite.
80    NotFinite,
81    /// The luminances do not strictly increase.
82    NotIncreasing,
83}
84
85impl std::fmt::Display for CompensationCurveError {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        f.write_str(match self {
88            Self::TooManyPoints => "a compensation curve has at most eight points",
89            Self::NotFinite => "a compensation curve point is not finite",
90            Self::NotIncreasing => "compensation curve luminances must strictly increase",
91        })
92    }
93}
94
95impl std::error::Error for CompensationCurveError {}
96
97impl CompensationCurve {
98    pub const MAX_POINTS: usize = 8;
99
100    /// The curve through `points`, each a log2 luminance and the stops of
101    /// compensation there, in increasing luminance.
102    pub fn new(points: &[[f32; 2]]) -> Result<Self, CompensationCurveError> {
103        if points.len() > Self::MAX_POINTS {
104            return Err(CompensationCurveError::TooManyPoints);
105        }
106        if points.iter().flatten().any(|value| !value.is_finite()) {
107            return Err(CompensationCurveError::NotFinite);
108        }
109        if points.windows(2).any(|pair| pair[1][0] <= pair[0][0]) {
110            return Err(CompensationCurveError::NotIncreasing);
111        }
112        let mut curve = Self::default();
113        curve.points[..points.len()].copy_from_slice(points);
114        curve.len = points.len();
115        Ok(curve)
116    }
117
118    pub fn points(&self) -> &[[f32; 2]] {
119        &self.points[..self.len]
120    }
121}
122
123/// Bevy's metering mask as a 16×16 grid over the frame, rows top to bottom:
124/// each weight scales how much the pixels under it count in metering, from
125/// 0 (not at all) to 255 (fully), quantized to 16 levels as Bevy does.
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub struct MeteringMask {
128    pub weights: [[u8; 16]; 16],
129}
130
131impl MeteringMask {
132    /// Every pixel counts fully.
133    pub const UNIFORM: Self = Self {
134        weights: [[255; 16]; 16],
135    };
136}
137
138/// Bevy's energy-conserving bloom: the scene downsampled through a mip
139/// chain and upsampled back, each level blended into the next finer one,
140/// and the result blended into the scene. SGL3D shapes the halo as Bevy's
141/// `Bloom::NATURAL` does.
142#[derive(Clone, Copy, Debug, PartialEq)]
143pub struct BloomParameters {
144    /// 0..=1: how likely light is to scatter; 0 is no bloom.
145    pub intensity: f32,
146}
147
148impl Default for BloomParameters {
149    /// Bevy's `Bloom::NATURAL`.
150    fn default() -> Self {
151        Self { intensity: 0.15 }
152    }
153}
154
155/// Local exposure: large bright and dark regions drawn toward middle grey
156/// (0.18 after the frame's exposure) before the tone map, local detail
157/// kept. Each pixel's base, a blend of a bilateral grid and a wide Gaussian
158/// of the frame's log2 luminance, has its contrast about middle grey scaled
159/// by the side's contrast; the pixel's detail over that base is unchanged.
160/// At 1, 1, the default, nothing runs.
161#[derive(Clone, Copy, Debug, PartialEq)]
162pub struct LocalExposure {
163    /// 0..=1: the contrast regions brighter than middle grey keep. 1 leaves
164    /// them. Clamped; non-finite is 1.
165    pub highlight_contrast: f32,
166    /// 0..=1: the contrast regions darker than middle grey keep. 1 leaves
167    /// them. Clamped; non-finite is 1.
168    pub shadow_contrast: f32,
169}
170
171impl Default for LocalExposure {
172    /// No local exposure.
173    fn default() -> Self {
174        Self {
175            highlight_contrast: 1.,
176            shadow_contrast: 1.,
177        }
178    }
179}
180
181impl LocalExposure {
182    /// The highlight and shadow contrasts in 0..=1, non-finite as 1, or
183    /// `None` at 1, 1, where nothing runs.
184    pub(crate) fn contrasts(self) -> Option<[f32; 2]> {
185        let contrast = |c: f32| if c.is_finite() { c.clamp(0., 1.) } else { 1. };
186        let contrasts = [
187            contrast(self.highlight_contrast),
188            contrast(self.shadow_contrast),
189        ];
190        (contrasts != [1., 1.]).then_some(contrasts)
191    }
192}
193
194/// Motion blur's authored strength, which `settings::MotionBlur` scales.
195#[derive(Clone, Copy, Debug, PartialEq)]
196pub struct MotionBlurParameters {
197    /// The share of the frame's interval the shutter is open: each pixel
198    /// blurs over this share of its motion since the last frame, centred on
199    /// it. 0.5 is film's 180°; 0 is no blur. Above 1 blurs further than
200    /// anything moved, as Bevy allows for effect. Blur follows the frame
201    /// rate: a faster frame moves less and blurs less.
202    pub shutter_angle: f32,
203}
204
205impl Default for MotionBlurParameters {
206    /// Bevy's: a 180° shutter.
207    fn default() -> Self {
208        Self { shutter_angle: 0.5 }
209    }
210}
211
212/// Bevy's colour grading, applied to the exposed scene before tone mapping,
213/// except `global.post_saturation`, after it. The default adjustments are
214/// neutral. `Settings::tone_mapping` selects the display transform.
215#[derive(Clone, Copy, Debug, Default, PartialEq)]
216pub struct ColorGrading {
217    pub global: ColorGradingGlobal,
218    /// Applied to the darker parts of the image.
219    pub shadows: ColorGradingSection,
220    pub midtones: ColorGradingSection,
221    /// Applied to the lighter parts of the image.
222    pub highlights: ColorGradingSection,
223    /// Applied only when `Settings::tone_mapping` selects AgX.
224    pub agx_look: AgxLook,
225}
226
227/// Filament's AgX looks (`AgxToneMapper::AgxLook`): a creative contrast and
228/// saturation within AgX, after its curve.
229#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
230pub enum AgxLook {
231    /// AgX's base contrast, with no look.
232    #[default]
233    None,
234    /// More contrast and saturation, for sRGB displays.
235    Punchy,
236    /// A golden tint, slightly washed out, for BT.1886 displays.
237    Golden,
238}
239
240/// Grading of the whole image.
241#[derive(Clone, Copy, Debug, PartialEq)]
242pub struct ColorGradingGlobal {
243    /// Subtracted from the white point's CIE 1931 x: positive is warmer
244    /// (redder), negative cooler. Luminance is unchanged.
245    pub temperature: f32,
246    /// Added to the white point's CIE 1931 y: positive is more magenta,
247    /// negative greener.
248    pub tint: f32,
249    /// Hue rotation in radians, wrapping either direction every 2π.
250    pub hue: f32,
251    /// Saturation after tone mapping: 0 is greyscale, 1 unchanged.
252    pub post_saturation: f32,
253    /// Where midtones start and end, as the exposed scene's mean of R, G and
254    /// B; sections blend over 0.1 either side.
255    pub midtones_start: f32,
256    pub midtones_end: f32,
257}
258
259impl Default for ColorGradingGlobal {
260    fn default() -> Self {
261        Self {
262            temperature: 0.,
263            tint: 0.,
264            hue: 0.,
265            post_saturation: 1.,
266            midtones_start: 0.2,
267            midtones_end: 0.7,
268        }
269    }
270}
271
272/// Grading of one section: saturation and contrast, then the ASC CDL
273/// `(colour × gain + lift)^(1 / gamma)`.
274#[derive(Clone, Copy, Debug, PartialEq)]
275pub struct ColorGradingSection {
276    /// 0 is greyscale, 1 unchanged.
277    pub saturation: f32,
278    /// Spread about 0.5: 1 unchanged.
279    pub contrast: f32,
280    pub gamma: f32,
281    pub gain: f32,
282    pub lift: f32,
283}
284
285impl Default for ColorGradingSection {
286    fn default() -> Self {
287        Self {
288            saturation: 1.,
289            contrast: 1.,
290            gamma: 1.,
291            gain: 1.,
292            lift: 0.,
293        }
294    }
295}