zng_unit/
color.rs

1use std::{fmt, ops};
2
3use crate::{EQ_GRANULARITY, Factor, FactorPercent, ParseIntCompositeError, about_eq, about_eq_hash, about_eq_ord};
4
5/// RGB + alpha.
6///
7/// # Equality
8///
9/// Equality is determined using [`about_eq`] with `0.00001` granularity.
10///
11/// [`about_eq`]: crate::about_eq
12#[repr(C)]
13#[derive(Default, Copy, Clone, serde::Serialize, serde::Deserialize)]
14pub struct Rgba {
15    /// Red channel value, in the `[0.0..=1.0]` range.
16    pub red: f32,
17    /// Green channel value, in the `[0.0..=1.0]` range.
18    pub green: f32,
19    /// Blue channel value, in the `[0.0..=1.0]` range.
20    pub blue: f32,
21    /// Alpha channel value, in the `[0.0..=1.0]` range.
22    pub alpha: f32,
23}
24impl PartialEq for Rgba {
25    fn eq(&self, other: &Self) -> bool {
26        about_eq(self.red, other.red, EQ_GRANULARITY)
27            && about_eq(self.green, other.green, EQ_GRANULARITY)
28            && about_eq(self.blue, other.blue, EQ_GRANULARITY)
29            && about_eq(self.alpha, other.alpha, EQ_GRANULARITY)
30    }
31}
32impl Eq for Rgba {}
33impl PartialOrd for Rgba {
34    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
35        Some(self.cmp(other))
36    }
37}
38impl Ord for Rgba {
39    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
40        about_eq_ord(self.red, other.red, EQ_GRANULARITY)
41            .cmp(&about_eq_ord(self.green, other.green, EQ_GRANULARITY))
42            .cmp(&about_eq_ord(self.blue, other.blue, EQ_GRANULARITY))
43            .cmp(&about_eq_ord(self.alpha, other.alpha, EQ_GRANULARITY))
44    }
45}
46impl std::hash::Hash for Rgba {
47    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
48        about_eq_hash(self.red, EQ_GRANULARITY, state);
49        about_eq_hash(self.green, EQ_GRANULARITY, state);
50        about_eq_hash(self.blue, EQ_GRANULARITY, state);
51        about_eq_hash(self.alpha, EQ_GRANULARITY, state);
52    }
53}
54impl Rgba {
55    /// New from RGB of a the same type and A that can be of a different type.
56    pub fn new<C: Into<RgbaComponent>, A: Into<RgbaComponent>>(red: C, green: C, blue: C, alpha: A) -> Rgba {
57        Rgba {
58            red: red.into().0,
59            green: green.into().0,
60            blue: blue.into().0,
61            alpha: alpha.into().0,
62        }
63    }
64
65    /// Set the [`red`](Rgba::red) component from any type that converts to [`RgbaComponent`].
66    pub fn set_red<R: Into<RgbaComponent>>(&mut self, red: R) {
67        self.red = red.into().0
68    }
69
70    /// Set the [`green`](Rgba::green) component from any type that converts to [`RgbaComponent`].
71    pub fn set_green<G: Into<RgbaComponent>>(&mut self, green: G) {
72        self.green = green.into().0
73    }
74
75    /// Set the [`blue`](Rgba::blue) component from any type that converts to [`RgbaComponent`].
76    pub fn set_blue<B: Into<RgbaComponent>>(&mut self, blue: B) {
77        self.blue = blue.into().0
78    }
79
80    /// Set the [`alpha`](Rgba::alpha) component from any type that converts to [`RgbaComponent`].
81    pub fn set_alpha<A: Into<RgbaComponent>>(&mut self, alpha: A) {
82        self.alpha = alpha.into().0
83    }
84
85    /// Returns a copy of the color with a new `red` value.
86    pub fn with_red<R: Into<RgbaComponent>>(mut self, red: R) -> Self {
87        self.set_red(red);
88        self
89    }
90
91    /// Returns a copy of the color with a new `green` value.
92    pub fn with_green<R: Into<RgbaComponent>>(mut self, green: R) -> Self {
93        self.set_green(green);
94        self
95    }
96
97    /// Returns a copy of the color with a new `blue` value.
98    pub fn with_blue<B: Into<RgbaComponent>>(mut self, blue: B) -> Self {
99        self.set_blue(blue);
100        self
101    }
102
103    /// Returns a copy of the color with a new `alpha` value.
104    pub fn with_alpha<A: Into<RgbaComponent>>(mut self, alpha: A) -> Self {
105        self.set_alpha(alpha);
106        self
107    }
108
109    /// Returns a copy of the color with the alpha set to `0`.
110    pub fn transparent(self) -> Self {
111        self.with_alpha(0.0)
112    }
113
114    /// Convert a copy to [R, G, B, A] bytes.
115    pub fn to_bytes(self) -> [u8; 4] {
116        [
117            (self.red * 255.0) as u8,
118            (self.green * 255.0) as u8,
119            (self.blue * 255.0) as u8,
120            (self.alpha * 255.0) as u8,
121        ]
122    }
123
124    /// Convert a copy to [B, G, R, A] bytes.
125    pub fn to_bgra_bytes(self) -> [u8; 4] {
126        [
127            (self.blue * 255.0) as u8,
128            (self.green * 255.0) as u8,
129            (self.red * 255.0) as u8,
130            (self.alpha * 255.0) as u8,
131        ]
132    }
133}
134impl fmt::Debug for Rgba {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        if f.alternate() {
137            f.debug_struct("Rgba")
138                .field("red", &self.red)
139                .field("green", &self.green)
140                .field("blue", &self.blue)
141                .field("alpha", &self.alpha)
142                .finish()
143        } else {
144            fn i(n: f32) -> u8 {
145                (clamp_normal(n) * 255.0).round() as u8
146            }
147            let a = i(self.alpha);
148            if a == 255 {
149                write!(f, "rgb({}, {}, {})", i(self.red), i(self.green), i(self.blue))
150            } else {
151                write!(f, "rgba({}, {}, {}, {})", i(self.red), i(self.green), i(self.blue), a)
152            }
153        }
154    }
155}
156impl fmt::Display for Rgba {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        fn i(n: f32) -> u32 {
159            (clamp_normal(n) * 255.0).round() as u32
160        }
161
162        let mut rgb: u32 = 0;
163        rgb |= i(self.red) << 16;
164        rgb |= i(self.green) << 8;
165        rgb |= i(self.blue);
166
167        let a = i(self.alpha);
168        if a == 255 {
169            write!(f, "#{rgb:0>6X}")
170        } else {
171            let rgba = (rgb << 8) | a;
172            write!(f, "#{rgba:0>8X}")
173        }
174    }
175}
176impl ops::Add<Self> for Rgba {
177    type Output = Self;
178
179    fn add(self, rhs: Self) -> Self::Output {
180        Rgba {
181            red: self.red + rhs.red,
182            green: self.green + rhs.green,
183            blue: self.blue + rhs.blue,
184            alpha: self.alpha + rhs.alpha,
185        }
186    }
187}
188impl ops::AddAssign<Self> for Rgba {
189    fn add_assign(&mut self, rhs: Self) {
190        *self = *self + rhs;
191    }
192}
193impl ops::Sub<Self> for Rgba {
194    type Output = Self;
195
196    fn sub(self, rhs: Self) -> Self::Output {
197        Rgba {
198            red: self.red - rhs.red,
199            green: self.green - rhs.green,
200            blue: self.blue - rhs.blue,
201            alpha: self.alpha - rhs.alpha,
202        }
203    }
204}
205impl ops::SubAssign<Self> for Rgba {
206    fn sub_assign(&mut self, rhs: Self) {
207        *self = *self - rhs;
208    }
209}
210
211// Util
212fn clamp_normal(i: f32) -> f32 {
213    i.clamp(0.0, 1.0)
214}
215
216/// Color functions argument conversion helper.
217///
218/// Don't use this value directly, if a function takes `Into<RgbaComponent>` you can use one of the
219/// types this converts from:
220///
221/// * `f32`, `f64` and [`Factor`] for a value in the `0.0` to `1.0` range.
222/// * `u8` for a value in the `0` to `255` range.
223/// * [`FactorPercent`] for a percentage value.
224///
225/// [`Factor`]: crate::Factor
226/// [`FactorPercent`]: crate::FactorPercent
227#[derive(Clone, Copy)]
228pub struct RgbaComponent(pub f32);
229/// Color channel value is in the [0..=1] range.
230impl From<f32> for RgbaComponent {
231    fn from(f: f32) -> Self {
232        RgbaComponent(f)
233    }
234}
235/// Color channel value is in the [0..=1] range.
236impl From<f64> for RgbaComponent {
237    fn from(f: f64) -> Self {
238        RgbaComponent(f as f32)
239    }
240}
241/// Color channel value is in the [0..=255] range.
242impl From<u8> for RgbaComponent {
243    fn from(u: u8) -> Self {
244        RgbaComponent(f32::from(u) / 255.)
245    }
246}
247/// Color channel value is in the [0..=100] range.
248impl From<FactorPercent> for RgbaComponent {
249    fn from(p: FactorPercent) -> Self {
250        RgbaComponent(p.0 / 100.)
251    }
252}
253/// Color channel value is in the [0..=1] range.
254impl From<Factor> for RgbaComponent {
255    fn from(f: Factor) -> Self {
256        RgbaComponent(f.0)
257    }
258}
259
260/// Parses `"#RRGGBBAA"`, `#RRGGBB`, `"rgba(u8, u8, u8, u8)"` and `"rgb(u8, u8, u8)"`.
261impl std::str::FromStr for Rgba {
262    type Err = ParseIntCompositeError;
263
264    fn from_str(s: &str) -> Result<Self, Self::Err> {
265        if let Some(hex) = s.strip_prefix('#') {
266            let mut parser = HexComponentParser::new(hex);
267            let rgba = Rgba::new(parser.next()?, parser.next()?, parser.next()?, parser.next_or(255)?);
268            parser.end()?;
269            Ok(rgba)
270        } else if let Some(rgba) = s.strip_prefix("rgba(")
271            && let Some(rgba) = rgba.strip_suffix(')')
272        {
273            let mut parser = ComponentParser::new(rgba);
274            let rgba = Rgba::new(parser.next()?, parser.next()?, parser.next()?, parser.next()?);
275            parser.end()?;
276            Ok(rgba)
277        } else if let Some(rgb) = s.strip_prefix("rgb(")
278            && let Some(rgb) = rgb.strip_suffix(')')
279        {
280            let mut parser = ComponentParser::new(rgb);
281            let rgba = Rgba::new(parser.next()?, parser.next()?, parser.next()?, 255);
282            parser.end()?;
283            Ok(rgba)
284        } else {
285            Err(ParseIntCompositeError::UnknownFormat)
286        }
287    }
288}
289struct ComponentParser<'s> {
290    s: std::str::Split<'s, char>,
291}
292impl<'s> ComponentParser<'s> {
293    fn new(s: &'s str) -> Self {
294        Self { s: s.split(',') }
295    }
296
297    fn next(&mut self) -> Result<u8, ParseIntCompositeError> {
298        Ok(self.s.next().ok_or(ParseIntCompositeError::MissingComponent)?.trim().parse()?)
299    }
300
301    fn end(mut self) -> Result<(), ParseIntCompositeError> {
302        if self.s.next().is_some() {
303            Err(ParseIntCompositeError::ExtraComponent)
304        } else {
305            Ok(())
306        }
307    }
308}
309struct HexComponentParser<'s> {
310    s: &'s str,
311}
312impl<'s> HexComponentParser<'s> {
313    fn new(s: &'s str) -> Self {
314        Self { s }
315    }
316
317    fn next(&mut self) -> Result<u8, ParseIntCompositeError> {
318        if self.s.len() < 2 {
319            Err(ParseIntCompositeError::MissingComponent)
320        } else {
321            let c = &self.s[..2];
322            self.s = &self.s[2..];
323            Ok(u8::from_str_radix(c, 16)?)
324        }
325    }
326
327    fn next_or(&mut self, c: u8) -> Result<u8, ParseIntCompositeError> {
328        if self.s.is_empty() { Ok(c) } else { self.next() }
329    }
330
331    fn end(self) -> Result<(), ParseIntCompositeError> {
332        if self.s.is_empty() {
333            Ok(())
334        } else {
335            Err(ParseIntCompositeError::ExtraComponent)
336        }
337    }
338}