1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
//! Functions and types relating to color.

use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};

use crate::error::{Result, TetraError};
use crate::math::Vec4;

/// An RGBA color.
///
/// The components are stored as [`f32`] values in the range of `0.0` to `1.0`.
/// If your data is made up of bytes or hex values, this type provides
/// constructors that will carry out the conversion for you.
///
/// The [`std` arithmetic traits](std::ops) are implemented for this type, which allows you to
/// add/subtract/multiply/divide colors. These are implemented as saturating
/// operations (i.e. the values will always remain between `0.0` and `1.0`).
///
/// # Serde
///
/// Serialization and deserialization of this type (via [Serde](https://serde.rs/))
/// can be enabled via the `serde_support` feature.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(
    feature = "serde_support",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Color {
    /// The red component of the color.
    pub r: f32,

    /// The green component of the color.
    pub g: f32,

    /// The blue component of the color.
    pub b: f32,

    /// The alpha component of the color.
    pub a: f32,
}

impl Color {
    /// Creates a new `Color`, with the specified RGB values and the alpha set to 1.0.
    pub const fn rgb(r: f32, g: f32, b: f32) -> Color {
        Color { r, g, b, a: 1.0 }
    }

    /// Creates a new `Color`, with the specified RGBA values.
    pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Color {
        Color { r, g, b, a }
    }

    /// Creates a new `Color`, with the specified RGB integer (0-255) values and the alpha set to 255.
    pub fn rgb8(r: u8, g: u8, b: u8) -> Color {
        let r = f32::from(r) / 255.0;
        let g = f32::from(g) / 255.0;
        let b = f32::from(b) / 255.0;

        Color { r, g, b, a: 1.0 }
    }

    /// Creates a new `Color`, with the specified RGBA (0-255) integer values.
    pub fn rgba8(r: u8, g: u8, b: u8, a: u8) -> Color {
        let r = f32::from(r) / 255.0;
        let g = f32::from(g) / 255.0;
        let b = f32::from(b) / 255.0;
        let a = f32::from(a) / 255.0;

        Color { r, g, b, a }
    }

    /// Creates a new `Color` using a hexidecimal color code, panicking if the input is
    /// invalid.
    ///
    /// Six and eight digit codes can be used - the former will be interpreted as RGB, and
    /// the latter as RGBA. The `#` prefix (commonly used on the web) will be stripped if present.
    pub fn hex(hex: &str) -> Color {
        let hex = hex.trim_start_matches('#');

        assert!(hex.len() == 6 || hex.len() == 8);

        let r = u8::from_str_radix(&hex[0..2], 16).unwrap();
        let g = u8::from_str_radix(&hex[2..4], 16).unwrap();
        let b = u8::from_str_radix(&hex[4..6], 16).unwrap();

        let a = if hex.len() == 8 {
            u8::from_str_radix(&hex[6..8], 16).unwrap()
        } else {
            255
        };

        Color::rgba8(r, g, b, a)
    }

    /// Creates a new `Color` using a hexidecimal color code, returning an error if the
    /// input is invalid.
    ///
    /// Six and eight digit codes can be used - the former will be interpreted as RGB, and
    /// the latter as RGBA. The `#` prefix (commonly used on the web) will be stripped if present.
    ///
    /// # Errors
    ///
    /// * [`TetraError::InvalidColor`] will be returned if the specified color is invalid.
    pub fn try_hex(hex: &str) -> Result<Color> {
        let hex = hex.trim_start_matches('#');

        if hex.len() != 6 && hex.len() != 8 {
            return Err(TetraError::InvalidColor);
        }

        let r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| TetraError::InvalidColor)?;
        let g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| TetraError::InvalidColor)?;
        let b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| TetraError::InvalidColor)?;

        let a = if hex.len() == 8 {
            u8::from_str_radix(&hex[6..8], 16).map_err(|_| TetraError::InvalidColor)?
        } else {
            255
        };

        Ok(Color::rgba8(r, g, b, a))
    }

    // These constants should remain at the bottom of the impl block to keep
    // the docs readable - don't want to have to scroll through a load of colors
    // to get to the methods!

    /// Shortcut for [`Color::rgb(0.0, 0.0, 0.0)`](Self::rgb).
    pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0);

    /// Shortcut for [`Color::rgb(1.0, 1.0, 1.0)`](Self::rgb).
    pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0);

    /// Shortcut for [`Color::rgb(1.0, 0.0, 0.0)`](Self::rgb).
    pub const RED: Color = Color::rgb(1.0, 0.0, 0.0);

    /// Shortcut for [`Color::rgb(0.0, 1.0, 0.0)`](Self::rgb).
    pub const GREEN: Color = Color::rgb(0.0, 1.0, 0.0);

    /// Shortcut for Color::rgb(0.0, 0.0, 1.0)`](Self::rgb).
    pub const BLUE: Color = Color::rgb(0.0, 0.0, 1.0);
}

impl From<Color> for Vec4<f32> {
    fn from(color: Color) -> Vec4<f32> {
        Vec4::new(color.r, color.g, color.b, color.a)
    }
}

impl From<Vec4<f32>> for Color {
    fn from(v: Vec4<f32>) -> Self {
        Color::rgba(v.x, v.y, v.z, v.w)
    }
}

impl Add for Color {
    type Output = Color;

    fn add(mut self, rhs: Self) -> Self::Output {
        self.r = clamp(self.r + rhs.r);
        self.g = clamp(self.g + rhs.g);
        self.b = clamp(self.b + rhs.b);
        self.a = clamp(self.a + rhs.a);

        self
    }
}

impl AddAssign for Color {
    fn add_assign(&mut self, rhs: Self) {
        self.r = clamp(self.r + rhs.r);
        self.g = clamp(self.g + rhs.g);
        self.b = clamp(self.b + rhs.b);
        self.a = clamp(self.a + rhs.a);
    }
}

impl Sub for Color {
    type Output = Color;

    fn sub(mut self, rhs: Self) -> Self::Output {
        self.r = clamp(self.r - rhs.r);
        self.g = clamp(self.g - rhs.g);
        self.b = clamp(self.b - rhs.b);
        self.a = clamp(self.a - rhs.a);

        self
    }
}

impl SubAssign for Color {
    fn sub_assign(&mut self, rhs: Self) {
        self.r = clamp(self.r - rhs.r);
        self.g = clamp(self.g - rhs.g);
        self.b = clamp(self.b - rhs.b);
        self.a = clamp(self.a - rhs.a);
    }
}

impl Mul for Color {
    type Output = Color;

    fn mul(mut self, rhs: Self) -> Self::Output {
        self.r = clamp(self.r * rhs.r);
        self.g = clamp(self.g * rhs.g);
        self.b = clamp(self.b * rhs.b);
        self.a = clamp(self.a * rhs.a);

        self
    }
}

impl MulAssign for Color {
    fn mul_assign(&mut self, rhs: Self) {
        self.r = clamp(self.r * rhs.r);
        self.g = clamp(self.g * rhs.g);
        self.b = clamp(self.b * rhs.b);
        self.a = clamp(self.a * rhs.a);
    }
}

impl Div for Color {
    type Output = Color;

    fn div(mut self, rhs: Self) -> Self::Output {
        self.r = clamp(self.r / rhs.r);
        self.g = clamp(self.g / rhs.g);
        self.b = clamp(self.b / rhs.b);
        self.a = clamp(self.a / rhs.a);

        self
    }
}

impl DivAssign for Color {
    fn div_assign(&mut self, rhs: Self) {
        self.r = clamp(self.r / rhs.r);
        self.g = clamp(self.g / rhs.g);
        self.b = clamp(self.b / rhs.b);
        self.a = clamp(self.a / rhs.a);
    }
}

fn clamp(val: f32) -> f32 {
    f32::min(f32::max(0.0, val), 1.0)
}

#[cfg(test)]
mod tests {
    use super::Color;

    #[test]
    fn rgb8_creation() {
        assert!(same_color(
            Color::rgba(0.2, 0.4, 0.6, 1.0),
            Color::rgb8(51, 102, 153)
        ));
    }

    #[test]
    fn hex_creation() {
        let expected = Color::rgba(0.2, 0.4, 0.6, 1.0);

        assert!(same_color(expected, Color::hex("336699")));
        assert!(same_color(expected, Color::hex("#336699")));
        assert!(same_color(expected, Color::hex("336699FF")));
        assert!(same_color(expected, Color::hex("#336699FF")));
    }

    #[test]
    fn try_hex_creation() {
        let expected = Color::rgba(0.2, 0.4, 0.6, 1.0);

        assert!(same_color(expected, Color::try_hex("336699").unwrap()));
        assert!(same_color(expected, Color::try_hex("#336699").unwrap()));
        assert!(same_color(expected, Color::try_hex("336699FF").unwrap()));
        assert!(same_color(expected, Color::try_hex("#336699FF").unwrap()));

        assert!(Color::try_hex("ZZZZZZ").is_err());
    }

    #[test]
    fn ops() {
        assert_eq!(
            Color::rgba(1.0, 1.0, 1.0, 1.0),
            Color::rgba(0.1, 0.2, 0.3, 0.4) + Color::rgba(0.9, 0.8, 0.7, 0.6)
        );

        assert_eq!(Color::rgba(1.0, 1.0, 1.0, 1.0), {
            let mut add_assign = Color::rgba(0.1, 0.2, 0.3, 0.4);
            add_assign += Color::rgba(0.9, 0.8, 0.7, 0.6);
            add_assign
        });

        assert_eq!(
            Color::rgba(0.0, 0.0, 0.0, 0.0),
            Color::rgba(0.5, 0.5, 0.5, 0.5) - Color::rgba(0.5, 0.5, 0.5, 0.5)
        );

        assert_eq!(Color::rgba(0.0, 0.0, 0.0, 0.0), {
            let mut sub_assign = Color::rgba(0.5, 0.5, 0.5, 0.5);
            sub_assign -= Color::rgba(0.5, 0.5, 0.5, 0.5);
            sub_assign
        });

        assert_eq!(
            Color::rgba(1.0, 1.0, 1.0, 1.0),
            Color::rgba(0.5, 0.5, 0.5, 0.5) * Color::rgba(2.0, 2.0, 2.0, 2.0)
        );

        assert_eq!(Color::rgba(1.0, 1.0, 1.0, 1.0), {
            let mut mul_assign = Color::rgba(0.5, 0.5, 0.5, 0.5);
            mul_assign *= Color::rgba(2.0, 2.0, 2.0, 2.0);
            mul_assign
        });

        assert_eq!(
            Color::rgba(0.5, 0.5, 0.5, 0.5),
            Color::rgba(1.0, 1.0, 1.0, 1.0) / Color::rgba(2.0, 2.0, 2.0, 2.0)
        );

        assert_eq!(Color::rgba(0.5, 0.5, 0.5, 0.5), {
            let mut div_assign = Color::rgba(1.0, 1.0, 1.0, 1.0);
            div_assign /= Color::rgba(2.0, 2.0, 2.0, 2.0);
            div_assign
        });
    }

    fn same_color(a: Color, b: Color) -> bool {
        (a.r - b.r).abs() < std::f32::EPSILON
            && (a.g - b.g).abs() < std::f32::EPSILON
            && (a.b - b.b).abs() < std::f32::EPSILON
            && (a.a - b.a).abs() < std::f32::EPSILON
    }
}