kallo-core 0.1.0

Reference film model: characteristic curves and development kinetics
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
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
//! The render: a negative is exposed, developed, and printed.
//!
//! Phase 0 keeps a single scalar per channel. There is no spectrum yet, but
//! the *shape* of the computation is already the final one: light becomes
//! density on the negative, the negative becomes light again in the enlarger,
//! and that light becomes density on the paper.
//!
//! ```text
//! E ──► D_neg ──► T = 10^-D ──► D_print ──► R = 10^-D
//!        ▲                          ▲
//!    H&D curve                 paper curve,
//!  (development)              balanced on 18 % grey
//! ```

use crate::curve::CharacteristicCurve;
use crate::development::DevelopmentParams;
use crate::emulsion::{FilmStock, PaperStock};
use crate::lut::ExposureLut;
use crate::model::SpectralModel;
use crate::print::PrintContext;
use crate::scan::ScanContext;
use crate::spectral::{CameraProfile, SpectralContext};

/// log10 of the luminance a mid-grey card reflects. The anchor everything is
/// balanced against; 0.18 is the conventional value.
#[must_use]
pub fn mid_grey_log_e() -> f64 {
    0.18_f64.log10()
}

/// Everything needed to render: which film, which paper, and how it was developed.
#[derive(Debug, Clone)]
pub struct RenderParams {
    /// The negative.
    pub film: &'static FilmStock,
    /// The paper it is printed on.
    pub paper: &'static PaperStock,
    /// How the negative was developed.
    pub development: DevelopmentParams,
    /// Exposure offset in stops, applied before the negative is exposed.
    pub exposure_ev: f64,
    /// Expose through the spectral path instead of the per-channel scalar one.
    pub spectral: bool,
    /// Which sensor the input RGB is assumed to have come from. Ignored by the
    /// scalar path.
    pub camera: CameraProfile,
    /// Bake the spectral exposure into a `size^3` table. Zero disables it.
    pub lut_size: usize,
    /// Print through spectral dye absorption and paper layer sensitivities.
    ///
    /// A non-empty colour pack or a heat glass turns this on by itself: those
    /// are spectra in the light path, and the scalar print has no wavelength
    /// to put them in.
    pub spectral_print: bool,
    /// Scan through spectral reflectance, illuminant and observer.
    pub spectral_scan: bool,
    /// Run the cyan-sensitive layer's inhibitor (ADR 0018).
    ///
    /// Off by default, and only meaningful for a stock that declares such a
    /// layer: its strength and diffusion length are placeholders, so turning it
    /// on is asking for a demonstration of the mechanism, not for a prediction
    /// about the film.
    pub interimage: bool,
    /// How much light the enlarger puts through, in stops, on top of the
    /// exposure solved to print a mid grey as a mid grey.
    ///
    /// Zero is "the test strip that came out right". Positive is more light,
    /// which is a darker print; negative is less. This is the number a printer
    /// dials, and the one a dodge or a burn will vary per pixel once the bench
    /// can ask for that.
    pub print_exposure_ev: f64,
    /// The enlarger's colour pack in Kodak CC units, and an optional heat glass.
    /// Empty and `None` are the model without this stage.
    pub filters: crate::filters::FilterPack,
    /// The heat-absorbing glass in the light path, at its 2 mm reference.
    pub heat_glass: Option<crate::filters::HeatGlass>,
}

impl Default for RenderParams {
    fn default() -> Self {
        Self {
            film: crate::emulsion::film_stock("vision3_500t").expect("built-in stock"),
            paper: crate::emulsion::paper_stock("portra_endura").expect("built-in stock"),
            development: DevelopmentParams::default(),
            exposure_ev: 0.0,
            spectral: false,
            camera: CameraProfile::default(),
            lut_size: 0,
            spectral_print: false,
            spectral_scan: false,
            print_exposure_ev: 0.0,
            interimage: false,
            filters: crate::filters::FilterPack::none(),
            heat_glass: None,
        }
    }
}

impl RenderParams {
    /// Freeze the development-dependent curves and solve the print balance.
    #[must_use]
    pub fn prepare(&self) -> PreparedRender {
        self.prepare_with(None)
    }

    /// Prepare with a table loaded from disk instead of baking one.
    ///
    /// The table was baked from some camera, film and dictionary; the caller is
    /// responsible for it matching this render's film. The format carries no
    /// model identity yet, which is a known gap.
    #[must_use]
    pub fn prepare_with_lut(&self, lut: ExposureLut) -> PreparedRender {
        let mut prepared = Self {
            spectral: false,
            lut_size: 0,
            ..self.clone()
        }
        .prepare_with(None);
        prepared.lut = Some(lut);
        prepared
    }

    /// As [`Self::prepare`], with an optional dictionary for the spectral prior.
    ///
    /// The atoms are what the hybrid needs; without them the spectral path uses
    /// the polynomial prior alone.
    #[must_use]
    pub fn prepare_with(&self, atoms: Option<&[kallo_spectral::Spectrum]>) -> PreparedRender {
        // A silver film has one record, so the three-channel scalar path cannot
        // express it: it would develop each input channel separately and print a
        // colour image from a film that has no colour. A monochrome stock is
        // therefore always exposed through its spectrum, whatever was asked for.
        let monochrome = self.film.process == crate::emulsion::FilmProcess::Monochrome;
        // ADR 0017: a dye fed by two emulsions is two integrals and two curves.
        // The scalar path has three numbers and one curve per channel, so it
        // cannot say a fourth layer exists; such a stock is always exposed
        // through its spectrum, exactly as a monochrome film is.
        let extra = self
            .film
            .extra_cyan
            .map(|emulsion| self.development.apply_to(emulsion.characteristic()));
        // A CL layer is a fourth integral too, and the scalar path has three
        // channels: it cannot even say that the layer exists.
        let cl_layer = self.interimage && self.film.cl_layer.is_some();
        let spectral = self.spectral || monochrome || extra.is_some() || cl_layer;
        let channels: [CharacteristicCurve; 3] =
            std::array::from_fn(|i| self.development.apply_to(self.film.channels[i]));

        let paper = self.paper.channel;

        // Solve the enlarger exposure so that a mid-grey negative prints at
        // the paper's target reflectance. This is what an operator does with
        // the aperture and the test strip, done in closed form: find the log
        // exposure at which the paper reaches the target density, and shift the
        // enlarger's exposure by however far mid grey is from it.
        let target_density = -self.paper.target_mid_reflectance.log10();
        let target_log_e = paper.log_exposure_at(target_density);

        let mid = mid_grey_log_e();
        let mut density_mid: [f64; 3] = std::array::from_fn(|i| channels[i].density(mid));
        // The cyan dye's second emulsion develops at mid grey too. Leaving it
        // out of this number would balance the enlarger on a negative the film
        // does not make, and every four-layer stock would print a stop dark in
        // cyan.
        if let Some(extra) = extra {
            density_mid[0] += extra.density(mid);
        }

        // Two ways to describe what reaches the paper. The scalar one treats each
        // density as that channel's light loss; the spectral one integrates the
        // dyes' absorption bands against the paper's layer sensitivities.
        //
        // A silver image has no dyes to integrate. Asking for the spectral print
        // on a monochrome film would leave a constant — the image would vanish
        // into a flat grey — so the scalar print is what those films get, and
        // `is_spectral_print` says so.
        //
        // A colour pack or a heat glass is a thing in the light path, and the
        // only model that can say what it does is the spectral one: filtering
        // the scalar print would be a colour wheel with no spectrum behind it.
        // Asking for either therefore turns the stage on, even when the caller
        // did not ask for the spectral print by name.
        let filtered = !self.filters.is_empty() || self.heat_glass.is_some();
        let print = ((self.spectral_print || filtered) && !monochrome).then(|| {
            PrintContext::measured_with(
                density_mid,
                self.film.dyes,
                self.film.mask,
                self.paper.layers,
            )
            .with_enlarger(self.filters, self.heat_glass)
        });
        let print_shift: [f64; 3] = match &print {
            // The spectral model is anchored on neutral grey, so the actual
            // mid-grey exposure is subtracted here rather than assumed to be 0.
            Some(context) => {
                let mid_exposure = context.expose(density_mid);
                std::array::from_fn(|i| target_log_e - mid_exposure[i])
            }
            // The non-spectral print has no mask to add, so the film's base
            // density goes into the exponent with the dye.
            None => {
                std::array::from_fn(|i| target_log_e + density_mid[i] + self.film.base_density[i])
            }
        };

        // The enlarger's timer, on top of the balance solved above: one number,
        // the same on every layer, which is what an exposure is. Everything
        // downstream — the CPU print, the scalar model handed to the GPU, the
        // replay — reads `print_shift`, so the timer rides there rather than
        // in a second field that three backends would have to learn about.
        let print_exposure = self.print_exposure_ev * 2.0_f64.log10();
        let print_shift: [f64; 3] =
            std::array::from_fn(|layer| print_shift[layer] + print_exposure);

        PreparedRender {
            channels,
            base_density: self.film.base_density,
            paper,
            print_shift,
            print,
            scan: self
                .spectral_scan
                .then(|| ScanContext::measured_with(self.paper.dyes)),
            extra,
            cl_layer,
            exposure_shift: self.exposure_ev * 2.0_f64.log10(),
            reversal: self.film.process == crate::emulsion::FilmProcess::Reversal,
            spectral: spectral
                .then(|| {
                    let context =
                        SpectralContext::for_stock(self.film).with_camera(self.camera.clone());
                    match atoms {
                        Some(atoms) => context.with_atoms(atoms),
                        None => context,
                    }
                })
                .filter(|_| self.lut_size < 2),
            lut: (spectral && self.lut_size >= 2 && extra.is_none()).then(|| {
                let context =
                    SpectralContext::for_stock(self.film).with_camera(self.camera.clone());
                let context = match atoms {
                    Some(atoms) => context.with_atoms(atoms),
                    None => context,
                };
                ExposureLut::bake(self.lut_size, &context)
            }),
        }
    }
}

/// The scalar model, flattened into the numbers another backend needs.
///
/// A GPU cannot call into this crate, and re-deriving the model from its
/// parameters on the other side would be a second implementation that could
/// drift. So the prepared render hands over the numbers it solved, in the shape
/// a shader wants: per layer, a base density, a span, a slope and an inflection
/// point; then the paper's two numbers and the enlarger's four.
///
/// Only the pure scalar path has one. The spectral exposure, the spectral print
/// and the spectral scan integrate over wavelength, and a backend that wants
/// them has to port the integration rather than the numbers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScalarModel {
    /// Per layer: `d_min`, `d_max`, `gamma`, `log_e0`.
    pub curve: [[f64; 4]; 3],
    /// The paper's `d_min`, `d_max`, `gamma` and `log_e0`.
    pub paper: [f64; 4],
    /// How sharply each curve's toe turns: the three layers, then the paper.
    ///
    /// It rides on the curve rather than on the model because it is a property
    /// of the material — see `crate::curve`.
    pub toe_transition: [f64; 4],
    /// How sharply each curve's shoulder turns: the three layers, then the
    /// paper. Equal to `toe_transition` for every material whose two corners
    /// were measured as one.
    pub shoulder_transition: [f64; 4],
    /// The film's minimum density in status terms: base, fog and mask.
    pub base_density: [f64; 3],
    /// The enlarger's exposure shift per layer, in decades.
    pub print_shift: [f64; 3],
    /// Exposure offset applied before the curve, in decades.
    pub exposure_shift: f64,
    /// Whether the film is its own picture. A reversal keeps its density and
    /// stops: there is no paper between the development and the eye.
    pub reversal: bool,
}

/// The exposure, as the curve stage receives it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Exposure {
    /// Log exposure of the three layers, in the order the film records them.
    pub layers: [f64; 3],
    /// Log exposure of the cyan dye's second emulsion, when the stock has one.
    pub extra: Option<f64>,
}

/// A [`RenderParams`] with the curves already developed and the print balanced.
#[derive(Debug, Clone)]
pub struct PreparedRender {
    /// Whether the film is viewed directly rather than printed.
    pub reversal: bool,
    channels: [CharacteristicCurve; 3],
    base_density: [f64; 3],
    paper: CharacteristicCurve,
    print_shift: [f64; 3],
    exposure_shift: f64,
    /// The live spectral model, when no table was baked.
    spectral: Option<SpectralContext>,
    /// The baked table, when one was requested.
    lut: Option<ExposureLut>,
    /// The spectral print model, when requested.
    print: Option<PrintContext>,
    /// The spectral scan model, when requested.
    scan: Option<ScanContext>,
    /// The cyan dye's second emulsion, when the stock has one — ADR 0017.
    ///
    /// Only its curve lives here. The sensitivity is a table the spectral
    /// context integrates, and the two meet in [`Self::negative_density_with`]:
    /// the context says how much light the layer saw, this says how much dye
    /// that made, and the cyan dye sums the two emulsions' densities.
    extra: Option<CharacteristicCurve>,
    /// Whether the fourth integral belongs to a cyan-sensitive inhibitor layer
    /// rather than to a dye-forming emulsion (ADR 0018).
    cl_layer: bool,
}

impl PreparedRender {
    /// The enlarger's exposure, per layer, in decades: the balance solved for
    /// a mid grey, plus the timer.
    ///
    /// This is what an operator dials: a colour head moves three exposure
    /// factors against each other until a neutral negative prints neutral, and
    /// a timer moves all three together. Both show up *here*, not in the
    /// per-pixel exponent — see `with_enlarger` in `print.rs` for why.
    #[must_use]
    pub fn print_shift(&self) -> [f64; 3] {
        self.print_shift
    }

    /// The same negative and paper, printed on another development's balance.
    ///
    /// A test strip is one exposure: several developments of one negative,
    /// every print made with the enlarger where the first print set it. The
    /// curves stay this development's — each print is a negative of its own
    /// time — while the paper, the enlarger's balance and the scan come from
    /// the reference. [`crate::contact::print()`] is the same idea on one
    /// sheet; this is the same idea for prints made one at a time.
    #[must_use]
    pub fn printed_like(mut self, reference: &Self) -> Self {
        self.paper = reference.paper;
        self.print_shift = reference.print_shift;
        self.print = reference.print.clone();
        self.scan = reference.scan.clone();
        self
    }

    /// The curve, the paper and the enlarger as plain numbers.
    ///
    /// Always available, because a spectral render runs the same three stages:
    /// it only reaches the paper through an integration instead of through a
    /// per-channel subtraction.
    fn numbers(&self) -> ScalarModel {
        ScalarModel {
            curve: std::array::from_fn(|layer| {
                let curve = &self.channels[layer];
                [curve.d_min, curve.d_max, curve.gamma, curve.log_e0]
            }),
            paper: [
                self.paper.d_min,
                self.paper.d_max,
                self.paper.gamma,
                self.paper.log_e0,
            ],
            toe_transition: [
                self.channels[0].toe_transition,
                self.channels[1].toe_transition,
                self.channels[2].toe_transition,
                self.paper.toe_transition,
            ],
            shoulder_transition: [
                self.channels[0].shoulder_transition,
                self.channels[1].shoulder_transition,
                self.channels[2].shoulder_transition,
                self.paper.shoulder_transition,
            ],
            base_density: self.base_density,
            print_shift: self.print_shift,
            exposure_shift: self.exposure_shift,
            reversal: self.reversal,
        }
    }

    /// The scalar model as plain numbers, when the render uses only the scalar
    /// path. `None` the moment any spectral stage is active.
    #[must_use]
    pub fn scalar_model(&self) -> Option<ScalarModel> {
        if self.spectral.is_some()
            || self.lut.is_some()
            || self.print.is_some()
            || self.scan.is_some()
        {
            return None;
        }
        Some(self.numbers())
    }

    /// The spectral model as plain numbers, when this render integrates over
    /// wavelength and nothing in it needs a solver or a sampled cube.
    ///
    /// `None` in three cases, and the distinction matters to a caller that has
    /// to choose a backend rather than to a caller that has to render:
    ///
    /// - nothing is spectral, so [`Self::scalar_model`] describes it;
    /// - a baked table is in use, which is a sampled approximation rather than
    ///   an integration;
    /// - a dictionary prior is in use, which solves a non-negative least
    ///   squares per pixel instead of a fixed matrix.
    ///
    /// The last two are their own models. A backend that implemented them would
    /// be porting a solver, not replaying numbers, and it should say so rather
    /// than substitute the closed form.
    #[must_use]
    pub fn spectral_model(&self) -> Option<SpectralModel> {
        // ADR 0017: the fourth layer is a fourth integral and a second curve on
        // the cyan dye. No field of the model carries it, and a backend that
        // replayed the three layers would render a different film without
        // saying so — so it declines, and the caller renders on the CPU.
        if self.extra.is_some() || self.cl_layer {
            return None;
        }
        if self.lut.is_some() {
            return None;
        }
        // All three stages integrate on the model grid, so the first one that
        // is present carries the step and the others cannot disagree.
        let step_nm = self
            .spectral
            .as_ref()
            .map(|context| context.grid().step_nm())
            .or_else(|| self.print.as_ref().map(|context| context.grid().step_nm()))
            .or_else(|| self.scan.as_ref().map(|context| context.grid().step_nm()))
            .unwrap_or(0.0);
        let model = SpectralModel {
            scalar: self.numbers(),
            step_nm,
            exposure: match &self.spectral {
                Some(context) => Some(context.model()?),
                None => None,
            },
            enlarger: match &self.print {
                Some(context) => Some(context.model()?),
                None => None,
            },
            scan: match &self.scan {
                Some(context) => Some(context.model()?),
                None => None,
            },
        };
        model.is_spectral().then_some(model)
    }

    /// The three negative curves after development.
    #[must_use]
    pub fn channels(&self) -> &[CharacteristicCurve; 3] {
        &self.channels
    }

    /// Whether the spectral path is active, baked or live.
    #[must_use]
    pub fn is_spectral(&self) -> bool {
        self.spectral.is_some() || self.lut.is_some()
    }

    /// Whether the print is going through the spectral model.
    #[must_use]
    pub fn is_spectral_print(&self) -> bool {
        self.print.is_some()
    }

    /// Whether the scan is going through the spectral model.
    #[must_use]
    pub fn is_spectral_scan(&self) -> bool {
        self.scan.is_some()
    }

    /// The baked table, if one was requested.
    #[must_use]
    pub fn lut(&self) -> Option<&ExposureLut> {
        self.lut.as_ref()
    }

    /// Everything the curve stage needs from a pixel.
    ///
    /// The fourth layer rides beside the three rather than inside them: its
    /// density lands on the cyan dye, which already has a layer, so folding it
    /// into the blue channel's log exposure would combine the emulsions before
    /// their curves and lose exactly what ADR 0017 added.
    ///
    /// `None` for the fourth layer is the ordinary case — every stock before
    /// PRO 400H — and makes the rest of the chain the model it always was.
    pub fn expose(&self, linear: [f64; 3]) -> Exposure {
        let scalar = || std::array::from_fn(|channel| linear[channel].max(1e-10).log10());
        if let Some(lut) = &self.lut {
            // Baked: three trilinear lookups. A table cannot carry a fourth
            // axis, which is why `prepare_with` refuses one for such a stock.
            return Exposure {
                layers: lut.sample(linear),
                extra: None,
            };
        }
        if let Some(context) = &self.spectral {
            // Live: reconstruct once and integrate four times. The fallback
            // keeps the function total; it cannot trigger with a context this
            // module built.
            return match context.expose_with_extra(linear) {
                Some((layers, extra)) => Exposure { layers, extra },
                None => Exposure {
                    layers: scalar(),
                    extra: None,
                },
            };
        }
        Exposure {
            layers: scalar(),
            extra: None,
        }
    }

    /// The three log exposures: scalar per channel, or the film's layers
    /// integrating a reconstructed spectrum.
    #[must_use]
    pub fn log_exposure(&self, linear: [f64; 3]) -> [f64; 3] {
        self.expose(linear).layers
    }

    /// The negative's density, from log exposure.
    ///
    /// This is the three-layer model: one emulsion per dye. A stock with a
    /// fourth layer wants [`Self::negative_density_with`], which is this plus
    /// the second cyan emulsion.
    #[must_use]
    pub fn negative_density(&self, log_e: [f64; 3]) -> [f64; 3] {
        self.negative_density_with(log_e, None)
    }

    /// The negative's density, with the cyan dye's second emulsion when there
    /// is one.
    ///
    /// The sum is over densities: both emulsions make the same dye, and the
    /// densitometer sees one number, so two emulsions at half a stop each are
    /// not one at a stop. Ignoring `extra` is bit-for-bit the old model.
    #[must_use]
    pub fn negative_density_with(&self, log_e: [f64; 3], extra: Option<f64>) -> [f64; 3] {
        let mut density: [f64; 3] = std::array::from_fn(|channel| {
            self.channels[channel].density(log_e[channel] + self.exposure_shift)
        });
        if let (Some(curve), Some(log_e)) = (self.extra, extra) {
            density[0] += curve.density(log_e + self.exposure_shift);
        }
        density
    }

    /// The print and the scan, from the negative's density.
    #[must_use]
    pub fn positive(&self, density_cmy: [f64; 3]) -> [f64; 3] {
        // A reversal film is its own picture: there is no print, no paper and no
        // enlarger between the development and the eye. What leaves is what the
        // film transmits, and the density *is* the image.
        if self.reversal {
            // The film's clearest point is the projector's white: a slide's
            // density is absolute — 0.08 for clean film, 3.3 for unexposed —
            // and displaying it as a fraction of *clear film* rather than of
            // nothing is what a lamp behind it does. Without that the whole
            // image sits between two and eighty per cent and reads as a murk;
            // a projector's white level is not a correction, it is the other
            // half of the observation.
            return std::array::from_fn(|channel| {
                let white = self.channels[channel].d_max;
                10.0_f64
                    .powf(-(density_cmy[channel] + self.base_density[channel] - white))
                    .clamp(0.0, 1.0)
            });
        }

        // The spectral print does one integration for all three layers; calling
        // it inside the channel loop made it six times more expensive per pixel.
        let print_exposure = self
            .print
            .as_ref()
            .map(|context| context.expose(density_cmy));

        let mut density_print = [0.0; 3];
        for channel in 0..3 {
            // The enlarger sees the light the negative transmitted: per channel
            // in the scalar model, through the dye spectra in the spectral one.
            // The non-spectral print has no spectrum for the base, so the
            // film's minimum density rides in the exponent with the dye. The
            // spectral one puts the measured mask into the integral instead.
            let log_transmittance = match &print_exposure {
                Some(values) => values[channel],
                None => -(density_cmy[channel] + self.base_density[channel]),
            };
            density_print[channel] = self
                .paper
                .density(log_transmittance + self.print_shift[channel]);
        }

        match &self.scan {
            // Spectral scan: reflectance through the illuminant and the observer.
            Some(context) => context.scan(density_print),
            // Scalar scan: each density is that channel's light loss.
            None => density_print.map(|density| 10.0_f64.powf(-density).clamp(0.0, 1.0)),
        }
    }

    /// Render one linear-light pixel.
    #[must_use]
    pub fn render_pixel(&self, linear: [f64; 3]) -> [f64; 3] {
        let exposure = self.expose(linear);
        self.positive(self.negative_density_with(exposure.layers, exposure.extra))
    }

    /// Whether the render carries a fourth layer of either kind.
    #[must_use]
    pub fn has_extra_layer(&self) -> bool {
        self.extra.is_some() || self.cl_layer
    }

    /// Whether the fourth layer releases inhibitor rather than forming dye.
    #[must_use]
    pub fn has_inhibitor_layer(&self) -> bool {
        self.cl_layer
    }
}

/// What happens between the exposure and the development.
///
/// Both are optional and independent; the model without them is the model.
#[derive(Debug, Clone, Copy, Default)]
pub struct Finishing<'a> {
    /// The film's own blur: how soft the emulsion makes everything.
    pub emulsion: Option<&'a crate::mtf::EmulsionBlur>,
    /// Light that scatters in the emulsion and reflects off the base.
    pub halation: Option<&'a crate::halation::Halation>,
    /// The emulsion's grain.
    pub grain: Option<&'a crate::grain::GrainField>,
    /// DIR couplers, acting on the developed densities.
    pub couplers: Option<&'a crate::couplers::Couplers>,
    /// The cyan-sensitive layer's inhibitor, acting on the cyan dye — ADR 0018.
    pub interimage: Option<&'a crate::interimage::InterImage>,
}

/// Run `f` over every pixel, in parallel when the `parallel` feature is on.
///
/// The render is embarrassingly parallel: a pixel's exposure, its density and
/// its print depend on that pixel alone. So this is the whole of the speed-up —
/// no tiling, no work queue, no second code path that could disagree with the
/// serial one. The spatial stages (halation, the couplers) run before and after
/// and stay serial, because they are the ones that genuinely look sideways.
#[inline]
fn each_pixel<T: Send>(data: &mut [T], width: usize, f: impl Fn(usize, usize, &mut T) + Sync) {
    #[cfg(feature = "parallel")]
    {
        use rayon::prelude::*;
        data.par_iter_mut()
            .enumerate()
            .for_each(|(index, slot)| f(index % width, index / width, slot));
    }
    #[cfg(not(feature = "parallel"))]
    {
        for (index, slot) in data.iter_mut().enumerate() {
            f(index % width, index / width, slot);
        }
    }
}

/// [`each_pixel`], for two planes that describe the same pixel.
///
/// The fourth layer needs a plane of its own — it is a layer, not a fourth
/// number in a three-channel pixel — and its exposure comes from the same
/// reconstructed spectrum as the other three. Filling the two in separate
/// passes would reconstruct every spectrum twice.
#[inline]
fn each_pixel_pair<A: Send, B: Send>(
    first: &mut [A],
    second: &mut [B],
    width: usize,
    f: impl Fn(usize, usize, &mut A, &mut B) + Sync,
) {
    #[cfg(feature = "parallel")]
    {
        use rayon::prelude::*;
        first
            .par_iter_mut()
            .zip(second.par_iter_mut())
            .enumerate()
            .for_each(|(index, (left, right))| f(index % width, index / width, left, right));
    }
    #[cfg(not(feature = "parallel"))]
    {
        for (index, (left, right)) in first.iter_mut().zip(second.iter_mut()).enumerate() {
            f(index % width, index / width, left, right);
        }
    }
}

/// Render a whole image with the finishing effects.
///
/// Halation runs first and needs the whole frame, because it moves light
/// between pixels; grain runs second and is per pixel. Both are applied to the
/// exposure — one to where the light went, one to how many grains it developed —
/// which is why they sit before the curve rather than after the print.
/// A developed negative: densities, and the grid they came at.
///
/// Densities do not depend on a paper, so one of these can be printed as many
/// times as wanted — on as many papers, at as many print exposures — without
/// touching the film model again. That is what a darkroom does, and it is what
/// the bench needs in order to stay responsive while a print exposure is being
/// dialled.
#[derive(Debug, Clone, PartialEq)]
pub struct Negative {
    /// Pixels across.
    pub width: usize,
    /// Pixels down.
    pub height: usize,
    /// Per pixel, the cyan, magenta and yellow density the film developed.
    pub densities: Vec<[f64; 3]>,
}

impl PreparedRender {
    /// Expose and develop: everything the film and the development decide, and
    /// nothing the paper does.
    #[must_use]
    pub fn develop(
        &self,
        pixels: &[[f64; 3]],
        width: usize,
        height: usize,
        finishing: &Finishing,
    ) -> Negative {
        let width = width.max(1);
        let height = height.max(1);

        // Without a spatial effect there is nothing to keep a frame for, and
        // grain is the only thing left that wants pixel coordinates.
        if finishing.emulsion.is_none()
            && finishing.halation.is_none()
            && finishing.couplers.is_none()
            && finishing.interimage.is_none()
        {
            let densities: Vec<[f64; 3]> = pixels
                .iter()
                .enumerate()
                .map(|(index, pixel)| {
                    let exposure = self.expose(*pixel);
                    let mean = self.negative_density_with(exposure.layers, exposure.extra);
                    match finishing.grain {
                        Some(grain) => self.negative_density_with(
                            std::array::from_fn(|channel| {
                                exposure.layers[channel]
                                    + grain.jitter(
                                        index % width,
                                        index / width,
                                        mean[channel],
                                        channel,
                                    )
                            }),
                            exposure.extra,
                        ),
                        None => mean,
                    }
                })
                .collect();
            return Negative {
                width,
                height,
                densities,
            };
        }

        // Exposure first: halation moves light between pixels, before anything
        // is developed.
        let mut log_e: Vec<[f64; 3]> = pixels.to_vec();
        // The fourth layer is a fourth plane, allocated only when the stock has
        // one: a stock without it renders through exactly the vectors it used to.
        let mut extra: Option<Vec<f64>> = self.has_extra_layer().then(|| vec![0.0; log_e.len()]);
        match extra.as_mut() {
            Some(plane) => each_pixel_pair(&mut log_e, plane, width, |_, _, pixel, slot| {
                let exposure = self.expose(*pixel);
                *pixel = exposure.layers;
                // No integral means no exposure: the emulsion stays at its
                // minimum density rather than at a plausible-looking zero.
                *slot = exposure.extra.unwrap_or(f64::NEG_INFINITY);
            }),
            None => each_pixel(&mut log_e, width, |_, _, pixel| {
                *pixel = self.log_exposure(*pixel);
            }),
        }
        // The emulsion's own blur comes first: it is the lens's image being
        // softened by the film, and the halo is light that entered the film and
        // came back, so it is distributed by the same blur afterwards.
        if let Some(emulsion) = finishing.emulsion {
            emulsion.apply(&mut log_e, width, height);
        }
        if let Some(halation) = finishing.halation {
            halation.apply(&mut log_e, width, height);
        }

        // Then the emulsion: grain on the exposure, the curve on the result.
        let mut density: Vec<[f64; 3]> = log_e.clone();
        each_pixel(&mut density, width, |x, y, slot| {
            let log_e = log_e[y * width + x];
            let extra = extra.as_ref().map(|plane| plane[y * width + x]);
            let mean = self.negative_density_with(log_e, extra);
            *slot = match finishing.grain {
                Some(grain) => self.negative_density_with(
                    std::array::from_fn(|channel| {
                        log_e[channel] + grain.jitter(x, y, mean[channel], channel)
                    }),
                    extra,
                ),
                None => mean,
            };
        });

        // The cyan-sensitive layer's inhibitor, before the couplers: its release
        // is the light the layer absorbed, not the density it developed, so it
        // is the earlier of the two development effects.
        if let (Some(stage), Some(plane)) = (finishing.interimage, extra.as_ref()) {
            let light: Vec<f64> = plane.iter().map(|value| 10f64.powf(*value)).collect();
            stage.apply(&mut density, &light, width, height);
        }

        // Then the chemistry: the inhibitors act on what has already developed.
        if let Some(couplers) = finishing.couplers {
            couplers.apply(&mut density, width, height);
        }

        Negative {
            width,
            height,
            densities: density,
        }
    }

    /// Print a developed negative through this render's paper and enlarger.
    #[must_use]
    pub fn print(&self, negative: &Negative) -> Vec<[f64; 3]> {
        negative
            .densities
            .iter()
            .map(|density| self.positive(*density))
            .collect()
    }
}

/// Develop a whole image and print it, in place.
///
/// This is `develop` followed by `print`, and exists because most callers want
/// a picture rather than a negative. A caller that wants the negative — to
/// print it on a second paper, or at another print exposure — should take it
/// apart the way this does.
pub fn render_pixels_finished(
    pixels: &mut [[f64; 3]],
    prepared: &PreparedRender,
    width: usize,
    height: usize,
    finishing: &Finishing,
) {
    let negative = prepared.develop(pixels, width, height, finishing);
    for (pixel, density) in pixels.iter_mut().zip(&negative.densities) {
        *pixel = prepared.positive(*density);
    }
}

/// Render a whole image in place.
pub fn render_pixels(pixels: &mut [[f64; 3]], prepared: &PreparedRender) {
    // Width only matters to the grain, which this path has none of.
    each_pixel(pixels, 1, |_, _, pixel| {
        *pixel = prepared.render_pixel(*pixel);
    });
}

/// Render a whole image with grain.
///
/// The grain is an exposure fluctuation, so it is applied to the log exposure
/// and then pushed through the same curve — which is what keeps it out of a
/// blank frame and out of the shoulder without either case being special-cased.
pub fn render_pixels_with_grain(
    pixels: &mut [[f64; 3]],
    prepared: &PreparedRender,
    grain: &crate::grain::GrainField,
) {
    render_pixels_finished(
        pixels,
        prepared,
        grain.width,
        grain.height,
        &Finishing {
            emulsion: None,
            halation: None,
            grain: Some(grain),
            couplers: None,
            interimage: None,
        },
    );
}

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

    /// The fourth layer's sensitivity: a straight line at 5 nm, sampled every
    /// 10 nm. Interpolating it back onto the model grid returns the same
    /// function, so it sees *exactly* what the blue layer sees and only the
    /// anchor can differ.
    const STRAIGHT: [f32; 36] = {
        let mut table = [0.0_f32; 36];
        let mut index = 0;
        while index < 36 {
            table[index] = 1.0 + 0.02 * (index as f32);
            index += 1;
        }
        table
    };

    /// A four-layer stock: three identical straight-line layers and a cyan dye
    /// fed by a second emulsion. `Box::leak` because [`RenderParams`] borrows
    /// the stock and the test is its only owner.
    fn four_layer(curve: [f64; 4]) -> &'static FilmStock {
        let mut straight = [0.0; crate::spectral::GRID_LEN];
        for (index, value) in straight.iter_mut().enumerate() {
            *value = 1.0 + 0.01 * index as f64;
        }
        let layers: &'static [[f64; crate::spectral::GRID_LEN]; 3] =
            Box::leak(Box::new([straight, straight, straight]));
        let mut stock = *crate::emulsion::film_stock("vision3_500t").expect("built-in stock");
        stock.id = "test_four_layer";
        stock.layers = layers;
        stock.extra_cyan = Some(crate::dye::Emulsion {
            curve,
            transition: crate::curve::TRANSITION,
            sensitivity: &STRAIGHT,
        });
        Box::leak(Box::new(stock))
    }

    /// A mid grey, printed once at the solved exposure and once a stop over.
    ///
    /// The timer is a separate number from the balance: zero is the test strip
    /// that came out right, and one stop is a darker print on every layer.
    #[test]
    fn print_exposure_darkens_the_print() {
        let base = RenderParams::default();
        let over = RenderParams {
            print_exposure_ev: 1.0,
            ..RenderParams::default()
        };

        let grey = [0.18, 0.18, 0.18];
        let solved = base.prepare().render_pixel(grey);
        let darker = over.prepare().render_pixel(grey);

        for channel in 0..3 {
            assert!(
                darker[channel] < solved[channel],
                "channel {channel}: {darker:?} should be darker than {solved:?}"
            );
        }
        // A stop is a factor of two in exposure, not a factor of two in the
        // print: the paper's curve stands between them, and it must not be
        // bypassed.
        assert!(darker[0] < solved[0] * 0.95);
    }

    /// A colour pack is a spectrum in the light path, so it turns on the stage
    /// that can carry one — even when the caller did not ask for the spectral
    /// print by name.
    #[test]
    fn a_colour_pack_engages_the_spectral_print() {
        use crate::filters::{FilterPack, HeatGlass};

        let plain = RenderParams::default().prepare();
        assert!(!plain.is_spectral_print(), "no glass, no spectral print");

        let filtered = RenderParams {
            filters: FilterPack::new(0.0, 30.0, 0.0),
            ..RenderParams::default()
        }
        .prepare();
        assert!(filtered.is_spectral_print());

        let glass = RenderParams {
            heat_glass: Some(HeatGlass::Kg3),
            ..RenderParams::default()
        }
        .prepare();
        assert!(glass.is_spectral_print());
    }

    /// A test strip is one exposure: every print keeps the first print's
    /// enlarger balance while carrying its own development.
    #[test]
    fn a_test_strip_keeps_the_first_prints_balance() {
        let at = |minutes: f64| {
            RenderParams {
                development: DevelopmentParams {
                    time_min: minutes,
                    ..DevelopmentParams::default()
                },
                ..RenderParams::default()
            }
            .prepare()
        };
        let first = at(3.0);
        let second = at(12.0);
        let strip = second.clone().printed_like(&first);

        assert_eq!(strip.print_shift(), first.print_shift());
        assert_ne!(strip.print_shift(), second.print_shift());

        // The negative is still the twelve-minute one: only the print is held.
        let log_e = [-1.0, -1.0, -1.0];
        assert_eq!(
            strip.negative_density_with(log_e, None),
            second.negative_density_with(log_e, None)
        );
        assert_ne!(
            strip.negative_density_with(log_e, None),
            first.negative_density_with(log_e, None)
        );

        // Printed on one exposure, the longer development is the denser
        // negative — so it passes less light and prints lighter. That is the
        // comparison a test strip exists to make.
        let grey = [0.18, 0.18, 0.18];
        assert!(
            strip.render_pixel(grey)[0] > first.render_pixel(grey)[0],
            "the strip's twelve-minute print should be lighter than its three"
        );
    }

    /// One negative, two papers.
    ///
    /// The negative is developed once and holds no paper, so the bench can try
    /// a second paper without re-developing the film — which is the whole point
    /// of the split.
    #[test]
    fn a_negative_prints_on_any_paper() {
        let first = RenderParams::default();
        let second = RenderParams {
            paper: crate::emulsion::paper_stock("endura_premier").expect("built-in paper"),
            ..RenderParams::default()
        };

        let negative = first.prepare().develop(
            &[[0.18, 0.18, 0.18], [0.4, 0.3, 0.2]],
            2,
            1,
            &Finishing::default(),
        );
        assert_eq!(negative.densities.len(), 2);

        let on_first = first.prepare().print(&negative);
        let on_second = second.prepare().print(&negative);
        assert_ne!(on_first, on_second);

        // And the two-stage path is what the one-shot path does.
        let mut pixels = vec![[0.18, 0.18, 0.18], [0.4, 0.3, 0.2]];
        render_pixels_finished(&mut pixels, &first.prepare(), 2, 1, &Finishing::default());
        assert_eq!(pixels, on_first);
    }

    /// The fourth layer's plane has to survive the effects path too: it is
    /// filled beside the three-channel exposure, developed by the same curve
    /// pass, and read back as the cyan dye's second density. A stock without a
    /// fourth layer never allocates it, which is why this is the only test that
    /// takes the pair path with a non-empty plane.
    #[test]
    fn a_four_layer_frame_renders_through_the_effects_path() {
        let prepared = RenderParams {
            film: four_layer([0.0, 1.0, 1.0, -0.5]),
            ..RenderParams::default()
        }
        .prepare();
        assert!(prepared.has_extra_layer());

        let mut pixels = vec![
            [0.6, 0.3, 0.1],
            [0.1, 0.2, 0.4],
            [0.05, 0.05, 0.05],
            [0.9, 0.9, 0.9],
        ];
        let halation = crate::halation::Halation::typical(6.0);
        render_pixels_finished(
            &mut pixels,
            &prepared,
            2,
            2,
            &Finishing {
                emulsion: None,
                halation: Some(&halation),
                grain: None,
                couplers: None,
                interimage: None,
            },
        );
        assert!(
            pixels
                .iter()
                .all(|pixel| pixel.iter().all(|value| value.is_finite() && *value >= 0.0))
        );

        // The same frame through the no-effects path: the two differ only by
        // the halo, which is small but not nothing on a bright edge.
        let mut plain = vec![
            [0.6, 0.3, 0.1],
            [0.1, 0.2, 0.4],
            [0.05, 0.05, 0.05],
            [0.9, 0.9, 0.9],
        ];
        render_pixels_finished(
            &mut plain,
            &prepared,
            2,
            2,
            &Finishing {
                emulsion: None,
                halation: None,
                grain: None,
                couplers: None,
                interimage: None,
            },
        );
        for (halated, plain) in pixels.iter().zip(&plain) {
            for (left, right) in halated.iter().zip(plain) {
                assert!((left - right).abs() < 0.5, "{halated:?} vs {plain:?}");
            }
        }
    }

    /// The enlarger is balanced on the density the negative actually has, so a
    /// four-layer stock must still print mid grey as mid grey. If the balance
    /// ignored the second emulsion, the printed grey would come out too dark in
    /// cyan by exactly that density.
    #[test]
    fn a_four_layer_stock_still_prints_mid_grey_as_mid_grey() {
        for curve in [[0.0, 1.0, 1.0, -1.0], [0.0, 2.0, 0.7, -0.2]] {
            let prepared = RenderParams {
                film: four_layer(curve),
                ..RenderParams::default()
            }
            .prepare();
            let exposure = prepared.expose([0.18, 0.18, 0.18]);
            let printed =
                prepared.positive(prepared.negative_density_with(exposure.layers, exposure.extra));
            for value in printed {
                assert!(
                    (value - 0.18).abs() < 0.02,
                    "curve {curve:?} printed {printed:?}"
                );
            }
        }
    }

    /// A stock with a cyan-sensitive inhibitor layer and no dye-forming fourth
    /// emulsion: the arrangement ADR 0018 exists for.
    fn inhibitor_stock() -> &'static FilmStock {
        static SENSITIVITY: [f64; crate::spectral::GRID_LEN] = [1.0; crate::spectral::GRID_LEN];
        let mut stock = *crate::emulsion::film_stock("vision3_500t").expect("built-in stock");
        stock.id = "test_inhibitor_layer";
        stock.cl_layer = Some(crate::dye::InhibitorLayer {
            sensitivity: &SENSITIVITY,
        });
        Box::leak(Box::new(stock))
    }

    /// ADR 0018: the layer shows where the frame has structure, and only in the
    /// cyan channel. A stock with such a layer renders identically until the
    /// stage is asked for, which is what keeps PRO 400H a three-layer stock on
    /// the GPU by default.
    #[test]
    fn the_inhibitor_layer_shows_only_where_the_frame_has_structure() {
        let off = RenderParams {
            film: inhibitor_stock(),
            ..RenderParams::default()
        }
        .prepare();
        let on = RenderParams {
            film: inhibitor_stock(),
            interimage: true,
            ..RenderParams::default()
        }
        .prepare();
        assert!(!off.has_inhibitor_layer());
        assert!(on.has_inhibitor_layer());
        // The fourth integral is a quantity the replayable model has no lane
        // for, so a backend declines whenever the layer is in the render.
        assert!(on.spectral_model().is_none());
        assert!(off.scalar_model().is_some());

        let stage = crate::interimage::InterImage::typical(6.0);
        let finishing = |interimage| Finishing {
            emulsion: None,
            halation: None,
            grain: None,
            couplers: None,
            interimage,
        };
        // Sixty-four pixels: thirty-two warm, thirty-two cool. Both renders use
        // the same prepared render — same exposure, same curve, same print — so
        // the only thing that differs is whether the inhibitor acted.
        let mut pixels = Vec::new();
        for index in 0..64 {
            pixels.push(if index < 32 {
                [0.9, 0.2, 0.1]
            } else {
                [0.1, 0.2, 0.9]
            });
        }
        let mut with = pixels.clone();
        let mut without = pixels;
        render_pixels_finished(&mut with, &on, 64, 1, &finishing(Some(&stage)));
        render_pixels_finished(&mut without, &on, 64, 1, &finishing(None));

        // Which half the layer sees more of is the exposure's answer, not the
        // eye's: a flat sensitivity integrates the reconstructed spectrum, and
        // a warm RGB triple is not the brighter one in it. So the expectation
        // comes from the render's own fourth integral.
        let warm = on
            .expose([0.9, 0.2, 0.1])
            .extra
            .expect("the layer is in the render");
        let cool = on
            .expose([0.1, 0.2, 0.9])
            .extra
            .expect("the layer is in the render");
        // The two pixels either side of the boundary: the brighter one is the
        // side whose inhibitor diffuses away, the shadow is the side that
        // receives it.
        let (bright, shadow) = if warm > cool { (31, 32) } else { (32, 31) };

        // The sign of the *print* is not the sign of the *density*: the
        // inhibitor takes cyan density off the negative, and a negative with
        // less cyan passes more red light, which the paper then develops into
        // more cyan. So the shadow keeps less red than it would have, and the
        // bright side keeps more.
        assert!(
            with[shadow][0] < without[shadow][0],
            "the shadow did not lose cyan: {:?} vs {:?}",
            with[shadow],
            without[shadow]
        );
        assert!(
            with[bright][0] > without[bright][0],
            "the bright side did not gain: {:?} vs {:?}",
            with[bright],
            without[bright]
        );
        // The other two dyes are not this layer's business.
        for (left, right) in with.iter().zip(&without) {
            assert!((left[1] - right[1]).abs() < 1e-12);
            assert!((left[2] - right[2]).abs() < 1e-12);
        }
    }

    /// ADR 0017's compatibility promise: the eighteen stocks that were here
    /// before the fourth layer exist are still the three-layer model, bit for
    /// bit, and a backend can still replay every one of them.
    #[test]
    fn a_stock_without_a_fourth_layer_is_still_the_three_layer_model() {
        for stock in crate::emulsion::FILM_STOCKS {
            let prepared = RenderParams {
                film: stock,
                ..RenderParams::default()
            }
            .prepare();
            assert!(!prepared.has_extra_layer(), "{}", stock.id);

            let pixel = [0.4, 0.3, 0.2];
            let exposure = prepared.expose(pixel);
            assert_eq!(exposure.extra, None, "{}", stock.id);
            let expected: [f64; 3] = std::array::from_fn(|channel| {
                prepared.channels()[channel].density(exposure.layers[channel])
            });
            assert_eq!(
                prepared.negative_density(exposure.layers),
                expected,
                "{}",
                stock.id
            );
            // Still exactly one of the two replayable models: nothing about a
            // three-layer stock newly declines the GPU.
            assert!(
                prepared.scalar_model().is_some() || prepared.spectral_model().is_some(),
                "{}",
                stock.id
            );
        }
    }

    /// The fourth layer is a density on the cyan dye, not a fourth exposure.
    #[test]
    fn a_second_emulsion_adds_density_on_the_cyan_dye() {
        let curve = [0.05, 1.2, 0.7, -1.0];
        let prepared = RenderParams {
            film: four_layer(curve),
            ..RenderParams::default()
        }
        .prepare();

        assert!(prepared.has_extra_layer());
        // A second emulsion is a fourth integral and a second curve: the
        // scalar path cannot say it, and the spectral model has no lane for
        // it, so a backend has to decline rather than replay three layers.
        assert!(prepared.is_spectral());
        assert!(prepared.scalar_model().is_none());
        assert!(prepared.spectral_model().is_none());

        let exposure = prepared.expose([0.4, 0.3, 0.2]);
        let extra = exposure.extra.expect("the stock has a second emulsion");
        let added = crate::curve::density_from(
            curve[0],
            curve[1],
            curve[2],
            curve[3],
            crate::curve::TRANSITION,
            crate::curve::TRANSITION,
            extra,
        );

        let without = prepared.negative_density_with(exposure.layers, None);
        let with = prepared.negative_density_with(exposure.layers, Some(extra));
        assert!(
            (with[0] - without[0] - added).abs() < 1e-12,
            "cyan: {} + {added} vs {}",
            without[0],
            with[0]
        );
        // The other two dyes are untouched: the layer shares a dye, not a
        // channel.
        assert_eq!([with[1], with[2]], [without[1], without[2]]);
    }

    /// The fourth layer is normalised on the **blue** layer's grey response,
    /// not on its own. The data sheet plots all four emulsions on one log H
    /// axis, and the distance between the blue-sensitive curve and the
    /// cyan-sensitive one is a speed difference that self-anchoring would
    /// divide out.
    ///
    /// With a sensitivity that is the blue layer's own function, the two
    /// integrals must agree to the last digit at every colour — including the
    /// ones where mid grey's exposure, −0.744, is nowhere near.
    #[test]
    fn the_fourth_layer_is_anchored_on_the_blue_layer() {
        let prepared = RenderParams {
            film: four_layer([0.0, 1.0, 1.0, 0.0]),
            ..RenderParams::default()
        }
        .prepare();
        for pixel in [[0.18, 0.18, 0.18], [0.9, 0.1, 0.05], [0.05, 0.2, 0.8]] {
            let exposure = prepared.expose(pixel);
            let extra = exposure.extra.expect("the stock has a second emulsion");
            let blue = exposure.layers[2];
            assert!(
                (extra - blue).abs() < 1e-6,
                "{pixel:?}: fourth layer {extra} vs blue layer {blue}"
            );
        }
    }

    fn chain(development: DevelopmentParams) -> PreparedRender {
        RenderParams {
            development,
            ..RenderParams::default()
        }
        .prepare()
    }

    #[test]
    fn print_balance_lands_mid_grey_on_target() {
        let prepared = chain(DevelopmentParams::default());
        let out = prepared.render_pixel([0.18, 0.18, 0.18]);
        for channel in out {
            assert!(
                (channel - 0.18).abs() < 0.005,
                "mid grey printed at {channel}"
            );
        }
    }

    #[test]
    fn a_reversal_film_is_not_printed() {
        // The only stage that separates a reversal from a negative is the print:
        // the film's own density is the picture, so what leaves is its
        // transmittance and not a paper's response to it. The white point is the
        // film's clearest density — a projector's lamp, not the absence of film.
        let stock = crate::emulsion::film_stock("provia_100f").expect("the reversal stock");
        let prepared = RenderParams {
            film: stock,
            ..RenderParams::default()
        }
        .prepare();
        assert!(prepared.reversal);

        let density = [1.0, 1.5, 2.0];
        let out = prepared.positive(density);
        for channel in 0..3 {
            let white = prepared.channels()[channel].d_max;
            let expected =
                10.0_f64.powf(-(density[channel] + prepared.base_density[channel] - white));
            assert!(
                (out[channel] - expected).abs() < 1e-12,
                "channel {channel}: {} against {expected}",
                out[channel]
            );
        }

        // And the ends behave: unexposed film is black, clear film is white.
        let black = prepared.render_pixel([0.0; 3]);
        let clear = prepared.render_pixel([4.0; 3]);
        for channel in 0..3 {
            assert!(black[channel] < 0.01, "unexposed at {}", black[channel]);
            assert!(clear[channel] > 0.9, "fully exposed at {}", clear[channel]);
        }
    }

    /// Local slope of the whole chain, in density per decade of scene exposure,
    /// measured one stop either side of mid grey.
    fn local_contrast(prepared: &PreparedRender) -> f64 {
        let mid = 0.18;
        let low = prepared.render_pixel([mid / 2.0; 3])[1].max(1e-6);
        let high = prepared.render_pixel([mid * 2.0; 3])[1].max(1e-6);
        (high / low).log10() / 4.0_f64.log10()
    }

    /// Luma of a linear RGB triple, the observer every check below uses.
    fn luma(rgb: [f64; 3]) -> f64 {
        0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]
    }

    /// The checks `tools/eval.py` used to make by rendering a grey ramp through
    /// every stock and reading the PNG back. They were the only ones that
    /// touched all thirty stocks instead of the default one, and they lived
    /// outside `cargo test`, where nothing ran them but a person remembering to.
    /// A stock is balanced or it is not; that is a test, not a screenshot.
    #[test]
    fn every_stock_prints_mid_grey_as_mid_grey() {
        for film in crate::emulsion::FILM_STOCKS {
            let prepared = RenderParams {
                film,
                ..RenderParams::default()
            }
            .prepare();
            // A reversal is its own picture: there is no print to balance.
            if prepared.reversal {
                continue;
            }
            let out = prepared.render_pixel([0.18; 3]);
            assert!(
                (luma(out) - 0.18).abs() < 0.01,
                "{} printed mid grey at {:.4}",
                film.id,
                luma(out)
            );
            let high = out.iter().copied().fold(f64::MIN, f64::max);
            let low = out.iter().copied().fold(f64::MAX, f64::min);
            assert!(
                high - low < 0.01,
                "{} printed mid grey {:.4} off neutral",
                film.id,
                high - low
            );
        }

        for paper in crate::emulsion::PAPER_STOCKS {
            let prepared = RenderParams {
                paper,
                ..RenderParams::default()
            }
            .prepare();
            let out = prepared.render_pixel([0.18; 3]);
            assert!(
                (luma(out) - 0.18).abs() < 0.02,
                "{} printed mid grey at {:.4}",
                paper.id,
                luma(out)
            );
        }
    }

    /// A ramp must not invert, whatever the stock: an inversion is a sign
    /// error, a clamped tone or a channel swap, and none of them should need a
    /// photograph to notice.
    #[test]
    fn every_stock_keeps_a_ramp_monotone() {
        let steps = [0.0, 0.02, 0.05, 0.1, 0.18, 0.35, 0.6, 0.8, 1.0];
        for film in crate::emulsion::FILM_STOCKS {
            let prepared = RenderParams {
                film,
                ..RenderParams::default()
            }
            .prepare();
            let mut previous = f64::MIN;
            for step in steps {
                let value = luma(prepared.render_pixel([step; 3]));
                assert!(
                    value >= previous - 1e-9,
                    "{} inverts the ramp at {step}: {value:.4} under {previous:.4}",
                    film.id
                );
                previous = value;
            }
        }
    }

    /// The spread of a nine-step ramp, which is how a printer judges contrast:
    /// the slope of one stop either side of mid grey inverts its sign on a
    /// reversal, whose output is a transmittance rather than a reflectance.
    fn spread(prepared: &PreparedRender) -> f64 {
        let steps = [0.0, 0.02, 0.05, 0.1, 0.18, 0.35, 0.6, 0.8, 1.0];
        let values: Vec<f64> = steps
            .iter()
            .map(|step| luma(prepared.render_pixel([*step; 3])))
            .collect();
        let mean = values.iter().sum::<f64>() / values.len() as f64;
        (values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / values.len() as f64).sqrt()
    }

    /// Development reaches the render for every stock, not only the default.
    #[test]
    fn every_stock_gains_contrast_with_development() {
        for film in crate::emulsion::FILM_STOCKS {
            let at = |time_min: f64| {
                spread(
                    &RenderParams {
                        film,
                        development: DevelopmentParams {
                            time_min,
                            ..DevelopmentParams::default()
                        },
                        ..RenderParams::default()
                    }
                    .prepare(),
                )
            };
            let pulled = at(4.0);
            let normal = at(8.0);
            let pushed = at(16.0);
            assert!(
                pulled < normal && normal < pushed,
                "{}: spread {pulled:.3} / {normal:.3} / {pushed:.3} at 4 / 8 / 16 min",
                film.id
            );
        }
    }

    #[test]
    fn over_development_raises_contrast() {
        let normal = local_contrast(&chain(DevelopmentParams::default()));
        let pushed = local_contrast(&chain(DevelopmentParams {
            time_min: 12.0,
            ..DevelopmentParams::default()
        }));
        assert!(pushed > normal, "normal {normal}, pushed {pushed}");
    }

    #[test]
    fn under_development_lowers_contrast() {
        let normal = local_contrast(&chain(DevelopmentParams::default()));
        let pulled = local_contrast(&chain(DevelopmentParams {
            time_min: 3.0,
            ..DevelopmentParams::default()
        }));
        assert!(pulled < normal, "normal {normal}, pulled {pulled}");
    }

    /// A silver image has no dyes. Asking for the spectral print on a
    /// monochrome film would integrate nothing and print a flat grey, so the
    /// scalar print is what the stock gets — and `is_spectral_print` agrees,
    /// because the CLI's summary reads it.
    #[test]
    fn a_silver_film_does_not_print_spectrally() {
        let prepared = RenderParams {
            film: crate::emulsion::film_stock("kodak_trix400").expect("the silver stock"),
            spectral: true,
            spectral_print: true,
            ..RenderParams::default()
        }
        .prepare();
        assert!(!prepared.is_spectral_print());
        let out = prepared.render_pixel([0.18, 0.18, 0.18]);
        assert!(out.iter().all(|channel| channel.is_finite()));
        assert!(out[1] > 0.02 && out[1] < 0.6, "mid grey at {}", out[1]);
    }

    #[test]
    fn spectral_path_keeps_mid_grey_on_target() {
        let prepared = RenderParams {
            spectral: true,
            ..RenderParams::default()
        }
        .prepare();
        assert!(prepared.is_spectral());
        let out = prepared.render_pixel([0.18, 0.18, 0.18]);
        for channel in out {
            assert!(
                (channel - 0.18).abs() < 0.01,
                "mid grey printed at {channel}"
            );
        }
    }

    #[test]
    fn spectral_scan_produces_neutral_grey() {
        let prepared = RenderParams {
            spectral_print: true,
            spectral_scan: true,
            ..RenderParams::default()
        }
        .prepare();
        assert!(prepared.is_spectral_scan());

        let out = prepared.render_pixel([0.18, 0.18, 0.18]);
        let spread = out.iter().copied().fold(f64::NEG_INFINITY, f64::max)
            - out.iter().copied().fold(f64::INFINITY, f64::min);
        assert!(spread < 0.02, "grey drifts by {spread}: {out:?}");
        assert!(out[1] > 0.02 && out[1] < 0.6, "mid grey at {}", out[1]);
    }

    #[test]
    fn spectral_scan_is_monotonic_and_bounded() {
        let prepared = RenderParams {
            spectral_print: true,
            spectral_scan: true,
            ..RenderParams::default()
        }
        .prepare();
        let mut previous = -1.0;
        for i in -80..80 {
            let x = 2.0_f64.powf(f64::from(i) / 10.0) * 0.18;
            let y = prepared.render_pixel([x; 3])[1];
            assert!((0.0..=1.0).contains(&y));
            assert!(y >= previous - 1e-9, "non-monotonic at {x}");
            previous = y;
        }
    }

    #[test]
    fn spectral_print_keeps_mid_grey_on_target() {
        let prepared = RenderParams {
            spectral_print: true,
            ..RenderParams::default()
        }
        .prepare();
        assert!(prepared.is_spectral_print());
        let out = prepared.render_pixel([0.18, 0.18, 0.18]);
        for channel in out {
            assert!(
                (channel - 0.18).abs() < 0.01,
                "mid grey printed at {channel}"
            );
        }
    }

    #[test]
    fn spectral_print_couples_the_layers() {
        let scalar = RenderParams::default().prepare();
        let spectral = RenderParams {
            spectral_print: true,
            ..RenderParams::default()
        }
        .prepare();

        // A cyan-dominant patch: its density sits mostly in one channel, but the
        // dyes overlap, so the paper's other layers must move too.
        let sample = [0.08, 0.42, 0.45];
        let a = scalar.render_pixel(sample);
        let b = spectral.render_pixel(sample);
        let difference: f64 = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).sum();
        assert!(difference > 1e-4, "no coupling visible: {difference}");
    }

    #[test]
    fn spectral_print_is_monotonic_and_bounded() {
        let prepared = RenderParams {
            spectral_print: true,
            ..RenderParams::default()
        }
        .prepare();
        let mut previous = -1.0;
        for i in -80..80 {
            let x = 2.0_f64.powf(f64::from(i) / 10.0) * 0.18;
            let y = prepared.render_pixel([x; 3])[1];
            assert!((0.0..=1.0).contains(&y));
            assert!(y >= previous - 1e-9, "non-monotonic at {x}");
            previous = y;
        }
    }

    #[test]
    fn the_baked_table_matches_the_live_path() {
        let live = RenderParams {
            spectral: true,
            ..RenderParams::default()
        }
        .prepare();
        let baked = RenderParams {
            spectral: true,
            lut_size: 33,
            ..RenderParams::default()
        }
        .prepare();
        assert!(baked.lut().is_some());
        assert!(live.lut().is_none());

        let mut worst = 0.0_f64;
        for r in 0..6 {
            for g in 0..6 {
                for b in 0..6 {
                    let rgb = [
                        0.02 + 0.16 * f64::from(r),
                        0.02 + 0.16 * f64::from(g),
                        0.02 + 0.16 * f64::from(b),
                    ];
                    let a = live.render_pixel(rgb);
                    let c = baked.render_pixel(rgb);
                    for channel in 0..3 {
                        worst = worst.max((a[channel] - c[channel]).abs());
                    }
                }
            }
        }
        // 0.05 reflectance is about the corner error of a 33^3 table; the
        // mean difference is two orders of magnitude smaller.
        assert!(worst < 0.05, "baked path differs by {worst}");
    }

    #[test]
    fn spectral_path_changes_colour_separation() {
        let scalar = RenderParams::default().prepare();
        let spectral = RenderParams {
            spectral: true,
            ..RenderParams::default()
        }
        .prepare();

        let sample = [0.75, 0.12, 0.08];
        let a = scalar.render_pixel(sample);
        let b = spectral.render_pixel(sample);
        let difference: f64 = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).sum();
        assert!(
            difference > 1e-4,
            "spectral path changed nothing: {difference}"
        );
    }

    #[test]
    fn spectral_output_is_monotonic_and_bounded() {
        let prepared = RenderParams {
            spectral: true,
            ..RenderParams::default()
        }
        .prepare();
        let mut previous = -1.0;
        for i in -80..80 {
            let x = 2.0_f64.powf(f64::from(i) / 10.0) * 0.18;
            let y = prepared.render_pixel([x; 3])[1];
            assert!((0.0..=1.0).contains(&y));
            assert!(y >= previous - 1e-9, "non-monotonic at {x}");
            previous = y;
        }
    }

    #[test]
    fn output_is_monotonic_and_bounded() {
        let prepared = chain(DevelopmentParams::default());
        let mut previous = -1.0;
        for i in -80..80 {
            let x = 2.0_f64.powf(f64::from(i) / 10.0) * 0.18;
            let y = prepared.render_pixel([x; 3])[1];
            assert!((0.0..=1.0).contains(&y));
            assert!(y >= previous - 1e-9, "non-monotonic at {x}");
            previous = y;
        }
    }

    /// Grain has to be visible where the eye expects it: not in a flat black, not
    /// in a flat white, and unmistakably in between. Both ends are flat for a
    /// reason that is not written down anywhere — one characteristic curve is in
    /// its toe, the other in its shoulder.
    ///
    /// The peak is not at mid grey, and it should not be. Visible grain is the
    /// counting noise multiplied by the curve's local slope, and on a negative the
    /// straight line extends a couple of stops *above* mid grey, so the product
    /// peaks there. Measured with the measured stock, the spread runs 0.0003 at
    /// −8 EV, 0.0123 at 0, a peak of 0.0174 at +2, and 0.0004 by +8.
    #[test]
    fn grain_peaks_inside_the_straight_line() {
        const SIDE: usize = 64;
        let mut grain = crate::grain::GrainField::new(SIDE, SIDE, 36.0, 11);
        // A 6 µm pixel: a 6000-pixel scan of a 35 mm frame, where grain is real.
        grain.pixel_area_um2 = 36.0;

        let spread = |ev: f64| {
            let prepared = RenderParams {
                exposure_ev: ev,
                ..RenderParams::default()
            }
            .prepare();
            let mut pixels = vec![[0.18; 3]; SIDE * SIDE];
            render_pixels_with_grain(&mut pixels, &prepared, &grain);
            let mean = pixels.iter().map(|p| p[0]).sum::<f64>() / pixels.len() as f64;
            (pixels.iter().map(|p| (p[0] - mean).powi(2)).sum::<f64>() / pixels.len() as f64).sqrt()
        };

        let dark = spread(-8.0);
        let mid = spread(0.0);
        let peak = spread(2.0);
        let bright = spread(8.0);
        assert!(
            peak > 5.0 * dark && peak > 5.0 * bright,
            "peak {peak}  dark {dark}  bright {bright}"
        );
        assert!(
            peak > spread(-2.0) && peak > spread(6.0),
            "the peak is not in the middle: -2 {}, +2 {peak}, +6 {}",
            spread(-2.0),
            spread(6.0)
        );
        assert!(mid > 0.5 * peak, "mid {mid} against peak {peak}");
    }

    #[test]
    fn probe() {
        for (name, params) in [
            (
                "spectral",
                RenderParams {
                    spectral: true,
                    ..RenderParams::default()
                },
            ),
            (
                "print",
                RenderParams {
                    spectral_print: true,
                    ..RenderParams::default()
                },
            ),
            (
                "scan",
                RenderParams {
                    spectral_print: true,
                    spectral_scan: true,
                    ..RenderParams::default()
                },
            ),
        ] {
            let prepared = params.prepare();
            let model = prepared.spectral_model().expect(name);
            println!("== {name}");
            if let Some(e) = &model.exposure {
                println!("  reconstruct = {:?}", e.reconstruct);
                println!("  reference   = {:?}", e.reference);
                println!(
                    "  basis max   = {:?}",
                    [
                        e.basis[0].iter().fold(f64::MIN, |a, &b| a.max(b)),
                        e.basis[1].iter().fold(f64::MIN, |a, &b| a.max(b)),
                        e.basis[2].iter().fold(f64::MIN, |a, &b| a.max(b)),
                    ]
                );
                println!(
                    "  film max    = {:?}",
                    [
                        e.film[0].iter().fold(f64::MIN, |a, &b| a.max(b)),
                        e.film[1].iter().fold(f64::MIN, |a, &b| a.max(b)),
                        e.film[2].iter().fold(f64::MIN, |a, &b| a.max(b)),
                    ]
                );
            }
            if let Some(p) = &model.enlarger {
                println!("  analytical  = {:?}", p.analytical);
                println!(
                    "  clamped={} reference={:?} masking={:?} ref={}",
                    p.clamped, p.reference, p.masking, p.masking_reference
                );
                println!(
                    "  paper max   = {:?}",
                    [0, 1, 2].map(|c| p.paper[c].iter().fold(f64::MIN, |a, &b| a.max(b)))
                );
            }
            if let Some(s) = &model.scan {
                println!(
                    "  scan clamped={} white_xyz={:?} white_rgb={:?}",
                    s.clamped, s.white_xyz, s.white_rgb
                );
                println!(
                    "  neutral[0]={:?} neutral[32]={:?}",
                    s.neutral[0], s.neutral[32]
                );
            }
        }
    }
}

#[cfg(test)]
mod enlarger_tests {
    use super::*;
    use crate::filters::{FilterPack, HeatGlass};

    fn print_with(pack: FilterPack, glass: Option<HeatGlass>) -> [f64; 3] {
        RenderParams {
            spectral_print: true,
            filters: pack,
            heat_glass: glass,
            ..RenderParams::default()
        }
        .prepare()
        .render_pixel([0.45, 0.28, 0.14])
    }

    /// A pack has to change the print at all before any dial can be said to
    /// move it — the first thing the two failed attempts got wrong.
    ///
    /// Note what is *not* asserted here. The gap between two printed channels
    /// is not monotone in the dial: it widens to about 20 CC and then closes,
    /// because the print's response to a cast is not linear once the paper's
    /// layers start clipping. The ADR's "a measurable, monotone shift" is
    /// therefore a statement about the *enlarger* — `print_shift` — and that is
    /// the quantity the next test has to be written against, not a pixel.
    #[test]
    fn a_pack_changes_the_print() {
        let clear = print_with(FilterPack::none(), None);
        let heavy = print_with(FilterPack::new(0.0, 200.0, 0.0), None);
        let moved = (0..3)
            .map(|i| (clear[i] - heavy[i]).abs())
            .fold(0.0, f64::max);
        assert!(moved > 0.01, "200 CC of magenta moved the print by {moved}");
    }

    /// One layer, one density, one dial: the statement the ADR now makes.
    ///
    /// A colour head is three exposure factors. Dialling magenta takes green out
    /// of the light, so the green layer needs *more* exposure to reach the same
    /// density — monotonic, because it is one integral against one spectrum and
    /// not a ratio of two that both contain the filter. The gap between two
    /// printed channels is not monotone and this test deliberately does not ask
    /// it to be; see the roadmap's amendment.
    #[test]
    fn magenta_moves_the_green_exposure_one_way() {
        let green_exposure = |cc: f64| {
            let prepared = RenderParams {
                spectral_print: true,
                filters: FilterPack::new(0.0, cc, 0.0),
                ..RenderParams::default()
            }
            .prepare();
            // The light the green layer needs, in log units: the print's shift
            // is `target - exposure`, so more shift is less light.
            prepared.print_shift()[1]
        };
        // From 5 CC, not 0: an empty pack returns the context untouched — equal
        // energy, no lamp — so the first step would measure the lamp arriving
        // rather than the filter closing.
        let mut previous: Option<f64> = None;
        for step in 1..=12 {
            let cc = 5.0 * f64::from(step);
            let shift = green_exposure(cc);
            if let Some(before) = previous {
                assert!(
                    shift > before + 1e-9,
                    "at {cc} CC the green layer's exposure went {before} -> {shift}"
                );
            }
            previous = Some(shift);
        }
        // And a step is a step: 5 CC is about 0.05 of density of green, which in
        // the head's log units is a small but real move.
        let step = green_exposure(10.0) - green_exposure(5.0);
        assert!(
            (0.005..0.08).contains(&step),
            "5 CC moved the green exposure by {step}"
        );
    }
}