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
use glm::*;
use glm::ext::recip;
use super::space::{ ColorSpace, from_rgb };
use super::rgb::Rgb;
use std::mem;
use rand::{ Rand, Rng };
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Srgb {
r: f32,
g: f32,
b: f32
}
impl Srgb {
#[inline]
pub fn new(r: f32, g: f32, b: f32) -> Srgb {
let v3 = clamp_s(vec3(r, g, b), 0., 1.);
Srgb { r: v3.x, g: v3.y, b: v3.z }
}
pub fn red(&self) -> f32 {
self.r
}
pub fn green(&self) -> f32 {
self.g
}
pub fn blue(&self) -> f32 {
self.b
}
pub fn as_vec3(&self) -> &Vec3 {
let v: &Vec3 = unsafe { mem::transmute(self) };
v
}
}
impl Rand for Srgb {
#[inline]
fn rand<R: Rng>(rng: &mut R) -> Srgb {
let rgb = rng.gen::<Rgb>();
from_rgb(rgb)
}
}
impl Eq for Srgb {}
impl ApproxEq for Srgb {
type BaseType = f32;
#[inline]
fn is_close_to(&self, other: &Srgb, max_diff: f32) -> bool {
self.as_vec3().is_close_to(other.as_vec3(), max_diff)
}
}
impl ColorSpace for Srgb {
#[inline]
fn from_rgb(rgb: Rgb) -> Srgb {
let v3 = rgb.as_vec3().map(|f| {
if f <= 0.0031308 {
f * 12.92
} else {
let a = 0.055_f32;
(1. + a) * pow(f, recip(2.4_f32)) - a
}
});
Srgb { r: v3.x, g: v3.y, b: v3.z }
}
#[inline]
fn to_rgb(&self) -> Rgb {
let v3 = self.as_vec3().map(|f| {
if f <= 0.04045 {
f / 12.92
} else {
let a = 0.055_f32;
pow((f + a) * recip(1. + a), 2.4)
}
});
Rgb::new(v3.x, v3.y, v3.z)
}
}
pub fn srgb(r: f32, g: f32, b: f32) -> Srgb {
Srgb::new(r, g, b)
}
#[cfg(test)]
mod test {
use glm::*;
use space::ColorSpace;
use rgb::Rgb;
use super::Srgb;
use quickcheck::*;
#[test]
fn test_to_rgb() {
fn prop(clr: Rgb) -> bool {
let s: Srgb = ColorSpace::from_rgb(clr);
let rgb = s.to_rgb();
is_close_to(&rgb, &clr, 0.0001)
}
quickcheck(prop as fn(Rgb) -> bool);
}
}