ferravex_render/
post.rs

1//! Opt-in full-screen post-processing: bloom, tonemapping, grading, vignette and
2//! optional film grain, chromatic aberration and scanlines.
3//!
4//! Games choose a [`PostFx`] with [`set_post_fx`]. The setting is **sticky**: it
5//! stays active across frames (and `clear_background`) until replaced, so a game
6//! usually sets it once per scene. [`PostFx::off()`] (the default) restores the
7//! original direct-to-screen path with zero extra GPU work.
8//!
9//! While post-processing is active, the world is drawn into an offscreen target.
10//! At the **world/HUD boundary** the hosts resolve that target, run the bloom
11//! chain and composite the graded image to the screen; every later draw (HUD,
12//! menus, the Controls editor) is drawn directly on top, crisp, un-bloomed and
13//! un-vignetted. The boundary is the first of:
14//!
15//! - an explicit [`post_fx_hud_begin`];
16//! - `set_world_colors(false)` while world colors are enabled;
17//! - `set_default_camera()` while world colors are enabled (that is, after a
18//!   `set_camera` in the same frame).
19//!
20//! The last two follow the existing world-palette boundary and can be disabled
21//! with [`PostFx::auto_hud`]. Without a boundary, the whole frame is
22//! post-processed. Only the first boundary in a frame counts.
23//!
24//! Player preferences and accessibility always win over authored settings:
25//!
26//! - An explicit Low quality choice (Details, `?quality=low` or
27//!   `FERRAVEX_QUALITY=low`) disables post-processing. Medium uses a four-level
28//!   bloom chain; High uses five levels. Without a player choice, an authored
29//!   `set_quality(High)` selects High and anything else selects Medium.
30//! - Sustained adaptive-performance pressure (level 2 and above) caps the tier at
31//!   Medium.
32//! - Reduced flash caps bloom intensity at [`REDUCED_FLASH_BLOOM`] and disables
33//!   grain and chromatic aberration.
34//!
35//! Developers can force a preset for a session with `FERRAVEX_POST=off|subtle|
36//! neon|warm-film|crt` (native) or `?post=…` (browser) without editing a game.
37//!
38//! ```
39//! use ferravex_render::{input, post::{self, PostFx, PostTier}};
40//! post::set_post_fx(PostFx::neon().vignette(0.25, 0.6));
41//! let status = input::host_frame(1. / 60., 320, 200, || {
42//!     ferravex_render::clear_background(ferravex_render::BLACK);
43//!     // World: bright additive accents feed the bloom.
44//!     post::glow_circle(160., 100., 24., ferravex_render::ORANGE, 1.5);
45//!     // HUD: drawn after the boundary, it stays crisp.
46//!     post::post_fx_hud_begin();
47//!     ferravex_render::draw_rectangle(8., 8., 40., 6., ferravex_render::WHITE);
48//!     post::post_fx_status()
49//! });
50//! assert_ne!(status.tier, PostTier::Off);
51//! post::set_post_fx(PostFx::off());
52//! ```
53use crate::{Color, Mat4, Vec3, lighting::Quality};
54
55/// Number of `f32` values in the resolved per-frame host block.
56pub const POST_FRAME_FLOATS: usize = 28;
57/// Bloom intensity cap applied while the player requests reduced flash.
58pub const REDUCED_FLASH_BLOOM: f32 = 0.6;
59/// Maximum bloom chain length used by the High tier.
60pub const MAX_BLOOM_LEVELS: usize = 5;
61
62/// How bloom and over-bright scene values are mapped to the display.
63#[repr(u32)]
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
65pub enum Tonemap {
66    /// Add bloom and clip at white. Highlights saturate toward pure hues.
67    Clamp = 0,
68    /// Identity for ordinary colors; bloom and over-bright values roll off
69    /// softly toward white (`1 - (1 - c) * exp(-glow)`). Preserves the
70    /// authored palette exactly where nothing glows.
71    #[default]
72    Soft = 1,
73    /// ACES-style filmic curve (Narkowicz fit) applied in approximately
74    /// linear light (display gamma 2.2). Mid-grey 0.5 maps to about 0.6 and
75    /// white to about 0.9, rolling highlights and bloom off smoothly.
76    Filmic = 2,
77}
78
79/// Effective post-processing tier after preferences, accessibility and adaptive
80/// performance are applied.
81#[repr(u32)]
82#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
83pub enum PostTier {
84    /// Direct rendering; no offscreen target or extra pass.
85    #[default]
86    Off = 0,
87    /// Four bloom levels starting at half resolution.
88    Medium = 1,
89    /// Five bloom levels starting at half resolution.
90    High = 2,
91}
92
93/// Authored post-processing settings. Start from a preset and adjust with the
94/// builder methods. Values are sanitized when applied: non-finite numbers use
95/// the neutral value and every field is clamped to its documented range.
96///
97/// ```
98/// use ferravex_render::post::{PostFx, Tonemap};
99/// let fx = PostFx::subtle()
100///     .bloom(0.5, 0.7, 1.2)
101///     .tint(ferravex_render::Color::new(1.05, 1., 0.92, 1.))
102///     .vignette(0.3, 0.5)
103///     .tonemap(Tonemap::Soft);
104/// assert!(!fx.is_off());
105/// assert!(PostFx::off().is_off());
106/// ```
107#[derive(Clone, Copy, Debug, PartialEq)]
108pub struct PostFx {
109    /// Bloom strength, 0–8. Zero skips the bloom chain. The chain is
110    /// normalized by its level count, so a value keeps the same overall
111    /// energy on Medium and High; small bright shapes need roughly 1–3 for a
112    /// clearly visible halo.
113    pub bloom_intensity: f32,
114    /// Brightness (max RGB channel) where bloom starts, 0–4.
115    pub bloom_threshold: f32,
116    /// Soft-threshold width around the threshold, 0–1.
117    pub bloom_knee: f32,
118    /// Upsample filter spread, 0.25–3. One is the dual-filter default.
119    pub bloom_radius: f32,
120    pub tonemap: Tonemap,
121    /// Scene multiplier before tonemapping, 0–8.
122    pub exposure: f32,
123    /// Power-law contrast around mid-grey (`0.5 * (2c)^contrast`), 0–2.
124    /// Black stays black, so dark palettes keep their relative detail.
125    pub contrast: f32,
126    /// Saturation, 0 (greyscale) – 2.
127    pub saturation: f32,
128    /// Shadow lift per channel, -0.5–0.5.
129    pub lift: [f32; 3],
130    /// Midtone gamma per channel, 0.2–5. Above one brightens.
131    pub gamma: [f32; 3],
132    /// Highlight gain (tint) per channel, 0–4.
133    pub gain: [f32; 3],
134    /// Corner darkening, 0–1.
135    pub vignette: f32,
136    /// Vignette falloff width, 0.05 (tight corners) – 1 (from the center).
137    pub vignette_softness: f32,
138    /// Animated film grain amplitude, 0–0.25. Default off.
139    pub grain: f32,
140    /// Radial chromatic aberration, 0–1 (1 ≈ 1% of the screen). Default off.
141    pub aberration: f32,
142    /// Scanline darkening, 0–1, one line every three logical pixels. Default off.
143    pub scanlines: f32,
144    /// Treat `set_world_colors(false)` / `set_default_camera()` as the HUD
145    /// boundary. Default true.
146    pub auto_hud: bool,
147}
148
149impl Default for PostFx {
150    fn default() -> Self {
151        Self::off()
152    }
153}
154
155impl PostFx {
156    /// Neutral settings: no post-processing and no extra GPU work.
157    pub const fn off() -> Self {
158        Self {
159            bloom_intensity: 0.,
160            bloom_threshold: 0.8,
161            bloom_knee: 0.25,
162            bloom_radius: 1.,
163            tonemap: Tonemap::Soft,
164            exposure: 1.,
165            contrast: 1.,
166            saturation: 1.,
167            lift: [0.; 3],
168            gamma: [1.; 3],
169            gain: [1.; 3],
170            vignette: 0.,
171            vignette_softness: 0.6,
172            grain: 0.,
173            aberration: 0.,
174            scanlines: 0.,
175            auto_hud: true,
176        }
177    }
178    /// Gentle glow on the brightest pixels, slight contrast/saturation and a
179    /// light vignette. Unlit areas keep their authored colors.
180    pub const fn subtle() -> Self {
181        let mut fx = Self::off();
182        fx.bloom_intensity = 0.9;
183        fx.bloom_threshold = 0.78;
184        fx.bloom_knee = 0.25;
185        fx.bloom_radius = 1.;
186        fx.contrast = 1.04;
187        fx.saturation = 1.06;
188        fx.vignette = 0.2;
189        fx.vignette_softness = 0.55;
190        fx
191    }
192    /// Strong, wide glow for dark scenes with saturated emissive shapes.
193    pub const fn neon() -> Self {
194        let mut fx = Self::off();
195        fx.bloom_intensity = 2.4;
196        fx.bloom_threshold = 0.5;
197        fx.bloom_knee = 0.3;
198        fx.bloom_radius = 1.35;
199        fx.contrast = 1.08;
200        fx.saturation = 1.18;
201        fx.vignette = 0.32;
202        fx.vignette_softness = 0.6;
203        fx
204    }
205    /// Filmic curve, warm highlights, lifted shadows, soft vignette and a hint
206    /// of grain.
207    pub const fn warm_film() -> Self {
208        let mut fx = Self::off();
209        fx.bloom_intensity = 0.8;
210        fx.bloom_threshold = 0.75;
211        fx.bloom_knee = 0.25;
212        fx.bloom_radius = 1.15;
213        fx.tonemap = Tonemap::Filmic;
214        fx.exposure = 1.;
215        fx.contrast = 1.06;
216        fx.saturation = 0.94;
217        fx.lift = [0.025, 0.014, 0.];
218        fx.gain = [1.05, 0.99, 0.9];
219        fx.vignette = 0.38;
220        fx.vignette_softness = 0.65;
221        fx.grain = 0.03;
222        fx
223    }
224    /// Arcade monitor: scanlines, light aberration, bloom and a deep vignette.
225    pub const fn crt() -> Self {
226        let mut fx = Self::off();
227        fx.bloom_intensity = 1.5;
228        fx.bloom_threshold = 0.6;
229        fx.bloom_knee = 0.3;
230        fx.bloom_radius = 1.2;
231        fx.contrast = 1.06;
232        fx.saturation = 1.1;
233        fx.vignette = 0.45;
234        fx.vignette_softness = 0.5;
235        fx.aberration = 0.25;
236        fx.scanlines = 0.3;
237        fx
238    }
239    /// Preset by name: `off`, `subtle`, `neon`, `warm-film` (or `warm_film`), `crt`.
240    pub fn from_name(name: &str) -> Option<Self> {
241        Self::from_index(match name {
242            "off" => 0,
243            "subtle" => 1,
244            "neon" => 2,
245            "warm-film" | "warm_film" => 3,
246            "crt" => 4,
247            _ => return None,
248        })
249    }
250    /// Preset by index in [`from_name`](Self::from_name) order.
251    pub fn from_index(index: u32) -> Option<Self> {
252        Some(match index {
253            0 => Self::off(),
254            1 => Self::subtle(),
255            2 => Self::neon(),
256            3 => Self::warm_film(),
257            4 => Self::crt(),
258            _ => return None,
259        })
260    }
261    pub const fn bloom(mut self, intensity: f32, threshold: f32, radius: f32) -> Self {
262        self.bloom_intensity = intensity;
263        self.bloom_threshold = threshold;
264        self.bloom_radius = radius;
265        self
266    }
267    pub const fn bloom_knee(mut self, knee: f32) -> Self {
268        self.bloom_knee = knee;
269        self
270    }
271    pub const fn tonemap(mut self, tonemap: Tonemap) -> Self {
272        self.tonemap = tonemap;
273        self
274    }
275    pub const fn exposure(mut self, exposure: f32) -> Self {
276        self.exposure = exposure;
277        self
278    }
279    pub const fn contrast(mut self, contrast: f32) -> Self {
280        self.contrast = contrast;
281        self
282    }
283    pub const fn saturation(mut self, saturation: f32) -> Self {
284        self.saturation = saturation;
285        self
286    }
287    pub const fn lift_gamma_gain(
288        mut self,
289        lift: [f32; 3],
290        gamma: [f32; 3],
291        gain: [f32; 3],
292    ) -> Self {
293        self.lift = lift;
294        self.gamma = gamma;
295        self.gain = gain;
296        self
297    }
298    /// Multiply highlights by a color (sets `gain`).
299    pub const fn tint(mut self, tint: Color) -> Self {
300        self.gain = [tint.r, tint.g, tint.b];
301        self
302    }
303    pub const fn vignette(mut self, strength: f32, softness: f32) -> Self {
304        self.vignette = strength;
305        self.vignette_softness = softness;
306        self
307    }
308    pub const fn grain(mut self, amount: f32) -> Self {
309        self.grain = amount;
310        self
311    }
312    pub const fn aberration(mut self, amount: f32) -> Self {
313        self.aberration = amount;
314        self
315    }
316    pub const fn scanlines(mut self, amount: f32) -> Self {
317        self.scanlines = amount;
318        self
319    }
320    pub const fn auto_hud(mut self, enabled: bool) -> Self {
321        self.auto_hud = enabled;
322        self
323    }
324    /// Clamp every field to its documented range; non-finite values become neutral.
325    pub fn sanitized(self) -> Self {
326        let n = Self::off();
327        let f = |v: f32, neutral: f32, lo: f32, hi: f32| {
328            if v.is_finite() {
329                v.clamp(lo, hi)
330            } else {
331                neutral
332            }
333        };
334        let rgb = |v: [f32; 3], neutral: [f32; 3], lo: f32, hi: f32| {
335            [
336                f(v[0], neutral[0], lo, hi),
337                f(v[1], neutral[1], lo, hi),
338                f(v[2], neutral[2], lo, hi),
339            ]
340        };
341        Self {
342            bloom_intensity: f(self.bloom_intensity, 0., 0., 8.),
343            bloom_threshold: f(self.bloom_threshold, n.bloom_threshold, 0., 4.),
344            bloom_knee: f(self.bloom_knee, n.bloom_knee, 0., 1.),
345            bloom_radius: f(self.bloom_radius, 1., 0.25, 3.),
346            tonemap: self.tonemap,
347            exposure: f(self.exposure, 1., 0., 8.),
348            contrast: f(self.contrast, 1., 0., 2.),
349            saturation: f(self.saturation, 1., 0., 2.),
350            lift: rgb(self.lift, n.lift, -0.5, 0.5),
351            gamma: rgb(self.gamma, n.gamma, 0.2, 5.),
352            gain: rgb(self.gain, n.gain, 0., 4.),
353            vignette: f(self.vignette, 0., 0., 1.),
354            vignette_softness: f(self.vignette_softness, n.vignette_softness, 0.05, 1.),
355            grain: f(self.grain, 0., 0., 0.25),
356            aberration: f(self.aberration, 0., 0., 1.),
357            scanlines: f(self.scanlines, 0., 0., 1.),
358            auto_hud: self.auto_hud,
359        }
360    }
361    /// True when the sanitized settings are the identity image transform, so
362    /// hosts keep their direct path. `Filmic` is never the identity.
363    pub fn is_off(&self) -> bool {
364        let s = self.sanitized();
365        s.bloom_intensity == 0.
366            && s.tonemap != Tonemap::Filmic
367            && s.exposure == 1.
368            && s.contrast == 1.
369            && s.saturation == 1.
370            && s.lift == [0.; 3]
371            && s.gamma == [1.; 3]
372            && s.gain == [1.; 3]
373            && s.vignette == 0.
374            && s.grain == 0.
375            && s.aberration == 0.
376            && s.scanlines == 0.
377    }
378}
379
380/// Effective post-processing state for the current settings and preferences.
381#[derive(Clone, Copy, Debug, Default, PartialEq)]
382pub struct PostStatus {
383    pub tier: PostTier,
384    /// Bloom chain length (0 when bloom is disabled or the tier is Off).
385    pub bloom_levels: u8,
386    /// Settings after accessibility caps (equal to the authored settings,
387    /// sanitized, unless reduced flash applies).
388    pub effective: PostFx,
389    /// A HUD boundary has been recorded in the current frame.
390    pub hud_started: bool,
391}
392
393/// Replace the sticky post-processing settings. Takes effect for the current
394/// frame's composite; use [`PostFx::off()`] to return to direct rendering.
395pub fn set_post_fx(fx: PostFx) {
396    crate::edit(|s| s.post = fx);
397}
398/// Current authored settings (before session overrides and preferences).
399pub fn post_fx() -> PostFx {
400    crate::read(|s| s.post)
401}
402/// Effective tier, bloom levels and capped settings for the current state.
403pub fn post_fx_status() -> PostStatus {
404    crate::read(|s| {
405        let (tier, effective) = s.post_effective();
406        PostStatus {
407            tier,
408            bloom_levels: levels(tier, &effective),
409            effective,
410            hud_started: s.post_hud,
411        }
412    })
413}
414/// Mark the world/HUD boundary explicitly. Draws after this call go straight to
415/// the screen on top of the post-processed world. Returns true when this call
416/// recorded the frame's boundary; false if post-processing is off or a
417/// boundary already exists in this frame.
418pub fn post_fx_hud_begin() -> bool {
419    crate::edit(|s| s.post_boundary())
420}
421/// Draw immediate primitives (rectangles, circles, lines, text, meshes) with
422/// additive blending inside `draw`, so bright shapes accumulate light and feed
423/// the bloom. Equivalent to `EffectBlend::Additive` for immediate geometry;
424/// works with post-processing off as plain additive blending.
425///
426/// ```
427/// use ferravex_render::{input, post, draw_circle, Color};
428/// input::host_frame(1. / 60., 64, 64, || {
429///     post::with_glow(|| draw_circle(32., 32., 6., Color::new(1., 0.6, 0.2, 0.8)));
430/// });
431/// ```
432pub fn with_glow<T>(draw: impl FnOnce() -> T) -> T {
433    let previous = crate::edit(|s| std::mem::replace(&mut s.glow, true));
434    struct Restore(bool);
435    impl Drop for Restore {
436        fn drop(&mut self) {
437            let previous = self.0;
438            crate::edit(|s| s.glow = previous);
439        }
440    }
441    let _restore = Restore(previous);
442    draw()
443}
444const GLOW_SEGMENTS: usize = 16;
445/// Radius fraction and alpha: a Gaussian-like falloff (`exp(-4.5 r²)`), zero at the rim.
446const GLOW_RINGS: [(f32, f32); 5] = [(0., 1.), (0.25, 0.76), (0.5, 0.32), (0.75, 0.08), (1., 0.)];
447/// Soft additive radial glow in the current camera's 2D coordinates (z = 0).
448/// `intensity` multiplies RGB and may exceed one: over-bright values bloom
449/// more strongly on half-float targets. Uses 112 unlit triangles; the world
450/// palette still applies inside a world camera.
451pub fn glow_circle(x: f32, y: f32, radius: f32, color: Color, intensity: f32) {
452    if ![x, y, radius, intensity].iter().all(|v| v.is_finite()) || radius <= 0. || intensity <= 0. {
453        return;
454    }
455    let rgb = [
456        color.r * intensity,
457        color.g * intensity,
458        color.b * intensity,
459    ];
460    // Shared unit-circle table: the same angles without per-vertex trig.
461    let units = crate::shapes::unit_circle(GLOW_SEGMENTS).unwrap_or(&[]);
462    let ring = |ring: usize, segment: usize| {
463        let (fraction, alpha) = GLOW_RINGS[ring];
464        let unit = units[segment];
465        (
466            Vec3::new(
467                x + unit.x * radius * fraction,
468                y + unit.y * radius * fraction,
469                0.,
470            ),
471            Vec3::Z,
472            Color::new(rgb[0], rgb[1], rgb[2], color.a * alpha),
473        )
474    };
475    crate::edit(|s| {
476        let glow = std::mem::replace(&mut s.glow, true);
477        let lighting = s.lighting.take();
478        let triangles = (0..GLOW_SEGMENTS).flat_map(|i| {
479            let j = (i + 1) % GLOW_SEGMENTS;
480            let fan = [ring(0, i), ring(1, i), ring(1, j)];
481            let bands = (1..GLOW_RINGS.len() - 1).flat_map(move |r| {
482                [
483                    ring(r, i),
484                    ring(r + 1, i),
485                    ring(r + 1, j),
486                    ring(r, i),
487                    ring(r + 1, j),
488                    ring(r, j),
489                ]
490            });
491            fan.into_iter().chain(bands)
492        });
493        s.push(triangles, Mat4::IDENTITY);
494        s.lighting = lighting;
495        s.glow = glow;
496    });
497}
498
499fn levels(tier: PostTier, fx: &PostFx) -> u8 {
500    match tier {
501        PostTier::Off => 0,
502        _ if fx.bloom_intensity <= 0. => 0,
503        PostTier::Medium => 4,
504        PostTier::High => MAX_BLOOM_LEVELS as u8,
505    }
506}
507
508/// Tier from authored settings plus the player's explicit quality choice
509/// (`None` follows the authored quality) and adaptive-performance level.
510pub(crate) fn tier(
511    fx: &PostFx,
512    choice: Option<Quality>,
513    authored: Quality,
514    adaptive: Option<u8>,
515) -> PostTier {
516    if fx.is_off() {
517        return PostTier::Off;
518    }
519    let tier = match choice {
520        Some(Quality::Low) => PostTier::Off,
521        Some(Quality::Medium) => PostTier::Medium,
522        Some(Quality::High) => PostTier::High,
523        None if authored == Quality::High => PostTier::High,
524        None => PostTier::Medium,
525    };
526    if adaptive.is_some_and(|level| level >= 2) {
527        tier.min(PostTier::Medium)
528    } else {
529        tier
530    }
531}
532
533/// Apply accessibility caps to sanitized settings.
534pub(crate) fn accessible(fx: PostFx, reduced_flash: bool) -> PostFx {
535    let mut fx = fx.sanitized();
536    if reduced_flash {
537        fx.bloom_intensity = fx.bloom_intensity.min(REDUCED_FLASH_BLOOM);
538        fx.grain = 0.;
539        fx.aberration = 0.;
540    }
541    fx
542}
543
544/// Pack the host uniform block (seven vec4 values). Index 0 is the tier; zero
545/// means hosts render directly. See `docs/VISUALS.md` for the layout.
546pub(crate) fn pack(
547    tier: PostTier,
548    fx: &PostFx,
549    frame: u64,
550    reduced_motion: bool,
551    dpi: f32,
552) -> [f32; POST_FRAME_FLOATS] {
553    if tier == PostTier::Off {
554        return [0.; POST_FRAME_FLOATS];
555    }
556    let seed = if reduced_motion {
557        0.
558    } else {
559        (frame % 1024) as f32
560    };
561    let dpi = if dpi.is_finite() {
562        dpi.clamp(0.25, 8.)
563    } else {
564        1.
565    };
566    [
567        tier as u32 as f32,
568        levels(tier, fx) as f32,
569        seed,
570        fx.tonemap as u32 as f32,
571        fx.bloom_intensity,
572        fx.bloom_threshold,
573        fx.bloom_knee,
574        fx.bloom_radius,
575        fx.exposure,
576        fx.contrast,
577        fx.saturation,
578        fx.vignette,
579        fx.lift[0],
580        fx.lift[1],
581        fx.lift[2],
582        fx.vignette_softness,
583        fx.gamma[0],
584        fx.gamma[1],
585        fx.gamma[2],
586        fx.grain,
587        fx.gain[0],
588        fx.gain[1],
589        fx.gain[2],
590        fx.aberration,
591        fx.scanlines,
592        (3. * dpi).max(2.),
593        0.,
594        0.,
595    ]
596}
597
598/// Full-screen triangle; no vertex attributes. Hosts prepend their GLSL
599/// version/precision header.
600pub const POST_VERTEX_BODY: &str = r#"
601out vec2 v_uv;
602void main(){vec2 p=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));v_uv=p;gl_Position=vec4(p*2.-1.,0.,1.);}
603"#;
604/// Dual-filter downsample. `u_texel.xy` is the source texel size; `u_texel.z`
605/// selects the bright-pass prefilter (threshold `u_bloom.x`, knee `u_bloom.y`).
606pub const POST_DOWN_FRAGMENT_BODY: &str = r#"
607in vec2 v_uv;
608out vec4 ferravex_pixel;
609uniform sampler2D u_source;
610uniform vec4 u_texel;
611uniform vec4 u_bloom;
612void main(){
613 vec2 o=u_texel.xy;
614 vec3 c=texture(u_source,v_uv).rgb*4.;
615 c+=texture(u_source,v_uv-o).rgb;
616 c+=texture(u_source,v_uv+o).rgb;
617 c+=texture(u_source,v_uv+vec2(o.x,-o.y)).rgb;
618 c+=texture(u_source,v_uv-vec2(o.x,-o.y)).rgb;
619 c*=0.125;
620 if(u_texel.z>0.5){
621  float b=max(c.r,max(c.g,c.b));
622  float k=max(u_bloom.y,0.0001);
623  float s=clamp(b-u_bloom.x+k,0.,2.*k);
624  s=s*s/(4.*k);
625  c*=max(s,b-u_bloom.x)/max(b,0.0001);
626 }
627 ferravex_pixel=vec4(max(c,vec3(0.)),1.);
628}
629"#;
630/// Dual-filter tent upsample. `u_texel.xy` is the source texel size and
631/// `u_texel.z` the radius; hosts additively blend into the larger level.
632pub const POST_UP_FRAGMENT_BODY: &str = r#"
633in vec2 v_uv;
634out vec4 ferravex_pixel;
635uniform sampler2D u_source;
636uniform vec4 u_texel;
637void main(){
638 vec2 o=u_texel.xy*u_texel.z;
639 vec3 c=texture(u_source,v_uv+vec2(-2.*o.x,0.)).rgb;
640 c+=texture(u_source,v_uv+vec2(-o.x,o.y)).rgb*2.;
641 c+=texture(u_source,v_uv+vec2(0.,2.*o.y)).rgb;
642 c+=texture(u_source,v_uv+vec2(o.x,o.y)).rgb*2.;
643 c+=texture(u_source,v_uv+vec2(2.*o.x,0.)).rgb;
644 c+=texture(u_source,v_uv+vec2(o.x,-o.y)).rgb*2.;
645 c+=texture(u_source,v_uv+vec2(0.,-2.*o.y)).rgb;
646 c+=texture(u_source,v_uv+vec2(-o.x,-o.y)).rgb*2.;
647 ferravex_pixel=vec4(c/12.,1.);
648}
649"#;
650/// Final composite: bloom upsample, exposure, tonemap, lift/gamma/gain,
651/// power-law contrast, saturation, vignette, scanlines, grain and a static
652/// sub-LSB dither (interleaved gradient noise) against 8-bit banding. `u_texel.xy` is the
653/// bloom texel size and `u_texel.zw` the scene texel size.
654pub const POST_COMPOSITE_FRAGMENT_BODY: &str = r#"
655in vec2 v_uv;
656out vec4 ferravex_pixel;
657uniform sampler2D u_scene;
658uniform sampler2D u_bloom;
659uniform vec4 u_texel;
660uniform vec4 u_post[7];
661vec3 ferravex_bloom(vec2 uv){
662 vec2 o=u_texel.xy*u_post[1].w;
663 vec3 c=texture(u_bloom,uv+vec2(-2.*o.x,0.)).rgb;
664 c+=texture(u_bloom,uv+vec2(-o.x,o.y)).rgb*2.;
665 c+=texture(u_bloom,uv+vec2(0.,2.*o.y)).rgb;
666 c+=texture(u_bloom,uv+vec2(o.x,o.y)).rgb*2.;
667 c+=texture(u_bloom,uv+vec2(2.*o.x,0.)).rgb;
668 c+=texture(u_bloom,uv+vec2(o.x,-o.y)).rgb*2.;
669 c+=texture(u_bloom,uv+vec2(0.,-2.*o.y)).rgb;
670 c+=texture(u_bloom,uv+vec2(-o.x,-o.y)).rgb*2.;
671 return c/12.;
672}
673float ferravex_noise(vec2 p){return fract(52.9829189*fract(dot(p,vec2(0.06711056,0.00583715))));}
674vec3 ferravex_filmic(vec3 x){return clamp(x*(2.51*x+0.03)/(x*(2.43*x+0.59)+0.14),0.,1.);}
675void main(){
676 vec2 uv=v_uv;
677 vec3 scene;
678 if(u_post[5].w>0.){
679  vec2 d=(uv-0.5)*u_post[5].w*0.02;
680  scene=vec3(texture(u_scene,uv+d).r,texture(u_scene,uv).g,texture(u_scene,uv-d).b);
681 }else scene=texture(u_scene,uv).rgb;
682 vec3 glow=vec3(0.);
683 if(u_post[0].y>0.5)glow=ferravex_bloom(uv)*(u_post[1].x/u_post[0].y);
684 vec3 c=max(scene*u_post[2].x,vec3(0.));
685 if(u_post[0].w>1.5)c=pow(ferravex_filmic(pow(c+glow,vec3(2.2))),vec3(1./2.2));
686 else if(u_post[0].w>0.5)c=1.-(1.-min(c,vec3(1.)))*exp(-(glow+max(c-1.,vec3(0.))));
687 else c=min(c+glow,vec3(1.));
688 c=clamp(u_post[5].rgb*(c+u_post[3].rgb*(1.-c)),0.,1.);
689 c=pow(c,1./max(u_post[4].rgb,vec3(0.01)));
690 c=0.5*pow(c*2.,vec3(u_post[2].y));
691 float luma=dot(c,vec3(0.2126,0.7152,0.0722));
692 c=mix(vec3(luma),c,u_post[2].z);
693 if(u_post[2].w>0.){
694  float aspect=u_texel.w/u_texel.z;
695  vec2 q=(uv-0.5)*vec2(aspect,1.);
696  float d=length(q)/length(vec2(aspect,1.)*0.5);
697  c*=1.-u_post[2].w*smoothstep(1.-u_post[3].w,1.,d);
698 }
699 if(u_post[6].x>0.)c*=1.-u_post[6].x*(0.5-0.5*cos(gl_FragCoord.y*6.2831853/u_post[6].y));
700 if(u_post[4].w>0.){
701  vec2 p=gl_FragCoord.xy+5.588238*u_post[0].z;
702  c+=(ferravex_noise(p)-0.5)*u_post[4].w;
703 }
704 // Static sub-LSB dither hides 8-bit banding in dark vignette/bloom gradients.
705 c+=(ferravex_noise(gl_FragCoord.xy+vec2(37.,17.))-0.5)/255.;
706 ferravex_pixel=vec4(clamp(c,0.,1.),1.);
707}
708"#;
709
710#[cfg(test)]
711mod tests {
712    use super::*;
713    use crate::{input::host_frame, retained::Command};
714
715    fn reset() {
716        crate::edit(|s| *s = crate::State::default());
717        crate::preferences::set_feedback_policy(Default::default());
718    }
719    fn kinds() -> Vec<u32> {
720        crate::read(|s| {
721            s.retained
722                .commands
723                .iter()
724                .map(|c: &Command| c.kind)
725                .collect()
726        })
727    }
728
729    #[test]
730    fn presets_sanitize_and_off_is_identity() {
731        for name in ["off", "subtle", "neon", "warm-film", "crt"] {
732            let fx = PostFx::from_name(name).unwrap();
733            assert_eq!(fx.sanitized(), fx, "{name} preset is in range");
734            assert_eq!(fx.is_off(), name == "off");
735        }
736        assert_eq!(PostFx::from_name("warm_film"), Some(PostFx::warm_film()));
737        assert_eq!(PostFx::from_name("bright"), None);
738        assert_eq!(PostFx::default(), PostFx::off());
739        let wild = PostFx::off()
740            .bloom(f32::NAN, 9., -1.)
741            .exposure(f32::INFINITY)
742            .vignette(3., 0.)
743            .grain(1.)
744            .lift_gamma_gain([-2.; 3], [0.; 3], [9.; 3]);
745        let s = wild.sanitized();
746        assert_eq!(
747            (s.bloom_intensity, s.bloom_threshold, s.bloom_radius),
748            (0., 4., 0.25)
749        );
750        assert_eq!(
751            (s.exposure, s.vignette, s.vignette_softness),
752            (1., 1., 0.05)
753        );
754        assert_eq!(
755            (s.grain, s.lift, s.gamma, s.gain),
756            (0.25, [-0.5; 3], [0.2; 3], [4.; 3])
757        );
758        // A filmic curve alone is not the identity transform.
759        assert!(!PostFx::off().tonemap(Tonemap::Filmic).is_off());
760        assert!(PostFx::off().tonemap(Tonemap::Clamp).is_off());
761    }
762
763    #[test]
764    fn quality_preferences_and_adaptive_pressure_select_tiers() {
765        let fx = PostFx::neon();
766        assert_eq!(
767            tier(&PostFx::off(), Some(Quality::High), Quality::High, None),
768            PostTier::Off
769        );
770        assert_eq!(
771            tier(&fx, Some(Quality::Low), Quality::High, None),
772            PostTier::Off
773        );
774        assert_eq!(
775            tier(&fx, Some(Quality::Medium), Quality::High, None),
776            PostTier::Medium
777        );
778        assert_eq!(
779            tier(&fx, Some(Quality::High), Quality::Low, None),
780            PostTier::High
781        );
782        // Authored Low (the engine default) does not disable an opted-in game.
783        assert_eq!(tier(&fx, None, Quality::Low, None), PostTier::Medium);
784        assert_eq!(tier(&fx, None, Quality::High, None), PostTier::High);
785        assert_eq!(tier(&fx, None, Quality::High, Some(1)), PostTier::High);
786        assert_eq!(tier(&fx, None, Quality::High, Some(2)), PostTier::Medium);
787        assert_eq!(levels(PostTier::Medium, &fx), 4);
788        assert_eq!(levels(PostTier::High, &fx), 5);
789        assert_eq!(levels(PostTier::High, &PostFx::off().vignette(0.3, 0.5)), 0);
790    }
791
792    #[test]
793    fn reduced_flash_caps_bloom_and_disables_grain_and_aberration() {
794        let fx = PostFx::crt().bloom(3., 0.5, 1.).grain(0.1);
795        let capped = accessible(fx, true);
796        assert_eq!(capped.bloom_intensity, REDUCED_FLASH_BLOOM);
797        assert_eq!((capped.grain, capped.aberration), (0., 0.));
798        assert_eq!(capped.scanlines, fx.scanlines);
799        assert_eq!(accessible(fx, false), fx.sanitized());
800        let packed = pack(PostTier::High, &capped, 7, false, 2.);
801        assert_eq!(&packed[..4], &[2., 5., 7., 1.]);
802        assert_eq!(packed[4], REDUCED_FLASH_BLOOM);
803        assert_eq!(packed[25], 6.);
804        assert_eq!(
805            pack(PostTier::High, &capped, 7, true, 1.)[2],
806            0.,
807            "static grain"
808        );
809        assert_eq!(
810            pack(PostTier::Off, &capped, 7, false, 1.),
811            [0.; POST_FRAME_FLOATS]
812        );
813    }
814
815    #[test]
816    fn hud_boundary_follows_world_palette_rules_once_per_frame() {
817        reset();
818        // Off: no boundary command and an all-zero host block.
819        host_frame(1. / 60., 64, 64, || {
820            crate::set_camera(&crate::Camera2D::default());
821            crate::draw_rectangle(0., 0., 1., 1., crate::WHITE);
822            crate::set_default_camera();
823            assert!(!post_fx_hud_begin());
824            crate::draw_rectangle(0., 0., 1., 1., crate::WHITE);
825        });
826        assert!(!kinds().contains(&4));
827        assert_eq!(crate::read(|s| s.retained.post), [0.; POST_FRAME_FLOATS]);
828
829        set_post_fx(PostFx::subtle());
830        host_frame(1. / 60., 64, 64, || {
831            // Default-camera drawing before any world camera is world content.
832            crate::draw_rectangle(0., 0., 1., 1., crate::WHITE);
833            crate::set_default_camera();
834            crate::set_camera(&crate::Camera2D::default());
835            crate::draw_rectangle(0., 0., 1., 1., crate::WHITE);
836            crate::set_default_camera();
837            crate::draw_rectangle(0., 0., 1., 1., crate::WHITE);
838            crate::set_camera(&crate::Camera2D::default());
839            crate::set_default_camera();
840            assert!(!post_fx_hud_begin(), "only the first boundary counts");
841            assert!(post_fx_status().hud_started);
842        });
843        assert_eq!(kinds(), [0, 4, 0]);
844        let block = crate::read(|s| s.retained.post);
845        assert_eq!((block[0], block[1]), (1., 4.), "medium by default");
846
847        host_frame(1. / 60., 64, 64, || {
848            crate::set_world_colors(true);
849            crate::draw_rectangle(0., 0., 1., 1., crate::WHITE);
850            crate::set_world_colors(false);
851            crate::draw_rectangle(0., 0., 1., 1., crate::WHITE);
852        });
853        assert_eq!(kinds(), [0, 4, 0], "set_world_colors(false) is a boundary");
854
855        set_post_fx(PostFx::subtle().auto_hud(false));
856        host_frame(1. / 60., 64, 64, || {
857            crate::set_camera(&crate::Camera2D::default());
858            crate::draw_rectangle(0., 0., 1., 1., crate::WHITE);
859            crate::set_default_camera();
860            crate::draw_rectangle(0., 0., 1., 1., crate::WHITE);
861            assert!(!post_fx_status().hud_started);
862            assert!(post_fx_hud_begin());
863            crate::draw_rectangle(0., 0., 1., 1., crate::WHITE);
864            // clear_background restarts the frame's command stream.
865            crate::clear_background(crate::BLACK);
866            assert!(!post_fx_status().hud_started);
867        });
868        assert!(kinds().is_empty());
869        reset();
870    }
871
872    #[test]
873    fn preferences_resolve_the_host_block_each_frame() {
874        reset();
875        set_post_fx(PostFx::warm_film());
876        crate::set_quality(Quality::High);
877        host_frame(1. / 60., 64, 64, || {});
878        assert_eq!(crate::read(|s| s.retained.post[0]), 2.);
879        crate::set_quality_preference(Some(Quality::Low));
880        host_frame(1. / 60., 64, 64, || {
881            crate::set_camera(&crate::Camera2D::default());
882            crate::set_default_camera();
883        });
884        assert_eq!(crate::read(|s| s.retained.post), [0.; POST_FRAME_FLOATS]);
885        assert!(!kinds().contains(&4), "no boundary while effectively off");
886        crate::set_quality_preference(None);
887        let policy = ferravex_play::feedback::FeedbackPolicy::new(false, true, 1.).unwrap();
888        crate::preferences::set_feedback_policy(policy);
889        host_frame(1. / 60., 64, 64, || {});
890        let block = crate::read(|s| s.retained.post);
891        assert_eq!(
892            (block[0], block[19], block[23]),
893            (2., 0., 0.),
894            "grain/aberration off"
895        );
896        assert!(block[4] <= REDUCED_FLASH_BLOOM);
897        // Session override wins over authored settings, including `off`.
898        crate::edit(|s| s.post_override = Some(PostFx::off()));
899        host_frame(1. / 60., 64, 64, || {});
900        assert_eq!(crate::read(|s| s.retained.post[0]), 0.);
901        reset();
902    }
903
904    #[test]
905    fn glow_draws_are_additive_effect_batches_and_restore_state() {
906        reset();
907        host_frame(1. / 60., 64, 64, || {
908            crate::draw_rectangle(0., 0., 4., 4., crate::WHITE);
909            with_glow(|| {
910                crate::draw_rectangle(0., 0., 4., 4., crate::WHITE);
911                crate::draw_circle(8., 8., 2., crate::RED);
912            });
913            glow_circle(32., 32., 10., crate::ORANGE, 2.);
914            glow_circle(32., 32., f32::NAN, crate::ORANGE, 2.);
915            crate::draw_rectangle(0., 0., 4., 4., crate::WHITE);
916        });
917        assert_eq!(kinds(), [0, 2, 0]);
918        crate::read(|s| {
919            let batch = s.retained.effects[0];
920            assert_eq!(batch.flags, 2 | 4, "additive, no depth write");
921            assert!(batch.count >= 6 + 112 * 3);
922            // Glow color keeps its over-bright intensity.
923            let end = (batch.start + batch.count) as usize;
924            assert!(s.vertices[end - 1][4..7].iter().any(|&c| c > 1.));
925            assert!(!s.glow);
926        });
927        reset();
928    }
929}