colr 0.1.0

Type-safe, zero-cost color science library with compile-time color space transforms
Documentation
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! Standard RGB color spaces, channel layouts, and their transforms.
//!
//! Layout is a parameter of the space: `RgbSpace<P, TF, L>` where `L` defaults
//! to `Rgba`. Chromatic adaptation uses Bradford per ICC, ACES, and CSS Color 4.
//!
//! # Space catalogue
//!
//! | Alias          | Primaries | Transfer fn | White |
//! |----------------|-----------|-------------|-------|
//! | Srgb           | sRGB/709  | sRGB        | D65   |
//! | LinearSrgb     | sRGB/709  | Linear      | D65   |
//! | Rec709         | sRGB/709  | Rec. 709    | D65   |
//! | DisplayP3      | P3        | sRGB        | D65   |
//! | LinearP3       | P3        | Linear      | D65   |
//! | Hdr10          | Rec. 2020 | PQ          | D65   |
//! | Hlg            | Rec. 2020 | HLG         | D65   |
//! | LinearRec2020  | Rec. 2020 | Linear      | D65   |
//! | AcesCg         | AP1       | Linear      | ACES  |
//! | Aces2065       | AP0       | Linear      | ACES  |
//! | AcesCc         | AP1       | ACEScc      | ACES  |
//! | AcesCct        | AP1       | ACEScct     | ACES  |
//! | ProPhoto       | ProPhoto  | ProPhoto    | D50   |
//! | LinearProPhoto | ProPhoto  | Linear      | D50   |
//! | DciP3          | DCI-P3    | gamma 2.6   | DCI   |
//! | P3D65Gamma26   | P3        | gamma 2.6   | D65   |

use core::marker::PhantomData;

use crate::adaptation::Bradford;
use crate::illuminant::Illuminant;
use crate::math::{DefaultMath, Mat3};
use crate::primaries::{
    AcesAp0Primaries, AcesAp1Primaries, DciP3Primaries, P3Primaries, Primaries, PrimariesToXyz, ProPhotoPrimaries,
    Rec2020Primaries, SrgbPrimaries,
};
use crate::transfer::{
    AcesCcTf, AcesCctTf, DciP3Tf, HlgTf, IsDisplayReferred, IsLinearEncoding, IsSceneReferred, LinearTf, PqTf,
    ProPhotoTf, Rec709Tf, SrgbTf, TransferFunction,
};
use crate::xyz::Xyz;
use crate::{
    Asserts, Color, ColorSpace, DisplayReferred, LinearLight, OutOfGamut, SceneReferred, Transform, TryTransform,
};

/// Maps all N channels to their storage indices.
///
/// INDICES contains the storage position of each logical channel in order.
/// For RGB layouts the first three are R, G, B. ALPHA points to which
/// position within INDICES holds alpha, if any.
pub trait ChannelMap<const N: usize>: 'static {
    /// Storage positions of all N channels in logical order.
    const INDICES: [usize; N];
    /// Which position within INDICES holds alpha, if any.
    const ALPHA: Option<usize>;
}

macro_rules! define_layout {
    ($name:ident, [$r:expr, $g:expr, $b:expr, $a:expr]) => {
        #[doc = concat!("Four-channel layout. R=`", stringify!($r), "` G=`", stringify!($g), "` B=`", stringify!($b), "` A=`", stringify!($a), "`.")]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
        pub struct $name;
        impl Asserts<[f32; 4]> for $name {}
        #[cfg(feature = "glam")]
        impl Asserts<glam::Vec4> for $name {}
        impl ChannelMap<4> for $name {
            const INDICES: [usize; 4] = [$r, $g, $b, $a];
            const ALPHA: Option<usize> = Some(3);
        }
    };
    ($name:ident, [$r:expr, $g:expr, $b:expr]) => {
        #[doc = concat!("Three-channel layout. R=`", stringify!($r), "` G=`", stringify!($g), "` B=`", stringify!($b), "`. No alpha.")]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
        pub struct $name;
        impl Asserts<[f32; 3]> for $name {}
        #[cfg(feature = "glam")]
        impl Asserts<glam::Vec3> for $name {}
        #[cfg(feature = "glam")]
        impl Asserts<glam::Vec3A> for $name {}
        impl ChannelMap<3> for $name {
            const INDICES: [usize; 3] = [$r, $g, $b];
            const ALPHA: Option<usize> = None;
        }
    };
    ($name:ident, [$a:expr, $b:expr]) => {
        /// Two-channel layout.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
        pub struct $name;
        impl Asserts<[f32; 2]> for $name {}
        #[cfg(feature = "glam")]
        impl Asserts<glam::Vec2> for $name {}
        impl ChannelMap<2> for $name {
            const INDICES: [usize; 2] = [$a, $b];
            const ALPHA: Option<usize> = None;
        }
    };
    ($name:ident, [$a:expr], alpha) => {
        /// Single alpha channel layout.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
        pub struct $name;
        impl Asserts<[f32; 1]> for $name {}
        impl Asserts<f32> for $name {}
        impl ChannelMap<1> for $name {
            const INDICES: [usize; 1] = [$a];
            const ALPHA: Option<usize> = Some(0);
        }
    };
    ($name:ident, [$a:expr]) => {
        /// Single-channel layout.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
        pub struct $name;
        impl Asserts<[f32; 1]> for $name {}
        impl Asserts<f32> for $name {}
        impl ChannelMap<1> for $name {
            const INDICES: [usize; 1] = [$a];
            const ALPHA: Option<usize> = None;
        }
    };
}

define_layout!(Rgba, [0, 1, 2, 3]);
define_layout!(Bgra, [2, 1, 0, 3]);
define_layout!(Argb, [1, 2, 3, 0]);
define_layout!(Abgr, [3, 2, 1, 0]);
define_layout!(Rgb, [0, 1, 2]);
define_layout!(Bgr, [2, 1, 0]);
define_layout!(Rg, [0, 1]);
define_layout!(Ra, [0, 1]);
define_layout!(R, [0]);
define_layout!(G, [0]);
define_layout!(B, [0]);
define_layout!(A, [0], alpha);

/// A color space formed by composing primaries P, transfer function TF,
/// and channel layout L. Layout defaults to Rgba.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RgbSpace<P: Primaries, TF: TransferFunction, L = Rgba>(PhantomData<(P, TF, L)>);

/// Marker for color spaces using the RGB channel model.
pub trait RgbColorSpace: ColorSpace {}

impl<P, TF, L> RgbColorSpace for RgbSpace<P, TF, L>
where
    P: Primaries,
    TF: TransferFunction,
    L: 'static,
{
}

impl<P, TF, L> ColorSpace for RgbSpace<P, TF, L>
where
    P: Primaries,
    TF: TransferFunction,
    L: 'static,
{
    const CHANNELS: usize = 3;
    const LUMINANCE_WEIGHTS: Option<[f32; 3]> = Some(P::TO_XYZ_NATIVE.luminance_weights());
}

impl<P, TF, L, S> Asserts<S> for RgbSpace<P, TF, L>
where
    P: Primaries,
    TF: TransferFunction,
    L: Asserts<S> + 'static,
    S: 'static,
{
}

impl<P, TF, L> LinearLight for RgbSpace<P, TF, L>
where
    P: Primaries,
    TF: TransferFunction + IsLinearEncoding,
    L: 'static,
{
}

impl<P, TF, L> SceneReferred for RgbSpace<P, TF, L>
where
    P: Primaries,
    TF: TransferFunction + IsSceneReferred,
    L: 'static,
{
}

impl<P, TF, L> DisplayReferred for RgbSpace<P, TF, L>
where
    P: Primaries,
    TF: TransferFunction + IsDisplayReferred,
    L: 'static,
{
}

// Compile-time matrix for direct primaries-to-primaries transform.
const fn direct_matrix<P1: Primaries, P2: Primaries>() -> Mat3 {
    use crate::adaptation::adapt;
    let a = adapt::<Bradford>(P1::Native::WHITE_POINT_XYZ, P2::Native::WHITE_POINT_XYZ);
    let adapted = Mat3::mul(&a, &P1::TO_XYZ_NATIVE);
    Mat3::mul(&P2::FROM_XYZ_NATIVE, &adapted)
}

// Layout reorder, four channel. Infallible.
impl<P, TF, L1, L2> Transform<Color<[f32; 4], RgbSpace<P, TF, L1>>> for Color<[f32; 4], RgbSpace<P, TF, L2>>
where
    P: Primaries,
    TF: TransferFunction,
    L1: Asserts<[f32; 4]> + ChannelMap<4> + 'static,
    L2: Asserts<[f32; 4]> + ChannelMap<4> + 'static,
{
    fn transform_from(src: Color<[f32; 4], RgbSpace<P, TF, L1>>, _: &()) -> Self {
        let s = src.inner();
        let [r1, g1, b1, a1] = L1::INDICES;
        let [r2, g2, b2, a2] = L2::INDICES;
        let mut out = [0.0f32; 4];
        out[r2] = s[r1];
        out[g2] = s[g1];
        out[b2] = s[b1];
        out[a2] = s[a1];
        Color::new_unchecked(out)
    }
}

// Layout reorder, three channel. Infallible.
impl<P, TF, L1, L2> Transform<Color<[f32; 3], RgbSpace<P, TF, L1>>> for Color<[f32; 3], RgbSpace<P, TF, L2>>
where
    P: Primaries,
    TF: TransferFunction,
    L1: Asserts<[f32; 3]> + ChannelMap<3> + 'static,
    L2: Asserts<[f32; 3]> + ChannelMap<3> + 'static,
{
    fn transform_from(src: Color<[f32; 3], RgbSpace<P, TF, L1>>, _: &()) -> Self {
        let s = src.inner();
        let [r1, g1, b1] = L1::INDICES;
        let [r2, g2, b2] = L2::INDICES;
        let mut out = [0.0f32; 3];
        out[r2] = s[r1];
        out[g2] = s[g1];
        out[b2] = s[b1];
        Color::new_unchecked(out)
    }
}

// RGB to XYZ, infallible, [f32; 4].
impl<P, TF, W, L> Transform<Color<[f32; 4], RgbSpace<P, TF, L>>> for Color<[f32; 4], Xyz<W>>
where
    P: Primaries + PrimariesToXyz<W, Bradford>,
    TF: TransferFunction,
    W: Illuminant,
    L: Asserts<[f32; 4]> + ChannelMap<4> + 'static,
    Xyz<W>: Asserts<[f32; 4]>,
{
    fn transform_from(src: Color<[f32; 4], RgbSpace<P, TF, L>>, _: &()) -> Self {
        let s = src.inner();
        let [ri, gi, bi, ai] = L::INDICES;
        let rgb = TF::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let xyz = <P as PrimariesToXyz<W, Bradford>>::TO_XYZ.apply(rgb);
        Color::new_unchecked([xyz[0], xyz[1], xyz[2], s[ai]])
    }
}

// XYZ to RGB, fallible, [f32; 4].
impl<P, TF, W, L> TryTransform<Color<[f32; 4], Xyz<W>>> for Color<[f32; 4], RgbSpace<P, TF, L>>
where
    P: Primaries + PrimariesToXyz<W, Bradford>,
    TF: TransferFunction,
    W: Illuminant,
    L: Asserts<[f32; 4]> + ChannelMap<4> + 'static,
    Xyz<W>: Asserts<[f32; 4]>,
{
    fn try_transform_from(src: Color<[f32; 4], Xyz<W>>, _: &()) -> Result<Self, OutOfGamut<Self>> {
        let x = src.inner();
        let rgb = <P as PrimariesToXyz<W, Bradford>>::FROM_XYZ.apply([x[0], x[1], x[2]]);
        let enc = TF::encode::<DefaultMath>(rgb);
        let [ri, gi, bi, ai] = L::INDICES;
        let mut s = [0.0f32; 4];
        s[ri] = enc[0];
        s[gi] = enc[1];
        s[bi] = enc[2];
        s[ai] = x[3];
        let min = TF::ENCODED_MIN;
        let max = TF::ENCODED_MAX;
        let clipped = enc[0] < min[0]
            || enc[0] > max[0]
            || enc[1] < min[1]
            || enc[1] > max[1]
            || enc[2] < min[2]
            || enc[2] > max[2]
            || enc[0].is_nan()
            || enc[1].is_nan()
            || enc[2].is_nan();
        if clipped {
            let c = |v: f32, lo: f32| if v.is_nan() { lo } else { v };
            s[ri] = c(enc[0], min[0]).clamp(min[0], max[0]);
            s[gi] = c(enc[1], min[1]).clamp(min[1], max[1]);
            s[bi] = c(enc[2], min[2]).clamp(min[2], max[2]);
            Err(OutOfGamut {
                clamped: Color::new_unchecked(s),
            })
        } else {
            Ok(Color::new_unchecked(s))
        }
    }
}

// RGB to XYZ, infallible, [f32; 3].
impl<P, TF, W, L> Transform<Color<[f32; 3], RgbSpace<P, TF, L>>> for Color<[f32; 3], Xyz<W>>
where
    P: Primaries + PrimariesToXyz<W, Bradford>,
    TF: TransferFunction,
    W: Illuminant,
    L: Asserts<[f32; 3]> + ChannelMap<3> + 'static,
    Xyz<W>: Asserts<[f32; 3]>,
{
    fn transform_from(src: Color<[f32; 3], RgbSpace<P, TF, L>>, _: &()) -> Self {
        let s = src.inner();
        let [ri, gi, bi] = L::INDICES;
        let rgb = TF::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let xyz = <P as PrimariesToXyz<W, Bradford>>::TO_XYZ.apply(rgb);
        Color::new_unchecked([xyz[0], xyz[1], xyz[2]])
    }
}

// XYZ to RGB, fallible, [f32; 3].
impl<P, TF, W, L> TryTransform<Color<[f32; 3], Xyz<W>>> for Color<[f32; 3], RgbSpace<P, TF, L>>
where
    P: Primaries + PrimariesToXyz<W, Bradford>,
    TF: TransferFunction,
    W: Illuminant,
    L: Asserts<[f32; 3]> + ChannelMap<3> + 'static,
    Xyz<W>: Asserts<[f32; 3]>,
{
    fn try_transform_from(src: Color<[f32; 3], Xyz<W>>, _: &()) -> Result<Self, OutOfGamut<Self>> {
        let x = src.inner();
        let rgb = <P as PrimariesToXyz<W, Bradford>>::FROM_XYZ.apply([x[0], x[1], x[2]]);
        let enc = TF::encode::<DefaultMath>(rgb);
        let [ri, gi, bi] = L::INDICES;
        let mut s = [0.0f32; 3];
        s[ri] = enc[0];
        s[gi] = enc[1];
        s[bi] = enc[2];
        let min = TF::ENCODED_MIN;
        let max = TF::ENCODED_MAX;
        let clipped = enc[0] < min[0]
            || enc[0] > max[0]
            || enc[1] < min[1]
            || enc[1] > max[1]
            || enc[2] < min[2]
            || enc[2] > max[2]
            || enc[0].is_nan()
            || enc[1].is_nan()
            || enc[2].is_nan();
        if clipped {
            let c = |v: f32, lo: f32| if v.is_nan() { lo } else { v };
            s[ri] = c(enc[0], min[0]).clamp(min[0], max[0]);
            s[gi] = c(enc[1], min[1]).clamp(min[1], max[1]);
            s[bi] = c(enc[2], min[2]).clamp(min[2], max[2]);
            Err(OutOfGamut {
                clamped: Color::new_unchecked(s),
            })
        } else {
            Ok(Color::new_unchecked(s))
        }
    }
}

#[cfg(feature = "glam")]
impl<P, TF, W, L> Transform<Color<glam::Vec4, RgbSpace<P, TF, L>>> for Color<glam::Vec4, Xyz<W>>
where
    P: Primaries + PrimariesToXyz<W, Bradford>,
    TF: TransferFunction,
    W: Illuminant,
    L: Asserts<glam::Vec4> + ChannelMap<4> + 'static,
    Xyz<W>: Asserts<glam::Vec4>,
{
    fn transform_from(src: Color<glam::Vec4, RgbSpace<P, TF, L>>, _: &()) -> Self {
        let s = src.inner().to_array();
        let [ri, gi, bi, ai] = L::INDICES;
        let rgb = TF::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let xyz = <P as PrimariesToXyz<W, Bradford>>::TO_XYZ.apply(rgb);
        Color::new_unchecked(glam::Vec4::new(xyz[0], xyz[1], xyz[2], s[ai]))
    }
}

#[cfg(feature = "glam")]
impl<P, TF, W, L> TryTransform<Color<glam::Vec4, Xyz<W>>> for Color<glam::Vec4, RgbSpace<P, TF, L>>
where
    P: Primaries + PrimariesToXyz<W, Bradford>,
    TF: TransferFunction,
    W: Illuminant,
    L: Asserts<glam::Vec4> + ChannelMap<4> + 'static,
    Xyz<W>: Asserts<glam::Vec4>,
{
    fn try_transform_from(src: Color<glam::Vec4, Xyz<W>>, _: &()) -> Result<Self, OutOfGamut<Self>> {
        let x = src.inner().to_array();
        let rgb = <P as PrimariesToXyz<W, Bradford>>::FROM_XYZ.apply([x[0], x[1], x[2]]);
        let enc = TF::encode::<DefaultMath>(rgb);
        let [ri, gi, bi, ai] = L::INDICES;
        let mut s = [0.0f32; 4];
        s[ri] = enc[0];
        s[gi] = enc[1];
        s[bi] = enc[2];
        s[ai] = x[3];
        let min = TF::ENCODED_MIN;
        let max = TF::ENCODED_MAX;
        let clipped = enc[0] < min[0]
            || enc[0] > max[0]
            || enc[1] < min[1]
            || enc[1] > max[1]
            || enc[2] < min[2]
            || enc[2] > max[2]
            || enc[0].is_nan()
            || enc[1].is_nan()
            || enc[2].is_nan();
        if clipped {
            let c = |v: f32, lo: f32| if v.is_nan() { lo } else { v };
            s[ri] = c(enc[0], min[0]).clamp(min[0], max[0]);
            s[gi] = c(enc[1], min[1]).clamp(min[1], max[1]);
            s[bi] = c(enc[2], min[2]).clamp(min[2], max[2]);
            Err(OutOfGamut {
                clamped: Color::new_unchecked(glam::Vec4::from_array(s)),
            })
        } else {
            Ok(Color::new_unchecked(glam::Vec4::from_array(s)))
        }
    }
}

#[cfg(feature = "glam")]
impl<P, TF, W, L> Transform<Color<glam::Vec3A, RgbSpace<P, TF, L>>> for Color<glam::Vec3A, Xyz<W>>
where
    P: Primaries + PrimariesToXyz<W, Bradford>,
    TF: TransferFunction,
    W: Illuminant,
    L: Asserts<glam::Vec3A> + ChannelMap<3> + 'static,
    Xyz<W>: Asserts<glam::Vec3A>,
{
    fn transform_from(src: Color<glam::Vec3A, RgbSpace<P, TF, L>>, _: &()) -> Self {
        let s = src.inner().to_array();
        let [ri, gi, bi] = L::INDICES;
        let rgb = TF::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let xyz = <P as PrimariesToXyz<W, Bradford>>::TO_XYZ.apply(rgb);
        Color::new_unchecked(glam::Vec3A::new(xyz[0], xyz[1], xyz[2]))
    }
}

#[cfg(feature = "glam")]
impl<P, TF, W, L> TryTransform<Color<glam::Vec3A, Xyz<W>>> for Color<glam::Vec3A, RgbSpace<P, TF, L>>
where
    P: Primaries + PrimariesToXyz<W, Bradford>,
    TF: TransferFunction,
    W: Illuminant,
    L: Asserts<glam::Vec3A> + ChannelMap<3> + 'static,
    Xyz<W>: Asserts<glam::Vec3A>,
{
    fn try_transform_from(src: Color<glam::Vec3A, Xyz<W>>, _: &()) -> Result<Self, OutOfGamut<Self>> {
        let x = src.inner().to_array();
        let rgb = <P as PrimariesToXyz<W, Bradford>>::FROM_XYZ.apply([x[0], x[1], x[2]]);
        let enc = TF::encode::<DefaultMath>(rgb);
        let [ri, gi, bi] = L::INDICES;
        let mut s = [0.0f32; 3];
        s[ri] = enc[0];
        s[gi] = enc[1];
        s[bi] = enc[2];
        let min = TF::ENCODED_MIN;
        let max = TF::ENCODED_MAX;
        let clipped = enc[0] < min[0]
            || enc[0] > max[0]
            || enc[1] < min[1]
            || enc[1] > max[1]
            || enc[2] < min[2]
            || enc[2] > max[2]
            || enc[0].is_nan()
            || enc[1].is_nan()
            || enc[2].is_nan();
        if clipped {
            let c = |v: f32, lo: f32| if v.is_nan() { lo } else { v };
            s[ri] = c(enc[0], min[0]).clamp(min[0], max[0]);
            s[gi] = c(enc[1], min[1]).clamp(min[1], max[1]);
            s[bi] = c(enc[2], min[2]).clamp(min[2], max[2]);
            Err(OutOfGamut {
                clamped: Color::new_unchecked(glam::Vec3A::from_array(s)),
            })
        } else {
            Ok(Color::new_unchecked(glam::Vec3A::from_array(s)))
        }
    }
}

// sRGB <-> Display P3 (both use sRGB transfer function, different primaries).
impl<L> Transform<Color<[f32; 4], Srgb<L>>> for Color<[f32; 4], DisplayP3<L>>
where
    L: Asserts<[f32; 4]> + ChannelMap<4> + 'static,
{
    fn transform_from(src: Color<[f32; 4], Srgb<L>>, _: &()) -> Self {
        let s = src.inner();
        let [ri, gi, bi, _ai] = L::INDICES;
        let lin = SrgbTf::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let out = const { direct_matrix::<SrgbPrimaries, P3Primaries>() }.apply(lin);
        let enc = SrgbTf::encode::<DefaultMath>(out);
        let mut r = s;
        r[ri] = enc[0];
        r[gi] = enc[1];
        r[bi] = enc[2];
        Color::new_unchecked(r)
    }
}

impl<L> Transform<Color<[f32; 3], Srgb<L>>> for Color<[f32; 3], DisplayP3<L>>
where
    L: Asserts<[f32; 3]> + ChannelMap<3> + 'static,
{
    fn transform_from(src: Color<[f32; 3], Srgb<L>>, _: &()) -> Self {
        let s = src.inner();
        let [ri, gi, bi] = L::INDICES;
        let lin = SrgbTf::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let out = const { direct_matrix::<SrgbPrimaries, P3Primaries>() }.apply(lin);
        let enc = SrgbTf::encode::<DefaultMath>(out);
        let mut r = s;
        r[ri] = enc[0];
        r[gi] = enc[1];
        r[bi] = enc[2];
        Color::new_unchecked(r)
    }
}

impl<L> Transform<Color<[f32; 4], DisplayP3<L>>> for Color<[f32; 4], Srgb<L>>
where
    L: Asserts<[f32; 4]> + ChannelMap<4> + 'static,
{
    fn transform_from(src: Color<[f32; 4], DisplayP3<L>>, _: &()) -> Self {
        let s = src.inner();
        let [ri, gi, bi, _ai] = L::INDICES;
        let lin = SrgbTf::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let out = const { direct_matrix::<P3Primaries, SrgbPrimaries>() }.apply(lin);
        let enc = SrgbTf::encode::<DefaultMath>(out);
        let mut r = s;
        r[ri] = enc[0];
        r[gi] = enc[1];
        r[bi] = enc[2];
        Color::new_unchecked(r)
    }
}

impl<L> Transform<Color<[f32; 3], DisplayP3<L>>> for Color<[f32; 3], Srgb<L>>
where
    L: Asserts<[f32; 3]> + ChannelMap<3> + 'static,
{
    fn transform_from(src: Color<[f32; 3], DisplayP3<L>>, _: &()) -> Self {
        let s = src.inner();
        let [ri, gi, bi] = L::INDICES;
        let lin = SrgbTf::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let out = const { direct_matrix::<P3Primaries, SrgbPrimaries>() }.apply(lin);
        let enc = SrgbTf::encode::<DefaultMath>(out);
        let mut r = s;
        r[ri] = enc[0];
        r[gi] = enc[1];
        r[bi] = enc[2];
        Color::new_unchecked(r)
    }
}

// sRGB <-> Rec709 (same primaries, transfer function only).
impl<L> Transform<Color<[f32; 4], Srgb<L>>> for Color<[f32; 4], Rec709<L>>
where
    L: Asserts<[f32; 4]> + ChannelMap<4> + 'static,
{
    fn transform_from(src: Color<[f32; 4], Srgb<L>>, _: &()) -> Self {
        let s = src.inner();
        let [ri, gi, bi, _ai] = L::INDICES;
        let lin = SrgbTf::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let enc = Rec709Tf::encode::<DefaultMath>(lin);
        let mut r = s;
        r[ri] = enc[0];
        r[gi] = enc[1];
        r[bi] = enc[2];
        Color::new_unchecked(r)
    }
}

impl<L> Transform<Color<[f32; 3], Srgb<L>>> for Color<[f32; 3], Rec709<L>>
where
    L: Asserts<[f32; 3]> + ChannelMap<3> + 'static,
{
    fn transform_from(src: Color<[f32; 3], Srgb<L>>, _: &()) -> Self {
        let s = src.inner();
        let [ri, gi, bi] = L::INDICES;
        let lin = SrgbTf::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let enc = Rec709Tf::encode::<DefaultMath>(lin);
        let mut r = s;
        r[ri] = enc[0];
        r[gi] = enc[1];
        r[bi] = enc[2];
        Color::new_unchecked(r)
    }
}

impl<L> Transform<Color<[f32; 4], Rec709<L>>> for Color<[f32; 4], Srgb<L>>
where
    L: Asserts<[f32; 4]> + ChannelMap<4> + 'static,
{
    fn transform_from(src: Color<[f32; 4], Rec709<L>>, _: &()) -> Self {
        let s = src.inner();
        let [ri, gi, bi, _ai] = L::INDICES;
        let lin = Rec709Tf::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let enc = SrgbTf::encode::<DefaultMath>(lin);
        let mut r = s;
        r[ri] = enc[0];
        r[gi] = enc[1];
        r[bi] = enc[2];
        Color::new_unchecked(r)
    }
}

impl<L> Transform<Color<[f32; 3], Rec709<L>>> for Color<[f32; 3], Srgb<L>>
where
    L: Asserts<[f32; 3]> + ChannelMap<3> + 'static,
{
    fn transform_from(src: Color<[f32; 3], Rec709<L>>, _: &()) -> Self {
        let s = src.inner();
        let [ri, gi, bi] = L::INDICES;
        let lin = Rec709Tf::decode::<DefaultMath>([s[ri], s[gi], s[bi]]);
        let enc = SrgbTf::encode::<DefaultMath>(lin);
        let mut r = s;
        r[ri] = enc[0];
        r[gi] = enc[1];
        r[bi] = enc[2];
        Color::new_unchecked(r)
    }
}

/// Standard sRGB (IEC 61966-2-1). Web, consumer images, and the default
/// assumption when no color space is specified.
pub type Srgb<L = Rgba> = RgbSpace<SrgbPrimaries, SrgbTf, L>;
/// Linear sRGB. The correct space for premultiplied alpha compositing.
pub type LinearSrgb<L = Rgba> = RgbSpace<SrgbPrimaries, LinearTf, L>;
/// Rec. ITU-R BT.709. HD broadcast. Same primaries as sRGB, different curve.
pub type Rec709<L = Rgba> = RgbSpace<SrgbPrimaries, Rec709Tf, L>;
/// Display P3 (D65). Apple and modern Android wide-gamut displays.
/// Roughly 25% larger gamut than sRGB with the sRGB transfer function.
pub type DisplayP3<L = Rgba> = RgbSpace<P3Primaries, SrgbTf, L>;
/// Linear Display P3. Wide-gamut SDR compositing on P3-capable displays.
pub type LinearP3<L = Rgba> = RgbSpace<P3Primaries, LinearTf, L>;
/// HDR10. Rec. 2020 primaries with PQ (SMPTE ST 2084).
/// Encoded 1.0 represents 10,000 cd/m2.
pub type Hdr10<L = Rgba> = RgbSpace<Rec2020Primaries, PqTf, L>;
/// HLG (ITU-R BT.2100). Rec. 2020 with Hybrid Log-Gamma.
/// SDR-backward-compatible HDR for broadcast.
pub type Hlg<L = Rgba> = RgbSpace<Rec2020Primaries, HlgTf, L>;
/// Linear Rec. 2020. Ultra-wide gamut scene-linear compositing space.
pub type LinearRec2020<L = Rgba> = RgbSpace<Rec2020Primaries, LinearTf, L>;
/// ACEScg (AP1 linear, Academy S-2014-004). VFX and animation rendering
/// working space. All real-world colors have positive values.
pub type AcesCg<L = Rgba> = RgbSpace<AcesAp1Primaries, LinearTf, L>;
/// ACES 2065-1 (AP0 linear, SMPTE ST 2065-1). Full-gamut scene-referred
/// archival and interchange space.
pub type Aces2065<L = Rgba> = RgbSpace<AcesAp0Primaries, LinearTf, L>;
/// ACEScc (AP1 logarithmic, Academy S-2014-003). Color grading working space.
pub type AcesCc<L = Rgba> = RgbSpace<AcesAp1Primaries, AcesCcTf, L>;
/// ACEScct (AP1 quasi-logarithmic, Academy S-2016-001). Grading with toe.
pub type AcesCct<L = Rgba> = RgbSpace<AcesAp1Primaries, AcesCctTf, L>;
/// ProPhoto (ROMM RGB, ISO 22028-2). Extremely wide gamut with gamma 1.8.
/// D50 native illuminant. Used in camera raw and professional photo workflows.
pub type ProPhoto<L = Rgba> = RgbSpace<ProPhotoPrimaries, ProPhotoTf, L>;
/// Linear ProPhoto. D50 native illuminant. Lightroom internal working space.
pub type LinearProPhoto<L = Rgba> = RgbSpace<ProPhotoPrimaries, LinearTf, L>;
/// Theatrical DCI-P3 (SMPTE EG 432-1). Gamma 2.6, DCI white point.
/// Distinct from Display P3 in both white point and transfer function.
pub type DciP3<L = Rgba> = RgbSpace<DciP3Primaries, DciP3Tf, L>;
/// P3 primaries with gamma 2.6 and D65 white point. Non-standard combination.
/// Most users want DisplayP3 (sRGB curve) or DciP3 (DCI white) instead.
pub type P3D65Gamma26<L = Rgba> = RgbSpace<P3Primaries, DciP3Tf, L>;