Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_display/
brightness.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! The BRIGHTNESS option: a signed step around the picture as drawn.
3//!
4//! The row reads `DEFAULT` at the centre, `DARKER 1` to `DARKER 5` to the left
5//! and `BRIGHTER 1` to `BRIGHTER 5` to the right. The GPU has no gamma, so a
6//! step is applied as one semi-transparent grey rectangle over the finished
7//! frame ([`BrightnessOverlay`]): subtracted to darken, added to brighten. At
8//! the centre nothing is drawn, so the default frame is the frame as drawn and
9//! the setting costs nothing.
10
11use psx_gpu::display::Resolution;
12use psx_gpu::prim::GpuPacket;
13use psx_hw::gpu::{gp0, packet};
14
15use crate::label::Label;
16
17/// Grey (of 255) the overlay carries per step, either way. The GPU blends in
18/// five bits per channel and a rectangle's grey is its top five bits, so 8 is
19/// the smallest grey that changes the picture by one blend unit: every step
20/// moves it by exactly one more than the step before.
21const GAIN_PER_STEP: u8 = 8;
22
23/// GP0(E1h) semi-transparency field value for `background + foreground`.
24const BLEND_ADD: u32 = 1;
25/// GP0(E1h) semi-transparency field value for `background - foreground`.
26const BLEND_SUBTRACT: u32 = 2;
27
28/// The BRIGHTNESS setting: [`Brightness::MIN`] to [`Brightness::MAX`], where
29/// [`Brightness::DEFAULT`] (zero) is the picture as drawn.
30///
31/// ```
32/// use psx_display::Brightness;
33/// let mut brightness = Brightness::DEFAULT;
34/// brightness = brightness.stepped(1);
35/// assert_eq!(brightness.label().as_str(), "BRIGHTER 1");
36/// brightness = brightness.stepped(-3);
37/// assert_eq!(brightness.label().as_str(), "DARKER 2");
38/// ```
39#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
40pub struct Brightness(i8);
41
42impl Brightness {
43    /// Steps either side of the picture as drawn.
44    pub const STEP_COUNT: i8 = 5;
45    /// The darkest step.
46    pub const MIN: Self = Self(-Self::STEP_COUNT);
47    /// The brightest step.
48    pub const MAX: Self = Self(Self::STEP_COUNT);
49    /// The picture as drawn.
50    pub const DEFAULT: Self = Self(0);
51
52    /// The step `level`: negative is darker, positive brighter. A level
53    /// outside [`MIN`](Self::MIN) to [`MAX`](Self::MAX) is clamped.
54    pub const fn new(level: i8) -> Self {
55        if level < -Self::STEP_COUNT {
56            Self::MIN
57        } else if level > Self::STEP_COUNT {
58            Self::MAX
59        } else {
60            Self(level)
61        }
62    }
63
64    /// The signed step: negative darker, positive brighter, zero as drawn.
65    pub const fn level(self) -> i8 {
66        self.0
67    }
68
69    /// Whether this is the picture as drawn, which needs no overlay.
70    pub const fn is_default(self) -> bool {
71        self.0 == 0
72    }
73
74    /// This setting moved by `delta` steps (left is negative, right
75    /// positive), stopping at the ends instead of wrapping.
76    pub const fn stepped(self, delta: i8) -> Self {
77        let level = self.0 as i16 + delta as i16;
78        if level < -(Self::STEP_COUNT as i16) {
79            Self::MIN
80        } else if level > Self::STEP_COUNT as i16 {
81            Self::MAX
82        } else {
83            Self(level as i8)
84        }
85    }
86
87    /// What the options row shows: `DEFAULT`, `DARKER n` or `BRIGHTER n`.
88    pub const fn label(self) -> Label {
89        Self::label_for_level(self.0)
90    }
91
92    /// The row text for any signed `level`, with no clamp. A game whose own
93    /// brightness steps are not five either side (a palette with its own
94    /// count of gamma rows) keeps its range and its application and shows
95    /// the same words through this.
96    pub const fn label_for_level(level: i8) -> Label {
97        if level == 0 {
98            Label::word(b"DEFAULT")
99        } else if level < 0 {
100            Label::toward(b"DARKER", level.unsigned_abs())
101        } else {
102            Label::toward(b"BRIGHTER", level.unsigned_abs())
103        }
104    }
105
106    /// The save byte: the step in two's complement, so zero (the default) is
107    /// also what a save from before the setting reads as.
108    pub const fn to_byte(self) -> u8 {
109        self.0 as u8
110    }
111
112    /// The setting a save byte holds. Any byte decodes: one outside the
113    /// range is clamped to the nearest end.
114    pub const fn from_byte(byte: u8) -> Self {
115        Self::new(byte as i8)
116    }
117
118    /// Grey of 255 the overlay carries: zero at the default, else the step
119    /// count times 8, darker or brighter. On the GPU's five bits that is
120    /// exactly the step count (1 to 5) subtracted or added per channel.
121    pub const fn overlay_gain(self) -> u8 {
122        self.0.unsigned_abs() * GAIN_PER_STEP
123    }
124
125    /// The overlay grey while a screen fades: [`overlay_gain`](Self::overlay_gain)
126    /// scaled by `fade`, where 128 is the screen at full strength. A fade to
127    /// black then still ends black instead of a lifted grey.
128    pub const fn faded_gain(self, fade: u8) -> u8 {
129        let grey = self.overlay_gain() as u32 * fade as u32 / 128;
130        if grey > 255 {
131            255
132        } else {
133            grey as u8
134        }
135    }
136
137    /// The overlay for a `resolution` frame, or `None` at the default (no
138    /// packet, no GPU work, no per-frame cost).
139    pub const fn overlay(self, resolution: Resolution) -> Option<BrightnessOverlay> {
140        if self.is_default() {
141            None
142        } else {
143            Some(BrightnessOverlay::new(self, resolution))
144        }
145    }
146
147    /// The overlay for a screen mid-fade (see [`faded_gain`](Self::faded_gain)),
148    /// or `None` when the setting is at the default or the fade has taken the
149    /// grey to nothing.
150    pub const fn faded_overlay(
151        self,
152        resolution: Resolution,
153        fade: u8,
154    ) -> Option<BrightnessOverlay> {
155        let grey = self.faded_gain(fade);
156        if grey == 0 {
157            None
158        } else {
159            Some(BrightnessOverlay::with_grey(
160                self.level() > 0,
161                grey,
162                resolution,
163            ))
164        }
165    }
166}
167
168/// The overlay packet: a draw-mode word and one semi-transparent grey
169/// rectangle (GP0 62h) covering the frame, as one linked-list node.
170///
171/// Link it into slot 0 of the frame's ordering table **before** anything
172/// else is inserted there. An insert prepends and slot 0 is walked last, so
173/// the first node in is the last drawn, and the overlay then lifts or dims
174/// the HUD and menus along with the scene. The draw area and offset must
175/// cover the whole frame when it runs (a split screen widens them first); its
176/// rectangle starts at the draw offset's origin.
177///
178/// It leaves GP0(E1h) set to its own semi-transparent mode with dithering
179/// off, as the last node of a frame; the next frame's first packets set their
180/// own draw mode.
181///
182/// ```
183/// use psx_display::Brightness;
184/// use psx_gpu::display::Resolution;
185/// let overlay = Brightness::new(-2).overlay(Resolution::R320X240).unwrap();
186/// assert_eq!(overlay.color_command & 0x00FF_FFFF, 16 * 0x0001_0101);
187/// assert!(Brightness::DEFAULT.overlay(Resolution::R320X240).is_none());
188/// ```
189#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
190#[repr(C, align(4))]
191pub struct BrightnessOverlay {
192    /// OT linkage.
193    pub tag: u32,
194    /// GP0(E1h) draw mode selecting `B + F` (brighter) or `B - F` (darker).
195    pub draw_mode: u32,
196    /// Semi-transparent flat rectangle opcode and the grey, `0x62gggggg`.
197    pub color_command: u32,
198    /// Top-left corner, relative to the draw offset.
199    pub origin: u32,
200    /// Width and height.
201    pub size: u32,
202}
203
204impl BrightnessOverlay {
205    /// Data-word count after the tag.
206    pub const WORDS: u8 = 4;
207
208    /// The overlay for `brightness` over a `resolution` frame. At
209    /// [`Brightness::DEFAULT`] the gain is zero and the packet changes
210    /// nothing, but prefer [`Brightness::overlay`], which gives no packet.
211    pub const fn new(brightness: Brightness, resolution: Resolution) -> Self {
212        Self::with_grey(
213            brightness.level() > 0,
214            brightness.overlay_gain(),
215            resolution,
216        )
217    }
218
219    const fn with_grey(brighter: bool, grey: u8, resolution: Resolution) -> Self {
220        let blend = if brighter { BLEND_ADD } else { BLEND_SUBTRACT };
221        let grey = grey as u32;
222        Self {
223            tag: 0,
224            draw_mode: gp0::draw_mode(0, 0, blend, 0, false, true),
225            color_command: packet::FLAT_RECT | packet::SEMI_TRANSPARENT | (grey * 0x0001_0101),
226            origin: 0,
227            size: ((resolution.height() as u32) << 16) | resolution.width() as u32,
228        }
229    }
230
231    /// The four payload words in the order the GPU reads them, for a caller
232    /// that copies packets into its own arena instead of linking this one.
233    pub const fn words(&self) -> [u32; Self::WORDS as usize] {
234        [self.draw_mode, self.color_command, self.origin, self.size]
235    }
236}
237
238// SAFETY: `repr(C, align(4))`, a `u32` tag first, then `WORDS` (four) payload
239// words of plain `u32` data, no interior mutability.
240unsafe impl GpuPacket for BrightnessOverlay {
241    const WORDS: u8 = BrightnessOverlay::WORDS;
242}
243
244const _: () = {
245    assert!(
246        core::mem::size_of::<BrightnessOverlay>() >= 4 * (1 + BrightnessOverlay::WORDS as usize)
247    );
248    assert!(core::mem::align_of::<BrightnessOverlay>() >= 4);
249};
250
251#[cfg(test)]
252mod tests {
253    use super::{Brightness, BrightnessOverlay};
254    use psx_gpu::display::Resolution;
255
256    /// The grey of step `n` either way, as the overlay states it.
257    fn grey(n: i8) -> u32 {
258        n.unsigned_abs() as u32 * 8
259    }
260
261    /// The four packet words for a 320x240 frame: the draw-mode word (GP0
262    /// E1h with B + F or B - F, and bit 10 set so an interlaced frame can draw
263    /// into the field being shown), the rectangle command, its corner and its
264    /// size.
265    fn words(level: i8) -> [u32; 4] {
266        let mode = if level > 0 { 0xe100_0420 } else { 0xe100_0440 };
267        [
268            mode,
269            0x6200_0000 | (grey(level) * 0x0001_0101),
270            0,
271            320 | (240 << 16),
272        ]
273    }
274
275    #[test]
276    fn the_gain_table_is_eight_grey_per_step_both_ways() {
277        let table = [0, 8, 16, 24, 32, 40];
278        for steps in 0..=5i8 {
279            assert_eq!(
280                Brightness::new(-steps).overlay_gain(),
281                table[steps as usize]
282            );
283            assert_eq!(Brightness::new(steps).overlay_gain(), table[steps as usize]);
284        }
285    }
286
287    #[test]
288    fn the_overlay_words_are_pinned_for_every_step() {
289        for level in -5..=5i8 {
290            if level == 0 {
291                continue;
292            }
293            let overlay = Brightness::new(level)
294                .overlay(Resolution::R320X240)
295                .unwrap();
296            assert_eq!(overlay.words(), words(level), "level {level}");
297        }
298        // Spelled out for the two ends.
299        assert_eq!(
300            Brightness::MIN
301                .overlay(Resolution::R320X240)
302                .unwrap()
303                .words(),
304            [0xe100_0440, 0x6228_2828, 0, 0x00f0_0140]
305        );
306        assert_eq!(
307            Brightness::MAX
308                .overlay(Resolution::R320X240)
309                .unwrap()
310                .words(),
311            [0xe100_0420, 0x6228_2828, 0, 0x00f0_0140]
312        );
313    }
314
315    /// The brighter words are the ones WipEout always drew (its draw-mode word
316    /// leaves bit 10 clear: the GPU ignores it for progressive frames).
317    #[test]
318    fn the_brighter_words_are_wipeouts() {
319        for level in 1..=5i8 {
320            let mut w = Brightness::new(level)
321                .overlay(Resolution::R320X240)
322                .unwrap()
323                .words();
324            w[0] &= !(1 << 10);
325            assert_eq!(
326                w,
327                [
328                    0xe100_0020,
329                    0x6200_0000 | (level as u32 * 8 * 0x0001_0101),
330                    0,
331                    320 | (240 << 16)
332                ]
333            );
334        }
335    }
336
337    /// Hollow Knight's fade rule: step count times the per-step grey, times
338    /// the screen's gain over 128, capped at 255.
339    #[test]
340    fn the_faded_gain_is_hollow_knights() {
341        for level in -5..=5i8 {
342            let per = 8;
343            for fade in 0..=u8::MAX {
344                let want = (level.unsigned_abs() as u32 * per * fade as u32 / 128).min(255) as u8;
345                assert_eq!(
346                    Brightness::new(level).faded_gain(fade),
347                    want,
348                    "{level} {fade}"
349                );
350            }
351        }
352        let full = Brightness::new(3)
353            .faded_overlay(Resolution::R320X240, 128)
354            .unwrap();
355        assert_eq!(
356            full,
357            Brightness::new(3).overlay(Resolution::R320X240).unwrap()
358        );
359        assert!(Brightness::new(3)
360            .faded_overlay(Resolution::R320X240, 0)
361            .is_none());
362        assert!(Brightness::DEFAULT
363            .faded_overlay(Resolution::R320X240, 128)
364            .is_none());
365        // Half faded, darker: half the grey, still subtracting.
366        let half = Brightness::new(-4)
367            .faded_overlay(Resolution::R320X240, 64)
368            .unwrap();
369        assert_eq!(half.color_command, 0x6200_0000 | (16 * 0x0001_0101));
370        assert_eq!(half.draw_mode, full.draw_mode ^ 0x0000_0060);
371    }
372
373    #[test]
374    fn the_default_has_no_overlay() {
375        assert!(Brightness::DEFAULT.overlay(Resolution::R320X240).is_none());
376        assert_eq!(Brightness::DEFAULT.overlay_gain(), 0);
377        assert!(Brightness::default().is_default());
378    }
379
380    #[test]
381    fn the_packet_is_one_node_of_five_words() {
382        assert_eq!(core::mem::size_of::<BrightnessOverlay>(), 20);
383        assert_eq!(core::mem::align_of::<BrightnessOverlay>(), 4);
384        let overlay = BrightnessOverlay::new(Brightness::new(1), Resolution::R256X240);
385        assert_eq!(overlay.tag, 0);
386        assert_eq!(overlay.size, 256 | (240 << 16));
387    }
388
389    #[test]
390    fn labels_read_default_in_the_middle() {
391        let want = [
392            "DARKER 5",
393            "DARKER 4",
394            "DARKER 3",
395            "DARKER 2",
396            "DARKER 1",
397            "DEFAULT",
398            "BRIGHTER 1",
399            "BRIGHTER 2",
400            "BRIGHTER 3",
401            "BRIGHTER 4",
402            "BRIGHTER 5",
403        ];
404        for (at, want) in want.iter().enumerate() {
405            let level = at as i8 - 5;
406            assert_eq!(Brightness::new(level).label().as_str(), *want);
407            assert_eq!(Brightness::label_for_level(level).as_str(), *want);
408        }
409        assert_eq!(Brightness::label_for_level(6).as_str(), "BRIGHTER 6");
410        assert_eq!(Brightness::label_for_level(-1).as_str(), "DARKER 1");
411    }
412
413    #[test]
414    fn stepping_clamps_at_both_ends() {
415        let mut brightness = Brightness::DEFAULT;
416        for _ in 0..20 {
417            brightness = brightness.stepped(1);
418        }
419        assert_eq!(brightness, Brightness::MAX);
420        for _ in 0..20 {
421            brightness = brightness.stepped(-1);
422        }
423        assert_eq!(brightness, Brightness::MIN);
424        assert_eq!(Brightness::MIN.stepped(i8::MIN), Brightness::MIN);
425        assert_eq!(Brightness::MAX.stepped(i8::MAX), Brightness::MAX);
426        assert_eq!(Brightness::new(i8::MIN), Brightness::MIN);
427        assert_eq!(Brightness::new(i8::MAX), Brightness::MAX);
428        assert_eq!(Brightness::new(2).stepped(-2), Brightness::DEFAULT);
429    }
430
431    #[test]
432    fn the_save_byte_is_wipeouts_and_survives_any_byte() {
433        for level in -5..=5i8 {
434            // WipEout saves `brightness as u8` and reads `(v as i8).clamp`.
435            assert_eq!(Brightness::new(level).to_byte(), level as u8);
436            assert_eq!(Brightness::from_byte(level as u8).level(), level);
437        }
438        assert_eq!(Brightness::DEFAULT.to_byte(), 0);
439        for byte in 0..=u8::MAX {
440            let level = (byte as i8).clamp(-5, 5);
441            assert_eq!(Brightness::from_byte(byte).level(), level, "byte {byte}");
442        }
443    }
444
445    /// The GPU blends in five bits per channel and a rectangle's grey is its
446    /// top five bits (`>> 3`, no dither on a rectangle; the emulator's
447    /// `blend_pixel` and `rgb24_to_bgr15` do the same), so what a step takes
448    /// off or adds to the picture is the grey `>> 3`. Every step must be a
449    /// different amount from its neighbours, the same either way: a smaller
450    /// per-step grey leaves dead or repeated steps.
451    #[test]
452    fn every_step_is_a_distinct_five_bit_amount() {
453        let five_bit = |level: i8| Brightness::new(level).overlay_gain() >> 3;
454        assert_eq!([-1, -2, -3, -4, -5].map(five_bit), [1, 2, 3, 4, 5]);
455        assert_eq!([1, 2, 3, 4, 5].map(five_bit), [1, 2, 3, 4, 5]);
456        for level in -4..=4i8 {
457            let here = five_bit(level);
458            let next = five_bit(level + level.signum());
459            if level != 0 {
460                assert_eq!(next, here + 1, "level {level}");
461            }
462        }
463        assert_eq!(five_bit(0), 0);
464        assert_eq!(five_bit(1), 1);
465        assert_eq!(five_bit(-1), 1);
466    }
467}