dream_soft_render/
color.rs1#[derive(Clone, Copy, Debug, Default)]
13#[repr(C, align(4))]
14pub struct Color {
15 pub r: u8,
17 pub g: u8,
19 pub b: u8,
21 pub a: u8,
23}
24
25impl Color {
26 pub const TRANSPARENT: Self = Self::from_rgba_premultiplied(0, 0, 0, 0);
28 pub const BLACK: Self = Self::from_rgba_premultiplied(0, 0, 0, 255);
30 pub const WHITE: Self = Self::from_rgba_premultiplied(255, 255, 255, 255);
32
33 #[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 #[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 #[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 #[must_use]
59 pub const fn to_array(self) -> [u8; 4] {
60 [self.r, self.g, self.b, self.a]
61 }
62
63 #[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 #[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
83impl 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}