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
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
//! Data-driven marks: points, lines, arcs, instanced shapes, text labels and
//! density fields, drawn from columns of per-instance data.
//!
//! The scene graph is the right model for a few hundred objects, each with a
//! material and a transform. It is the wrong one for a million rows of a
//! table, where every row is drawn the same way and differs only in its data.
//! A *mark* is that second model: one draw for the whole layer, with each
//! property — position, radius, colour — read from its own
//! [`Column`] of per-instance data.
//!
//! | | |
//! |---|---|
//! | [`PointMarks`] | Circles sized in pixels or world units, with strokes |
//! | [`SegmentMarks`] | Wide lines, polylines and arcs, in pixels or world units |
//! | [`ShapeMarks`] | Any geometry, instanced — extruded columns, 3D glyphs |
//! | [`PolygonMarks`] | Filled and extruded polygons with holes, many to a draw |
//! | [`TextLabels`] | Camera-facing text anchored in the world, with collision culling (`captions` feature) |
//! | [`DensityMarks`] | Kernels summed into a field and mapped through a colour ramp |
//!
//! Every mark kind shares the same machinery:
//!
//! - **High precision.** Positions are `f64` and drawn relative to an
//!   [`Origin`] — see [`precision`].
//! - **Hooks.** [`ShaderHooks`] splice WGSL into the vertex and colour stages,
//!   which is how filtering on the GPU works ([`ShaderHooks::range_filter`]).
//! - **Picking.** [`MarkRenderer::pick`] draws instance ids and reads back the
//!   pixel under the cursor, without blocking a browser's thread.
//! - **WebGL2.** Instanced vertex buffers and render passes only; nothing
//!   needs compute or storage buffers.
//!
//! Marks draw *over* a frame the [`Renderer`](crate::Renderer) has already
//! drawn, depth-tested against it, so they sit correctly among meshes:
//!
//! ```no_run
//! use threers::marks::{MarkRenderer, MarkTarget, MarkView, Origin, PointMarks, Mark};
//! # fn frame(renderer: &mut threers::Renderer, scene: &mut threers::Scene,
//! #          camera: &threers::PerspectiveCamera, frame_view: &wgpu::TextureView) {
//! let device = renderer.device_arc();
//! let queue = renderer.queue_arc();
//! let mut marks = MarkRenderer::new(&device);
//! let mut points = PointMarks::new();
//! points.set_positions(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]);
//! points.set_colors(&[[255, 80, 0, 255], [0, 160, 255, 255]]);
//! points.style_mut().size_scale = 6.0;
//!
//! renderer.render(scene, camera, frame_view, false);
//! let view = MarkView::new(camera, Origin::ZERO, renderer.drawing_buffer_size());
//! let target = MarkTarget::over_frame(renderer, frame_view);
//! marks.draw(&device, &queue, &target, &view, &mut [&mut points]);
//! # }
//! ```

mod atlas;
mod clear;
mod collision;
mod columns;
mod density;
pub mod geo;
pub mod geojson;
pub mod gpu;
#[cfg(metal_backend)]
mod gpu_metal;
mod hooks;
mod images;
#[cfg(feature = "captions")]
mod labels;
mod lines;
mod map_view;
#[cfg(feature = "captions")]
mod msdf;
mod picking;
mod points;
mod polygon_mesh;
mod polygons;
/// Double precision on the GPU; lives in [`crate::math`], since it needs no GPU.
pub use crate::math::precision;
mod segments;
pub(crate) mod shader;
mod shapes;
mod sprites;

pub use atlas::{AtlasError, AtlasRect, SharedAtlas, TextureAtlas};
pub use collision::{CollisionIndex, SharedCollision, SharedVisibility};
pub use columns::{Column, ColumnFormat};
pub use density::DensityMarks;
pub use hooks::{transition_offsets, ShaderHooks};
pub use images::{ImageMarks, ImageQuad};
#[cfg(feature = "captions")]
pub mod binning;
// Gated with the modules they re-export: `binning` and `labels` are both behind
// `captions`, so an ungated `pub use` breaks every build without that feature — which is
// how the browser target is built.
#[cfg(feature = "captions")]
pub use binning::{BinRequest, ScreenBinner, ScreenBins};
#[cfg(feature = "captions")]
pub use labels::{GlyphField, LabelAnchor, LabelBackground, LabelIcon, TextLabel, TextLabels};
pub use lines::LineMarks;
pub use map_view::{MapFrame, MapView};
pub use picking::{PickHit, PickRectRequest, PickRequest};
pub use points::PointMarks;
pub use polygon_mesh::PolygonMesh;
pub use polygons::{
    PatternFrame, PolygonFeature, PolygonMarks, PolygonPattern, ProceduralFrame, ProceduralShape,
};
pub use precision::{split_f64, split_f64x3, Origin};
pub use segments::{ArcProfile, DashMode, LineCap, LineJoin, PathMesh, SegmentMarks};
pub use shader::{CustomShader, MarkKind, PREAMBLE, SWIFTSHADER_SAMPLING};
pub use shapes::ShapeMarks;

pub use sprites::{SpriteBox, SpriteMarks, SpriteMode, SpriteSdf};

use std::collections::HashMap;

/// The depth buffer format marks test against — the renderer's.
pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;

/// How the camera sees the marks: the projection, the viewport and the origin.
#[derive(Debug, Clone, Copy)]
pub struct MarkView {
    /// Projection × view, in origin-relative coordinates.
    pub view_proj: [f32; 16],
    /// The projection's `[1][1]` — what turns world size into pixels.
    pub projection_scale: f32,
    /// Viewport size in pixels.
    pub viewport: (u32, u32),
    pub origin: Origin,
    /// Direction *towards* the light, for [`ShapeMarks`]. Normalised on use.
    pub light_direction: [f32; 3],
    /// The camera, origin-relative: its position with `w = 1` for a
    /// perspective view, or the direction towards it with `w = 0` for an
    /// orthographic one. Used by [`MarkStyle::depth_lift`].
    pub eye: [f32; 4],
    /// The scene's tone mapping and exposure, for layers with
    /// [`MarkStyle::tone_mapped`] set. [`from_renderer`](Self::from_renderer)
    /// copies the renderer's.
    pub tone_mapping: (crate::ToneMapping, f32),
    /// The depth buffer is reversed
    /// ([`Renderer::set_reversed_z`](crate::Renderer::set_reversed_z)):
    /// `view_proj` maps the near plane to 1, and marks test with `Greater`.
    /// [`from_renderer`](Self::from_renderer) sets both.
    pub reversed_z: bool,
    /// Clip `w` at the focal plane — the view's look-at distance — for
    /// layers with [`MarkStyle::focal_pixels`]. 0 when the view has none.
    pub focal_distance: f32,
    /// Clip `w` at which a line facing the camera that passes behind it is
    /// cut (deck.gl's `clipLine` epsilon, 0.001 of its own units).
    pub clip_epsilon: f32,
    /// Vertices snapped to `steps` positions a pixel, in the target's window
    /// coordinates, before rasterizing — a software rasterizer's fixed-point
    /// precision (SwiftShader's sixteen), coarser than a GPU's — and then
    /// moved by `bias` pixels. SwiftShader is matched exactly by sixteen
    /// steps, rounded half to even, no bias, with [`flip_y`](Self::flip_y)
    /// for its tie-breaking. `None`: the GPU's own.
    pub subpixel_snap: Option<(f32, [f32; 2])>,
    /// Draw upside down: clip y negated as each vertex's last step, after
    /// the snap. A rasterizer breaks ties (an edge through a pixel's
    /// centre) by its own top-left rule; drawn flipped, that rule acts as a
    /// bottom-left one on the image — as GL drawn by ANGLE on Vulkan (and so
    /// SwiftShader) breaks them. Whoever reads the target reverses its rows.
    pub flip_y: bool,
    /// Sample atlases (sprites, glyphs, fill patterns) as Chromium's
    /// SwiftShader does, bit for bit — its own filtering, mip selection and
    /// mip blend, from texel loads — instead of the GPU's sampler, whose
    /// weights are coarser. For comparing images with WebGL's.
    pub swiftshader_sampling: bool,
    /// Depth as Chromium's SwiftShader computes it: each triangle's plane
    /// from its vertices as rasterized, evaluated per fragment in float32
    /// (written as the fragment's depth), rather than the GPU's own
    /// interpolation, whose lower precision settles near-ties between
    /// coplanar shapes differently. Marks that support it: sprites.
    pub swiftshader_depth: bool,
    /// The scene's lights, for layers lit by them ([`Lighting::scene`]).
    pub scene_lights: Option<SceneLights>,
}

/// A point light: absolute world position, colour, and attenuation
/// (constant, linear, quadratic in world units).
pub type PointLight = ([f64; 3], [f32; 3], [f32; 3]);

/// Lights for a whole view — deck.gl's `LightingEffect` — that layers with
/// [`Lighting::scene`] shade by, per pixel. Colours are colour × intensity,
/// each channel 0 to 1 (more for bright lights).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct SceneLights {
    pub ambient: [f32; 3],
    /// Up to four: absolute world position, colour, and attenuation
    /// (constant, linear, quadratic in world units).
    pub points: [Option<PointLight>; 4],
    /// Up to four: the direction the light travels, world space, and colour.
    pub directional: [Option<([f32; 3], [f32; 3])>; 4],
    /// A shadow map to darken layers with
    /// [`MarkStyle::receive_shadows`] by (its texture given by
    /// [`MarkRenderer::set_shadow_map`]).
    pub shadow: Option<SceneShadow>,
}

/// deck.gl's shadow: where the shadow map was drawn from and the colour
/// shadows take.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SceneShadow {
    /// Absolute world position to the light's clip space, column-major,
    /// GL depth (−1 to 1): what [`MarkRenderer::set_shadow_pass`] draws
    /// depth by, packed into RGBA as deck.gl packs it.
    pub matrix: [f64; 16],
    /// The shadows' colour (sRGB, 0 to 1) and strength.
    pub color: [f32; 4],
}

impl MarkView {
    /// The view through `camera`, whose pose is in coordinates relative to
    /// `origin`.
    pub fn new(camera: &dyn crate::Camera, origin: Origin, viewport: (u32, u32)) -> Self {
        let proj = camera.projection_matrix();
        let view = camera.view_matrix();
        let vp = proj.multiply(&view);
        // The camera's world transform is the view's inverse: its translation
        // is the eye, its +Z the direction back towards the camera.
        let world = view.invert().elements;
        let eye = if proj.elements[15].abs() > 0.5 {
            [world[8], world[9], world[10], 0.0]
        } else {
            [world[12], world[13], world[14], 1.0]
        };
        Self {
            view_proj: vp.elements,
            projection_scale: proj.elements[5],
            viewport: (viewport.0.max(1), viewport.1.max(1)),
            origin,
            light_direction: [0.4, 0.8, 0.45],
            eye,
            tone_mapping: (crate::ToneMapping::None, 1.0),
            reversed_z: false,
            focal_distance: 0.0,
            clip_epsilon: 0.001,
            subpixel_snap: None,
            flip_y: false,
            swiftshader_sampling: false,
            swiftshader_depth: false,
            scene_lights: None,
        }
    }

    /// Set [`scene_lights`](Self::scene_lights).
    pub fn with_scene_lights(mut self, lights: Option<SceneLights>) -> Self {
        self.scene_lights = lights;
        self
    }

    /// Set [`focal_distance`](Self::focal_distance).
    pub fn with_focal_distance(mut self, w: f32) -> Self {
        self.focal_distance = w.max(0.0);
        self
    }

    /// Set [`flip_y`](Self::flip_y).
    pub fn with_flip_y(mut self, flip: bool) -> Self {
        self.flip_y = flip;
        self
    }

    /// Set [`swiftshader_depth`](Self::swiftshader_depth).
    pub fn with_swiftshader_depth(mut self, on: bool) -> Self {
        self.swiftshader_depth = on;
        self
    }

    /// Set [`swiftshader_sampling`](Self::swiftshader_sampling).
    pub fn with_swiftshader_sampling(mut self, on: bool) -> Self {
        self.swiftshader_sampling = on;
        self
    }

    /// Set [`subpixel_snap`](Self::subpixel_snap).
    pub fn with_subpixel_snap(mut self, steps: f32, bias: [f32; 2]) -> Self {
        self.subpixel_snap = Some((steps, bias));
        self
    }

    /// Set [`clip_epsilon`](Self::clip_epsilon).
    pub fn with_clip_epsilon(mut self, w: f32) -> Self {
        self.clip_epsilon = w;
        self
    }

    /// The view through `camera` at `renderer`'s drawing size and with its
    /// tone mapping — what marks drawn over that renderer's frames want.
    pub fn from_renderer(
        camera: &dyn crate::Camera,
        origin: Origin,
        renderer: &crate::Renderer,
    ) -> Self {
        Self::for_surface(camera, origin, &MarkSurface::of(renderer))
    }

    /// The view of marks drawn over `surface`'s frames.
    pub fn for_surface(camera: &dyn crate::Camera, origin: Origin, surface: &MarkSurface) -> Self {
        let mut v = Self::new(camera, origin, surface.size);
        v.tone_mapping = surface.tone_mapping;
        if surface.reversed_z {
            v = v.with_reversed_z();
        }
        v
    }

    /// Remap to reversed depth, as a renderer with
    /// [`set_reversed_z`](crate::Renderer::set_reversed_z) draws: clip
    /// `z' = w - z`.
    pub fn with_reversed_z(mut self) -> Self {
        if !self.reversed_z {
            for c in 0..4 {
                self.view_proj[c * 4 + 2] = self.view_proj[c * 4 + 3] - self.view_proj[c * 4 + 2];
            }
            self.reversed_z = true;
        }
        self
    }

    /// Set [`tone_mapping`](Self::tone_mapping).
    pub fn with_tone_mapping(mut self, mode: crate::ToneMapping, exposure: f32) -> Self {
        self.tone_mapping = (mode, exposure);
        self
    }

    /// World units one pixel spans at absolute point `p` — what picks a
    /// tile zoom or a level of detail there. `None` behind the camera.
    pub fn units_per_pixel(&self, p: [f64; 3]) -> Option<f64> {
        let w = self.project(p)?[2] as f64;
        let px_per_unit = self.projection_scale.abs() as f64 * self.viewport.1 as f64 * 0.5;
        Some(w / px_per_unit.max(1e-12))
    }

    /// An absolute position on screen: `(x, y)` pixels from the top left and
    /// clip `w`, or `None` behind the camera.
    pub fn project(&self, p: [f64; 3]) -> Option<[f32; 3]> {
        let l = self.origin.to_local(p);
        let m = &self.view_proj;
        let x = m[0] * l.x + m[4] * l.y + m[8] * l.z + m[12];
        let y = m[1] * l.x + m[5] * l.y + m[9] * l.z + m[13];
        let w = m[3] * l.x + m[7] * l.y + m[11] * l.z + m[15];
        if w <= 1e-9 {
            return None;
        }
        let (vw, vh) = (self.viewport.0 as f32, self.viewport.1 as f32);
        Some([(x / w * 0.5 + 0.5) * vw, (0.5 - y / w * 0.5) * vh, w])
    }

    fn scene_uniforms(&self) -> SceneUniforms {
        let mut u: SceneUniforms = bytemuck::Zeroable::zeroed();
        let Some(l) = &self.scene_lights else {
            return u;
        };
        let points = l.points.iter().flatten().count();
        let dirs = l.directional.iter().flatten().count();
        u.counts = [points as f32, dirs as f32, 1.0, 0.0];
        u.ambient = [l.ambient[0], l.ambient[1], l.ambient[2], 0.0];
        for (i, (p, c, a)) in l.points.iter().flatten().enumerate() {
            let r = self.origin.to_local(*p);
            u.point_pos[i] = [r.x, r.y, r.z, 1.0];
            u.point_color[i] = [c[0], c[1], c[2], 0.0];
            u.point_att[i] = [a[0], a[1], a[2], 0.0];
        }
        for (i, (d, c)) in l.directional.iter().flatten().enumerate() {
            let n = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-12);
            u.dir_dir[i] = [d[0] / n, d[1] / n, d[2] / n, 0.0];
            u.dir_color[i] = [c[0], c[1], c[2], 0.0];
        }
        if let Some(sh) = &l.shadow {
            // Relative to the origin: M · T(origin), in f64, then to f32.
            let m = &sh.matrix;
            let o = self.origin.position;
            let mut r = [0f32; 16];
            for c in 0..4 {
                for row in 0..4 {
                    let v = if c == 3 {
                        m[12 + row] + m[row] * o[0] + m[4 + row] * o[1] + m[8 + row] * o[2]
                    } else {
                        m[c * 4 + row]
                    };
                    r[c * 4 + row] = v as f32;
                }
            }
            u.shadow_matrix = bytemuck::cast(r);
            u.shadow_color = sh.color;
            u.shadow_on = [1.0, 0.0, 0.0, 0.0];
        }
        u
    }

    fn uniforms(&self, encode_srgb: bool, samples: u32, offset: [f32; 2]) -> FrameUniforms {
        let (w, h) = (self.viewport.0 as f32, self.viewport.1 as f32);
        let (ohi, olo) = self.origin.split();
        let l = self.light_direction;
        let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt().max(1e-9);
        FrameUniforms {
            view_proj: self.view_proj,
            origin_hi: ohi,
            origin_lo: olo,
            viewport: [w, h, 1.0 / w, 1.0 / h],
            misc: [
                // A mirrored projection (top and bottom swapped) scales by
                // the same amount.
                self.projection_scale.abs() * h * 0.5,
                if encode_srgb { 1.0 } else { 0.0 },
                self.tone_mapping.0.shader_mode(),
                self.tone_mapping.1,
            ],
            // w: reversed depth, which `mark_order` pushes the other way.
            light: [
                l[0] / len,
                l[1] / len,
                l[2] / len,
                if self.reversed_z { 1.0 } else { 0.0 },
            ],
            eye: self.eye,
            // zw: where the target's rectangle begins, device pixels.
            aa: [
                if samples > 1 { 1.0 } else { 0.5 },
                self.focal_distance,
                offset[0],
                offset[1],
            ],
            // yzw: the sub-pixel snap's steps (0 for none) and bias.
            clip: match self.subpixel_snap {
                Some((steps, bias)) => [self.clip_epsilon, steps, bias[0], bias[1]],
                None => [self.clip_epsilon, 0.0, 0.0, 0.0],
            },
            raster: [
                if self.flip_y { 1.0 } else { 0.0 },
                if self.swiftshader_sampling { 1.0 } else { 0.0 },
                if self.swiftshader_depth { 1.0 } else { 0.0 },
                0.0,
            ],
            scene: self.scene_uniforms(),
        }
    }
}

/// What marks need to know of the frames they draw over: their size in
/// device pixels, the tone mapping they were drawn with, and which way their
/// depth runs. [`MarkSurface::of`] a wgpu [`Renderer`](crate::Renderer);
/// [`WindowRenderer::mark_surface`](crate::renderer::WindowRenderer::mark_surface)
/// for a window on either backend.
#[derive(Debug, Clone, Copy)]
pub struct MarkSurface {
    pub size: (u32, u32),
    pub tone_mapping: (crate::ToneMapping, f32),
    pub reversed_z: bool,
}

impl MarkSurface {
    pub fn of(renderer: &crate::Renderer) -> Self {
        Self {
            size: renderer.drawing_buffer_size(),
            tone_mapping: renderer.tone_mapping(),
            reversed_z: renderer.reversed_z(),
        }
    }
}

/// Where marks are drawn: a colour target, and optionally the depth buffer of
/// the frame already in it.
pub struct MarkTarget<'a> {
    /// The view drawn into — the multisampled colour when `samples > 1`.
    pub color: gpu::TextureView,
    /// Where a multisampled `color` resolves to.
    pub resolve: Option<gpu::TextureView>,
    /// The frame's depth, [`DEPTH_FORMAT`], with `samples` samples.
    pub depth: Option<gpu::TextureView>,
    pub format: wgpu::TextureFormat,
    pub samples: u32,
    /// Draw only within `[x, y, width, height]` (device pixels from the
    /// top left) — one view of several on a canvas. The [`MarkView`]'s
    /// viewport is then this rectangle's size. `None`: all of it.
    pub rect: Option<[u32; 4]>,
    /// The views are handles; the target borrows nothing, but keeps the
    /// lifetime its wgpu constructors have always had.
    pub _borrow: std::marker::PhantomData<&'a ()>,
}

impl<'a> MarkTarget<'a> {
    /// A plain colour target with no depth: marks draw over everything.
    pub fn new(color: &'a wgpu::TextureView, format: wgpu::TextureFormat) -> Self {
        Self::from_view(color.into(), format)
    }

    /// [`new`](Self::new) for a view of either backend.
    pub fn from_view(color: gpu::TextureView, format: wgpu::TextureFormat) -> Self {
        Self {
            color,
            resolve: None,
            depth: None,
            format,
            samples: 1,
            rect: None,
            _borrow: std::marker::PhantomData,
        }
    }

    /// Draw within `rect` only ([`rect`](Self::rect)).
    pub fn with_rect(mut self, rect: [u32; 4]) -> Self {
        self.rect = Some(rect);
        self
    }

    /// Depth-test against `depth` ([`DEPTH_FORMAT`], same size and sample count).
    pub fn with_depth(mut self, depth: &'a wgpu::TextureView) -> Self {
        self.depth = Some(depth.into());
        self
    }

    /// [`with_depth`](Self::with_depth) for a view of either backend.
    pub fn with_depth_view(mut self, depth: gpu::TextureView) -> Self {
        self.depth = Some(depth);
        self
    }

    /// A [`RenderTarget`](crate::RenderTarget) that
    /// [`Renderer::render_to`](crate::Renderer::render_to) just drew into.
    pub fn render_target(rt: &'a crate::RenderTarget) -> Self {
        Self::new(&rt.color_view, rt.format).with_depth(&rt.depth_view)
    }

    /// The frame [`Renderer::render`](crate::Renderer::render) just drew into
    /// `frame`, with that frame's depth — multisampled if it was.
    pub fn over_frame(renderer: &'a crate::Renderer, frame: &'a wgpu::TextureView) -> Self {
        let (msaa_color, depth, samples) = renderer.overlay_attachments();
        match msaa_color {
            Some(color) => Self {
                color: color.into(),
                resolve: Some(frame.into()),
                depth: Some(depth.into()),
                format: renderer.color_format(),
                samples,
                rect: None,
                _borrow: std::marker::PhantomData,
            },
            None => Self::new(frame, renderer.color_format()).with_depth(depth),
        }
    }
}

/// What a size is measured in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SizeUnits {
    /// Screen pixels: the same size at any distance.
    #[default]
    Pixels,
    /// World units: smaller with distance, like geometry.
    World,
}

/// How a mark's colour combines with what is under it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum MarkBlend {
    /// Ordinary straight-alpha "over".
    #[default]
    Alpha,
    /// Colours add — glows, and dense layers that should brighten where they
    /// overlap.
    Additive,
    /// No blending: what is drawn replaces what was there (data written as
    /// colour, such as a shadow map's packed depths).
    Replace,
}

/// Settings every mark has.
#[derive(Debug, Clone, PartialEq)]
pub struct MarkStyle {
    /// Multiplies every instance's size (radius, width, scale).
    pub size_scale: f32,
    pub units: SizeUnits,
    /// Pixel clamps on the drawn size, whatever the units.
    pub min_pixels: f32,
    pub max_pixels: f32,
    pub opacity: f32,
    /// Four `vec4`s the hooks read as `layer.params` — filter ranges, time.
    pub params: [[f32; 4]; 4],
    /// Hide behind the frame's geometry. Needs a target with depth.
    pub depth_test: bool,
    /// Write depth, so later marks and passes are hidden behind this one.
    pub depth_write: bool,
    /// How far towards the camera a mark drawn facing it (a point, a line, a
    /// label) is depth-tested, as a multiple of its drawn size.
    ///
    /// At 0 the whole sprite takes its anchor's depth, so a point resting on
    /// the ground loses the part of its disc that lies over nearer ground,
    /// and a line along the ground fights it for every pixel. Seen from an
    /// elevation θ, the ground under a disc's lower edge is `1 / tan θ`
    /// radii nearer than its centre, so that is the lift a mark needs to draw
    /// whole on a level surface: 1 for views steeper than 45°, 2 (the
    /// default) down to 27°, 4 down to 14°. The price is that geometry less
    /// than that far in front of a mark no longer hides it. Ignored by
    /// shapes, which are real geometry.
    pub depth_lift: f32,
    /// A constant depth bias in units of the minimum resolvable depth
    /// difference (GL's `polygonOffset` units; negative is nearer): the
    /// GPU's for the built-in kinds (in SwiftShader's depth planes under
    /// [`MarkView::swiftshader_depth`]), `layer.shadow.y` for custom kinds;
    /// deck.gl gives each layer `-100 × its index`. Not for lines, which
    /// SwiftShader gives no bias of their own.
    pub depth_bias_units: f32,
    /// Draw order among layers lying in the same plane: a higher order wins
    /// the depth test over a lower one at the same depth, so water, land
    /// use and roads on the ground stack instead of fighting. Each step is
    /// 10⁻⁶ of the depth range: a few float steps, enough to separate
    /// coplanar layers, and too little to pull a camera-facing sprite
    /// through the ground just in front of its anchor.
    pub depth_order: i32,
    /// Polygon fills and images pulled towards the camera by a depth bias
    /// (the default), so one lying on a ground mesh at the same height wins
    /// instead of fighting it. The bias grows with the surface's slope to
    /// the eye: off, a fill ties with lines on it under a tilted view and
    /// draw order decides, as in deck.gl.
    pub ground_bias: bool,
    /// Draw only inside this ground rectangle, `[min_x, min_y, max_x,
    /// max_y]` in the ground convention of [`geo`] — a tile's bounds.
    /// Fills, lines and images are cut at its edge; points, sprites, shapes
    /// and labels are kept or dropped by their anchor, which also drops the
    /// copies of a point that vector tiles repeat in their buffer. Flat
    /// ground only.
    pub clip: Option<[f64; 4]>,
    /// One row drawn in [`highlight_color`](Self::highlight_color) — the
    /// hovered or selected one. A uniform: changing it rewrites no column.
    pub highlight: Option<u32>,
    /// How many rows from [`highlight`](Self::highlight) light up: a whole
    /// path or feature is several (1, the default, is one row).
    pub highlight_len: u32,
    /// sRGB; alpha is how far the row's colour moves towards it.
    pub highlight_color: [u8; 4],
    /// A planet as `(centre, radius)`: rows on its far side from the eye
    /// are not drawn — labels, icons and points that do not depth-test
    /// against the globe would otherwise show through it.
    pub horizon: Option<([f64; 3], f64)>,
    /// Cull triangles facing away (counter-clockwise on screen is the
    /// front, as in GL; a [`MarkView::flip_y`] view mirrors it): deck.gl's
    /// `GlobeView` culls its layers' back faces, so geometry on the globe's
    /// far side faces away and is not drawn. Lines are never culled.
    pub cull_back: bool,
    /// Run the layer's colours through the scene's tone mapping
    /// ([`MarkView::tone_mapping`]), so marks sit in a lit, exposed scene
    /// the way its materials do. Off by default: data colours then reach the
    /// screen exactly, and a legend matches them.
    pub tone_mapped: bool,
    /// Darkened where the scene's shadow map ([`SceneLights::shadow`]) says
    /// something nearer the light covers it — deck.gl's `shadowEnabled`.
    /// Off by default. Also whether the mark casts, in a shadow pass,
    /// unless [`cast_shadows`](Self::cast_shadows) says otherwise.
    pub receive_shadows: bool,
    /// Whether the mark draws into a shadow pass; `None` (the default)
    /// follows [`receive_shadows`](Self::receive_shadows). deck.gl's
    /// `shadowEnabled: false` keeps a layer out of the shadow pass while it
    /// still takes the shadows of others.
    pub cast_shadows: Option<bool>,
    pub blend: MarkBlend,
    /// Smooth edges by analytic coverage (the default). Off, points and
    /// lines draw hard-edged, every fragment fully in or out — deck.gl's
    /// look without MSAA, and its `antialiasing: false`.
    pub antialias: bool,
    /// Blend between a mark's two colours (a segment's source and target)
    /// on sRGB values rather than linear ones — deck.gl's gradients, which
    /// interpolate the colour bytes. Off by default.
    pub mix_srgb: bool,
    /// Pixel sizes hold at the view's focal plane
    /// ([`MarkView::focal_distance`]) and scale with perspective elsewhere,
    /// clamps included — deck.gl's convention, where a 2-pixel line is
    /// wider nearer the camera. Off by default: pixels are screen pixels
    /// everywhere. No effect when the view sets no focal distance.
    pub focal_pixels: bool,
    pub visible: bool,
    pub pickable: bool,
}

impl MarkStyle {
    /// Whether the mark draws into a shadow pass ([`cast_shadows`](Self::cast_shadows)).
    pub fn casts_shadows(&self) -> bool {
        self.cast_shadows.unwrap_or(self.receive_shadows)
    }
}

impl Default for MarkStyle {
    fn default() -> Self {
        Self {
            size_scale: 1.0,
            units: SizeUnits::Pixels,
            min_pixels: 0.0,
            max_pixels: f32::MAX,
            opacity: 1.0,
            params: [[0.0; 4]; 4],
            depth_test: true,
            depth_write: false,
            depth_lift: 2.0,
            depth_bias_units: 0.0,
            depth_order: 0,
            ground_bias: true,
            clip: None,
            highlight: None,
            highlight_len: 1,
            highlight_color: [255, 220, 0, 255],
            horizon: None,
            cull_back: false,
            tone_mapped: false,
            receive_shadows: false,
            cast_shadows: None,
            blend: MarkBlend::Alpha,
            antialias: true,
            mix_srgb: false,
            focal_pixels: false,
            visible: true,
            pickable: true,
        }
    }
}

/// The parts of a mark that are the same for every kind.
#[derive(Debug, Default)]
pub struct MarkCommon {
    pub style: MarkStyle,
    pub hooks: ShaderHooks,
    /// Set when the layer's positions are
    /// [`PositionLocal`](ColumnFormat::PositionLocal): the absolute point
    /// they are relative to. The `set_local_*` methods of each mark set it
    /// with the columns; set it yourself only for a mark of your own.
    pub local_origin: Option<[f64; 3]>,
    /// A stable id per row, reported by picks as [`PickHit::feature`] — the
    /// feature a tile's row came from, which another tile's row of the same
    /// feature shares. Shared, so a pick takes a snapshot for free.
    pub feature_ids: Option<std::sync::Arc<[u64]>>,
    custom: [Option<Column>; 2],
    pick_id: u32,
    /// Where this layer's uniforms sit in the renderer's arena, set by each
    /// prepare.
    layer_offset: u32,
}

impl MarkCommon {
    /// Custom column `slot` (0 or 1): up to four floats a row, read by hooks as
    /// `custom0` / `custom1`.
    pub fn set_custom(&mut self, slot: usize, components: u32, values: &[f32]) {
        assert!(slot < 2, "custom slot {slot} is not 0 or 1");
        assert!((1..=4).contains(&components), "1..=4 floats a row");
        let col = self.custom[slot].get_or_insert_with(|| Column::float(components));
        if col.format() != ColumnFormat::Float(components) {
            *col = Column::float(components);
        }
        col.set_f32(values);
    }

    /// Whether custom column `slot` is set.
    pub fn has_custom(&self, slot: usize) -> bool {
        self.custom.get(slot).is_some_and(|c| c.is_some())
    }

    /// Overwrite rows of a custom column from `start`.
    pub fn update_custom(&mut self, slot: usize, start: usize, values: &[f32]) {
        self.custom[slot]
            .as_mut()
            .expect("set_custom first")
            .update_f32(start, values);
    }

    /// Set [`feature_ids`](Self::feature_ids).
    pub fn set_feature_ids(&mut self, ids: Vec<u64>) {
        self.feature_ids = Some(ids.into());
    }

    pub fn clear_custom(&mut self, slot: usize) {
        self.custom[slot] = None;
    }

    /// Drop the custom columns' GPU copies.
    pub fn release_gpu(&mut self) {
        for c in self.custom.iter_mut().flatten() {
            c.release();
        }
    }

    /// Bytes the custom columns hold on the GPU. (A layer's uniforms live
    /// in the [`MarkRenderer`]'s shared arena.)
    pub fn gpu_bytes(&self) -> u64 {
        self.custom.iter().flatten().map(Column::gpu_bytes).sum()
    }

    pub fn custom(&self, slot: usize) -> Option<&Column> {
        self.custom[slot].as_ref()
    }

    fn custom_widths(&self) -> [u32; 2] {
        let w = |c: &Option<Column>| match c.as_ref().map(|c| c.format()) {
            Some(ColumnFormat::Float(n)) => n,
            _ => 0,
        };
        [w(&self.custom[0]), w(&self.custom[1])]
    }
}

/// Instanced geometry: a vertex buffer of position + normal, its vertex
/// count, and an optional `u32` index buffer with its count.
pub type InstancedGeometry<'a> = (&'a gpu::Buffer, u32, Option<(&'a gpu::Buffer, u32)>);

/// Phong-style lighting for lit marks ([`ShapeMarks`], [`PolygonMarks`]),
/// as deck.gl's default `LightingEffect` and material light them: the
/// colour times `ambient + diffuse × Σ intensity × max(n·l, 0)`, with the
/// product taken on sRGB values when [`srgb`](Self::srgb) is set (as
/// deck.gl's shaders do). Replaces the marks' own `ambient`-only light.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Lighting {
    /// The material's ambient reflectance times the ambient light.
    pub ambient: f32,
    /// The material's diffuse reflectance.
    pub diffuse: f32,
    /// The material's specular reflectance (Blinn-Phong highlights), 0 for
    /// none.
    pub specular: f32,
    /// The highlights' exponent.
    pub shininess: f32,
    /// Up to two directional lights: the direction *towards* each light,
    /// world space (need not be normalized), and its intensity.
    pub lights: [([f32; 3], f32); 2],
    /// Multiply sRGB-encoded colours rather than linear ones.
    pub srgb: bool,
    /// Physically based instead, as luma.gl's `pbrMaterial` lights glTF:
    /// `[metallic, roughness]`. `ambient` is then the ambient light's
    /// intensity, the lights' intensities their colours, and `diffuse`,
    /// `specular`, `shininess` and `srgb` are unused.
    pub pbr: Option<[f32; 2]>,
    /// Light by the view's [`SceneLights`] instead of `lights`, per pixel,
    /// as luma.gl's Phong material (`ambient`, `diffuse`, `shininess` and
    /// `specular_color` its material; on sRGB values). Shapes only.
    pub scene: bool,
    /// The highlights' colour, sRGB 0 to 1, for `scene` lighting.
    pub specular_color: [f32; 3],
}

impl Lighting {
    /// deck.gl's default: an ambient light of intensity 1, directional
    /// lights travelling along `[-1, 3, -1]` (intensity 1) and
    /// `[1, -8, -2.5]` (0.9) in deck.gl's frame (x east, y north, z up),
    /// and its default Phong material (ambient 0.35, diffuse 0.6, specular
    /// 30/255 with shininess 32), applied to sRGB values.
    pub fn deck_gl() -> Self {
        // deck.gl's (x, y, z) is threers' (x, z, -y); towards the light is
        // against its direction of travel.
        let toward = |[x, y, z]: [f32; 3]| [-x, -z, y];
        Self {
            ambient: 0.35,
            diffuse: 0.6,
            specular: 30.0 / 255.0,
            shininess: 32.0,
            lights: [
                (toward([-1.0, 3.0, -1.0]), 1.0),
                (toward([1.0, -8.0, -2.5]), 0.9),
            ],
            srgb: true,
            pbr: None,
            scene: false,
            specular_color: [30.0 / 255.0; 3],
        }
    }

    /// deck.gl's Phong material lit by a `LightingEffect`: the view's
    /// [`SceneLights`], per pixel. `specular_color` is the material's
    /// `specularColor` (sRGB, 0 to 1).
    pub fn deck_gl_scene(specular_color: [f32; 3]) -> Self {
        Self {
            scene: true,
            specular_color,
            ..Self::deck_gl()
        }
    }

    /// deck.gl's default lights on luma.gl's physically based material
    /// (`ScenegraphLayer`'s `_lighting: 'pbr'`): Cook-Torrance per light,
    /// the ambient light as one straight along the normal, in linear light.
    ///
    /// luma.gl's physically based shader takes each light's direction of
    /// travel as the way *towards* it (its Phong shader negates it), so the
    /// lights here come from the opposite side of `deck_gl`'s.
    pub fn deck_gl_pbr(metallic: f32, roughness: f32) -> Self {
        let toward = |[x, y, z]: [f32; 3]| [x, z, -y];
        Self {
            ambient: 1.0,
            srgb: false,
            pbr: Some([metallic, roughness]),
            lights: [
                (toward([-1.0, 3.0, -1.0]), 1.0),
                (toward([1.0, -8.0, -2.5]), 0.9),
            ],
            ..Self::deck_gl()
        }
    }

    /// `material` as the lit kinds' shaders read it.
    pub(crate) fn material(lighting: Option<&Lighting>) -> [f32; 4] {
        lighting.map_or([0.0; 4], |l| match l.pbr {
            // w: 2 for the scene's lights.
            None if l.scene => [l.specular, l.shininess.max(1.0), 0.0, 2.0],
            // w: 1 for the physically based model (z is a polygon
            // pattern's mask flag).
            Some([metallic, roughness]) => [
                metallic.clamp(0.0, 1.0),
                roughness.clamp(0.04, 1.0),
                0.0,
                1.0,
            ],
            None => [l.specular, l.shininess.max(1.0), 0.0, 0.0],
        })
    }

    /// `(style2.yz, stroke, extra)` as the lit kinds' shaders read them.
    pub(crate) fn uniforms(lighting: Option<&Lighting>) -> ([f32; 2], [f32; 4], [f32; 4]) {
        let Some(l) = lighting else {
            return ([0.0; 2], [0.0; 4], [0.0; 4]);
        };
        let light = |(d, i): ([f32; 3], f32)| {
            let n = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-12);
            [d[0] / n, d[1] / n, d[2] / n, i]
        };
        if l.scene {
            // stroke: the highlights' colour.
            let c = l.specular_color;
            return (
                [l.diffuse.max(1e-6), 1.0],
                [c[0], c[1], c[2], 0.0],
                [0.0; 4],
            );
        }
        (
            [l.diffuse.max(1e-6), if l.srgb { 1.0 } else { 0.0 }],
            light(l.lights[0]),
            light(l.lights[1]),
        )
    }
}

/// Per-kind uniform values beyond [`MarkStyle`]: `(style2, style3, stroke)`.
/// `style2.w` is always the opacity; the renderer fills it in.
pub type KindUniforms = ([f32; 4], [f32; 4], [f32; 4]);

/// What [`Mark::prepare`] gets to upload with.
pub struct PrepareContext<'a> {
    pub device: &'a gpu::Device,
    pub queue: &'a gpu::Queue,
    pub view: &'a MarkView,
    pub(crate) resources: &'a SharedResources,
}

impl PrepareContext<'_> {
    /// The renderer's clamp-to-edge, linearly filtered sampler, for a custom
    /// mark's bind group.
    pub fn linear_sampler(&self) -> &gpu::Sampler {
        &self.resources.linear_sampler
    }
}

/// One layer of marks: the renderer's interface to it.
///
/// The mark types in this module implement it, and so can a crate of your
/// own: report a [`MarkKind::Custom`] from a [`CustomShader`], hand its
/// source back from [`custom_shader`](Self::custom_shader), list the columns
/// its vertex input reads, and — for a kind that samples textures — give
/// [`extra_layout`](Self::extra_layout) and
/// [`extra_bind_group`](Self::extra_bind_group). Uniforms, hooks, custom
/// columns, picking, depth and blending then work as they do for the
/// built-in kinds.
pub trait Mark {
    fn kind(&self) -> MarkKind;
    fn common(&self) -> &MarkCommon;
    fn common_mut(&mut self) -> &mut MarkCommon;
    /// Instances to draw.
    fn instance_count(&self) -> usize;
    /// Rows the columns are uploaded for: instances, or vertices for a mark
    /// whose columns are [`per_vertex`](Self::per_vertex).
    fn rows(&self) -> usize {
        self.instance_count()
    }
    /// Columns, custom ones included, advance per vertex rather than per
    /// instance.
    fn per_vertex(&self) -> bool {
        false
    }
    /// An index buffer for a mark with no instanced geometry, and its count.
    fn index_buffer(&self) -> Option<(&gpu::Buffer, u32)> {
        None
    }

    /// Shorthand for `common_mut().style`.
    fn style_mut(&mut self) -> &mut MarkStyle {
        &mut self.common_mut().style
    }

    /// Vertices drawn per instance when there is no
    /// [`geometry`](Self::geometry): 6 for a quad.
    fn vertices_per_instance(&self) -> u32 {
        6
    }
    /// Drawn as the GPU's line primitives, two vertices a line
    /// ([`LineMarks`]), rather than triangles.
    fn line_list(&self) -> bool {
        false
    }
    /// The kind's own uniforms, read as `layer.style2`, `layer.style3` and
    /// `layer.stroke`.
    fn kind_uniforms(&self) -> KindUniforms {
        ([0.0; 4], [0.0; 4], [0.0; 4])
    }
    /// A fourth vector of the kind's own uniforms, read as `layer.extra`.
    fn kind_extra(&self) -> [f32; 4] {
        [0.0; 4]
    }
    /// A fifth, read as `layer.extra2` (for custom kinds; the built-in
    /// kinds leave it unused).
    fn kind_extra2(&self) -> [f32; 4] {
        [0.0; 4]
    }
    /// A sixth to eighth, read as `layer.extra3`, `layer.extra4` and
    /// `layer.extra5` (custom kinds).
    fn kind_extra3(&self) -> [[f32; 4]; 3] {
        [[0.0; 4]; 3]
    }
    /// The kind's surface: x the specular reflectance, y the shininess, of
    /// a lit kind's [`Lighting`] (`layer.material`).
    fn kind_material(&self) -> [f32; 4] {
        [0.0; 4]
    }
    /// Bring GPU copies up to date. Column uploads happen in the renderer.
    fn prepare(&mut self, _ctx: &PrepareContext) {}
    /// Prepare after every mark that does not, keeping this one's place in
    /// the draw order: for a mark that reads what another's preparation
    /// decided (icons [following](SpriteMarks::follow) labels drawn above
    /// them).
    fn prepare_late(&self) -> bool {
        false
    }
    /// The kind's own instance columns, in shader location order from 0
    /// (from 2 after [`geometry`](Self::geometry), which takes 0 and 1).
    fn columns(&mut self) -> Vec<&mut Column>;
    /// Instanced geometry: `(vertex buffer of position+normal, vertices,
    /// optional u32 index buffer and count)`.
    fn geometry(&self) -> Option<InstancedGeometry<'_>> {
        None
    }
    /// The source of a [`MarkKind::Custom`] kind.
    fn custom_shader(&self) -> Option<&CustomShader> {
        None
    }
    /// The layout of bind group 2, for a custom kind that binds one.
    fn extra_layout(&self) -> Option<&gpu::BindGroupLayout> {
        None
    }
    /// Bind group 2, for kinds that sample a texture.
    fn extra_bind_group(&self) -> Option<&gpu::BindGroup> {
        None
    }
    /// Kind-specific flags for the shader, `ids.z` bits 3 to 7.
    fn kind_flags(&self) -> u32 {
        0
    }
    /// Draws its fill with a texture pattern: the kind's `fs_pattern`
    /// entry, with an atlas bound as group 2 ([`PolygonMarks::set_pattern`]).
    fn patterned(&self) -> bool {
        false
    }
    /// Free the layer's GPU memory and keep its data, so a tile cache can
    /// hold many more layers than it draws: the next draw uploads again.
    /// Kinds with GPU objects of their own (meshes, atlases' bind groups,
    /// fields) drop those too.
    fn release_gpu(&mut self) {
        release_columns(self);
    }
    /// Bytes this layer holds on the GPU: its columns, uniforms and any GPU
    /// objects of its own — what a cache budgets with.
    fn gpu_bytes(&mut self) -> u64 {
        column_bytes(self)
    }
    /// Density marks: the accumulation target and composite bind group.
    #[doc(hidden)]
    fn density(&self) -> Option<(&gpu::TextureView, &gpu::BindGroup)> {
        None
    }
    /// Density marks that scale to their own maximum: each reduction level,
    /// its target and the bind group reading the level before it, ending at
    /// one texel.
    #[doc(hidden)]
    fn density_reduction(&self) -> Option<&[density::ReduceLevel]> {
        None
    }
}

/// The part of [`Mark::release_gpu`] every kind shares: columns and common
/// state. For an override that frees GPU objects of its own as well.
pub fn release_columns<M: Mark + ?Sized>(m: &mut M) {
    for c in m.columns() {
        c.release();
    }
    m.common_mut().release_gpu();
}

/// The part of [`Mark::gpu_bytes`] every kind shares.
pub fn column_bytes<M: Mark + ?Sized>(m: &mut M) -> u64 {
    let own: u64 = m.columns().iter().map(|c| c.gpu_bytes()).sum();
    own + m.common().gpu_bytes()
}

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct FrameUniforms {
    view_proj: [f32; 16],
    origin_hi: [f32; 4],
    origin_lo: [f32; 4],
    viewport: [f32; 4],
    misc: [f32; 4],
    light: [f32; 4],
    eye: [f32; 4],
    /// x: the quad margin past a mark's edge, pixels.
    aa: [f32; 4],
    /// x: [`MarkView::clip_epsilon`]; yzw: [`MarkView::subpixel_snap`].
    clip: [f32; 4],
    /// x: 1 when [`MarkView::flip_y`]; y: [`MarkView::swiftshader_sampling`].
    raster: [f32; 4],
    scene: SceneUniforms,
}

/// [`SceneLights`] as the shaders read them.
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct SceneUniforms {
    /// Point lights, directional lights, 1 when there are scene lights.
    counts: [f32; 4],
    ambient: [f32; 4],
    point_pos: [[f32; 4]; 4],
    point_color: [[f32; 4]; 4],
    point_att: [[f32; 4]; 4],
    dir_dir: [[f32; 4]; 4],
    dir_color: [[f32; 4]; 4],
    /// The shadow map's matrix (origin-relative), its colour, and x 1 when
    /// there is one.
    shadow_matrix: [[f32; 4]; 4],
    shadow_color: [f32; 4],
    shadow_on: [f32; 4],
}

const LAYER_SIZE: u64 = std::mem::size_of::<LayerUniforms>() as u64;

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct LayerUniforms {
    params: [[f32; 4]; 4],
    style: [f32; 4],
    style2: [f32; 4],
    style3: [f32; 4],
    stroke: [f32; 4],
    ids: [u32; 4],
    /// x: [`MarkStyle::depth_lift`].
    depth: [f32; 4],
    /// x: 1 when the layer takes the scene's shadows; y:
    /// [`MarkStyle::depth_bias_units`].
    shadow: [f32; 4],
    /// What positions are measured from, split — see `mark_relative`.
    origin_hi: [f32; 4],
    origin_lo: [f32; 4],
    /// The clip rectangle, relative: `(x0, z0, x1, z1)`.
    clip: [f32; 4],
    /// [`Mark::kind_extra`].
    extra: [f32; 4],
    /// [`MarkStyle::highlight_color`], linear.
    highlight: [f32; 4],
    /// [`MarkStyle::horizon`], relative.
    horizon: [f32; 4],
    /// [`Mark::kind_material`].
    material: [f32; 4],
    /// [`Mark::kind_extra2`].
    extra2: [f32; 4],
    /// [`Mark::kind_extra3`].
    extra3: [f32; 4],
    extra4: [f32; 4],
    extra5: [f32; 4],
}

/// Layouts and samplers the mark types build their bind groups against.
#[doc(hidden)]
pub struct SharedResources {
    pub(crate) frame_layout: gpu::BindGroupLayout,
    pub(crate) layer_layout: gpu::BindGroupLayout,
    /// Group 2 of a glyph mark: atlas + sampler.
    pub(crate) texture_layout: gpu::BindGroupLayout,
    /// Group 2 of the density composite: field, ramp, sampler, maximum.
    pub(crate) density_layout: gpu::BindGroupLayout,
    /// Group 0 of a density reduction step: the level before, a sampler.
    pub(crate) reduce_layout: gpu::BindGroupLayout,
    pub(crate) nearest_sampler: gpu::Sampler,
    pub(crate) linear_sampler: gpu::Sampler,
    /// Linear between mip levels too, for atlases that keep them.
    pub(crate) mip_sampler: gpu::Sampler,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum DepthKey {
    /// The pass has no depth attachment.
    None,
    /// It has one, and this pipeline ignores it.
    Ignore,
    /// It has one: compared against unless `!test` (drawn whatever is
    /// there), written unless `!write`.
    Test {
        test: bool,
        write: bool,
        /// Reversed depth: nearer is larger.
        reversed: bool,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct PipelineKey {
    kind: MarkKind,
    hooks: u64,
    custom: [u32; 2],
    local: bool,
    format: wgpu::TextureFormat,
    samples: u32,
    depth: DepthKey,
    blend: MarkBlend,
    pick: bool,
    patterned: bool,
    /// Fills and images pulled towards the camera ([`MarkStyle::ground_bias`]).
    bias: bool,
    /// [`MarkStyle::depth_bias_units`] as the GPU's constant depth bias, for
    /// the built-in kinds drawn with the GPU's depth (custom kinds read it
    /// from `layer.shadow.y`).
    bias_units: i32,
    /// Drawn into a shadow map: the light's depth, packed (`fs_shadow`).
    shadow: bool,
    /// Line primitives ([`Mark::line_list`]).
    lines: bool,
    /// Back faces culled ([`MarkStyle::cull_back`]): 1 with GL's
    /// counter-clockwise front, 2 with it mirrored by a flipped view; 0 none.
    cull: u8,
}

/// Every layer's uniforms in one buffer, one bind group over it, a layer
/// picked by dynamic offset: a frame of hundreds of tile layers is one
/// buffer write rather than hundreds.
struct LayerArena {
    buffer: gpu::Buffer,
    bind_group: gpu::BindGroup,
    /// Layers it holds.
    capacity: usize,
}

/// Draws and picks marks. Holds the pipelines, built on first use and cached
/// for the life of the renderer.
pub struct MarkRenderer {
    resources: SharedResources,
    frame_uniform: gpu::Buffer,
    frame_bind_group: gpu::BindGroup,
    /// The shadow map bound with the frame (a far-plane texel for none).
    no_shadow: std::sync::Arc<gpu::TextureView>,
    shadow_map: std::sync::Arc<gpu::TextureView>,
    shadow_map_dirty: bool,
    /// Draws are into a shadow map ([`set_shadow_pass`](Self::set_shadow_pass)).
    shadow_pass: bool,
    layers: Option<LayerArena>,
    /// Bytes between layers in the arena: the uniforms rounded up to the
    /// device's dynamic-offset alignment.
    layer_stride: u64,
    /// The layer uniforms of the prepare in progress.
    layer_bytes: Vec<u8>,
    modules: HashMap<(MarkKind, u64, [u32; 2], bool), gpu::ShaderModule>,
    pipelines: HashMap<PipelineKey, gpu::RenderPipeline>,
    composites: HashMap<(wgpu::TextureFormat, u32, DepthKey), gpu::RenderPipeline>,
    composite_module: Option<gpu::ShaderModule>,
    reduce_pipeline: Option<gpu::RenderPipeline>,
    pick: picking::PickTargets,
    clearer: Option<clear::Clearer>,
}

fn uniform_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
        ty: wgpu::BindingType::Buffer {
            ty: wgpu::BufferBindingType::Uniform,
            has_dynamic_offset: false,
            min_binding_size: None,
        },
        count: None,
    }
}

fn texture_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Texture {
            sample_type: wgpu::TextureSampleType::Float { filterable },
            view_dimension: wgpu::TextureViewDimension::D2,
            multisampled: false,
        },
        count: None,
    }
}

fn sampler_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
        count: None,
    }
}

fn blend_state(blend: MarkBlend) -> wgpu::BlendState {
    match blend {
        MarkBlend::Replace => wgpu::BlendState::REPLACE,
        MarkBlend::Alpha => wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::SrcAlpha,
                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                operation: wgpu::BlendOperation::Add,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                operation: wgpu::BlendOperation::Add,
            },
        },
        MarkBlend::Additive => wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::SrcAlpha,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::Zero,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
        },
    }
}

/// With `THREERS_DUMP_WGSL` set to a directory (native only), each mark
/// shader module's assembled source is written there as
/// `<kind>-<hash>.wgsl`, for inspecting what the GPU compiler is given.
fn dump_wgsl(kind: &str, source: &str) {
    #[cfg(not(target_arch = "wasm32"))]
    if let Some(dir) = std::env::var_os("THREERS_DUMP_WGSL") {
        use std::hash::{Hash, Hasher};
        let mut h = std::collections::hash_map::DefaultHasher::new();
        source.hash(&mut h);
        let path = std::path::Path::new(&dir).join(format!("{kind}-{:016x}.wgsl", h.finish()));
        if let Err(e) = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&path, source)) {
            log::warn!("THREERS_DUMP_WGSL {}: {e}", path.display());
        }
    }
    #[cfg(target_arch = "wasm32")]
    let _ = (kind, source);
}

fn depth_state(depth: DepthKey) -> Option<wgpu::DepthStencilState> {
    let (write, compare) = match depth {
        DepthKey::None => return None,
        DepthKey::Ignore => (false, wgpu::CompareFunction::Always),
        DepthKey::Test {
            test: false, write, ..
        } => (write, wgpu::CompareFunction::Always),
        DepthKey::Test {
            write, reversed, ..
        } => (
            write,
            if reversed {
                wgpu::CompareFunction::GreaterEqual
            } else {
                wgpu::CompareFunction::LessEqual
            },
        ),
    };
    Some(wgpu::DepthStencilState {
        format: DEPTH_FORMAT,
        depth_write_enabled: Some(write),
        depth_compare: Some(compare),
        stencil: wgpu::StencilState::default(),
        bias: wgpu::DepthBiasState::default(),
    })
}

impl MarkRenderer {
    fn frame_group(
        device: &gpu::Device,
        layout: &gpu::BindGroupLayout,
        uniform: &gpu::Buffer,
        shadow: &gpu::TextureView,
        sampler: &gpu::Sampler,
    ) -> gpu::BindGroup {
        device.create_bind_group(&gpu::BindGroupDescriptor {
            label: Some("threers marks frame bind group"),
            layout,
            entries: &[
                gpu::BindGroupEntry {
                    binding: 0,
                    resource: uniform.as_entire_binding(),
                },
                gpu::BindGroupEntry {
                    binding: 1,
                    resource: gpu::BindingResource::TextureView(shadow),
                },
                gpu::BindGroupEntry {
                    binding: 2,
                    resource: gpu::BindingResource::Sampler(sampler),
                },
            ],
        })
    }

    /// The shadow map [`SceneLights::shadow`] darkens layers by: a texture of
    /// packed depths drawn with [`set_shadow_pass`](Self::set_shadow_pass)
    /// on (`None`: none).
    pub fn set_shadow_map(&mut self, map: Option<std::sync::Arc<wgpu::TextureView>>) {
        self.set_shadow_map_view(map.map(|m| std::sync::Arc::new(gpu::TextureView::from(&*m))));
    }

    /// [`set_shadow_map`](Self::set_shadow_map) for a view of either backend.
    pub fn set_shadow_map_view(&mut self, map: Option<std::sync::Arc<gpu::TextureView>>) {
        let map = map.unwrap_or_else(|| self.no_shadow.clone());
        if !std::sync::Arc::ptr_eq(&map, &self.shadow_map) {
            self.shadow_map = map;
            self.shadow_map_dirty = true;
        }
    }

    /// Draw into a shadow map rather than colour: the marks that can (shapes
    /// and polygons with [`MarkStyle::receive_shadows`]) write the light's
    /// depth of each fragment, packed into RGBA as deck.gl packs it, by the
    /// view's [`SceneLights::shadow`] matrix. Draw with a view rasterizing
    /// from the light, into an `Rgba8Unorm` target with depth.
    pub fn set_shadow_pass(&mut self, on: bool) {
        self.shadow_pass = on;
    }

    /// Whether a mark draws in the current pass.
    fn drawn(&self, m: &dyn Mark) -> bool {
        m.common().style.visible
            && m.instance_count() > 0
            && (!self.shadow_pass
                || (m.common().style.casts_shadows()
                    && matches!(m.kind(), MarkKind::Shape | MarkKind::Polygon)))
    }

    pub fn new(device: &wgpu::Device) -> Self {
        Self::new_on(&gpu::Gpu::from(device))
    }

    /// A renderer on `gpu` — wgpu, or the native Metal backend.
    pub fn new_on(device: &gpu::Gpu) -> Self {
        let frame_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("threers marks frame bgl"),
            // The frame's uniforms, and the scene's shadow map.
            entries: &[uniform_entry(0), texture_entry(1, true), sampler_entry(2)],
        });
        let layer_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("threers marks layer bgl"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: true,
                    min_binding_size: wgpu::BufferSize::new(LAYER_SIZE),
                },
                count: None,
            }],
        });
        let align = u64::from(device.limits().min_uniform_buffer_offset_alignment);
        let layer_stride = LAYER_SIZE.div_ceil(align) * align;
        let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("threers marks texture bgl"),
            entries: &[texture_entry(0, true), sampler_entry(1)],
        });
        let density_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("threers marks density bgl"),
            entries: &[
                // The field is sampled filtered: it may be smaller than the
                // target.
                texture_entry(0, true),
                texture_entry(1, true),
                sampler_entry(2),
                // The field's maximum, one texel, for `auto_max`.
                texture_entry(3, true),
            ],
        });
        let reduce_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("threers marks density reduce bgl"),
            entries: &[texture_entry(0, true), sampler_entry(1)],
        });
        let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("threers marks sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });
        let frame_uniform = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("threers marks frame uniforms"),
            size: std::mem::size_of::<FrameUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        // No shadow map: one texel at the far plane, which shadows nothing.
        let no_shadow = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("threers marks no shadow map"),
            size: wgpu::Extent3d {
                width: 1,
                height: 1,
                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: &[],
        });
        let no_shadow = std::sync::Arc::new(no_shadow.create_view(&Default::default()));
        let frame_bind_group = Self::frame_group(
            device,
            &frame_layout,
            &frame_uniform,
            &no_shadow,
            &linear_sampler,
        );
        Self {
            resources: SharedResources {
                frame_layout,
                layer_layout,
                texture_layout,
                density_layout,
                reduce_layout,
                // Texel centres, read exactly: see `sample_postfx_depth` on
                // why a sample and not a `textureLoad` (WebGL2).
                nearest_sampler: device.create_sampler(&wgpu::SamplerDescriptor {
                    label: Some("threers marks nearest sampler"),
                    ..Default::default()
                }),
                linear_sampler,
                mip_sampler: device.create_sampler(&wgpu::SamplerDescriptor {
                    label: Some("threers marks mip sampler"),
                    address_mode_u: wgpu::AddressMode::ClampToEdge,
                    address_mode_v: wgpu::AddressMode::ClampToEdge,
                    mag_filter: wgpu::FilterMode::Linear,
                    min_filter: wgpu::FilterMode::Linear,
                    mipmap_filter: wgpu::MipmapFilterMode::Linear,
                    ..Default::default()
                }),
            },
            frame_uniform,
            frame_bind_group,
            no_shadow: no_shadow.clone(),
            shadow_map: no_shadow,
            shadow_map_dirty: false,
            shadow_pass: false,
            layers: None,
            layer_stride,
            layer_bytes: Vec::new(),
            modules: HashMap::new(),
            pipelines: HashMap::new(),
            composites: HashMap::new(),
            composite_module: None,
            reduce_pipeline: None,
            pick: picking::PickTargets::default(),
            clearer: None,
        }
    }

    /// Pipelines built so far — for tests and diagnostics.
    pub fn pipeline_count(&self) -> usize {
        self.pipelines.len() + self.composites.len()
    }

    /// Upload everything `marks` need for `view`, and give each its pick id.
    fn prepare_all(
        &mut self,
        device: &gpu::Device,
        queue: &gpu::Queue,
        view: &MarkView,
        marks: &mut [&mut dyn Mark],
    ) {
        let stride = self.layer_stride as usize;
        let mut bytes = std::mem::take(&mut self.layer_bytes);
        bytes.clear();
        bytes.resize(marks.len().max(1) * stride, 0);
        // Late marks after the rest; each keeps its own index (pick id,
        // uniform slot, draw order).
        let mut order: Vec<usize> = (0..marks.len())
            .filter(|&i| !marks[i].prepare_late())
            .collect();
        order.extend((0..marks.len()).filter(|&i| marks[i].prepare_late()));
        for i in order {
            let m = &mut marks[i];
            m.common_mut().pick_id = i as u32 + 1;
            m.common_mut().layer_offset = (i * stride) as u32;
            let ctx = PrepareContext {
                device,
                queue,
                view,
                resources: &self.resources,
            };
            m.prepare(&ctx);
            let rows = m.rows();
            for c in m.columns() {
                c.upload(device, queue, rows);
            }
            for c in m.common_mut().custom.iter_mut().flatten() {
                c.upload(device, queue, rows);
            }
            let (mut style2, style3, stroke) = m.kind_uniforms();
            let extra = m.kind_extra();
            let extra2 = m.kind_extra2();
            let [extra3, extra4, extra5] = m.kind_extra3();
            let material = m.kind_material();
            let kind_flags = m.kind_flags();
            let common = m.common_mut();
            let s = &common.style;
            style2[3] = s.opacity;
            // Absolute: the view's origin. Local: minus the offset from the
            // view's origin to the layer's, so `(p + d_hi) + d_lo` comes out
            // of the same subtraction.
            let layer_origin = match common.local_origin {
                Some(o) => {
                    let v = view.origin.position;
                    let (hi, lo) = split_f64x3([-(o[0] - v[0]), -(o[1] - v[1]), -(o[2] - v[2])]);
                    ([hi[0], hi[1], hi[2], 0.0], [lo[0], lo[1], lo[2], 0.0])
                }
                None => view.origin.split(),
            };
            let u = LayerUniforms {
                params: s.params,
                style: [
                    s.size_scale,
                    s.min_pixels,
                    s.max_pixels,
                    if s.units == SizeUnits::World {
                        1.0
                    } else {
                        0.0
                    },
                ],
                style2,
                style3,
                stroke,
                // ids.z: flags in bits 0-2, the kind's in 3-7, the
                // highlighted rows' count from bit 8.
                ids: [
                    common.pick_id,
                    s.highlight.map_or(0, |r| r + 1),
                    u32::from(!s.antialias)
                        | (u32::from(s.mix_srgb) << 1)
                        | (u32::from(s.focal_pixels) << 2)
                        | ((kind_flags & 0x1f) << 3)
                        | (s.highlight_len.clamp(1, (1 << 24) - 1) << 8),
                    0,
                ],
                highlight: points::srgb_u8_to_linear(s.highlight_color),
                horizon: match s.horizon {
                    Some((c, r)) => {
                        let o = view.origin.position;
                        [
                            (c[0] - o[0]) as f32,
                            (c[1] - o[1]) as f32,
                            (c[2] - o[2]) as f32,
                            r as f32,
                        ]
                    }
                    None => [0.0; 4],
                },
                material,
                depth: [
                    s.depth_lift.max(0.0),
                    s.depth_order as f32 * 1e-6,
                    if s.clip.is_some() { 1.0 } else { 0.0 },
                    if s.tone_mapped { 1.0 } else { 0.0 },
                ],
                clip: match s.clip {
                    // Ground y runs along world -z.
                    Some([x0, y0, x1, y1]) => {
                        let o = view.origin.position;
                        [
                            (x0 - o[0]) as f32,
                            (-y1 - o[2]) as f32,
                            (x1 - o[0]) as f32,
                            (-y0 - o[2]) as f32,
                        ]
                    }
                    None => [0.0; 4],
                },
                origin_hi: layer_origin.0,
                origin_lo: layer_origin.1,
                extra,
                extra2,
                extra3,
                extra4,
                extra5,
                shadow: [
                    if s.receive_shadows { 1.0 } else { 0.0 },
                    s.depth_bias_units,
                    0.0,
                    0.0,
                ],
            };
            bytes[i * stride..i * stride + LAYER_SIZE as usize]
                .copy_from_slice(bytemuck::bytes_of(&u));
        }
        let needed = marks.len().max(1);
        if self.layers.as_ref().is_none_or(|a| a.capacity < needed) {
            // Grown by half again, so a map adding tiles one at a time does
            // not rebuild it every frame.
            let capacity = needed.max(16) + needed / 2;
            let buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("threers mark layer uniforms"),
                size: capacity as u64 * self.layer_stride,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            let bind_group = device.create_bind_group(&gpu::BindGroupDescriptor {
                label: Some("threers mark layer bind group"),
                layout: &self.resources.layer_layout,
                entries: &[gpu::BindGroupEntry {
                    binding: 0,
                    resource: gpu::BindingResource::Buffer(gpu::BufferBinding {
                        buffer: &buffer,
                        offset: 0,
                        size: wgpu::BufferSize::new(LAYER_SIZE),
                    }),
                }],
            });
            self.layers = Some(LayerArena {
                buffer,
                bind_group,
                capacity,
            });
        }
        let arena = self.layers.as_ref().unwrap();
        queue.write_buffer(&arena.buffer, 0, &bytes);
        self.layer_bytes = bytes;
    }

    /// The layer arena's bind group, after a prepare.
    fn layer_bind_group(&self) -> &gpu::BindGroup {
        &self.layers.as_ref().expect("prepared").bind_group
    }

    /// Bytes the shared layer uniforms hold on the GPU.
    pub fn gpu_bytes(&self) -> u64 {
        self.layers.as_ref().map_or(0, |a| a.buffer.size())
    }

    fn module(
        &mut self,
        device: &gpu::Device,
        kind: MarkKind,
        hooks: &ShaderHooks,
        custom: [u32; 2],
        local: bool,
        custom_shader: Option<&CustomShader>,
    ) -> &gpu::ShaderModule {
        self.modules
            .entry((kind, hooks.key(), custom, local))
            .or_insert_with(|| {
                let source = match (custom_shader, local) {
                    (Some(cs), false) => cs.module_source(hooks, custom),
                    (Some(cs), true) => cs.module_source_local(hooks, custom),
                    (None, _) => shader::module_source_with(kind, hooks, custom, local),
                };
                dump_wgsl(&format!("{kind:?}"), &source);
                device.create_shader_module(gpu::ShaderModuleDescriptor {
                    label: Some("threers mark shader"),
                    source: gpu::ShaderSource::Wgsl(source.into()),
                })
            })
    }

    fn ensure_pipeline(&mut self, device: &gpu::Device, key: &PipelineKey, mark: &mut dyn Mark) {
        if self.pipelines.contains_key(key) {
            return;
        }
        let hooks = mark.common().hooks.clone();
        let custom_widths = key.custom;
        // Vertex layouts: geometry first for shapes, then the kind's columns,
        // then the custom columns.
        let mut layouts: Vec<(u64, wgpu::VertexStepMode, Vec<wgpu::VertexAttribute>)> = Vec::new();
        let mut loc = 0;
        if key.kind == MarkKind::Shape {
            // Shapes: position, normal, uv, colour, and the vertex's
            // triangle's three corners.
            let attr = |format, offset, shader_location| wgpu::VertexAttribute {
                format,
                offset,
                shader_location,
            };
            layouts.push((
                84,
                wgpu::VertexStepMode::Vertex,
                vec![
                    attr(wgpu::VertexFormat::Float32x3, 0, 0),
                    attr(wgpu::VertexFormat::Float32x3, 12, 1),
                    attr(wgpu::VertexFormat::Float32x2, 24, 2),
                    attr(wgpu::VertexFormat::Float32x4, 32, 3),
                    attr(wgpu::VertexFormat::Float32x3, 48, 4),
                    attr(wgpu::VertexFormat::Float32x3, 60, 5),
                    attr(wgpu::VertexFormat::Float32x3, 72, 6),
                ],
            ));
            loc = 7;
        } else if mark.geometry().is_some() {
            layouts.push((
                24,
                wgpu::VertexStepMode::Vertex,
                vec![
                    wgpu::VertexAttribute {
                        format: wgpu::VertexFormat::Float32x3,
                        offset: 0,
                        shader_location: 0,
                    },
                    wgpu::VertexAttribute {
                        format: wgpu::VertexFormat::Float32x3,
                        offset: 12,
                        shader_location: 1,
                    },
                ],
            ));
            loc = 2;
        }
        let step = if mark.per_vertex() {
            wgpu::VertexStepMode::Vertex
        } else {
            wgpu::VertexStepMode::Instance
        };
        {
            let cols = mark.columns();
            let refs: Vec<&Column> = cols.iter().map(|c| &**c).collect();
            for (stride, attrs) in columns::instance_layouts(&refs, loc) {
                layouts.push((stride, step, attrs));
            }
        }
        if key.kind != MarkKind::Glyph {
            let first = match mark.custom_shader() {
                Some(cs) => cs.custom_location,
                None => shader::custom_location(key.kind),
            };
            for (cloc, c) in (first..).zip(mark.common().custom.iter().flatten()) {
                let (stride, attrs) = c.layout(cloc);
                layouts.push((stride, step, attrs));
            }
        }
        let buffers: Vec<Option<wgpu::VertexBufferLayout>> = layouts
            .iter()
            .map(|(stride, step, attrs)| {
                Some(wgpu::VertexBufferLayout {
                    array_stride: *stride,
                    step_mode: *step,
                    attributes: attrs,
                })
            })
            .collect();

        let mut groups: Vec<Option<&gpu::BindGroupLayout>> = vec![
            Some(&self.resources.frame_layout),
            Some(&self.resources.layer_layout),
        ];
        if key.patterned
            || matches!(
                key.kind,
                MarkKind::Glyph | MarkKind::Sprite | MarkKind::Image
            )
        {
            groups.push(Some(&self.resources.texture_layout));
        } else if let Some(l) = mark.extra_layout() {
            groups.push(Some(l));
        }
        let layout = device.create_pipeline_layout(&gpu::PipelineLayoutDescriptor {
            label: Some("threers mark pipeline layout"),
            bind_group_layouts: &groups,
            immediate_size: 0,
        });
        let cs = mark.custom_shader().cloned();
        let module = self
            .module(
                device,
                key.kind,
                &hooks,
                custom_widths,
                key.local,
                cs.as_ref(),
            )
            .clone();
        let target = if key.pick || key.shadow {
            wgpu::ColorTargetState {
                format: key.format,
                blend: None,
                write_mask: wgpu::ColorWrites::ALL,
            }
        } else if key.kind == MarkKind::Splat {
            // Densities sum, unweighted by alpha.
            wgpu::ColorTargetState {
                format: key.format,
                blend: Some(wgpu::BlendState {
                    color: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::One,
                        operation: wgpu::BlendOperation::Add,
                    },
                    alpha: wgpu::BlendComponent {
                        src_factor: wgpu::BlendFactor::One,
                        dst_factor: wgpu::BlendFactor::One,
                        operation: wgpu::BlendOperation::Add,
                    },
                }),
                write_mask: wgpu::ColorWrites::ALL,
            }
        } else {
            wgpu::ColorTargetState {
                format: key.format,
                blend: (key.blend != MarkBlend::Replace).then(|| blend_state(key.blend)),
                write_mask: wgpu::ColorWrites::ALL,
            }
        };
        let pipeline = device.create_render_pipeline(&gpu::RenderPipelineDescriptor {
            label: Some("threers mark pipeline"),
            layout: Some(&layout),
            vertex: gpu::VertexState {
                module: &module,
                entry_point: Some("vs_main"),
                buffers: &buffers,
                compilation_options: Default::default(),
            },
            fragment: Some(gpu::FragmentState {
                module: &module,
                entry_point: Some(if key.pick {
                    "fs_pick"
                } else if key.shadow {
                    "fs_shadow"
                } else if key.patterned {
                    "fs_pattern"
                } else {
                    "fs_main"
                }),
                targets: &[Some(target)],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: if key.lines {
                    wgpu::PrimitiveTopology::LineList
                } else {
                    wgpu::PrimitiveTopology::TriangleList
                },
                front_face: if key.cull == 2 {
                    wgpu::FrontFace::Cw
                } else {
                    wgpu::FrontFace::Ccw
                },
                cull_mode: (key.cull != 0).then_some(wgpu::Face::Back),
                ..Default::default()
            },
            depth_stencil: depth_state(key.depth).map(|mut d| {
                // deck.gl's polygon offset (`-100` units a layer), nearer
                // towards larger depth when depth is reversed.
                let reversed = matches!(key.depth, DepthKey::Test { reversed: true, .. });
                d.bias.constant = if reversed {
                    -key.bias_units
                } else {
                    key.bias_units
                };
                if key.bias {
                    // Pull fills towards the camera, so one lying on a ground
                    // mesh at the same height wins instead of fighting it —
                    // towards larger depth when depth is reversed.
                    let toward = if matches!(key.depth, DepthKey::Test { reversed: true, .. }) {
                        -1
                    } else {
                        1
                    };
                    d.bias = wgpu::DepthBiasState {
                        constant: d.bias.constant - 2 * toward,
                        slope_scale: -(toward as f32),
                        clamp: 0.0,
                    };
                }
                d
            }),
            multisample: wgpu::MultisampleState {
                count: key.samples,
                ..Default::default()
            },
            multiview_mask: None,
            cache: None,
        });
        self.pipelines.insert(key.clone(), pipeline);
    }

    fn ensure_composite(
        &mut self,
        device: &gpu::Device,
        format: wgpu::TextureFormat,
        samples: u32,
        depth: DepthKey,
    ) {
        if self.composites.contains_key(&(format, samples, depth)) {
            return;
        }
        let module = self
            .composite_module
            .get_or_insert_with(|| {
                device.create_shader_module(gpu::ShaderModuleDescriptor {
                    label: Some("threers density composite"),
                    source: gpu::ShaderSource::Wgsl(shader::composite_source().into()),
                })
            })
            .clone();
        let layout = device.create_pipeline_layout(&gpu::PipelineLayoutDescriptor {
            label: Some("threers density composite layout"),
            bind_group_layouts: &[
                Some(&self.resources.frame_layout),
                Some(&self.resources.layer_layout),
                Some(&self.resources.density_layout),
            ],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&gpu::RenderPipelineDescriptor {
            label: Some("threers density composite pipeline"),
            layout: Some(&layout),
            vertex: gpu::VertexState {
                module: &module,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(gpu::FragmentState {
                module: &module,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(blend_state(MarkBlend::Alpha)),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState::default(),
            depth_stencil: depth_state(depth),
            multisample: wgpu::MultisampleState {
                count: samples,
                ..Default::default()
            },
            multiview_mask: None,
            cache: None,
        });
        self.composites.insert((format, samples, depth), pipeline);
    }

    /// The max-of-4×4 step a density field's maximum is reduced by.
    fn ensure_reduce(&mut self, device: &gpu::Device) {
        if self.reduce_pipeline.is_some() {
            return;
        }
        let module = device.create_shader_module(gpu::ShaderModuleDescriptor {
            label: Some("threers density reduce"),
            source: gpu::ShaderSource::Wgsl(shader::reduce_source().into()),
        });
        let layout = device.create_pipeline_layout(&gpu::PipelineLayoutDescriptor {
            label: Some("threers density reduce layout"),
            bind_group_layouts: &[Some(&self.resources.reduce_layout)],
            immediate_size: 0,
        });
        self.reduce_pipeline = Some(device.create_render_pipeline(
            &gpu::RenderPipelineDescriptor {
                label: Some("threers density reduce pipeline"),
                layout: Some(&layout),
                vertex: gpu::VertexState {
                    module: &module,
                    entry_point: Some("vs_main"),
                    buffers: &[],
                    compilation_options: Default::default(),
                },
                fragment: Some(gpu::FragmentState {
                    module: &module,
                    entry_point: Some("fs_main"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: density::FIELD_FORMAT,
                        blend: None,
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: Default::default(),
                }),
                primitive: wgpu::PrimitiveState::default(),
                depth_stencil: None,
                multisample: wgpu::MultisampleState::default(),
                multiview_mask: None,
                cache: None,
            },
        ));
    }

    fn key_for(
        mark: &dyn Mark,
        format: wgpu::TextureFormat,
        samples: u32,
        has_depth: bool,
        pick: bool,
        reversed: bool,
        flipped: bool,
    ) -> PipelineKey {
        let s = &mark.common().style;
        let depth = if !has_depth {
            DepthKey::None
        } else if s.depth_test || s.depth_write {
            DepthKey::Test {
                test: s.depth_test,
                write: s.depth_write,
                reversed,
            }
        } else {
            DepthKey::Ignore
        };
        PipelineKey {
            kind: mark.kind(),
            hooks: mark.common().hooks.key(),
            local: mark.common().local_origin.is_some(),
            custom: if mark.kind() == MarkKind::Glyph {
                [0, 0]
            } else {
                mark.common().custom_widths()
            },
            format,
            samples,
            depth,
            blend: s.blend,
            pick,
            patterned: !pick && mark.patterned(),
            bias: s.ground_bias && matches!(mark.kind(), MarkKind::Polygon | MarkKind::Image),
            bias_units: if matches!(mark.kind(), MarkKind::Custom(_)) {
                0
            } else {
                s.depth_bias_units.round() as i32
            },
            shadow: false,
            lines: mark.line_list(),
            cull: match (s.cull_back && !mark.line_list(), flipped) {
                (false, _) => 0,
                (true, false) => 1,
                (true, true) => 2,
            },
        }
    }

    /// Record one mark's draw into `pass`.
    fn record(
        pass: &mut gpu::RenderPass<'_>,
        pipeline: &gpu::RenderPipeline,
        layers: &gpu::BindGroup,
        mark: &mut dyn Mark,
    ) {
        let count = mark.instance_count() as u32;
        let verts = mark.vertices_per_instance();
        pass.set_pipeline(pipeline);
        pass.set_bind_group(1, layers, &[mark.common().layer_offset]);
        if let Some(bg) = mark.extra_bind_group() {
            pass.set_bind_group(2, bg, &[]);
        }
        let mut slot = 0;
        let geometry = mark
            .geometry()
            .map(|(vb, n, ib)| (vb.clone(), n, ib.map(|(b, c)| (b.clone(), c))));
        if let Some((vb, _, _)) = &geometry {
            pass.set_vertex_buffer(0, vb.slice(..));
            slot = 1;
        }
        let kind = mark.kind();
        let mut buffers: Vec<gpu::Buffer> = mark
            .columns()
            .iter()
            .map(|c| c.buffer.clone().expect("uploaded"))
            .collect();
        if kind != MarkKind::Glyph {
            buffers.extend(
                mark.common()
                    .custom
                    .iter()
                    .flatten()
                    .map(|c| c.buffer.clone().expect("uploaded")),
            );
        }
        for b in &buffers {
            pass.set_vertex_buffer(slot, b.slice(..));
            slot += 1;
        }
        let index = mark.index_buffer().map(|(b, n)| (b.clone(), n));
        match (geometry, index) {
            (Some((_, _, Some((ib, n)))), _) | (None, Some((ib, n))) => {
                pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
                pass.draw_indexed(0..n, 0, 0..count);
            }
            (Some((_, n, None)), _) => pass.draw(0..n, 0..count),
            (None, None) => pass.draw(0..verts, 0..count),
        }
    }

    /// Draw `marks`, in order, over `target`.
    pub fn draw(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        target: &MarkTarget,
        view: &MarkView,
        marks: &mut [&mut dyn Mark],
    ) {
        self.draw_on(&gpu::Gpu::from((device, queue)), target, view, marks);
    }

    /// [`draw`](Self::draw) on `gpu` — the one this renderer was made on.
    pub fn draw_on(
        &mut self,
        gpu: &gpu::Gpu,
        target: &MarkTarget,
        view: &MarkView,
        marks: &mut [&mut dyn Mark],
    ) {
        let (device, queue) = (gpu, gpu);
        let encode = crate::renderer::shader_applies_transfer(target.format);
        queue.write_buffer(
            &self.frame_uniform,
            0,
            bytemuck::bytes_of(&view.uniforms(
                encode,
                target.samples,
                target.rect.map_or([0.0; 2], |r| [r[0] as f32, r[1] as f32]),
            )),
        );
        self.prepare_all(device, queue, view, marks);
        if std::mem::take(&mut self.shadow_map_dirty) {
            self.frame_bind_group = Self::frame_group(
                device,
                &self.resources.frame_layout,
                &self.frame_uniform,
                &self.shadow_map,
                &self.resources.linear_sampler,
            );
        }

        let has_depth = target.depth.is_some();
        // Build every pipeline first; recording borrows them.
        for m in marks.iter_mut() {
            if !self.drawn(&**m) {
                continue;
            }
            if m.kind() == MarkKind::Splat {
                let key = Self::key_for(
                    &**m,
                    density::FIELD_FORMAT,
                    1,
                    false,
                    false,
                    view.reversed_z,
                    view.flip_y,
                );
                self.ensure_pipeline(device, &key, &mut **m);
                let depth = if has_depth {
                    DepthKey::Ignore
                } else {
                    DepthKey::None
                };
                self.ensure_composite(device, target.format, target.samples, depth);
                if m.density_reduction().is_some() {
                    self.ensure_reduce(device);
                }
            } else {
                let mut key = Self::key_for(
                    &**m,
                    target.format,
                    target.samples,
                    has_depth,
                    false,
                    view.reversed_z,
                    view.flip_y,
                );
                key.shadow = self.shadow_pass;
                self.ensure_pipeline(device, &key, &mut **m);
            }
        }

        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("threers marks"),
        });
        let mut i = 0;
        while i < marks.len() {
            // A run of ordinary marks shares one pass; a density mark needs
            // a pass of its own into its field first.
            let start = i;
            while i < marks.len() && marks[i].kind() != MarkKind::Splat {
                i += 1;
            }
            if i > start {
                let mut pass = Self::begin_target_pass(&mut encoder, target);
                pass.set_bind_group(0, &self.frame_bind_group, &[]);
                for m in marks[start..i].iter_mut() {
                    if !self.drawn(&**m) {
                        continue;
                    }
                    let mut key = Self::key_for(
                        &**m,
                        target.format,
                        target.samples,
                        has_depth,
                        false,
                        view.reversed_z,
                        view.flip_y,
                    );
                    key.shadow = self.shadow_pass;
                    let pipeline = &self.pipelines[&key];
                    Self::record(&mut pass, pipeline, self.layer_bind_group(), &mut **m);
                }
            }
            if i < marks.len() {
                let m = &mut marks[i];
                i += 1;
                if !self.drawn(&**m) {
                    continue;
                }
                let key = Self::key_for(
                    &**m,
                    density::FIELD_FORMAT,
                    1,
                    false,
                    false,
                    view.reversed_z,
                    view.flip_y,
                );
                {
                    let (field, _) = m.density().unwrap();
                    let mut pass = encoder.begin_render_pass(&gpu::RenderPassDescriptor {
                        label: Some("threers density field"),
                        color_attachments: &[Some(gpu::RenderPassColorAttachment {
                            view: field,
                            depth_slice: None,
                            resolve_target: None,
                            ops: wgpu::Operations {
                                load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                                store: wgpu::StoreOp::Store,
                            },
                        })],
                        depth_stencil_attachment: None,
                        timestamp_writes: None,
                        occlusion_query_set: None,
                        multiview_mask: None,
                    });
                    pass.set_bind_group(0, &self.frame_bind_group, &[]);
                    Self::record(
                        &mut pass,
                        &self.pipelines[&key],
                        self.layer_bind_group(),
                        &mut **m,
                    );
                }
                if let Some(levels) = m.density_reduction() {
                    let reduce = self
                        .reduce_pipeline
                        .as_ref()
                        .expect("built with the pipelines");
                    for level in levels {
                        let mut pass = encoder.begin_render_pass(&gpu::RenderPassDescriptor {
                            label: Some("threers density reduce"),
                            color_attachments: &[Some(gpu::RenderPassColorAttachment {
                                view: &level.target,
                                depth_slice: None,
                                resolve_target: None,
                                ops: wgpu::Operations {
                                    load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                                    store: wgpu::StoreOp::Store,
                                },
                            })],
                            depth_stencil_attachment: None,
                            timestamp_writes: None,
                            occlusion_query_set: None,
                            multiview_mask: None,
                        });
                        pass.set_pipeline(reduce);
                        pass.set_bind_group(0, &level.bind_group, &[]);
                        pass.draw(0..3, 0..1);
                    }
                }
                let depth = if has_depth {
                    DepthKey::Ignore
                } else {
                    DepthKey::None
                };
                let composite = &self.composites[&(target.format, target.samples, depth)];
                let mut pass = Self::begin_target_pass(&mut encoder, target);
                pass.set_pipeline(composite);
                pass.set_bind_group(0, &self.frame_bind_group, &[]);
                pass.set_bind_group(1, self.layer_bind_group(), &[m.common().layer_offset]);
                pass.set_bind_group(2, m.density().unwrap().1, &[]);
                pass.draw(0..3, 0..1);
            }
        }
        queue.submit(Some(encoder.finish()));
    }

    fn begin_target_pass<'e>(
        encoder: &'e mut gpu::CommandEncoder,
        target: &MarkTarget<'_>,
    ) -> gpu::RenderPass<'e> {
        let mut pass = encoder.begin_render_pass(&gpu::RenderPassDescriptor {
            label: Some("threers marks pass"),
            color_attachments: &[Some(gpu::RenderPassColorAttachment {
                view: &target.color,
                depth_slice: None,
                resolve_target: target.resolve.as_ref(),
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Load,
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: target.depth.as_ref().map(|d| {
                gpu::RenderPassDepthStencilAttachment {
                    view: d,
                    depth_ops: Some(wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: wgpu::StoreOp::Store,
                    }),
                    stencil_ops: None,
                }
            }),
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        if let Some([x, y, w, h]) = target.rect {
            pass.set_viewport(
                x as f32,
                y as f32,
                w.max(1) as f32,
                h.max(1) as f32,
                0.0,
                1.0,
            );
            pass.set_scissor_rect(x, y, w.max(1), h.max(1));
        }
        pass
    }

    /// Set the target's [`rect`](MarkTarget::rect) (or all of it) to
    /// `color`, as a pass's load-op clear takes it, and its depth to
    /// `depth`; `None` leaves either as it is. A view's own clear, on a
    /// canvas shared with others.
    pub fn clear(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        target: &MarkTarget,
        color: Option<wgpu::Color>,
        depth: Option<f32>,
    ) {
        self.clear_on(&gpu::Gpu::from((device, queue)), target, color, depth);
    }

    /// [`clear`](Self::clear) on `gpu`.
    pub fn clear_on(
        &mut self,
        gpu: &gpu::Gpu,
        target: &MarkTarget,
        color: Option<wgpu::Color>,
        depth: Option<f32>,
    ) {
        let (device, queue) = (gpu, gpu);
        self.clearer
            .get_or_insert_with(|| clear::Clearer::new(device))
            .clear(device, queue, target, color, depth);
    }
}

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

    /// WebGPU guarantees a pipeline only eight vertex buffers, and the
    /// ninth only fails when a layer binds both custom columns — which no
    /// test without hooks does.
    #[test]
    fn every_kind_fits_in_eight_vertex_buffers_with_both_custom_columns() {
        let geometry = crate::BoxGeometry::new(1.0, 1.0, 1.0);
        let mut marks: Vec<Box<dyn Mark>> = vec![
            Box::new(PointMarks::new()),
            Box::new(SegmentMarks::new()),
            Box::new(ShapeMarks::new(&geometry)),
            Box::new(DensityMarks::new()),
            Box::new(PolygonMarks::new()),
            Box::new(SpriteMarks::new(TextureAtlas::new(64).shared())),
            Box::new(ImageMarks::new(TextureAtlas::new(64).shared())),
        ];
        for m in &mut marks {
            let kind = m.kind();
            let own = m.columns().len();
            let mesh = usize::from(kind == MarkKind::Shape);
            let custom = if kind == MarkKind::Glyph { 0 } else { 2 };
            assert!(
                own + mesh + custom <= 8,
                "{kind:?}: {own} columns + {mesh} mesh + {custom} custom"
            );
        }
    }
}