ranga 1.0.0

Core image processing library — color spaces, blend modes, pixel buffers, filters, and GPU compute for Rust
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
//! Color spaces and conversions.
//!
//! Provides types and conversions between sRGB, linear RGB, HSL, CIE XYZ,
//! CIE L\*a\*b\*, Oklab, Oklch, Display P3, CMYK, and YUV color spaces with
//! proper gamma handling. Includes Delta-E color distance metrics and color
//! temperature.

use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Core types
// ---------------------------------------------------------------------------

/// A color in linear RGBA float space (0.0–1.0 per channel).
///
/// Linear space is required for physically correct blending and compositing.
/// Use [`From<Srgba>`] to convert from sRGB byte space.
///
/// # Examples
///
/// ```
/// use ranga::color::{LinRgba, Srgba};
///
/// let srgb = Srgba { r: 128, g: 64, b: 200, a: 255 };
/// let linear: LinRgba = srgb.into();
/// assert!(linear.r > 0.0 && linear.r < 1.0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LinRgba {
    /// Red channel (0.0–1.0).
    pub r: f32,
    /// Green channel (0.0–1.0).
    pub g: f32,
    /// Blue channel (0.0–1.0).
    pub b: f32,
    /// Alpha channel (0.0–1.0).
    pub a: f32,
}

/// A color in sRGB byte space (0–255 per channel).
///
/// This is the standard color representation for 8-bit displays and image
/// formats. Convert to [`LinRgba`] for blending operations.
///
/// # Examples
///
/// ```
/// use ranga::color::Srgba;
///
/// let red = Srgba { r: 255, g: 0, b: 0, a: 255 };
/// assert_eq!(red.r, 255);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Srgba {
    /// 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,
}

/// A color in HSL space.
///
/// # Examples
///
/// ```
/// use ranga::color::{Hsl, Srgba};
///
/// let red = Srgba { r: 255, g: 0, b: 0, a: 255 };
/// let hsl: Hsl = red.into();
/// assert!((hsl.h - 0.0).abs() < 1.0);
/// assert!((hsl.s - 1.0).abs() < 0.01);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Hsl {
    /// Hue in degrees (0.0–360.0).
    pub h: f32,
    /// Saturation (0.0–1.0).
    pub s: f32,
    /// Lightness (0.0–1.0).
    pub l: f32,
}

/// A color in CIE XYZ space (D65 illuminant).
///
/// XYZ is the intermediate space for converting between sRGB, Display P3,
/// and CIE L\*a\*b\*.
///
/// # Examples
///
/// ```
/// use ranga::color::{CieXyz, LinRgba};
///
/// let white = LinRgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
/// let xyz: CieXyz = white.into();
/// assert!((xyz.y - 1.0).abs() < 0.01);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CieXyz {
    /// X tristimulus value.
    pub x: f64,
    /// Y tristimulus value (luminance).
    pub y: f64,
    /// Z tristimulus value.
    pub z: f64,
}

impl CieXyz {
    /// CIE D65 standard illuminant white point.
    pub const D65_WHITE: Self = Self {
        x: 0.95047,
        y: 1.0,
        z: 1.08883,
    };
    /// CIE D50 standard illuminant white point.
    pub const D50_WHITE: Self = Self {
        x: 0.96422,
        y: 1.0,
        z: 0.82521,
    };
}

/// A color in CIE L\*a\*b\* space (D65 illuminant).
///
/// Perceptually uniform color space used for Delta-E color difference
/// calculations. L\* is lightness (0–100), a\* is green–red, b\* is blue–yellow.
///
/// # Examples
///
/// ```
/// use ranga::color::{CieLab, Srgba};
///
/// let white = Srgba { r: 255, g: 255, b: 255, a: 255 };
/// let lab: CieLab = white.into();
/// assert!((lab.l - 100.0).abs() < 0.1);
/// assert!(lab.a.abs() < 0.5);
/// assert!(lab.b.abs() < 0.5);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CieLab {
    /// Lightness (0.0–100.0).
    pub l: f64,
    /// Green (−) to red (+) axis.
    pub a: f64,
    /// Blue (−) to yellow (+) axis.
    pub b: f64,
}

/// A color in CMYK space (0.0–1.0 per channel).
///
/// Used for print workflows. Convert to/from sRGB with [`cmyk_to_srgb`] and
/// [`srgb_to_cmyk`]. For ICC-accurate conversion, use the [`crate::icc`] module.
///
/// # Examples
///
/// ```
/// use ranga::color::{Cmyk, cmyk_to_srgb};
///
/// let black = Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 1.0 };
/// let srgb = cmyk_to_srgb(&black);
/// assert_eq!(srgb.r, 0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Cmyk {
    /// Cyan (0.0–1.0).
    pub c: f32,
    /// Magenta (0.0–1.0).
    pub m: f32,
    /// Yellow (0.0–1.0).
    pub y: f32,
    /// Key/black (0.0–1.0).
    pub k: f32,
}

/// A color in the Oklab perceptual color space.
///
/// Oklab (Björn Ottosson, 2020) is a perceptual color space designed for
/// uniform lightness and hue linearity. `l` is lightness (0.0–1.0),
/// `a` is green (−) to red (+), and `b` is blue (−) to yellow (+),
/// both roughly in the −0.5 to 0.5 range.
///
/// # Examples
///
/// ```
/// use ranga::color::{Oklab, LinRgba};
///
/// let white = LinRgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
/// let lab: Oklab = white.into();
/// assert!((lab.l - 1.0).abs() < 0.01);
/// assert!(lab.a.abs() < 0.01);
/// assert!(lab.b.abs() < 0.01);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Oklab {
    /// Lightness (0.0–1.0).
    pub l: f32,
    /// Green (−) to red (+) axis (roughly −0.5 to 0.5).
    pub a: f32,
    /// Blue (−) to yellow (+) axis (roughly −0.5 to 0.5).
    pub b: f32,
}

/// A color in the Oklch perceptual color space (polar form of Oklab).
///
/// Oklch represents colors as lightness, chroma (saturation), and hue angle.
/// It is the cylindrical form of [`Oklab`] and is convenient for hue-based
/// manipulations.
///
/// # Examples
///
/// ```
/// use ranga::color::{Oklch, Oklab};
///
/// let lab = Oklab { l: 0.5, a: 0.1, b: -0.1 };
/// let lch: Oklch = lab.into();
/// assert!((lch.l - 0.5).abs() < 1e-5);
/// assert!(lch.c > 0.0);
/// assert!(lch.h >= 0.0 && lch.h < 360.0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Oklch {
    /// Lightness (0.0–1.0).
    pub l: f32,
    /// Chroma (0.0+). Zero means achromatic.
    pub c: f32,
    /// Hue angle in degrees (0.0–360.0).
    pub h: f32,
}

/// Color space identifiers.
///
/// # Examples
///
/// ```
/// use ranga::color::ColorSpace;
///
/// let cs = ColorSpace::Srgb;
/// assert_eq!(cs, ColorSpace::Srgb);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ColorSpace {
    Srgb,
    LinearRgb,
    DisplayP3,
    Bt601,
    Bt709,
    /// ITU-R BT.2020 wide-gamut color space (HDR/UHD video).
    Bt2020,
    /// CIE XYZ tristimulus (device-independent reference space).
    CieXyz,
}

impl std::fmt::Display for ColorSpace {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Srgb => write!(f, "sRGB"),
            Self::LinearRgb => write!(f, "Linear RGB"),
            Self::DisplayP3 => write!(f, "Display P3"),
            Self::Bt601 => write!(f, "BT.601"),
            Self::Bt709 => write!(f, "BT.709"),
            Self::Bt2020 => write!(f, "BT.2020"),
            Self::CieXyz => write!(f, "CIE XYZ"),
        }
    }
}

// ---------------------------------------------------------------------------
// sRGB ↔ Linear
// ---------------------------------------------------------------------------

/// Convert a single sRGB component (0–255) to linear (0.0–1.0).
///
/// Applies the sRGB transfer function (gamma ~2.2) for physically correct
/// color math.
///
/// # Examples
///
/// ```
/// use ranga::color::srgb_to_linear;
///
/// assert_eq!(srgb_to_linear(0), 0.0);
/// assert!((srgb_to_linear(255) - 1.0).abs() < 0.001);
/// let mid = srgb_to_linear(128);
/// assert!(mid > 0.2 && mid < 0.3);
/// ```
#[inline]
#[must_use]
pub fn srgb_to_linear(c: u8) -> f32 {
    let s = c as f32 / 255.0;
    if s <= 0.04045 {
        s / 12.92
    } else {
        ((s + 0.055) / 1.055).powf(2.4)
    }
}

/// Convert a single linear component (0.0–1.0) to sRGB (0–255).
///
/// Applies the inverse sRGB transfer function.
///
/// # Examples
///
/// ```
/// use ranga::color::linear_to_srgb;
///
/// assert_eq!(linear_to_srgb(0.0), 0);
/// assert_eq!(linear_to_srgb(1.0), 255);
/// ```
#[inline]
#[must_use]
pub fn linear_to_srgb(c: f32) -> u8 {
    let s = if c <= 0.0031308 {
        c * 12.92
    } else {
        1.055 * c.powf(1.0 / 2.4) - 0.055
    };
    (s * 255.0 + 0.5).clamp(0.0, 255.0) as u8
}

impl From<Srgba> for LinRgba {
    #[inline]
    fn from(c: Srgba) -> Self {
        Self {
            r: srgb_to_linear(c.r),
            g: srgb_to_linear(c.g),
            b: srgb_to_linear(c.b),
            a: c.a as f32 / 255.0,
        }
    }
}

impl From<LinRgba> for Srgba {
    #[inline]
    fn from(c: LinRgba) -> Self {
        Self {
            r: linear_to_srgb(c.r),
            g: linear_to_srgb(c.g),
            b: linear_to_srgb(c.b),
            a: (c.a * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
        }
    }
}

// ---------------------------------------------------------------------------
// RGB ↔ HSL (bidirectional — replaces rasa's inline hsl code)
// ---------------------------------------------------------------------------

impl From<Srgba> for Hsl {
    #[inline]
    fn from(c: Srgba) -> Self {
        let r = c.r as f32 / 255.0;
        let g = c.g as f32 / 255.0;
        let b = c.b as f32 / 255.0;

        let max = r.max(g).max(b);
        let min = r.min(g).min(b);
        let d = max - min;
        let l = (max + min) / 2.0;

        if d < 1e-6 {
            return Hsl { h: 0.0, s: 0.0, l };
        }

        let s = if l > 0.5 {
            d / (2.0 - max - min)
        } else {
            d / (max + min)
        };

        let h = if (max - r).abs() < 1e-6 {
            (g - b) / d + if g < b { 6.0 } else { 0.0 }
        } else if (max - g).abs() < 1e-6 {
            (b - r) / d + 2.0
        } else {
            (r - g) / d + 4.0
        };

        Hsl { h: h * 60.0, s, l }
    }
}

/// Helper for HSL-to-RGB conversion.
#[inline]
fn hue_to_rgb(p: f32, q: f32, mut t: f32) -> f32 {
    if t < 0.0 {
        t += 1.0;
    }
    if t > 1.0 {
        t -= 1.0;
    }
    if t < 1.0 / 6.0 {
        return p + (q - p) * 6.0 * t;
    }
    if t < 0.5 {
        return q;
    }
    if t < 2.0 / 3.0 {
        return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
    }
    p
}

impl From<Hsl> for Srgba {
    #[inline]
    fn from(c: Hsl) -> Self {
        if c.s < 1e-6 {
            let v = (c.l * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
            return Srgba {
                r: v,
                g: v,
                b: v,
                a: 255,
            };
        }
        let q = if c.l < 0.5 {
            c.l * (1.0 + c.s)
        } else {
            c.l + c.s - c.l * c.s
        };
        let p = 2.0 * c.l - q;
        let h = c.h / 360.0;
        let r = hue_to_rgb(p, q, h + 1.0 / 3.0);
        let g = hue_to_rgb(p, q, h);
        let b = hue_to_rgb(p, q, h - 1.0 / 3.0);
        Srgba {
            r: (r * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
            g: (g * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
            b: (b * 255.0 + 0.5).clamp(0.0, 255.0) as u8,
            a: 255,
        }
    }
}

// ---------------------------------------------------------------------------
// sRGB ↔ CIE XYZ (D65)
// ---------------------------------------------------------------------------

// sRGB to XYZ matrix (D65 illuminant, IEC 61966-2-1)
const SRGB_TO_XYZ: [[f64; 3]; 3] = [
    [0.4124564, 0.3575761, 0.1804375],
    [0.2126729, 0.7151522, 0.0721750],
    [0.0193339, 0.1191920, 0.9503041],
];

// XYZ to sRGB matrix (inverse of above)
const XYZ_TO_SRGB: [[f64; 3]; 3] = [
    [3.2404542, -1.5371385, -0.4985314],
    [-0.9692660, 1.8760108, 0.0415560],
    [0.0556434, -0.2040259, 1.0572252],
];

impl From<LinRgba> for CieXyz {
    #[inline]
    fn from(c: LinRgba) -> Self {
        let r = c.r as f64;
        let g = c.g as f64;
        let b = c.b as f64;
        CieXyz {
            x: SRGB_TO_XYZ[0][0] * r + SRGB_TO_XYZ[0][1] * g + SRGB_TO_XYZ[0][2] * b,
            y: SRGB_TO_XYZ[1][0] * r + SRGB_TO_XYZ[1][1] * g + SRGB_TO_XYZ[1][2] * b,
            z: SRGB_TO_XYZ[2][0] * r + SRGB_TO_XYZ[2][1] * g + SRGB_TO_XYZ[2][2] * b,
        }
    }
}

/// Alpha is set to 1.0 (fully opaque) since [`CieXyz`] does not carry alpha.
impl From<CieXyz> for LinRgba {
    #[inline]
    fn from(c: CieXyz) -> Self {
        LinRgba {
            r: (XYZ_TO_SRGB[0][0] * c.x + XYZ_TO_SRGB[0][1] * c.y + XYZ_TO_SRGB[0][2] * c.z) as f32,
            g: (XYZ_TO_SRGB[1][0] * c.x + XYZ_TO_SRGB[1][1] * c.y + XYZ_TO_SRGB[1][2] * c.z) as f32,
            b: (XYZ_TO_SRGB[2][0] * c.x + XYZ_TO_SRGB[2][1] * c.y + XYZ_TO_SRGB[2][2] * c.z) as f32,
            a: 1.0,
        }
    }
}

// ---------------------------------------------------------------------------
// CIE XYZ ↔ CIE L*a*b* (D65)
// ---------------------------------------------------------------------------

// D65 reference white point
const D65_XN: f64 = 0.95047;
const D65_YN: f64 = 1.00000;
const D65_ZN: f64 = 1.08883;

const LAB_EPSILON: f64 = 0.008856; // (6/29)^3
const LAB_KAPPA: f64 = 903.3; // (29/3)^3

#[inline]
fn lab_f(t: f64) -> f64 {
    if t > LAB_EPSILON {
        t.cbrt()
    } else {
        (LAB_KAPPA * t + 16.0) / 116.0
    }
}

#[inline]
fn lab_f_inv(t: f64) -> f64 {
    if t > 6.0 / 29.0 {
        t * t * t
    } else {
        3.0 * (6.0 / 29.0) * (6.0 / 29.0) * (t - 4.0 / 29.0)
    }
}

impl From<CieXyz> for CieLab {
    #[inline]
    fn from(c: CieXyz) -> Self {
        let fx = lab_f(c.x / D65_XN);
        let fy = lab_f(c.y / D65_YN);
        let fz = lab_f(c.z / D65_ZN);
        CieLab {
            l: 116.0 * fy - 16.0,
            a: 500.0 * (fx - fy),
            b: 200.0 * (fy - fz),
        }
    }
}

impl From<CieLab> for CieXyz {
    #[inline]
    fn from(c: CieLab) -> Self {
        let fy = (c.l + 16.0) / 116.0;
        let fx = c.a / 500.0 + fy;
        let fz = fy - c.b / 200.0;
        CieXyz {
            x: D65_XN * lab_f_inv(fx),
            y: D65_YN * lab_f_inv(fy),
            z: D65_ZN * lab_f_inv(fz),
        }
    }
}

/// Convenience: sRGB byte → Lab in one step.
impl From<Srgba> for CieLab {
    #[inline]
    fn from(c: Srgba) -> Self {
        let lin: LinRgba = c.into();
        let xyz: CieXyz = lin.into();
        xyz.into()
    }
}

// ---------------------------------------------------------------------------
// Display P3 ↔ sRGB (both linear space)
// ---------------------------------------------------------------------------

// P3 linear → sRGB linear (via XYZ)
const P3_TO_SRGB: [[f64; 3]; 3] = [
    [1.2249401, -0.2249402, 0.0000001],
    [-0.0420569, 1.0420571, -0.0000002],
    [-0.0196376, -0.0786361, 1.0982735],
];

// sRGB linear → P3 linear
const SRGB_TO_P3: [[f64; 3]; 3] = [
    [0.8224622, 0.1775380, -0.0000002],
    [0.0331942, 0.9668058, 0.0000000],
    [0.0170608, 0.0723740, 0.9105650],
];

/// Convert a color from Display P3 linear space to sRGB linear space.
///
/// Both input and output are in linear (gamma 1.0) space. P3 and sRGB share
/// the same transfer function, so apply [`srgb_to_linear`]/[`linear_to_srgb`]
/// for encoding.
///
/// # Examples
///
/// ```
/// use ranga::color::p3_to_linear_srgb;
///
/// let (r, g, b) = p3_to_linear_srgb(1.0, 0.0, 0.0);
/// assert!(r > 1.0); // P3 red is outside sRGB gamut
/// ```
#[inline]
#[must_use]
pub fn p3_to_linear_srgb(r: f64, g: f64, b: f64) -> (f64, f64, f64) {
    (
        P3_TO_SRGB[0][0] * r + P3_TO_SRGB[0][1] * g + P3_TO_SRGB[0][2] * b,
        P3_TO_SRGB[1][0] * r + P3_TO_SRGB[1][1] * g + P3_TO_SRGB[1][2] * b,
        P3_TO_SRGB[2][0] * r + P3_TO_SRGB[2][1] * g + P3_TO_SRGB[2][2] * b,
    )
}

/// Convert a color from sRGB linear space to Display P3 linear space.
///
/// # Examples
///
/// ```
/// use ranga::color::linear_srgb_to_p3;
///
/// let (r, g, b) = linear_srgb_to_p3(1.0, 0.0, 0.0);
/// assert!(r < 1.0); // sRGB red fits within P3
/// ```
#[inline]
#[must_use]
pub fn linear_srgb_to_p3(r: f64, g: f64, b: f64) -> (f64, f64, f64) {
    (
        SRGB_TO_P3[0][0] * r + SRGB_TO_P3[0][1] * g + SRGB_TO_P3[0][2] * b,
        SRGB_TO_P3[1][0] * r + SRGB_TO_P3[1][1] * g + SRGB_TO_P3[1][2] * b,
        SRGB_TO_P3[2][0] * r + SRGB_TO_P3[2][1] * g + SRGB_TO_P3[2][2] * b,
    )
}

// ---------------------------------------------------------------------------
// CMYK ↔ sRGB (naive — for ICC-accurate, use crate::icc)
// ---------------------------------------------------------------------------

/// Convert CMYK to sRGB (naive, without ICC profile).
///
/// For print-accurate conversion, use an ICC profile via [`crate::icc`].
///
/// # Examples
///
/// ```
/// use ranga::color::{Cmyk, cmyk_to_srgb};
///
/// let cyan = Cmyk { c: 1.0, m: 0.0, y: 0.0, k: 0.0 };
/// let srgb = cmyk_to_srgb(&cyan);
/// assert_eq!(srgb.r, 0);
/// assert_eq!(srgb.g, 255);
/// assert_eq!(srgb.b, 255);
/// ```
#[inline]
#[must_use]
pub fn cmyk_to_srgb(c: &Cmyk) -> Srgba {
    let r = (255.0 * (1.0 - c.c) * (1.0 - c.k) + 0.5).clamp(0.0, 255.0) as u8;
    let g = (255.0 * (1.0 - c.m) * (1.0 - c.k) + 0.5).clamp(0.0, 255.0) as u8;
    let b = (255.0 * (1.0 - c.y) * (1.0 - c.k) + 0.5).clamp(0.0, 255.0) as u8;
    Srgba { r, g, b, a: 255 }
}

/// Convert sRGB to CMYK (naive, without ICC profile).
///
/// # Examples
///
/// ```
/// use ranga::color::{Srgba, srgb_to_cmyk};
///
/// let white = Srgba { r: 255, g: 255, b: 255, a: 255 };
/// let cmyk = srgb_to_cmyk(&white);
/// assert!((cmyk.k - 0.0).abs() < 0.01);
/// ```
#[inline]
#[must_use]
pub fn srgb_to_cmyk(c: &Srgba) -> Cmyk {
    let r = c.r as f32 / 255.0;
    let g = c.g as f32 / 255.0;
    let b = c.b as f32 / 255.0;
    let k = 1.0 - r.max(g).max(b);
    if k >= 1.0 - 1e-6 {
        return Cmyk {
            c: 0.0,
            m: 0.0,
            y: 0.0,
            k: 1.0,
        };
    }
    let inv_k = 1.0 / (1.0 - k);
    Cmyk {
        c: (1.0 - r - k) * inv_k,
        m: (1.0 - g - k) * inv_k,
        y: (1.0 - b - k) * inv_k,
        k,
    }
}

// ---------------------------------------------------------------------------
// Linear RGB ↔ Oklab (Björn Ottosson, 2020)
// ---------------------------------------------------------------------------

/// Convert linear sRGB to Oklab.
///
/// Uses the standard Ottosson two-matrix approach: linear RGB → LMS via M1,
/// cube-root each channel, then LMS' → Oklab via M2.
///
/// # Examples
///
/// ```
/// use ranga::color::{Oklab, LinRgba};
///
/// let red = LinRgba { r: 1.0, g: 0.0, b: 0.0, a: 1.0 };
/// let lab: Oklab = red.into();
/// assert!(lab.l > 0.0 && lab.l < 1.0);
/// ```
#[allow(clippy::excessive_precision)]
impl From<LinRgba> for Oklab {
    #[inline]
    fn from(c: LinRgba) -> Self {
        // M1: linear sRGB → LMS
        let l = 0.4122214708_f32 * c.r + 0.5363325363 * c.g + 0.0514459929 * c.b;
        let m = 0.2119034982_f32 * c.r + 0.6806995451 * c.g + 0.1073969566 * c.b;
        let s = 0.0883024619_f32 * c.r + 0.2817188376 * c.g + 0.6299787005 * c.b;

        // Cube root
        let l_ = l.cbrt();
        let m_ = m.cbrt();
        let s_ = s.cbrt();

        // M2: cube-rooted LMS → Oklab
        Oklab {
            l: 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
            a: 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
            b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
        }
    }
}

/// Convert Oklab back to linear sRGB.
///
/// Inverts the M2 and M1 matrices, cubing the intermediate LMS channels.
/// Alpha is set to 1.0 (fully opaque) since [`Oklab`] does not carry alpha.
///
/// # Examples
///
/// ```
/// use ranga::color::{Oklab, LinRgba};
///
/// let lab = Oklab { l: 0.5, a: 0.0, b: 0.0 };
/// let rgb: LinRgba = lab.into();
/// assert!(rgb.r >= 0.0);
/// ```
#[allow(clippy::excessive_precision)]
impl From<Oklab> for LinRgba {
    #[inline]
    fn from(c: Oklab) -> Self {
        // Inverse M2: Oklab → cube-rooted LMS
        let l_ = c.l + 0.3963377774 * c.a + 0.2158037573 * c.b;
        let m_ = c.l - 0.1055613458 * c.a - 0.0638541728 * c.b;
        let s_ = c.l - 0.0894841775 * c.a - 1.2914855480 * c.b;

        // Cube to recover LMS
        let l = l_ * l_ * l_;
        let m = m_ * m_ * m_;
        let s = s_ * s_ * s_;

        // Inverse M1: LMS → linear sRGB
        LinRgba {
            r: 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
            g: -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
            b: -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
            a: 1.0,
        }
    }
}

/// Convert Oklab to its polar form Oklch.
///
/// Chroma is the Euclidean length of (a, b) and hue is the angle in degrees.
///
/// # Examples
///
/// ```
/// use ranga::color::{Oklab, Oklch};
///
/// let gray = Oklab { l: 0.5, a: 0.0, b: 0.0 };
/// let lch: Oklch = gray.into();
/// assert!(lch.c < 1e-5); // achromatic
/// ```
impl From<Oklab> for Oklch {
    #[inline]
    fn from(c: Oklab) -> Self {
        let chroma = (c.a * c.a + c.b * c.b).sqrt();
        let hue = if chroma < 1e-8 {
            0.0
        } else {
            c.b.atan2(c.a).to_degrees().rem_euclid(360.0)
        };
        Oklch {
            l: c.l,
            c: chroma,
            h: hue,
        }
    }
}

/// Convert Oklch (polar) back to Oklab (rectangular).
///
/// # Examples
///
/// ```
/// use ranga::color::{Oklab, Oklch};
///
/// let lch = Oklch { l: 0.7, c: 0.15, h: 180.0 };
/// let lab: Oklab = lch.into();
/// assert!((lab.a - (-0.15)).abs() < 1e-5);
/// assert!(lab.b.abs() < 1e-5);
/// ```
impl From<Oklch> for Oklab {
    #[inline]
    fn from(c: Oklch) -> Self {
        let h_rad = c.h.to_radians();
        Oklab {
            l: c.l,
            a: c.c * h_rad.cos(),
            b: c.c * h_rad.sin(),
        }
    }
}

/// Convenience: sRGB byte → Oklab in one step.
///
/// Converts through [`LinRgba`] as the intermediate space.
///
/// # Examples
///
/// ```
/// use ranga::color::{Oklab, Srgba};
///
/// let red = Srgba { r: 255, g: 0, b: 0, a: 255 };
/// let lab: Oklab = red.into();
/// assert!(lab.l > 0.0);
/// ```
impl From<Srgba> for Oklab {
    #[inline]
    fn from(c: Srgba) -> Self {
        let lin: LinRgba = c.into();
        lin.into()
    }
}

// ---------------------------------------------------------------------------
// Color temperature (Tanner Helland approximation of Planckian locus)
// ---------------------------------------------------------------------------

/// Compute RGB multipliers for a given color temperature in Kelvin.
///
/// Returns `[R, G, B]` multipliers in 0.0–1.0 range. Multiply with pixel
/// values to apply a white-balance shift. Valid range is 1000–40000 K.
/// 6600 K is approximately daylight (neutral).
///
/// Matches the temperature adjustment used in tazama's color grading pipeline.
///
/// # Examples
///
/// ```
/// use ranga::color::color_temperature;
///
/// let daylight = color_temperature(6600.0);
/// assert!((daylight[0] - 1.0).abs() < 0.01); // neutral at ~6600K
///
/// let warm = color_temperature(3000.0);
/// assert!(warm[2] < warm[0]); // warm = more red, less blue
/// ```
#[must_use]
pub fn color_temperature(kelvin: f32) -> [f32; 3] {
    if kelvin.is_nan() {
        return [1.0, 1.0, 1.0]; // neutral for invalid input
    }
    let temp = kelvin.clamp(1000.0, 40000.0) / 100.0;

    let r = if temp <= 66.0 {
        1.0
    } else {
        (329.699 * (temp - 60.0).powf(-0.133_205) / 255.0).clamp(0.0, 1.0)
    };

    let g = if temp <= 66.0 {
        ((99.4708 * temp.ln() - 161.1196) / 255.0).clamp(0.0, 1.0)
    } else {
        (288.1222 * (temp - 60.0).powf(-0.075_515) / 255.0).clamp(0.0, 1.0)
    };

    let b = if temp >= 66.0 {
        1.0
    } else if temp <= 19.0 {
        0.0
    } else {
        ((138.5177 * (temp - 10.0).ln() - 305.0448) / 255.0).clamp(0.0, 1.0)
    };

    [r, g, b]
}

// ---------------------------------------------------------------------------
// Delta-E color distance (CIE76, CIE94, CIEDE2000)
// ---------------------------------------------------------------------------

/// CIE76 color distance (Euclidean distance in L\*a\*b\* space).
///
/// Simple and fast but not perceptually uniform for large differences.
///
/// # Examples
///
/// ```
/// use ranga::color::{CieLab, delta_e_cie76};
///
/// let a = CieLab { l: 50.0, a: 0.0, b: 0.0 };
/// let b = CieLab { l: 50.0, a: 0.0, b: 0.0 };
/// assert!(delta_e_cie76(&a, &b) < 1e-10);
/// ```
#[inline]
#[must_use]
pub fn delta_e_cie76(a: &CieLab, b: &CieLab) -> f64 {
    let dl = a.l - b.l;
    let da = a.a - b.a;
    let db = a.b - b.b;
    (dl * dl + da * da + db * db).sqrt()
}

/// CIE94 color distance (graphic arts weighting).
///
/// More perceptually uniform than CIE76, especially for chromatic differences.
///
/// # Examples
///
/// ```
/// use ranga::color::{CieLab, delta_e_cie94};
///
/// let a = CieLab { l: 50.0, a: 25.0, b: 0.0 };
/// let b = CieLab { l: 50.0, a: 0.0, b: 0.0 };
/// assert!(delta_e_cie94(&a, &b) > 0.0);
/// ```
#[inline]
#[must_use]
pub fn delta_e_cie94(a: &CieLab, b: &CieLab) -> f64 {
    let dl = a.l - b.l;
    let da = a.a - b.a;
    let db = a.b - b.b;
    let c1 = (a.a * a.a + a.b * a.b).sqrt();
    let c2 = (b.a * b.a + b.b * b.b).sqrt();
    let dc = c1 - c2;
    let dh_sq = da * da + db * db - dc * dc;
    let dh_sq = dh_sq.max(0.0); // guard against floating-point negatives

    // Graphic arts constants
    let sl = 1.0;
    let sc = 1.0 + 0.045 * c1;
    let sh = 1.0 + 0.015 * c1;

    ((dl / sl).powi(2) + (dc / sc).powi(2) + dh_sq / (sh * sh)).sqrt()
}

/// CIEDE2000 color distance — the most perceptually accurate Delta-E formula.
///
/// Implements the full Sharma et al. (2005) specification with lightness,
/// chroma, and hue weighting plus the rotation term.
///
/// # Examples
///
/// ```
/// use ranga::color::{CieLab, delta_e_ciede2000};
///
/// let a = CieLab { l: 50.0, a: 2.6772, b: -79.7751 };
/// let b = CieLab { l: 50.0, a: 0.0, b: -82.7485 };
/// let de = delta_e_ciede2000(&a, &b);
/// assert!(de > 2.0 && de < 3.0);
/// ```
#[inline]
#[must_use]
pub fn delta_e_ciede2000(lab1: &CieLab, lab2: &CieLab) -> f64 {
    use std::f64::consts::PI;

    let c1_star = (lab1.a * lab1.a + lab1.b * lab1.b).sqrt();
    let c2_star = (lab2.a * lab2.a + lab2.b * lab2.b).sqrt();
    let c_bar = (c1_star + c2_star) / 2.0;

    let c_bar_7 = c_bar.powi(7);
    let g = 0.5 * (1.0 - (c_bar_7 / (c_bar_7 + 6103515625.0_f64)).sqrt()); // 25^7

    let a1_prime = lab1.a * (1.0 + g);
    let a2_prime = lab2.a * (1.0 + g);

    let c1_prime = (a1_prime * a1_prime + lab1.b * lab1.b).sqrt();
    let c2_prime = (a2_prime * a2_prime + lab2.b * lab2.b).sqrt();

    let h1_prime = lab1.b.atan2(a1_prime).to_degrees().rem_euclid(360.0);
    let h2_prime = lab2.b.atan2(a2_prime).to_degrees().rem_euclid(360.0);

    // Step 2: ΔL', ΔC', ΔH'
    let dl_prime = lab2.l - lab1.l;
    let dc_prime = c2_prime - c1_prime;

    let dh_prime_deg = if c1_prime * c2_prime < 1e-10 {
        0.0
    } else if (h2_prime - h1_prime).abs() <= 180.0 {
        h2_prime - h1_prime
    } else if h2_prime - h1_prime > 180.0 {
        h2_prime - h1_prime - 360.0
    } else {
        h2_prime - h1_prime + 360.0
    };

    let dh_prime = 2.0 * (c1_prime * c2_prime).sqrt() * (dh_prime_deg / 2.0 * PI / 180.0).sin();

    // Step 3: Weighting functions
    let l_bar_prime = (lab1.l + lab2.l) / 2.0;
    let c_bar_prime = (c1_prime + c2_prime) / 2.0;

    let h_bar_prime = if c1_prime * c2_prime < 1e-10 {
        h1_prime + h2_prime
    } else if (h1_prime - h2_prime).abs() <= 180.0 {
        (h1_prime + h2_prime) / 2.0
    } else if h1_prime + h2_prime < 360.0 {
        (h1_prime + h2_prime + 360.0) / 2.0
    } else {
        (h1_prime + h2_prime - 360.0) / 2.0
    };

    let t = 1.0 - 0.17 * ((h_bar_prime - 30.0) * PI / 180.0).cos()
        + 0.24 * ((2.0 * h_bar_prime) * PI / 180.0).cos()
        + 0.32 * ((3.0 * h_bar_prime + 6.0) * PI / 180.0).cos()
        - 0.20 * ((4.0 * h_bar_prime - 63.0) * PI / 180.0).cos();

    let l_diff = l_bar_prime - 50.0;
    let sl = 1.0 + 0.015 * l_diff * l_diff / (20.0 + l_diff * l_diff).sqrt();
    let sc = 1.0 + 0.045 * c_bar_prime;
    let sh = 1.0 + 0.015 * c_bar_prime * t;

    let d_theta = 30.0 * (-((h_bar_prime - 275.0) / 25.0).powi(2)).exp();
    let c_bar_prime_7 = c_bar_prime.powi(7);
    let rc = 2.0 * (c_bar_prime_7 / (c_bar_prime_7 + 6103515625.0_f64)).sqrt();
    let rt = -(2.0 * d_theta * PI / 180.0).sin() * rc;

    let l_term = dl_prime / sl;
    let c_term = dc_prime / sc;
    let h_term = dh_prime / sh;

    (l_term * l_term + c_term * c_term + h_term * h_term + rt * c_term * h_term).sqrt()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn srgb_linear_roundtrip() {
        for v in [0u8, 1, 50, 128, 200, 255] {
            let lin = srgb_to_linear(v);
            let back = linear_to_srgb(lin);
            assert!(
                (v as i16 - back as i16).unsigned_abs() <= 1,
                "v={v} back={back}"
            );
        }
    }

    #[test]
    fn srgba_to_linrgba_black() {
        let c: LinRgba = Srgba {
            r: 0,
            g: 0,
            b: 0,
            a: 255,
        }
        .into();
        assert_eq!(c.r, 0.0);
        assert_eq!(c.g, 0.0);
        assert_eq!(c.b, 0.0);
        assert!((c.a - 1.0).abs() < 1e-3);
    }

    #[test]
    fn srgba_to_linrgba_white() {
        let c: LinRgba = Srgba {
            r: 255,
            g: 255,
            b: 255,
            a: 255,
        }
        .into();
        assert!((c.r - 1.0).abs() < 1e-3);
    }

    #[test]
    fn hsl_from_red() {
        let hsl: Hsl = Srgba {
            r: 255,
            g: 0,
            b: 0,
            a: 255,
        }
        .into();
        assert!((hsl.h - 0.0).abs() < 1.0);
        assert!((hsl.s - 1.0).abs() < 1e-3);
        assert!((hsl.l - 0.5).abs() < 1e-3);
    }

    #[test]
    fn hsl_from_gray() {
        let hsl: Hsl = Srgba {
            r: 128,
            g: 128,
            b: 128,
            a: 255,
        }
        .into();
        assert!((hsl.s - 0.0).abs() < 1e-3);
    }

    #[test]
    fn hsl_roundtrip() {
        for (r, g, b) in [(255, 0, 0), (0, 255, 0), (0, 0, 255), (128, 64, 200)] {
            let orig = Srgba { r, g, b, a: 255 };
            let hsl: Hsl = orig.into();
            let back: Srgba = hsl.into();
            assert!((orig.r as i16 - back.r as i16).unsigned_abs() <= 1, "r");
            assert!((orig.g as i16 - back.g as i16).unsigned_abs() <= 1, "g");
            assert!((orig.b as i16 - back.b as i16).unsigned_abs() <= 1, "b");
        }
    }

    #[test]
    fn hsl_gray_roundtrip() {
        let orig = Srgba {
            r: 128,
            g: 128,
            b: 128,
            a: 255,
        };
        let hsl: Hsl = orig.into();
        let back: Srgba = hsl.into();
        assert_eq!(back.r, back.g);
        assert_eq!(back.g, back.b);
    }

    #[test]
    fn xyz_white_y_is_one() {
        let white = LinRgba {
            r: 1.0,
            g: 1.0,
            b: 1.0,
            a: 1.0,
        };
        let xyz: CieXyz = white.into();
        assert!((xyz.y - 1.0).abs() < 0.01);
    }

    #[test]
    fn xyz_roundtrip() {
        let orig = LinRgba {
            r: 0.5,
            g: 0.3,
            b: 0.8,
            a: 1.0,
        };
        let xyz: CieXyz = orig.into();
        let back: LinRgba = xyz.into();
        // f64→f32→f64 roundtrip loses precision
        assert!((orig.r - back.r).abs() < 1e-3);
        assert!((orig.g - back.g).abs() < 1e-3);
        assert!((orig.b - back.b).abs() < 1e-3);
    }

    #[test]
    fn lab_white_is_100() {
        let white: CieLab = Srgba {
            r: 255,
            g: 255,
            b: 255,
            a: 255,
        }
        .into();
        assert!((white.l - 100.0).abs() < 0.5);
        assert!(white.a.abs() < 1.0);
        // b* offset is expected: sRGB matrix Z-row sums to 1.0288, not D65 Zn=1.0888
        assert!(white.b.abs() < 5.0);
    }

    #[test]
    fn lab_black_is_zero() {
        let black: CieLab = Srgba {
            r: 0,
            g: 0,
            b: 0,
            a: 255,
        }
        .into();
        assert!(black.l.abs() < 0.5);
    }

    #[test]
    fn lab_roundtrip() {
        let orig = Srgba {
            r: 128,
            g: 64,
            b: 200,
            a: 255,
        };
        let lab: CieLab = orig.into();
        let xyz: CieXyz = lab.into();
        let lin: LinRgba = xyz.into();
        let back: Srgba = lin.into();
        assert!((orig.r as i16 - back.r as i16).unsigned_abs() <= 1);
        assert!((orig.g as i16 - back.g as i16).unsigned_abs() <= 1);
        assert!((orig.b as i16 - back.b as i16).unsigned_abs() <= 1);
    }

    #[test]
    fn p3_srgb_roundtrip() {
        let (r, g, b) = linear_srgb_to_p3(0.5, 0.3, 0.8);
        let (r2, g2, b2) = p3_to_linear_srgb(r, g, b);
        assert!((0.5 - r2).abs() < 1e-4);
        assert!((0.3 - g2).abs() < 1e-4);
        assert!((0.8 - b2).abs() < 1e-4);
    }

    #[test]
    fn p3_red_outside_srgb() {
        let (r, _, _) = p3_to_linear_srgb(1.0, 0.0, 0.0);
        assert!(r > 1.0, "P3 red should exceed sRGB gamut");
    }

    #[test]
    fn cmyk_roundtrip() {
        let orig = Srgba {
            r: 200,
            g: 100,
            b: 50,
            a: 255,
        };
        let cmyk = srgb_to_cmyk(&orig);
        let back = cmyk_to_srgb(&cmyk);
        assert!((orig.r as i16 - back.r as i16).unsigned_abs() <= 1);
        assert!((orig.g as i16 - back.g as i16).unsigned_abs() <= 1);
        assert!((orig.b as i16 - back.b as i16).unsigned_abs() <= 1);
    }

    #[test]
    fn cmyk_black() {
        let cmyk = srgb_to_cmyk(&Srgba {
            r: 0,
            g: 0,
            b: 0,
            a: 255,
        });
        assert!((cmyk.k - 1.0).abs() < 0.01);
    }

    #[test]
    fn temperature_daylight_neutral() {
        let d = color_temperature(6600.0);
        assert!((d[0] - 1.0).abs() < 0.02);
    }

    #[test]
    fn temperature_warm_has_more_red() {
        let w = color_temperature(3000.0);
        assert!(w[0] > w[2], "warm light should have more red than blue");
    }

    #[test]
    fn temperature_cool_has_more_blue() {
        let c = color_temperature(10000.0);
        assert!(c[2] > c[0], "cool light should have more blue than red");
    }

    #[test]
    fn delta_e_76_identical() {
        let a = CieLab {
            l: 50.0,
            a: 25.0,
            b: -10.0,
        };
        assert!(delta_e_cie76(&a, &a) < 1e-10);
    }

    #[test]
    fn delta_e_76_known() {
        let a = CieLab {
            l: 50.0,
            a: 0.0,
            b: 0.0,
        };
        let b = CieLab {
            l: 53.0,
            a: 4.0,
            b: 0.0,
        };
        let de = delta_e_cie76(&a, &b);
        assert!((de - 5.0).abs() < 0.01); // sqrt(9+16) = 5
    }

    #[test]
    fn delta_e_94_positive() {
        let a = CieLab {
            l: 50.0,
            a: 25.0,
            b: 0.0,
        };
        let b = CieLab {
            l: 50.0,
            a: 0.0,
            b: 0.0,
        };
        assert!(delta_e_cie94(&a, &b) > 0.0);
    }

    #[test]
    fn delta_e_2000_identical() {
        let a = CieLab {
            l: 50.0,
            a: 25.0,
            b: -10.0,
        };
        assert!(delta_e_ciede2000(&a, &a) < 1e-10);
    }

    #[test]
    fn delta_e_2000_known_pair() {
        // Sharma (2005) test pair #1
        let a = CieLab {
            l: 50.0,
            a: 2.6772,
            b: -79.7751,
        };
        let b = CieLab {
            l: 50.0,
            a: 0.0,
            b: -82.7485,
        };
        let de = delta_e_ciede2000(&a, &b);
        assert!((de - 2.0425).abs() < 0.01, "got {de}");
    }

    #[test]
    fn oklab_white() {
        let white: Oklab = Srgba {
            r: 255,
            g: 255,
            b: 255,
            a: 255,
        }
        .into();
        assert!((white.l - 1.0).abs() < 0.01, "L={}", white.l);
        assert!(white.a.abs() < 0.01, "a={}", white.a);
        assert!(white.b.abs() < 0.01, "b={}", white.b);
    }

    #[test]
    fn oklab_black() {
        let black: Oklab = Srgba {
            r: 0,
            g: 0,
            b: 0,
            a: 255,
        }
        .into();
        assert!(black.l.abs() < 0.01, "L={}", black.l);
        assert!(black.a.abs() < 0.01, "a={}", black.a);
        assert!(black.b.abs() < 0.01, "b={}", black.b);
    }

    #[test]
    fn oklab_roundtrip() {
        for (r, g, b) in [(255, 0, 0), (0, 255, 0), (0, 0, 255), (128, 64, 200)] {
            let orig = Srgba { r, g, b, a: 255 };
            let lin: LinRgba = orig.into();
            let lab: Oklab = lin.into();
            let back_lin: LinRgba = lab.into();
            let back: Srgba = back_lin.into();
            assert!(
                (orig.r as i16 - back.r as i16).unsigned_abs() <= 1,
                "r: orig={} back={}",
                orig.r,
                back.r
            );
            assert!(
                (orig.g as i16 - back.g as i16).unsigned_abs() <= 1,
                "g: orig={} back={}",
                orig.g,
                back.g
            );
            assert!(
                (orig.b as i16 - back.b as i16).unsigned_abs() <= 1,
                "b: orig={} back={}",
                orig.b,
                back.b
            );
        }
    }

    #[test]
    fn oklch_roundtrip() {
        let orig = Oklab {
            l: 0.6,
            a: 0.15,
            b: -0.08,
        };
        let lch: Oklch = orig.into();
        let back: Oklab = lch.into();
        assert!((orig.l - back.l).abs() < 1e-5, "l");
        assert!((orig.a - back.a).abs() < 1e-5, "a");
        assert!((orig.b - back.b).abs() < 1e-5, "b");
    }

    #[test]
    fn oklch_red_hue() {
        let red: Oklab = Srgba {
            r: 255,
            g: 0,
            b: 0,
            a: 255,
        }
        .into();
        let lch: Oklch = red.into();
        assert!(
            lch.h >= 20.0 && lch.h <= 30.0,
            "red hue={}, expected 20-30 degrees",
            lch.h
        );
    }
}