threers 0.1.0

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
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
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
//! Headless offscreen rendering — a batteries-included wrapper that owns the
//! wgpu instance/adapter/device plus a [`Renderer`] and offscreen [`RenderTarget`],
//! so you can render a [`Scene`] to a pixel buffer in a few lines instead of the
//! ~50-line surfaceless-wgpu dance every tool otherwise reimplements.
//!
//! ```no_run
//! use threers::{HeadlessRenderer, Scene, PerspectiveCamera};
//! let mut hr = HeadlessRenderer::builder().size(1920, 1080).supersample(2).build().unwrap();
//! let mut scene = Scene::new();
//! let cam = PerspectiveCamera::new(50.0, 16.0 / 9.0, 0.1, 1000.0);
//! let rgba = hr.render_to_rgba(&mut scene, &cam); // tightly-packed RGBA8
//! ```
//!
//! Native-only (uses `pollster` to block on device acquisition + readback).

use std::sync::Arc;

use crate::cameras::Camera;

cfg_metal! {
    use super::headless_metal::MetalPath;

    /// The Metal side of a new renderer, when `backend` (or, for `Auto`,
    /// `THREERS_BACKEND=metal`) asks for it.
    fn metal_path_for(
        backend: super::RenderBackend,
        format: wgpu::TextureFormat,
        width: u32,
        height: u32,
    ) -> Option<MetalPath> {
        if super::headless_metal::requested(backend) {
            MetalPath::new(format, width, height)
        } else {
            None
        }
    }
}

cfg_no_metal! {
    /// Without the Metal backend the field is still there, always `None`: an
    /// empty enum has no values, so nothing can ever be on this path.
    enum MetalPath {}

    fn metal_path_for(
        _: super::RenderBackend,
        _: wgpu::TextureFormat,
        _: u32,
        _: u32,
    ) -> Option<MetalPath> {
        None
    }
}

use crate::renderer::renderer::stratified_jitter;
use crate::renderer::{RenderTarget, Renderer};
use crate::scene::Scene;

/// Prefer a specific GPU vendor when multiple adapters are present.
///
/// On Linux/Windows this selects a Vulkan adapter — NVIDIA (CUDA driver stack)
/// or AMD (ROCm / RADV). macOS ignores this and uses Metal.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GpuVendor {
    #[default]
    Any,
    /// NVIDIA (`0x10DE`) — discrete GeForce/RTX via Vulkan.
    Nvidia,
    /// AMD (`0x1002`) — Radeon via RADV, AMDVLK, or ROCm-backed drivers.
    Amd,
}

impl GpuVendor {
    const NVIDIA_ID: u32 = 0x10DE;
    const AMD_ID: u32 = 0x1002;

    fn vendor_id(self) -> Option<u32> {
        match self {
            Self::Any => None,
            Self::Nvidia => Some(Self::NVIDIA_ID),
            Self::Amd => Some(Self::AMD_ID),
        }
    }

    /// Parse `THREERS_GPU` / `FLY_GPU`: `nvidia`, `cuda`, `amd`, or `rocm`.
    pub fn from_env() -> Self {
        match std::env::var("THREERS_GPU")
            .or_else(|_| std::env::var("FLY_GPU"))
            .ok()
            .as_deref()
        {
            Some("nvidia") | Some("cuda") | Some("NVIDIA") | Some("CUDA") => Self::Nvidia,
            Some("amd") | Some("rocm") | Some("AMD") | Some("ROCM") => Self::Amd,
            _ => Self::Any,
        }
    }
}

fn adapter_score(info: &wgpu::AdapterInfo) -> u32 {
    match info.device_type {
        wgpu::DeviceType::DiscreteGpu => 100,
        wgpu::DeviceType::IntegratedGpu => 50,
        wgpu::DeviceType::VirtualGpu => 25,
        _ => 0,
    }
}

fn request_headless_adapter(
    instance: &wgpu::Instance,
    config: &HeadlessConfig,
) -> Result<wgpu::Adapter, String> {
    let backends = wgpu::Backends::PRIMARY;
    if let Some(vendor_id) = config.gpu_vendor.vendor_id() {
        let adapters = pollster::block_on(instance.enumerate_adapters(backends));
        let mut best: Option<(u32, wgpu::Adapter)> = None;
        for adapter in adapters {
            let info = adapter.get_info();
            if info.vendor != vendor_id {
                continue;
            }
            let score = adapter_score(&info);
            if best.as_ref().map(|(s, _)| score > *s).unwrap_or(true) {
                best = Some((score, adapter));
            }
        }
        if let Some((_, adapter)) = best {
            let info = adapter.get_info();
            eprintln!(
                "   gpu       {} ({:?}, {:?}, vendor 0x{:04x})",
                info.name, info.backend, info.device_type, info.vendor
            );
            return Ok(adapter);
        }
        eprintln!(
            "   gpu       warning: no adapter for vendor 0x{vendor_id:04x}, falling back to default"
        );
    }

    let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
        power_preference: config.power_preference,
        compatible_surface: None,
        force_fallback_adapter: false,
        apply_limit_buckets: false,
    }))
    .map_err(|e| format!("no suitable wgpu adapter for headless rendering: {e}"))?;
    let info = adapter.get_info();
    eprintln!(
        "   gpu       {} ({:?}, {:?})",
        info.name, info.backend, info.device_type
    );
    Ok(adapter)
}

/// Configuration for a [`HeadlessRenderer`]. Prefer [`HeadlessRenderer::builder`].
#[derive(Clone, Debug)]
pub struct HeadlessConfig {
    /// Output width in pixels (before supersampling).
    pub width: u32,
    /// Output height in pixels (before supersampling).
    pub height: u32,
    /// Supersample factor — the scene renders at `size × supersample`. `1` = off.
    pub supersample: u32,
    /// Reconstruction filter the supersample resolve uses. The default halves
    /// the sampling error of the plain block average; see
    /// [`DownsampleFilter`](crate::renderer::DownsampleFilter).
    pub downsample_filter: crate::renderer::DownsampleFilter,
    /// Color target format. `Rgba8UnormSrgb` for images; `Rgba16Float` for HDR.
    pub color_format: wgpu::TextureFormat,
    /// Raise the device's texture-size limits to the adapter maximum — required
    /// for 4K (and 2K × supersample), which exceed wgpu's conservative defaults.
    pub high_resolution: bool,
    /// Enable temporal anti-aliasing (accumulate jittered frames; see
    /// [`Renderer::set_taa`]).
    pub taa: bool,
    /// Adapter selection preference.
    pub power_preference: wgpu::PowerPreference,
    /// When set, pick a discrete adapter from this vendor (Vulkan on Linux).
    pub gpu_vendor: GpuVendor,
    /// The backend frames are drawn with. [`Auto`](super::RenderBackend::Auto)
    /// reads `THREERS_BACKEND`; name one to choose it in code instead, which a
    /// test running beside others must, since the environment is shared.
    pub backend: super::RenderBackend,
}

impl Default for HeadlessConfig {
    fn default() -> Self {
        Self {
            width: 1024,
            height: 1024,
            supersample: 1,
            downsample_filter: crate::renderer::DownsampleFilter::default(),
            color_format: wgpu::TextureFormat::Rgba8UnormSrgb,
            high_resolution: true,
            taa: false,
            power_preference: wgpu::PowerPreference::HighPerformance,
            gpu_vendor: GpuVendor::Any,
            backend: super::RenderBackend::Auto,
        }
    }
}

/// Fluent builder for [`HeadlessRenderer`].
#[derive(Clone, Debug, Default)]
pub struct HeadlessBuilder {
    config: HeadlessConfig,
}

impl HeadlessBuilder {
    /// Output size in pixels (before supersampling).
    pub fn size(mut self, width: u32, height: u32) -> Self {
        self.config.width = width;
        self.config.height = height;
        self
    }
    /// Supersample factor (render at `size × factor`, then read back at that
    /// resolution). `1` disables it.
    pub fn supersample(mut self, factor: u32) -> Self {
        self.config.supersample = factor.max(1);
        self
    }
    /// Reconstruction filter for the supersample resolve (default
    /// [`Mitchell`](crate::renderer::DownsampleFilter::Mitchell)).
    ///
    /// Supersampling harder stops paying off early because the block average is
    /// the limit, not the sample count — a wider filter is the other half of
    /// the fix. Pass [`Box`](crate::renderer::DownsampleFilter::Box) for the
    /// pre-0.0.7 pixels.
    pub fn downsample_filter(mut self, filter: crate::renderer::DownsampleFilter) -> Self {
        self.config.downsample_filter = filter;
        self
    }
    /// Color target format (default `Rgba8UnormSrgb`).
    pub fn color_format(mut self, format: wgpu::TextureFormat) -> Self {
        self.config.color_format = format;
        self
    }
    /// Raise texture-size limits to the adapter max (default `true`; needed for 4K).
    pub fn high_resolution(mut self, enabled: bool) -> Self {
        self.config.high_resolution = enabled;
        self
    }
    /// Enable temporal anti-aliasing.
    pub fn taa(mut self, enabled: bool) -> Self {
        self.config.taa = enabled;
        self
    }
    /// Adapter power preference.
    pub fn power_preference(mut self, preference: wgpu::PowerPreference) -> Self {
        self.config.power_preference = preference;
        self
    }
    /// Prefer NVIDIA or AMD when multiple GPUs are present (Linux/Windows Vulkan).
    /// The backend to draw with — see [`HeadlessConfig::backend`].
    pub fn backend(mut self, backend: super::RenderBackend) -> Self {
        self.config.backend = backend;
        self
    }
    pub fn gpu_vendor(mut self, vendor: GpuVendor) -> Self {
        self.config.gpu_vendor = vendor;
        self
    }
    /// Acquire the GPU and construct the renderer.
    pub fn build(self) -> Result<HeadlessRenderer, String> {
        HeadlessRenderer::new(self.config)
    }
}

/// A headless renderer: owns the GPU device/queue, a [`Renderer`], and an
/// offscreen [`RenderTarget`]. Render with [`render`](Self::render) /
/// [`render_to_rgba`](Self::render_to_rgba); reach the underlying [`Renderer`]
/// via [`renderer`](Self::renderer) for post-fx, TAA, etc.
pub struct HeadlessRenderer {
    /// `THREERS_BACKEND=metal`: frames drawn by the native Metal backend.
    metal: Option<MetalPath>,
    /// The screen [`compose`](Self::compose) draws into on wgpu.
    compose_target: Option<crate::postprocessing::Target>,
    /// Set by a `&self` call that hands out wgpu itself (`device`, `queue`,
    /// `target`, `mark_target`): the frames that follow must be wgpu's.
    metal_off: std::sync::atomic::AtomicBool,
    device: Arc<wgpu::Device>,
    queue: Arc<wgpu::Queue>,
    renderer: Renderer,
    target: RenderTarget,
    config: HeadlessConfig,
    render_width: u32,
    render_height: u32,
    /// Mapping buffers, recycled. Allocating one per frame costs an allocation
    /// and a free inside the frame loop for no benefit — the size never changes.
    spare: Vec<wgpu::Buffer>,
    /// A readback submitted but not yet drained, for the pipelined path.
    pending: Option<Pending>,
    /// Readbacks in flight on the RGB path, oldest first.
    ///
    /// One deep is not enough. A copy submitted this frame is not finished when
    /// the next frame's draw is queued behind it, so taking it immediately means
    /// waiting on the GPU: measured over 360 frames at 4K, a readback that costs
    /// 9.7 ms on its own costs 34-46 ms in a stream. Holding several lets the
    /// CPU run ahead far enough that the oldest is always already done.
    ///
    /// Measured, 360 frames at 4K with MSAA 4, wall time for the frame stage:
    ///
    /// ```text
    /// depth 1   23.6 s     depth 4   18.5 s
    /// depth 2   22.9 s     depth 6   17.2 s
    ///                      depth 8    8.6 s
    /// ```
    ///
    /// The cost is one mapped buffer per level -- 25 MB a frame at 4K, 100 MB
    /// at 8K -- which is why this is bounded rather than unbounded.
    rgb_queue: std::collections::VecDeque<Pending>,
    /// How many to keep in flight before draining one. READAHEAD overrides it.
    read_ahead: usize,
    /// Averages the supersampled target down to the output size on the GPU.
    /// Built on first use, and only when `supersample > 1`.
    resolve: Option<crate::renderer::Downsampler>,
    /// Sums jittered frames at output resolution for
    /// [`render_accumulated`](HeadlessRenderer::render_accumulated).
    accum: Option<crate::renderer::accumulate::Accumulator>,
    /// The view the accumulator reads and finally writes, cached across samples.
    accum_view: Option<wgpu::TextureView>,
    /// Bumped whenever `accum_view` is replaced, so the accumulator knows to
    /// rebuild its bind group.
    accum_generation: u64,
    /// Set when `render_accumulated` has already left the averaged frame in the
    /// texture readback reads, so the next `run_resolve` must not overwrite it
    /// with the last sample alone. Consumed by that call.
    accum_ready: bool,
    /// Set by [`HeadlessRenderer::render_accumulated_unjittered`].
    unjittered: bool,
    /// GPU alpha-strip, built on first use and only when a caller asks for RGB.
    rgb_pack: Option<crate::renderer::rgb_pack::RgbPack>,
    /// Bloom, when a caller has asked for it. Runs just before the pack, on the
    /// same finished frame, so the render path is untouched.
    bloom: Option<crate::renderer::bloom::Bloom>,
    bloom_cfg: Option<(f32, f32, f32)>,
    /// Ambient occlusion, alongside bloom on the same finished frame.
    ssao: Option<crate::renderer::ssao::Ssao>,
    ssao_cfg: Option<(f32, f32)>,
    /// focus, range, radius in pixels. The clip planes come from the frame.
    dof_cfg: Option<(f32, f32, f32)>,
    /// Shutter fraction for camera motion blur; 0 disables it.
    shutter: f32,
    film: crate::renderer::rgb_pack::FilmGrade,
    /// An RGBA overlay composited over the frame during the pack, so the CPU
    /// never has to write to the frame at all.
    overlay: Option<wgpu::Texture>,
}

/// A texture→buffer copy in flight.
struct Pending {
    buffer: wgpu::Buffer,
    rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,
    padded: u32,
    unpadded: u32,
    height: u32,
    /// What the texture held, so the bytes can be unpacked. The readback used
    /// to assume four bytes a pixel, which made `Rgba16Float` — the HDR format
    /// this builder offers — fail validation with "bytes per row is less than
    /// the number of bytes in a complete row".
    format: wgpu::TextureFormat,
}

/// Bytes a pixel, for the formats a headless colour target can hold.
fn target_bpp(format: wgpu::TextureFormat) -> u32 {
    match format {
        wgpu::TextureFormat::Rgba16Float => 8,
        wgpu::TextureFormat::Rgba32Float => 16,
        _ => 4,
    }
}

/// IEEE-754 binary16 → binary32.
///
/// Duplicated rather than shared with `raytrace::texture`: that module only
/// exists under the `raytrace` feature, and reading back a frame must not
/// depend on whether a path tracer was compiled in.
fn half_to_f32(bits: u16) -> f32 {
    crate::renderer::readback::f16_to_f32(bits)
}

/// Linear light → an sRGB byte, the same curve the raster shader applies when
/// it writes to an 8-bit target.
fn encode_srgb_byte(v: f32) -> u8 {
    let v = v.clamp(0.0, 1.0);
    let s = if v <= 0.003_130_8 {
        v * 12.92
    } else {
        1.055 * v.powf(1.0 / 2.4) - 0.055
    };
    (s * 255.0 + 0.5) as u8
}

impl HeadlessRenderer {
    /// Start a fluent [`HeadlessBuilder`].
    pub fn builder() -> HeadlessBuilder {
        HeadlessBuilder::default()
    }

    /// Construct from a [`HeadlessConfig`] (acquires the GPU; blocks).
    pub fn new(config: HeadlessConfig) -> Result<Self, String> {
        let width = config.width.max(1);
        let height = config.height.max(1);
        let ss = config.supersample.max(1);
        let render_width = width.saturating_mul(ss).max(1);
        let render_height = height.saturating_mul(ss).max(1);

        // `InstanceDescriptor` has no `Default` in wgpu 30 — a display handle is
        // something you either have or deliberately do not, and headless is the
        // second case.
        let mut instance_desc = wgpu::InstanceDescriptor::new_without_display_handle();
        instance_desc.backends = wgpu::Backends::PRIMARY;
        let instance = wgpu::Instance::new(instance_desc);
        let adapter = request_headless_adapter(&instance, &config)?;

        let adapter_limits = adapter.limits();
        let mut limits = if config.high_resolution {
            wgpu::Limits::downlevel_defaults().using_resolution(adapter_limits.clone())
        } else {
            wgpu::Limits::downlevel_defaults()
        };
        // Downlevel allows 16 sampled textures and samplers per stage; the main
        // pass declares 20 in the fragment stage — material maps, shadow
        // atlases and the environment all bind there. wgpu 0.20 never checked
        // this, so the layout has been over the line the whole time and only
        // wgpu 30's validation says so. `using_resolution` does not cover
        // binding counts, so raise them separately, to whatever the adapter has.
        limits.max_sampled_textures_per_shader_stage =
            adapter_limits.max_sampled_textures_per_shader_stage;
        limits.max_samplers_per_shader_stage = adapter_limits.max_samplers_per_shader_stage;
        // A mesh is one vertex buffer, and the default cap is 256 MiB: an
        // 11.8M-triangle lattice needs 376. Whatever the adapter can hold.
        limits.max_buffer_size = limits.max_buffer_size.max(adapter_limits.max_buffer_size);
        // WHATEVER COMPRESSION THIS ADAPTER HAS, ask for it — and 16-bit unorm
        // and filtered 32-bit floats (`gpu::TEXTURE_FEATURES`).
        //
        // A device only exposes features it was asked for, so with
        // `Features::empty()` every BC texture would be decoded on the CPU at
        // upload on hardware that samples it perfectly well. Which family is
        // present is not portable -- BC is universal on desktop and missing on
        // most mobile parts, ASTC the other way round, Apple silicon has all
        // three -- so the request is the intersection of what is wanted and
        // what the adapter reports, and asking for nothing else keeps the
        // device as widely creatable as it was.
        let compression = crate::gpu::TEXTURE_FEATURES
            // Timestamps for `Renderer::gpu_frame_ms`. Masked by what the
            // adapter reports, like the compression formats above, so asking
            // still cannot fail device creation.
            | wgpu::Features::TIMESTAMP_QUERY;
        let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
            label: Some("threers headless device"),
            required_features: adapter.features() & compression,
            required_limits: limits,
            ..Default::default()
        }))
        .map_err(|e| format!("wgpu request_device failed: {e:?}"))?;

        let device = Arc::new(device);
        let queue = Arc::new(queue);
        let mut renderer = Renderer::new(
            device.clone(),
            queue.clone(),
            config.color_format,
            render_width,
            render_height,
        );
        renderer.set_taa(config.taa);
        // Viewport and scissor rectangles are given in output pixels; the
        // supersampled target is `ss` device pixels to each of them.
        renderer.set_pixel_ratio(ss as f32);
        let target = RenderTarget::new(&device, render_width, render_height, config.color_format);
        // The headless image is the picture: tone-mapped like a canvas.
        target.set_presents(true);

        Ok(Self {
            metal: metal_path_for(
                config.backend,
                config.color_format,
                render_width,
                render_height,
            ),
            compose_target: None,
            metal_off: std::sync::atomic::AtomicBool::new(false),
            device,
            queue,
            renderer,
            target,
            config,
            render_width,
            render_height,
            spare: Vec::new(),
            pending: None,
            rgb_queue: std::collections::VecDeque::new(),
            read_ahead: std::env::var("READAHEAD")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(8usize)
                .clamp(1, 8),
            rgb_pack: None,
            bloom: None,
            bloom_cfg: None,
            ssao: None,
            ssao_cfg: None,
            dof_cfg: None,
            shutter: 0.0,
            film: Default::default(),
            overlay: None,
            resolve: None,
            accum: None,
            accum_view: None,
            accum_generation: 0,
            accum_ready: false,
            unjittered: false,
        })
    }

    /// The wrapped [`Renderer`] (for post-fx, TAA, render-target registration…).
    ///
    /// Under `THREERS_BACKEND=metal` its tone mapping still applies: it is
    /// carried to the Metal renderer each frame.
    pub fn renderer(&mut self) -> &mut Renderer {
        &mut self.renderer
    }
    /// The GPU device (share it to build geometry/textures/render targets).
    ///
    /// Resources built on it are wgpu's, so under `THREERS_BACKEND=metal`
    /// asking for it puts this renderer back on wgpu.
    pub fn device(&self) -> &Arc<wgpu::Device> {
        self.leave_metal("HeadlessRenderer::device");
        &self.device
    }
    /// The GPU queue. See [`device`](Self::device).
    pub fn queue(&self) -> &Arc<wgpu::Queue> {
        self.leave_metal("HeadlessRenderer::queue");
        &self.queue
    }

    /// Block until the GPU has finished everything submitted — what a timing
    /// loop waits on. On either backend: on the native Metal one,
    /// [`render`](Self::render) returns without waiting for the frame, and
    /// this waits for it (and its readback) without handing the renderer to
    /// wgpu the way [`device`](Self::device) does.
    pub fn wait_idle(&mut self) {
        on_metal! {
            if let Some(m) = self.metal_path() {
                m.wait_idle();
                return;
            }
        }
        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
    }

    /// Whether frames are being drawn by the native Metal backend
    /// (`THREERS_BACKEND=metal`, see `headless_metal`).
    pub fn is_native_metal(&self) -> bool {
        self.metal.is_some() && !self.metal_off.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Put this renderer back on wgpu for good, saying why (once per reason).
    fn leave_metal(&self, reason: &str) {
        let _ = reason;
        on_metal! {
            if self.is_native_metal() {
                super::headless_metal::warn_fallback(reason);
                self.metal_off.store(true, std::sync::atomic::Ordering::Relaxed);
            }
        }
    }

    /// The Metal path, if frames still go through it.
    // Called only from `on_metal!` blocks, which a build without the backend
    // leaves out.
    #[allow(dead_code)]
    fn metal_path(&mut self) -> Option<&mut MetalPath> {
        if self.metal_off.load(std::sync::atomic::Ordering::Relaxed) {
            self.metal = None;
        }
        self.metal.as_mut()
    }
    /// Enable/disable temporal anti-aliasing (see [`Renderer::set_taa`]).
    pub fn set_taa(&mut self, enabled: bool) {
        self.renderer.set_taa(enabled);
    }
    /// Enable hardware MSAA (`samples <= 1` = off, else 4×) for the opaque forward
    /// pass. Composes with (and is usually preferable to) `supersample`.
    pub fn set_msaa(&mut self, samples: u32) {
        self.renderer.set_msaa(samples);
        on_metal! {
            if let Some(m) = self.metal_path()
                && !m.set_msaa(samples) {
                    self.leave_metal("MSAA on this device");
                }
        }
    }
    /// The render resolution (output size × supersample).
    pub fn render_size(&self) -> (u32, u32) {
        (self.render_width, self.render_height)
    }
    /// The config this renderer was built with.
    pub fn config(&self) -> &HeadlessConfig {
        &self.config
    }

    /// Render `scene` from `camera` into the offscreen target.
    pub fn render(&mut self, scene: &mut Scene, camera: &dyn Camera) {
        on_metal! {
            let wgpu = &self.renderer;
            if let Some(m) = self.metal.as_mut().filter(|_| {
                !self.metal_off.load(std::sync::atomic::Ordering::Relaxed)
            }) {
                match m.render(scene, camera, wgpu) {
                    // Until a frame has been read from Metal, wgpu draws it too
                    // (see `MetalPath::confirmed`).
                    Ok(()) if m.confirmed() => return,
                    Ok(()) => {}
                    Err(e) => self.leave_metal(&format!("a frame the Metal backend refused ({e})")),
                }
            }
        }
        // Any ordinary draw invalidates an accumulated frame, so the resolve
        // pass is due again. Keeping the flag until then rather than having the
        // readback consume it makes reading the same frame twice idempotent.
        self.accum_ready = false;
        if self.renderer.msaa() > 1 {
            // Surface-style path so the MSAA opaque pass engages and resolves into
            // the offscreen target's color view — and, unlike the plain
            // `render` it used to call, one that hands the temporal pass its
            // textures. The two compose: MSAA resolves coverage, accumulation
            // resolves shading, and asking for both used to get only the first.
            let linear = self.config.color_format == wgpu::TextureFormat::Rgba16Float;
            self.renderer
                .render_to_multisampled(scene, camera, &self.target, linear);
        } else {
            self.renderer.render_to(scene, camera, &self.target);
        }
    }

    /// Render one settled frame: `samples` jittered draws averaged into the
    /// target, with the pose held still between them.
    ///
    /// This is the offline counterpart to supersampling, and the one to reach
    /// for when a frame has to be *right* rather than fast. Each sample offsets
    /// the projection by a sub-pixel Halton step and folds the result into a
    /// running mean, so `n` samples give the quality of `n` samples a pixel
    /// while only ever holding one buffer at output size — which is what makes
    /// it usable at 4K and 8K, where a supersampled target does not fit.
    ///
    /// It is also better per sample than supersampling, because the jitter is
    /// stochastic where a supersample grid is regular: what is left over is
    /// noise that averages away rather than a pattern that folds back. On a
    /// rotating phone's side rail, 32 accumulated samples measured 0.21 rms
    /// banding against 0.30 for the 36 samples of `supersample(6)`.
    ///
    /// Composes with [`supersample`](HeadlessBuilder::supersample) and with
    /// MSAA — all three resolve different things, and using two of them
    /// together is usually cheaper than pushing one of them hard.
    ///
    /// ```no_run
    /// # use threers::{HeadlessRenderer, Scene, PerspectiveCamera};
    /// let mut hr = HeadlessRenderer::builder().size(1920, 1080).taa(true).build().unwrap();
    /// # let mut scene = Scene::new();
    /// # let cam = PerspectiveCamera::new(50.0, 16.0 / 9.0, 0.1, 100.0);
    /// hr.render_accumulated(&mut scene, &cam, 32);
    /// let frame = hr.read_rgba();
    /// # let _ = frame;
    /// ```
    ///
    /// `samples` of 0 or 1 is one ordinary render, and leaves the accumulation
    /// state alone.
    ///
    /// With [`supersample`](HeadlessBuilder::supersample) above 1 the averaged
    /// frame lands in the *resolved* target, so read it with
    /// [`read_rgba_resolved`](Self::read_rgba_resolved) or one of the other
    /// resolved readbacks. [`read_rgba`](Self::read_rgba) returns the internal
    /// buffer, which holds the last jittered sample on its own.
    /// [`render_accumulated`](Self::render_accumulated) with the jitter held at
    /// zero, so every sample draws the same picture.
    ///
    /// Only useful for checking the accumulator itself: `n` identical samples
    /// must come back bit-for-bit as one render, and any drift in the running
    /// sum, the weights or the transfer curve shows up there and nowhere else.
    #[doc(hidden)]
    pub fn render_accumulated_unjittered(
        &mut self,
        scene: &mut Scene,
        camera: &dyn Camera,
        samples: u32,
    ) {
        self.unjittered = true;
        self.render_accumulated(scene, camera, samples);
        self.unjittered = false;
    }

    pub fn render_accumulated(&mut self, scene: &mut Scene, camera: &dyn Camera, samples: u32) {
        if self.is_native_metal() {
            self.leave_metal("render_accumulated (jittered accumulation)");
        }
        if samples <= 1 {
            self.render(scene, camera);
            return;
        }
        // Average after the supersample resolve rather than before it. Both are
        // linear *in the same space* — see `accumulate` for the transfer curve,
        // which is the part that was wrong — so the picture is the same either
        // way, but the mean then runs over output pixels instead of
        // `supersample²` times as many.
        //
        // The payoff is memory, not time, and it is worth saying so because the
        // arithmetic suggests otherwise. Peak footprint for an 8K render fell
        // from 11.07 GB to 8.78 GB, since the internal history there is two
        // buffers of 8640×15360×8 bytes. Wall time did not move: 74.3 ms a
        // frame against 76.9, inside a ±6 ms spread. What the traffic model
        // leaves out is that the resolve, which used to run once a frame, now
        // runs once a sample and gives most of the saving back.
        let (ow, oh) = match self.ensure_resolve() {
            Some(ds) => ds.size(),
            None => (self.render_width, self.render_height),
        };
        let out_format = match self.resolve.as_ref() {
            Some(ds) => ds.texture().format(),
            None => self.target.color_texture.format(),
        };
        if !matches!(&self.accum, Some(a) if a.matches(ow, oh, out_format)) {
            self.accum = Some(crate::renderer::accumulate::Accumulator::new(
                &self.device,
                ow,
                oh,
                out_format,
            ));
            self.accum_view = None;
        }
        // The add pass reads this and the final resolve writes it: the texture
        // readback will look at, which is the resolve target when there is one
        // and the render target when there is not. Built once — the first
        // version of this made a view and two bind groups per sample, sixty-four
        // objects a frame, and measured 11% slower than the ordering it
        // replaced.
        if self.accum_view.is_none() {
            let src = match self.resolve.as_ref() {
                Some(ds) => ds.texture(),
                None => &self.target.color_texture,
            };
            self.accum_view = Some(src.create_view(&wgpu::TextureViewDescriptor::default()));
            self.accum_generation += 1;
        }
        // Identifies the texture behind that view for the accumulator's own
        // bind-group cache. It only ever changes with the view.
        let key = self.accum_generation;

        // The renderer's own temporal pass stays out of it: its history is at
        // internal resolution, which is the cost being removed here. All it is
        // asked for is the jitter — and because the sample count is known here
        // and is not known inside a streaming temporal pass, it can be the
        // stratified set rather than Halton. See [`stratified_jitter`].
        let offsets = stratified_jitter(samples);
        let was_taa = self.renderer.taa();
        self.renderer.set_taa(false);
        for i in 0..samples {
            self.renderer.set_jitter_override(Some(if self.unjittered {
                (0.0, 0.0)
            } else {
                offsets[i as usize]
            }));
            self.render(scene, camera);
            let mut enc = self
                .device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("threers accumulate sample"),
                });
            if let Some(ds) = self.resolve.as_ref() {
                ds.resolve(&mut enc);
            }
            let accum = self.accum.as_ref().expect("accumulator built above");
            let view = self.accum_view.as_ref().expect("view built above");
            accum.add_sample(&self.device, &self.queue, &mut enc, view, key, 1.0, i == 0);
            if i + 1 == samples {
                // Land the mean where readback looks, which is the resolve
                // target when there is one and the render target when there is
                // not. Neither is bound by the pass reading the accumulator.
                accum.resolve_into(&self.queue, &mut enc, view, samples as f32);
            }
            self.queue.submit(Some(enc.finish()));
        }
        self.renderer.set_jitter_override(None);
        self.renderer.set_taa(was_taa);
        self.accum_ready = self.resolve.is_some();
    }

    /// Fill the offscreen target with `color` — the scissor rectangle when the
    /// renderer's scissor test is on, all of it otherwise. See
    /// [`Renderer::clear`].
    pub fn clear(&mut self, color: crate::math::Color, alpha: f32) {
        on_metal! {
            let wgpu = &self.renderer;
            if let Some(m) = self.metal.as_mut().filter(|_| {
                !self.metal_off.load(std::sync::atomic::Ordering::Relaxed)
            }) {
                match m.clear(color, alpha, wgpu) {
                    Ok(()) if m.confirmed() => return,
                    Ok(()) => {}
                    Err(e) => self.leave_metal(&format!("a clear the Metal backend refused ({e})")),
                }
            }
        }
        self.accum_ready = false;
        self.renderer
            .clear_render_target(&self.target, color, alpha);
    }

    /// A [`MarkRenderer`](crate::marks::MarkRenderer) for this renderer's
    /// backend — wgpu's device, or under `THREERS_BACKEND=metal` the Metal
    /// one its frames are drawn on. Draw with [`draw_marks`](Self::draw_marks).
    pub fn mark_renderer(&mut self) -> crate::marks::MarkRenderer {
        crate::marks::MarkRenderer::new_on(&self.marks_gpu())
    }

    /// Upload `geometry` now rather than at its first draw, on whichever
    /// backend draws — so a compute pass can write its
    /// [`vertex_buffer`](Self::vertex_buffer).
    pub fn upload_geometry(&mut self, geometry: &Arc<crate::core::BufferGeometry>) {
        on_metal! {
            if let Some(m) = self.metal_path() {
                m.upload_geometry(geometry);
                return;
            }
        }
        self.renderer.upload_geometry(geometry);
    }

    /// The vertex buffer an uploaded geometry is drawn from, for a compute
    /// pass on [`marks_gpu`](Self::marks_gpu) to write in place.
    ///
    /// [`vertex_floats`](Self::vertex_floats) `f32` a vertex. The first
    /// twelve are the same on both backends — position(3), normal(3),
    /// uv(2), colour(4) — and wgpu's has a tangent(4) after them. The
    /// conditions are [`Renderer::vertex_buffer`]'s:
    /// [`BufferGeometry::gpu_writable`](crate::core::BufferGeometry::gpu_writable),
    /// and valid until the geometry's version changes.
    pub fn vertex_buffer(
        &mut self,
        geometry: &Arc<crate::core::BufferGeometry>,
    ) -> Option<crate::marks::gpu::Buffer> {
        on_metal! {
            if let Some(m) = self.metal_path() {
                return m.vertex_buffer(geometry);
            }
        }
        self.renderer
            .vertex_buffer(geometry)
            .map(crate::marks::gpu::Buffer::from)
    }

    /// `f32`s a vertex in [`vertex_buffer`](Self::vertex_buffer): 16 on
    /// wgpu, 12 on the native Metal backend.
    pub fn vertex_floats(&self) -> u32 {
        if self.is_native_metal() {
            12
        } else {
            (crate::renderer::gpu_mesh::GpuMesh::VERTEX_STRIDE / 4) as u32
        }
    }

    /// The GPU [`mark_renderer`](Self::mark_renderer)'s marks draw with.
    pub fn marks_gpu(&mut self) -> crate::marks::gpu::Gpu {
        on_metal! {
            if let Some(m) = self.metal_path() {
                return m.marks_gpu();
            }
        }
        crate::marks::gpu::Gpu::from((&*self.device, &*self.queue))
    }

    /// Draw `layers` over the frame [`render`](Self::render) just produced,
    /// depth-tested against it, on either backend. `marks` comes from
    /// [`mark_renderer`](Self::mark_renderer). Read the result back as usual.
    pub fn draw_marks(
        &mut self,
        marks: &mut crate::marks::MarkRenderer,
        view: &crate::marks::MarkView,
        layers: &mut [&mut dyn crate::marks::Mark],
    ) {
        let gpu = self.marks_gpu();
        on_metal! {
            if gpu.is_metal()
                && let Some(m) = self.metal_path() {
                    let target = m.mark_target();
                    marks.draw_on(&gpu, &target, view, layers);
                    return;
                }
        }
        let target = self.wgpu_mark_target();
        marks.draw_on(&gpu, &target, view, layers);
    }

    /// The layer and row nearest pixel `(x, y)` within `radius` pixels, on
    /// either backend — [`MarkRenderer::pick`](crate::marks::MarkRenderer::pick)
    /// without an occluder, waited for.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn pick_marks(
        &mut self,
        marks: &mut crate::marks::MarkRenderer,
        view: &crate::marks::MarkView,
        layers: &mut [&mut dyn crate::marks::Mark],
        (x, y): (f32, f32),
        radius: u32,
    ) -> Option<crate::marks::PickHit> {
        let gpu = self.marks_gpu();
        marks
            .pick_on(&gpu, view, layers, None, x, y, radius)
            .wait_on(&gpu)
    }

    /// Where [`marks`](crate::marks) draw over the frame [`render`](Self::render)
    /// just produced, depth-testing against it. Read the result back with
    /// [`read_rgba`](Self::read_rgba) as usual.
    ///
    /// On the backend frames are drawn with: under `THREERS_BACKEND=metal`
    /// the Metal frame, for a [`MarkRenderer`](crate::marks::MarkRenderer)
    /// on [`marks_gpu`](Self::marks_gpu) — unless something has already put
    /// this renderer on wgpu ([`device`](Self::device), for one).
    pub fn mark_target(&self) -> crate::marks::MarkTarget<'_> {
        on_metal! {
            if self.is_native_metal()
                && let Some(m) = self.metal.as_ref() {
                    return m.mark_target();
                }
        }
        self.wgpu_mark_target()
    }

    fn wgpu_mark_target(&self) -> crate::marks::MarkTarget<'_> {
        match self.renderer.overlay_attachments() {
            (Some(color), depth, samples) if self.renderer.msaa() > 1 => crate::marks::MarkTarget {
                color: color.into(),
                resolve: Some((&self.target.color_view).into()),
                depth: Some(depth.into()),
                format: self.target.format,
                samples,
                rect: None,
                _borrow: std::marker::PhantomData,
            },
            _ => crate::marks::MarkTarget::render_target(&self.target),
        }
    }

    /// The target frames are drawn into.
    pub fn target(&self) -> &RenderTarget {
        self.leave_metal("HeadlessRenderer::target");
        &self.target
    }

    /// Run `composer` over `scene` from `camera` and read the screen back:
    /// tightly-packed bytes in the composer's
    /// [`screen_format`](crate::postprocessing::EffectComposer::screen_format),
    /// at its [`drawing_size`](crate::postprocessing::EffectComposer::drawing_size).
    ///
    /// On whichever backend this renderer draws with — under
    /// `THREERS_BACKEND=metal` every pass runs on Metal. A composer belongs to
    /// the backend it first ran on: its targets live there.
    pub fn compose(
        &mut self,
        composer: &mut crate::postprocessing::EffectComposer,
        scene: &mut Scene,
        camera: &dyn Camera,
    ) -> Vec<u8> {
        on_metal! {
            let wgpu = &self.renderer;
            if let Some(m) = self.metal.as_mut().filter(|_| {
                !self.metal_off.load(std::sync::atomic::Ordering::Relaxed)
            }) {
                match m.compose(composer, scene, camera, wgpu) {
                    Ok(px) => return px,
                    Err(e) => self.leave_metal(&format!("post-processing the Metal backend refused ({e})")),
                }
            }
        }
        let (w, h) = composer.drawing_size();
        let t = crate::postprocessing::ensure_target(
            &mut self.compose_target,
            &mut self.renderer,
            w,
            h,
            composer.screen_format(),
        );
        composer.render_to_target(&mut self.renderer, scene, camera, t.clone());
        super::readback::texture_bytes(&self.device, &self.queue, &t.render_target().color_texture)
    }

    /// Render, then read the target back as tightly-packed RGBA8 (row-major,
    /// top-left origin) sized [`render_size`](Self::render_size).
    pub fn render_to_rgba(&mut self, scene: &mut Scene, camera: &dyn Camera) -> Vec<u8> {
        self.render(scene, camera);
        self.read_rgba()
    }

    /// Draw the caption showing at `time` seconds over the current target
    /// contents, on the GPU.
    ///
    /// Call it between [`render`](Self::render) and [`read_rgba`](Self::read_rgba),
    /// or use [`render_to_rgba_with_captions`](Self::render_to_rgba_with_captions)
    /// for the whole sequence.
    #[cfg(feature = "captions")]
    pub fn draw_captions(&mut self, overlay: &mut crate::captions::CaptionOverlay, time: f64) {
        on_metal! {
            let (rw, rh) = (self.render_width, self.render_height);
            if let Some(m) = self.metal_path() {
                overlay.set_size(rw, rh);
                overlay.update(time);
                if overlay.is_visible() {
                    m.blend_overlay(overlay.rgba());
                }
                // Until Metal is confirmed wgpu holds the frame as well; give
                // it the captions too.
                if m.confirmed() {
                    return;
                }
            }
        }
        let (w, h) = (self.render_width, self.render_height);
        // Blend through an sRGB *view* of the target, not through its own view.
        //
        // Fixed-function blending on an sRGB attachment decodes the destination
        // to linear, mixes, and re-encodes; on a plain `Unorm` one it mixes the
        // stored bytes, which for a framebuffer holding shader-encoded colour
        // means mixing encodings rather than light. Half coverage of white on
        // black then lands on 128 where the light says 188, and antialiased text
        // reads thin on dark backgrounds.
        //
        // `RenderTarget::new` already declares both variants in `view_formats`,
        // so a view in the sRGB variant costs nothing and puts the blend in
        // linear for either target format. `Rgba16Float` has no sRGB variant and
        // needs none — it is linear throughout.
        let srgb = self.target.format.add_srgb_suffix();
        let view = if srgb == self.target.format {
            None
        } else {
            Some(
                self.target
                    .color_texture
                    .create_view(&wgpu::TextureViewDescriptor {
                        format: Some(srgb),
                        ..Default::default()
                    }),
            )
        };
        // Split the borrow: `renderer` and `target` are separate fields.
        let target_view = view.as_ref().unwrap_or(&self.target.color_view);
        self.renderer
            .draw_caption_overlay(overlay, time, w, h, target_view, srgb);
    }

    /// Render, blend the caption for `time` seconds on top, and read back RGBA8.
    ///
    /// This is the video-export entry point when you want the captions
    /// composited by the GPU rather than by
    /// [`CaptionPainter`](crate::captions::CaptionPainter) on the CPU. The
    /// result is the same; doing it here keeps the pixels on the GPU for one
    /// fewer pass over the frame.
    ///
    /// ```no_run
    /// # use threers::{HeadlessRenderer, Scene, PerspectiveCamera};
    /// # use threers::captions::{CaptionOverlay, CaptionTrack};
    /// # let mut hr = HeadlessRenderer::builder().size(640, 360).build().unwrap();
    /// # let mut scene = Scene::new();
    /// # let camera = PerspectiveCamera::new(50.0, 16.0 / 9.0, 0.1, 100.0);
    /// let mut overlay = CaptionOverlay::new(CaptionTrack::new().cue(0.0, 2.0, "Hi"))
    ///     .auto_scale(true);
    /// let rgba = hr.render_to_rgba_with_captions(&mut scene, &camera, &mut overlay, 1.0);
    /// # let _ = rgba;
    /// ```
    #[cfg(feature = "captions")]
    pub fn render_to_rgba_with_captions(
        &mut self,
        scene: &mut Scene,
        camera: &dyn Camera,
        overlay: &mut crate::captions::CaptionOverlay,
        time: f64,
    ) -> Vec<u8> {
        self.render(scene, camera);
        self.draw_captions(overlay, time);
        self.read_rgba()
    }

    /// Read the current target contents back as tightly-packed RGBA8, unpadding
    /// the 256-byte row alignment wgpu requires for texture→buffer copies.
    ///
    /// This blocks until the GPU has finished the frame. For a video export,
    /// prefer [`read_rgba_pipelined`](Self::read_rgba_pipelined), which lets the
    /// CPU build the next frame while this one is still being copied.
    ///
    /// With post passes on ([`set_bloom`](Self::set_bloom), SSAO, depth of
    /// field, film) and no supersampling, the frame comes back with them
    /// applied, as the Metal backend's does; they run where
    /// [`read_rgba_resolved`](Self::read_rgba_resolved) runs them. A
    /// supersampled target reads back raw here, at its full size.
    pub fn read_rgba(&mut self) -> Vec<u8> {
        on_metal! {
            if let Some(m) = self.metal_path() {
                return m.frame();
            }
        }
        if self.has_post() && self.config.supersample.max(1) == 1 {
            return self.read_rgba_resolved();
        }
        let p = self.queue_readback();
        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
        self.drain(p)
    }

    /// Render, then read back at the configured [`size`](HeadlessBuilder::size),
    /// averaging any [`supersample`](HeadlessBuilder::supersample) on the GPU.
    ///
    /// This is what you usually want when supersampling: `render_to_rgba` hands
    /// back the *oversized* frame and leaves the averaging to you, which means
    /// dragging `factor²` more bytes across the bus and then walking them on the
    /// CPU. At 1920×1080 with `supersample(2)` that walk costs 33 ms against
    /// 4.4 ms for the whole render — so it is done here in the render pass
    /// instead, and only the finished frame is copied back.
    ///
    /// With `supersample(1)` there is nothing to average and this is exactly
    /// [`render_to_rgba`](Self::render_to_rgba).
    ///
    /// ```no_run
    /// # use threers::{HeadlessRenderer, Scene, PerspectiveCamera};
    /// let mut hr = HeadlessRenderer::builder().size(1920, 1080).supersample(2).build().unwrap();
    /// # let mut scene = Scene::new();
    /// # let cam = PerspectiveCamera::new(50.0, 16.0 / 9.0, 0.1, 100.0);
    /// let rgba = hr.render_to_rgba_resolved(&mut scene, &cam); // 1920×1080
    /// # let _ = rgba;
    /// ```
    pub fn render_to_rgba_resolved(&mut self, scene: &mut Scene, camera: &dyn Camera) -> Vec<u8> {
        self.render(scene, camera);
        self.read_rgba_resolved()
    }

    /// Read the target back at the configured output size, averaging any
    /// supersample factor on the GPU. See
    /// [`render_to_rgba_resolved`](Self::render_to_rgba_resolved).
    pub fn read_rgba_resolved(&mut self) -> Vec<u8> {
        on_metal! {
            let factor = self.config.supersample.max(1);
            let (rw, rh) = (self.render_width, self.render_height);
            if let Some(m) = self.metal_path() {
                let raw = m.frame();
                return if factor > 1 {
                    crate::renderer::downsample::average_blocks_srgb(&raw, rw, rh, factor)
                } else {
                    raw
                };
            }
        }
        // Bloom, ambient occlusion and the film grade all live in the RGB pack,
        // which is a compute pass on its way to an encoder — so for a long time
        // asking for them and then reading RGBA got a frame with none of them
        // applied, and nothing said so. `set_bloom` returning quietly and doing
        // nothing is the worst shape a setting can have.
        //
        // Rather than grow a second implementation of the same composite, this
        // runs the one that exists and widens its output. That costs a pass over
        // the frame on the CPU, which against a GPU render is noise, and it
        // guarantees the two readbacks cannot drift apart because there is only
        // one of them.
        if self.has_post()
            && self.rgb_readback_supported()
            && let Some(rgb) = self.read_rgb_resolved_now()
        {
            return rgba_from_rgb(&rgb);
        }
        let Some((w, h)) = self.run_resolve() else {
            // Either there is nothing to average, or the GPU pass declined this
            // format/size. The size this returns is part of the contract, so in
            // the second case fall back rather than hand back an oversized frame.
            let raw = self.read_rgba();
            let factor = self.config.supersample.max(1);
            return if factor > 1 {
                let (rw, rh) = (self.render_width, self.render_height);
                crate::renderer::downsample::average_blocks_srgb(&raw, rw, rh, factor)
            } else {
                raw
            };
        };
        let p = self.queue_readback_from(true, w, h);
        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
        self.drain(p)
    }

    /// Record the averaging pass, building the downsampler on first use.
    ///
    /// `None` when there is nothing to average — no supersample, or a format the
    /// pass cannot render into — in which case the caller reads the target back
    /// as it stands.
    fn run_resolve(&mut self) -> Option<(u32, u32)> {
        if self.accum_ready {
            // The averaged frame is already sitting in the resolve target;
            // re-running the pass would replace it with the last sample.
            return self.resolve.as_ref().map(|ds| ds.size());
        }
        let ds = self.ensure_resolve()?;
        let size = ds.size();
        let ds = self.resolve.as_ref()?;
        let mut enc = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("threers headless resolve"),
            });
        ds.resolve(&mut enc);
        self.queue.submit(Some(enc.finish()));
        Some(size)
    }

    /// Build the downsampler if it is wanted and not built yet.
    ///
    /// `None` when `supersample` is 1, or when the pass declined the target's
    /// format — the two cases where the caller reads the target as it stands.
    fn ensure_resolve(&mut self) -> Option<&crate::renderer::Downsampler> {
        if self.config.supersample.max(1) < 2 {
            return None;
        }
        if self.resolve.is_none() {
            self.resolve = crate::renderer::Downsampler::with_filter(
                &self.device,
                &self.target.color_texture,
                self.config.supersample.max(1),
                self.config.downsample_filter,
            );
        }
        self.resolve.as_ref()
    }

    /// Queue this frame's readback and return the frame queued on the PREVIOUS
    /// call — `None` the first time. Finish the sequence with
    /// [`finish_readback`](Self::finish_readback).
    ///
    /// `read_rgba` submits a copy and immediately blocks on it, so the GPU is
    /// idle for as long as the CPU takes to build the next frame and the CPU is
    /// idle for as long as the GPU takes to draw. Handing back the previous
    /// frame instead overlaps the two: by the time it is asked for, the copy has
    /// usually already landed and the wait is zero.
    ///
    /// ```no_run
    /// # use threers::{HeadlessRenderer, Scene, PerspectiveCamera};
    /// # let mut hr = HeadlessRenderer::builder().size(64, 64).build().unwrap();
    /// # let mut scene = Scene::new();
    /// # let cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
    /// for _frame in 0..10 {
    ///     hr.render(&mut scene, &cam);
    ///     if let Some(rgba) = hr.read_rgba_pipelined() { let _ = rgba; }
    /// }
    /// if let Some(rgba) = hr.finish_readback() { let _ = rgba; }
    /// ```
    pub fn read_rgba_pipelined(&mut self) -> Option<Vec<u8>> {
        on_metal! {
            if let Some(m) = self.metal_path() {
                let frame = m.frame();
                return m.pipelined(frame);
            }
        }
        let next = self.queue_readback();
        let out = self.pending.take().map(|p| {
            // Poll rather than Wait: Wait blocks on everything submitted, which
            // now includes the copy queued one line above — that would serialise
            // exactly what this is here to overlap.
            loop {
                let _ = self.device.poll(wgpu::PollType::Poll);
                match p.rx.try_recv() {
                    Ok(_) => break,
                    Err(std::sync::mpsc::TryRecvError::Empty) => std::hint::spin_loop(),
                    Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
                }
            }
            self.take_pixels(p)
        });
        self.pending = Some(next);
        out
    }

    /// [`HeadlessRenderer::read_rgba_pipelined`] and [`HeadlessRenderer::read_rgba_resolved`] at once: average the
    /// supersample on the GPU, then hand back the PREVIOUS frame at output size.
    ///
    /// The two existing calls do not compose, and a renderer writing a long
    /// animation wants both. `read_rgba_resolved` averages on the GPU but blocks
    /// on its own copy, so the CPU idles through the draw and the GPU idles
    /// through the encode. `read_rgba_pipelined` overlaps them but reads the
    /// target as it stands — the *large* one — leaving the caller to average
    /// `factor²` samples per pixel on the CPU, which is the cost this module
    /// exists to avoid: 33 ms against 4.4 ms for the whole frame at 1080p.
    /// Reaching for it because it was the only pipelined option is an easy
    /// mistake and an expensive one.
    ///
    /// Returns frames sized `size`, not `size × factor`, and shrinks the copy
    /// by `factor²` because it starts from the small texture.
    ///
    /// Finish the sequence with [`finish_readback`](Self::finish_readback), as
    /// with the unresolved version.
    ///
    /// ```no_run
    /// # use threers::{HeadlessRenderer, Scene, PerspectiveCamera};
    /// let mut hr = HeadlessRenderer::builder().size(1920, 1080).supersample(2).build().unwrap();
    /// # let mut scene = Scene::new();
    /// # let cam = PerspectiveCamera::new(50.0, 16.0 / 9.0, 0.1, 100.0);
    /// for _frame in 0..10 {
    ///     hr.render(&mut scene, &cam);
    ///     // 1920×1080, averaged on the GPU, one frame behind.
    ///     if let Some(rgba) = hr.read_rgba_resolved_pipelined() { let _ = rgba; }
    /// }
    /// if let Some(rgba) = hr.finish_readback() { let _ = rgba; }
    /// ```
    pub fn read_rgba_resolved_pipelined(&mut self) -> Option<Vec<u8>> {
        on_metal! {
            if self.is_native_metal() {
                let frame = self.read_rgba_resolved();
                return self.metal_path().and_then(|m| m.pipelined(frame));
            }
        }
        let factor = self.config.supersample.max(1);
        let resolved = self.run_resolve();
        // The downsampler is built once and cached, so whether the GPU pass is
        // available does not change between frames; the frame handed back below
        // was queued the same way as the one queued here.
        let on_gpu = resolved.is_some();
        let next = match resolved {
            Some((w, h)) => self.queue_readback_from(true, w, h),
            None => self.queue_readback(),
        };
        let out = self.pending.take().map(|p| {
            // Poll rather than Wait, for the reason given on read_rgba_pipelined.
            loop {
                let _ = self.device.poll(wgpu::PollType::Poll);
                match p.rx.try_recv() {
                    Ok(_) => break,
                    Err(std::sync::mpsc::TryRecvError::Empty) => std::hint::spin_loop(),
                    Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
                }
            }
            let raw = self.take_pixels(p);
            // Only when the GPU declined the format or size. The output size is
            // part of the contract either way.
            if !on_gpu && factor > 1 {
                let (rw, rh) = (self.render_width, self.render_height);
                crate::renderer::downsample::average_blocks_srgb(&raw, rw, rh, factor)
            } else {
                raw
            }
        });
        self.pending = Some(next);
        out
    }

    /// Drain the last frame left in flight by
    /// [`read_rgba_pipelined`](Self::read_rgba_pipelined).
    pub fn finish_readback(&mut self) -> Option<Vec<u8>> {
        on_metal! {
            if let Some(m) = self.metal_path() {
                return m.finish();
            }
        }
        let p = self.pending.take()?;
        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
        Some(self.drain(p))
    }

    fn drain(&mut self, p: Pending) -> Vec<u8> {
        let _ = p.rx.recv();
        self.take_pixels(p)
    }

    /// Read a cube render target back as six linear-light RGBA faces.
    ///
    /// A cube rendered from a point in the scene is a reflection probe, and a
    /// probe is not usable as image-based lighting until it has been filtered
    /// per roughness: sampled raw, a surface at roughness 0.5 reflects a
    /// mirror-sharp environment, which looks worse than the crude static one it
    /// replaced. wgpu exposes a render target's cube view with a single mip, so
    /// there is nothing for a roughness-to-mip mapping to read.
    ///
    /// Reading it back is what makes the existing prefilter usable on it: the
    /// caller hands these faces to `PmremGenerator` and gets the same
    /// roughness-aware environment a static cube gets. A probe is small — six
    /// 48-pixel faces is 55 kB — so this costs far less than it sounds.
    ///
    /// Faces come back in cube order (+X, -X, +Y, -Y, +Z, -Z), decoded to
    /// LINEAR light: the target is usually sRGB, and lighting maths in an
    /// sRGB-encoded value is wrong in a way that looks merely "a bit dark".
    pub fn read_cube_faces(&self, rt: &crate::renderer::CubeRenderTarget) -> Option<[Vec<f32>; 6]> {
        let n = rt.side as usize;
        let bpp = 4usize;
        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
        let unpadded = n * bpp;
        let padded = unpadded.div_ceil(align) * align;
        let size = (padded * n) as u64;

        let srgb = matches!(
            rt.format,
            wgpu::TextureFormat::Rgba8UnormSrgb | wgpu::TextureFormat::Bgra8UnormSrgb
        );
        let bgra = matches!(
            rt.format,
            wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb
        );

        let buf = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("threers cube readback"),
            size,
            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let mut out: [Vec<f32>; 6] = std::array::from_fn(|_| Vec::new());
        for (face, slot) in out.iter_mut().enumerate() {
            let mut enc = self
                .device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("threers cube readback"),
                });
            enc.copy_texture_to_buffer(
                wgpu::TexelCopyTextureInfo {
                    texture: &rt.color_texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d {
                        x: 0,
                        y: 0,
                        z: face as u32,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::TexelCopyBufferInfo {
                    buffer: &buf,
                    layout: wgpu::TexelCopyBufferLayout {
                        offset: 0,
                        bytes_per_row: Some(padded as u32),
                        rows_per_image: Some(n as u32),
                    },
                },
                wgpu::Extent3d {
                    width: rt.side,
                    height: rt.side,
                    depth_or_array_layers: 1,
                },
            );
            self.queue.submit(Some(enc.finish()));
            let (tx, rx) = std::sync::mpsc::channel();
            buf.slice(..).map_async(wgpu::MapMode::Read, move |r| {
                let _ = tx.send(r);
            });
            let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
            if rx.recv().ok()?.is_err() {
                return None;
            }
            {
                let view = buf
                    .slice(..)
                    .get_mapped_range()
                    .expect("buffer range is mapped");
                let mut f = Vec::with_capacity(n * n * 4);
                for y in 0..n {
                    let row = &view[y * padded..y * padded + unpadded];
                    for x in 0..n {
                        let p = &row[x * 4..x * 4 + 4];
                        let (r, g, b) = if bgra {
                            (p[2], p[1], p[0])
                        } else {
                            (p[0], p[1], p[2])
                        };
                        for c in [r, g, b] {
                            let v = c as f32 / 255.0;
                            f.push(if srgb {
                                crate::utils::srgb::srgb_to_linear_f32(v)
                            } else {
                                v
                            });
                        }
                        f.push(1.0);
                    }
                }
                *slot = f;
            }
            buf.unmap();
        }
        Some(out)
    }

    /// Turn bloom on: `strength` scales what is added back, `threshold` is the
    /// linear luminance a pixel must exceed to bloom at all, and `radius`
    /// widens the blur.
    ///
    /// The composite lives in the RGB pack, where the frame is already being
    /// read by a compute shader on its way to an encoder, so it costs a sample
    /// rather than another pass over the picture.
    /// [`read_rgba_resolved`](Self::read_rgba_resolved) runs that same pack and
    /// widens its output, so bloom applies to both readbacks. It used to apply
    /// to only one of them, silently.
    pub fn set_bloom(&mut self, strength: f32, threshold: f32, radius: f32) {
        on_metal! {
            if let Some(m) = self.metal_path() {
                m.set_bloom(strength, threshold, radius);
            }
        }
        let cfg = (strength, threshold, radius);
        if self.bloom_cfg != Some(cfg) {
            self.bloom_cfg = Some(cfg);
            self.bloom = None;
            self.rgb_pack = None;
        }
    }

    /// Turn depth of field on.
    ///
    /// `focus` is the distance from the camera that stays sharp, in world
    /// units; `range` is how far either side of it the image takes to reach
    /// full blur; `radius` is that full blur in pixels. Pass a radius of 0 to
    /// turn it off.
    ///
    /// The camera's near and far planes are taken from the frame itself rather
    /// than from the caller. They used to be arguments, with a note that
    /// passing the wrong ones was *"wrong silently"* — which it is: the depth
    /// linearises at the wrong distances and the result still looks like a
    /// depth of field, just one focused somewhere else. The renderer has known
    /// them all along.
    ///
    /// The gather is a golden-angle spiral weighted so a sharp foreground
    /// cannot smear over a blurred background, with the tap count scaled to the
    /// area being gathered. Anything at the far plane counts as fully
    /// defocused, so a backdrop with no geometry in it falls away the way a
    /// real one does rather than staying inexplicably sharp.
    pub fn set_depth_of_field(&mut self, focus: f32, range: f32, radius: f32) {
        self.leave_metal("set_depth_of_field");
        let cfg = (focus, range, radius);
        if radius <= 0.0 {
            if self.dof_cfg.is_some() {
                self.dof_cfg = None;
                self.rgb_pack = None;
            }
            return;
        }
        // Only the uniform changes, so the pack does not have to be rebuilt —
        // but it does have to exist, and it is built lazily.
        self.dof_cfg = Some(cfg);
    }

    /// Turn ambient occlusion on. `radius` is in world units.
    ///
    /// The clip planes and the lens come from the frame, for the same reason
    /// they do in [`set_depth_of_field`](Self::set_depth_of_field): they are
    /// properties of the camera, the renderer already has them, and a caller
    /// who gets them wrong gets occlusion computed at the wrong distances with
    /// nothing to say so.
    ///
    /// Cheap to call every frame: only a change of strength or radius rebuilds
    /// anything, and a new depth range is a buffer write.
    pub fn set_ssao(&mut self, strength: f32, radius: f32) {
        on_metal! {
            if let Some(m) = self.metal_path() {
                m.set_ssao(strength, radius);
            }
        }
        let rebuild = self
            .ssao_cfg
            .map(|(s, r)| s != strength || r != radius)
            .unwrap_or(true);
        self.ssao_cfg = Some((strength, radius));
        if rebuild {
            self.ssao = None;
            self.rgb_pack = None;
        }
        // The range is refreshed after the frame is drawn, not here. This is
        // called before `render`, so the camera the renderer remembers is the
        // *previous* one — and on the first frame there is no previous one.
    }

    /// Set an RGBA overlay composited over the top-left of every frame on the
    /// RGB readback path — a masthead, a lower third.
    ///
    /// Doing this here rather than after readback is what allows the frame to
    /// be handed to an encoder without copying it: a CPU composite needs a
    /// writable frame, and the frame the GPU wrote is mapped read-only.
    pub fn set_overlay(&mut self, width: u32, height: u32, rgba: &[u8]) {
        self.leave_metal("set_overlay");
        if width == 0 || height == 0 || rgba.len() < (width * height * 4) as usize {
            self.overlay = None;
            self.rgb_pack = None;
            return;
        }
        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
            label: Some("threers headless overlay"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        self.queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &tex,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            rgba,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(width * 4),
                rows_per_image: Some(height),
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        self.overlay = Some(tex);
        self.rgb_pack = None;
    }

    /// Camera motion blur on the RGB readback path. `shutter` is the fraction
    /// of the frame interval the shutter is open — 0.5 is the 180-degree
    /// convention, 0 is off.
    pub fn set_motion_blur(&mut self, shutter: f32) {
        self.leave_metal("set_motion_blur");
        if self.shutter != shutter {
            self.shutter = shutter;
            self.rgb_pack = None;
        }
    }

    /// Vignette and grain on the RGB readback path -- the two things that read
    /// as "photograph" rather than "render".
    ///
    /// They are applied in the pack pass, which already touches every pixel, and
    /// BEFORE the overlay, so a masthead composited on top stays clean. Both at
    /// zero is bit-for-bit the frame without them.
    ///
    /// The seed advances itself per packed frame, so grain moves.
    pub fn set_film_grade(&mut self, vignette: f32, grain: f32) {
        on_metal! {
            if let Some(m) = self.metal_path() {
                m.set_film_grade(vignette, grain);
            }
        }
        if self.film.vignette != vignette || self.film.grain != grain {
            self.film.vignette = vignette;
            self.film.grain = grain;
            self.rgb_pack = None;
        }
    }

    /// Whether [`read_rgb_resolved_pipelined`](Self::read_rgb_resolved_pipelined)
    /// can serve this target. Ask once, before the first frame: the two
    /// readbacks share a pipeline slot and cannot be alternated.
    /// Whether any of the post passes that live in the RGB pack are configured.
    fn has_post(&self) -> bool {
        self.bloom_cfg.is_some()
            || self.ssao_cfg.is_some()
            || self.dof_cfg.is_some()
            || self.film.vignette > 0.0
            || self.film.grain > 0.0
            || self.shutter > 0.0
    }

    /// One RGB frame, post applied, read back synchronously. `None` when the
    /// pack declined this target — a format or a size it cannot serve — in
    /// which case the caller falls back to the plain copy.
    ///
    /// Queues and drains in the same call, so it leaves the pipelined queue as
    /// it found it and cannot interleave with `read_rgb_frame`.
    fn read_rgb_resolved_now(&mut self) -> Option<Vec<u8>> {
        self.queue_rgb_readback()?;
        let pending = self.rgb_queue.pop_front()?;
        self.await_pending(&pending);
        Some(self.take_pixels(pending))
    }

    pub fn rgb_readback_supported(&self) -> bool {
        matches!(
            self.target.color_texture.format(),
            wgpu::TextureFormat::Rgba8Unorm
                | wgpu::TextureFormat::Rgba8UnormSrgb
                | wgpu::TextureFormat::Bgra8Unorm
                | wgpu::TextureFormat::Bgra8UnormSrgb
        )
    }
}

/// Three bytes a pixel to four, with an opaque alpha.
///
/// The post composite packs to RGB because that is what a video encoder wants;
/// a caller asking for RGBA gets the same pixels widened rather than a second
/// composite written to produce them.
/// Drop the alpha: the RGB readbacks' layout, from an RGBA frame.
#[allow(dead_code)] // only the Metal path builds one from RGBA
fn rgb_from_rgba(rgba: &[u8]) -> Vec<u8> {
    rgba.as_chunks::<4>()
        .0
        .iter()
        .flat_map(|p| [p[0], p[1], p[2]])
        .collect()
}

fn rgba_from_rgb(rgb: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(rgb.len() / 3 * 4);
    for p in rgb.as_chunks::<3>().0 {
        out.extend_from_slice(&[p[0], p[1], p[2], 255]);
    }
    out
}

/// A frame still sitting in the buffer the GPU wrote it to.
///
/// The ordinary readback copies the mapped range into a `Vec` and hands that
/// on. At 8K that is 99.5 MB memcpy'd per frame for no reason: the bytes are
/// already in memory the CPU can read, and the only thing done with them is a
/// write to a pipe, which reads them once more. Handing the buffer over instead
/// removes a full-frame copy from every frame.
///
/// The buffer belongs to the renderer's pool and MUST come back — call
/// [`HeadlessRenderer::recycle`] when the bytes have been consumed, or the pool
/// allocates a fresh 99.5 MB every frame instead of reusing four.
///
/// On the native Metal backend the frame has already been read into memory
/// of its own, and this holds those bytes; recycling it just drops them.
pub struct MappedFrame {
    frame: Frame,
    len: usize,
}

enum Frame {
    Mapped(wgpu::Buffer),
    #[cfg_attr(not(metal_backend), allow(dead_code))]
    Read(Vec<u8>),
}

impl MappedFrame {
    #[cfg_attr(not(metal_backend), allow(dead_code))]
    fn read(bytes: Vec<u8>) -> Self {
        Self {
            len: bytes.len(),
            frame: Frame::Read(bytes),
        }
    }

    /// The frame's bytes. Valid until this is recycled.
    pub fn bytes(&self) -> crate::marks::gpu::BufferView<'_> {
        match &self.frame {
            Frame::Mapped(buffer) => crate::marks::gpu::BufferView::Wgpu(
                buffer
                    .slice(..self.len as u64)
                    .get_mapped_range()
                    .expect("buffer range is mapped"),
            ),
            Frame::Read(bytes) => crate::marks::gpu::BufferView::Metal(bytes),
        }
    }

    pub fn len(&self) -> usize {
        self.len
    }

    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Give the buffer back. Unmaps first, which is what makes it reusable.
    ///
    /// # Panics
    ///
    /// For a frame from the native Metal backend, which has no wgpu buffer;
    /// [`HeadlessRenderer::recycle`] takes either.
    pub fn into_buffer(self) -> wgpu::Buffer {
        match self.frame {
            Frame::Mapped(buffer) => {
                buffer.unmap();
                buffer
            }
            Frame::Read(_) => panic!("a frame read on the native Metal backend has no wgpu buffer"),
        }
    }
}

impl HeadlessRenderer {
    /// Like [`read_rgb_resolved_pipelined`](Self::read_rgb_resolved_pipelined),
    /// but without copying the frame out of the buffer the GPU wrote it to.
    ///
    /// The returned [`MappedFrame`] must be handed back with
    /// [`recycle`](Self::recycle) once its bytes have been used.
    pub fn read_rgb_frame(&mut self) -> Option<MappedFrame> {
        on_metal! {
            if self.is_native_metal() {
                return self.read_rgb_resolved_pipelined().map(MappedFrame::read);
            }
        }
        self.queue_rgb_readback()?;
        if self.rgb_queue.len() <= self.read_ahead {
            return None;
        }
        self.drain_rgb_frame()
    }

    /// Take the oldest readback in flight without queuing another.
    ///
    /// The tail of a sequence: `read_ahead` frames are still in the queue when
    /// the last one has been drawn, and every one of them is a frame the caller
    /// asked for. Call until it returns `None`.
    pub fn drain_rgb_frame(&mut self) -> Option<MappedFrame> {
        on_metal! {
            if let Some(m) = self.metal_path() {
                return m.finish().map(MappedFrame::read);
            }
        }
        let p = self.rgb_queue.pop_front()?;
        self.await_pending(&p);
        Some(MappedFrame {
            frame: Frame::Mapped(p.buffer),
            len: p.unpadded as usize,
        })
    }

    /// As [`drain_rgb_frame`](Self::drain_rgb_frame), copying the bytes out.
    pub fn drain_rgb_pixels(&mut self) -> Option<Vec<u8>> {
        on_metal! {
            if let Some(m) = self.metal_path() {
                return m.finish();
            }
        }
        let p = self.rgb_queue.pop_front()?;
        self.await_pending(&p);
        Some(self.take_pixels(p))
    }

    /// Return a buffer taken by [`read_rgb_frame`](Self::read_rgb_frame).
    pub fn recycle(&mut self, frame: MappedFrame) {
        if let Frame::Mapped(_) = frame.frame {
            self.spare.push(frame.into_buffer());
        }
    }
}

impl HeadlessRenderer {
    /// Like [`read_rgba_resolved_pipelined`](Self::read_rgba_resolved_pipelined),
    /// but the frame comes back as tightly-packed RGB — three bytes a pixel,
    /// no alpha, no row padding.
    ///
    /// The strip happens in a compute pass on the frame the GPU already holds,
    /// so a quarter less data crosses the readback and the CPU never touches
    /// the pixels twice. Doing the same pack on the CPU costs far more than the
    /// encoder saves; the numbers are in [`rgb_pack`](crate::renderer::rgb_pack).
    ///
    /// Returns `None` if the colour format cannot be packed, or if
    /// supersampling is on but the GPU downsampler is unavailable — in either
    /// case the caller should stay on the RGBA path. Decide once, before the
    /// sequence starts: switching mid-stream would drop the frame in flight.
    /// Queue this frame's post passes and readback, leaving the PREVIOUS
    /// frame in `self.pending` for a caller to take. Shared by the copying and
    /// zero-copy readbacks so the two cannot drift apart.
    fn queue_rgb_readback(&mut self) -> Option<usize> {
        let factor = self.config.supersample.max(1);
        let resolved = self.run_resolve();
        if factor > 1 && resolved.is_none() {
            return None;
        }
        let (w, h) = resolved.unwrap_or((self.render_width, self.render_height));

        // Rebuild when the target resizes; the bind groups hold views of it.
        if self.rgb_pack.as_ref().map(|p| p.size()) != Some((w, h))
            || self.bloom.as_ref().map(|b| b.src_size()) != self.bloom_cfg.map(|_| (w, h))
            || (self.ssao_cfg.is_some() && self.ssao.is_none())
        {
            let src: &wgpu::Texture = match (resolved.is_some(), self.resolve.as_ref()) {
                (true, Some(ds)) => ds.texture(),
                _ => &self.target.color_texture,
            };
            // Raw pointer dance avoided: build bloom first, then the pack that
            // borrows its view, and only then store both.
            let bloom = self.bloom_cfg.and_then(|(_, threshold, radius)| {
                crate::renderer::bloom::Bloom::new(&self.device, src, threshold, radius)
            });
            let strength = self.bloom_cfg.map(|c| c.0).unwrap_or(0.0);
            // Whichever depth buffer this frame was actually drawn into.
            // `render` branches: with MSAA it takes a surface-style path and
            // writes the renderer's own depth, without it `render_to` writes
            // the target's. Occlusion built on the other one reads an empty
            // buffer and produces a uniformly white factor — which looks
            // exactly like "SSAO is on and subtle", and is why turning it on
            // changed nothing at all on the default, non-MSAA path.
            let depth_src: &wgpu::Texture = if self.renderer.msaa() > 1 {
                self.renderer.depth_texture()
            } else {
                &self.target.depth_texture
            };
            let (near, far) = self.renderer.camera_planes();
            let (tan_half_fov, aspect) = self.renderer.camera_lens();
            let ssao = self.ssao_cfg.and_then(|(strength, radius)| {
                let depth = depth_src;
                crate::renderer::ssao::Ssao::new(
                    &self.device,
                    depth,
                    near,
                    far,
                    radius,
                    strength,
                    tan_half_fov,
                    aspect,
                )
            });
            let (inv_vp, prev_vp) = self.renderer.reprojection();
            self.rgb_pack = crate::renderer::rgb_pack::RgbPack::with_post_film(
                &self.device,
                src,
                bloom.as_ref().map(|b| b.view()),
                strength,
                ssao.as_ref().map(|s| s.view()),
                Some(depth_src),
                inv_vp,
                prev_vp,
                self.shutter,
                self.overlay.as_ref(),
                self.film,
            );
            self.bloom = bloom;
            self.ssao = ssao;
        }
        let pack = self.rgb_pack.as_ref()?;
        // Tick the grain so it moves frame to frame. Free when grain is off:
        // the shader branches out on it either way, and this is eight bytes.
        if self.film.grain > 0.0 {
            self.film.seed += 1.0;
            pack.set_grain_seed(&self.queue, self.film.seed);
        }
        let len = pack.len();
        // buffer_to_buffer copies must be a whole number of words; the few
        // bytes of slack past `len` are the 4-pixel group padding, trimmed by
        // `take_pixels` because `unpadded` states the honest length.
        let copy = len.div_ceil(4) * 4;

        let buffer = match self.spare.iter().position(|b| b.size() == copy as u64) {
            Some(i) => self.spare.swap_remove(i),
            None => {
                self.spare.clear();
                self.device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("threers headless rgb readback"),
                    size: copy as u64,
                    usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
                    mapped_at_creation: false,
                })
            }
        };
        let mut enc = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("threers headless rgb readback"),
            });
        let (near, far) = self.renderer.camera_planes();
        if let Some((focus, range, radius)) = self.dof_cfg {
            pack.set_dof(&self.queue, focus, range, radius, near, far);
        }
        // Depth of field, motion blur and occlusion all read the frame's
        // depth, which `set_reversed_z` stores reversed.
        let reversed = self.renderer.reversed_z();
        pack.set_reversed_depth(&self.queue, reversed);
        if let Some(a) = self.ssao.as_ref() {
            a.set_reversed_depth(&self.queue, reversed);
        }
        // Every frame, from the camera that actually drew it: the clip planes
        // and the lens can both change between frames, and occlusion built on
        // last frame's numbers is wrong in a way nothing reports.
        if let (Some((strength, radius)), Some(a)) = (self.ssao_cfg, self.ssao.as_ref()) {
            let (tan_half_fov, aspect) = self.renderer.camera_lens();
            a.set_range(
                &self.queue,
                near,
                far,
                radius,
                strength,
                tan_half_fov,
                aspect,
            );
        }
        // This frame's reprojection, before anything samples it.
        if self.shutter > 0.0 {
            let (inv_vp, prev_vp) = self.renderer.reprojection();
            pack.set_reprojection(&self.queue, inv_vp, prev_vp);
        }
        // Bloom first: the pack reads its output.
        if let Some(b) = self.bloom.as_ref() {
            b.record(&mut enc);
        }
        if let Some(a) = self.ssao.as_ref() {
            a.record(&mut enc);
        }
        pack.pack(&mut enc);
        enc.copy_buffer_to_buffer(pack.buffer(), 0, &buffer, 0, copy as u64);
        self.queue.submit(Some(enc.finish()));

        let (tx, rx) = std::sync::mpsc::channel();
        buffer.slice(..).map_async(wgpu::MapMode::Read, move |r| {
            let _ = tx.send(r);
        });
        // One linear "row": `take_pixels` hands back exactly `unpadded` bytes.
        let next = Pending {
            // A packed byte stream, not an image: unpacked verbatim.
            format: wgpu::TextureFormat::Rgba8Unorm,
            buffer,
            rx,
            padded: copy as u32,
            unpadded: len as u32,
            height: 1,
        };

        // Queued, not taken: the caller drains the OLDEST once enough are in
        // flight. `pending` still gets it so `finish_readback` keeps working
        // for callers that never touch the queue.
        self.rgb_queue.push_back(next);
        Some(len)
    }

    /// Copying readback: the frame comes back as a `Vec`.
    pub fn read_rgb_resolved_pipelined(&mut self) -> Option<Vec<u8>> {
        on_metal! {
            if self.is_native_metal() {
                let frame = rgb_from_rgba(&self.read_rgba_resolved());
                return self.metal_path().and_then(|m| m.pipelined(frame));
            }
        }
        self.queue_rgb_readback()?;
        if self.rgb_queue.len() <= self.read_ahead {
            return None;
        }
        self.drain_rgb_pixels()
    }

    fn await_pending(&self, p: &Pending) {
        loop {
            let _ = self.device.poll(wgpu::PollType::Poll);
            match p.rx.try_recv() {
                Ok(_) => break,
                Err(std::sync::mpsc::TryRecvError::Empty) => std::hint::spin_loop(),
                Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
            }
        }
    }

    fn take_pixels(&mut self, p: Pending) -> Vec<u8> {
        let data = p
            .buffer
            .slice(..)
            .get_mapped_range()
            .expect("buffer range is mapped");
        let (padded, unpadded, h) = (p.padded as usize, p.unpadded as usize, p.height as usize);
        let pixels = if padded == unpadded {
            // The common case at sane widths — 1920 * 4 is already 256-aligned —
            // and one memcpy instead of `height` of them.
            data.to_vec()
        } else {
            let mut v = Vec::with_capacity(unpadded * h);
            for row in data.chunks(padded) {
                v.extend_from_slice(&row[..unpadded]);
            }
            v
        };
        drop(data);
        p.buffer.unmap();
        self.spare.push(p.buffer);
        // These accessors are documented to hand back RGBA8, so an HDR target
        // is tone-neutrally encoded here rather than leaking half-floats to a
        // caller that is about to write a PNG.
        if p.format == wgpu::TextureFormat::Rgba16Float {
            return pixels
                .as_chunks::<8>()
                .0
                .iter()
                .flat_map(|px| {
                    let h = |i: usize| half_to_f32(u16::from_le_bytes([px[i], px[i + 1]]));
                    [
                        encode_srgb_byte(h(0)),
                        encode_srgb_byte(h(2)),
                        encode_srgb_byte(h(4)),
                        (h(6).clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
                    ]
                })
                .collect();
        }
        pixels
    }

    fn queue_readback(&mut self) -> Pending {
        let (w, h) = (self.render_width, self.render_height);
        self.queue_readback_from(false, w, h)
    }

    /// Copy the render target — or, when `resolved`, the downsampler's output —
    /// into a mapped buffer.
    ///
    /// Takes a flag rather than a `&wgpu::Texture` so the source can be borrowed
    /// from `self` at the point of use; the size is passed because the caller
    /// already knows it and the two must agree.
    fn queue_readback_from(&mut self, resolved: bool, w: u32, h: u32) -> Pending {
        let source_format = match (resolved, self.resolve.as_ref()) {
            (true, Some(ds)) => ds.texture().format(),
            _ => self.target.color_texture.format(),
        };
        let unpadded = w * target_bpp(source_format);
        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
        let padded = unpadded.div_ceil(align) * align;
        let size = (padded * h) as u64;

        let buffer = match self.spare.iter().position(|b| b.size() == size) {
            Some(i) => self.spare.swap_remove(i),
            None => {
                self.spare.clear(); // the target resized; the old ones are useless
                self.device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("threers headless readback"),
                    size,
                    usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
                    mapped_at_creation: false,
                })
            }
        };
        let mut enc = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("threers headless readback"),
            });
        let source = match (resolved, self.resolve.as_ref()) {
            (true, Some(ds)) => ds.texture(),
            _ => &self.target.color_texture,
        };
        enc.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: source,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(padded),
                    rows_per_image: Some(h),
                },
            },
            wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
        );
        self.queue.submit(Some(enc.finish()));

        let (tx, rx) = std::sync::mpsc::channel();
        buffer.slice(..).map_async(wgpu::MapMode::Read, move |r| {
            let _ = tx.send(r);
        });
        Pending {
            buffer,
            rx,
            padded,
            unpadded,
            height: h,
            format: source_format,
        }
    }
}

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

    #[test]
    fn an_hdr_target_is_eight_bytes_a_pixel() {
        // The readback assumed four, and a `Rgba16Float` frame failed
        // validation rather than coming back wrong, which at least was loud.
        assert_eq!(target_bpp(wgpu::TextureFormat::Rgba16Float), 8);
        assert_eq!(target_bpp(wgpu::TextureFormat::Rgba8UnormSrgb), 4);
        assert_eq!(target_bpp(wgpu::TextureFormat::Bgra8Unorm), 4);
    }

    #[test]
    fn halves_decode_at_the_anchors() {
        assert_eq!(half_to_f32(0x0000), 0.0);
        assert_eq!(half_to_f32(0x3c00), 1.0);
        assert_eq!(half_to_f32(0x3800), 0.5);
        assert_eq!(half_to_f32(0xbc00), -1.0);
        // Subnormals are the branch worth pinning: 0x0001 is the smallest.
        assert!((half_to_f32(0x0001) - 5.96e-8).abs() < 1e-9);
    }

    #[test]
    fn srgb_encoding_hits_the_known_anchors() {
        assert_eq!(encode_srgb_byte(0.0), 0);
        assert_eq!(encode_srgb_byte(1.0), 255);
        assert_eq!(encode_srgb_byte(0.5), 188);
        // Out of range on either side is clamped, not wrapped.
        assert_eq!(encode_srgb_byte(-1.0), 0);
        assert_eq!(encode_srgb_byte(4.0), 255);
    }
}