Skip to main content

rust_motion_cms/
math.rs

1//! Small colour-science helpers: 3×3 matrices, CIE XYZ ↔ L*a*b*, chromatic adaptation.
2//!
3//! All formulas are from public standards: CIE 15 (L*a*b*), ICC.1:2010 Annex A (PCS, D50),
4//! and the Bradford cone response matrix published by Lam (1985).
5
6/// The ICC profile connection space illuminant (D50), as encoded in s15Fixed16 in every
7/// ICC header: X = 0.9642, Y = 1.0, Z = 0.8249.
8pub const D50: [f64; 3] = [0.9642, 1.0, 0.8249];
9
10/// CIE D65 white point as XYZ (Y = 1), from the chromaticity (0.3127, 0.3290) used by sRGB,
11/// Display P3 and Adobe RGB-compatible spaces.
12pub const D65_XY: [f64; 2] = [0.3127, 0.3290];
13
14/// Row-major 3×3 matrix.
15pub type Mat3 = [[f64; 3]; 3];
16
17pub const IDENTITY: Mat3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
18
19pub fn mul(a: &Mat3, b: &Mat3) -> Mat3 {
20    let mut o = [[0.0; 3]; 3];
21    for (i, row) in o.iter_mut().enumerate() {
22        for (j, v) in row.iter_mut().enumerate() {
23            *v = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j];
24        }
25    }
26    o
27}
28
29pub fn apply(m: &Mat3, v: [f64; 3]) -> [f64; 3] {
30    [
31        m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2],
32        m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2],
33        m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2],
34    ]
35}
36
37pub fn det(m: &Mat3) -> f64 {
38    m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
39        - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
40        + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
41}
42
43/// Inverse, or `None` when (nearly) singular.
44pub fn invert(m: &Mat3) -> Option<Mat3> {
45    let d = det(m);
46    if !d.is_finite() || d.abs() < 1e-12 {
47        return None;
48    }
49    let inv = 1.0 / d;
50    Some([
51        [
52            (m[1][1] * m[2][2] - m[1][2] * m[2][1]) * inv,
53            (m[0][2] * m[2][1] - m[0][1] * m[2][2]) * inv,
54            (m[0][1] * m[1][2] - m[0][2] * m[1][1]) * inv,
55        ],
56        [
57            (m[1][2] * m[2][0] - m[1][0] * m[2][2]) * inv,
58            (m[0][0] * m[2][2] - m[0][2] * m[2][0]) * inv,
59            (m[0][2] * m[1][0] - m[0][0] * m[1][2]) * inv,
60        ],
61        [
62            (m[1][0] * m[2][1] - m[1][1] * m[2][0]) * inv,
63            (m[0][1] * m[2][0] - m[0][0] * m[2][1]) * inv,
64            (m[0][0] * m[1][1] - m[0][1] * m[1][0]) * inv,
65        ],
66    ])
67}
68
69/// XYZ (Y = 1) of a chromaticity `(x, y)`.
70pub fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] {
71    let [x, y] = xy;
72    [x / y, 1.0, (1.0 - x - y) / y]
73}
74
75/// Bradford cone response matrix (Lam 1985).
76const BRADFORD: Mat3 = [
77    [0.8951, 0.2664, -0.1614],
78    [-0.7502, 1.7135, 0.0367],
79    [0.0389, -0.0685, 1.0296],
80];
81
82/// Bradford chromatic adaptation matrix from white `src` to white `dst` (both XYZ).
83pub fn bradford(src: [f64; 3], dst: [f64; 3]) -> Mat3 {
84    // `BRADFORD` is a constant with determinant ~1.7 (see `bradford_maps_white`).
85    #[allow(clippy::expect_used)]
86    let inv = invert(&BRADFORD).expect("Bradford matrix is invertible");
87    let s = apply(&BRADFORD, src);
88    let d = apply(&BRADFORD, dst);
89    let scale = [
90        [d[0] / s[0], 0.0, 0.0],
91        [0.0, d[1] / s[1], 0.0],
92        [0.0, 0.0, d[2] / s[2]],
93    ];
94    mul(&inv, &mul(&scale, &BRADFORD))
95}
96
97/// RGB → XYZ matrix (relative to `white`, Y = 1) for primaries given as chromaticities, or
98/// `None` when the primaries are not independent.
99pub fn rgb_to_xyz_matrix(r: [f64; 2], g: [f64; 2], b: [f64; 2], white: [f64; 3]) -> Option<Mat3> {
100    let (xr, xg, xb) = (xy_to_xyz(r), xy_to_xyz(g), xy_to_xyz(b));
101    let m = [
102        [xr[0], xg[0], xb[0]],
103        [xr[1], xg[1], xb[1]],
104        [xr[2], xg[2], xb[2]],
105    ];
106    let s = apply(&invert(&m)?, white);
107    Some([
108        [m[0][0] * s[0], m[0][1] * s[1], m[0][2] * s[2]],
109        [m[1][0] * s[0], m[1][1] * s[1], m[1][2] * s[2]],
110        [m[2][0] * s[0], m[2][1] * s[1], m[2][2] * s[2]],
111    ])
112}
113
114const EPS: f64 = 216.0 / 24389.0; // (6/29)^3
115const KAPPA: f64 = 24389.0 / 27.0; // (29/3)^3
116
117#[inline]
118fn lab_f(t: f64) -> f64 {
119    if t > EPS {
120        t.cbrt()
121    } else {
122        (KAPPA * t + 16.0) / 116.0
123    }
124}
125
126#[inline]
127fn lab_finv(f: f64) -> f64 {
128    let f3 = f * f * f;
129    if f3 > EPS {
130        f3
131    } else {
132        (116.0 * f - 16.0) / KAPPA
133    }
134}
135
136/// CIE XYZ → L*a*b* relative to `white` (CIE 15).
137pub fn xyz_to_lab(xyz: [f64; 3], white: [f64; 3]) -> [f64; 3] {
138    let fx = lab_f(xyz[0] / white[0]);
139    let fy = lab_f(xyz[1] / white[1]);
140    let fz = lab_f(xyz[2] / white[2]);
141    [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]
142}
143
144/// CIE L*a*b* → XYZ relative to `white`.
145pub fn lab_to_xyz(lab: [f64; 3], white: [f64; 3]) -> [f64; 3] {
146    let fy = (lab[0] + 16.0) / 116.0;
147    let fx = fy + lab[1] / 500.0;
148    let fz = fy - lab[2] / 200.0;
149    [
150        lab_finv(fx) * white[0],
151        lab_finv(fy) * white[1],
152        lab_finv(fz) * white[2],
153    ]
154}
155
156/// f32 versions for the hot paths (D50 PCS only).
157#[inline]
158pub fn xyz_to_lab_f32(xyz: [f32; 3]) -> [f32; 3] {
159    const W: [f32; 3] = [0.9642, 1.0, 0.8249];
160    const E: f32 = 216.0 / 24389.0;
161    const K: f32 = 24389.0 / 27.0;
162    let f = |t: f32| {
163        if t > E {
164            t.cbrt()
165        } else {
166            (K * t + 16.0) / 116.0
167        }
168    };
169    let fx = f(xyz[0] / W[0]);
170    let fy = f(xyz[1] / W[1]);
171    let fz = f(xyz[2] / W[2]);
172    [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]
173}
174
175#[inline]
176pub fn lab_to_xyz_f32(lab: [f32; 3]) -> [f32; 3] {
177    const W: [f32; 3] = [0.9642, 1.0, 0.8249];
178    const E: f32 = 216.0 / 24389.0;
179    const K: f32 = 24389.0 / 27.0;
180    let fy = (lab[0] + 16.0) / 116.0;
181    let fx = fy + lab[1] / 500.0;
182    let fz = fy - lab[2] / 200.0;
183    let finv = |f: f32| {
184        let f3 = f * f * f;
185        if f3 > E {
186            f3
187        } else {
188            (116.0 * f - 16.0) / K
189        }
190    };
191    [finv(fx) * W[0], finv(fy) * W[1], finv(fz) * W[2]]
192}
193
194/// CIE 1976 colour difference.
195pub fn delta_e76(a: [f64; 3], b: [f64; 3]) -> f64 {
196    ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
197}
198
199/// Quantizes to ICC s15Fixed16Number and back (what a profile can actually store).
200pub fn s15f16_round(v: f64) -> f64 {
201    (v * 65536.0).round() / 65536.0
202}
203
204/// The D50 illuminant exactly as an ICC header stores it (s15Fixed16).
205pub fn d50_quantized() -> [f64; 3] {
206    [
207        s15f16_round(D50[0]),
208        s15f16_round(D50[1]),
209        s15f16_round(D50[2]),
210    ]
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn lab_roundtrip() {
219        for xyz in [
220            [0.2, 0.3, 0.1],
221            [0.9642, 1.0, 0.8249],
222            [0.001, 0.002, 0.0005],
223        ] {
224            let back = lab_to_xyz(xyz_to_lab(xyz, D50), D50);
225            for i in 0..3 {
226                assert!((back[i] - xyz[i]).abs() < 1e-12);
227            }
228        }
229        let w = xyz_to_lab(D50, D50);
230        assert!((w[0] - 100.0).abs() < 1e-12 && w[1].abs() < 1e-12 && w[2].abs() < 1e-12);
231    }
232
233    #[test]
234    fn bradford_maps_white() {
235        let d65 = xy_to_xyz(D65_XY);
236        let m = bradford(d65, D50);
237        let w = apply(&m, d65);
238        for i in 0..3 {
239            assert!((w[i] - D50[i]).abs() < 1e-12);
240        }
241    }
242
243    #[test]
244    fn invert_roundtrip() {
245        let m = [[0.4, 0.3, 0.2], [0.2, 0.7, 0.1], [0.0, 0.1, 0.8]];
246        let p = mul(&m, &invert(&m).unwrap());
247        for (i, row) in p.iter().enumerate() {
248            for (j, v) in row.iter().enumerate() {
249                assert!((v - if i == j { 1.0 } else { 0.0 }).abs() < 1e-12);
250            }
251        }
252    }
253}