unlit3d 0.1.0-dev.1

The high-level WebGPU rendering API over unlit_wgpu and unlit_ecs: ECS components, frame sources, input, UI and winit presentation.
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
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
//! The built-in mesh source: the 3D half of a frame.
//!
//! [`MeshSource`] owns everything the mesh path needs: the resource-graph nodes
//! a mesh is uploaded into, the pipeline families an entity's key resolves
//! through, the per-frame caches the draw list is built from, and the
//! [`Scene`] those draws are recorded from. It is an ordinary
//! [`FrameSource`] — the frame driver knows nothing about meshes, so a
//! caller's own source runs beside it with no less privilege.
//!
//! The GPU state it draws with lives in the world, addressed by the
//! [`RenderContext`] it was created with: every setup-time method takes
//! `&LocalWorld` and fetches the device, the queue and the resource graph
//! itself, so the source never holds a borrow of them between calls.

use arrayvec::ArrayVec;
use core::any::TypeId;
use core::ops::DerefMut;
use hashbrown::HashMap;
use std::sync::Arc;

use unlit_ecs::{LocalWorld, TypeIdHashMap};
use unlit_wgpu::buffer_pool::BufferPool;
use unlit_wgpu::globals::{Globals, View};
use unlit_wgpu::mesh::{
    JointMatrix, MeshInfo, MeshInstance, MeshMetadata, PoseBase, compress_indices, compress_weights,
};
use unlit_wgpu::pipeline::{
    BASE_COLOR_SAMPLER_BINDING, BASE_COLOR_TEXTURE_BINDING, CAMERA_BINDING, FRAME_BINDING,
    INSTANCE_SLOT, JOINTS_BINDING, MESH_INFO_BINDING, MESH_METADATA_BINDING, MORPH_DELTAS_BINDING,
    MORPH_WEIGHTS_BINDING, POSITION_SLOT, UV_COLOR_SLOT, UnlitFlags, UnlitOptions, UnlitPipeline,
    apply_surface,
};
use unlit_wgpu::resources::{Resource, ResourceGraph, ResourceId};
use unlit_wgpu::scene::{MAX_VERTEX_BUFFERS, Scene};
use unlit_wgpu::specialize::{
    Specializable, Specializer, SpecializerKey, SurfaceKey, VertexAttributes,
    VertexBufferLayoutDesc,
};
use unlit_wgpu::staging::StagingBuffer;
use unlit_wgpu::vertex_pool::VertexStreamPool;
use zerocopy::IntoBytes;

use crate::bounds::Aabb;
use crate::components::{
    Camera, GpuMaterial, GpuMesh, MorphBinding, MorphWeights, SkinBinding, SkinPose,
};
use crate::culling::VisibleMesh;
use crate::mesh::{MeshDesc, MorphDeltas, UnlitMeshDesc};
use crate::pipeline::{
    DrawKey, FamilyContext, GlobalBinding, GlobalGroupRebuild, PipelineDesc, PipelineFactory,
    PipelineId, PipelineKey, RegisteredGlobal, RenderResources,
};
use crate::scene::{
    AnyFamily, DrawShape, EntryHandles, Family, PipelineHandles, SceneFrame, VisibleEntry,
    assemble_scene, collect_and_sort_visible,
};
use crate::source::{FrameOrder, FrameSource, RenderContext, frame_target};

/// The entries of an unlit mesh's bind group, in the order the variant's mesh
/// layout declares them.
///
/// The mesh-info uniform is the group's first entry always; the morph
/// displacements follow it only when the mesh carries targets. A variant that
/// reads a binding the mesh did not supply is a programming error, and the bind
/// group creation below rejects it.
///
/// The pose is deliberately absent: the joint matrices and morph weights are
/// per-instance state the frame's global group binds, so two instances of one
/// mesh can deform differently.
fn mesh_group_entries<'a>(
    mesh_info: &'a wgpu::Buffer,
    morph_deltas: Option<&'a wgpu::Buffer>,
) -> arrayvec::ArrayVec<wgpu::BindGroupEntry<'a>, 2> {
    let mut entries = arrayvec::ArrayVec::new();
    entries.push(wgpu::BindGroupEntry {
        binding: MESH_INFO_BINDING,
        resource: mesh_info.as_entire_binding(),
    });
    if let Some(deltas) = morph_deltas {
        entries.push(wgpu::BindGroupEntry {
            binding: MORPH_DELTAS_BINDING,
            resource: deltas.as_entire_binding(),
        });
    }
    entries
}

/// The most resources one mesh can be built from: every vertex buffer a pass
/// can bind, plus the index buffer, the mesh bind group, the mesh-info uniform
/// and the morph displacements.
const MAX_MESH_PARTS: usize = MAX_VERTEX_BUFFERS + 4;

/// The byte size of one index of `format`.
///
/// A pooled index range starts at a multiple of [`wgpu::COPY_BUFFER_ALIGNMENT`],
/// which is a multiple of either format's size, so dividing its byte offset by
/// this yields a whole number of indices.
fn index_format_size(format: wgpu::IndexFormat) -> u32 {
    match format {
        wgpu::IndexFormat::Uint16 => size_of::<u16>() as u32,
        wgpu::IndexFormat::Uint32 => size_of::<u32>() as u32,
    }
}

/// Build the unlit shader's global bind group from the source's buffers.
///
/// A free function rather than a method so the rebuild closure the pipeline is
/// registered with can capture it without borrowing the source.
fn create_unlit_global_group(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    resources: &RenderResources,
    needs_metadata: bool,
    needs_joints: bool,
    needs_morphs: bool,
) -> wgpu::BindGroup {
    // An inline `ArrayVec` rather than a `Vec`: this runs on the frame path
    // whenever a global buffer is replaced, and the optional entries depend on
    // the variant, so the group is assembled rather than truncated.
    let mut entries = ArrayVec::<wgpu::BindGroupEntry<'_>, 5>::new();
    entries.push(wgpu::BindGroupEntry {
        binding: CAMERA_BINDING,
        resource: resources.camera.as_entire_binding(),
    });
    entries.push(wgpu::BindGroupEntry {
        binding: FRAME_BINDING,
        resource: resources.globals.as_entire_binding(),
    });
    if needs_metadata {
        entries.push(wgpu::BindGroupEntry {
            binding: MESH_METADATA_BINDING,
            resource: resources.metadata.as_entire_binding(),
        });
    }
    // The pose arrays are the frame's, not a mesh's: binding them here rather
    // than in the mesh group is what lets two instances of one mesh deform
    // differently.
    if needs_joints {
        entries.push(wgpu::BindGroupEntry {
            binding: JOINTS_BINDING,
            resource: resources.joints.as_entire_binding(),
        });
    }
    if needs_morphs {
        entries.push(wgpu::BindGroupEntry {
            binding: MORPH_WEIGHTS_BINDING,
            resource: resources.morph_weights.as_entire_binding(),
        });
    }
    device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("unlit3d::global"),
        layout,
        entries: &entries,
    })
}

/// Register one concrete pipeline and return its index in `pipelines`.
///
/// A free function rather than a method: the family that resolves the key
/// holds the source mutably, so the closure it registers through can only
/// borrow the disjoint fields this needs — the pipeline list, the resource
/// graph and the ids of the source's global buffers.
fn register_concrete(
    pipelines: &mut Vec<RegisteredPipeline>,
    graph: &mut ResourceGraph,
    buffers: GlobalBufferNodes,
    desc: PipelineDesc,
) -> PipelineId {
    // The material and mesh layouts describe a pipeline's binding interface,
    // but they do not outlive registration: the source builds those groups
    // from the family it registered, and wgpu already holds the pipeline's own
    // layout internally.
    let PipelineDesc {
        pipeline, global, ..
    } = desc;

    // A globally bound pipeline reads the source's own frame buffers, so it
    // depends on all of them: a rebuild of any marks the group dirty. The
    // group is rebuilt through the pipeline's own closure, so a custom
    // pipeline keeps control of what its layout binds.
    let global = global.map(|binding| {
        let GlobalBinding {
            bind_group,
            rebuild,
        } = binding;
        let id = graph
            .insert_strong(Resource::BindGroup(bind_group), &buffers.all())
            .expect("the source's buffers exist");
        RegisteredGlobal { id, rebuild }
    });

    pipelines.push(RegisteredPipeline { pipeline, global });
    // The length before the push is the index the pipeline landed on.
    PipelineId::new((pipelines.len() - 1) as u32)
}

/// The full specialization key of the built-in unlit family: the entity's
/// options, the frame's target and the mesh's vertex layout.
///
/// The mesh layout is not injective — two meshes whose raw attributes differ
/// but imply the same [UnlitFlags] rewrite the options to the same thing — so
/// the canonical form is the specialized options themselves, and those meshes
/// share one compiled pipeline.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct UnlitDrawKey {
    options: UnlitOptions,
    surface: SurfaceKey,
    vertex_buffers: ArrayVec<(u32, VertexBufferLayoutDesc), MAX_VERTEX_BUFFERS>,
}

impl From<(UnlitPipelineKey, DrawKey)> for UnlitDrawKey {
    fn from((key, draw): (UnlitPipelineKey, DrawKey)) -> Self {
        Self {
            options: key.options,
            surface: draw.surface,
            vertex_buffers: draw.vertex_buffers,
        }
    }
}

impl SpecializerKey for UnlitDrawKey {
    // The raw mesh layout is not part of the descriptor, so the primary key
    // alone is not injective; the canonical form below is.
    const IS_CANONICAL: bool = false;
    type Canonical = UnlitOptions;
}

/// The flag set a mesh's vertex layout implies, from every slot it declares.
///
/// A mesh's vertex layout cannot imply the morph flag — the displacements are
/// storage data rather than attributes — so morph channels come from the
/// entity's own key, like the material and target flags.
fn unlit_flags_for_layout(layout: &[(u32, VertexBufferLayoutDesc)]) -> UnlitFlags {
    layout
        .iter()
        .fold(UnlitFlags::empty(), |flags, (slot, buffer)| {
            flags | UnlitFlags::for_vertex_buffer(*slot, buffer)
        })
}

/// The per-entity options the built-in unlit family draws with.
///
/// Two entities drawing the same family may start from different options, so
/// the options live on the entity's key rather than on the source. The key's
/// type is how the source finds the family it draws with.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct UnlitPipelineKey {
    /// The options the entity's variants are specialized from.
    pub options: UnlitOptions,
}

impl UnlitPipelineKey {
    /// A key whose variants start from `options`.
    pub fn new(options: UnlitOptions) -> Self {
        Self { options }
    }
}

impl PipelineKey for UnlitPipelineKey {
    type Pipeline = UnlitPipeline;

    fn base_descriptor(&self) -> UnlitOptions {
        self.options.clone()
    }
}

/// Specializes the built-in unlit pipeline per entity options, frame target
/// and mesh layout.
///
/// The descriptor starts from the entity's own options, so one family serves
/// entities that differ in material or target policy. The target-dependent
/// fields are rewritten through [apply_surface], the same helper the core
/// crate's own specializer uses, and only the mesh-derived bits of
/// [UnlitFlags::MESH_MASK] are replaced. The canonical key the cache indexes
/// on is the resulting options: two draws whose specialized options agree
/// share one compiled pipeline.
#[derive(Clone, Copy, Debug, Default)]
struct UnlitDrawSpecializer;

impl Specializer<UnlitPipeline> for UnlitDrawSpecializer {
    type Key = UnlitDrawKey;

    fn specialize(&self, key: UnlitDrawKey, options: &mut UnlitOptions) -> UnlitOptions {
        *options = key.options;
        apply_surface(options, key.surface);
        options.flags =
            (options.flags & !UnlitFlags::MESH_MASK) | unlit_flags_for_layout(&key.vertex_buffers);
        options.clone()
    }
}

/// Describes a specialized [UnlitPipeline] the way the source registers it.
///
/// This is what keeps the built-in pipeline an ordinary client of the family
/// machinery: it packages the shader's layouts and a closure over the
/// shader's global bindings — the camera, globals and, for variants that read
/// a compressed channel, the metadata buffer.
struct UnlitFactory;

impl PipelineFactory<UnlitPipeline> for UnlitFactory {
    fn descriptor(&self, context: &FamilyContext<'_>, value: &UnlitPipeline) -> PipelineDesc {
        let layout = value.global_layout.clone();
        let options = &value.options;
        let needs_metadata = options.needs_metadata();
        let needs_joints = options.needs_joints();
        let needs_morphs = options.needs_morphs();
        let device = context.device.clone();

        let rebuild_layout = layout.clone();
        let rebuild: GlobalGroupRebuild = Arc::new(move |resources| {
            create_unlit_global_group(
                &device,
                &rebuild_layout,
                resources,
                needs_metadata,
                needs_joints,
                needs_morphs,
            )
        });

        let bind_group = rebuild(context.resources);
        PipelineDesc {
            pipeline: value.pipeline.clone(),
            global: Some(GlobalBinding {
                bind_group,
                rebuild,
            }),
            material_layout: value.material_layout.clone(),
            mesh_layout: value.mesh_layout.clone(),
        }
    }
}

/// A pipeline registered with the source.
struct RegisteredPipeline {
    /// The compiled pipeline.
    pipeline: wgpu::RenderPipeline,
    /// The bind group bound at the global index (0), together with the id it
    /// lives under in the resource graph and how to rebuild it. `None` for a
    /// pipeline that binds nothing there.
    global: Option<RegisteredGlobal>,
}

/// The resource-graph nodes of the source's own frame-wide buffers.
///
/// Every pipeline's global bind group is built from them, so they travel
/// together: replacing any one marks every such group dirty and rebuilds it
/// from the current handles.
#[derive(Clone, Copy, Debug)]
struct GlobalBufferNodes {
    /// The camera uniform.
    camera: ResourceId,
    /// The frame globals uniform.
    globals: ResourceId,
    /// The mesh-metadata storage buffer.
    metadata: ResourceId,
    /// The frame's joint matrices.
    joints: ResourceId,
    /// The frame's morph weights.
    morph_weights: ResourceId,
}

impl GlobalBufferNodes {
    /// Every node, in the order a global bind group depends on them.
    fn all(&self) -> [ResourceId; 5] {
        [
            self.camera,
            self.globals,
            self.metadata,
            self.joints,
            self.morph_weights,
        ]
    }
}

/// The built-in mesh renderer, as one frame source.
///
/// It owns the mesh pools, the pipeline families, the per-frame caches and the
/// [`Scene`] the frame's draws are assembled into, and it fetches the device,
/// the queue and the resource graph from the world through the
/// [`RenderContext`] it was created with. Register the families it draws with
/// — [`MeshSource::register_unlit_family`] for the built-in unlit shader — and
/// mount it with [`spawn_source`](crate::source::spawn_source).
pub struct MeshSource {
    /// The world addresses of the frame's GPU state, kept so every entry point
    /// fetches the device, the queue and the graph for itself instead of
    /// holding a borrow of them between calls.
    context: RenderContext,

    /// Resource id of the camera uniform buffer.
    camera_buf: ResourceId,
    /// Resource id of the frame-globals uniform buffer.
    globals_buf: ResourceId,
    /// Resource id of the mesh-metadata storage buffer.
    metadata_buf: ResourceId,
    /// Resource id of the frame's joint-matrix storage buffer.
    joints_buf: ResourceId,
    /// Resource id of the frame's morph-weight storage buffer.
    morph_weights_buf: ResourceId,
    /// Per-frame globals (advanced once per built scene).
    globals: Globals,
    /// Metadata entries, one per live uploaded mesh.
    metadata: Vec<MeshMetadata>,
    /// Metadata slots whose mesh was removed and whose index is free to hand
    /// out again.
    free_metadata: Vec<u32>,
    /// How many metadata entries the current storage buffer can hold.
    metadata_capacity: u32,
    /// Whether the metadata array changed since it was last uploaded.
    ///
    /// Allocating or removing a mesh marks it; the next
    /// [build](FrameSource::build_scene) uploads the array then, so an upload
    /// always lands in the same encoder as the draws that read it.
    metadata_dirty: bool,

    /// A reused instance-data buffer, grown as needed.
    instance_buffer: Option<wgpu::Buffer>,
    instance_capacity: u32,

    /// The frame's joint matrices, packed in visible-instance order.
    ///
    /// Reused across frames rather than reallocated: the packed data is exactly
    /// what is uploaded, so the array and the buffer stay one allocation each.
    packed_joints: Vec<JointMatrix>,
    /// The frame's morph weights, packed in visible-instance order.
    packed_morph_weights: Vec<f32>,

    /// A reused buffer holding the frame's joint matrices, grown as needed.
    ///
    /// One array serves every visible skinned instance: an instance's own
    /// matrices start where its [`MeshInstance::pose`] says. The buffer is a
    /// global binding, so it is uploaded whenever the pose changed.
    joints_capacity: u32,
    /// A reused buffer holding the frame's morph weights, grown as needed.
    ///
    /// Like the joint matrices this is one array for the whole frame, and an
    /// instance's own weights start where its [`MeshInstance::pose`] says.
    morph_weights_capacity: u32,

    /// Reused staging buffers, one per buffer uploaded to every frame, so a
    /// steady frame reaches the GPU without a per-frame allocation or
    /// submission.
    camera_staging: StagingBuffer,
    globals_staging: StagingBuffer,
    metadata_staging: StagingBuffer,
    instance_staging: StagingBuffer,
    joints_staging: StagingBuffer,
    morph_weights_staging: StagingBuffer,

    /// The pool every mesh uploaded through
    /// [`MeshSource::allocate_unlit_mesh`] keeps its indices in, as one large
    /// buffer shared by every indexed mesh.
    ///
    /// A mesh names it through [`GpuMesh::index_buffer`], which is why the
    /// buffer is a node in the resource graph and has to be replaced there
    /// when the pool grows; see [`MeshSource::sync_pool_node`].
    index_pool: BufferPool,
    /// The graph node of [`MeshSource::index_pool`]'s buffer.
    index_pool_id: ResourceId,
    /// The pool every mesh uploaded through
    /// [`MeshSource::allocate_unlit_mesh`] keeps its vertices in: one large
    /// buffer per vertex layout, so meshes that share a layout share a buffer,
    /// and one element allocation covers every stream of a mesh at the same
    /// element index.
    vertex_pool: VertexStreamPool,
    /// The graph node of each of [`MeshSource::vertex_pool`]'s buffers, by the
    /// layout the buffer is shaped for.
    vertex_pool_ids: HashMap<VertexBufferLayoutDesc, ResourceId>,

    /// Every concrete pipeline registered with this source, in registration
    /// order.
    ///
    /// A pipeline is appended the first time a family resolves a key that
    /// needs it, so an entity's concrete pipeline exists once its family has
    /// resolved the draw's surface and mesh layout.
    pipelines: Vec<RegisteredPipeline>,

    /// Every pipeline family registered with this source, keyed by the
    /// [TypeId] of its key type.
    ///
    /// Registration compiles nothing: a family appends to
    /// [`MeshSource::pipelines`] lazily, the first time one of its variant
    /// keys is resolved.
    families: TypeIdHashMap<Box<dyn AnyFamily>>,

    // -- cached per-frame allocations ------------------------------------------
    /// Reused Vec of the meshes that passed this frame's frustum culling.
    visible_meshes_cache: Vec<VisibleMesh>,
    /// Reused Vec for visible-entity collection and per-frame sorting.
    visible_cache: Vec<VisibleEntry>,
    /// Reused Vec for packed instance data.
    packed_instances_cache: Vec<MeshInstance>,
    /// Reused Vec for cloned pipeline handles while the scene is built.
    pipeline_handle_cache: Vec<PipelineHandles>,
    /// Reused Vec of per-entry handles while the scene is built.
    entry_handle_cache: Vec<EntryHandles>,
    /// The scene this source built for the frame, whose allocation survives
    /// between frames.
    scene: Scene,
}

impl MeshSource {
    /// Create the source and the GPU resources the mesh path shares.
    ///
    /// The camera and globals uniforms, the mesh-metadata storage buffer and
    /// the index and vertex pools every uploaded mesh draws out of are inserted
    /// into the context's resource graph. The source starts with no families:
    /// register the ones you draw with through
    /// [`MeshSource::register_family`] — for the built-in unlit shader,
    /// [`MeshSource::register_unlit_family`] does it for you. Registration
    /// compiles nothing; a family's first concrete pipeline is built the first
    /// time an entity that uses it is drawn.
    ///
    /// # Panics
    ///
    /// If `ctx` does not name the world's device, queue and resource graph.
    pub fn new(world: &LocalWorld, ctx: RenderContext) -> Self {
        let device = world
            .get::<wgpu::Device>(ctx.device)
            .expect("the context names the world's device")
            .clone();
        let queue = world
            .get::<wgpu::Queue>(ctx.queue)
            .expect("the context names the world's queue")
            .clone();
        let mut graph = world
            .get_mut::<ResourceGraph>(ctx.graph)
            .expect("the context names the world's resource graph");

        // Camera uniform buffer.
        let camera_buf = graph
            .insert_strong(
                Resource::Buffer(device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("unlit3d::camera"),
                    size: size_of::<View>() as u64,
                    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                    mapped_at_creation: false,
                })),
                &[],
            )
            .expect("camera buffer has no dependencies");

        // Globals uniform buffer.
        let globals = Globals::default();
        let globals_buf = graph
            .insert_strong(
                Resource::Buffer(device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("unlit3d::globals"),
                    size: size_of::<Globals>() as u64,
                    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                    mapped_at_creation: false,
                })),
                &[],
            )
            .expect("globals buffer has no dependencies");

        // Metadata storage buffer (initially 1 entry).
        let metadata_buf = graph
            .insert_strong(
                Resource::Buffer(device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("unlit3d::mesh_metadata"),
                    size: size_of::<MeshMetadata>() as u64,
                    usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                    mapped_at_creation: false,
                })),
                &[],
            )
            .expect("metadata buffer has no dependencies");

        // The frame's pose arrays, one storage buffer each, initially holding a
        // single element. They start out too small for any real frame and grow
        // on the first built scene; a buffer cannot be zero-sized, so the
        // smallest one a draw can read is one element.
        let joints_buf = graph
            .insert_strong(
                Resource::Buffer(device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("unlit3d::pose::joints"),
                    size: <JointMatrix as const_shader_layout::ShaderLayout>::SIZE.get(),
                    usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                    mapped_at_creation: false,
                })),
                &[],
            )
            .expect("the joint buffer has no dependencies");
        let morph_weights_buf = graph
            .insert_strong(
                Resource::Buffer(device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("unlit3d::pose::morph_weights"),
                    size: size_of::<f32>() as u64,
                    usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                    mapped_at_creation: false,
                })),
                &[],
            )
            .expect("the morph-weight buffer has no dependencies");

        // Initial upload of camera and globals.
        queue.write_buffer(
            graph.get_buffer(camera_buf).expect("just inserted"),
            0,
            View::new(glam::Mat4::IDENTITY, glam::Vec3::ZERO).as_bytes(),
        );
        queue.write_buffer(
            graph.get_buffer(globals_buf).expect("just inserted"),
            0,
            globals.as_bytes(),
        );

        // The pools the built-in meshes upload into. Each is one buffer in the
        // graph that many meshes read through, so the node is strong — the
        // source owns it, no mesh does — and starts out the size of the first
        // mesh's worth of data.
        let index_pool = BufferPool::new(
            &device,
            "unlit3d::mesh::indices",
            wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
            size_of::<u32>() as u64 * 1024,
        );
        let index_pool_id = graph
            .insert_strong(Resource::Buffer(index_pool.buffer().clone()), &[])
            .expect("an index pool has no dependencies");
        let vertex_pool = VertexStreamPool::new(
            &device,
            "unlit3d::mesh::vertices",
            wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            1024,
        );

        Self {
            context: ctx,
            camera_buf,
            globals_buf,
            metadata_buf,
            joints_buf,
            morph_weights_buf,
            globals,
            metadata: Vec::new(),
            free_metadata: Vec::new(),
            metadata_capacity: 1,
            metadata_dirty: false,
            instance_buffer: None,
            instance_capacity: 0,
            packed_joints: Vec::new(),
            packed_morph_weights: Vec::new(),
            joints_capacity: 0,
            morph_weights_capacity: 0,
            camera_staging: StagingBuffer::new(),
            globals_staging: StagingBuffer::new(),
            metadata_staging: StagingBuffer::new(),
            instance_staging: StagingBuffer::new(),
            joints_staging: StagingBuffer::new(),
            morph_weights_staging: StagingBuffer::new(),
            index_pool,
            index_pool_id,
            vertex_pool,
            vertex_pool_ids: HashMap::new(),
            pipelines: Vec::new(),
            families: TypeIdHashMap::default(),
            visible_meshes_cache: Vec::new(),
            visible_cache: Vec::new(),
            packed_instances_cache: Vec::new(),
            pipeline_handle_cache: Vec::new(),
            entry_handle_cache: Vec::new(),
            scene: Scene::new(),
        }
    }

    /// The world addresses this source draws through.
    ///
    /// Setup-time code that needs the resource graph reaches it with
    /// `world.get_mut::<ResourceGraph>(source.context().graph)`, which is an
    /// ordinary ECS access: the graph and the source live in different cells.
    pub fn context(&self) -> RenderContext {
        self.context
    }

    /// The device the frame is drawn with, cloned out of `world`.
    ///
    /// # Panics
    ///
    /// If the context's device resource is gone.
    pub fn device(&self, world: &LocalWorld) -> wgpu::Device {
        world
            .get::<wgpu::Device>(self.context.device)
            .expect("the context's device resource exists")
            .clone()
    }

    /// The queue the frame is submitted to, cloned out of `world`.
    ///
    /// # Panics
    ///
    /// If the context's queue resource is gone.
    pub fn queue(&self, world: &LocalWorld) -> wgpu::Queue {
        world
            .get::<wgpu::Queue>(self.context.queue)
            .expect("the context's queue resource exists")
            .clone()
    }

    /// The resource graph `ctx` addresses in `world`.
    ///
    /// An associated function rather than a method so the borrow it takes is
    /// visibly disjoint from the `&mut self` fields a caller may be splitting
    /// alongside it.
    ///
    /// # Panics
    ///
    /// If the context's graph resource is gone.
    pub fn graph<'w>(
        world: &'w LocalWorld,
        ctx: RenderContext,
    ) -> impl DerefMut<Target = ResourceGraph> + 'w {
        world
            .get_mut::<ResourceGraph>(ctx.graph)
            .expect("the context's resource graph exists")
    }

    // -- pipeline registration -------------------------------------------------

    /// Register a pipeline family for the key type `K`.
    ///
    /// This is the only way a pipeline enters the source, for the built-in
    /// unlit shader and a caller's own alike. The key type is the family's
    /// identity: entities draw with it when they carry a
    /// [GpuPipeline](crate::components::GpuPipeline) of that type, and registering a
    /// second family for the same key type is a programming error.
    ///
    /// A family compiles nothing on registration: its concrete pipelines are
    /// built lazily, the first time a draw resolves a variant key, and are
    /// appended to the source's pipeline list in resolution order.
    ///
    /// [`MeshSource::register_unlit_family`] is the built-in unlit family; a
    /// pipeline with nothing to specialize on is registered with the
    /// [`TrivialSpecializer`](crate::pipeline::TrivialSpecializer) and
    /// [`RenderPipelineFactory`](crate::pipeline::RenderPipelineFactory) helpers.
    ///
    /// # Panics
    ///
    /// If a family is already registered for `K`.
    pub fn register_family<K, T, S, F>(&mut self, world: &LocalWorld, specializer: S, factory: F)
    where
        K: PipelineKey<Pipeline = T> + 'static,
        T: Specializable + 'static,
        S: Specializer<T> + 'static,
        S::Key: From<(K, DrawKey)>,
        F: PipelineFactory<T> + 'static,
    {
        let key = TypeId::of::<K>();
        assert!(
            !self.families.contains_key(&key),
            "a pipeline family is already registered for this key type"
        );
        self.families.insert(
            key,
            Box::new(Family::<T, S, F, K>::new(
                &self.device(world),
                specializer,
                factory,
            )),
        );
    }

    /// Register the built-in unlit shader as a family.
    ///
    /// The family specializes each entity's options on the frame's render
    /// target and the mesh's vertex layout: two draws that agree on both share
    /// one compiled pipeline, and a draw whose mesh layout implies different
    /// channels compiles its own. The options are the entity's: a mesh or
    /// material is built against the [UnlitPipelineKey] it will be drawn with,
    /// through [`MeshSource::allocate_unlit_mesh`] and
    /// [`MeshSource::allocate_unlit_material`].
    ///
    /// This compiles nothing; like any family, its first concrete pipeline is
    /// built when an entity that uses it is first drawn.
    ///
    /// # Panics
    ///
    /// If the unlit family is already registered.
    pub fn register_unlit_family(&mut self, world: &LocalWorld) {
        self.register_family::<UnlitPipelineKey, _, _, _>(
            world,
            UnlitDrawSpecializer,
            UnlitFactory,
        );
    }

    // -- mesh allocation -------------------------------------------------------

    /// Upload vertex and index data and return a [GpuMesh] handle.
    ///
    /// The source assumes no vertex layout: `vertex_buffers` lists exactly the
    /// buffers a draw binds, each tagged with the slot the pipeline's vertex
    /// state declares, so a mesh may carry any combination of attributes in
    /// any format. The pipeline specializes on the layout.
    ///
    /// The mesh's [`Aabb`] is recorded in the source's
    /// mesh-metadata array, which the next built scene uploads.
    ///
    /// [`MeshSource::allocate_unlit_mesh`] is the helper that builds the
    /// compressed layout the built-in unlit shader expects.
    ///
    /// # Panics
    ///
    /// If `count` is zero for a non-empty draw, or if the index format does
    /// not match the packed data.
    pub fn allocate_mesh(&mut self, world: &LocalWorld, desc: MeshDesc) -> GpuMesh {
        let metadata = MeshMetadata {
            aabb_center: desc.aabb.center,
            aabb_half_extents: desc.aabb.half_extents,
            ..Default::default()
        };
        // The raw API says nothing about the mesh's channels, so the mesh is
        // not known to carry joints; a caller that uploads a skinned layout
        // goes through `allocate_unlit_mesh`, which does know.
        self.allocate_mesh_with_metadata(world, desc, metadata, false)
    }

    /// Upload a mesh together with the full metadata entry it owns.
    ///
    /// The entry is appended to the CPU-side array and reaches the GPU on the
    /// next built scene; the returned handle names its index.
    ///
    /// `skinned` records whether the mesh's position stream carries joints, so
    /// a skinned draw can be required to name the pose entity it deforms by.
    fn allocate_mesh_with_metadata(
        &mut self,
        world: &LocalWorld,
        desc: MeshDesc,
        metadata: MeshMetadata,
        skinned: bool,
    ) -> GpuMesh {
        let queue = self.queue(world);

        let MeshDesc {
            vertex_buffers,
            index_buffer,
            count,
            indexed,
            aabb,
            bind_group,
            mesh_info_buffer,
            morph_deltas,
        } = desc;

        // The parts, capped like the description they come from: a mesh cannot
        // have more vertex buffers than a pass can bind.
        let mut buffers = ArrayVec::<ResourceId, MAX_VERTEX_BUFFERS>::new();
        let mut vertex_slots = ArrayVec::<(u32, ResourceId), MAX_VERTEX_BUFFERS>::new();
        let mut vertex_layout =
            ArrayVec::<(u32, VertexBufferLayoutDesc), MAX_VERTEX_BUFFERS>::new();
        for desc in vertex_buffers {
            // A weak node: the mesh's virtual root is built from it, so the
            // buffer lives exactly as long as the root does.
            let id = Self::graph(world, self.context)
                .insert_weak(Resource::Buffer(desc.buffer), &[])
                .expect("a vertex buffer has no dependencies");
            vertex_slots.push((desc.slot, id));
            // The layout is owned by the mesh so a family can key on it
            // without reading the description again.
            vertex_layout.push((
                desc.slot,
                VertexBufferLayoutDesc {
                    array_stride: desc.array_stride,
                    step_mode: desc.step_mode,
                    attributes: desc.attributes,
                },
            ));
            buffers.push(id);
        }

        let index_buffer = index_buffer.map(|(buffer, format)| {
            // Weak for the same reason as the vertex buffers.
            let id = Self::graph(world, self.context)
                .insert_weak(Resource::Buffer(buffer), &[])
                .expect("an index buffer has no dependencies");
            (id, format)
        });

        // The uniform the mesh's group reads is a weak node that nothing is
        // built from: the group depends on it, not the other way round. It is
        // the mesh's virtual root that keeps it alive, like every other part.
        let mesh_info_id = mesh_info_buffer.map(|buffer| {
            Self::graph(world, self.context)
                .insert_weak(Resource::Buffer(buffer), &[])
                .expect("a mesh-info buffer has no dependencies")
        });

        // The morph displacements are a weak node like the mesh-info uniform,
        // and like it they are the bind group's dependency: the mesh owns them,
        // so removing it frees them with the rest of its parts.
        //
        // The joint matrices and the morph weights are *not* here. They are
        // per-instance pose state: the frame's global group binds them, so two
        // instances of one mesh can deform differently.
        let morph_target_count = morph_deltas.as_ref().map_or(0, |morph| morph.target_count);
        let morph_deltas_id = morph_deltas.as_ref().map(|morph| {
            Self::graph(world, self.context)
                .insert_weak(Resource::Buffer(morph.buffer.clone()), &[])
                .expect("a morph-delta buffer has no dependencies")
        });

        let bind_group_id = bind_group.map(|bind_group| {
            // Only the buffers the group reads, so replacing or removing one
            // reaches the group. The mesh's vertex and index buffers are
            // deliberately absent: a draw binds them directly, the group reads
            // none of them, and a pooled buffer changes when the pool grows —
            // a dependency would rebuild every group of every mesh that shares
            // the pool for nothing.
            let mut dependencies = ArrayVec::<ResourceId, MAX_MESH_PARTS>::new();
            dependencies.extend(mesh_info_id);
            dependencies.extend(morph_deltas_id);
            Self::graph(world, self.context)
                .insert_weak(Resource::BindGroup(bind_group), &dependencies)
                .expect("a mesh bind group's dependencies are in the graph")
        });

        // The entry is owned whether or not the pipeline reads it: a draw that
        // binds no metadata group simply leaves the index unused. A slot a
        // removed mesh held is reused, so the array stays as dense as the
        // meshes that are still alive.
        let metadata_index = match self.free_metadata.pop() {
            Some(index) => {
                self.metadata[index as usize] = metadata;
                index
            }
            None => {
                let index = self.metadata.len() as u32;
                self.metadata.push(metadata);
                index
            }
        };
        self.metadata_dirty = true;

        // The uniform names the entry the mesh just took, so it is written
        // once the index above is known.
        if let Some(id) = mesh_info_id {
            queue.write_buffer(
                Self::graph(world, self.context)
                    .get_buffer(id)
                    .expect("mesh-info buffer exists"),
                0,
                MeshInfo::new(metadata_index).as_bytes(),
            );
        }

        // Every part of the mesh is registered weak and dependency-free, so
        // the strong virtual root below is the one node that keeps them all
        // alive: removing it orphans them for the cleanup in `remove_mesh` to
        // collect. The root is built from the parts, which is also what makes
        // a replaced part mark it dirty.
        let mut parts = ArrayVec::<ResourceId, MAX_MESH_PARTS>::new();
        parts.extend(buffers.iter().copied());
        parts.extend(index_buffer.map(|(id, _format)| id));
        parts.extend(bind_group_id);
        parts.extend(mesh_info_id);
        parts.extend(morph_deltas_id);
        let root = Self::graph(world, self.context)
            .insert_strong(Resource::Virtual, &parts)
            .expect("a mesh's parts are in the graph");

        GpuMesh {
            root,
            vertex_buffers: vertex_slots,
            vertex_layout,
            index_buffer,
            count,
            first: 0,
            base_vertex: 0,
            indexed,
            aabb,
            metadata_index,
            bind_group_id,
            morph_targets: morph_target_count,
            skinned,
            vertex_allocation: None,
            index_allocation: None,
        }
    }

    /// Upload raw mesh channels in the layout the built-in unlit shader
    /// expects, and return a [GpuMesh] handle.
    ///
    /// Positions and UVs are compressed to the compact vertex formats the
    /// shader decodes, packed into a position buffer and an interleaved
    /// UV-and-colour buffer, and bound with the mesh-metadata bind group the
    /// shader reads its decode parameters from. Colours are already stored in
    /// the width they are uploaded at, so they are copied through unchanged.
    ///
    /// A skinned mesh's joint indices and weights are packed into the *same*
    /// stream as its positions, right after them. A morphed mesh's per-vertex
    /// displacements go into a buffer of its own.
    ///
    /// Neither mesh carries a pose: the joint matrices and morph weights a
    /// frame deforms by are per-instance state the CPU writes, so they live in
    /// the [`SkinPose`] and [`MorphWeights`] components the mesh's entity names
    /// through a [`SkinBinding`] and a [`MorphBinding`]. The source packs them
    /// once per frame, so animating a mesh costs a component write and no
    /// re-upload.
    ///
    /// This is a convenience over [`MeshSource::allocate_mesh`]: it builds the
    /// same [`MeshDesc`] a caller could build by hand, and shares the
    /// compression in [unlit_wgpu::mesh] with anyone else who wants it.
    ///
    /// Which channels are packed is the key's own vertex layout: a slice for a
    /// channel the variant does not declare is left out, so the buffer always
    /// matches what the shader reads.
    ///
    /// # Panics
    ///
    /// If the input slices are empty or of mismatched length (see the
    /// compressors in [unlit_wgpu::mesh]); if the key's options read no
    /// compressed channel and so declare no mesh-metadata group; if the key
    /// declares the joint channel but [`UnlitMeshDesc::joints`] or
    /// [`UnlitMeshDesc::weights`] is `None`; or if the key declares morph
    /// positions but [`UnlitMeshDesc::morph_targets`] is empty.
    pub fn allocate_unlit_mesh(
        &mut self,
        world: &LocalWorld,
        key: &UnlitPipelineKey,
        desc: UnlitMeshDesc<'_>,
    ) -> GpuMesh {
        let device = self.device(world);
        let queue = self.queue(world);

        let UnlitMeshDesc {
            positions,
            uvs,
            colors,
            indices,
            joints,
            weights,
            morph_targets,
        } = desc;

        // The key's layouts are derived on the fly: the source keeps no
        // per-family state, and the pure layout builder is the same one the
        // family's factory uses, so the two cannot drift.
        let options = &key.options;
        let layouts = UnlitPipeline::bind_group_layouts(&device, options);
        let mesh_layout = layouts
            .mesh
            .clone()
            .expect("the unlit variant reads mesh metadata");
        // The streams are the key's, not the caller's: a buffer has to be
        // packed the way the shader reading it declares its vertex layout, so
        // a channel the key does not read is left out.
        let position_stream = options.position_stream();
        let uv_color_stream = options.uv_color_stream();

        // The joint pair belongs to the position stream, so a skinned mesh's
        // stream is wider by it and no separate buffer exists. A variant that
        // deforms by joints reads them from that stream, so it needs the
        // caller's joint indices and weights exactly as a compressed variant
        // needs its UVs. A variant that reads none ignores joints it was
        // handed, as it ignores UVs it does not declare.
        let skinned = options.needs_joints();
        let (packed_joints, packed_weights) = if skinned {
            let joints = joints.expect("a variant that reads joints needs the mesh's joints");
            let weights = weights.expect("a variant that reads joints needs the mesh's weights");
            assert_eq!(
                joints.len(),
                positions.len(),
                "the joint stream must describe the same vertices as the positions"
            );
            assert_eq!(
                weights.len(),
                positions.len(),
                "the weight stream must describe the same vertices as the positions"
            );
            (joints.to_vec(), compress_weights(weights).collect())
        } else {
            (Vec::new(), Vec::new())
        };

        // Compress every vertex stream.
        let mut meta = MeshMetadata::default();
        let position_len = position_stream.byte_len(positions.len());
        let mut position_data = vec![0u8; position_len];
        position_stream.write(
            positions,
            &packed_joints,
            &packed_weights,
            &mut meta,
            wgpu::WriteOnly::from_mut(position_data.as_mut_slice()),
        );
        let vertex_count = positions.len();

        // UV and colour vertex data, interleaved in the order the shader
        // declares: the channel a slice is given for is the channel packed.
        let uv_color_len = uv_color_stream.byte_len(vertex_count);
        let mut uv_color_data = vec![0u8; uv_color_len];
        if uv_color_len > 0 {
            uv_color_stream.write(
                uvs.unwrap_or(&[]),
                colors.unwrap_or(&[]),
                &mut meta,
                wgpu::WriteOnly::from_mut(uv_color_data.as_mut_slice()),
            );
        }

        // The morph displacements, when the draw reads them. They are geometry
        // the mesh owns, written once here; the weights that blend them are
        // per-instance pose state the frame's global group binds.
        let morph_deltas = options.needs_morphs().then(|| {
            assert!(
                !morph_targets.is_empty(),
                "a variant that reads morph positions needs the mesh's morph targets"
            );
            let target_count = morph_targets.len() as u32;
            // One vertex's targets are contiguous, so the flat array is a
            // vertex-major, target-minor matrix of three-component
            // displacements.
            let mut deltas = Vec::with_capacity(positions.len() * morph_targets.len() * 3);
            for vertex in 0..positions.len() {
                for target in morph_targets {
                    assert_eq!(
                        target.positions.len(),
                        positions.len(),
                        "a morph target must displace every vertex of its mesh"
                    );
                    deltas.extend_from_slice(&target.positions[vertex]);
                }
            }
            let buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("unlit3d::mesh::morph_deltas"),
                size: size_of_val(deltas.as_slice()) as u64,
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            queue.write_buffer(&buffer, 0, deltas.as_bytes());
            MorphDeltas {
                buffer,
                target_count,
            }
        });

        // The mesh-info uniform and the bind group the shader reads it
        // through. The index is unknown until the mesh is allocated below, and
        // the buffer is written then.
        let mesh_info_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("unlit3d::mesh::info"),
            size: size_of::<MeshInfo>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let mesh_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("unlit3d::mesh::bind_group"),
            layout: &mesh_layout,
            // The entries follow the variant's own layout: the metadata index
            // is always there, and the morph displacements exist exactly when
            // the variant reads them and the mesh supplied them.
            entries: &mesh_group_entries(
                &mesh_info_buf,
                morph_deltas.as_ref().map(|morph| &morph.buffer),
            ),
        });

        // Index buffer (optional): `Uint16` when every index fits, otherwise
        // `Uint32` — the same choice the compressor makes. The indices go into
        // the index pool, so every indexed mesh draws out of one shared buffer
        // and names its own slice through `GpuMesh::first`.
        let (index_buffer, count, indexed, index_allocation, first_index) = match indices {
            Some(indices) if !indices.is_empty() => {
                let index_count = indices.len() as u32;
                let format = if compress_indices(indices).is_ok() {
                    wgpu::IndexFormat::Uint16
                } else {
                    wgpu::IndexFormat::Uint32
                };
                let data: Vec<u8> = match format {
                    wgpu::IndexFormat::Uint16 => compress_indices(indices)
                        .expect("checked above")
                        .collect::<Vec<u16>>()
                        .as_bytes()
                        .to_vec(),
                    _ => indices.as_bytes().to_vec(),
                };
                let padded_len = data
                    .len()
                    .next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT as usize);
                let mut padded = data;
                padded.resize(padded_len, 0);
                let range = self
                    .index_pool
                    .allocate(&device, &queue, padded_len as u32)
                    .expect("the index pool grows with the mesh");
                {
                    let mut graph = Self::graph(world, self.context);
                    Self::sync_pool_node(&self.index_pool, self.index_pool_id, &mut graph);
                    queue.write_buffer(
                        graph
                            .get_buffer(self.index_pool_id)
                            .expect("the index pool node exists"),
                        u64::from(range.offset()),
                        &padded,
                    );
                }
                let first = range.offset() / index_format_size(format);
                (
                    Some((self.index_pool_id, format)),
                    index_count,
                    true,
                    Some(range.allocation()),
                    first,
                )
            }
            _ => (None, vertex_count as u32, false, None, 0),
        };

        // The vertex layout the key's options declare, slot for slot. An empty
        // stream still gets a buffer entry — the pipeline simply declares no
        // attributes for that slot — so the mesh's layout matches the key's.
        let vertex_layouts = UnlitPipeline::vertex_buffer_layouts(options);
        let layout_of = |slot: u32| -> VertexBufferLayoutDesc {
            vertex_layouts
                .get(slot as usize)
                .and_then(|layout| layout.as_ref())
                .cloned()
                .unwrap_or(VertexBufferLayoutDesc {
                    array_stride: 0,
                    step_mode: wgpu::VertexStepMode::Vertex,
                    attributes: VertexAttributes::new(),
                })
        };
        let position_layout = layout_of(POSITION_SLOT);
        let uv_color_layout = layout_of(UV_COLOR_SLOT);
        let instance_layout = layout_of(INSTANCE_SLOT);

        // The mesh's streams are the vertex pool's: one element allocation
        // covers every stream of the mesh at the same element index, which is
        // what lets a draw address them all with one `firstVertex` or
        // `baseVertex`. A stream the variant declares nothing for — an empty
        // UV-and-colour stream, say — gets no buffer and no part in it.
        let stream_layouts = [position_layout.clone(), uv_color_layout.clone()];
        let vertices = self
            .vertex_pool
            .allocate(&device, &queue, &stream_layouts, vertex_count as u32)
            .expect("the vertex pool grows with the mesh");
        let vertex_offset = vertices.offset();
        for (_slot, (layout, data)) in [
            (POSITION_SLOT, (&position_layout, position_data.as_bytes())),
            (UV_COLOR_SLOT, (&uv_color_layout, uv_color_data.as_bytes())),
        ] {
            if layout.array_stride == 0 {
                continue;
            }
            let id = self.vertex_node(world, layout);
            self.sync_vertex_node(world, id, layout);
            let buffer = Self::graph(world, self.context)
                .get_buffer(id)
                .expect("the stream's node exists")
                .clone();
            queue.write_buffer(
                &buffer,
                VertexStreamPool::byte_offset(layout, vertex_offset),
                data,
            );
        }
        assert!(
            vertex_offset <= i32::MAX as u32,
            "a vertex offset has to fit the i32 a draw's base vertex is"
        );

        // The mesh owns the metadata entry `meta` — the same AABB and UV
        // decode parameters the compression just derived.
        let aabb = Aabb::new(meta.aabb_center, meta.aabb_half_extents);
        let mut mesh = self.allocate_mesh_with_metadata(
            world,
            MeshDesc {
                // The streams are the vertex pool's, not the mesh's own: the
                // mesh names the pool's node for each slot and its own range,
                // so no buffer is registered under the mesh for them.
                vertex_buffers: ArrayVec::new(),
                // The indices are the index pool's, not the mesh's own: the
                // mesh names the pool's node and its own range, so no buffer
                // is registered under the mesh for them.
                index_buffer: None,
                count,
                indexed,
                aabb,
                bind_group: Some(mesh_bind_group),
                // The group reads the metadata index through this uniform, so
                // the group depends on it: the uniform is inserted weak, and
                // removing the mesh frees the group and then collects the
                // orphaned uniform.
                mesh_info_buffer: Some(mesh_info_buf.clone()),
                morph_deltas,
            },
            meta,
            skinned,
        );

        // The addressing the shader reads: the metadata index names the decode
        // parameters, the vertex offset maps `@builtin(vertex_index)` back to
        // this mesh's own vertex ordinal for the morph displacements, and the
        // target count bounds that loop.
        queue.write_buffer(
            &mesh_info_buf,
            0,
            MeshInfo {
                metadata_index: mesh.metadata_index,
                vertex_offset,
                morph_count: mesh.morph_targets,
                pad0: 0,
            }
            .as_bytes(),
        );

        // The source binds the per-instance buffer at [INSTANCE_SLOT] for
        // every draw, so the mesh's layout declares that slot even though the
        // buffer itself is not uploaded here. Without it the draw's key would
        // imply no [UnlitFlags::VERTEX_INSTANCE] and the pipeline would ignore
        // the instance transform.
        mesh.vertex_layout.push((INSTANCE_SLOT, instance_layout));

        // The mesh's slices of the pools it shares: the draw names its ranges
        // by `first` and `base_vertex`, and the allocations are handed back on
        // removal. The layout is the key's own, slot by slot: the family keys
        // on it, so it is owned by the mesh even though the buffers behind it
        // are the pool's. A stream the variant declares nothing for is left
        // out, as it is for a mesh that owns its buffers.
        for (slot, layout) in [
            (POSITION_SLOT, &position_layout),
            (UV_COLOR_SLOT, &uv_color_layout),
        ] {
            if layout.array_stride > 0 {
                mesh.vertex_layout.push((slot, layout.clone()));
                mesh.vertex_buffers
                    .push((slot, self.vertex_node(world, layout)));
            }
        }
        mesh.index_buffer = index_buffer;
        mesh.first = first_index;
        mesh.base_vertex = vertex_offset;
        mesh.index_allocation = index_allocation;
        mesh.vertex_allocation = Some(vertices.allocation());
        mesh
    }

    // -- materials -------------------------------------------------------------

    /// Insert `texture` into the resource graph and return a pair of ids: the
    /// texture itself and a default view of it.
    ///
    /// The view is recorded as depending on the texture, so replacing the
    /// texture marks every material built from the view dirty. The caller
    /// keeps ownership of the texture only until this call; afterwards the
    /// graph holds it.
    pub fn register_texture_and_default_view(
        &mut self,
        world: &LocalWorld,
        texture: wgpu::Texture,
    ) -> (ResourceId, ResourceId) {
        let mut graph = Self::graph(world, self.context);
        let texture_id = graph
            .insert_strong(Resource::Texture(texture), &[])
            .expect("a texture has no dependencies");
        let view = graph
            .get_texture(texture_id)
            .expect("texture exists")
            .create_view(&wgpu::TextureViewDescriptor::default());
        let view_id = graph
            .insert_strong(view, &[texture_id])
            .expect("the view depends on its texture");
        (texture_id, view_id)
    }

    /// Create a sampler with `descriptor` — or the default one when `None` —
    /// insert it into the resource graph and return its id.
    pub fn register_sampler(
        &mut self,
        world: &LocalWorld,
        descriptor: Option<wgpu::SamplerDescriptor<'_>>,
    ) -> ResourceId {
        let sampler = self
            .device(world)
            .create_sampler(&descriptor.unwrap_or_default());
        Self::graph(world, self.context)
            .insert_strong(Resource::Sampler(sampler), &[])
            .expect("a sampler has no dependencies")
    }

    /// Allocate the unlit material bind group from an existing base-colour
    /// texture view and sampler, and return its [GpuMaterial] handle.
    ///
    /// Only the bind group is built. `view_id` and `sampler_id` name resources
    /// the caller has already put in the graph, and they become the group's
    /// dependencies, so replacing either marks it dirty. Returns `None` when
    /// the key's options read no base-color texture, so the variant binds no
    /// material group to put them in.
    ///
    /// # Panics
    ///
    /// If `view_id` or `sampler_id` is not a texture view or sampler in the
    /// graph.
    pub fn allocate_unlit_material(
        &mut self,
        world: &LocalWorld,
        key: &UnlitPipelineKey,
        view_id: ResourceId,
        sampler_id: ResourceId,
    ) -> Option<GpuMaterial> {
        if !key.options.flags.contains(UnlitFlags::BASE_COLOR_TEXTURE) {
            return None;
        }
        let layout = UnlitPipeline::bind_group_layouts(&self.device(world), &key.options)
            .material
            .clone()
            .expect("the base-color variant declares a material group");

        // Clone the handles out so the entries borrow nothing from the graph
        // while `allocate_material` mutates it.
        let view = Self::graph(world, self.context)
            .get_texture_view(view_id)
            .expect("the view is in the graph")
            .clone();
        let sampler = Self::graph(world, self.context)
            .get_sampler(sampler_id)
            .expect("the sampler is in the graph")
            .clone();
        let entries = [
            wgpu::BindGroupEntry {
                binding: BASE_COLOR_TEXTURE_BINDING,
                resource: wgpu::BindingResource::TextureView(&view),
            },
            wgpu::BindGroupEntry {
                binding: BASE_COLOR_SAMPLER_BINDING,
                resource: wgpu::BindingResource::Sampler(&sampler),
            },
        ];
        Some(self.allocate_material(world, &layout, &entries, &[view_id, sampler_id]))
    }

    /// Build a material bind group from `entries` against `layout` and return
    /// its [GpuMaterial] handle.
    ///
    /// Only the bind group is created here: the resources it reads are the
    /// caller's, already in the resource graph and named in `dependencies` so
    /// replacing one marks the group dirty. `layout` is the material layout of
    /// the pipeline the material is for —
    /// [`UnlitPipeline::bind_group_layouts`](unlit_wgpu::pipeline::UnlitPipeline::bind_group_layouts)
    /// for the built-in shader, or the one a custom pipeline registered.
    ///
    /// # Panics
    ///
    /// If a resource named in `entries` is not in the graph.
    pub fn allocate_material(
        &mut self,
        world: &LocalWorld,
        layout: &wgpu::BindGroupLayout,
        entries: &[wgpu::BindGroupEntry<'_>],
        dependencies: &[ResourceId],
    ) -> GpuMaterial {
        let bind_group = self
            .device(world)
            .create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("unlit3d::material::bind_group"),
                layout,
                entries,
            });
        let bind_group_id = Self::graph(world, self.context)
            .insert_strong(Resource::BindGroup(bind_group), dependencies)
            .expect("a material bind group depends on graph resources");

        GpuMaterial { bind_group_id }
    }

    /// Free `mesh` and every resource it owns, and drop its mesh-metadata
    /// entry.
    ///
    /// Every resource of the mesh is registered under its virtual root, so
    /// removing that one node and collecting the parts it orphans frees the
    /// whole mesh: its bind group and the per-mesh uniform that only fed that
    /// bind group. A mesh uploaded through
    /// [`allocate_unlit_mesh`](MeshSource::allocate_unlit_mesh) keeps its
    /// vertices and indices in pools the source shares between meshes; those
    /// allocations are handed back here, and the pool buffers outlive the mesh.
    /// A mesh uploaded with [`allocate_mesh`](MeshSource::allocate_mesh) owns
    /// its buffers, and they die with it.
    ///
    /// Its metadata slot is freed and reused by a mesh allocated later, so
    /// removing meshes does not grow the array a long-lived source uploads.
    /// The next built scene uploads the array the shader reads. Removing a mesh
    /// does not shrink the metadata buffer: it grows to the largest array it
    /// has ever held and stays there.
    ///
    /// Removing a mesh while the world still holds its handle is a programming
    /// error the caller has to avoid: nothing detects the stale handle.
    pub fn remove_mesh(&mut self, world: &LocalWorld, mesh: GpuMesh) {
        {
            let mut graph = Self::graph(world, self.context);
            graph.remove_drop(mesh.root);
            // The root was the only node built from the parts, so with it gone
            // every part is an orphan.
            graph.cleanup_drop();
        }

        if let Some(vertex) = mesh.vertex_allocation {
            self.vertex_pool.release(vertex);
        }
        if let Some(index) = mesh.index_allocation {
            self.index_pool.release(index);
        }

        let emptied = self.metadata.get_mut(mesh.metadata_index as usize);
        if let Some(entry) = emptied {
            *entry = MeshMetadata::default();
            self.free_metadata.push(mesh.metadata_index);
            self.metadata_dirty = true;
        }
    }

    /// Free the bind group `material` names, together with everything built
    /// from it.
    ///
    /// The material's own resources — the texture view and sampler it was
    /// built from — are the caller's and stay in the graph: remove them
    /// separately if nothing else reads them. The [`GpuMaterial`] handle must
    /// not be used afterwards.
    pub fn remove_material(&mut self, world: &LocalWorld, material: GpuMaterial) {
        let mut graph = Self::graph(world, self.context);
        graph.remove_drop(material.bind_group_id);
        // A resource that only fed this material's bind group is an orphan now.
        graph.cleanup_drop();
    }

    // -- poses -----------------------------------------------------------------

    /// Pack every visible instance's pose into the frame's shared arrays and
    /// record where each instance's slice starts.
    ///
    /// A mesh's pose is not part of its upload: the joints and weights live in
    /// components the CPU writes, and this reads them once per frame. A mesh
    /// names the entity holding each through a [`SkinBinding`] and a
    /// [`MorphBinding`], so several meshes may share one pose — packing it once
    /// however many of them are visible — or deform independently.
    ///
    /// The packed offsets go into each instance's [`MeshInstance::pose`], which
    /// the shader reads to find its own joints and weights.
    ///
    /// # Panics
    ///
    /// If a visible mesh deforms but names no pose entity, if that entity
    /// carries no pose component, or if a pose's weight count does not match
    /// the mesh's target count.
    fn pack_poses(&mut self, world: &LocalWorld) {
        // Split the borrows: the packed arrays grow while the visible entries
        // are written.
        let Self {
            visible_cache,
            packed_joints,
            packed_morph_weights,
            ..
        } = self;
        packed_joints.clear();
        packed_morph_weights.clear();

        for entry in visible_cache.iter_mut() {
            let entity = entry.mesh.entity;

            let joints_base = if entry.mesh.skinned {
                let binding = world.get::<SkinBinding>(entity).unwrap_or_else(|| {
                    panic!(
                        "a skinned mesh needs a `SkinBinding` naming the entity that holds \
                         its `SkinPose`"
                    )
                });
                let pose = world.get::<SkinPose>(binding.pose).unwrap_or_else(|| {
                    panic!("the entity a skinned mesh binds to carries no `SkinPose`")
                });
                assert!(
                    !pose.matrices.is_empty(),
                    "a skinned mesh's pose needs at least one joint matrix"
                );
                let base = packed_joints.len() as u32;
                packed_joints.extend_from_slice(&pose.matrices);
                base
            } else {
                0
            };

            let weights_base = if entry.mesh.morph_targets > 0 {
                let binding = world.get::<MorphBinding>(entity).unwrap_or_else(|| {
                    panic!(
                        "a mesh with morph targets needs a `MorphBinding` naming the entity \
                         that holds its `MorphWeights`"
                    )
                });
                let weights = world
                    .get::<MorphWeights>(binding.weights)
                    .unwrap_or_else(|| {
                        panic!("the entity a morphed mesh binds to carries no `MorphWeights`")
                    });
                assert_eq!(
                    weights.weights.len() as u32,
                    entry.mesh.morph_targets,
                    "a mesh's morph weights must hold one weight per morph target"
                );
                let base = packed_morph_weights.len() as u32;
                packed_morph_weights.extend_from_slice(&weights.weights);
                base
            } else {
                0
            };

            entry.mesh.instance.pose = PoseBase::new(joints_base, weights_base);
        }
    }

    /// Grow the frame's joint-matrix buffer if the packed array outgrew it, and
    /// upload the array through the frame's encoder.
    ///
    /// Like the metadata array the buffer is recreated only when it is too
    /// small, so a steady frame rewrites in place and rebuilds no bind group.
    fn upload_joints(&mut self, world: &LocalWorld, encoder: &mut wgpu::CommandEncoder) {
        let needed = self.packed_joints.len().max(1) as u32;
        if needed > self.joints_capacity {
            let capacity = needed.max(self.joints_capacity * 2);
            let buf = self.device(world).create_buffer(&wgpu::BufferDescriptor {
                label: Some("unlit3d::pose::joints"),
                size: capacity as u64
                    * <JointMatrix as const_shader_layout::ShaderLayout>::SIZE.get(),
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            Self::graph(world, self.context)
                .replace(self.joints_buf, Resource::Buffer(buf))
                .expect("the joint buffer exists");
            self.joints_capacity = capacity;
            // A replaced buffer invalidates every global group bound to it.
            self.rebuild_dirty_global_groups(world);
        }
        let buffer = Self::graph(world, self.context)
            .get_buffer(self.joints_buf)
            .expect("the joint buffer exists")
            .clone();
        self.joints_staging.write(
            &self.device(world),
            encoder,
            &buffer,
            0,
            self.packed_joints.as_bytes(),
        );
    }

    /// Grow the frame's morph-weight buffer if the packed array outgrew it, and
    /// upload the array through the frame's encoder.
    fn upload_morph_weights(&mut self, world: &LocalWorld, encoder: &mut wgpu::CommandEncoder) {
        let needed = self.packed_morph_weights.len().max(1) as u32;
        if needed > self.morph_weights_capacity {
            let capacity = needed.max(self.morph_weights_capacity * 2);
            let buf = self.device(world).create_buffer(&wgpu::BufferDescriptor {
                label: Some("unlit3d::pose::morph_weights"),
                size: capacity as u64 * size_of::<f32>() as u64,
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            Self::graph(world, self.context)
                .replace(self.morph_weights_buf, Resource::Buffer(buf))
                .expect("the morph-weight buffer exists");
            self.morph_weights_capacity = capacity;
            self.rebuild_dirty_global_groups(world);
        }
        let buffer = Self::graph(world, self.context)
            .get_buffer(self.morph_weights_buf)
            .expect("the morph-weight buffer exists")
            .clone();
        self.morph_weights_staging.write(
            &self.device(world),
            encoder,
            &buffer,
            0,
            self.packed_morph_weights.as_bytes(),
        );
    }

    // -- internal helpers ------------------------------------------------------

    /// The source's global buffers, cloned out of the resource graph.
    fn render_resources(&self, world: &LocalWorld) -> RenderResources {
        let graph = Self::graph(world, self.context);
        RenderResources {
            camera: graph
                .get_buffer(self.camera_buf)
                .expect("camera buf")
                .clone(),
            globals: graph
                .get_buffer(self.globals_buf)
                .expect("globals buf")
                .clone(),
            metadata: graph
                .get_buffer(self.metadata_buf)
                .expect("meta buf")
                .clone(),
            joints: graph
                .get_buffer(self.joints_buf)
                .expect("joints buf")
                .clone(),
            morph_weights: graph
                .get_buffer(self.morph_weights_buf)
                .expect("morph weights buf")
                .clone(),
        }
    }

    /// Rebuild the global bind group of every registered pipeline whose
    /// dependencies changed.
    ///
    /// Each pipeline supplies its own rebuild closure, so a replacement of the
    /// camera, globals or metadata buffer refreshes the built-in unlit
    /// pipeline and any custom one that binds those buffers alike.
    fn rebuild_dirty_global_groups(&mut self, world: &LocalWorld) {
        let resources = self.render_resources(world);
        // Walked by index rather than collected into a `Vec` first: this runs
        // on the frame path, and the replacement below needs the graph
        // mutably, which a live borrow of `self.pipelines` rules out. Taking
        // each entry's handle and dropping the borrow before rebuilding keeps
        // the loop allocation-free.
        for index in 0..self.pipelines.len() {
            let dirty = {
                let Some(global) = self.pipelines[index].global.as_ref() else {
                    continue;
                };
                if !Self::graph(world, self.context).is_dirty(global.id) {
                    continue;
                }
                (global.id, Arc::clone(&global.rebuild))
            };

            let (id, rebuild) = dirty;
            let bind_group = rebuild(&resources);
            let mut graph = Self::graph(world, self.context);
            graph
                .replace(id, Resource::BindGroup(bind_group))
                .expect("global group exists");
            graph.mark_clean(id);
        }
    }

    /// Upload the camera uniform, staging the bytes through the frame's
    /// encoder.
    fn upload_camera(
        &mut self,
        world: &LocalWorld,
        encoder: &mut wgpu::CommandEncoder,
        view: &View,
    ) {
        let buffer = Self::graph(world, self.context)
            .get_buffer(self.camera_buf)
            .expect("camera buffer exists")
            .clone();
        self.camera_staging
            .write(&self.device(world), encoder, &buffer, 0, view.as_bytes());
    }

    /// Upload the frame-globals uniform, staging the bytes through the frame's
    /// encoder.
    fn upload_globals(&mut self, world: &LocalWorld, encoder: &mut wgpu::CommandEncoder) {
        let buffer = Self::graph(world, self.context)
            .get_buffer(self.globals_buf)
            .expect("globals buffer exists")
            .clone();
        self.globals_staging.write(
            &self.device(world),
            encoder,
            &buffer,
            0,
            self.globals.as_bytes(),
        );
    }

    /// Pack and upload the frame's instance data, staging the bytes through
    /// the frame's encoder.
    fn upload_instances(&mut self, world: &LocalWorld, encoder: &mut wgpu::CommandEncoder) {
        self.packed_instances_cache.clear();
        self.packed_instances_cache
            .extend(self.visible_cache.iter().map(|entry| entry.mesh.instance));
        let buffer = self
            .instance_buffer
            .as_ref()
            .expect("instance buffer exists")
            .clone();
        self.instance_staging.write(
            &self.device(world),
            encoder,
            &buffer,
            0,
            self.packed_instances_cache.as_bytes(),
        );
    }

    /// Grow the metadata buffer if the array outgrew it, and upload the array
    /// through the frame's encoder if it changed.
    ///
    /// Allocating or removing a mesh marks the array dirty, so the upload lands
    /// in the next frame together with the draws that read it. The storage
    /// buffer is recreated only when the array outgrows it, so a steady scene
    /// rewrites in place and rebuilds no bind group.
    fn upload_metadata(&mut self, world: &LocalWorld, encoder: &mut wgpu::CommandEncoder) {
        if !self.metadata_dirty {
            return;
        }
        self.metadata_dirty = false;

        let needed = self.metadata.len().max(1) as u32;
        if needed > self.metadata_capacity {
            // Grow geometrically so repeated allocations amortize, and
            // recreate rather than resize: a buffer has a fixed size.
            let capacity = needed.max(self.metadata_capacity * 2);
            let buf = self.device(world).create_buffer(&wgpu::BufferDescriptor {
                label: Some("unlit3d::mesh_metadata"),
                size: capacity as u64 * size_of::<MeshMetadata>() as u64,
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            Self::graph(world, self.context)
                .replace(self.metadata_buf, Resource::Buffer(buf))
                .expect("metadata buffer exists");
            self.metadata_capacity = capacity;
            // A replaced buffer invalidates every global group bound to it.
            self.rebuild_dirty_global_groups(world);
        }
        let buffer = Self::graph(world, self.context)
            .get_buffer(self.metadata_buf)
            .expect("metadata buffer exists")
            .clone();
        self.metadata_staging.write(
            &self.device(world),
            encoder,
            &buffer,
            0,
            self.metadata.as_bytes(),
        );
    }

    /// The graph node of the vertex pool's buffer for `layout`, creating it if
    /// the pool has never been asked for the layout before.
    ///
    /// The node is strong: the source owns the pool, no mesh does. See
    /// [`MeshSource::sync_pool_node`] for why nothing may depend on it.
    fn vertex_node(&mut self, world: &LocalWorld, layout: &VertexBufferLayoutDesc) -> ResourceId {
        if let Some(&id) = self.vertex_pool_ids.get(layout) {
            return id;
        }
        let id = Self::graph(world, self.context)
            .insert_strong(Resource::Virtual, &[])
            .expect("a new stream node has no dependencies");
        self.vertex_pool_ids.insert(layout.clone(), id);
        id
    }

    /// Point the stream node `id` at the vertex pool's buffer for `layout`.
    ///
    /// A stream node starts as a virtual stand-in, so its first sync swaps in
    /// the real buffer; later syncs only happen when the pool grew.
    fn sync_vertex_node(
        &mut self,
        world: &LocalWorld,
        id: ResourceId,
        layout: &VertexBufferLayoutDesc,
    ) {
        let buffer = self
            .vertex_pool
            .buffer(layout)
            .expect("the layout has a buffer");
        let mut graph = Self::graph(world, self.context);
        if graph.get_buffer(id) != Some(buffer) {
            graph
                .replace(id, Resource::Buffer(buffer.clone()))
                .expect("a stream node exists");
        }
    }

    /// Point the graph node `id` at the buffer `pool` currently hands out.
    ///
    /// A pool grows by creating a new buffer, and a mesh keeps the pool's node
    /// id rather than its buffer, so the node has to follow the buffer. The
    /// check is the pool's own handle compared against what the node holds: no
    /// counter to keep in step, and repeating the call is free.
    ///
    /// Nothing depends on a pool node — a mesh's bind group reads only its
    /// mesh-info uniform — so replacing one marks nothing else dirty. A
    /// dependency added onto a pool buffer makes every grow rebuild it, which
    /// is why there must not be one.
    fn sync_pool_node(pool: &BufferPool, id: ResourceId, graph: &mut ResourceGraph) {
        if graph.get_buffer(id) != Some(pool.buffer()) {
            graph
                .replace(id, Resource::Buffer(pool.buffer().clone()))
                .expect("a pool node exists");
        }
    }

    /// Grow the per-instance buffer geometrically when needed.
    fn ensure_instance_buffer(&mut self, world: &LocalWorld, count: u32) {
        if count <= self.instance_capacity {
            return;
        }
        let new_cap = count.max(self.instance_capacity * 2).max(1);
        let buf = self.device(world).create_buffer(&wgpu::BufferDescriptor {
            label: Some("unlit3d::instance"),
            size: (new_cap as u64) * size_of::<MeshInstance>() as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        self.instance_buffer = Some(buf);
        self.instance_capacity = new_cap;
    }

    /// Collect entities that pass frustum culling, then sort them for drawing.
    ///
    /// The pass itself lives in [crate::scene]; this only unpacks the source's
    /// caches and the closure that registers a newly resolved pipeline, so a
    /// family never borrows the whole source.
    ///
    /// `surface` is the render target this frame draws into; it is threaded
    /// into every entity's pipeline resolution, so each entry's `pipeline_id`
    /// is a concrete pipeline valid for that target.
    fn collect_and_sort_visible(
        &mut self,
        world: &LocalWorld,
        camera: &Camera,
        surface: SurfaceKey,
    ) {
        let resources = self.render_resources(world);
        let device = self.device(world);

        // Split the borrows: the families mutate the pipeline list and the
        // resource graph through the register closure, while the caches are
        // disjoint fields.
        let (families, meshes, visible) = (
            &mut self.families,
            &mut self.visible_meshes_cache,
            &mut self.visible_cache,
        );
        let (pipelines, buffers) = (
            &mut self.pipelines,
            GlobalBufferNodes {
                camera: self.camera_buf,
                globals: self.globals_buf,
                metadata: self.metadata_buf,
                joints: self.joints_buf,
                morph_weights: self.morph_weights_buf,
            },
        );
        let ctx = self.context;
        let mut graph = Self::graph(world, ctx);
        let mut register = |desc| register_concrete(pipelines, &mut graph, buffers, desc);

        collect_and_sort_visible(
            SceneFrame {
                families,
                meshes,
                visible,
                register: &mut register,
            },
            world,
            camera,
            surface,
            &device,
            &resources,
        );
    }

    /// Assemble the draws of the frame's visible set into `self.scene`.
    ///
    /// The handles every draw names — the bind groups, the vertex and index
    /// buffers, the pipeline — are cloned out of the resource graph into reused
    /// scratch lists first, so assembling touches the graph once per entry and
    /// the assembled scene owns everything it names.
    fn assemble_frame(&mut self, world: &LocalWorld) {
        let mut handles = std::mem::take(&mut self.entry_handle_cache);
        handles.clear();
        {
            let graph = Self::graph(world, self.context);
            for entry in &self.visible_cache {
                let mesh = world
                    .get::<GpuMesh>(entry.mesh.entity)
                    .expect("visible entity has GpuMesh");

                let mesh_bg = mesh.bind_group_id.map(|id| {
                    graph
                        .get_bind_group(id)
                        .expect("mesh bind group exists")
                        .clone()
                });

                let material_bg = world.get::<GpuMaterial>(entry.mesh.entity).map(|material| {
                    graph
                        .get_bind_group(material.bind_group_id)
                        .expect("material bind group exists")
                        .clone()
                });

                let mut vertex_buffers = ArrayVec::new();
                for &(slot, buffer) in &mesh.vertex_buffers {
                    let buffer = graph
                        .get_buffer(buffer)
                        .expect("mesh vertex buffer exists")
                        .clone();
                    // A mesh binds its vertex buffers whole; the draw's range
                    // is what picks the mesh's slice out of the pool.
                    vertex_buffers.push((slot, buffer.clone(), 0..buffer.size()));
                }

                let index_buffer = mesh.index_buffer.map(|(buffer, format)| {
                    (
                        graph
                            .get_buffer(buffer)
                            .expect("mesh index buffer exists")
                            .clone(),
                        format,
                    )
                });

                // The mesh is named once here and nowhere else: what a draw
                // reads is carried alongside its handles, so assembling the
                // scene needs no lookup per draw.
                handles.push(EntryHandles {
                    mesh_bg,
                    material_bg,
                    vertex_buffers,
                    index_buffer,
                    shape: DrawShape {
                        indexed: mesh.indexed,
                        count: mesh.count,
                        first: mesh.first,
                        base_vertex: mesh.base_vertex,
                    },
                });
            }
        }

        // Every registered pipeline's handle and global bind group, indexed the
        // same way [`MeshSource::pipelines`] is. A pipeline that binds no
        // global group carries `None`. The list is reused between frames, so a
        // steady scene allocates nothing.
        let mut pipeline_handles = std::mem::take(&mut self.pipeline_handle_cache);
        pipeline_handles.clear();
        {
            let graph = Self::graph(world, self.context);
            pipeline_handles.extend(self.pipelines.iter().map(|registered| PipelineHandles {
                pipeline: registered.pipeline.clone(),
                global: registered.global.as_ref().map(|global| {
                    graph
                        .get_bind_group(global.id)
                        .expect("global group exists")
                        .clone()
                }),
            }));
        }

        let instance_buf = self
            .instance_buffer
            .as_ref()
            .expect("instance buffer exists")
            .clone();

        // The scene keeps its allocation across frames: `clear` drops the
        // draws but not the buffer behind them.
        self.scene.clear();
        assemble_scene(
            &mut self.scene,
            &self.visible_cache,
            &pipeline_handles,
            &handles,
            &instance_buf,
        );

        self.pipeline_handle_cache = pipeline_handles;
        self.entry_handle_cache = handles;
    }
}

impl FrameSource for MeshSource {
    fn build_scene(
        &mut self,
        world: &LocalWorld,
        _ctx: RenderContext,
        encoder: &mut wgpu::CommandEncoder,
    ) {
        // The scene is cleared on every path: a frame that records it must
        // never replay the previous frame's draws, and a source with nothing
        // to draw leaves it empty rather than absent.
        self.scene.clear();

        // A frame that draws still has to publish a changed metadata array, but
        // one that does not draw can leave it for the next frame.
        self.upload_metadata(world, encoder);

        // The frame is drawn from the first camera in `world`, copied out of
        // its cell so the borrow does not block the world accesses below.
        let camera = world.query::<&Camera>().next().map(|(_, c)| Camera {
            clip_from_world: c.clip_from_world,
            position: c.position,
        });
        let Some(camera) = camera else {
            return;
        };

        // The target the frame is specialized for, written by the frame loop
        // before it renders. Without it no pipeline can be resolved, and a
        // stale one is worse than none: reading the previous frame's target
        // would silently specialize for the wrong attachments.
        let Some(target) = frame_target(world) else {
            log::warn!(
                "MeshSource::build_scene: no FrameTarget in the world, so the \
                 frame's render target is unknown and nothing is drawn; write \
                 one by binding a render target before rendering"
            );
            return;
        };
        let surface = target.surface;

        // Update global uniforms.
        self.globals.time += self.globals.delta_time;
        self.globals.frame_count += 1;
        self.upload_globals(world, encoder);

        let view = View::new(camera.clip_from_world, camera.position);
        self.upload_camera(world, encoder, &view);

        // A rebuild has to happen before the global groups are read, and the
        // metadata upload above may have replaced the buffer one of them binds.
        self.rebuild_dirty_global_groups(world);

        // Collect, cull and sort the visible set in one pass. The cache keeps
        // its allocation between frames, so a steady scene allocates nothing.
        self.collect_and_sort_visible(world, &camera, surface);
        if self.visible_cache.is_empty() {
            return;
        }
        let instance_count = self.visible_cache.len() as u32;

        // Resolve and pack every visible instance's pose before the instance
        // data is written: the packed offsets are part of each instance record,
        // so the instance stream cannot be uploaded until they are known. Each
        // upload rebuilds the global groups itself if it had to replace its
        // buffer.
        self.pack_poses(world);
        self.upload_joints(world, encoder);
        self.upload_morph_weights(world, encoder);

        // Pack instance data into the reused scratch buffer and upload it.
        self.ensure_instance_buffer(world, instance_count);
        self.upload_instances(world, encoder);

        self.assemble_frame(world);
    }

    fn scene(&self) -> &Scene {
        &self.scene
    }

    fn order(&self) -> FrameOrder {
        FrameOrder::MESH
    }

    /// Remove every node this source registered: its own uniform buffers, the
    /// pools that hold the meshes, and the global bind group of every
    /// registered pipeline.
    ///
    /// The nodes are the source's, not a caller's: a mesh or material a caller
    /// still holds a handle for is released first by
    /// [`MeshSource::remove_mesh`]/[`MeshSource::remove_material`], and the
    /// handles must not be used after this.
    fn release(&mut self, world: &LocalWorld) {
        let mut graph = Self::graph(world, self.context);

        // The pipelines' global groups are strong nodes in their own right, so
        // removing the buffers they depend on would leave them behind.
        for registered in &self.pipelines {
            if let Some(global) = &registered.global {
                graph.remove_drop(global.id);
            }
        }
        // The pools, the two uniform buffers and the frame's two pose arrays.
        // Every mesh part hangs off a mesh's own virtual root, which the caller
        // removed with its handle; anything left over is an orphan of those
        // nodes and is collected below.
        graph.remove_drop(self.camera_buf);
        graph.remove_drop(self.globals_buf);
        graph.remove_drop(self.metadata_buf);
        graph.remove_drop(self.joints_buf);
        graph.remove_drop(self.morph_weights_buf);
        graph.remove_drop(self.index_pool_id);
        for id in self.vertex_pool_ids.values() {
            graph.remove_drop(*id);
        }
        graph.cleanup_drop();

        self.pipelines.clear();
        self.vertex_pool_ids.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::components::{Transform, UnlitPipeline, ZSortedDrawing};
    use crate::source::{FrameTarget, set_frame_target, spawn_context};
    use unlit_ecs::Entity;
    use unlit_wgpu::render_attachments::{RenderAttachments, create_render_target};
    use unlit_wgpu::scene::DrawRange;

    /// The size every test target is built with.
    const TEST_SIZE: u32 = 64;

    fn test_perspective() -> glam::Mat4 {
        glam::camera::rh::proj::opengl::perspective(1.0, 1.0, 0.1, 100.0)
    }

    /// A source on wgpu's noop backend, ready to draw into a bound target.
    ///
    /// The source is driven directly — not through a
    /// [`Renderer`](crate::Renderer) — so the tests exercise the 3D path
    /// itself. The world holds only the frame's context and target; the source
    /// stays outside it and reaches the world through its `RenderContext`.
    struct Harness {
        world: LocalWorld,
        source: MeshSource,
        key: UnlitPipelineKey,
        target: FrameTarget,
    }

    impl Harness {
        /// The triangle mesh every mesh-level test allocates.
        fn tri_mesh(&mut self) -> GpuMesh {
            self.source.allocate_unlit_mesh(
                &self.world,
                &self.key,
                UnlitMeshDesc {
                    positions: &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
                    uvs: Some(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]),
                    colors: Some(&[[255; 4], [255, 0, 0, 255], [0, 255, 0, 255]]),
                    indices: Some(&[0u32, 1, 2]),
                    ..Default::default()
                },
            )
        }

        /// A command encoder to record a test's uploads into.
        fn encoder(&self) -> wgpu::CommandEncoder {
            self.source.device(&self.world).create_command_encoder(
                &wgpu::CommandEncoderDescriptor {
                    label: Some("test::encoder"),
                },
            )
        }
    }

    /// Resolve every entity in `world` on `surface` and return the concrete
    /// pipeline the last one was drawn with.
    fn resolve_draw(
        source: &mut MeshSource,
        world: &LocalWorld,
        surface: SurfaceKey,
    ) -> PipelineId {
        let camera = test_camera(glam::Vec3::new(0.0, 0.0, 5.0));
        source.collect_and_sort_visible(world, &camera, surface);
        source
            .visible_cache
            .last()
            .expect("the entity is visible")
            .pipeline_id
    }

    fn harness() -> Harness {
        let (device, queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor::default());
        let mut world = LocalWorld::new();
        let ctx = spawn_context(&mut world, device, queue, ResourceGraph::new());
        let mut source = MeshSource::new(&world, ctx);
        source.register_unlit_family(&world);
        let key = UnlitPipelineKey::new(UnlitOptions::standard(&source.device(&world)));
        let target = bind_test_target(&mut world, ctx);
        Harness {
            world,
            source,
            key,
            target,
        }
    }

    /// Register a color texture and a matching depth texture in the context's
    /// graph and state them as the frame's target.
    fn bind_test_target(world: &mut LocalWorld, ctx: RenderContext) -> FrameTarget {
        let device = world
            .get::<wgpu::Device>(ctx.device)
            .expect("the context's device")
            .clone();
        let ft = create_render_target(
            &device,
            wgpu::TextureFormat::Rgba8UnormSrgb,
            TEST_SIZE,
            TEST_SIZE,
            1,
        );
        let target = {
            let mut graph = world
                .get_mut::<ResourceGraph>(ctx.graph)
                .expect("the context's graph");
            let color = graph
                .insert_strong(
                    ft.color
                        .create_view(&wgpu::TextureViewDescriptor::default()),
                    &[],
                )
                .expect("a color view has no dependencies");
            let depth = graph
                .insert_strong(
                    ft.depth
                        .create_view(&wgpu::TextureViewDescriptor::default()),
                    &[],
                )
                .expect("a depth view has no dependencies");
            let attachments = RenderAttachments::from_views(
                graph.get_texture_view(color).cloned(),
                graph.get_texture_view(depth).cloned(),
                None,
            );
            FrameTarget {
                surface: attachments.surface_key(),
                width: TEST_SIZE,
                height: TEST_SIZE,
            }
        };
        assert!(
            set_frame_target(world, target),
            "the context spawned a slot"
        );
        target
    }

    /// A camera at `eye` looking at the origin, with a frustum wide enough
    /// that nothing in these tests is culled.
    fn test_camera(eye: glam::Vec3) -> Camera {
        let view = glam::camera::rh::view::look_at_mat4(eye, glam::Vec3::ZERO, glam::Vec3::Y);
        Camera {
            clip_from_world: test_perspective() * view,
            position: eye,
        }
    }

    /// The entities of the source's visible cache in draw order.
    fn drawn(source: &MeshSource) -> Vec<Entity> {
        source
            .visible_cache
            .iter()
            .map(|entry| entry.mesh.entity)
            .collect()
    }

    /// A variant of the standard one that reads no UV — so no base-color
    /// texture either — and therefore packs its vertices differently.
    fn uv_less_options(device: &wgpu::Device) -> UnlitOptions {
        use unlit_wgpu::pipeline::UnlitFlags;
        let mut options = UnlitOptions::standard(device);
        options.flags &= !(UnlitFlags::VERTEX_UV | UnlitFlags::BASE_COLOR_TEXTURE);
        options
    }

    /// Register a 2D texture with `source` and return a view id and a sampler
    /// id, ready for [`MeshSource::allocate_unlit_material`].
    fn test_material_resources(harness: &mut Harness) -> (ResourceId, ResourceId) {
        let texture =
            harness
                .source
                .device(&harness.world)
                .create_texture(&wgpu::TextureDescriptor {
                    label: Some("test::texture"),
                    size: wgpu::Extent3d {
                        width: 4,
                        height: 4,
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format: wgpu::TextureFormat::Rgba8UnormSrgb,
                    usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                    view_formats: &[],
                });
        let view = harness
            .source
            .register_texture_and_default_view(&harness.world, texture)
            .1;
        let sampler = harness.source.register_sampler(&harness.world, None);
        (view, sampler)
    }

    /// A raw-layout key for `mesh` on `surface`.
    fn draw_key(surface: SurfaceKey, mesh: &GpuMesh) -> DrawKey {
        DrawKey::for_mesh(surface, mesh)
    }

    #[test]
    fn mesh_instance_from_transform() {
        let t = Transform {
            translation: glam::Vec3::new(1.0, 2.0, 3.0),
            rotation: glam::Quat::IDENTITY,
            scale: glam::Vec3::ONE,
        };
        let instance = MeshInstance::new(t.compute_matrix(), glam::Vec4::new(1.0, 1.0, 1.0, 1.0));
        assert_eq!(instance.translation(), glam::Vec3::new(1.0, 2.0, 3.0));
        // The color is quantized to the `Unorm8x4` the stream carries.
        assert_eq!(instance.base_color, [u8::MAX; 4]);
    }

    // -- pipeline registration ---------------------------------------------

    #[test]
    fn registering_a_family_compiles_nothing() {
        let (device, queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor::default());
        let mut world = LocalWorld::new();
        let ctx = spawn_context(&mut world, device, queue, ResourceGraph::new());
        let mut source = MeshSource::new(&world, ctx);

        source.register_unlit_family(&world);

        // Registration records the family; its first concrete pipeline is
        // built only when a draw resolves a variant.
        assert!(source.pipelines.is_empty());
        assert_eq!(source.families.len(), 1);
    }

    #[test]
    fn a_source_starts_with_no_pipelines() {
        let (device, queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor::default());
        let mut world = LocalWorld::new();
        let ctx = spawn_context(&mut world, device, queue, ResourceGraph::new());
        let source = MeshSource::new(&world, ctx);

        // Nothing is privileged: pipelines arrive only through registration.
        assert!(source.pipelines.is_empty());
    }

    #[test]
    fn a_unlit_mesh_is_built_from_its_keys_options() {
        let mut h = harness();
        let standard = UnlitPipelineKey::new(UnlitOptions::standard(&h.source.device(&h.world)));
        let uv_less = UnlitPipelineKey::new(uv_less_options(&h.source.device(&h.world)));

        // Each mesh packs the channels its own key reads, not the last
        // registered family's.
        let standard_mesh = h.source.allocate_unlit_mesh(
            &h.world,
            &standard,
            UnlitMeshDesc {
                positions: &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
                uvs: Some(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]),
                colors: Some(&[[255; 4], [255, 0, 0, 255], [0, 255, 0, 255]]),
                indices: Some(&[0u32, 1, 2]),
                ..Default::default()
            },
        );
        let uv_less_mesh = h.source.allocate_unlit_mesh(
            &h.world,
            &uv_less,
            UnlitMeshDesc {
                positions: &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
                uvs: Some(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]),
                colors: Some(&[[255; 4], [255, 0, 0, 255], [0, 255, 0, 255]]),
                indices: Some(&[0u32, 1, 2]),
                ..Default::default()
            },
        );
        assert!(
            unlit_flags_for_layout(&standard_mesh.vertex_layout).contains(UnlitFlags::VERTEX_UV)
        );
        assert!(
            !unlit_flags_for_layout(&uv_less_mesh.vertex_layout).contains(UnlitFlags::VERTEX_UV)
        );

        // A material is built against the key's layout: the standard variant
        // samples a base-color texture, the UV-less one does not.
        let (view, sampler) = test_material_resources(&mut h);
        assert!(
            h.source
                .allocate_unlit_material(&h.world, &standard, view, sampler)
                .is_some()
        );
        assert!(
            h.source
                .allocate_unlit_material(&h.world, &uv_less, view, sampler)
                .is_none()
        );
    }

    #[test]
    fn every_registered_pipeline_gets_its_own_global_group() {
        let mut h = harness();
        let mesh = h.tri_mesh();
        let a = h.target.surface;
        // A second target, so the family resolves two variants.
        let b = SurfaceKey {
            color_format: wgpu::TextureFormat::Bgra8Unorm,
            ..a
        };
        h.world.spawn((
            Transform::default(),
            mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
        ));
        resolve_draw(&mut h.source, &h.world, a);
        resolve_draw(&mut h.source, &h.world, b);
        assert_eq!(h.source.pipelines.len(), 2);

        let ctx = h.source.context();
        let ids: Vec<_> = h
            .source
            .pipelines
            .iter()
            .map(|registered| registered.global.as_ref().expect("has a global group").id)
            .collect();
        for (index, &id) in ids.iter().enumerate() {
            assert!(
                MeshSource::graph(&h.world, ctx)
                    .get_bind_group(id)
                    .is_some(),
                "pipeline {index}'s global group is in the graph"
            );
            // No two pipelines share one: each binds its own layout.
            assert!(!ids[..index].contains(&id));
        }
    }

    #[test]
    fn a_variant_is_compiled_when_a_draw_resolves_it() {
        let mut h = harness();

        // A family has no concrete pipeline until a draw asks for a variant.
        let mesh = h.tri_mesh();
        let surface = h.target.surface;
        h.world.spawn((
            Transform::default(),
            mesh,
            UnlitPipeline::new(h.key.clone()),
        ));
        resolve_draw(&mut h.source, &h.world, surface);

        assert_eq!(h.source.pipelines.len(), 1);
    }

    #[test]
    fn a_material_is_allocated_from_caller_owned_resources() {
        let mut h = harness();
        let (view, sampler) = test_material_resources(&mut h);

        let material = h
            .source
            .allocate_unlit_material(&h.world, &h.key, view, sampler)
            .expect("the standard variant reads a base-color texture");
        let ctx = h.source.context();
        assert!(
            MeshSource::graph(&h.world, ctx)
                .get_bind_group(material.bind_group_id)
                .is_some()
        );
    }

    #[test]
    fn a_variant_without_a_base_color_texture_allocates_no_material() {
        let mut h = harness();
        let key = UnlitPipelineKey::new(uv_less_options(&h.source.device(&h.world)));
        let (view, sampler) = test_material_resources(&mut h);

        assert!(
            h.source
                .allocate_unlit_material(&h.world, &key, view, sampler)
                .is_none()
        );
    }

    // -- removal -----------------------------------------------------------

    #[test]
    fn removing_a_mesh_frees_every_resource_built_from_it() {
        let mut h = harness();
        let mesh = h.tri_mesh();
        let ctx = h.source.context();

        // The root is the mesh's lifetime entry point; its parts are the bind
        // group and the mesh-info uniform that feeds it. The mesh's vertices
        // and indices live in pools, so they are strong nodes the source owns
        // and survive the mesh — what the mesh loses is its share of them,
        // which `remove_mesh` hands back.
        let before = MeshSource::graph(&h.world, ctx).len();
        let index_pool_free = h.source.index_pool.free_space();
        assert!(matches!(
            MeshSource::graph(&h.world, ctx).get(mesh.root),
            Some(Resource::Virtual)
        ));
        let bind_group = mesh.bind_group_id.expect("the mesh has a group");
        let root = mesh.root;

        h.source.remove_mesh(&h.world, mesh);

        assert!(
            MeshSource::graph(&h.world, ctx).get(root).is_none(),
            "root removed"
        );
        assert!(
            MeshSource::graph(&h.world, ctx).get(bind_group).is_none(),
            "the bind group built from them removed"
        );
        assert!(
            MeshSource::graph(&h.world, ctx).len() < before,
            "the graph shrank"
        );
        assert!(
            h.source.index_pool.free_space() > index_pool_free,
            "the mesh's index range is free again"
        );
    }

    #[test]
    fn a_mesh_registers_its_pooled_parts_nowhere_under_its_root() {
        let mut h = harness();
        let mesh = h.tri_mesh();
        let ctx = h.source.context();

        // The pools are the source's, not the mesh's: a mesh that goes away
        // must not take the shared buffers with it, so they sit outside the
        // root and the root holds only what is the mesh's own.
        let dependencies: Vec<_> = MeshSource::graph(&h.world, ctx)
            .dependencies(mesh.root)
            .collect();
        let bind_group = mesh.bind_group_id.expect("the mesh has a group");
        assert!(
            dependencies.contains(&bind_group),
            "the bind group is under the root"
        );
        let pool = h.source.index_pool_id;
        assert!(
            !dependencies.contains(&pool),
            "the index pool is not under the root"
        );
        assert!(
            MeshSource::graph(&h.world, ctx).get(pool).is_some(),
            "the index pool survives"
        );
    }

    #[test]
    fn a_removed_mesh_frees_its_metadata_slot() {
        let mut h = harness();
        let first = h.tri_mesh();
        let second = h.tri_mesh();
        let first_index = first.metadata_index;
        assert_ne!(first_index, second.metadata_index);

        h.source.remove_mesh(&h.world, first);
        let reused = h.tri_mesh();

        assert_eq!(
            reused.metadata_index, first_index,
            "the slot the removed mesh held is handed out again"
        );
        assert_ne!(reused.metadata_index, second.metadata_index);
    }

    #[test]
    fn removing_a_material_keeps_the_resources_it_reads() {
        let mut h = harness();
        let ctx = h.source.context();
        let (view, sampler) = test_material_resources(&mut h);
        let material = h
            .source
            .allocate_unlit_material(&h.world, &h.key, view, sampler)
            .expect("the standard variant reads a base-color texture");

        h.source.remove_material(&h.world, material.clone());

        assert!(
            MeshSource::graph(&h.world, ctx)
                .get(material.bind_group_id)
                .is_none(),
            "the bind group is gone"
        );
        // The view and sampler are the caller's, so removing the material
        // that reads them leaves them alone.
        assert!(
            MeshSource::graph(&h.world, ctx).get(view).is_some(),
            "the view stays"
        );
        assert!(
            MeshSource::graph(&h.world, ctx).get(sampler).is_some(),
            "the sampler stays"
        );
    }

    // -- draw ordering ------------------------------------------------------

    #[test]
    fn indexed_meshes_share_one_index_buffer() {
        let mut h = harness();
        let first = h.tri_mesh();
        let second = h.tri_mesh();

        // Both name the pool's node, and each names its own slice of it.
        let pool = h.source.index_pool_id;
        assert_eq!(first.index_buffer.map(|(id, _)| id), Some(pool));
        assert_eq!(second.index_buffer.map(|(id, _)| id), Some(pool));
        assert_ne!(first.first, second.first, "the slices do not overlap");

        // The ranges tile the pool in allocation order.
        let first_range = h.source.index_pool.allocation_size(
            first
                .index_allocation
                .expect("the mesh holds an allocation"),
        );
        assert_eq!(
            first.first + first_range / index_format_size(wgpu::IndexFormat::Uint16),
            second.first,
            "the second mesh starts where the first ends"
        );
    }

    #[test]
    fn a_removed_mesh_frees_its_index_range_for_the_next_mesh() {
        let mut h = harness();
        let first = h.tri_mesh();
        let first_offset = first.first;
        h.source.remove_mesh(&h.world, first);

        let again = h.tri_mesh();
        assert_eq!(
            again.first, first_offset,
            "the freed range is handed out again"
        );
    }

    #[test]
    fn an_index_pool_that_grows_keeps_every_meshes_slice() {
        let mut h = harness();
        let ctx = h.source.context();
        let first = h.tri_mesh();
        let first_node = first.index_buffer.expect("the mesh is indexed").0;
        let first_offset = first.first;

        // Enough meshes to push the pool past its starting size.
        let mut last = None;
        for _ in 0..40 {
            last = Some(h.tri_mesh());
        }
        let last = last.expect("the loop runs");

        // The node still names the pool, and the graph holds the buffer the
        // pool currently does: a mesh needs no update after a grow.
        assert_eq!(last.index_buffer.map(|(id, _)| id), Some(first_node));
        assert_eq!(
            MeshSource::graph(&h.world, ctx).get_buffer(first_node),
            Some(h.source.index_pool.buffer()),
            "the node follows the pool's buffer"
        );
        assert_eq!(
            first.first, first_offset,
            "the first mesh's slice did not move"
        );
        assert!(
            h.source.index_pool.size() > first_offset as u64,
            "the pool grew"
        );
    }

    #[test]
    fn a_non_indexed_mesh_holds_no_index_allocation() {
        let mut h = harness();
        let key = UnlitPipelineKey::new(UnlitOptions::standard(&h.source.device(&h.world)));
        let mesh = h.source.allocate_unlit_mesh(
            &h.world,
            &key,
            UnlitMeshDesc {
                positions: &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
                uvs: Some(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]),
                colors: Some(&[[255; 4], [255, 0, 0, 255], [0, 255, 0, 255]]),
                indices: None,
                ..Default::default()
            },
        );

        assert!(!mesh.indexed);
        assert!(mesh.index_buffer.is_none());
        assert!(mesh.index_allocation.is_none());
        assert_eq!(mesh.first, 0);
    }

    #[test]
    fn meshes_sharing_a_layout_share_one_buffer_per_stream() {
        let mut h = harness();
        let first = h.tri_mesh();
        let second = h.tri_mesh();
        let ctx = h.source.context();

        // Every stream of a mesh names its pool's node, and both meshes name
        // the same node per slot.
        for ((_, first_id), (_, second_id)) in first
            .vertex_buffers
            .iter()
            .zip(second.vertex_buffers.iter())
        {
            assert_eq!(first_id, second_id, "the streams share a buffer");
            assert!(
                MeshSource::graph(&h.world, ctx)
                    .get_buffer(*first_id)
                    .is_some(),
                "the stream's node holds a buffer"
            );
        }
        // One element allocation covers both streams at the same index, which
        // is what makes a single `base_vertex` address them all.
        assert_eq!(first.base_vertex, 0);
        assert_ne!(second.base_vertex, first.base_vertex);
    }

    #[test]
    fn a_removed_mesh_frees_its_vertex_range_for_the_next_mesh() {
        let mut h = harness();
        let first = h.tri_mesh();
        let vertex_offset = first.base_vertex;
        h.source.remove_mesh(&h.world, first);

        let again = h.tri_mesh();
        assert_eq!(
            again.base_vertex, vertex_offset,
            "the freed element range is handed out again"
        );
    }

    #[test]
    fn a_vertex_pool_that_grows_keeps_every_meshes_element_index() {
        let mut h = harness();
        let ctx = h.source.context();
        let first = h.tri_mesh();
        let nodes: Vec<_> = first.vertex_buffers.iter().map(|(_, id)| *id).collect();
        let base_vertex = first.base_vertex;

        // Enough meshes to push the pool past its starting capacity.
        let mut last = None;
        for _ in 0..80 {
            last = Some(h.tri_mesh());
        }
        let last = last.expect("the loop runs");

        // The nodes still name the streams, and each holds the buffer the pool
        // currently does for its layout: a mesh needs no update after a grow.
        // Only the pool-backed slots count: the per-instance slot is bound by
        // the source from its own buffer, not the pool's.
        let stream_slots = last
            .vertex_layout
            .iter()
            .filter(|(slot, _)| *slot != INSTANCE_SLOT);
        for (node, (_, layout)) in nodes.iter().zip(stream_slots) {
            let pool_buffer = h
                .source
                .vertex_pool
                .buffer(layout)
                .expect("the layout has a buffer");
            assert_eq!(
                MeshSource::graph(&h.world, ctx).get_buffer(*node),
                Some(pool_buffer),
                "the node follows the pool's buffer"
            );
        }
        assert_eq!(
            first.base_vertex, base_vertex,
            "the first mesh's element index did not move"
        );
        assert!(
            h.source.vertex_pool.element_capacity() > base_vertex,
            "the pool grew"
        );
    }

    #[test]
    fn entities_without_a_sort_marker_are_drawn_first() {
        let mut h = harness();
        let mesh = h.tri_mesh();

        // The z-sorted entity is the nearer of the two, so depth alone would
        // put it first: it is drawn second because it carries the marker.
        let z_sorted = h.world.spawn((
            Transform {
                translation: glam::Vec3::new(0.0, 0.0, 4.0),
                ..Default::default()
            },
            mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
            ZSortedDrawing,
        ));
        let opaque = h.world.spawn((
            Transform::default(),
            mesh,
            UnlitPipeline::new(h.key.clone()),
        ));

        let camera = test_camera(glam::Vec3::new(0.0, 0.0, 5.0));
        h.source
            .collect_and_sort_visible(&h.world, &camera, h.target.surface);

        assert_eq!(drawn(&h.source), vec![opaque, z_sorted]);
        assert!(h.source.visible_cache[0].depth > h.source.visible_cache[1].depth);
    }

    #[test]
    fn z_sorted_entities_are_drawn_back_to_front() {
        let mut h = harness();
        let mesh = h.tri_mesh();

        let near = h.world.spawn((
            Transform {
                translation: glam::Vec3::new(0.0, 0.0, 4.0),
                ..Default::default()
            },
            mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
            ZSortedDrawing,
        ));
        let middle = h.world.spawn((
            Transform::default(),
            mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
            ZSortedDrawing,
        ));
        let far = h.world.spawn((
            Transform {
                translation: glam::Vec3::new(0.0, 0.0, -4.0),
                ..Default::default()
            },
            mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
            ZSortedDrawing,
        ));
        // Spawned out of order on purpose: registration order is not draw
        // order for z-sorted entities.
        assert_ne!(drawn(&h.source), vec![far, middle, near]);

        let camera = test_camera(glam::Vec3::new(0.0, 0.0, 5.0));
        h.source
            .collect_and_sort_visible(&h.world, &camera, h.target.surface);

        assert_eq!(drawn(&h.source), vec![far, middle, near]);
    }

    #[test]
    fn entities_are_drawn_in_pipeline_id_order() {
        let mut h = harness();
        // A second key whose specialized options differ, so it resolves to its
        // own concrete pipeline.
        let uv_less_key = UnlitPipelineKey::new(uv_less_options(&h.source.device(&h.world)));

        // Warm both variants, first key first, so their pipeline ids follow
        // the order they were resolved in.
        let standard_mesh = h.tri_mesh();
        let uv_less_mesh = h.source.allocate_unlit_mesh(
            &h.world,
            &uv_less_key,
            UnlitMeshDesc {
                positions: &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
                uvs: Some(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]),
                colors: Some(&[[255; 4], [255, 0, 0, 255], [0, 255, 0, 255]]),
                indices: Some(&[0u32, 1, 2]),
                ..Default::default()
            },
        );
        let surface = h.target.surface;
        let camera = test_camera(glam::Vec3::new(0.0, 0.0, 5.0));
        let warm_standard = h.world.spawn((
            Transform::default(),
            standard_mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
        ));
        let warm_uv_less = h.world.spawn((
            Transform::default(),
            uv_less_mesh.clone(),
            UnlitPipeline::new(uv_less_key.clone()),
        ));
        h.source
            .collect_and_sort_visible(&h.world, &camera, surface);
        let first_id = h
            .source
            .visible_cache
            .iter()
            .find(|entry| entry.mesh.entity == warm_standard)
            .expect("the standard entity is visible")
            .pipeline_id;
        let second_id = h
            .source
            .visible_cache
            .iter()
            .find(|entry| entry.mesh.entity == warm_uv_less)
            .expect("the uv-less entity is visible")
            .pipeline_id;
        assert!(first_id < second_id);
        assert!(h.world.despawn(warm_standard));
        assert!(h.world.despawn(warm_uv_less));

        // Spawn the later-drawn entity first: draw order is the pipeline id,
        // not the spawn order.
        let second = h.world.spawn((
            Transform::default(),
            uv_less_mesh,
            UnlitPipeline::new(uv_less_key),
        ));
        let first = h.world.spawn((
            Transform::default(),
            standard_mesh,
            UnlitPipeline::new(h.key.clone()),
        ));

        h.source
            .collect_and_sort_visible(&h.world, &camera, surface);

        assert_eq!(drawn(&h.source), vec![first, second]);
    }

    #[test]
    fn opaque_draws_sharing_a_material_stay_adjacent() {
        let mut h = harness();
        let mesh = h.tri_mesh();
        let (view, sampler) = test_material_resources(&mut h);
        let shared = h
            .source
            .allocate_unlit_material(&h.world, &h.key, view, sampler)
            .expect("the standard variant reads a base-color texture");
        let (view, sampler) = test_material_resources(&mut h);
        let other = h
            .source
            .allocate_unlit_material(&h.world, &h.key, view, sampler)
            .expect("the standard variant reads a base-color texture");
        assert_ne!(shared.sort_key(), other.sort_key());

        let a = h.world.spawn((
            Transform::default(),
            mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
            shared.clone(),
        ));
        // The odd one out: sharing no material with the other two, so it is
        // the draw that has to sit on the other side of the pair.
        let _other_material = h.world.spawn((
            Transform::default(),
            mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
            other.clone(),
        ));
        let c = h.world.spawn((
            Transform::default(),
            mesh,
            UnlitPipeline::new(h.key.clone()),
            shared.clone(),
        ));

        let camera = test_camera(glam::Vec3::new(0.0, 0.0, 5.0));
        h.source
            .collect_and_sort_visible(&h.world, &camera, h.target.surface);

        // The two draws sharing a material are neighbours, so the source
        // binds its bind group once for the pair.
        let order = drawn(&h.source);
        assert_eq!(order.len(), 3);
        let (pos_a, pos_c) = (
            order.iter().position(|&e| e == a).expect("a is drawn"),
            order.iter().position(|&e| e == c).expect("c is drawn"),
        );
        assert_eq!(pos_a.abs_diff(pos_c), 1);
    }

    #[test]
    fn sorting_survives_a_second_frame_on_the_reused_cache() {
        let mut h = harness();
        let mesh = h.tri_mesh();
        let opaque = h.world.spawn((
            Transform::default(),
            mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
        ));
        let z_sorted = h.world.spawn((
            Transform::default(),
            mesh,
            UnlitPipeline::new(h.key.clone()),
            ZSortedDrawing,
        ));

        let camera = test_camera(glam::Vec3::new(0.0, 0.0, 5.0));
        h.source
            .collect_and_sort_visible(&h.world, &camera, h.target.surface);
        assert_eq!(drawn(&h.source), vec![opaque, z_sorted]);

        // The cache is cleared and refilled, not reallocated.
        let capacity = h.source.visible_cache.capacity();
        h.source
            .collect_and_sort_visible(&h.world, &camera, h.target.surface);
        assert_eq!(drawn(&h.source), vec![opaque, z_sorted]);
        assert_eq!(h.source.visible_cache.capacity(), capacity);
    }

    // -- specialization cache ------------------------------------------------

    #[test]
    fn a_render_target_change_respecializes_the_family() {
        let mut h = harness();
        let mesh = h.tri_mesh();

        let internal = h.target.surface;
        h.world.spawn((
            Transform::default(),
            mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
        ));
        let first = resolve_draw(&mut h.source, &h.world, internal);
        // The same key twice reuses one compiled pipeline.
        assert_eq!(resolve_draw(&mut h.source, &h.world, internal), first);

        // A different color format is a different surface, so the family
        // compiles a second variant for it.
        let other = SurfaceKey {
            color_format: wgpu::TextureFormat::Bgra8Unorm,
            ..internal
        };
        let second = resolve_draw(&mut h.source, &h.world, other);
        assert_ne!(second, first);
        assert_eq!(h.source.pipelines.len(), 2);
    }

    #[test]
    fn a_mesh_layout_change_respecializes_the_family() {
        let mut h = harness();
        let surface = h.target.surface;
        let standard = h.tri_mesh();
        h.world.spawn((
            Transform::default(),
            standard.clone(),
            UnlitPipeline::new(h.key.clone()),
        ));
        let first = resolve_draw(&mut h.source, &h.world, surface);

        // A second mesh whose layout declares fewer channels implies a
        // different variant. Dropping only the color attribute keeps the UV
        // the base-color flag needs, so the variant differs without
        // invalidating the base options.
        const COLOR: u32 = 2;
        let mut other = standard.clone();
        let layout: Vec<_> = other
            .vertex_layout
            .iter()
            .map(|(slot, layout)| {
                let mut layout = layout.clone();
                layout
                    .attributes
                    .retain(|attribute| attribute.shader_location != COLOR);
                (*slot, layout)
            })
            .collect();
        other.vertex_layout = ArrayVec::try_from(layout.as_slice()).expect("the layout still fits");
        assert_ne!(draw_key(surface, &other), draw_key(surface, &standard));

        h.world.spawn((
            Transform::default(),
            other.clone(),
            UnlitPipeline::new(h.key.clone()),
        ));
        let second = resolve_draw(&mut h.source, &h.world, surface);

        assert_ne!(second, first);
        assert_eq!(h.source.pipelines.len(), 2);
    }

    #[test]
    fn meshes_that_share_flags_share_one_variant() {
        let mut h = harness();
        let surface = h.target.surface;
        let base = h.tri_mesh();
        h.world.spawn((
            Transform::default(),
            base.clone(),
            UnlitPipeline::new(h.key.clone()),
        ));
        let first = resolve_draw(&mut h.source, &h.world, surface);

        // A layout the flags cannot tell from `base`: the attribute is at the
        // same location, so the derived flags are identical even though the
        // raw attribute list differs. The raw keys differ, so a canonical key
        // is what makes both resolve to one compiled pipeline.
        let mut twin = base.clone();
        let layout: Vec<_> = twin
            .vertex_layout
            .iter()
            .map(|(slot, layout)| {
                let mut layout = layout.clone();
                for attribute in &mut layout.attributes {
                    attribute.offset += 4;
                }
                layout.array_stride += 4;
                (*slot, layout)
            })
            .collect();
        twin.vertex_layout = ArrayVec::try_from(layout.as_slice()).expect("the layout still fits");
        assert_ne!(draw_key(surface, &twin), draw_key(surface, &base));

        h.world.spawn((
            Transform::default(),
            twin.clone(),
            UnlitPipeline::new(h.key.clone()),
        ));
        let second = resolve_draw(&mut h.source, &h.world, surface);
        assert_eq!(second, first);
        assert_eq!(h.source.pipelines.len(), 1);
    }

    #[test]
    fn an_entity_without_a_pipeline_is_not_drawn() {
        let mut h = harness();
        let mesh = h.tri_mesh();
        // No GpuPipeline: the query filters it out.
        let _unpipelined = h.world.spawn((Transform::default(), mesh.clone()));
        let drawn_entity = h.world.spawn((
            Transform::default(),
            mesh,
            UnlitPipeline::new(h.key.clone()),
        ));

        let camera = test_camera(glam::Vec3::new(0.0, 0.0, 5.0));
        h.source
            .collect_and_sort_visible(&h.world, &camera, h.target.surface);

        assert_eq!(drawn(&h.source), vec![drawn_entity]);
    }

    // -- metadata buffer -----------------------------------------------------

    #[test]
    fn the_metadata_buffer_grows_only_when_the_array_outgrows_it() {
        let mut h = harness();
        let ctx = h.source.context();
        // The source starts with room for one entry and grows by doubling,
        // so only the entries past the capacity it holds recreate the buffer.
        assert_eq!(h.source.metadata_capacity, 1);

        h.tri_mesh();
        let encoder = h.encoder();
        h.source.upload_metadata(&h.world, &mut { encoder });
        assert_eq!(h.source.metadata_capacity, 1, "one entry fills the room");

        h.tri_mesh();
        let encoder = h.encoder();
        h.source.upload_metadata(&h.world, &mut { encoder });
        assert_eq!(
            h.source.metadata_capacity, 2,
            "a second entry outgrows room for one"
        );

        // A third entry does not fit in two, so the buffer doubles again.
        h.tri_mesh();
        let encoder = h.encoder();
        h.source.upload_metadata(&h.world, &mut { encoder });
        assert_eq!(h.source.metadata_capacity, 4);

        // A fourth entry does fit in four, so the buffer is left alone.
        let before = MeshSource::graph(&h.world, ctx)
            .get_buffer(h.source.metadata_buf)
            .cloned();
        h.tri_mesh();
        let encoder = h.encoder();
        h.source.upload_metadata(&h.world, &mut { encoder });
        assert_eq!(h.source.metadata_capacity, 4, "four entries fit");
        assert_eq!(
            MeshSource::graph(&h.world, ctx).get_buffer(h.source.metadata_buf),
            before.as_ref(),
            "no growth means the same buffer, so no global group is rebuilt"
        );
    }

    #[test]
    fn a_removed_mesh_marks_the_metadata_array_for_upload() {
        let mut h = harness();
        let mesh = h.tri_mesh();
        let encoder = h.encoder();
        h.source.upload_metadata(&h.world, &mut { encoder });
        assert!(!h.source.metadata_dirty, "the mesh's own upload cleared it");

        // Removing the mesh clears its entry in the array, so the array
        // reaches the GPU again on the next frame.
        h.source.remove_mesh(&h.world, mesh);
        assert!(h.source.metadata_dirty, "removing a mesh marks the array");
        let encoder = h.encoder();
        h.source.upload_metadata(&h.world, &mut { encoder });
        assert!(!h.source.metadata_dirty, "the upload cleared the mark");
    }

    // -- a whole built scene --------------------------------------------------

    #[test]
    fn a_frame_without_a_camera_only_clears() {
        let mut h = harness();
        let mesh = h.tri_mesh();
        // A drawable entity, but nothing the source can view it from.
        h.world.spawn((
            Transform::default(),
            mesh,
            UnlitPipeline::new(h.key.clone()),
        ));

        // The source builds nothing, so the driver's pass draws nothing while
        // still applying the frame's clears.
        let mut encoder = h.encoder();
        let ctx = h.source.context();
        h.source.build_scene(&h.world, ctx, &mut encoder);
        assert!(h.source.visible_cache.is_empty(), "nothing was drawn");
        assert!(h.source.scene().draws.is_empty(), "the scene is empty");
    }

    #[test]
    fn rendering_a_world_twice_reuses_every_per_frame_cache() {
        let mut h = harness();
        // A variant that binds no material group, so the frame needs no
        // material to be a complete draw.
        let key = UnlitPipelineKey::new(uv_less_options(&h.source.device(&h.world)));
        let mesh = h.source.allocate_unlit_mesh(
            &h.world,
            &key,
            UnlitMeshDesc {
                positions: &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
                uvs: Some(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]),
                colors: Some(&[[255; 4], [255, 0, 0, 255], [0, 255, 0, 255]]),
                indices: Some(&[0u32, 1, 2]),
                ..Default::default()
            },
        );
        h.world
            .spawn((test_camera(glam::Vec3::new(0.0, 0.0, 5.0)),));
        h.world.spawn((
            Transform::default(),
            mesh,
            UnlitPipeline::new(key),
            ZSortedDrawing,
        ));

        let ctx = h.source.context();
        let mut encoder = h.encoder();
        h.source.build_scene(&h.world, ctx, &mut encoder);
        let drawn_first = drawn(&h.source);
        assert_eq!(drawn_first.len(), 1, "the entity was drawn");
        let capacities = (
            h.source.visible_cache.capacity(),
            h.source.entry_handle_cache.capacity(),
            h.source.pipeline_handle_cache.capacity(),
            h.source.scene.draws.capacity(),
        );

        let mut encoder = h.encoder();
        h.source.build_scene(&h.world, ctx, &mut encoder);
        assert_eq!(drawn(&h.source), drawn_first, "the same draws, in order");
        assert_eq!(
            (
                h.source.visible_cache.capacity(),
                h.source.entry_handle_cache.capacity(),
                h.source.pipeline_handle_cache.capacity(),
                h.source.scene.draws.capacity(),
            ),
            capacities,
            "a second frame allocates nothing"
        );
    }

    /// Each entry carries its own shape and vertex buffers, so an indexed mesh
    /// followed by another one is addressed by its own slice of the shared pool
    /// rather than reading across entries.
    #[test]
    fn an_indexed_mesh_followed_by_another_keeps_its_own_slice() {
        let mut h = harness();
        let key = UnlitPipelineKey::new(uv_less_options(&h.source.device(&h.world)));
        // Both meshes are indexed and share the pool's index buffer, so what
        // tells their draws apart is the slice each one names.
        let first = h.source.allocate_unlit_mesh(
            &h.world,
            &key,
            UnlitMeshDesc {
                positions: &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
                uvs: Some(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]),
                colors: Some(&[[255; 4], [255, 0, 0, 255], [0, 255, 0, 255]]),
                indices: Some(&[0u32, 1, 2]),
                ..Default::default()
            },
        );
        let second = h.source.allocate_unlit_mesh(
            &h.world,
            &key,
            UnlitMeshDesc {
                positions: &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
                uvs: Some(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]),
                colors: Some(&[[255; 4], [255, 0, 0, 255], [0, 255, 0, 255]]),
                indices: Some(&[0u32, 1, 2]),
                ..Default::default()
            },
        );
        assert!(first.indexed && second.indexed, "both meshes are indexed");
        assert_ne!(first.first, second.first, "the slices do not overlap");

        h.world
            .spawn((test_camera(glam::Vec3::new(0.0, 0.0, 5.0)),));
        h.world
            .spawn((Transform::default(), first, UnlitPipeline::new(key.clone())));
        h.world
            .spawn((Transform::default(), second, UnlitPipeline::new(key)));

        let ctx = h.source.context();
        let mut encoder = h.encoder();
        h.source.build_scene(&h.world, ctx, &mut encoder);
        let handles = &h.source.entry_handle_cache;
        assert_eq!(handles.len(), 2, "one handle set per drawn entity");
        assert_eq!(handles[0].shape.first, 0, "the first mesh starts at zero");
        assert_ne!(
            handles[0].shape.first, handles[1].shape.first,
            "each draw keeps its own slice of the pool"
        );
        assert_eq!(drawn(&h.source).len(), 2, "both entities were drawn");
    }

    /// Entities that share a mesh and a material are drawn as one instanced
    /// draw, so their pose state rides the instance stream instead of each
    /// entity paying for a draw.
    #[test]
    fn entities_sharing_a_mesh_are_drawn_as_one_instanced_draw() {
        let mut h = harness();
        let mesh = h.tri_mesh();
        h.world
            .spawn((test_camera(glam::Vec3::new(0.0, 0.0, 5.0)),));
        for i in 0..3 {
            h.world.spawn((
                Transform {
                    translation: glam::Vec3::new(i as f32, 0.0, 0.0),
                    ..Default::default()
                },
                mesh.clone(),
                UnlitPipeline::new(h.key.clone()),
            ));
        }

        let ctx = h.source.context();
        let mut encoder = h.encoder();
        h.source.build_scene(&h.world, ctx, &mut encoder);

        assert_eq!(h.source.scene().draws.len(), 1, "one draw for all three");
        let range = &h.source.scene().draws[0].range;
        let instances = match range {
            DrawRange::Indexed { instances, .. } | DrawRange::Vertices { instances, .. } => {
                instances
            }
        };
        assert_eq!(
            instances.clone(),
            0..3,
            "the draw covers every shared instance, in order"
        );
    }

    /// Two entities that share a pipeline but draw different meshes cannot
    /// share one draw: each keeps its own slice of the vertex pool, so the
    /// shapes differ even though the buffers do not.
    #[test]
    fn entities_drawing_different_meshes_stay_separate_draws() {
        let mut h = harness();
        let first = h.tri_mesh();
        let second = h.tri_mesh();
        assert_ne!(first.first, second.first, "the meshes own different slices");
        h.world
            .spawn((test_camera(glam::Vec3::new(0.0, 0.0, 5.0)),));
        let key = h.key.clone();
        h.world
            .spawn((Transform::default(), first, UnlitPipeline::new(key.clone())));
        h.world
            .spawn((Transform::default(), second, UnlitPipeline::new(key)));

        let ctx = h.source.context();
        let mut encoder = h.encoder();
        h.source.build_scene(&h.world, ctx, &mut encoder);

        assert_eq!(
            h.source.scene().draws.len(),
            2,
            "different meshes stay one draw each"
        );
    }

    /// A translucent entry never merges, with another translucent entry or with
    /// an opaque one: its draw order is its blend order, so the source must
    /// not let the instance stream reorder it.
    #[test]
    fn z_sorted_entries_never_merge() {
        let mut h = harness();
        let mesh = h.tri_mesh();
        h.world
            .spawn((test_camera(glam::Vec3::new(0.0, 0.0, 5.0)),));
        // Two translucent copies of the same mesh, drawn back to front.
        let key = h.key.clone();
        h.world.spawn((
            Transform {
                translation: glam::Vec3::new(0.0, 0.0, 1.0),
                ..Default::default()
            },
            mesh.clone(),
            UnlitPipeline::new(key.clone()),
            ZSortedDrawing,
        ));
        h.world.spawn((
            Transform {
                translation: glam::Vec3::new(0.0, 0.0, 2.0),
                ..Default::default()
            },
            mesh,
            UnlitPipeline::new(key),
            ZSortedDrawing,
        ));

        let ctx = h.source.context();
        let mut encoder = h.encoder();
        h.source.build_scene(&h.world, ctx, &mut encoder);

        assert_eq!(
            h.source.scene().draws.len(),
            2,
            "translucent entries keep their own draw order"
        );
    }

    /// Releasing the source removes the nodes it registered, so a program that
    /// mounts and unmounts sources does not grow the graph forever.
    #[test]
    fn releasing_the_source_removes_the_nodes_it_registered() {
        let mut h = harness();
        let ctx = h.source.context();
        // A drawn frame, so the pools, the mesh parts and the global bind
        // groups all exist.
        let mesh = h.tri_mesh();
        h.world
            .spawn((test_camera(glam::Vec3::new(0.0, 0.0, 5.0)),));
        h.world.spawn((
            Transform::default(),
            mesh.clone(),
            UnlitPipeline::new(h.key.clone()),
        ));
        let mut encoder = h.encoder();
        h.source.build_scene(&h.world, ctx, &mut encoder);

        let before = MeshSource::graph(&h.world, ctx).len();
        // The camera/globals/metadata buffers, the index pool and the global
        // bind group are the source's own; the mesh's parts hang off its root.
        h.source.remove_mesh(&h.world, mesh);
        h.source.release(&h.world);
        let after = MeshSource::graph(&h.world, ctx).len();

        assert!(
            after < before,
            "releasing must shrink the graph: {after} was {before}"
        );
        // What the context itself spawned — the target's views — is all that
        // should be left, plus nothing the source registered.
        assert!(
            MeshSource::graph(&h.world, ctx)
                .get(h.source.camera_buf)
                .is_none(),
            "the source's camera buffer is gone"
        );
        assert!(
            MeshSource::graph(&h.world, ctx)
                .get(h.source.index_pool_id)
                .is_none(),
            "the index pool is gone"
        );
    }
}