Skip to main content

dream_soft_render/
color.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3/// An RGBA8 color with **premultiplied** alpha.
4///
5/// Every color the renderer accepts or stores is premultiplied: `r`, `g`, and `b` have already
6/// been scaled by `a / 255`. Opaque colors are the same either way; for translucent ones, use
7/// [`Color::from_rgba_unmultiplied`] to convert straight-alpha input. A channel above `a` is
8/// allowed and blends additively, as in egui.
9///
10/// It is four bytes with four-byte alignment, so the rasterizer compares and moves a color as
11/// one 32-bit word.
12#[derive(Clone, Copy, Debug, Default)]
13#[repr(C, align(4))]
14pub struct Color {
15    /// Red, premultiplied.
16    pub r: u8,
17    /// Green, premultiplied.
18    pub g: u8,
19    /// Blue, premultiplied.
20    pub b: u8,
21    /// Alpha: 0 is transparent, 255 is opaque.
22    pub a: u8,
23}
24
25impl Color {
26    /// Fully transparent (all channels 0).
27    pub const TRANSPARENT: Self = Self::from_rgba_premultiplied(0, 0, 0, 0);
28    /// Opaque black.
29    pub const BLACK: Self = Self::from_rgba_premultiplied(0, 0, 0, 255);
30    /// Opaque white.
31    pub const WHITE: Self = Self::from_rgba_premultiplied(255, 255, 255, 255);
32
33    /// A color from channels that are already premultiplied.
34    #[must_use]
35    pub const fn from_rgba_premultiplied(r: u8, g: u8, b: u8, a: u8) -> Self {
36        Self { r, g, b, a }
37    }
38
39    /// A color from straight (unmultiplied) channels, premultiplying each of `r`, `g`, `b` by
40    /// `a` with round-to-nearest: `(channel * a + 127) / 255`.
41    #[must_use]
42    pub const fn from_rgba_unmultiplied(r: u8, g: u8, b: u8, a: u8) -> Self {
43        Self {
44            r: premultiply(r, a),
45            g: premultiply(g, a),
46            b: premultiply(b, a),
47            a,
48        }
49    }
50
51    /// An opaque color.
52    #[must_use]
53    pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
54        Self::from_rgba_premultiplied(r, g, b, 255)
55    }
56
57    /// The channels as `[r, g, b, a]`, the same order as surface and texture bytes.
58    #[must_use]
59    pub const fn to_array(self) -> [u8; 4] {
60        [self.r, self.g, self.b, self.a]
61    }
62
63    /// Packs the color into a `u32` with a fixed layout that does not depend on host byte
64    /// order: bits 0-7 red, 8-15 green, 16-23 blue, 24-31 alpha.
65    #[must_use]
66    pub const fn to_packed(self) -> u32 {
67        (self.r as u32) | (self.g as u32) << 8 | (self.b as u32) << 16 | (self.a as u32) << 24
68    }
69
70    /// Unpacks a color from the [`Color::to_packed`] layout. Every `u32` is a valid color.
71    #[must_use]
72    pub const fn from_packed(packed: u32) -> Self {
73        let [r, g, b, a] = packed.to_le_bytes();
74        Self { r, g, b, a }
75    }
76
77    #[cfg(all(test, feature = "egui"))]
78    pub(crate) const fn to_egui(self) -> egui::Color32 {
79        egui::Color32::from_rgba_premultiplied(self.r, self.g, self.b, self.a)
80    }
81}
82
83// Whole-word comparison: the uniform-color checks that pick every fast path run this per
84// vertex, and field-by-field comparison costs four compares where one will do.
85impl PartialEq for Color {
86    fn eq(&self, other: &Self) -> bool {
87        u32::from_ne_bytes(self.to_array()) == u32::from_ne_bytes(other.to_array())
88    }
89}
90
91impl Eq for Color {}
92
93impl std::hash::Hash for Color {
94    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
95        self.to_packed().hash(state);
96    }
97}
98
99#[allow(
100    clippy::cast_possible_truncation,
101    reason = "(channel * alpha + 127) / 255 is at most 255"
102)]
103const fn premultiply(channel: u8, alpha: u8) -> u8 {
104    ((channel as u16 * alpha as u16 + 127) / 255) as u8
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    #[test]
112    fn packed_layout_is_red_in_the_low_byte() {
113        let color = Color::from_rgba_premultiplied(0x11, 0x22, 0x33, 0x44);
114        assert_eq!(color.to_packed(), 0x4433_2211);
115        assert_eq!(Color::from_packed(0x4433_2211), color);
116    }
117
118    #[test]
119    fn unmultiplied_colors_round_to_nearest() {
120        assert_eq!(
121            Color::from_rgba_unmultiplied(255, 128, 1, 128),
122            Color::from_rgba_premultiplied(128, 64, 1, 128)
123        );
124        assert_eq!(
125            Color::from_rgba_unmultiplied(200, 100, 50, 255),
126            Color::from_rgb(200, 100, 50)
127        );
128        assert_eq!(
129            Color::from_rgba_unmultiplied(200, 100, 50, 0),
130            Color::TRANSPARENT
131        );
132    }
133}