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
//!  A module for handling colors.

// from rust
use std;

// from external crate

// from local crate
use error::{RasterError, RasterResult};

/// A struct for representing and creating color.
#[derive(Debug, Clone)]
pub struct Color {
    /// Red channel 0 - 255
    pub r: u8,

    /// Green channel 0 - 255
    pub g: u8,

    /// Blue channel 0 - 255
    pub b: u8,

    /// Alpha channel 0 - 255
    pub a: u8,
}

impl<'a> Color {
    /// Returns a black Color.
    pub fn black() -> Color {
        Color {
            r: 0,
            g: 0,
            b: 0,
            a: 255,
        }
    }

    /// Returns a blue Color.
    pub fn blue() -> Color {
        Color {
            r: 0,
            g: 0,
            b: 255,
            a: 255,
        }
    }

    /// Returns a green Color.
    pub fn green() -> Color {
        Color {
            r: 0,
            g: 255,
            b: 0,
            a: 255,
        }
    }

    /// Create a color from hexadecimal value.
    ///
    /// Example of valid formats: #FFFFFF, #ffeecc, #00ff007f
    ///
    /// # Errors
    ///
    /// If the hex *string* is malformed (doesn't begin with `#` or is of invalid length) then this
    /// fails with `RasterError::InvalidHex`. If it passes that, but the string can't be parsed
    /// into actual values, then this fails with `RasterError::HexParse`.
    ///
    /// # Examples
    /// ```
    /// use raster::Color;
    ///
    /// // Ok tests
    /// let color = Color::hex("#FFFFFF"); // Opaque white
    /// assert!(color.is_ok());
    ///
    /// let color = Color::hex("#00FF007F"); // Green with 50% opacity
    /// assert!(color.is_ok());
    ///
    /// // Error tests
    /// let color = Color::hex("");
    /// assert!(color.is_err());
    ///
    /// let color = Color::hex("#");
    /// assert!(color.is_err());
    ///
    /// let color = Color::hex("#FFF");
    /// assert!(color.is_err());
    ///
    /// ```
    ///
    /// To get the value, use unwrap:
    ///
    /// ```
    /// use raster::Color;
    ///
    /// let color = Color::hex("#00FF007F").unwrap();
    /// assert_eq!(255, color.g);
    /// ```
    pub fn hex(hex: &str) -> RasterResult<Color> {
        if hex.len() == 9 && hex.starts_with('#') {
            // #FFFFFFFF (Red Green Blue Alpha)
            Ok(Color {
                r: _hex_dec(&hex[1..3])?,
                g: _hex_dec(&hex[3..5])?,
                b: _hex_dec(&hex[5..7])?,
                a: _hex_dec(&hex[7..9])?,
            })
        } else if hex.len() == 7 && hex.starts_with('#') {
            // #FFFFFF (Red Green Blue)
            Ok(Color {
                r: _hex_dec(&hex[1..3])?,
                g: _hex_dec(&hex[3..5])?,
                b: _hex_dec(&hex[5..7])?,
                a: 255,
            })
        } else {
            Err(RasterError::InvalidHex)
        }
    }

    /// Returns a red Color.
    pub fn red() -> Color {
        Color {
            r: 255,
            g: 0,
            b: 0,
            a: 255,
        }
    }

    /// Create a RGB color. Alpha defaults to opaque (255).
    ///
    /// # Examples
    ///
    /// ```
    /// use raster::Color;
    ///
    /// let rgb = Color::rgb(0, 255, 0); // Green
    ///
    /// println!("{:?}", rgb);
    ///
    /// assert_eq!(rgb.r, 0);
    /// assert_eq!(rgb.g, 255);
    /// assert_eq!(rgb.b, 0);
    /// assert_eq!(rgb.a, 255);
    /// ```
    pub fn rgb(r: u8, g: u8, b: u8) -> Color {
        Color { r, g, b, a: 255 }
    }

    /// Create a RGBA color.
    ///
    /// # Examples
    ///
    /// ```
    /// use raster::Color;
    ///
    /// let rgba = Color::rgba(0, 0, 255, 255); // Blue
    ///
    /// println!("{:?}", rgba);
    ///
    /// assert_eq!(rgba.r, 0);
    /// assert_eq!(rgba.g, 0);
    /// assert_eq!(rgba.b, 255);
    /// assert_eq!(rgba.a, 255);
    /// ```
    pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
        Color { r, g, b, a }
    }

    /// Convert RGB to HSV/HSB (Hue, Saturation, Brightness).
    ///
    /// ```
    /// use raster::Color;
    ///
    /// let hsv = Color::to_hsv(50, 50, 100);
    ///
    /// assert_eq!(240, hsv.0);
    /// assert_eq!(50.0, (hsv.1).round()); // Saturation in float
    /// assert_eq!(39.0, (hsv.2).round()); // Brightness in float
    /// ```
    // Using f32 for s,v for accuracy when converting from RGB-HSV and vice-versa.
    pub fn to_hsv(r: u8, g: u8, b: u8) -> (u16, f32, f32) {
        let r = r as f32 / 255.0;
        let g = g as f32 / 255.0;
        let b = b as f32 / 255.0;

        let min = rgb_min(r, g, b);
        let max = rgb_max(r, g, b);

        let chroma = max - min;

        let h = {
            let mut h = 0.0;

            if chroma != 0.0 {
                if (max - r).abs() < std::f32::EPSILON {
                    h = 60.0 * ((g - b) / chroma);
                    if h < 0.0 {
                        h += 360.0;
                    }
                } else if (max - g).abs() < std::f32::EPSILON {
                    h = 60.0 * (((b - r) / chroma) + 2.0);
                } else if (max - b).abs() < std::f32::EPSILON {
                    h = 60.0 * (((r - g) / chroma) + 4.0);
                }
            }

            if h > 359.0 {
                h = 360.0 - h; // Invert if > 0 to 359
            }

            h
        };

        let v = max;
        let s = if v != 0.0 { chroma / v } else { 0.0 };

        (h.round() as u16, s * 100.0, v * 100.0)
    }

    /// Convert HSV/HSB (Hue, Saturation, Brightness) to RGB.
    ///
    /// ```
    /// use raster::Color;
    ///
    /// let rgb1 = (127, 70, 60);
    /// let hsv = Color::to_hsv(rgb1.0, rgb1.1, rgb1.2); // Convert to HSV
    /// let rgb2 = Color::to_rgb(hsv.0, hsv.1, hsv.2); // Convert back to RGB
    ///
    /// // Check if source RGB is equal to final RGB
    /// assert_eq!(rgb1.0, rgb2.0);
    /// assert_eq!(rgb1.1, rgb2.1);
    /// assert_eq!(rgb1.2, rgb2.2);
    /// ```
    // Using f32 for s,v for accuracy when converting from RGB-HSV and vice-versa.
    pub fn to_rgb(h: u16, s: f32, v: f32) -> (u8, u8, u8) {
        let h = h as f32 / 60.0;
        let s = s as f32 / 100.0; // Convert to 0.0 - 1.0
        let v = v as f32 / 100.0;

        let chroma = v * s;

        let x = chroma * (1.0 - ((h % 2.0) - 1.0).abs());

        let mut r = 0.0;
        let mut g = 0.0;
        let mut b = 0.0;

        if h >= 0.0 {
            if h < 1.0 {
                r = chroma;
                g = x;
                b = 0.0;
            } else if h < 2.0 {
                r = x;
                g = chroma;
                b = 0.0;
            } else if h < 3.0 {
                r = 0.0;
                g = chroma;
                b = x;
            } else if h < 4.0 {
                r = 0.0;
                g = x;
                b = chroma;
            } else if h < 5.0 {
                r = x;
                g = 0.0;
                b = chroma;
            } else if h < 6.0 {
                r = chroma;
                g = 0.0;
                b = x;
            }
        }

        let m = v - chroma;
        r += m;
        g += m;
        b += m;
        (
            (r * 255.0).round() as u8,
            (g * 255.0).round() as u8,
            (b * 255.0).round() as u8,
        )
    }

    /// Returns a white Color.
    pub fn white() -> Color {
        Color {
            r: 255,
            g: 255,
            b: 255,
            a: 255,
        }
    }
}

// Private functions

// Convert a hex string to decimal. Eg. "00" -> 0. "FF" -> 255.
fn _hex_dec(hex_string: &str) -> RasterResult<u8> {
    u8::from_str_radix(hex_string, 16)
        .map(|o| o as u8)
        .map_err(RasterError::HexParse)
}

fn rgb_min(r: f32, g: f32, b: f32) -> f32 {
    let min = if g < r { g } else { r };

    if b < min {
        b
    } else {
        min
    }
}

fn rgb_max(r: f32, g: f32, b: f32) -> f32 {
    let max = if g > r { g } else { r };

    if b > max {
        b
    } else {
        max
    }
}