bracket_rex/
xpcolor.rs

1use bracket_color::prelude::{RGB, RGBA};
2use byteorder::{ReadBytesExt, WriteBytesExt};
3use std::io;
4
5/// Structure representing the components of one color
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct XpColor {
8    /// Red component 0..255
9    pub r: u8,
10    /// Green component 0..255
11    pub g: u8,
12    /// Blue component 0..255
13    pub b: u8,
14}
15
16impl From<RGB> for XpColor {
17    fn from(rgb: RGB) -> Self {
18        XpColor::new(
19            (rgb.r * 255.0) as u8,
20            (rgb.g * 255.0) as u8,
21            (rgb.b * 255.0) as u8,
22        )
23    }
24}
25
26impl From<RGBA> for XpColor {
27    fn from(rgb: RGBA) -> Self {
28        XpColor::new(
29            (rgb.r * 255.0) as u8,
30            (rgb.g * 255.0) as u8,
31            (rgb.b * 255.0) as u8,
32        )
33    }
34}
35
36impl XpColor {
37    /// deepest black
38    pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };
39    /// color 0xff00ff (hot pink) is regarded as transparent
40    pub const TRANSPARENT: Self = Self {
41        r: 255,
42        g: 0,
43        b: 255,
44    };
45
46    /// Construct a new color from r,g,b values
47    #[inline]
48    #[must_use]
49    pub const fn new(r: u8, g: u8, b: u8) -> Self {
50        Self { r, g, b }
51    }
52
53    /// Return whether this color is considered transparent (if this is the background color of a
54    /// cell, the layer below it will see through)
55    #[inline]
56    #[must_use]
57    pub fn is_transparent(self) -> bool {
58        self == Self::TRANSPARENT
59    }
60
61    /// Read a RGB color from a `ReadBytesExt`
62    ///
63    /// # Errors
64    #[inline]
65    pub fn read<T: ReadBytesExt>(rdr: &mut T) -> io::Result<Self> {
66        let r = rdr.read_u8()?;
67        let g = rdr.read_u8()?;
68        let b = rdr.read_u8()?;
69        Ok(Self { r, g, b })
70    }
71
72    /// Write a RGB color to a `WriteBytesExt`
73    ///
74    /// # Errors
75    #[inline]
76    pub fn write<T: WriteBytesExt>(self, wr: &mut T) -> io::Result<()> {
77        wr.write_u8(self.r)?;
78        wr.write_u8(self.g)?;
79        wr.write_u8(self.b)?;
80        Ok(())
81    }
82}
83
84impl From<XpColor> for RGB {
85    fn from(xp: XpColor) -> Self {
86        RGB::from_u8(xp.r, xp.g, xp.b)
87    }
88}
89
90impl From<XpColor> for RGBA {
91    fn from(xp: XpColor) -> Self {
92        RGBA::from_u8(xp.r, xp.g, xp.b, 255)
93    }
94}