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
extern crate rand;
use rand::prelude::*;
trait InRange {
fn in_range(&self, begin: Self, end: Self) -> bool;
}
impl InRange for f32 {
fn in_range(&self, begin: f32, end: f32) -> bool {
*self >= begin && *self < end
}
}
pub struct ColorPalette {
pub colors: Vec<Color>
}
#[derive(Copy, Clone)]
pub struct Color {
pub red: f32,
pub green: f32,
pub blue: f32
}
impl Color {
pub fn to_array(&self) -> [f32; 3] {
[self.red, self.green, self.blue]
}
pub fn hsv_to_rgb(hue: f32, saturation: f32, value: f32) -> Color {
let chroma = value * saturation;
let hue2 = hue / 60.0;
let tmp = chroma * (1.0 - ((hue2 % 2.0) - 1.0).abs());
let color2: (f32, f32, f32);
match hue2 {
h if h.in_range(0.0, 1.0) => color2 = (chroma, tmp, 0.0),
h if h.in_range(1.0, 2.0) => color2 = (tmp, chroma, 0.0),
h if h.in_range(2.0, 3.0) => color2 = (0.0, chroma, tmp),
h if h.in_range(3.0, 4.0) => color2 = (0.0, tmp, chroma),
h if h.in_range(4.0, 5.0) => color2 = (tmp, 0.0, chroma),
h if h.in_range(5.0, 6.0) => color2 = (chroma, 0.0, tmp),
_ => color2 = (0.0, 0.0, 0.0)
}
let m = value - chroma;
let red = color2.0 + m;
let green = color2.1 + m;
let blue = color2.2 + m;
Color {
red,
green,
blue
}
}
}
impl ColorPalette {
pub fn new(count: u32) -> ColorPalette {
let mut rng = rand::thread_rng();
let mut hue: f32 = rng.gen_range(0.0, 360.0);
let mut saturation: f32 = rng.gen_range(0.5, 1.0);
let value: f32 = rng.gen_range(0.3, 1.0);
let mut palette: Vec<Color> = vec![];
for i in 0..count {
let rgb = Color::hsv_to_rgb(hue, saturation, value);
hue = (hue + 85.0 + (i as f32) * 55.0) % 360.0;
saturation = ((i as f32) * 0.5).sin();
palette.push(Color {
red: rgb.red,
green: rgb.green,
blue: rgb.blue
});
}
ColorPalette {
colors: palette
}
}
}
#[cfg(test)]
mod tests {
use super::ColorPalette;
#[test]
fn generates_palette() {
let palette = ColorPalette::new(7);
for color in palette.colors {
assert!(color.red >= 0.0);
assert!(color.red <= 1.0);
assert!(color.green >= 0.0);
assert!(color.green <= 1.0);
assert!(color.blue >= 0.0);
assert!(color.blue <= 1.0);
}
}
}