Skip to main content

wde_pbr/post_process/
settings.rs

1use std::borrow::Cow;
2
3use bevy::prelude::*;
4use bytemuck::{Pod, Zeroable};
5
6use crate::prelude::PbrDebugView;
7
8/// Settings of the post-processing stack. Insert it in the main world to configure the effects.
9///
10/// Every color is in linear RGB.
11#[derive(Resource, Clone, Debug, Default, Reflect)]
12#[reflect(Resource)]
13pub struct PostProcessSettings {
14    pub fog: FogSettings,
15    pub bloom: BloomSettings,
16    pub exposure: ExposureSettings,
17    pub color_grading: ColorGrading,
18    pub tonemapping: Tonemapping,
19    pub vignette: VignetteSettings,
20    pub chromatic_aberration: ChromaticAberrationSettings,
21    pub film_grain: FilmGrainSettings,
22    /// Adds a tiny noise to the output to hide the banding of 8-bit gradients.
23    pub dithering: bool,
24    pub anti_aliasing: AntiAliasing,
25    /// Quality of the [`AntiAliasing::Smaa`].
26    pub smaa_preset: SmaaPreset,
27    pub taa: TaaSettings,
28    pub sharpening: SharpeningSettings
29}
30impl PostProcessSettings {
31    /// The settings applied over a debug view of the lighting (see [`PbrDebugView`]): its lighting views keep the
32    /// exposure (frozen) and the color grading, its data views keep only the anti-aliasing.
33    pub fn for_debug_view(&self, view: PbrDebugView) -> Cow<'_, Self> {
34        if view == PbrDebugView::Off {
35            return Cow::Borrowed(self);
36        }
37        let mut s = self.clone();
38        s.fog.enabled = false;
39        s.bloom.enabled = false;
40        s.exposure.brighten_speed = 0.0;
41        s.exposure.darken_speed = 0.0;
42        s.vignette.intensity = 0.0;
43        s.chromatic_aberration.intensity = 0.0;
44        s.film_grain.intensity = 0.0;
45        s.sharpening.enabled = false;
46        if view.is_data() {
47            s.exposure.eye_adaptation = false;
48            s.exposure.day_compensation = 0.0;
49            s.exposure.night_compensation = 0.0;
50            s.color_grading = ColorGrading::default();
51            s.tonemapping = Tonemapping::None;
52            s.dithering = false;
53        }
54        Cow::Owned(s)
55    }
56}
57
58/// Anti-aliasing of the final image.
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Reflect)]
60pub enum AntiAliasing {
61    None,
62    /// Fast approximate anti-aliasing: blurs the contrasted edges along their direction.
63    #[default]
64    Fxaa,
65    /// Subpixel morphological anti-aliasing: recognizes the shapes of the aliased edges, and blends each pixel
66    /// with its neighbors by the area the real edge covers. Sharper than FXAA, at about twice its cost.
67    Smaa,
68    /// Temporal anti-aliasing: jitters the projection by a sub-pixel offset each frame, and accumulates the frames
69    /// reprojected by the camera motion, in HDR before the bloom. Resolves the details thinner than a pixel and stops
70    /// their flickering, but softens the image (pair it with the [`SharpeningSettings`]). The objects moving on their
71    /// own are not reprojected, so their history is mostly rejected and they are less anti-aliased.
72    Taa
73}
74
75/// Settings of the [`AntiAliasing::Taa`].
76#[derive(Clone, Debug, Reflect)]
77pub struct TaaSettings {
78    /// Weight of the current frame in the accumulated image, in (0, 1]. Lower is smoother and more stable,
79    /// but slower to react and more prone to ghosting.
80    pub frame_weight: f32
81}
82impl Default for TaaSettings {
83    fn default() -> Self {
84        Self { frame_weight: 0.05 }
85    }
86}
87
88/// Quality of the SMAA: the edge threshold, and the length of the edges searched.
89#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Reflect)]
90pub enum SmaaPreset {
91    Low,
92    Medium,
93    /// Also smooths the diagonal edges and rounds the corners.
94    #[default]
95    High,
96    Ultra
97}
98impl SmaaPreset {
99    /// x=edge threshold, y=search steps, z=diagonal search steps (0 disables them), w=corner rounding in [0, 1] (negative disables it).
100    fn params(self) -> [f32; 4] {
101        match self {
102            Self::Low => [0.15, 4.0, 0.0, -1.0],
103            Self::Medium => [0.1, 8.0, 0.0, -1.0],
104            Self::High => [0.1, 16.0, 8.0, 0.25],
105            Self::Ultra => [0.05, 32.0, 16.0, 0.25]
106        }
107    }
108}
109
110/// AMD FidelityFX contrast adaptive sharpening, applied after the anti-aliasing to restore the details it blurred.
111/// It sharpens the low-contrast areas more than the edges, which limits the halos.
112#[derive(Clone, Debug, Reflect)]
113pub struct SharpeningSettings {
114    pub enabled: bool,
115    /// Sharpening strength, in [0, 1].
116    pub sharpness: f32
117}
118impl Default for SharpeningSettings {
119    fn default() -> Self {
120        Self {
121            enabled: false,
122            sharpness: 0.5
123        }
124    }
125}
126impl SharpeningSettings {
127    /// Negative weight of the neighbors at full amplitude, from -1/8 to -1/5.
128    fn peak(&self) -> f32 {
129        -1.0 / (8.0 - 3.0 * self.sharpness.clamp(0.0, 1.0))
130    }
131}
132
133/// Exponential height fog, applied to the opaque geometry and to the sky, before the transparent objects.
134#[derive(Clone, Debug, Reflect)]
135pub struct FogSettings {
136    pub enabled: bool,
137    pub color: [f32; 3],
138    /// Extinction per meter at the base height.
139    pub density: f32,
140    /// How fast the density decreases with the height above the base height. 0 gives a uniform fog.
141    pub height_falloff: f32,
142    pub base_height: f32,
143    /// Distance from the camera before which there is no fog.
144    pub start_distance: f32,
145    /// Maximum fog opacity in [0, 1].
146    pub max_opacity: f32,
147    /// Distance at which the sky is fogged.
148    pub sky_distance: f32,
149    /// How much the fog takes the color of the sky horizon, in [0, 1] (requires the `atmosphere` feature).
150    pub sky_color: f32,
151    /// Color of the light scattered by the fog towards the directional light.
152    pub sun_color: [f32; 3],
153    /// Strength of the scattered directional light. 0 disables it.
154    pub sun_intensity: f32,
155    /// Concentration of the scattered light around the light direction.
156    pub sun_exponent: f32
157}
158impl Default for FogSettings {
159    fn default() -> Self {
160        Self {
161            enabled: false,
162            color: [0.5, 0.6, 0.7],
163            density: 0.002,
164            height_falloff: 0.05,
165            base_height: 0.0,
166            start_distance: 0.0,
167            max_opacity: 1.0,
168            sky_distance: 1000.0,
169            sky_color: 0.0,
170            sun_color: [1.0, 0.9, 0.7],
171            sun_intensity: 0.0,
172            sun_exponent: 8.0
173        }
174    }
175}
176
177/// Bloom of the bright parts of the image.
178#[derive(Clone, Debug, Reflect)]
179pub struct BloomSettings {
180    pub enabled: bool,
181    /// Strength of the bloom added to the image.
182    pub intensity: f32,
183    /// Brightness from which pixels bloom. 0 makes the whole image bloom.
184    pub threshold: f32,
185    /// Smoothness of the threshold transition, in [0, 1].
186    pub threshold_softness: f32,
187    /// Spread of the bloom, in [0, 1].
188    pub scatter: f32
189}
190impl Default for BloomSettings {
191    fn default() -> Self {
192        Self {
193            enabled: false,
194            intensity: 0.1,
195            threshold: 1.0,
196            threshold_softness: 0.5,
197            scatter: 0.7
198        }
199    }
200}
201
202/// Exposure of the image, on top of [`ColorGrading::exposure`]: a day/night compensation, and an
203/// optional eye adaptation to the image brightness, measured with a luminance histogram.
204#[derive(Clone, Debug, Reflect)]
205pub struct ExposureSettings {
206    /// Exposure compensation in EV stops in full daylight.
207    pub day_compensation: f32,
208    /// Exposure compensation in EV stops at night, blended with the day one by the sun height
209    /// (requires the `atmosphere` feature, else the day compensation is used).
210    pub night_compensation: f32,
211    /// Adapts the exposure so that the average luminance of the image becomes middle grey.
212    pub eye_adaptation: bool,
213    /// Range of the measured luminance, in log2 units. The pixels outside are clamped to it.
214    pub luminance_range: [f32; 2],
215    /// Fraction of the darkest pixels ignored by the metering, in [0, 1].
216    pub low_percentile: f32,
217    /// Fraction of the pixels below which the brightest are ignored, in [0, 1].
218    pub high_percentile: f32,
219    /// Limits of the adapted exposure, in EV stops.
220    pub min_ev: f32,
221    pub max_ev: f32,
222    /// Adaptation rate when the exposure increases (the image got darker), in 1/s.
223    pub brighten_speed: f32,
224    /// Adaptation rate when the exposure decreases (the image got brighter), in 1/s.
225    pub darken_speed: f32
226}
227impl Default for ExposureSettings {
228    fn default() -> Self {
229        Self {
230            day_compensation: 0.0,
231            night_compensation: 0.0,
232            eye_adaptation: false,
233            luminance_range: [-10.0, 6.0],
234            low_percentile: 0.1,
235            high_percentile: 0.9,
236            min_ev: -4.0,
237            max_ev: 4.0,
238            brighten_speed: 1.0,
239            darken_speed: 3.0
240        }
241    }
242}
243impl ExposureSettings {
244    /// Compensation in EV stops for a day amount in [0, 1] (0 at night, 1 in daylight).
245    pub fn compensation(&self, day: f32) -> f32 {
246        self.night_compensation
247            + (self.day_compensation - self.night_compensation) * day.clamp(0.0, 1.0)
248    }
249}
250
251/// Color grading, applied in HDR before the tonemapping, except `lift`, `gamma` and `gain` which are applied after.
252#[derive(Clone, Debug, Reflect)]
253pub struct ColorGrading {
254    /// Exposure in EV stops.
255    pub exposure: f32,
256    /// White balance temperature in [-1, 1]: negative is cooler, positive warmer.
257    pub temperature: f32,
258    /// White balance tint in [-1, 1]: negative is greener, positive more magenta.
259    pub tint: f32,
260    /// Contrast around the mid-grey. 1 is neutral.
261    pub contrast: f32,
262    /// 0 is greyscale, 1 is neutral.
263    pub saturation: f32,
264    /// Multiplier of the image color.
265    pub color_filter: [f32; 3],
266    /// Shadows offset, 0 is neutral.
267    pub lift: [f32; 3],
268    /// Midtones power, 1 is neutral.
269    pub gamma: [f32; 3],
270    /// Highlights multiplier, 1 is neutral.
271    pub gain: [f32; 3]
272}
273impl Default for ColorGrading {
274    fn default() -> Self {
275        Self {
276            exposure: 0.0,
277            temperature: 0.0,
278            tint: 0.0,
279            contrast: 1.0,
280            saturation: 1.0,
281            color_filter: [1.0; 3],
282            lift: [0.0; 3],
283            gamma: [1.0; 3],
284            gain: [1.0; 3]
285        }
286    }
287}
288
289/// Operator mapping the HDR colors to the display range.
290#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Reflect)]
291pub enum Tonemapping {
292    /// Clamps the colors.
293    None,
294    Reinhard,
295    /// Stephen Hill's fit of the ACES curve. Contrasted, shifts saturated colors.
296    Aces,
297    /// Desaturates the highlights smoothly.
298    AgX,
299    /// Khronos PBR Neutral: keeps the colors below 0.76 untouched and only compresses the highlights.
300    #[default]
301    PbrNeutral
302}
303
304/// Darkening of the image borders.
305#[derive(Clone, Debug, Reflect)]
306pub struct VignetteSettings {
307    /// 0 disables the vignette.
308    pub intensity: f32,
309    /// Distance from the center where the vignette starts, 1 being the middle of the left and right borders.
310    pub radius: f32,
311    /// Width of the vignette transition.
312    pub smoothness: f32,
313    /// 0 follows the screen aspect ratio, 1 is a circle.
314    pub roundness: f32,
315    pub color: [f32; 3]
316}
317impl Default for VignetteSettings {
318    fn default() -> Self {
319        Self {
320            intensity: 0.0,
321            radius: 0.6,
322            smoothness: 0.8,
323            roundness: 1.0,
324            color: [0.0; 3]
325        }
326    }
327}
328
329/// Splitting of the color channels towards the image borders.
330#[derive(Clone, Debug, Default, Reflect)]
331pub struct ChromaticAberrationSettings {
332    /// Channel offset at the image corners, in percent of the screen. 0 disables it.
333    pub intensity: f32
334}
335
336/// Animated film grain noise.
337#[derive(Clone, Debug, Reflect)]
338pub struct FilmGrainSettings {
339    /// 0 disables the grain.
340    pub intensity: f32,
341    /// How much the grain is reduced in the bright areas, in [0, 1].
342    pub response: f32
343}
344impl Default for FilmGrainSettings {
345    fn default() -> Self {
346        Self {
347            intensity: 0.0,
348            response: 0.8
349        }
350    }
351}
352
353/// GPU layout of the post-processing parameters (bloom and final composite).
354#[repr(C)]
355#[derive(Resource, Clone, Copy, Debug, Pod, Zeroable)]
356pub(crate) struct PostProcessUniform {
357    /// x=threshold, y=knee, z=scatter, w=intensity (0 when disabled)
358    pub bloom: [f32; 4],
359    /// Columns of the white balance matrix (linear RGB), w=unused
360    pub white_balance: [[f32; 4]; 3],
361    /// x=exposure multiplier, y=contrast, z=saturation, w=tonemapper
362    pub grading: [f32; 4],
363    pub color_filter: [f32; 4],
364    pub lift: [f32; 4],
365    pub gamma: [f32; 4],
366    pub gain: [f32; 4],
367    /// x=intensity, y=radius, z=smoothness, w=roundness
368    pub vignette: [f32; 4],
369    pub vignette_color: [f32; 4],
370    /// x=chromatic aberration, y=grain intensity, z=grain response, w=dithering
371    pub effects: [f32; 4],
372    /// x=time in seconds
373    pub time: [f32; 4],
374    /// x=anti-aliasing method, y=TAA frame weight
375    pub anti_aliasing: [f32; 4],
376    /// See [`SmaaPreset::params`]
377    pub smaa: [f32; 4],
378    /// x=enabled (0 or 1), y=peak weight (see [`SharpeningSettings::peak`])
379    pub sharpening: [f32; 4],
380    /// x=eye adaptation (0 or 1), y=delta time in seconds, z=brighten speed, w=darken speed
381    pub exposure: [f32; 4],
382    /// x=min log2 luminance, y=log2 luminance range, z=low percentile, w=high percentile
383    pub exposure_metering: [f32; 4],
384    /// x=min EV, y=max EV
385    pub exposure_limits: [f32; 4]
386}
387impl Default for PostProcessUniform {
388    fn default() -> Self {
389        Self::from_settings(&PostProcessSettings::default(), 0.0, 0.0, 1.0)
390    }
391}
392impl PostProcessUniform {
393    pub fn anti_aliasing(&self) -> AntiAliasing {
394        match self.anti_aliasing[0] as u32 {
395            1 => AntiAliasing::Fxaa,
396            2 => AntiAliasing::Smaa,
397            3 => AntiAliasing::Taa,
398            _ => AntiAliasing::None
399        }
400    }
401
402    /// `day` is the day amount in [0, 1] used for the exposure compensation.
403    pub fn from_settings(settings: &PostProcessSettings, time: f32, delta: f32, day: f32) -> Self {
404        let bloom = &settings.bloom;
405        let grading = &settings.color_grading;
406        let vignette = &settings.vignette;
407        let exposure = &settings.exposure;
408        let [min_lum, max_lum] = exposure.luminance_range;
409        let low = exposure.low_percentile.clamp(0.0, 1.0);
410        let wb = white_balance(grading.temperature, grading.tint);
411        let rgb = |c: [f32; 3]| [c[0], c[1], c[2], 0.0];
412        Self {
413            bloom: [
414                bloom.threshold.max(0.0),
415                bloom.threshold.max(0.0) * bloom.threshold_softness.clamp(0.0, 1.0),
416                bloom.scatter.clamp(0.0, 1.0),
417                if bloom.enabled {
418                    bloom.intensity.max(0.0)
419                } else {
420                    0.0
421                }
422            ],
423            white_balance: [wb.x_axis, wb.y_axis, wb.z_axis].map(|c| c.extend(0.0).to_array()),
424            grading: [
425                (grading.exposure + exposure.compensation(day)).exp2(),
426                grading.contrast.max(0.01),
427                grading.saturation.max(0.0),
428                settings.tonemapping as u32 as f32
429            ],
430            color_filter: rgb(grading.color_filter),
431            lift: rgb(grading.lift),
432            gamma: rgb(grading.gamma.map(|g| g.max(0.01))),
433            gain: rgb(grading.gain),
434            vignette: [
435                vignette.intensity.clamp(0.0, 1.0),
436                vignette.radius,
437                vignette.smoothness.max(0.001),
438                vignette.roundness.clamp(0.0, 1.0)
439            ],
440            vignette_color: rgb(vignette.color),
441            effects: [
442                settings.chromatic_aberration.intensity.max(0.0) * 0.01,
443                settings.film_grain.intensity.max(0.0),
444                settings.film_grain.response.clamp(0.0, 1.0),
445                if settings.dithering { 1.0 } else { 0.0 }
446            ],
447            time: [time, 0.0, 0.0, 0.0],
448            anti_aliasing: [
449                settings.anti_aliasing as u32 as f32,
450                settings.taa.frame_weight.clamp(0.01, 1.0),
451                0.0,
452                0.0
453            ],
454            smaa: settings.smaa_preset.params(),
455            sharpening: [
456                if settings.sharpening.enabled {
457                    1.0
458                } else {
459                    0.0
460                },
461                settings.sharpening.peak(),
462                0.0,
463                0.0
464            ],
465            exposure: [
466                if exposure.eye_adaptation { 1.0 } else { 0.0 },
467                delta.max(0.0),
468                exposure.brighten_speed.max(0.0),
469                exposure.darken_speed.max(0.0)
470            ],
471            exposure_metering: [
472                min_lum,
473                (max_lum - min_lum).max(0.01),
474                low,
475                exposure.high_percentile.clamp(low, 1.0)
476            ],
477            exposure_limits: [
478                exposure.min_ev,
479                exposure.max_ev.max(exposure.min_ev),
480                0.0,
481                0.0
482            ]
483        }
484    }
485}
486
487/// GPU layout of the fog parameters.
488#[repr(C)]
489#[derive(Resource, Clone, Copy, Debug, Pod, Zeroable)]
490pub(crate) struct FogUniform {
491    /// xyz=color, w=sky color amount
492    pub color: [f32; 4],
493    /// x=density, y=height falloff, z=base height, w=start distance
494    pub params: [f32; 4],
495    /// x=max opacity, y=sky distance, z=enabled
496    pub limits: [f32; 4],
497    /// xyz=sun color, w=sun exponent
498    pub sun: [f32; 4],
499    /// x=sun intensity
500    pub sun_params: [f32; 4]
501}
502impl Default for FogUniform {
503    fn default() -> Self {
504        Self::from_settings(&FogSettings::default())
505    }
506}
507impl FogUniform {
508    pub fn from_settings(fog: &FogSettings) -> Self {
509        let [r, g, b] = fog.color;
510        let [sr, sg, sb] = fog.sun_color;
511        Self {
512            color: [r, g, b, fog.sky_color.clamp(0.0, 1.0)],
513            params: [
514                fog.density.max(0.0),
515                fog.height_falloff.max(0.0),
516                fog.base_height,
517                fog.start_distance.max(0.0)
518            ],
519            limits: [
520                fog.max_opacity.clamp(0.0, 1.0),
521                fog.sky_distance.max(0.0),
522                if fog.enabled { 1.0 } else { 0.0 },
523                0.0
524            ],
525            sun: [sr, sg, sb, fog.sun_exponent.max(1.0)],
526            sun_params: [fog.sun_intensity.max(0.0), 0.0, 0.0, 0.0]
527        }
528    }
529}
530
531// Linear RGB <-> LMS cone response
532const LIN_TO_LMS: Mat3 = Mat3::from_cols(
533    Vec3::new(3.904_05e-1, 7.084_16e-2, 2.310_82e-2),
534    Vec3::new(5.499_41e-1, 9.631_72e-1, 1.280_21e-1),
535    Vec3::new(8.926_32e-3, 1.357_75e-3, 9.362_45e-1)
536);
537const LMS_TO_LIN: Mat3 = Mat3::from_cols(
538    Vec3::new(2.858_47, -2.101_82e-1, -4.181_20e-2),
539    Vec3::new(-1.628_79, 1.158_20, -1.181_69e-1),
540    Vec3::new(-2.489_10e-2, 3.242_81e-4, 1.068_67)
541);
542
543/// White balance matrix, as a von Kries adaptation from a shifted D65 illuminant.
544fn white_balance(temperature: f32, tint: f32) -> Mat3 {
545    let t1 = temperature.clamp(-1.0, 1.0) * 100.0 / 65.0;
546    let t2 = tint.clamp(-1.0, 1.0) * 100.0 / 65.0;
547    let x = 0.31271 - t1 * if t1 < 0.0 { 0.1 } else { 0.05 };
548    let y = 2.87 * x - 3.0 * x * x - 0.275_095_07 + t2 * 0.05;
549
550    // CIE xy to LMS, with Y = 1
551    let xyz = Vec3::new(x / y, 1.0, (1.0 - x - y) / y);
552    let lms = Vec3::new(
553        0.7328 * xyz.x + 0.4296 * xyz.y - 0.1624 * xyz.z,
554        -0.7036 * xyz.x + 1.6975 * xyz.y + 0.0061 * xyz.z,
555        0.0030 * xyz.x + 0.0136 * xyz.y + 0.9834 * xyz.z
556    );
557    let d65 = Vec3::new(0.949_237, 1.035_42, 1.087_28);
558    LMS_TO_LIN * Mat3::from_diagonal(d65 / lms) * LIN_TO_LMS
559}
560
561#[cfg(test)]
562mod tests {
563    use super::*;
564
565    #[test]
566    fn neutral_white_balance_is_identity() {
567        let wb = white_balance(0.0, 0.0);
568        let diff = wb - Mat3::IDENTITY;
569        for c in [diff.x_axis, diff.y_axis, diff.z_axis] {
570            assert!(c.abs().max_element() < 0.01, "{wb:?}");
571        }
572    }
573
574    #[test]
575    fn exposure_compensation_blends_night_to_day() {
576        let exposure = ExposureSettings {
577            day_compensation: -1.0,
578            night_compensation: 2.0,
579            ..Default::default()
580        };
581        assert_eq!(exposure.compensation(0.0), 2.0);
582        assert_eq!(exposure.compensation(1.0), -1.0);
583        assert_eq!(exposure.compensation(0.5), 0.5);
584    }
585
586    #[test]
587    fn sharpening_peak_spans_cas_range() {
588        let peak = |sharpness| {
589            SharpeningSettings {
590                enabled: true,
591                sharpness
592            }
593            .peak()
594        };
595        assert_eq!(peak(0.0), -1.0 / 8.0);
596        assert_eq!(peak(1.0), -1.0 / 5.0);
597    }
598
599    #[test]
600    fn anti_aliasing_round_trips() {
601        for method in [
602            AntiAliasing::None,
603            AntiAliasing::Fxaa,
604            AntiAliasing::Smaa,
605            AntiAliasing::Taa
606        ] {
607            let settings = PostProcessSettings {
608                anti_aliasing: method,
609                ..Default::default()
610            };
611            assert_eq!(
612                PostProcessUniform::from_settings(&settings, 0.0, 0.0, 1.0).anti_aliasing(),
613                method
614            );
615        }
616    }
617
618    #[test]
619    fn warm_white_balance_boosts_red() {
620        let white = white_balance(0.5, 0.0) * Vec3::ONE;
621        assert!(white.x > white.z);
622    }
623}